From a42a05c565908dd3910e7ea78155c91c354e2cc0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 12:39:43 +0000 Subject: [PATCH 01/23] feat(metadata-protocol): refuse a package-less create at the kernel save (#38174) ADR-0070 D1, ruling 7184753035: a save that still names no package after its address resolved, of a name no package holds and no loose row carries, is refused 422 WRITABLE_PACKAGE_REQUIRED naming the writable packages. In-place saves, holder customizations, W3/W4/W12 keep their answers. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CasbvyQnz4st6s79P9 --- .../src/protocol-packageless-create.ts | 140 ++++++++++++++++++ .../metadata-protocol/src/protocol-save.ts | 19 ++- 2 files changed, 156 insertions(+), 3 deletions(-) create mode 100644 packages/metadata-protocol/src/protocol-packageless-create.ts diff --git a/packages/metadata-protocol/src/protocol-packageless-create.ts b/packages/metadata-protocol/src/protocol-packageless-create.ts new file mode 100644 index 00000000000..f7e7e174714 --- /dev/null +++ b/packages/metadata-protocol/src/protocol-packageless-create.ts @@ -0,0 +1,140 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38174, ADR-0070 D1, ADR-0084 amendment 2026-11-26-org, ruling 7184753035] + * The kernel refuses a package-less CREATE. + * + * ADR-0070 D1: "A runtime **create** … MUST resolve to a **writable** + * `package_id`. The kernel write path is the enforcement point of last + * resort." Until this card the save path judged only a NAMED package (D1's + * read-only-base check in `saveMetaItemUnaudited`), and a save naming none + * stored a new loose row. Studio now asks for a package before a create + * (#38149) and loose rows have a move door (#38150); this is the backstop that + * stops new loose items from every other door: `/meta` publish and draft, + * `os meta register`, the automation definition doors, the MCP and AI doors. + * + * ## What is a create + * + * Asked after the save has resolved its address, so it judges the row the + * save would write: + * + * - the save still names no package (`packageId` empty after the package-less + * address, the row-held base and the one-enabled-holder rules have run: + * a save those rules bind to a package is a save INTO that package); + * - its intent is `runtime-only` (an `override-artifact` write customizes an + * item a package ships: W3, the kernel-item overlay, is judged by + * `packagelessOverlayWriteRefusal` and is not a create); + * - no package holds the name: no active row of it is bound to a package + * (a package-less save of a name a package holds customizes that holder, + * ADR-0150 D4, and keeps its answer); + * - no package-less row of it is stored, active or draft (saving a loose row + * that already exists, in place, stays open: the ruling's sibling clause). + * + * ## The named exemptions, and no other + * + * - W4, the ruled external-datasource import: `writeFace: 'external-import'`, + * which only the datasource service states and no wire body reaches; + * - W12, binding-preserving migrations: `source` set (`migrate-stored`, the + * stored flow-credential move), server-stated, never on the wire; + * - W3, the kernel-item overlay: intent `override-artifact`, above. + * + * W13, platform registration (`MetadataManager.register(…, { origin: + * 'platform' })`), writes the metadata service's own store and never reaches + * this path. `package-duplicate` always names its target, so it never arrives + * here package-less. Ruling 7184753035 answered Q-a A and Q-b C: no type and + * no case adds an exemption, and there is no flag or environment switch. + * + * Tests that need a loose row insert it directly through the engine with the + * system context (the fixture, not a fifth exemption). + */ + +import type { ProtocolHost } from './protocol-host.js'; + +/** How many writable packages the refusal names before it counts the rest. */ +export const PACKAGELESS_CREATE_NAMED_PACKAGES_CAP = 5; + +/** The save request fields this judgment reads. */ +export interface PackagelessCreateRequest { + readonly type: string; + readonly name: string; + readonly packageId?: string | null; + readonly source?: unknown; + readonly writeFace?: string; +} + +/** + * The refusal a package-less create answers, or `undefined` when the save is + * not one (see the module docblock). Reads the stored rows of the name, so it + * is asked once, after the address is resolved and before anything is written. + */ +export async function packagelessCreateRefusal( + host: Pick, + request: PackagelessCreateRequest, + singularType: string, + member: string | undefined, + intent: 'override-artifact' | 'runtime-only', +): Promise { + if (intent !== 'runtime-only') return undefined; + if (request.packageId != null && request.packageId !== '') return undefined; + if (request.source !== undefined) return undefined; + if (request.writeFace === 'external-import' || request.writeFace === 'package-duplicate') return undefined; + + const active = await host.packagelessAddress(singularType, request.name, member, 'active'); + if (active.candidates.length > 0 || active.unbound) return undefined; + const drafts = await host.packagelessAddress(singularType, request.name, member, 'draft'); + if (drafts.unbound) return undefined; + + return packagelessCreateError(singularType, request.name, writablePackageIds(host)); +} + +/** + * The writable packages a refused create may name: every enabled package the + * registry holds that is a writable base (ADR-0070 D2), sorted. `undefined` + * when the registry cannot list them. + */ +function writablePackageIds(host: Pick): string[] | undefined { + const registry = (host.engine as { registry?: { getAllPackages?: () => unknown } } | undefined)?.registry; + if (typeof registry?.getAllPackages !== 'function') return undefined; + let listed: unknown; + try { + listed = registry.getAllPackages(); + } catch { + return undefined; + } + if (!Array.isArray(listed)) return undefined; + const ids = new Set(); + for (const entry of listed as Array<{ manifest?: { id?: unknown }; enabled?: unknown } | undefined>) { + const id = entry?.manifest?.id; + if (typeof id !== 'string' || id === '') continue; + if (entry?.enabled === false) continue; + if (host.isWritablePackage(id)) ids.add(id); + } + return [...ids].sort(); +} + +/** + * `422 WRITABLE_PACKAGE_REQUIRED` (ADR-0070 D1's code): the item is new and no + * package was named. Names the writable packages, capped, as the MCP draft + * door's `packageRequiredMessage` does. + */ +export function packagelessCreateError(type: string, name: string, writable: readonly string[] | undefined): Error { + const head = `Cannot create ${type}/${name} with no package: a new item is saved into a writable package ` + + `(ADR-0070). Name one (on the REST door add ?package=PKG, in the CLI --package PKG, in Studio choose a package). ` + + `Nothing was saved.`; + let tail: string; + if (writable === undefined) tail = ' The packages could not be listed on this request; list them with GET /api/v1/packages.'; + else if (writable.length === 0) tail = ' No package in this environment is writable: create one first.'; + else { + const named = writable.slice(0, PACKAGELESS_CREATE_NAMED_PACKAGES_CAP).join(', '); + const more = writable.length - PACKAGELESS_CREATE_NAMED_PACKAGES_CAP; + tail = ` Writable packages here: ${named}${more > 0 ? `, and ${more} more` : ''}.`; + } + const err = new Error(head + tail) as Error & { + code: string; status: number; docs: string; writablePackages?: readonly string[]; + }; + err.code = 'WRITABLE_PACKAGE_REQUIRED'; + err.status = 422; + err.docs = 'docs/adr/0070-package-first-authoring.md'; + if (writable !== undefined) err.writablePackages = writable; + return err; +} diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index 200ef563177..937aaf60ff9 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -87,6 +87,7 @@ import { captureStoredExpressionChange, fillStoredExpressionChange } from './pro import { reportObjectRegistryRefusal } from './protocol-registry-hydration.js'; import type { MutationProjectionOutcome } from './protocol-mutation-events.js'; import type { ProtocolHost } from './protocol-host.js'; +import { packagelessCreateRefusal } from './protocol-packageless-create.js'; import type { ObjectStackProtocolImplementation } from './protocol.js'; import { saveRegistryQuestion } from './registry-question.js'; import { OBJECT_EXTENSION_TYPE, registrableObjectExtension } from './protocol-object-extension-item.js'; @@ -2158,6 +2159,17 @@ export class ProtocolSaveFacet { const intent: 'override-artifact' | 'runtime-only' = artifactBacked && !declaredOverride ? 'override-artifact' : 'runtime-only'; + // [#38174, ADR-0070 D1, ruling 7184753035] A package-less CREATE is + // refused before anything is written: a save that still names no + // package after its address resolved, of a name no package holds and + // no loose row (active or draft) carries. In-place saves of an existing + // loose row, a holder's customization (ADR-0150 D4), the kernel-item + // overlay (W3), the external import (W4) and the binding-preserving + // migrations (W12) keep their answers. See {@link packagelessCreateRefusal}. + const createRefusal = await packagelessCreateRefusal( + host, request, singularTypeForRepo, itemDiscriminator(singularTypeForRepo, request.item), intent, + ); + if (createRefusal) throw createRefusal; // D1 (ADR-0070) — a brand-new, DB-only ("runtime-only") metadata // item MUST resolve to a WRITABLE base. Binding it to a read-only // code/installed package makes it read back as "code-provided" and @@ -2179,9 +2191,10 @@ export class ProtocolSaveFacet { // taken. // • a project-scoped base, or a bare ADR-0048 authoring-workspace // id — both are writable; `isWritablePackage` returns true. - // A `null` packageId is still accepted here (legacy org-overlay - // destination); ADR-0070 D5 retires it once the surfaces always - // resolve a base and the orphan migration has run. + // A `null` packageId never reaches here for a create: the + // package-less create was refused just above (#38174). What still + // arrives with none is an in-place save of a loose row, a holder's + // customization, or one of the named exemptions. // // [#8361] THE SENTENCE IS THE REPOSITORY'S, the predicate is still // D1's. `SysMetadataRepository.readOnlyBaseCreateError` is CALLED, not From 1c030f0779287bbf0c1b51f8e1d16930d3e71ad9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 12:45:52 +0000 Subject: [PATCH 02/23] feat: notify-channel refusal at the /meta flow save; retire POST /automation (#38174) - lint: flow-notify-channel-unregistered, the one predicate both flow write doors ask (unregisteredNotifyChannels); the metadata protocol hands the settled channel roster to the publish gate. - runtime: POST /automation unmounted and its ledger row removed; PUT /automation/:name of a new name answers 422 naming the /meta door. - client: automation.create removed; spec: createFlow contract and Create/FlowRequest/Response schemas retired; semantic migration entry. - refusal texts and docs no longer prescribe a package-less save. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CasbvyQnz4st6s79P9 --- content/docs/api/metadata-api.mdx | 12 + content/docs/api/plugin-endpoints.mdx | 4 +- content/docs/automation/flows.mdx | 19 +- content/docs/concepts/metadata-lifecycle.mdx | 2 +- packages/cli/src/commands/meta/register.ts | 17 +- packages/client/src/index.ts | 33 +-- packages/lint/src/authoring-rules.ts | 25 +++ packages/lint/src/index.ts | 8 + packages/lint/src/rule-explanations.ts | 2 + .../publish-time-inert-refusals.ts | 17 +- packages/lint/src/runtime-gate.ts | 13 ++ .../lint/src/validate-flow-notify-channels.ts | 158 ++++++++++++++ .../src/protocol-authoring-gate.ts | 57 ++++- .../src/protocol-package-scope.ts | 9 +- packages/metadata-protocol/src/protocol.ts | 11 + .../src/runtime-authoring-gate.ts | 11 + .../src/objects/sys-sharing-rule.object.ts | 8 + packages/runtime/src/dispatcher-plugin.ts | 22 +- packages/runtime/src/domains/automation.ts | 206 +++++++----------- packages/runtime/src/route-ledger.ts | 13 +- packages/spec/src/api/automation-api.zod.ts | 55 ++--- .../semantic/19.packageless-create-refused.ts | 43 ++++ 22 files changed, 512 insertions(+), 233 deletions(-) create mode 100644 packages/lint/src/validate-flow-notify-channels.ts create mode 100644 packages/spec/src/migrations/entries/semantic/19.packageless-create-refused.ts diff --git a/content/docs/api/metadata-api.mdx b/content/docs/api/metadata-api.mdx index eba0a06d0f5..d42d65d8453 100644 --- a/content/docs/api/metadata-api.mdx +++ b/content/docs/api/metadata-api.mdx @@ -76,6 +76,18 @@ D11), so a `manage_metadata` holder inside one organization is refused `POST /meta/_migrate-stored`, the install-wide rewrite of the stored metadata, preview included. +**A new item is saved into a writable package** +([ADR-0070](https://github.com/objectstack-ai/objectstack/blob/main/docs/adr/0070-package-first-authoring.md) +D1). A `PUT` (publish or `?mode=draft`) of a name no package holds and no stored +item carries, naming no package, is refused `422 WRITABLE_PACKAGE_REQUIRED` before +anything is written; the sentence lists the writable packages you may name. Add +`?package=PKG` (`os meta register --package PKG`, or choose a package in Studio). +Saving an item that already exists with no package stays open: a package-less item +stored earlier is saved in place, and an item a package holds is saved into that +package's row. Only the platform's own writes keep a named exemption: customizing an +item a kernel package ships, the external-datasource import, the stored-metadata +migrations, and platform registration at boot. + Creates are gated per type: `MetadataTypeRegistryEntry.allowRuntimeCreate` decides whether a **brand-new** name may be minted under that type at all, separately from whether an item that already exists may be overlaid (`allowEnvironmentOverlay`). A type that diff --git a/content/docs/api/plugin-endpoints.mdx b/content/docs/api/plugin-endpoints.mdx index 573281d6046..e10a8a34147 100644 --- a/content/docs/api/plugin-endpoints.mdx +++ b/content/docs/api/plugin-endpoints.mdx @@ -51,9 +51,9 @@ Approve/reject were never workflow routes (ADR-0019): approval is a flow node, a |:-------|:---------|:------------| | POST | `/automation/:name/trigger` | Trigger an automation flow by name (legacy alias: `/automation/trigger/:name`). Failures answer real status codes, not a `200` wrapping an inner failure: **404** unknown flow (a stored flow with no `start` node is never armed, so it answers here), **409** `FLOW_DISABLED`, **422** `FLOW_INPUT_SCHEMA_INVALID`, **400** `FLOW_FAILED` for a run that ran and was rejected — see [Run a flow via API](/docs/automation/flows#run-a-flow-via-api) | -The automation dispatcher also exposes flow CRUD (`POST /automation`, `GET`/`PUT`/`DELETE /automation/:name`) and run observability/resume routes — see [Durable pause & resume](/docs/automation/flows#durable-pause--resume-adr-0019). +The automation dispatcher also exposes flow reads and edits (`GET`/`PUT`/`DELETE /automation/:name`; `PUT` updates a flow that exists) and run observability/resume routes — see [Durable pause & resume](/docs/automation/flows#durable-pause--resume-adr-0019). -To **list** flows, read the metadata plane: `GET /meta/flow` (`client.meta.getItems('flow')`) — flows are metadata (ADR-0106). There is no `GET /automation` list route; it was retired, and a `GET` to that path gets the host's method-mismatch answer (`405` with `Allow: POST` on the default server), because only `POST` lives there. Per-flow runtime enablement and trigger binding is `GET /automation/_status` (`client.automation.getRuntimeStatus()`). +To **list** flows, read the metadata plane: `GET /meta/flow` (`client.meta.getItems('flow')`) — flows are metadata (ADR-0106). There is no `GET /automation` list route and no `POST /automation` create route; both were retired, and nothing is mounted at that path. To **create** a flow, save it into a package through the metadata door: `PUT /meta/flow/:name?package=PKG` (`client.meta.saveItem('flow', name, definition, { packageId })`), which registers and arms it at once. Per-flow runtime enablement and trigger binding is `GET /automation/_status` (`client.automation.getRuntimeStatus()`). ### Views (`/ui`) — Plugin Required diff --git a/content/docs/automation/flows.mdx b/content/docs/automation/flows.mdx index 91939c2b4b4..ea95a0dfb89 100644 --- a/content/docs/automation/flows.mdx +++ b/content/docs/automation/flows.mdx @@ -389,16 +389,19 @@ organization's flows notify its own. **A `notify` node's `channels` must name channels the deployment registers.** A channel is code: the messaging service registers `inbox`, and `email`, `sms` and `push` (each sends once its transport service is configured), and a plugin -can register more. The `/automation` write doors (`POST /`, `PUT /:name` and the -copy door `POST /:name/clone`) refuse a flow whose `notify` node, at any depth, -names any other channel: `400 VALIDATION_FAILED`, naming the node and the channel -at `nodes.N.config.channels`, with a did-you-mean, and listing the channels the -deployment registers. Nothing is registered or stored. A channel whose transport +can register more. Every flow write door refuses a flow whose `notify` node, at +any depth, names any other channel, naming the node and the channel at +`nodes.N.config.channels`, with a did-you-mean, and listing the channels the +deployment registers: the metadata door (`PUT /api/v1/meta/flow/:name`, publish) +answers `422 INVALID_METADATA` (rule `flow-notify-channel-unregistered`), and the +`/automation` doors (`PUT /:name` and the copy door `POST /:name/clone`) answer +`400 VALIDATION_FAILED`. Nothing is registered or stored. A channel whose transport is not configured yet is listed and accepted, because it starts sending once the transport is configured, with no flow edit. With no messaging service installed, a `notify` node delivers nothing whatever it names, and its channels -are not judged. The check is the save's: a flow a package ships, and a flow -stored through the metadata door, register as before, and a delivery on a +are not judged. The check is the save's, judged on the channels the deployment knows once its +boot has settled: a flow a package ships, and a stored flow re-saved with a +channel it already named, register as before, and a delivery on a channel nothing registers fails at run time with `channel 'NAME' not registered` and a step warning. **Positions and queues are not checked when a flow is saved.** An approval node's `position` or `queue` names runtime data @@ -2993,7 +2996,7 @@ door's own admission check, made before anything is dispatched: | `403` | `PERMISSION_DENIED` | The flow declares `requiredPermissions` and the caller, not the system principal, does not hold every capability it names. Checked after the two rows above, at the same doors; the message names the declared and the missing capabilities | Grant the capability through a permission set's `systemPermissions`, or start the flow as someone who holds it | | `404` | `RECORD_NOT_FOUND` | The start names a record (`recordId`, or the object's id alias such as `crmLeadId`) that the caller, not the system principal, cannot read in its own scope, or that does not exist: the two get one answer, the one the action door gives. Checked after the three rows above, at the same doors. A record key that is not one id, or a record named with no `objectName` for a flow declared `runAs: 'system'`, is refused `400` `VALIDATION_FAILED` naming the key. Where the flow's own definition reads a start input as the id of a record of a fixed object (a `get_record`, `update_record` or `delete_record` node with a literal `objectName` whose `filter.id` or `filter.id.$eq` is the input, or whose `filter.id.$in` is; a `screen` node with a literal `objectName` whose `recordId` is the input; a `subflow` or `map` node that hands the input to a callee input the callee reads so), that input is also loaded in the caller's own scope from THAT object, whatever object the start names, or none, and whatever the flow runs as: a value the caller cannot read there gets this `404`, and a value that is not one id (or a list of ids, where the definition reads a list) is refused `400` `VALIDATION_FAILED` naming the input. An input the flow declares a record id (`objectName` on the variable, [above](#a-start-input-that-is-a-record-id)) is loaded from the declared object the same way, whether or not the definition reads it | Start the flow on a record the caller can read, and name the record's object (`objectName`) beside `recordId`. Hand an input the flow reads as a record id the id of a record the caller can read in the object the flow reads it from, in the shape the flow reads (one id, or a list of ids) | | `409` | `FLOW_DISABLED` | The flow exists but is switched off | Enable it — the identical request then succeeds | -| `422` | `FLOW_NO_START_NODE` | A defensive exit of the engine that no door reaches today. A flow with no `start` node is refused at registration (`POST` / `PUT /api/v1/automation` answer `400` `VALIDATION_FAILED`), and a stored one is not armed, so its trigger answers `404` above, not `422` | Add a `start` node to the flow; its metadata read shows `registration: refused` until then | +| `422` | `FLOW_NO_START_NODE` | A defensive exit of the engine that no door reaches today. A flow with no `start` node is refused at registration (`PUT /api/v1/automation/:name` answers `400` `VALIDATION_FAILED`, the metadata door `422` `INVALID_METADATA`), and a stored one is not armed, so its trigger answers `404` above, not `422` | Add a `start` node to the flow; its metadata read shows `registration: refused` until then | | `422` | `FLOW_INPUT_SCHEMA_INVALID` | A node's `config` violates the `inputSchema` its own definition declares | Fix the flow; the refusal is non-retryable — even under `errorHandling.strategy: 'retry'` the engine refuses once and never enters the retry loop | | `400` | `FLOW_FAILED` | The flow **ran** and was rejected | Read `error.details.summary` for the failing node | diff --git a/content/docs/concepts/metadata-lifecycle.mdx b/content/docs/concepts/metadata-lifecycle.mdx index 6993a37e3ae..0d2ee6e7c18 100644 --- a/content/docs/concepts/metadata-lifecycle.mdx +++ b/content/docs/concepts/metadata-lifecycle.mdx @@ -190,7 +190,7 @@ document **whole** for every read that serves the base's name > **ADR-0131 D6 — the per-organization overlay axis is retired.** The `/meta` doors (REST and the runtime dispatcher) carry no organization into a metadata write or read: a Studio or `PUT /api/v1/meta/...` write of the five ✅ types below lands **environment-wide** (since ADR-0131 D7 the `sys_metadata` family declares no organization column) and is served to every organization, and an organization admin holding only the retired `manage_org_presentation` capability is refused (`403`). The protocol itself refuses every organization-scoped write, and every read — item, list, layers, cached, history, diff, audit, drafts and the commit timeline — is environment → code, whatever organization a caller names. An overlay row an earlier release stored under an organization — under the `single` posture, every Studio save of these types, filed under the Default Organization — is served by no read, and on a SQL database (SQLite, PostgreSQL, MySQL) still holding one a v18 `os serve` refuses to start until the v18 migration ceremony (ADR-0131 C7: `os migrate organization-ownership --out PLAN`, then `--apply --plan-file PLAN`) has carried such a row to the environment layer and dropped the column; nothing deletes or rewrites it before then. The anonymous form doors read the environment alone too: the ceremony carries every organization-layer public-form withdrawal onto the environment, fail-closed. The table still records which types take an overlay of a shipped item. -> **ADR-0146 D11 — the tier no longer opens a write door onto a packaged item.** A write naming no package — a save, a publish, a reset (`DELETE`) or a rollback — onto a ✅-type item that one installed read-only package ships is refused `403 NOT_OVERRIDABLE`, and the sentence names the base's pair: save it into `?package=.custom`, declaring `overrides` ([above](#customizing-an-installed-package-the-paired-custom-override-adr-0146)); for an item a kernel package (scope `system` or `cloud`) ships, the same write is refused with a sentence that names no pair, because kernel objects are not customizable in this version and a kernel package has no pair. A package-less row stored before the close is still served until `os migrate packageless-overlays` moves it into the pair as a declared override; the ✅ row is now the set that ceremony moves and the read path honours for an unmoved row. A package-less write of a name no package ships is environment metadata, and stays open. So does the package-less write of a view container (`list` and `listViews`; since protocol 19 a write that carries a `form` or `formViews` member is refused `422 INVALID_METADATA` with a prescription naming `forms:`, and the members a row stored before it still holds are moved to `form` rows by `os migrate protocol --to 19 --apply`): only a single view declares an override, so the ceremony lists the container and leaves it, and its views move into the pair one by one, each as a single view. +> **ADR-0146 D11 — the tier no longer opens a write door onto a packaged item.** A write naming no package — a save, a publish, a reset (`DELETE`) or a rollback — onto a ✅-type item that one installed read-only package ships is refused `403 NOT_OVERRIDABLE`, and the sentence names the base's pair: save it into `?package=.custom`, declaring `overrides` ([above](#customizing-an-installed-package-the-paired-custom-override-adr-0146)); for an item a kernel package (scope `system` or `cloud`) ships, the same write is refused with a sentence that names no pair, because kernel objects are not customizable in this version and a kernel package has no pair. A package-less row stored before the close is still served until `os migrate packageless-overlays` moves it into the pair as a declared override; the ✅ row is now the set that ceremony moves and the read path honours for an unmoved row. A package-less save of a name no package ships stays open only for an item already stored that way, saved in place; a new item is saved into a writable package, and the kernel refuses a package-less create `422 WRITABLE_PACKAGE_REQUIRED` (ADR-0070 D1). So does the package-less write of a view container (`list` and `listViews`; since protocol 19 a write that carries a `form` or `formViews` member is refused `422 INVALID_METADATA` with a prescription naming `forms:`, and the members a row stored before it still holds are moved to `form` rows by `os migrate protocol --to 19 --apply`): only a single view declares an override, so the ceremony lists the container and leaves it, and its views move into the pair one by one, each as a single view. | Type | `allowEnvironmentOverlay` | Rationale | | :--- | :---: | :--- | diff --git a/packages/cli/src/commands/meta/register.ts b/packages/cli/src/commands/meta/register.ts index e722565b70b..e4ec3d52cc6 100644 --- a/packages/cli/src/commands/meta/register.ts +++ b/packages/cli/src/commands/meta/register.ts @@ -15,7 +15,8 @@ import { studioChangesReviewLink } from '@objectstack/types'; * The SDK sends nothing for `packageId: ''` (`SaveMetaItemOptions.packageId` * is truthy-guarded), and a save that names no package is not a refusal on * every item: the door resolves it, writing the row of the one package that - * holds the item, or the package-unbound overlay when none does. So + * holds the item, or an existing loose row in place (a new item naming no + * package is refused by the kernel, #38174). So * `os meta register view --data v.json --package "$PKG"` with `PKG` unset would * write whichever row that resolution picks while the operator reads their * command line as naming one package. The CLI refuses rather than degrades. A @@ -24,8 +25,8 @@ import { studioChangesReviewLink } from '@objectstack/types'; */ export const EMPTY_PACKAGE_SAVE_REFUSAL = '--package needs the id of the package the save writes into, and was given an empty value. ' - + 'Name the package (for example com.acme.crm), or omit --package to save into the row ' - + 'the server resolves when the item belongs to one package.'; + + 'Name the package (for example com.acme.crm). Omit --package only to save an item that already ' + + 'exists into the row the server resolves; a new item needs a package.'; /** * [#34777, ruling D4] The refusal a `--mode draft` run that names no package @@ -259,12 +260,14 @@ export default class MetaRegister extends Command { }), // [#23350] The package whose row the save writes, forwarded verbatim as // `SaveMetaItemOptions.packageId` (`?package=`). It is the remedy the save - // door's `409 RESOURCE_CONFLICT` prescribes for an item two packages hold. + // door's `409 RESOURCE_CONFLICT` prescribes for an item two packages hold, + // and [#38174] its `422 WRITABLE_PACKAGE_REQUIRED` for a new item: optional, + // because an in-place save of an existing item names none. package: Flags.string({ description: - 'Save into this package\'s row (a package id, e.g. com.acme.crm). Required when two or ' - + 'more packages hold the item: without it the server refuses with 409 RESOURCE_CONFLICT ' - + 'and names the packages.', + 'Save into this package\'s row (a package id, e.g. com.acme.crm). Required for a new item ' + + '(the server refuses a package-less create with 422 WRITABLE_PACKAGE_REQUIRED and names the ' + + 'writable packages), and when two or more packages hold the item (409 RESOURCE_CONFLICT).', }), // [#23480] The acknowledgement the save door's `409 DESTRUCTIVE_CHANGE` // names as its remedy, forwarded as `SaveMetaItemOptions.force` diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 27364b78ea8..c489bc51f1c 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -6427,32 +6427,21 @@ export class ObjectStackClient { return this.unwrapResponse(res); }, - /** - * Create (register) a new flow - * - * [#12206, Option A] Answers the canonicalized PARSED flow the engine - * stored (schema defaults materialized, `edge.condition` strings - * lowered to their `{dialect, source}` envelopes) — the same shape - * `get` answers, so a write-then-read on the resource is stable. - * `CreateFlowResponseSchema` declares the wire envelope this unwraps. - */ - create: async (name: string, definition: any): Promise => { - const route = this.getRoute('automation'); - const res = await this.fetch(`${this.baseUrl}${route}`, { - method: 'POST', - body: JSON.stringify({ name, ...definition }), - }); - return this.unwrapResponse(res); - }, + // [#38174] No `create`: `POST /api/v1/automation` is retired (ruling + // 7234518908). A new flow belongs to a package (ADR-0070 D1) and is + // created with `client.meta.saveItem('flow', name, definition, { packageId })` + // (the `PUT /api/v1/meta/flow/:name?package=` door), which registers and + // arms it in the same boot. Removed rather than re-pointed so a caller + // learns at compile time, not from a 404. /** * Update an existing flow * - * [#12206, Option A] Same contract as `create` above: answers the - * canonicalized parsed flow the engine stored — always carrying `name`, - * which the old echo could omit on PUT. The engine requires a COMPLETE - * definition (`UpdateFlowRequestSchema`); partial update is not - * implemented. + * [#12206, Option A] Answers the canonicalized parsed flow the engine + * stored — always carrying `name`, which the old echo could omit on PUT. + * The engine requires a COMPLETE definition (`UpdateFlowRequestSchema`); + * partial update is not implemented. [#38174] A flow that exists only: + * a new name answers 422 `WRITABLE_PACKAGE_REQUIRED`. */ update: async (name: string, definition: any, address?: QualifiedAddressOptions): Promise => { const route = this.getRoute('automation'); diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index eeb877ad9bc..e0cfdb2c336 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -165,6 +165,7 @@ import { validateActionLocations } from './validate-action-locations.js'; import { validateObjectActionLayout } from './validate-object-action-layout.js'; import { validateActionObjectBinding } from './validate-action-object-binding.js'; import { validateFlowNodeExecutors } from './validate-flow-node-executors.js'; +import { validateFlowNotifyChannels } from './validate-flow-notify-channels.js'; import { validateInertObjectDeclarations } from './validate-inert-object-declarations.js'; import { lintFlowPatterns } from './lint-flow-patterns.js'; import { lintFlowCredentialLiterals } from './lint-flow-credential-literals.js'; @@ -521,6 +522,14 @@ export interface AuthoringRuleContext { * contradict (AGENTS.md "Startup registry reads"). */ flowNodeTypeVocabulary?: ReadonlySet; + /** + * [#38174] The channels the deployment's messaging service knows + * (`getKnownChannels()`), handed in only once the host's boot has SETTLED. + * Set only by the runtime publish gate; ABSENT on the three CLI commands, + * whose stack does not say which plugins the deployment loads. Read by + * `validateFlowNotifyChannels` only, which judges nothing without it. + */ + notifyChannelRoster?: ReadonlySet; /** * The names of every flow the deployment holds: every installed package's * flows (a disabled package's included), the stored flow rows in every @@ -2461,6 +2470,22 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ runtimeTypes: ['flow'], run: (stack, ctx) => validateFlowNodeExecutors(stack, ctx.flowNodeTypeVocabulary), }, + // [#38174, ruling 6810493176 B] A `notify` node naming a channel no plugin + // registers fails every delivery on it. Judged only against the SETTLED + // roster the runtime gate hands in (`AuthoringRuleContext.notifyChannelRoster`); + // the CLI commands have none, so there the entry runs and judges nothing. + // The `/automation` definition doors ask the same predicate + // (`unregisteredNotifyChannels`). + { + name: 'validateFlowNotifyChannels', + tier: 'gating', + input: 'parsed', + commands: ALL, + source: 'packages/lint/src/validate-flow-notify-channels.ts', + surfaces: CLI_AND_RUNTIME, + runtimeTypes: ['flow'], + run: (stack, ctx) => validateFlowNotifyChannels(stack, ctx.notifyChannelRoster), + }, // A credential typed as a LITERAL into a flow position every flow reader is // served — an `http` node's `headers` or `url` query, a node's // `connectorConfig.input` — named at every authoring door, with the diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index aeb5360d7e1..3284bf232ca 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -810,6 +810,14 @@ export type { ObjectActionLayoutFinding } from './validate-object-action-layout. export { validateActionObjectBinding, ACTION_NO_OBJECT_BINDING } from './validate-action-object-binding.js'; export type { ActionObjectBindingFinding } from './validate-action-object-binding.js'; export { validateFlowNodeExecutors, FLOW_NODE_TYPE_NO_EXECUTOR } from './validate-flow-node-executors.js'; +export { + validateFlowNotifyChannels, + unregisteredNotifyChannels, + notifyChannelEntries, + FLOW_NOTIFY_CHANNEL_UNREGISTERED, + type UnregisteredNotifyChannel, + type NotifyChannelEntry, +} from './validate-flow-notify-channels.js'; export type { FlowNodeExecutorFinding } from './validate-flow-node-executors.js'; export { validateInertObjectDeclarations, diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 79145162bca..fdc077a08df 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -429,6 +429,7 @@ import { } from './rule-explanations/transfer-cascades.js'; import { FLOW_NODE_TYPE_NO_EXECUTOR_EXPLANATION, + FLOW_NOTIFY_CHANNEL_UNREGISTERED_EXPLANATION, FLOW_APPROVAL_DECISION_UNROUTED_EXPLANATION, FLOW_TRIGGER_OBJECT_MISSING_EXPLANATION, FLOW_CONDITION_OPTION_LABEL_EXPLANATION, @@ -724,6 +725,7 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [TRANSFER_CASCADE_EXTENSION_CHILD_INELIGIBLE_EXPLANATION.rule]: TRANSFER_CASCADE_EXTENSION_CHILD_INELIGIBLE_EXPLANATION, [TRANSFER_CASCADE_CHILD_UPDATE_UNEXPOSED_EXPLANATION.rule]: TRANSFER_CASCADE_CHILD_UPDATE_UNEXPOSED_EXPLANATION, [FLOW_NODE_TYPE_NO_EXECUTOR_EXPLANATION.rule]: FLOW_NODE_TYPE_NO_EXECUTOR_EXPLANATION, + [FLOW_NOTIFY_CHANNEL_UNREGISTERED_EXPLANATION.rule]: FLOW_NOTIFY_CHANNEL_UNREGISTERED_EXPLANATION, [FLOW_APPROVAL_DECISION_UNROUTED_EXPLANATION.rule]: FLOW_APPROVAL_DECISION_UNROUTED_EXPLANATION, [FLOW_HTTP_TIMEOUT_MISSING_EXPLANATION.rule]: FLOW_HTTP_TIMEOUT_MISSING_EXPLANATION, [FLOW_TRIGGER_OBJECT_MISSING_EXPLANATION.rule]: FLOW_TRIGGER_OBJECT_MISSING_EXPLANATION, diff --git a/packages/lint/src/rule-explanations/publish-time-inert-refusals.ts b/packages/lint/src/rule-explanations/publish-time-inert-refusals.ts index d908abc2be2..038c68c6bba 100644 --- a/packages/lint/src/rule-explanations/publish-time-inert-refusals.ts +++ b/packages/lint/src/rule-explanations/publish-time-inert-refusals.ts @@ -3,7 +3,7 @@ import type { RuleExplanation } from '../rule-explanations.js'; // ── Publish-time refusals of metadata that parses and does nothing ────────── -// (`validate-flow-node-executors.ts`, `lint-flow-patterns.ts`, +// (`validate-flow-node-executors.ts`, `validate-flow-notify-channels.ts`, `lint-flow-patterns.ts`, // `validate-inert-object-declarations.ts`, `validate-action-object-binding.ts`) export const FLOW_NODE_TYPE_NO_EXECUTOR_EXPLANATION: RuleExplanation = { @@ -22,6 +22,21 @@ export const FLOW_NODE_TYPE_NO_EXECUTOR_EXPLANATION: RuleExplanation = { ], }; +export const FLOW_NOTIFY_CHANNEL_UNREGISTERED_EXPLANATION: RuleExplanation = { + rule: 'flow-notify-channel-unregistered', + covers: 'which channels a notify node may name', + paragraphs: [ + 'A `notify` node\'s `channels` names the messaging channels it delivers on. A channel is code a plugin ' + + 'registers, never data an administrator adds later, so a name no plugin registers is a typo or a missing ' + + 'plugin: the flow publishes and arms, and every delivery on that channel fails at run time.', + 'The rule judges against the channels the deployment\'s messaging service knows, and only once the boot has ' + + 'settled, because plugins register channels while it runs. A channel whose transport is not configured yet ' + + '(`email` with no email service) is known and is never refused for it. The CLI commands judge nothing here: ' + + 'which plugins a deployment loads is not part of the stack. Every flow write door of a running server asks ' + + 'the same question, region bodies included, and its message lists the channels that deployment registers.', + ], +}; + export const FLOW_APPROVAL_DECISION_UNROUTED_EXPLANATION: RuleExplanation = { rule: 'flow-approval-decision-unrouted', covers: 'how an approval decision picks its branch', diff --git a/packages/lint/src/runtime-gate.ts b/packages/lint/src/runtime-gate.ts index a3e7cb329ec..da4401f5d5a 100644 --- a/packages/lint/src/runtime-gate.ts +++ b/packages/lint/src/runtime-gate.ts @@ -1500,6 +1500,13 @@ export function runRuntimeAuthoringRules(args: { * same value in every pass. Omitted, a flow node's type is not judged. */ flowNodeTypeVocabulary?: readonly string[]; + /** + * [#38174] On a `flow` write: the channels the host's messaging service + * knows, stated only once the host's boot has SETTLED. Handed to the rules + * as `AuthoringRuleContext.notifyChannelRoster`, the same value in every + * pass. Omitted, a `notify` node's channels are not judged. + */ + notifyChannelRoster?: readonly string[]; /** * On a `flow` write: the names of every flow the deployment holds, as the * host read them (every installed package's flows, a disabled package's @@ -1605,6 +1612,12 @@ export function runRuntimeAuthoringRules(args: { ...(args.flowNodeTypeVocabulary !== undefined && args.flowNodeTypeVocabulary.length > 0 ? { flowNodeTypeVocabulary: new Set(args.flowNodeTypeVocabulary) } : {}), + // [#38174] The settled channel roster, stated by the host on a flow write; + // the same value in every pass, so it moves no baseline. An EMPTY roster + // is a verdict too (the deployment registers no channel), so it is passed. + ...(args.notifyChannelRoster !== undefined + ? { notifyChannelRoster: new Set(args.notifyChannelRoster) } + : {}), // The deployment's flow names, stated by the host on a flow write; the // same value in every pass, so it moves no baseline. ...(args.deploymentFlowNames !== undefined && args.deploymentFlowNames.length > 0 diff --git a/packages/lint/src/validate-flow-notify-channels.ts b/packages/lint/src/validate-flow-notify-channels.ts new file mode 100644 index 00000000000..a47c6159db1 --- /dev/null +++ b/packages/lint/src/validate-flow-notify-channels.ts @@ -0,0 +1,158 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A `notify` node naming a channel no plugin registers in the deployment. + * + * A channel is code a plugin registers with the messaging service, never data + * an administrator adds later, so a name no plugin registers can only be a + * typo or a missing plugin: at run time every delivery on it fails with + * `channel 'NAME' not registered`, and the node records a warning, after the + * flow was saved and armed with no word to its author (ruling 6810493176, + * letter B). + * + * ## One judge for both flow write doors + * + * The `/automation` definition doors (`@objectstack/runtime`) refused this + * first; the metadata door (`PUT /meta/flow/:name`) stored it and armed it + * (#38174's premise measurement). One operation with two doors is judged by + * one predicate, the governed one: {@link unregisteredNotifyChannels} is what + * both doors ask, and this rule is how the metadata protocol's runtime publish + * gate asks it. + * + * ## Judged against a SETTLED roster, never a registry still filling + * + * The channel registry fills during the boot (the messaging plugin registers + * its `email`, `sms` and `push` providers from its own `kernel:ready` + * handler), so an absence is a verdict only once nothing can still register + * (AGENTS.md "Startup registry reads"). The rule judges only with the roster + * its caller hands in, and a caller hands one in only once the boot has + * settled. With no roster (every CLI command, whose stack does not say which + * plugins the deployment loads) the rule judges nothing. + * + * The roster is the KNOWN channels: a lazy provider whose transport is not + * installed yet (`email` with no email service) is known, so a node naming it + * is never refused for it. + * + * Every node is judged, at any region depth (`collectFlowGraphs`). + */ + +import { collectFlowGraphs, type FlowNodeParsed } from '@objectstack/spec/automation'; +import { recordsOf, nearestName } from './object-graph.js'; + +export const FLOW_NOTIFY_CHANNEL_UNREGISTERED = 'flow-notify-channel-unregistered'; + +/** One channel name a `notify` node's `channels` carries, and where. */ +export interface NotifyChannelEntry { + readonly channel: string; + /** Its key path below the node's `config.channels`: `[]` for the string form, `[i]` for a list member. */ + readonly at: readonly number[]; +} + +/** + * The channel names a `notify` node's `channels` value holds, read the way the + * node's executor reads them at run time (`toStringList` in + * `service-automation`'s `notify-node.ts`): a string or a list of strings, + * read raw, each trimmed, blank entries dropped. An absent value names no + * channel (the node then delivers to the inbox, the messaging default). + */ +export function notifyChannelEntries(value: unknown): NotifyChannelEntry[] { + if (Array.isArray(value)) { + const entries: NotifyChannelEntry[] = []; + value.forEach((member, index) => { + if (member == null) return; + const channel = String(member).trim(); + if (channel) entries.push({ channel, at: [index] }); + }); + return entries; + } + if (typeof value === 'string' && value.trim()) return [{ channel: value.trim(), at: [] }]; + return []; +} + +/** One `notify` node's channel that no plugin registers. */ +export interface UnregisteredNotifyChannel { + readonly nodeId: string; + readonly channel: string; + /** The key path from the flow root, dotted (`nodes.1.config.channels.0`). */ + readonly field: string; + /** The region the node sits in, when it is not the top-level graph. */ + readonly scope?: string; + /** The nearest known channel name, when one is close. */ + readonly near?: string; + /** The sentence that names it. */ + readonly line: string; +} + +/** + * Every `notify` node channel in `flow` that `known` does not list, at any + * region depth. The one predicate both flow write doors ask. + */ +export function unregisteredNotifyChannels( + flow: unknown, + known: readonly string[], +): UnregisteredNotifyChannel[] { + if (!flow || typeof flow !== 'object') return []; + const found: UnregisteredNotifyChannel[] = []; + for (const graph of collectFlowGraphs(flow as { nodes?: readonly FlowNodeParsed[] })) { + graph.nodes.forEach((node, index) => { + if (node.type !== 'notify') return; + const config = node.config as { channels?: unknown } | undefined; + for (const { channel, at } of notifyChannelEntries(config?.channels)) { + if (known.includes(channel)) continue; + const field = [...graph.path, 'nodes', index, 'config', 'channels', ...at].join('.'); + const where = graph.scope ? ` (in ${graph.scope})` : ''; + const near = nearestName(channel, known); + const line = + `node '${node.id}' (\`notify\`)${where} names channel '${channel}' at ${field}, which no plugin ` + + `registers in this deployment${near ? ` — did you mean '${near}'?` : ''}`; + found.push({ + nodeId: String(node.id), channel, field, line, + ...(graph.scope ? { scope: graph.scope } : {}), + ...(near ? { near } : {}), + }); + } + }); + } + return found; +} + +export interface FlowNotifyChannelFinding { + severity: 'error'; + rule: string; + where: string; + path: string; + message: string; + hint: string; +} + +/** + * Flag every `notify` node channel outside `known`, the channels the + * deployment's messaging service knows once its boot has settled. Returns + * nothing when no roster is given. + */ +export function validateFlowNotifyChannels( + stack: Record, + known: ReadonlySet | undefined, +): FlowNotifyChannelFinding[] { + const findings: FlowNotifyChannelFinding[] = []; + if (!known || !stack || typeof stack !== 'object') return findings; + const roster = [...known].sort(); + const flowList: readonly unknown[] = Array.isArray(stack.flows) ? stack.flows : []; + for (const flow of recordsOf(stack.flows)) { + const flowName = typeof flow.name === 'string' ? flow.name : '(unnamed flow)'; + const flowPath = `flows[${Math.max(flowList.indexOf(flow), 0)}]`; + for (const hit of unregisteredNotifyChannels(flow, roster)) { + findings.push({ + severity: 'error', + rule: FLOW_NOTIFY_CHANNEL_UNREGISTERED, + where: `flow '${flowName}' · node '${hit.nodeId}'`, + path: `${flowPath}.${hit.field}`, + message: `The ${hit.line}: the flow publishes, and every delivery on that channel fails at run time.`, + hint: roster.length === 0 + ? 'This deployment registers no channel: install the plugin that provides one, or remove the channel.' + : `Name a channel this deployment registers (${roster.join(', ')}), or install the plugin that provides '${hit.channel}'.`, + }); + } + } + return findings; +} diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index 8b477e37419..b86d8df6e0d 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -111,6 +111,8 @@ export interface AuthoringGateHost { formRestoreRefusal: (type: string, item: unknown, name: string, binding: string | null) => Promise; /** [#34776] The automation engine's sealed node-type vocabulary ({@link sealedFlowNodeTypeVocabulary}). */ sealedFlowNodeTypeVocabulary: () => readonly string[] | undefined; + /** [#38174] The messaging service's known channels, once the boot has settled ({@link settledNotifyChannelRoster}). */ + settledNotifyChannelRoster: () => readonly string[] | undefined; } /** The body of `ObjectStackProtocolImplementation#restoredBodyDerivation`; the method's docblock there is its contract. */ @@ -342,7 +344,7 @@ export function withTargetFoldedWithout( * The members {@link judgeRuntimeAuthoringRules} reads: the host facts and * collections every judgement of the shared rules is made against. */ -type RuntimeRulesHost = Pick & { +type RuntimeRulesHost = Pick & { /** * [#35143] The protocol's services registry reader, read per call and * recorded nowhere: {@link deploymentFlowNamesOf} asks its `automation` @@ -672,6 +674,11 @@ export async function judgeRuntimeAuthoringRules( // flow write only, and passed in so the gate stays pure. const flowNodeTypeVocabulary = singular === 'flow' ? this.sealedFlowNodeTypeVocabulary() : undefined; + // [#38174] The channels the deployment's messaging service knows, stated + // only once the boot has settled — a host fact of the same kind, read here + // per publish, on a flow write only, and passed in so the gate stays pure. + const notifyChannelRoster = singular === 'flow' ? this.settledNotifyChannelRoster() : undefined; + // [#35143] Every flow the deployment holds, by name, on a flow write whose // body calls another flow only: the universe a `subflow` / `map` call is // judged against, since the gate's own snapshot holds just the written @@ -737,6 +744,8 @@ export async function judgeRuntimeAuthoringRules( ...(rlsMembershipResolverKeys !== undefined ? { rlsMembershipResolverKeys } : {}), // With it the gate refuses a flow node no executor of this deployment runs. ...(flowNodeTypeVocabulary !== undefined ? { flowNodeTypeVocabulary } : {}), + // [#38174] With it the gate refuses a notify node naming a channel no plugin registers. + ...(notifyChannelRoster !== undefined ? { notifyChannelRoster } : {}), // [#35143] With it the gate refuses a subflow / map call to a flow the deployment does not hold. ...(deploymentFlowNames !== undefined ? { deploymentFlowNames } : {}), // [#26188] With it the gate refuses a hierarchy scope no resolver enforces. @@ -1170,3 +1179,49 @@ export function sealedFlowNodeTypeVocabulary( ? (vocabulary as readonly string[]) : undefined; } + +/** + * [#38174, ruling 6810493176 B] The channels the deployment's messaging + * service knows (`getKnownChannels()`), read per write: the roster the runtime + * publish gate refuses a `notify` node naming any other channel against + * (`flow-notify-channel-unregistered`), the predicate the `/automation` + * definition doors ask too. + * + * Stated only once the boot has SETTLED, because plugins register channels + * while it runs (the messaging plugin registers `email`, `sms` and `push` from + * its own `kernel:ready` handler), and "no plugin registers it" read earlier is + * a verdict the boot can contradict (AGENTS.md "Startup registry reads"). The + * settled signal is the automation engine's sealed node-type vocabulary + * ({@link sealedFlowNodeTypeVocabulary}): it is sealed at `kernel:bootstrapped`, + * which the kernel raises only after every `kernel:ready` handler has run, and + * a deployment with no automation engine runs no `notify` node at all. + * + * `undefined` (nothing judged) when the boot has not settled, when there is no + * messaging service or it cannot list its channels, or when the list is not a + * list of `{ id: string }`: an unreadable registry gives no verdict, as at the + * `/automation` doors. + */ +export function settledNotifyChannelRoster( + this: { readonly getServicesRegistry?: () => Map }, +): readonly string[] | undefined { + if (sealedFlowNodeTypeVocabulary.call(this) === undefined) return undefined; + let messaging: unknown; + try { + messaging = this.getServicesRegistry?.().get('messaging'); + } catch { + return undefined; + } + const read = (messaging as { getKnownChannels?: () => unknown } | undefined)?.getKnownChannels; + if (typeof read !== 'function') return undefined; + let listed: unknown; + try { + listed = read.call(messaging); + } catch { + return undefined; + } + if (!Array.isArray(listed)) return undefined; + const isChannel = (entry: unknown): entry is { id: string } => + !!entry && typeof entry === 'object' && typeof (entry as { id?: unknown }).id === 'string'; + if (!listed.every(isChannel)) return undefined; + return listed.map((entry) => entry.id); +} diff --git a/packages/metadata-protocol/src/protocol-package-scope.ts b/packages/metadata-protocol/src/protocol-package-scope.ts index 503bf636975..beeee8b2aa3 100644 --- a/packages/metadata-protocol/src/protocol-package-scope.ts +++ b/packages/metadata-protocol/src/protocol-package-scope.ts @@ -110,9 +110,10 @@ export function uninstalledNamedBaseRefusal( const type = PLURAL_TO_SINGULAR[request.type] ?? request.type; // Kept under the REST door's client-message bound (`truncateClientMessage`) // for ordinary names, so the last sentence reaches the caller. + // [#38174] Never "with no package": a new item names a writable package + // (ADR-0070 D1), and the kernel refuses a package-less create. const storedWayOut = `Create a package with that id first, or remove the rows bound to it (a delete naming ` - + `that package; discard-drafts for drafts) and save again, into an installed writable package or with ` - + `no package.`; + + `that package; discard-drafts for drafts) and save again, into an installed writable package.`; const err = new Error( how.verb === 'rollback' ? `Cannot roll back ${type} '${request.name}' into package '${namedBase}': no row of it is stored ` @@ -129,8 +130,8 @@ export function uninstalledNamedBaseRefusal( + `extend that binding. ${storedWayOut} Nothing was written.` : `Cannot save ${type} '${request.name}' into package '${namedBase}': no package with that id is ` + `installed in this deployment, so the ${type} would be stored bound to a package that does not ` - + `exist. Name an installed writable package as the ${type}'s base (or create one first), or save ` - + `the ${type} without naming a package. Nothing was written.`, + + `exist. Name an installed writable package as the ${type}'s base, or create one first. ` + + `Nothing was written.`, ); (err as any).code = 'WRITABLE_PACKAGE_REQUIRED'; (err as any).status = 422; diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index cc8711b3d6a..a676760b4ad 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -273,6 +273,7 @@ import { restoredBodyWriter, runAuthoringGate, sealedFlowNodeTypeVocabulary, + settledNotifyChannelRoster, } from './protocol-authoring-gate.js'; // [#25467 cut 9] The credential carry-forward and the credential channel lookup. import { @@ -1932,6 +1933,7 @@ export class ObjectStackProtocolImplementation implements resolveWritePackageScope: (...a) => this.resolveWritePackageScope(...a), rlsMembershipResolverKeys: (...a) => this.rlsMembershipResolverKeys(...a), sealedFlowNodeTypeVocabulary: (...a) => this.sealedFlowNodeTypeVocabulary(...a), + settledNotifyChannelRoster: (...a) => this.settledNotifyChannelRoster(...a), tenancyPostureInForce: (...a) => this.tenancyPostureInForce(...a), servicesRegistry: () => this.getServicesRegistry, }; @@ -2239,6 +2241,15 @@ export class ObjectStackProtocolImplementation implements return sealedFlowNodeTypeVocabulary.call(host); } + /** [#38174] The messaging service's known channels once the boot has settled; the body's docblock is its contract. */ + private settledNotifyChannelRoster(): readonly string[] | undefined { + const readGetServicesRegistry = () => this.getServicesRegistry; + const host: ThisParameterType = { + get getServicesRegistry() { return readGetServicesRegistry(); }, + }; + return settledNotifyChannelRoster.call(host); + } + /** * [#26188] Is a hierarchy resolver mounted on this runtime — a service * registered under `HIERARCHY_SCOPE_RESOLVER_SERVICE` (ADR-0057; the diff --git a/packages/metadata-protocol/src/runtime-authoring-gate.ts b/packages/metadata-protocol/src/runtime-authoring-gate.ts index 34926a44852..831d2c5d006 100644 --- a/packages/metadata-protocol/src/runtime-authoring-gate.ts +++ b/packages/metadata-protocol/src/runtime-authoring-gate.ts @@ -1492,6 +1492,14 @@ export function evaluateRuntimeAuthoringGate(args: { * judged. */ flowNodeTypeVocabulary?: readonly string[]; + /** + * [#38174] On a `flow` write: the channels the host's messaging service + * knows, stated only once the boot has settled. A fact only the host + * holds, of the #6285 kind: handed to the shared rules, where + * `validateFlowNotifyChannels` refuses a `notify` node naming any other + * channel. Absent, channels are not judged. + */ + notifyChannelRoster?: readonly string[]; /** * On a `flow` write: the names of every flow the deployment holds, as the * impure caller read them (every installed package's flows, the stored @@ -1593,6 +1601,9 @@ export function evaluateRuntimeAuthoringGate(args: { ...(args.flowNodeTypeVocabulary !== undefined ? { flowNodeTypeVocabulary: args.flowNodeTypeVocabulary } : {}), + ...(args.type === 'flow' && args.notifyChannelRoster !== undefined + ? { notifyChannelRoster: args.notifyChannelRoster } + : {}), ...(args.type === 'flow' && args.deploymentFlowNames !== undefined ? { deploymentFlowNames: withPendingFlowNames(args.deploymentFlowNames, args.pending?.flows) } : {}), diff --git a/packages/plugins/plugin-sharing/src/objects/sys-sharing-rule.object.ts b/packages/plugins/plugin-sharing/src/objects/sys-sharing-rule.object.ts index 44e8637596d..8edf15824d2 100644 --- a/packages/plugins/plugin-sharing/src/objects/sys-sharing-rule.object.ts +++ b/packages/plugins/plugin-sharing/src/objects/sys-sharing-rule.object.ts @@ -290,6 +290,14 @@ export const SysSharingRule = ObjectSchema.create({ // organization's own rule (`managed_by` admin) is never asked and stays // empty, as does a name no single package holds. Nothing reads it yet and // no writer stamps it. Width: the package-id class (`sys_metadata.package_id`). + // + // [#38174, decision Q-d answered A] The kernel's package-less create close + // (ADR-0070 D1) does not reach these rows, and they bind to no package: an + // organization's own sharing rule (like its queues and assignment rules) is + // a DATA row written through the data door and `POST /sharing/rules` + // (regime C, ADR-0131 D6), never a `sys_metadata` item — the type is + // code-only (`allowRuntimeCreate: false`). So this column stays empty for + // them, and no `.custom` binding is asked of them. package_id: Field.text({ label: 'Package', required: false, diff --git a/packages/runtime/src/dispatcher-plugin.ts b/packages/runtime/src/dispatcher-plugin.ts index 831a228f4c3..caaaa55c0a4 100644 --- a/packages/runtime/src/dispatcher-plugin.ts +++ b/packages/runtime/src/dispatcher-plugin.ts @@ -1813,22 +1813,12 @@ export function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plu // `automation` service (which lives on the project kernel, // not the host kernel, in ObjectOS multi-tenant mode). const registerAutomationRoutes = (base: string) => { - // [#19543, door ④] No `GET ${base}/automation`: the flow-list - // route is RETIRED (「退役,统一走 /meta/flow」), so GET is not - // mounted at this path at all and the host gives its standard - // unmatched answer — on the Hono host a `405` with - // `Allow: POST`, because the POST below (createFlow) keeps the - // path; the same answer any POST-only path gets, with no - // residual refusal of its own. Flows are metadata (ADR-0106); - // the list is `GET /api/v1/meta/flow`. - server!.post(`${base}/automation`, async (req: any, res: any) => { - try { - const result = await dispatcher.dispatch('POST', '/automation', deferRequestBody(req), req.query, { request: req }); - sendResult(result, res); - } catch (err: any) { - errorResponse(err, res); - } - }); + // [#19543, door ④; #38174] Nothing is mounted at + // `${base}/automation` itself: the flow list (GET) and the + // create door (POST) are both RETIRED, so the host gives its + // standard unmatched answer. Flows are metadata (ADR-0106): the + // list is `GET /api/v1/meta/flow` and a new flow is created by + // `PUT /api/v1/meta/flow/:name?package=` (ruling 7234518908). // [#7526] `/actions`, `/connectors`, `/_status` — REGISTERED // BEFORE `/automation/:name`, which is the whole point. diff --git a/packages/runtime/src/domains/automation.ts b/packages/runtime/src/domains/automation.ts index 78fbc1a27ce..8dc366baa49 100644 --- a/packages/runtime/src/domains/automation.ts +++ b/packages/runtime/src/domains/automation.ts @@ -56,8 +56,8 @@ import { unknownQueryParamRefusalMessage } from '@objectstack/rest'; import { validationFailure, validationFailureDetails, fieldsFromZodIssues, VALIDATION_FAILED_STATUS, } from '../validation-failure.js'; -import { ExecutionStatus, collectFlowGraphs, type FlowNodeParsed } from '@objectstack/spec/automation'; -import { nearestName } from '@objectstack/formula'; +import { ExecutionStatus } from '@objectstack/spec/automation'; +import { unregisteredNotifyChannels } from '@objectstack/lint'; import { ListRunsRequestSchema, RecordUpdateStartsRequestSchema, standardErrorCodeForHttpStatus } from '@objectstack/spec/api'; import { recordNotFoundError } from '@objectstack/metadata-protocol'; import type { ResumeFailureDetails } from '@objectstack/spec/api'; @@ -536,7 +536,7 @@ const FLOW_WRITE_DENY_MESSAGE = * Shaped on {@link SCREEN_READ_DENY_MESSAGE} (#7968) one screen up: a second * constant for a second question, rather than a reworded shared one. Rewording * the shared sentence was considered and declined — it reads correctly for the - * authoring writes that reach it (`POST /`, `PUT /:name`, `DELETE /:name`, and + * authoring writes that reach it (`PUT /:name`, `DELETE /:name`, and * [#12156]'s `POST /:name/clone`), and widening it to cover both would degrade * it for every one of them in order to fix one. * @@ -620,10 +620,8 @@ function isFlowEnablementWrite(parts: string[], method: string): boolean { * keep the posture the #7900 audit recorded for them. */ function isFlowAuthoringWrite(parts: string[], method: string): boolean { - // `POST /automation` — the create door. `parts` is empty only for the - // domain root, so `POST /trigger/:name` (parts `['trigger', name]`) and - // `POST /:name/trigger` cannot reach this arm. - if (method === 'POST' && parts.length === 0) return true; + // [#38174] `POST /automation`, the create door, is retired: no branch + // answers it, so there is nothing for this predicate to gate. // [commit 266436a7f] `POST /automation/:name/toggle` — the enablement door. // // Matched exactly as the ROUTER matches it, not approximately, because a @@ -778,7 +776,7 @@ function refuseUngrantedFlowWrite( /** * [ADR-0131 D3 · D12 items 7–8] The walled refusal at the `/automation` - * definition writes (`POST /`, `PUT /:name`, `DELETE /:name`, + * definition writes (`PUT /:name`, `DELETE /:name`, * `POST /:name/clone`). The decision is `walledCatalogWriteVerdict`'s * (`@objectstack/metadata-core`), never restated: admitted under `single`, with * no `tenancy` service, for `isSystem` and for the `PLATFORM_ADMIN` rung; @@ -2088,7 +2086,7 @@ const FLOW_METADATA_TYPE = 'flow'; * doors onto one definition cannot disagree about what is withheld; this * function holds no opinion of its own about what a credential is. * - * Applied at the four exits — `GET /:name`, the `POST /` and `PUT /:name` + * Applied at the four exits — `GET /:name`, the `PUT /:name` * write answers (#12206: a write answers what the subsequent read serves) and * the clone answer — and NOT to `automationService.getFlow` itself: that is the * in-process read the clone copies a WHOLE definition through (ADR-0126 §7.1), @@ -2165,7 +2163,7 @@ async function cloneTargetHeld(readHeld: (name: string) => Promise, nam /** * [#20552] The write-path inverse for the two doors that overwrite a flow by - * name (`POST /` onto an existing name, `PUT /:name`): a body that carries the + * name (`PUT /:name`): a body that carries the * projected form — no secret where the read served none — keeps the secret the * engine holds, so a read → edit → republish round trip never wipes it; an * explicit value replaces it. The metadata plane's own save door applies the @@ -2295,35 +2293,6 @@ interface NotifyChannelRegistry { getKnownChannels(): ReadonlyArray<{ id: string; configured: boolean }>; } -/** One channel name a `notify` node's `channels` carries, and where. */ -interface NotifyChannelEntry { - readonly channel: string; - /** Its key path below the node's `config.channels`: `[]` for the string form, `[i]` for a list member. */ - readonly at: readonly number[]; -} - -/** - * The channel names a `notify` node's `channels` value holds, read the way the - * node's executor reads them at run time (`toStringList` in - * `service-automation`'s `notify-node.ts`): a string or a list of strings, - * read raw, each trimmed, blank entries dropped. An absent value names no - * channel (the node then delivers to the inbox, the messaging default), so - * nothing here is judged for it. - */ -function notifyChannelEntries(value: unknown): NotifyChannelEntry[] { - if (Array.isArray(value)) { - const entries: NotifyChannelEntry[] = []; - value.forEach((member, index) => { - if (member == null) return; - const channel = String(member).trim(); - if (channel) entries.push({ channel, at: [index] }); - }); - return entries; - } - if (typeof value === 'string' && value.trim()) return [{ channel: value.trim(), at: [] }]; - return []; -} - /** * Refuse, at the `/automation` definition write doors, a `notify` node that * names a channel this deployment does not register (ruling 6810493176, letter @@ -2373,7 +2342,9 @@ function notifyChannelEntries(value: unknown): NotifyChannelEntry[] { * registers a package's flows from the automation plugin's `start()`, before * the messaging plugin's `kernel:ready` handler has registered its providers, * and a stored row re-registered later must keep binding as it did when it - * was saved. Every node is judged, at any region depth (`collectFlowGraphs`). + * was saved. Every node is judged, at any region depth: the predicate is + * `@objectstack/lint`'s `unregisteredNotifyChannels`, which the metadata + * door's publish gate asks too (#38174). */ async function refuseUnknownNotifyChannels( deps: DomainHandlerDeps, @@ -2410,25 +2381,11 @@ async function refuseUnknownNotifyChannels( const known = read as Array<{ id: string; configured: boolean }>; const knownIds = known.map((entry) => entry.id); - const lines: string[] = []; - const fields: Array<{ field: string; code: string; message: string }> = []; - for (const graph of collectFlowGraphs(flow as { nodes?: readonly FlowNodeParsed[] })) { - graph.nodes.forEach((node, index) => { - if (node.type !== 'notify') return; - const config = node.config as { channels?: unknown } | undefined; - for (const { channel, at } of notifyChannelEntries(config?.channels)) { - if (knownIds.includes(channel)) continue; - const field = [...graph.path, 'nodes', index, 'config', 'channels', ...at].join('.'); - const where = graph.scope ? ` (in ${graph.scope})` : ''; - const near = nearestName(channel, knownIds); - const line = - `node '${node.id}' (\`notify\`)${where} names channel '${channel}' at ${field}, which no plugin ` + - `registers in this deployment${near ? ` — did you mean '${near}'?` : ''}`; - lines.push(line); - fields.push({ field, code: 'invalid_value', message: line }); - } - }); - } + // [#38174] One predicate for both flow write doors: the metadata door's + // publish gate asks the same one (`flow-notify-channel-unregistered`). + const hits = unregisteredNotifyChannels(flow, knownIds); + const lines = hits.map((hit) => hit.line); + const fields = hits.map((hit) => ({ field: hit.field, code: 'invalid_value', message: hit.line })); if (lines.length === 0) return undefined; const roster = known.length === 0 @@ -2449,7 +2406,7 @@ async function refuseUnknownNotifyChannels( /** * [#20679, ADR-0126 §2] THE LOCKED BASE at this domain's definition-write and - * removal doors — `PUT /:name`, `DELETE /:name`, and `POST /` onto a name the + * removal doors — `PUT /:name`, `DELETE /:name`, and (until #38174 retired it) `POST /` onto a name the * engine already holds (a create onto an existing name is an overwrite). * * ADR-0126 §2 puts a packaged flow in Regime C: "the packaged base is locked — @@ -2511,7 +2468,7 @@ async function refusePackagedFlowBaseChange( /** * [#20761, ADR-0126 §2, ADR-0131 D6] THE AUTHORING RULE at this domain's - * definition-write doors — `POST /`, `PUT /:name` and the copy + * definition-write doors — `PUT /:name` and the copy * `POST /:name/clone` writes: a flow written through an authoring door is * tenant-authored, no exception. * @@ -2675,13 +2632,44 @@ function isFirstWriteConflict(refusal: unknown): boolean { return envelope?.code === 'METADATA_CONFLICT' && (envelope.status ?? envelope.statusCode) === 409; } +/** + * [#38174] Whether a store refusal is the kernel's package-less create refusal + * (`422 WRITABLE_PACKAGE_REQUIRED` naming no package): read from the ADR-0112 + * envelope and the absence of a `packageId`, which ADR-0070 D1's read-only-base + * refusal always carries — never from the sentence. + */ +function isPackagelessCreateRefusal(refusal: unknown): refusal is { writablePackages?: readonly string[] } { + const envelope = refusal as { code?: unknown; status?: unknown; packageId?: unknown } | null | undefined; + return envelope?.code === 'WRITABLE_PACKAGE_REQUIRED' && envelope.status === 422 && envelope.packageId === undefined; +} + +/** + * [#38174, ruling 7234518908 (Q-g C)] `PUT /automation/:name` updates flows + * that exist; a new name is created through the metadata door, in a package. + * The prescription comes first (a 4xx message can be truncated at a REST + * boundary), then the writable packages the kernel listed. ⛔ It never + * prescribes `?package=` on this door: that is a new door input. + */ +function flowNewNameRefusalMessage(name: string, refusal: { writablePackages?: readonly string[] }): string { + const writable = Array.isArray(refusal.writablePackages) ? refusal.writablePackages : undefined; + const listed = writable === undefined + ? '' + : writable.length === 0 + ? ' No package in this environment is writable: create one first.' + : ` Writable packages here: ${writable.slice(0, FLOW_PACKAGES_SHOWN).join(', ')}` + + `${writable.length > FLOW_PACKAGES_SHOWN ? `, and ${writable.length - FLOW_PACKAGES_SHOWN} more` : ''}.`; + return `Create flow '${name}' through the metadata door, in a package: PUT ${FLOW_META_ITEM_ROUTE}/${name}?package=PKG ` + + `with the flow definition as the body. /api/v1/automation updates flows that exist and reads no ?package=; ` + + `a new flow belongs to a package (ADR-0070). Nothing was written.${listed}`; +} + /** * [#23501] The refusal a definition door answers for a write the store refused: * the store's own, as it was thrown, unless {@link flowPackagesRefusingWrite} * reads it as a name two or more packages hold — then this door's own * `409 RESOURCE_CONFLICT`, whose remedy is one its caller can follow: * - * - `'definition'` (`POST /`, `PUT /:name`) and `'delete'` (`DELETE /:name`): + * - `'definition'` (`PUT /:name`) and `'delete'` (`DELETE /:name`): * the metadata door's `?package=` route, {@link flowPackageRefusalMessage}; * - `'clone'`: the clone door's own taken-name refusal. A name two packages * hold is taken, and a clone takes a NEW name (ADR-0126 §7.1) — writing the @@ -2707,6 +2695,14 @@ async function flowWriteRefusal( code: 'RESOURCE_CONFLICT', status: FLOW_CLONE_NAME_TAKEN_STATUS, }); } + // [#38174, ruling 7234518908 (Q-g C)] A new flow name: the kernel refuses + // the package-less create, and this door holds no package, so its remedy + // ("add ?package=") is relayed as the metadata door's route. + if (door === 'definition' && isPackagelessCreateRefusal(refusal)) { + return Object.assign(new Error(flowNewNameRefusalMessage(name, refusal)), { + code: 'WRITABLE_PACKAGE_REQUIRED', status: 422, docs: 'docs/adr/0070-package-first-authoring.md', + }); + } const packageIds = await flowPackagesRefusingWrite(store, refusal, name); if (!packageIds) return refusal; const [message, status] = door === 'clone' @@ -2717,7 +2713,7 @@ async function flowWriteRefusal( /** * [#20862, #20761, ADR-0126 §2, ADR-0131 D6] THE ONE PERSISTENCE PATH for this - * domain's definition writes — `POST /`, `PUT /:name` and the copy + * domain's definition writes — `PUT /:name` and the copy * `POST /:name/clone` writes: register the definition in the engine, then save * it as a tenant row through the metadata protocol's own `saveMetaItem`. * @@ -2734,6 +2730,10 @@ async function flowWriteRefusal( * The default save mode is the live one (`active`), which is what the * engine registration already is: a draft row would leave the engine * running a flow the next boot does not bind. + * - **A new name is refused** [#38174, ADR-0070 D1]: the kernel refuses a + * package-less create, so `PUT /:name` updates flows that exist and a new + * name answers `422 WRITABLE_PACKAGE_REQUIRED` with the metadata door's + * route ({@link flowWriteRefusal}), the registration undone as below. * - **No package, because no caller here holds one** [#23292]. The save * resolves the row (ADR-0048): the one package's row when the flow's * active rows are bound to exactly one, else the package-unbound row; a @@ -2749,7 +2749,7 @@ async function flowWriteRefusal( * The protocol's own remedy ("on the REST door add ?package=") is for the * doors that read `?package=`, and this one does not, so it is not relayed * as it is ({@link flowWriteRefusal}). `door` says which answer: - * `'definition'` (`POST /`, `PUT /:name`) sends the save to the metadata + * `'definition'` (`PUT /:name`) sends the save to the metadata * door's `PUT /meta/flow/:name?package=`; `'clone'` answers the clone * door's own taken-name refusal, because a name two packages hold is taken * and a clone takes a NEW name (ADR-0126 §7.1) — writing the copy into one @@ -3839,11 +3839,10 @@ async function respondToRecordUpdateStarts( * GET /connectors → getConnectorDescriptors (ADR-0022; ?type single-string * filter — validated, #7360) * GET /:name → getFlow - * POST / → createFlow (registerFlow) - * ⚑ authoring write — `manage_metadata` (#10145) - * ⚑ packaged base locked — as `PUT /:name` - * ⚑ a name two packages hold — as `PUT /:name` - * PUT /:name → updateFlow + * (POST / → RETIRED, #38174: a new flow is created through + * `PUT /api/v1/meta/flow/:name?package=` — no route answers) + * PUT /:name → updateFlow (a flow that exists; a new name → 422 + * `WRITABLE_PACKAGE_REQUIRED` naming the `/meta` route, #38174) * ⚑ authoring write — `manage_metadata` (#10145) * ⚑ packaged base locked — the `/meta` door's * `403` refusal, ADR-0126 §2 (#20679) @@ -4269,9 +4268,9 @@ export async function handleAutomationRequest(deps: DomainHandlerDeps, path: str // /meta/flow」). With no branch for it, `GET /` reaches the `handled: // false` exit at the foot of this function, which `dispatch()` hands back // as-is, so the transport gives its own unmatched answer: the dispatcher - // plugin never mounts GET here (Hono then answers 405 + `Allow: POST`, - // since createFlow keeps the path), and a catch-all adapter answers its - // enveloped 404. The anonymous floor above still runs first, as for every + // plugin mounts nothing at this path since the create door retired too + // (#38174), so the host answers its own 404, and a catch-all adapter + // answers its enveloped 404. The anonymous floor above still runs first, as for every // path of this domain. ⛔ Do not re-add a branch that answers this path — // not even a 410: the retirement's contract is "no GET lives here", the // same answer as a path where one was never registered. @@ -4295,60 +4294,15 @@ export async function handleAutomationRequest(deps: DomainHandlerDeps, path: str // not — every exit here answers `servedFlowDefinition(…)`, the metadata // plane's own `flow` redaction, so the secret is withheld on both planes. - // POST / → createFlow - if (parts.length === 0 && m === 'POST') { - if (typeof automationService.registerFlow === 'function') { - // [#3899] `registerFlow(body?.name, body)` used to run unchecked, so - // a definition whose `name` was missing or mistyped registered the - // flow under the key `undefined` — 200, body echoed back, caller - // convinced it succeeded, flow unreachable ever after. The name is - // the registry key; require it before touching the registry. - if (!body || typeof body !== 'object' || Array.isArray(body)) { - throw validationFailure('Flow definition body required', [ - { field: '(body)', code: 'invalid_type', message: 'expected a flow definition object' }, - ]); - } - if (typeof body.name !== 'string' || body.name.trim() === '') { - throw validationFailure('Flow definition requires a non-empty `name` (the registry key this flow is stored and triggered under)', [ - { field: 'name', code: body.name === undefined ? 'required' : 'invalid_type', message: 'expected a non-empty string' }, - ]); - } - // [#8055] The engine's verdict on the definition is served as a - // 400, not a 500 — see `flowDefinitionRefusal` above for what that - // does and does not change. Caught and RETURNED (rather than - // rethrown) for the reason the resume branch below already returns - // its engine-originated refusals: `dispatch()` re-throws everything - // that is not a permission denial, so a transport calling it - // directly would otherwise get an exception where every other - // refusal on this domain hands back a response. - // [#12206, Option A] The door answers the canonicalized PARSED - // flow `registerFlow` stored (schema defaults materialized, - // `edge.condition` strings lowered to their envelopes) — the same - // shape `GET /automation/:name` serves — never an echo of the - // caller's own pre-parse bytes. - // [#20679, ADR-0126 §2] Creating onto a name the engine already - // holds is an overwrite (below), so a packaged flow's name is - // locked here exactly as on `PUT /:name` — the same verdict, asked - // before anything is read or registered. A name no code package - // ships is created as before. - // [#20761] …through the one authoring rule, which reuses that - // verdict and also refuses a definition claiming a package's - // provenance for a name no package ships — see - // `refuseUnauthoredFlowWrite`. - const locked = await refuseUnauthoredFlowWrite(deps, context, body.name, body); - if (locked) return locked; - // [#20552] Creating onto a name the engine already holds is an - // overwrite, so the round-trip rule applies here as on `PUT /:name`. - const definition = await keepStoredFlowCredentials(automationService, body.name, body); - // [#20862] Registered AND saved as a tenant row, so the flow this - // answers `200` for survives a restart — see `registerAndSaveFlow`. - const written = await registerAndSaveFlow( - deps, context, automationService as FlowRegistrationService, body.name, definition, 'definition', - ); - if ('refused' in written) return written.refused; - return { handled: true, response: deps.success(servedFlowDefinition(written.registered)) }; - } - } + // [#38174, ruling 7234518908 (Q-g C)] `POST /` — the create door — is + // RETIRED. A new flow is created through the metadata door, in a package: + // `PUT /api/v1/meta/flow/NAME?package=PKG`, which registers and arms it in + // the same boot and judges the same refusals (the notify-channel one + // included, `flow-notify-channel-unregistered`). The kernel refuses a + // package-less create on every door (ADR-0070 D1), and this door holds no + // package. Like the flow list before it, no branch answers this path: + // `POST /` reaches the `handled: false` exit, and the transport gives its + // own unmatched answer. ⛔ Do not re-add a branch here, not even a 410. // GET /actions → list registered action descriptors (ADR-0018). // MUST precede the `/:name → getFlow` catch-all below, otherwise a diff --git a/packages/runtime/src/route-ledger.ts b/packages/runtime/src/route-ledger.ts index 4e5c03ccf02..661a5fdb982 100644 --- a/packages/runtime/src/route-ledger.ts +++ b/packages/runtime/src/route-ledger.ts @@ -604,8 +604,9 @@ export const ROUTE_LEDGER: readonly RouteLedgerEntry[] = [ note: 'legacy verb-first shape; duplicates execute() against a different URL — candidates for consolidation' }, // `GET /automation` (flow list, `automation.list`) — RETIRED by #19543 (door ④): // unmounted, and the flow list is `GET /meta/flow`. No row, because nothing serves it. - { route: 'POST /automation', domain: '/automation', disposition: 'sdk', client: 'automation.create', - note: "authored metadata, so `manage_metadata` gates it: a flow definition lives on the metadata plane (ADR-0106), and this door now asks the capability every other door onto that plane already asks. Fail-closed by construction — an absent executionContext, an absent `systemPermissions` or an empty one all fall through to the refusal, 403 with code `PERMISSION_DENIED` (ADR-0112); only engine self-invocation (`isSystem`, never settable from the wire) bypasses. WHICH routes is one predicate, `isFlowAuthoringWrite` in `domains/automation.ts` — this row, PUT/DELETE `/:name` below, and, since the ruling that enablement is an authoring write, `POST /:name/toggle`, with the execution doors (trigger / execute / resume) deliberately outside it. Second layer, not the first: the domain-wide anonymous floor answers an unidentified caller 401 here, not 403. Pinned in `domains/automation-write-capability-gate.test.ts`" }, + // `POST /automation` (flow create, `automation.create`) — RETIRED by #38174 + // (ruling 7234518908, Q-g C): unmounted; a new flow is created by + // `PUT /meta/flow/:name?package=` (ADR-0070 D1). No row, because nothing serves it. { route: 'GET /automation/actions', domain: '/automation', disposition: 'sdk', client: 'automation.listActions' }, { route: 'GET /automation/connectors', domain: '/automation', disposition: 'sdk', client: 'automation.listConnectors' }, // [#27237] The connector credential door (ruling A on #27230): an administrator @@ -637,13 +638,13 @@ export const ROUTE_LEDGER: readonly RouteLedgerEntry[] = [ note: "Ruling record 7073655354: a caller who can READ the record is answered the flows the proposed update would start, each as `{ name, label, startsApproval }` — no description, condition, node or link; hooks are never listed (ADR-0077 §2); no new capability. Body `RecordUpdateStartsRequestSchema` (`{ object, recordId, changes }`, closed; 400 `VALIDATION_FAILED` on the member). No query parameter is read, so any is refused 400 `VALIDATION_ERROR`. The record is read AS THE CALLER through the `/data` door's own `get` (`callData`), so an object the caller may not address or a record they cannot read answers that read's refusal (404 `RECORD_NOT_FOUND`, the same as an absent id) and the engine is never asked; a read that answers no record is refused the same 404. Every `changes` key must be a declared field of the object (the registry object's own `fields` key; the request schema also holds each key to the field-name grammar), else 400 `VALIDATION_FAILED` on `changes.KEY` and the engine is never asked. The engine (`IAutomationService.listRecordUpdateStarts`) lists enabled flows armed on a record-change trigger of the object whose token binds an update (the spec's `recordChangeTriggerFiresOnUpdate`) and whose start condition holds — the ONE start-condition gate a run passes — for the stored row with `changes` applied against the stored row; a condition it cannot evaluate is not listed; nothing runs or is written. An engine without the optional member answers 501. The domain-wide anonymous floor answers 401 first. Pinned in `domains/automation-record-update-starts.test.ts`" }, { route: 'POST /automation/:name/trigger', domain: '/automation', disposition: 'sdk', client: 'automation.execute' }, { route: 'POST /automation/:name/toggle', domain: '/automation', disposition: 'sdk', client: 'automation.toggle', - note: "enablement, and since the 2026-08-23 ruling that enablement is an authoring write, `manage_metadata` gates it — the same `isFlowAuthoringWrite` door as `POST /automation` above, NOT a fourth copy of the policy. The definition-write gate deliberately left this one out as engine state and filed the question; the measurement is what settled it. No organization wall scopes the enabled bit: `toggleFlow` writes the ADR-0126 §7.2 activation ledger first — one deployment-wide `sys_metadata_activation` row per flow, keyed by `(metadata_type, name)`, carrying the flow's package id and no organization column — and only then updates the engine's in-process projection, which `getFlowRuntimeStates()` reads with no caller and no organization; the automation service is ONE instance per environment — so an unentitled tenant org owner switched a shipped flow off and an unrelated tenant in a different organization, plus the platform admin, read it off, in both directions. Disabling a shipped flow is equivalent to deleting it for as long as it stays off, and DELETE was already gated. ⚠️ BREAKING: 200 → 403 for callers without the capability. Fail-closed on an absent executionContext, an absent `systemPermissions` or an empty one, refusing 403 `PERMISSION_DENIED`, with only `isSystem` bypassing; the domain-wide anonymous floor still answers 401 first. The predicate excludes `POST /automation/trigger/:name` so a flow literally NAMED `toggle` keeps its execution door. Pinned in `domains/automation-write-capability-gate.test.ts` and `qa/dogfood/test/automation-toggle-tenant-scope.dogfood.test.ts`" }, + note: "enablement, and since the 2026-08-23 ruling that enablement is an authoring write, `manage_metadata` gates it — the same `isFlowAuthoringWrite` door as `PUT /automation/:name` below, NOT a fourth copy of the policy. The definition-write gate deliberately left this one out as engine state and filed the question; the measurement is what settled it. No organization wall scopes the enabled bit: `toggleFlow` writes the ADR-0126 §7.2 activation ledger first — one deployment-wide `sys_metadata_activation` row per flow, keyed by `(metadata_type, name)`, carrying the flow's package id and no organization column — and only then updates the engine's in-process projection, which `getFlowRuntimeStates()` reads with no caller and no organization; the automation service is ONE instance per environment — so an unentitled tenant org owner switched a shipped flow off and an unrelated tenant in a different organization, plus the platform admin, read it off, in both directions. Disabling a shipped flow is equivalent to deleting it for as long as it stays off, and DELETE was already gated. ⚠️ BREAKING: 200 → 403 for callers without the capability. Fail-closed on an absent executionContext, an absent `systemPermissions` or an empty one, refusing 403 `PERMISSION_DENIED`, with only `isSystem` bypassing; the domain-wide anonymous floor still answers 401 first. The predicate excludes `POST /automation/trigger/:name` so a flow literally NAMED `toggle` keeps its execution door. Pinned in `domains/automation-write-capability-gate.test.ts` and `qa/dogfood/test/automation-toggle-tenant-scope.dogfood.test.ts`" }, // [#20676, #28149] The ADR-0126 §7.1 clone door. Its domain arm landed with #12156 and // nothing mounted it until #20676, so the row and the mount arrive together. { route: 'POST /automation/:name/clone', domain: '/automation', disposition: 'sdk', client: 'automation.clone', requestSchema: 'CloneFlowRequestSchema', responseSchema: 'CloneFlowResponseSchema', - note: "[ADR-0146 D4] \"New similar\" — copy a flow's whole definition under a NEW machine name, INTO A PACKAGE, switched off. Body `CloneFlowRequestSchema`: `{ name, label }` mandatory, `package` optional, closed (an undeclared key is refused 400 on that key; the door reads the member set off the schema). `package` given: an installed, writable package whose dependency closure holds the source's package (`newSimilarTargetRefusal`, `domains/new-similar-target.ts`: unknown or read-only 422 `WRITABLE_PACKAGE_REQUIRED`, outside the closure 409 `RESOURCE_CONFLICT`). Omitted: the source's paired customization package `.custom`, `` being the package the loader's set says ships the source, ensured through the protocol's `ensureCustomizationPackage` — the body of `POST /packages/:id/ensure-customization`, called in process, never re-implemented; a source no package ships has no pair and is refused 400 on `package`. ⛔ Never a package-less copy (ADR-0070 D5/D6). The copy is written `status: 'obsolete'`, so it never runs beside its original; its save is a first write (a row the target already holds under the name is refused 409, never overwritten). An unknown source answers 404, a taken name 409 `RESOURCE_CONFLICT`, a source holding a credential 409, a definition the engine refuses 400. The schema names the WHOLE BODY, envelope included (as the uninstall row's does): `data` is `{ flow, packageId, notice, noticeCode }`, `packageId` the package the copy landed in, the notice saying the copy is switched off and that references are not re-pointed, and `noticeCode` (`FLOW_CLONE_NOTICE_CODE`) naming that sentence so a console can translate it, `notice` staying the English fallback. ⛔ No ancestry on the definition or the response (ADR-0126 §9). ⚑ `manage_metadata` — the same `isFlowAuthoringWrite` door as `POST /automation` above, then the walled refusal (the gates the ensure door asks, so the in-process ensure creates nothing a caller could not create there); fail-closed, only `isSystem` bypassing, and the domain-wide anonymous floor answers an unidentified caller 401 first. ⛔ NOT the ADR-0126 §5 activation gate: a clone takes nothing away from any tenant. Conformance: `domains/automation-flow-clone-custom-package.test.ts` drives THIS handler over the real protocol, registry and store, parses each answer through `CloneFlowResponseSchema` and pins this row; the copy itself in `domains/automation-flow-clone.test.ts`; over HTTP in `qa/dogfood/test/automation-flow-clone-door.dogfood.test.ts`, the environment-scoped mount in `dispatcher-plugin.automation-clone-mount.integration.test.ts`" }, + note: "[ADR-0146 D4] \"New similar\" — copy a flow's whole definition under a NEW machine name, INTO A PACKAGE, switched off. Body `CloneFlowRequestSchema`: `{ name, label }` mandatory, `package` optional, closed (an undeclared key is refused 400 on that key; the door reads the member set off the schema). `package` given: an installed, writable package whose dependency closure holds the source's package (`newSimilarTargetRefusal`, `domains/new-similar-target.ts`: unknown or read-only 422 `WRITABLE_PACKAGE_REQUIRED`, outside the closure 409 `RESOURCE_CONFLICT`). Omitted: the source's paired customization package `.custom`, `` being the package the loader's set says ships the source, ensured through the protocol's `ensureCustomizationPackage` — the body of `POST /packages/:id/ensure-customization`, called in process, never re-implemented; a source no package ships has no pair and is refused 400 on `package`. ⛔ Never a package-less copy (ADR-0070 D5/D6). The copy is written `status: 'obsolete'`, so it never runs beside its original; its save is a first write (a row the target already holds under the name is refused 409, never overwritten). An unknown source answers 404, a taken name 409 `RESOURCE_CONFLICT`, a source holding a credential 409, a definition the engine refuses 400. The schema names the WHOLE BODY, envelope included (as the uninstall row's does): `data` is `{ flow, packageId, notice, noticeCode }`, `packageId` the package the copy landed in, the notice saying the copy is switched off and that references are not re-pointed, and `noticeCode` (`FLOW_CLONE_NOTICE_CODE`) naming that sentence so a console can translate it, `notice` staying the English fallback. ⛔ No ancestry on the definition or the response (ADR-0126 §9). ⚑ `manage_metadata` — the same `isFlowAuthoringWrite` door as `PUT /automation/:name` below, then the walled refusal (the gates the ensure door asks, so the in-process ensure creates nothing a caller could not create there); fail-closed, only `isSystem` bypassing, and the domain-wide anonymous floor answers an unidentified caller 401 first. ⛔ NOT the ADR-0126 §5 activation gate: a clone takes nothing away from any tenant. Conformance: `domains/automation-flow-clone-custom-package.test.ts` drives THIS handler over the real protocol, registry and store, parses each answer through `CloneFlowResponseSchema` and pins this row; the copy itself in `domains/automation-flow-clone.test.ts`; over HTTP in `qa/dogfood/test/automation-flow-clone-door.dogfood.test.ts`, the environment-scoped mount in `dispatcher-plugin.automation-clone-mount.integration.test.ts`" }, { route: 'POST /automation/:name/runs/:runId/resume', domain: '/automation', disposition: 'sdk', client: 'automation.resume', note: "generic, so the SUSPENDED NODE gates it: a pause whose descriptor declares resumeAuthority:'service' — today `approval` / `approval_revise` — answers 403 here and continues only through its owning service (ApprovalService.decide), which authorizes and records the decision first. A node type that declares NO resumeAuthority answers 403 too, fail-closed: this door is an opt-in a descriptor states with 'any'. Screen/wait pauses are unaffected because they declare it; this route is the screen-flow runner's door. The node gate asks WHAT the run is parked on, never WHO is resuming, so the route also gates the CALLER on the screen read's own question: the run's own trigger identity, or the `sys_automation_run` read grant as the operator override — one predicate, `isRunStarterOrRunStateReader` in `domains/automation.ts`. Refused 403 `PERMISSION_DENIED` before the engine is reached, so nothing is consumed. Pinned in `domains/automation-resume-caller-gate.test.ts`" }, { route: 'GET /automation/:name/runs/:runId/screen', domain: '/automation', disposition: 'sdk', client: 'automation.getScreen' }, @@ -668,9 +669,9 @@ export const ROUTE_LEDGER: readonly RouteLedgerEntry[] = [ { route: 'GET /automation/:name/runs', domain: '/automation', disposition: 'sdk', client: 'automation.listRuns' }, { route: 'GET /automation/:name', domain: '/automation', disposition: 'sdk', client: 'automation.get' }, { route: 'PUT /automation/:name', domain: '/automation', disposition: 'sdk', client: 'automation.update', - note: "authored metadata, so `manage_metadata` gates it — the same `isFlowAuthoringWrite` door as `POST /automation` above: fail-closed on an absent executionContext, an absent `systemPermissions` or an empty one, refusing 403 `PERMISSION_DENIED`, with only `isSystem` bypassing" }, + note: "authored metadata, so `manage_metadata` gates it: a flow definition lives on the metadata plane (ADR-0106), and this door asks the capability every other door onto that plane asks. Fail-closed by construction — an absent executionContext, an absent `systemPermissions` or an empty one all fall through to the refusal, 403 with code `PERMISSION_DENIED` (ADR-0112); only engine self-invocation (`isSystem`, never settable from the wire) bypasses. WHICH routes is one predicate, `isFlowAuthoringWrite` in `domains/automation.ts` — this row, DELETE `/:name` below and `POST /:name/toggle`, with the execution doors (trigger / execute / resume) deliberately outside it. Updates a flow that exists: a new name answers 422 `WRITABLE_PACKAGE_REQUIRED` naming `PUT /meta/flow/:name?package=` (#38174, the create door `POST /automation` retired). Pinned in `domains/automation-write-capability-gate.test.ts`" }, { route: 'DELETE /automation/:name', domain: '/automation', disposition: 'sdk', client: 'automation.delete', - note: "authored metadata, so `manage_metadata` gates it — the same `isFlowAuthoringWrite` door as `POST /automation` above, and the destructive member of the family: before the gate a tenant org owner WITHOUT the capability deregistered a registered flow, 200, and flow metadata is registered at ENVIRONMENT scope so the write crossed the tenant wall. Fail-closed on an absent executionContext, an absent `systemPermissions` or an empty one, refusing 403 `PERMISSION_DENIED`, with only `isSystem` bypassing" }, + note: "authored metadata, so `manage_metadata` gates it — the same `isFlowAuthoringWrite` door as `PUT /automation/:name` below, and the destructive member of the family: before the gate a tenant org owner WITHOUT the capability deregistered a registered flow, 200, and flow metadata is registered at ENVIRONMENT scope so the write crossed the tenant wall. Fail-closed on an absent executionContext, an absent `systemPermissions` or an empty one, refusing 403 `PERMISSION_DENIED`, with only `isSystem` bypassing" }, // [#22773] The inbound hook's hosted door (segment 2 of ruling A on #22757). { route: 'POST /automation/hooks/:flowName/:hookId', domain: '/automation', disposition: 'public', note: 'the inbound hook a third-party sender posts a signed event through to start an `api` flow (ADR-0041 Tier 1). Session-less by design: the HMAC signature over the raw body, under the hook\'s own secret, is the only credential, and the trigger-api slot\'s ITriggerApiService.handleInboundHook verifies it before anything is enqueued. With its qualified spelling (the row below), the one route under /automation the domain\'s anonymous floor admits: the ADR-0069 allow-list\'s parameterised row (core auth-gate.ts, exactly these four segments, POST only) is read by the floor, the ADR-0069 gate and the membership gate\'s skip through one reading, and the domain hands the route to `domains/automation-hooks.ts` on the statement after the floor, ahead of every other /automation gate. Forwarded with its body UNREAD, the two path parameters decoded, the slot resolved per request, and the member\'s Response returned as it is. An absent slot or member answers 501 NOT_IMPLEMENTED, never ROUTE_NOT_FOUND; a body consumed before it got here is a transport fault, answered 500 and logged. Every other method on the path stays an ordinary /automation request at the floor. This is the door for a kernel with no raw app; a self-hosted kernel serves the same path from the trigger\'s raw-app mount, which never passes through the dispatcher. NOT JS-SDK surface: a sender is a third-party service, not a client of this SDK. Pinned in `domains/automation-hooks.test.ts`' }, diff --git a/packages/spec/src/api/automation-api.zod.ts b/packages/spec/src/api/automation-api.zod.ts index 6b2bee309eb..8214cbdb0e2 100644 --- a/packages/spec/src/api/automation-api.zod.ts +++ b/packages/spec/src/api/automation-api.zod.ts @@ -115,35 +115,14 @@ export type GetFlowResponse = z.input; export type GetFlowResponseParsed = z.infer; // ========================================== -// 4. Create Flow (POST /api/v1/automation) +// 4. Create Flow — RETIRED (#38174) // ========================================== - -/** - * Request body for creating a new flow. - * - * @example POST /api/v1/automation - * { name: 'approval_flow', label: 'Approval Flow', type: 'autolaunched', ... } - */ -export const CreateFlowRequestSchema = lazySchema(() => FlowSchema); -export type CreateFlowRequest = z.input; -/** Post-parse shape of {@link CreateFlowRequest} — defaults applied, transforms run (ADR-0122). */ -export type CreateFlowRequestParsed = z.infer; - -/** - * Response after creating a flow. - * - * `data` is the CANONICALIZED flow the engine stored (#12206, Option A): - * `FlowSchema.parse` output with schema defaults materialized (`version`, - * `status`, `runAs`, per-edge `type`/`isDefault`) and `edge.condition` - * strings lowered to their `{dialect, source}` envelopes — the same shape - * `GET /api/v1/automation/:name` answers, never an echo of the request bytes. - */ -export const CreateFlowResponseSchema = lazySchema(() => BaseResponseSchema.extend({ - data: FlowSchema.describe('The created flow, canonicalized — the parsed shape the engine stored, identical to what a subsequent GET answers'), -})); -export type CreateFlowResponse = z.input; -/** Post-parse shape of {@link CreateFlowResponse} — defaults applied, transforms run (ADR-0122). */ -export type CreateFlowResponseParsed = z.infer; +// +// `POST /api/v1/automation` and its `CreateFlowRequestSchema` / +// `CreateFlowResponseSchema` are retired (ruling 7234518908, Q-g C): a new flow +// belongs to a package (ADR-0070 D1), and the kernel refuses a package-less +// create. A flow is created by `PUT /api/v1/meta/flow/:name?package=PKG`, +// which registers and arms it in the same boot. // ========================================== // 5. Update Flow (PUT /api/v1/automation/:name) @@ -171,9 +150,12 @@ export type UpdateFlowRequestParsed = z.infer; /** * Response after updating a flow. * - * `data` is the canonicalized flow the engine stored — see - * {@link CreateFlowResponseSchema}; the two write doors answer the same - * shape (#12206, Option A). Unlike the old echo, it always carries `name`. + * `data` is the CANONICALIZED flow the engine stored (#12206, Option A): + * `FlowSchema.parse` output with schema defaults materialized (`version`, + * `status`, `runAs`, per-edge `type`/`isDefault`) and `edge.condition` + * strings lowered to their `{dialect, source}` envelopes — the same shape + * `GET /api/v1/automation/:name` answers. Unlike the old echo, it always + * carries `name`. */ export const UpdateFlowResponseSchema = lazySchema(() => BaseResponseSchema.extend({ data: FlowSchema.describe('The updated flow, canonicalized — the parsed shape the engine stored, identical to what a subsequent GET answers'), @@ -1003,20 +985,15 @@ export type AutomationApiErrorCode = z.input; */ export const AutomationApiContracts = { // No `listFlows` entry: the list route is retired (#19543) — flows are read - // through `GET /api/v1/meta/flow`. `POST /api/v1/automation` (createFlow) - // below is unaffected and stays at the same path. + // through `GET /api/v1/meta/flow`. No `createFlow` entry either: the create + // door is retired (#38174) — a flow is created by + // `PUT /api/v1/meta/flow/:name?package=PKG`. getFlow: { method: 'GET' as const, path: '/api/v1/automation/:name', input: GetFlowRequestSchema, output: GetFlowResponseSchema, }, - createFlow: { - method: 'POST' as const, - path: '/api/v1/automation', - input: CreateFlowRequestSchema, - output: CreateFlowResponseSchema, - }, updateFlow: { method: 'PUT' as const, path: '/api/v1/automation/:name', diff --git a/packages/spec/src/migrations/entries/semantic/19.packageless-create-refused.ts b/packages/spec/src/migrations/entries/semantic/19.packageless-create-refused.ts new file mode 100644 index 00000000000..86ffa82b191 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.packageless-create-refused.ts @@ -0,0 +1,43 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// #38174 (ADR-0070 D1, ruling 7184753035 on the App Studio topic; Q-g C, +// ruling 7234518908) — the kernel refuses a package-less create, and the flow +// create door `POST /api/v1/automation` is retired. A runtime HTTP verdict: no +// authored source spells anything that moves, so there is no D2 conversion. +export const entry: SemanticMigration = { + id: 'packageless-create-refused', + surface: + 'PUT /api/v1/meta/{type}/{name} (publish and ?mode=draft), `os meta register`, the MCP and AI ' + + 'authoring doors and every other caller of the metadata save, naming no package, for a name no ' + + 'package holds and no stored item carries; and POST /api/v1/automation (`client.automation.create`, ' + + '`AutomationApiContracts.createFlow`, `CreateFlowRequestSchema`, `CreateFlowResponseSchema`). FROM ' + + '`200` storing a new package-less ("loose") row, and `POST /automation` creating a package-less ' + + 'flow, TO `422 WRITABLE_PACKAGE_REQUIRED` naming the writable packages, nothing stored; ' + + '`POST /automation` is unmounted and `PUT /api/v1/automation/{name}` of a new name answers `422 ' + + 'WRITABLE_PACKAGE_REQUIRED` naming the metadata door', + replacement: + 'name the package the new item belongs to: `?package=PKG` on the REST door, `--package PKG` on ' + + '`os meta register`, `{ packageId }` on `client.meta.saveItem`, or choose a package in Studio. ' + + 'Create a flow with `PUT /api/v1/meta/flow/{name}?package=PKG` (it registers and arms in the same ' + + 'boot); a flow triggered on an object another package ships needs a package that declares that ' + + 'package as a dependency. Existing package-less items save in place unchanged, and Studio\'s ' + + '"move into package" moves them', + reason: + 'ADR-0070 D1: a runtime create MUST resolve to a writable package, and the kernel write path is the ' + + 'enforcement point of last resort. The save path judged only a NAMED package, so every door that ' + + 'named none scattered new loose items with no container to version, publish, move or delete. ' + + 'Studio now asks for a package before a create and loose items have a move door; this closes the ' + + 'kernel so no new loose item is made. Four writers keep a named exemption (ADR-0084 amendment ' + + '2026-11-26-org): the kernel-item overlay, the external-datasource import, the binding-preserving ' + + 'migrations and platform registration. The automation create door held no package, so it is ' + + 'retired rather than given one (Q-g C).', + acceptanceCriteria: + 'A save naming no package of a new name answers 422 `WRITABLE_PACKAGE_REQUIRED` and stores nothing, ' + + 'on `/meta` publish and draft and on `os meta register` (non-zero exit, the server\'s sentence ' + + 'printed); `POST /api/v1/automation` is not served; `PUT /api/v1/automation/{new}` answers 422. ' + + 'Verify UNAFFECTED: an in-place save, draft save, delete and per-item publish of an existing ' + + 'package-less item; a package-less save of a name a package holds; `os migrate meta --stored`; the ' + + 'external-datasource import; platform registration at boot; `PUT /api/v1/automation/{existing}`.', +}; From b237a7ee51afd47e362ca984dd7cb30d64e85a51 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 13:44:10 +0000 Subject: [PATCH 03/23] test+fix: retire CreateFlow schemas from the contract, clone door's package-less sentence, refusal pins (#38174) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CasbvyQnz4st6s79P9 --- ...utomation-write-door-parsed-answer.test.ts | 48 +---- packages/client/src/client.test.ts | 36 +--- .../src/meta-delete-item-carriers.test.ts | 22 +- .../client/src/return-type-precision.test.ts | 9 +- .../src/domains/permission-set-clone.test.ts | 41 ++++ .../src/domains/permission-set-clone.ts | 37 ++++ .../meta-packageless-create-refused.test.ts | 195 ++++++++++++++++++ packages/spec/authorable-defaults/api.json | 3 - packages/spec/authorable-surface/api.json | 28 --- .../spec/dropped-refinements.baseline.json | 16 -- packages/spec/json-schema.manifest/api.json | 2 - .../spec/src/api/automation-api.zod.test.ts | 67 ++---- .../retired-defs/19.api__CreateFlowRequest.ts | 7 + .../19.api__CreateFlowResponse.ts | 7 + 14 files changed, 333 insertions(+), 185 deletions(-) create mode 100644 packages/runtime/src/meta-packageless-create-refused.test.ts create mode 100644 packages/spec/src/migrations/entries/retired-defs/19.api__CreateFlowRequest.ts create mode 100644 packages/spec/src/migrations/entries/retired-defs/19.api__CreateFlowResponse.ts diff --git a/packages/client/src/automation-write-door-parsed-answer.test.ts b/packages/client/src/automation-write-door-parsed-answer.test.ts index a503cc379a5..46697842a35 100644 --- a/packages/client/src/automation-write-door-parsed-answer.test.ts +++ b/packages/client/src/automation-write-door-parsed-answer.test.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * [#12206, Option A — ruled 2026-08-26] The two `/automation` definition-write - * doors answer the CANONICALIZED, PARSED flow the engine stored — the same + * [#12206, Option A — ruled 2026-08-26] The `/automation` definition-write + * door answers the CANONICALIZED, PARSED flow the engine stored — the same * shape `GET /automation/:name` answers — never an echo of the caller's own * pre-parse bytes. * @@ -24,12 +24,15 @@ * survey measured, zero consumers); * 2. write ≡ read — the write door's `data` deep-equals what the read door * then serves for the same resource, so write-then-read is stable; - * 3. the published `CreateFlowResponseSchema` / `UpdateFlowResponseSchema` - * parse the REAL wire body (inherited item ①: conformant, not + * 3. the published `UpdateFlowResponseSchema` parses the REAL wire body (inherited item ①: conformant, not * aspirational — the first response these schemas have ever seen); * 4. the PUT answer always carries `name`, which the old echo could omit * (the name rode the path, not the body). * + * [#38174, Q-g C] The create door `POST /automation` is retired (a flow is + * created on the metadata door, in a package), so its leg is gone and the + * flow the PUT leg updates is registered in the engine first. + * * Reverse verification, direction predicted BEFORE running: reverting the two * route exits in `packages/runtime/src/domains/automation.ts` back to * `deps.success(body)` / `deps.success(definition)` turns legs 1-4 RED (the @@ -41,7 +44,7 @@ import { describe, it, expect } from 'vitest'; import { AutomationEngine, InMemorySuspendedRunStore } from '@objectstack/service-automation'; import { HttpDispatcher } from '@objectstack/runtime'; -import { CreateFlowResponseSchema, UpdateFlowResponseSchema } from '@objectstack/spec/api'; +import { UpdateFlowResponseSchema } from '@objectstack/spec/api'; import type { FlowParsed } from '@objectstack/spec/automation'; import { ObjectStackClient } from './index'; @@ -114,39 +117,10 @@ function producerBackedClient() { return { client, engine, wire }; } -describe('#12206 — POST /automation answers the canonicalized parsed flow, not the echo', () => { - it('materializes schema defaults, lowers edge.condition, matches the read door, and conforms to CreateFlowResponseSchema', async () => { - const { client, wire } = producerBackedClient(); - - const answered: FlowParsed = await client.automation.create('wd_flow', RAW_DEFINITION); - - // ① NOT the echo: the caller never wrote any of these. - expect(answered.name).toBe('wd_flow'); - expect(answered.version).toBe(1); - expect(answered.status).toBe('draft'); - expect((answered as any).runAs).toBe('user'); - expect(answered.edges[0]).toMatchObject({ type: 'default', isDefault: false }); - // The one genuine type change the survey measured: string condition → - // lowered `{dialect, source}` envelope. - expect(answered.edges[0].condition).toEqual({ dialect: 'cel', source: RAW_CONDITION }); - - // ③ Inherited item ①: the published response schema parses the REAL - // wire envelope — conformant, no longer aspirational. - const envelope = CreateFlowResponseSchema.parse(wire.last); - expect(envelope.success).toBe(true); - expect(envelope.data.name).toBe('wd_flow'); - - // ② Write ≡ read: the write door answered exactly what the read door - // now serves for the same resource. - const read = await client.automation.get('wd_flow'); - expect(answered).toEqual(read); - }); -}); - describe('#12206 — PUT /automation/:name answers the canonicalized parsed flow, not the echo', () => { it('always carries name, matches the read door, and conforms to UpdateFlowResponseSchema', async () => { - const { client, wire } = producerBackedClient(); - await client.automation.create('wd_flow', RAW_DEFINITION); + const { client, engine, wire } = producerBackedClient(); + engine.registerFlow('wd_flow', { name: 'wd_flow', ...RAW_DEFINITION } as never); // The SDK sends `{ definition }`; the engine requires a COMPLETE // definition (inherited item ② — `UpdateFlowRequestSchema` no longer @@ -158,7 +132,7 @@ describe('#12206 — PUT /automation/:name answers the canonicalized parsed flow // omit `name` entirely; the parsed answer always carries it. expect(answered.name).toBe('wd_flow'); expect(answered.label).toBe('Write Door Flow v2'); - // ① NOT the echo — same materialized defaults as the POST door. + // ① NOT the echo: schema defaults the caller never wrote are materialized. expect(answered.version).toBe(1); expect(answered.edges[0].condition).toEqual({ dialect: 'cel', source: RAW_CONDITION }); diff --git a/packages/client/src/client.test.ts b/packages/client/src/client.test.ts index 270c290f0bb..79f5443c8b3 100644 --- a/packages/client/src/client.test.ts +++ b/packages/client/src/client.test.ts @@ -1368,40 +1368,16 @@ describe('ObjectStackClient.automation', () => { expect(result.name).toBe('my_flow'); }); - // [#12206, inherited item ③] These two bodies used to be `{ label }` + // [#12206, inherited item ③] These bodies used to be `{ label }` // fragments — 400 against a real server (`registerFlow` runs // `FlowSchema.parse`), passing only because `fetch` is mocked. They are // now REGISTRABLE, and each test pins that with a real parse of the exact // wire body the SDK sends, so the fixture cannot silently rot again. - it('should create a flow (registrable body)', async () => { - const definition = { - label: 'New Flow', - type: 'autolaunched', - nodes: [ - { id: 'start', type: 'start', label: 'Start' }, - { id: 'end', type: 'end', label: 'End' }, - ], - edges: [{ id: 'e1', source: 'start', target: 'end' }], - }; - // `create` sends `{ name, ...definition }` — that merged object is - // what the engine parses; prove it is registrable. - expect(() => FlowSchema.parse({ name: 'new_flow', ...definition })).not.toThrow(); - - const { client, fetchMock } = createMockClient({ - success: true, - data: FlowSchema.parse({ name: 'new_flow', ...definition }), - }); - - const result = await client.automation.create('new_flow', definition); - expect(fetchMock).toHaveBeenCalledWith( - 'http://localhost:3000/api/v1/automation', - expect.objectContaining({ method: 'POST' }), - ); - // The door answers the canonicalized parsed flow (#12206, Option A): - // schema defaults the caller never wrote are materialized. - expect(result.name).toBe('new_flow'); - expect(result.version).toBe(1); - expect(result.status).toBe('draft'); + // [#38174, Q-g C] The create door `POST /api/v1/automation` is retired: a + // flow is created with `meta.saveItem('flow', name, def, { packageId })`. + it('has no automation.create (the retired create door)', () => { + const { client } = createMockClient({ success: true, data: {} }); + expect((client.automation as Record).create).toBeUndefined(); }); it('should update a flow (registrable body)', async () => { diff --git a/packages/client/src/meta-delete-item-carriers.test.ts b/packages/client/src/meta-delete-item-carriers.test.ts index af8dd02dcf4..00de92b65d4 100644 --- a/packages/client/src/meta-delete-item-carriers.test.ts +++ b/packages/client/src/meta-delete-item-carriers.test.ts @@ -568,13 +568,13 @@ describe('[#12181] the real reset door: a concurrent edit is destroyed unpinned, const { engine, client, deleteRequests } = await bootDoor(); // Author A writes, and reads back the OCC token the docstring names. - const first: any = await client.meta.saveItem('view', 'race_probe', VIEW('race_probe', 'A')); + const first: any = await client.meta.saveItem('view', 'race_probe', VIEW('race_probe', 'A'), { packageId: PKG }); expect(first.success).toBe(true); const staleToken = first.version; expect(typeof staleToken).toBe('string'); // Author B edits the same item. A's token is now stale. - const second: any = await client.meta.saveItem('view', 'race_probe', VIEW('race_probe', 'B')); + const second: any = await client.meta.saveItem('view', 'race_probe', VIEW('race_probe', 'B'), { packageId: PKG }); expect(second.version).not.toBe(staleToken); expect(await overlayRows(engine, 'race_probe')).toHaveLength(1); @@ -612,9 +612,9 @@ describe('[#12181] the real reset door: a concurrent edit is destroyed unpinned, it('PINNED: the same stale reset is REFUSED 409 metadata_conflict, and the other author\'s row survives', async () => { const { engine, client, deleteRequests } = await bootDoor(); - const first: any = await client.meta.saveItem('view', 'race_probe', VIEW('race_probe', 'A')); + const first: any = await client.meta.saveItem('view', 'race_probe', VIEW('race_probe', 'A'), { packageId: PKG }); const staleToken = first.version; - const second: any = await client.meta.saveItem('view', 'race_probe', VIEW('race_probe', 'B')); + const second: any = await client.meta.saveItem('view', 'race_probe', VIEW('race_probe', 'B'), { packageId: PKG }); expect(second.version).not.toBe(staleToken); // Do literally what the docstring prescribes — impossible before this @@ -644,7 +644,7 @@ describe('[#12181] the real reset door: a concurrent edit is destroyed unpinned, // The other half of the pin — it refuses a stale write, not every // write. Without this, "always 409" would pass the case above. const { engine, client } = await bootDoor(); - const saved: any = await client.meta.saveItem('view', 'fresh_probe', VIEW('fresh_probe', 'A')); + const saved: any = await client.meta.saveItem('view', 'fresh_probe', VIEW('fresh_probe', 'A'), { packageId: PKG }); const reset: DeleteMetaItemResponse = await client.meta.deleteItem('view', 'fresh_probe', { ifMatch: saved.version }); expect(reset.success).toBe(true); expect(await overlayRows(engine, 'fresh_probe')).toHaveLength(0); @@ -656,9 +656,9 @@ describe('[#12181] the real reset door: a concurrent edit is destroyed unpinned, const { engine, client, deleteRequests } = await bootDoor(); const scoped = client.environment('env-123').meta; - const first: any = await scoped.saveItem('view', 'scoped_race', VIEW('scoped_race', 'A')); + const first: any = await scoped.saveItem('view', 'scoped_race', VIEW('scoped_race', 'A'), { packageId: PKG }); const staleToken = first.version; - await scoped.saveItem('view', 'scoped_race', VIEW('scoped_race', 'B')); + await scoped.saveItem('view', 'scoped_race', VIEW('scoped_race', 'B'), { packageId: PKG }); const err: any = await scoped .deleteItem('view', 'scoped_race', { ifMatch: staleToken }) @@ -684,8 +684,8 @@ describe('[#12181] the real reset door: `?state=draft` discards ONLY the pending const { engine, client, deleteRequests } = await bootDoor(); // A published overlay, then a pending draft on top of it. - await client.meta.saveItem('view', 'draft_probe', VIEW('draft_probe', 'published')); - await client.meta.saveItem('view', 'draft_probe', VIEW('draft_probe', 'pending'), { mode: 'draft' }); + await client.meta.saveItem('view', 'draft_probe', VIEW('draft_probe', 'published'), { packageId: PKG }); + await client.meta.saveItem('view', 'draft_probe', VIEW('draft_probe', 'pending'), { mode: 'draft', packageId: PKG }); const before = await overlayRows(engine, 'draft_probe'); // Two rows: the active overlay and the draft. expect(before.length).toBe(2); @@ -726,8 +726,8 @@ describe('[#12181] the real reset door: `?state=draft` discards ONLY the pending const { engine, client, deleteRequests } = await bootDoor(); const scoped = client.environment('env-123').meta; - await scoped.saveItem('view', 'scoped_draft', VIEW('scoped_draft', 'published')); - await scoped.saveItem('view', 'scoped_draft', VIEW('scoped_draft', 'pending'), { mode: 'draft' }); + await scoped.saveItem('view', 'scoped_draft', VIEW('scoped_draft', 'published'), { packageId: PKG }); + await scoped.saveItem('view', 'scoped_draft', VIEW('scoped_draft', 'pending'), { mode: 'draft', packageId: PKG }); const discarded: DeleteMetaItemResponse = await scoped.deleteItem('view', 'scoped_draft', { state: 'draft' }); expect(discarded.success).toBe(true); diff --git a/packages/client/src/return-type-precision.test.ts b/packages/client/src/return-type-precision.test.ts index 661e6b11416..775ce4c5ddb 100644 --- a/packages/client/src/return-type-precision.test.ts +++ b/packages/client/src/return-type-precision.test.ts @@ -180,12 +180,9 @@ export async function returnTypePrecisionPins(): Promise { expectTypeOf(await client.automation.execute('flow_a')).toEqualTypeOf(); expectTypeOf(await client.automation.getRun('flow_a', 'run_1')).toEqualTypeOf(); - // [#12206, Option A] The two write doors answer the canonicalized parsed - // flow — the single true return type the read door already binds. These - // pins retire the last two DELIBERATE `Promise` declarations of the - // automation family (`exported-any-returns.json` entries deleted in the - // same change). - expectTypeOf(await client.automation.create('flow_a', {})).toEqualTypeOf(); + // [#12206, Option A] The write door answers the canonicalized parsed + // flow — the single true return type the read door already binds. (Its + // create sibling was retired by #38174, Q-g C.) expectTypeOf(await client.automation.update('flow_a', {})).toEqualTypeOf(); // Explicit type arguments still work for a LEGITIMATE narrowing — the diff --git a/packages/runtime/src/domains/permission-set-clone.test.ts b/packages/runtime/src/domains/permission-set-clone.test.ts index 7f8692b4761..d9a50c756b2 100644 --- a/packages/runtime/src/domains/permission-set-clone.test.ts +++ b/packages/runtime/src/domains/permission-set-clone.test.ts @@ -796,3 +796,44 @@ describe('[#37811] the clone door\'s 501s follow the request\'s language', () => } }); }); + +describe('[#38174] a copy with no package to land in is refused by the kernel, in this door\'s words', () => { + // The kernel's package-less create refusal (ADR-0070 D1), as + // `packagelessCreateError` in `@objectstack/metadata-protocol` throws it: + // its sentence prescribes the metadata door's `?package=`, which this door + // does not read. + const kernelRefusal = (writablePackages?: string[]) => Object.assign( + new Error('Cannot create permission/env_reader_copy with no package: … (on the REST door add ?package=PKG …)'), + { code: 'WRITABLE_PACKAGE_REQUIRED', status: 422, docs: 'docs/adr/0070-package-first-authoring.md', ...(writablePackages ? { writablePackages } : {}) }, + ); + + it('a loose source with no target: 422 WRITABLE_PACKAGE_REQUIRED naming the body\'s `package` and the writable packages', async () => { + const h = boot({ saveError: kernelRefusal(['crm.custom', 'sales']) }); + const res = await clone(h, HOLDER(), ENV_SET.name, { name: 'env_reader_copy', label: 'Env Reader Copy' }); + expect(statusOf(res)).toBe(422); + expect(codeOf(res)).toBe('WRITABLE_PACKAGE_REQUIRED'); + const message = String((res as any).response.body.error.message); + expect(message).toContain(`Cannot clone permission set '${ENV_SET.name}' as 'env_reader_copy' with no package`); + expect(message).toContain('Name one with `package` in the request body'); + expect(message).toContain('Writable packages here: crm.custom, sales.'); + expect(message).not.toContain('?package='); + }); + + it('a kernel source with no pair answers the same', async () => { + const h = boot({ saveError: kernelRefusal([]) }); + const res = await clone(h, HOLDER(), KERNEL_SET.name, { name: 'my_member', label: 'My Member' }); + expect(statusOf(res)).toBe(422); + expect(codeOf(res)).toBe('WRITABLE_PACKAGE_REQUIRED'); + expect(String((res as any).response.body.error.message)).toContain('No package in this environment is writable'); + }); + + it('CONTROL — a D1 read-only-base refusal (it names a package) keeps the kernel\'s own sentence', async () => { + const named = Object.assign(new Error('Cannot save permission into read-only package \'crm\'.'), { + code: 'WRITABLE_PACKAGE_REQUIRED', status: 422, packageId: 'crm', + }); + const h = boot({ saveError: named }); + const res = await clone(h, HOLDER(), ENV_SET.name, { name: 'env_reader_copy', label: 'Env Reader Copy' }); + expect(statusOf(res)).toBe(422); + expect(String((res as any).response.body.error.message)).toContain('read-only package'); + }); +}); diff --git a/packages/runtime/src/domains/permission-set-clone.ts b/packages/runtime/src/domains/permission-set-clone.ts index bb006fc1547..13cacf8f95b 100644 --- a/packages/runtime/src/domains/permission-set-clone.ts +++ b/packages/runtime/src/domains/permission-set-clone.ts @@ -369,6 +369,32 @@ export async function resolveDefaultCloneLanding( return { packageId: pair.packageId, created: pair.created }; } +/** [#38174] The kernel's package-less create refusal (ADR-0070 D1's code, with no named package). */ +function isPackagelessCreateRefusal(err: unknown): err is { writablePackages?: readonly string[] } { + const e = err as { code?: unknown; status?: unknown; packageId?: unknown } | null | undefined; + return e?.code === 'WRITABLE_PACKAGE_REQUIRED' && e.status === 422 && e.packageId === undefined; +} + +/** How many writable packages the clone refusal names before it counts the rest. */ +const CLONE_PACKAGES_SHOWN = 5; + +/** + * [#38174] The clone door's sentence for a copy the kernel refused to create + * package-less: the prescription in this door's input (`package` in the + * body), then the writable packages the kernel listed. + */ +function packagelessCloneMessage(sourceName: string, targetName: string, writable: readonly string[] | undefined): string { + const listed = writable === undefined + ? '' + : writable.length === 0 + ? ' No package in this environment is writable: create one first.' + : ` Writable packages here: ${writable.slice(0, CLONE_PACKAGES_SHOWN).join(', ')}` + + `${writable.length > CLONE_PACKAGES_SHOWN ? `, and ${writable.length - CLONE_PACKAGES_SHOWN} more` : ''}.`; + return `Cannot clone permission set '${sourceName}' as '${targetName}' with no package: the copy is a new item, ` + + `and a new item is saved into a writable package (ADR-0070), but '${sourceName}' has no package the copy ` + + `could land in. Name one with \`package\` in the request body. Nothing was saved.${listed}`; +} + function nameTakenMessage(name: string): string { return ( `Permission set '${name}' already exists — a clone must take a NEW machine name. ` @@ -654,6 +680,17 @@ export async function handlePermissionSetCloneWrite( status: PERMISSION_SET_CLONE_NAME_TAKEN_STATUS, }); } + // [#38174, ADR-0070 D1] The kernel refused a package-less create: + // the landing found no package (a loose source, or a kernel source + // with no paired customization package). The copy is a new item, + // so the refusal stands; its sentence names the metadata door's + // `?package=`, which this door does not read, so it is answered in + // this door's own words: its body's `package`. + if (isPackagelessCreateRefusal(err)) { + throw Object.assign(new Error(packagelessCloneMessage(source.name, target.name, err.writablePackages)), { + code: 'WRITABLE_PACKAGE_REQUIRED', status: 422, docs: 'docs/adr/0070-package-first-authoring.md', + }); + } throw err; } diff --git a/packages/runtime/src/meta-packageless-create-refused.test.ts b/packages/runtime/src/meta-packageless-create-refused.test.ts new file mode 100644 index 00000000000..9c47fb917d6 --- /dev/null +++ b/packages/runtime/src/meta-packageless-create-refused.test.ts @@ -0,0 +1,195 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38174, ADR-0070 D1, ruling 7184753035] The kernel refuses a package-less + * CREATE, on every door that reaches the metadata save. + * + * A save naming no package, of a name no package holds and no stored row + * carries, answered `200` and stored a new loose row — an item with no + * container to version, publish, move or delete. It now answers `422 + * WRITABLE_PACKAGE_REQUIRED` naming the writable packages, and stores nothing. + * + * The rig is real end to end below the identity step: better-sqlite3 + * `:memory:`, the real `sys_metadata*` objects, a real + * `ObjectStackProtocolImplementation`, and the real `HttpDispatcher` reached + * the way `@objectstack/hono`'s catch-all reaches it. Every verdict is read + * from the store, not from the door's word for it. + * + * The controls pin what the close does NOT reach: the same save naming a + * package, an in-place save of a loose row that already exists, a package-less + * save of a name a package holds, and the server-stated exemptions (a + * binding-preserving migration's `source`, the external-datasource import's + * `writeFace`). + * + * Ablation: dropping the `packagelessCreateRefusal` call from + * `saveMetaItemUnaudited` (`protocol-save.ts`) turns every "refused" case RED + * (the save answers 200 and a loose row is stored) and leaves every control + * GREEN. + */ + +// Pays the lint root's first load at collection, never inside a clocked case. +import './lint-root-preload.testkit.js'; +import { describe, it, expect, afterEach } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject, hashSpec } from '@objectstack/metadata-core'; +import { HttpDispatcher } from './http-dispatcher.js'; + +const PREFIX = '/api/v1'; +const META = `${PREFIX}/meta`; +/** The package the fixture's object ships in (`registry.registerObject` needs one). */ +const BASE_PKG = 'objectstack-test'; +/** A writable authored package, depending on the base so a view over `task` is in its closure. */ +const PKG = 'com.qa.alpha'; +const AUTHOR = { userId: 'u_author', isSystem: false, systemPermissions: ['manage_metadata'] }; + +const TASK = { + name: 'task', + label: 'Task', + fields: { + id: { name: 'id', type: 'text' as const, primaryKey: true, label: 'ID' }, + name: { name: 'name', type: 'text' as const, label: 'Name' }, + }, +}; + +const viewBody = (name: string, label: string) => ({ + name, label, object: 'task', viewKind: 'list', columns: [{ field: 'name', label: 'Name' }], +}); + +const objectBody = (name: string) => ({ + name, label: 'Gizmo', sharingModel: 'private', fields: { title: { name: 'title', type: 'text', label: 'Title' } }, +}); + +const flowBody = (name: string) => ({ + name, label: 'Probe flow', type: 'autolaunched', + nodes: [{ id: 'start', type: 'start', label: 'Start' }, { id: 'end', type: 'end', label: 'End' }], + edges: [{ id: 'e1', source: 'start', target: 'end' }], +}); + +const datasetBody = (name: string) => ({ name, label: 'Probe dataset', object: 'task', dimensions: [], measures: [] }); + +const clone = (v: T): T => JSON.parse(JSON.stringify(v)); + +const liveEngines: ObjectQL[] = []; +afterEach(async () => { + while (liveEngines.length) { + try { await liveEngines.pop()?.destroy(); } catch { /* noop */ } + } +}); + +async function boot() { + const engine = new ObjectQL(); + liveEngines.push(engine); + engine.registerDriver(new SqlDriver({ + client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true, + }), true); + await engine.init(); + engine.registry.registerObject(TASK as any, BASE_PKG); + engine.registry.registerObject(SysMetadataObject as any, BASE_PKG); + engine.registry.registerObject(SysMetadataHistoryObject as any, BASE_PKG); + engine.registry.registerObject(SysMetadataAuditObject as any, BASE_PKG); + engine.registry.installPackage( + { id: PKG, name: PKG, version: '1.0.0', dependencies: { [BASE_PKG]: '*' } } as any, + 'authored', + ); + await engine.syncSchemas(); + const protocol: any = new ObjectStackProtocolImplementation(engine as any); + + const get = (n: string) => (n === 'protocol' ? protocol : null); + const dispatcher = new HttpDispatcher({ context: { getService: get }, getService: get, getServiceAsync: async (n: string) => get(n) } as any); + (dispatcher as any).timedResolveExecutionContext = async () => clone(AUTHOR); + + /** `PUT /api/v1/meta/:type/:name` through the catch-all's call. */ + const put = async (type: string, name: string, body: unknown, query: Record = {}) => { + const res = await dispatcher.dispatch('PUT', `/meta/${type}/${name}`, clone(body), query, { + request: new Request(`http://localhost${META}/${type}/${name}`, { method: 'PUT' }), + } as any, PREFIX); + const envelope: any = res.response?.body; + return { + status: res.response?.status ?? 0, + code: envelope?.error?.code as string | undefined, + message: envelope?.error?.message as string | undefined, + }; + }; + + /** Every stored row of `type/name`, any state, any package. */ + const rows = async (type: string, name: string) => + ((await engine.find('sys_metadata', { where: { type, name } })) ?? []) as Array<{ package_id: string | null; state: string }>; + + /** A package-less row as it exists at rest, written straight into the store (never through the save door). */ + const seedLooseRow = async (type: string, name: string, body: Record) => { + const now = new Date().toISOString(); + await engine.insert('sys_metadata', { + id: `seed_loose_${type}_${name}`, type, name, package_id: null, state: 'active', + metadata: JSON.stringify(body), checksum: hashSpec(body, type), version: 1, created_at: now, updated_at: now, + }, { context: { isSystem: true } } as any); + }; + + return { protocol, put, rows, seedLooseRow }; +} + +describe('[#38174] PUT /meta/:type/:name naming no package, of a new name, is refused', () => { + it.each([ + ['view', 'probe_grid', viewBody('probe_grid', 'A')], + ['object', 'gizmo', objectBody('gizmo')], + ['flow', 'probe_flow', flowBody('probe_flow')], + ['dataset', 'probe_ds', datasetBody('probe_ds')], + ] as const)('publish: %s → 422 WRITABLE_PACKAGE_REQUIRED naming the writable package, nothing stored', async (type, name, body) => { + const { put, rows } = await boot(); + const answer = await put(type, name, body); + expect(answer.code, JSON.stringify(answer)).toBe('WRITABLE_PACKAGE_REQUIRED'); + expect(answer.status).toBe(422); + expect(answer.code).toBe('WRITABLE_PACKAGE_REQUIRED'); + expect(answer.message).toContain(`Cannot create ${type}/${name} with no package`); + expect(answer.message).toContain(`Writable packages here: ${PKG}`); + expect(await rows(type, name)).toEqual([]); + }); + + it('draft: ?mode=draft of a new name is refused the same way, and no draft row is stored', async () => { + const { put, rows } = await boot(); + const answer = await put('view', 'probe_grid', viewBody('probe_grid', 'A'), { mode: 'draft' }); + expect(answer.status, JSON.stringify(answer)).toBe(422); + expect(answer.code).toBe('WRITABLE_PACKAGE_REQUIRED'); + expect(await rows('view', 'probe_grid')).toEqual([]); + }); + + it('the kernel answers the same to a direct saveMetaItem caller (the MCP, AI and CLI doors reach this)', async () => { + const { protocol, rows } = await boot(); + await expect(protocol.saveMetaItem({ type: 'view', name: 'probe_grid', item: viewBody('probe_grid', 'A') })) + .rejects.toMatchObject({ code: 'WRITABLE_PACKAGE_REQUIRED', status: 422, writablePackages: [PKG] }); + expect(await rows('view', 'probe_grid')).toEqual([]); + }); +}); + +describe('[#38174] controls — what the close does not reach', () => { + it('the same create naming a writable package saves into it', async () => { + const { put, rows } = await boot(); + const answer = await put('view', 'probe_grid', viewBody('probe_grid', 'A'), { package: PKG }); + expect(answer.status, JSON.stringify(answer)).toBe(200); + expect((await rows('view', 'probe_grid')).map((r) => r.package_id)).toEqual([PKG]); + }); + + it('an in-place save of a loose row that already exists stays open', async () => { + const { put, rows, seedLooseRow } = await boot(); + await seedLooseRow('view', 'legacy_grid', viewBody('legacy_grid', 'old')); + const answer = await put('view', 'legacy_grid', viewBody('legacy_grid', 'new')); + expect(answer.status, JSON.stringify(answer)).toBe(200); + const stored = await rows('view', 'legacy_grid'); + expect(stored.map((r) => r.package_id)).toEqual([null]); + }); + + it('a package-less save of a name a package holds is not a create', async () => { + const { put } = await boot(); + expect((await put('view', 'held_grid', viewBody('held_grid', 'A'), { package: PKG })).status).toBe(200); + const answer = await put('view', 'held_grid', viewBody('held_grid', 'B')); + expect(answer.code).not.toBe('WRITABLE_PACKAGE_REQUIRED'); + expect(answer.status, JSON.stringify(answer)).toBe(200); + }); + + it('a binding-preserving migration (server-stated `source`) is exempt', async () => { + const { protocol, rows } = await boot(); + await protocol.saveMetaItem({ type: 'view', name: 'migrated_grid', item: viewBody('migrated_grid', 'A'), source: 'migrate-stored' }); + expect((await rows('view', 'migrated_grid')).map((r) => r.package_id)).toEqual([null]); + }); +}); diff --git a/packages/spec/authorable-defaults/api.json b/packages/spec/authorable-defaults/api.json index 6e490e29e20..1a91bbdea73 100644 --- a/packages/spec/authorable-defaults/api.json +++ b/packages/spec/authorable-defaults/api.json @@ -30,9 +30,6 @@ "api/BatchOptions:returnRecords = false", "api/BulkRequest:allOrNone = true", "api/CacheInvalidationRequest:cascade = false", - "api/CreateFlowRequest:runAs = \"user\"", - "api/CreateFlowRequest:status = \"draft\"", - "api/CreateFlowRequest:version = 1", "api/CreateImportJobRequest:createMissingOptions = false", "api/CreateImportJobRequest:dryRun = false", "api/CreateImportJobRequest:runAutomations = true", diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index e2608e515c1..0f134fdf555 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -452,34 +452,6 @@ "api/CreateDataResponse:record", "api/CreateDataResponse:warnings", "api/CreateDataResponse:withheldMentions", - "api/CreateFlowRequest:_lock", - "api/CreateFlowRequest:_lockDocsUrl", - "api/CreateFlowRequest:_lockReason", - "api/CreateFlowRequest:_lockSource", - "api/CreateFlowRequest:_packageId", - "api/CreateFlowRequest:_packageVersion", - "api/CreateFlowRequest:_provenance", - "api/CreateFlowRequest:defaultActive", - "api/CreateFlowRequest:description", - "api/CreateFlowRequest:edges", - "api/CreateFlowRequest:errorHandling", - "api/CreateFlowRequest:errorMessage", - "api/CreateFlowRequest:label", - "api/CreateFlowRequest:name", - "api/CreateFlowRequest:nodes", - "api/CreateFlowRequest:overrides", - "api/CreateFlowRequest:protection", - "api/CreateFlowRequest:requiredPermissions", - "api/CreateFlowRequest:runAs", - "api/CreateFlowRequest:status", - "api/CreateFlowRequest:successMessage", - "api/CreateFlowRequest:type", - "api/CreateFlowRequest:variables", - "api/CreateFlowRequest:version", - "api/CreateFlowResponse:data", - "api/CreateFlowResponse:error", - "api/CreateFlowResponse:meta", - "api/CreateFlowResponse:success", "api/CreateImportJobRequest:createMissingOptions", "api/CreateImportJobRequest:csv", "api/CreateImportJobRequest:dryRun", diff --git a/packages/spec/dropped-refinements.baseline.json b/packages/spec/dropped-refinements.baseline.json index 384b2d472a0..193f4e778bb 100644 --- a/packages/spec/dropped-refinements.baseline.json +++ b/packages/spec/dropped-refinements.baseline.json @@ -278,22 +278,6 @@ "question.source.filter.lazy" ] }, - "api/CreateFlowRequest": { - "sites": [ - "", - "errorHandling", - "nodes.element.in.waitEventConfig", - "variables.element" - ] - }, - "api/CreateFlowResponse": { - "sites": [ - "data", - "data.errorHandling", - "data.nodes.element.in.waitEventConfig", - "data.variables.element" - ] - }, "api/CreateImportJobRequest": { "sites": [ "" diff --git a/packages/spec/json-schema.manifest/api.json b/packages/spec/json-schema.manifest/api.json index fc5c3166a1d..bb2fb614c5f 100644 --- a/packages/spec/json-schema.manifest/api.json +++ b/packages/spec/json-schema.manifest/api.json @@ -107,8 +107,6 @@ "api/CreateAiSavedQuestionResponse", "api/CreateDataRequest", "api/CreateDataResponse", - "api/CreateFlowRequest", - "api/CreateFlowResponse", "api/CreateImportJobRequest", "api/CreateImportJobResponse", "api/CreateManyDataRequest", diff --git a/packages/spec/src/api/automation-api.zod.test.ts b/packages/spec/src/api/automation-api.zod.test.ts index e7cb5e9ea48..2293dcec730 100644 --- a/packages/spec/src/api/automation-api.zod.test.ts +++ b/packages/spec/src/api/automation-api.zod.test.ts @@ -4,8 +4,6 @@ import { AutomationRunPathParamsSchema, GetFlowRequestSchema, GetFlowResponseSchema, - CreateFlowRequestSchema, - CreateFlowResponseSchema, UpdateFlowRequestSchema, UpdateFlowResponseSchema, DeleteFlowRequestSchema, @@ -119,7 +117,7 @@ describe('the GET /api/v1/automation flow-list door is retired', () => { it('the module still exports its surviving request schemas (the absence above is not a dead import)', () => { expect(Object.keys(AutomationApiModule)).toEqual( - expect.arrayContaining(['GetFlowRequestSchema', 'CreateFlowRequestSchema', 'ListRunsRequestSchema']), + expect.arrayContaining(['GetFlowRequestSchema', 'UpdateFlowRequestSchema', 'ListRunsRequestSchema']), ); }); }); @@ -159,50 +157,18 @@ describe('GetFlowResponseSchema', () => { // Create Flow // ========================================== -describe('CreateFlowRequestSchema', () => { - it('should accept a valid flow definition', () => { - const result = CreateFlowRequestSchema.parse({ - name: 'new_flow', - label: 'New Flow', - type: 'api', - nodes: [ - { id: 'start', type: 'start', label: 'Start' }, - { id: 'end', type: 'end', label: 'End' }, - ], - edges: [{ id: 'e1', source: 'start', target: 'end' }], - }); - expect(result.name).toBe('new_flow'); - expect(result.status).toBe('draft'); // default +// #38174 (Q-g C, ruling 7234518908): the create door `POST /api/v1/automation` +// is retired with its two schemas; a flow is created on the metadata door +// naming its package. The absence is pinned so the door cannot drift back. +describe('the retired flow create door', () => { + it.each(['CreateFlowRequestSchema', 'CreateFlowResponseSchema'])('%s is no longer exported', (name) => { + expect(Object.keys(AutomationApiModule)).not.toContain(name); }); - it('should reject invalid flow name', () => { - expect(() => CreateFlowRequestSchema.parse({ - name: 'InvalidName', - label: 'Bad', - type: 'api', - nodes: [], - edges: [], - })).toThrow(); - }); -}); - -describe('CreateFlowResponseSchema', () => { - it('should accept a response wrapping a FlowSchema', () => { - const result = CreateFlowResponseSchema.parse({ - success: true, - data: { - name: 'new_flow', - label: 'New Flow', - type: 'api', - nodes: [ - { id: 'start', type: 'start', label: 'Start' }, - { id: 'end', type: 'end', label: 'End' }, - ], - edges: [{ id: 'e1', source: 'start', target: 'end' }], - }, - }); - expect(result.success).toBe(true); - expect(result.data.name).toBe('new_flow'); + it('declares no createFlow contract and no POST at the bare /api/v1/automation path', () => { + expect(Object.keys(AutomationApiContracts)).not.toContain('createFlow'); + const routes = Object.values(AutomationApiContracts).map((c) => `${c.method} ${c.path}`); + expect(routes).not.toContain('POST /api/v1/automation'); }); }); @@ -962,14 +928,16 @@ describe('AutomationApiErrorCode', () => { // ========================================== describe('AutomationApiContracts', () => { - it('should define all 10 contract endpoints', () => { + it('should define all 9 contract endpoints', () => { // 9 -> 8: `listFlows` (`GET /api/v1/automation`) retired with its route // (#19543) — flows are listed through `GET /api/v1/meta/flow`. // 8 -> 9: `cloneFlow` (`POST /api/v1/automation/:name/clone`) gained its // request/response schemas (#28149, ADR-0146 D4 "new similar"). // 9 -> 10: `listRecordUpdateStarts` (`POST /api/v1/automation/_record-starts`), // the record-update preview the stage-change confirms read (#35928). - expect(Object.keys(AutomationApiContracts)).toHaveLength(10); + // 10 -> 9: `createFlow` (`POST /api/v1/automation`) retired with its route + // (#38174, Q-g C) — a flow is created on the metadata door, in a package. + expect(Object.keys(AutomationApiContracts)).toHaveLength(9); expect(AutomationApiContracts).toHaveProperty('cloneFlow'); expect(AutomationApiContracts).toHaveProperty('listRecordUpdateStarts'); }); @@ -978,14 +946,10 @@ describe('AutomationApiContracts', () => { expect(Object.keys(AutomationApiContracts)).not.toContain('listFlows'); const routes = Object.values(AutomationApiContracts).map((c) => `${c.method} ${c.path}`); expect(routes).not.toContain('GET /api/v1/automation'); - // …while the create door at the same path survives, so the absence is the - // one verb and not the whole path. - expect(routes).toContain('POST /api/v1/automation'); }); it('should define correct HTTP methods', () => { expect(AutomationApiContracts.getFlow.method).toBe('GET'); - expect(AutomationApiContracts.createFlow.method).toBe('POST'); expect(AutomationApiContracts.updateFlow.method).toBe('PUT'); expect(AutomationApiContracts.deleteFlow.method).toBe('DELETE'); expect(AutomationApiContracts.triggerFlow.method).toBe('POST'); @@ -996,7 +960,6 @@ describe('AutomationApiContracts', () => { it('should define correct paths', () => { expect(AutomationApiContracts.getFlow.path).toBe('/api/v1/automation/:name'); - expect(AutomationApiContracts.createFlow.path).toBe('/api/v1/automation'); expect(AutomationApiContracts.updateFlow.path).toBe('/api/v1/automation/:name'); expect(AutomationApiContracts.deleteFlow.path).toBe('/api/v1/automation/:name'); expect(AutomationApiContracts.triggerFlow.path).toBe('/api/v1/automation/:name/trigger'); diff --git a/packages/spec/src/migrations/entries/retired-defs/19.api__CreateFlowRequest.ts b/packages/spec/src/migrations/entries/retired-defs/19.api__CreateFlowRequest.ts new file mode 100644 index 00000000000..2e92d64d73b --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-defs/19.api__CreateFlowRequest.ts @@ -0,0 +1,7 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// #38174 (Q-g C, ruling 7234518908) — `api/CreateFlowRequest` leaves with the flow +// create door `POST /api/v1/automation` it described: a flow is created on +// the metadata door, in a package (ADR-0070 D1). A wire shape, never authored +// metadata, so nothing stored carries it. D3: `packageless-create-refused`. +export const entry = 'api/CreateFlowRequest'; diff --git a/packages/spec/src/migrations/entries/retired-defs/19.api__CreateFlowResponse.ts b/packages/spec/src/migrations/entries/retired-defs/19.api__CreateFlowResponse.ts new file mode 100644 index 00000000000..3d5e856fb12 --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-defs/19.api__CreateFlowResponse.ts @@ -0,0 +1,7 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// #38174 (Q-g C, ruling 7234518908) — `api/CreateFlowResponse` leaves with the flow +// create door `POST /api/v1/automation` it described: a flow is created on +// the metadata door, in a package (ADR-0070 D1). A wire shape, never authored +// metadata, so nothing stored carries it. D3: `packageless-create-refused`. +export const entry = 'api/CreateFlowResponse'; From 8f7ad03076aea03a30864f4f86168df51205cf82 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 13:50:27 +0000 Subject: [PATCH 04/23] docs: changeset, checklist follow-up, generated references, notify-channel rule tests (#38174) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CasbvyQnz4st6s79P9 --- .../38174-packageless-create-refused.md | 35 ++++ content/docs/references/index.mdx | 10 +- docs/qa/platform-checklist/FOLLOW-UPS.md | 4 + .../src/validate-flow-notify-channels.test.ts | 95 ++++++++++ .../docs/references/api/automation-api.md | 168 +----------------- packages/spec/export-origins/api.json | 6 - 6 files changed, 141 insertions(+), 177 deletions(-) create mode 100644 .changeset/38174-packageless-create-refused.md create mode 100644 packages/lint/src/validate-flow-notify-channels.test.ts diff --git a/.changeset/38174-packageless-create-refused.md b/.changeset/38174-packageless-create-refused.md new file mode 100644 index 00000000000..99054a07bd5 --- /dev/null +++ b/.changeset/38174-packageless-create-refused.md @@ -0,0 +1,35 @@ +--- +'@objectstack/metadata-protocol': minor +'@objectstack/runtime': minor +'@objectstack/client': minor +'@objectstack/spec': minor +'@objectstack/cli': minor +'@objectstack/lint': minor +'@objectstack/plugin-sharing': minor +--- + +feat(metadata-protocol)!: the kernel refuses a package-less create; `POST /api/v1/automation` is retired; a flow saved through `/meta` is refused for a `notify` channel no plugin registers + +Clause-②: no (narrowing) +Metadata-protocol: narrowed +Skills-docs: none — no skill teaches a package-less create, `POST /api/v1/automation` or `client.automation.create`; `skills/objectstack-platform/references/operations.md` lists `os meta register` as "create/update" and names no flag, which stays true (a create now names `--package`, and the refusal says so) + + + +**BREAKING** accept-set narrowing (ADR-0070 D1; ruling 7184753035; Q-g C, ruling 7234518908). + +- **A package-less create is refused.** FROM a metadata save naming no package, of a name no package holds and no stored row carries, answering `200` and storing a new package-less ("loose") row, TO `422 WRITABLE_PACKAGE_REQUIRED` naming the writable packages, nothing stored. It holds on every door that reaches the kernel save: `PUT /api/v1/meta/{type}/{name}` publish and `?mode=draft`, `os meta register` (non-zero exit, the server's sentence printed), `client.meta.saveItem`, the MCP and AI authoring doors, the automation definition door, and the permission-set clone door (a copy with no package to land in; its sentence names the body's `package`). +- **Not reached.** An in-place save, draft save, delete and per-item publish of an existing package-less item; a package-less save of a name a package holds; the four named exemptions: the kernel-item overlay, the external-datasource import, the binding-preserving migrations (`os migrate meta --stored`, the flow-credential move) and platform registration at boot. There is no flag or environment switch. Sharing rules, queues and assignment rules are data rows (Q-d A) and are not reached. +- **`POST /api/v1/automation` is retired** with `client.automation.create`, `AutomationApiContracts.createFlow`, `CreateFlowRequestSchema` and `CreateFlowResponseSchema`. The door held no package, so it is retired rather than given one. `PUT /api/v1/automation/{name}` still updates a flow that exists; for a new name it answers `422 WRITABLE_PACKAGE_REQUIRED` naming the metadata door. +- **One notify-channel judge on both flow doors.** A flow saved through `PUT /api/v1/meta/flow/{name}` whose `notify` node names a channel no plugin registers was stored and armed (the `/automation` door refused it). The metadata door's runtime publish gate now refuses it too (rule `flow-notify-channel-unregistered`), once the boot has settled; both doors ask the one predicate `unregisteredNotifyChannels` (`@objectstack/lint`). + +## FROM → TO + +| FROM | TO | +|:---|:---| +| `PUT /api/v1/meta/view/my_grid` (new name, no package) | `PUT /api/v1/meta/view/my_grid?package=my_pkg` | +| `os meta register view --data v.json` (new item) | `os meta register view --data v.json --package my_pkg` | +| `client.meta.saveItem('view', 'my_grid', body)` (new item) | `client.meta.saveItem('view', 'my_grid', body, { packageId: 'my_pkg' })` | +| `POST /api/v1/automation` / `client.automation.create('f', def)` | `PUT /api/v1/meta/flow/f?package=my_pkg` / `client.meta.saveItem('flow', 'f', def, { packageId: 'my_pkg' })` | + +One-line fix: name the package a new item belongs to. A flow triggered on an object another package ships needs a package that declares that package as a dependency. Existing package-less items keep saving in place, and Studio's "move into package" moves them. diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 6a664ccff33..65aaa2ae17b 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1761 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1759 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -23,7 +23,7 @@ counts are sums of the rows they head. Regenerate with | Module | Pages | Schemas | Description | | :--- | ---: | ---: | :--- | | [AI Protocol](/docs/references/ai) | 18 | 108 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | -| [API Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/api) | 39 | 539 | REST contracts, endpoints, routing, realtime, batch, discovery. | +| [API Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/api) | 39 | 537 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | | [Data Protocol](/docs/references/data) | 35 | 198 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | | [Identity Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/identity) | 5 | 27 | Users and accounts, organizations, positions, SCIM provisioning. | @@ -36,7 +36,7 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 17 | 188 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **226** | **1761** | 14 protocol modules | +| **Total** | **226** | **1759** | 14 protocol modules | --- @@ -71,7 +71,7 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. ## API Protocol -**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **39 pages, 539 schemas** +**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **39 pages, 537 schemas** REST contracts, endpoints, routing, realtime, batch, discovery. @@ -82,7 +82,7 @@ REST contracts, endpoints, routing, realtime, batch, discovery. | [`app-bundle.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/app-bundle.md) | `AppMetadataBundleResponse` | | [`auth.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/auth.md) | `AuthProvider`, `LoginRequest`, `LoginType`, `MePermissionsAnonymousResponse`, `MePermissionsAuthenticatedResponse`, `MePermissionsResponse`, `RefreshTokenRequest`, `RegisterRequest`, `Session`, `SessionResponse`, `SessionUser`, `UserProfileResponse` | | [`auth-endpoints.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/auth-endpoints.md) | `AuthEndpoint`, `AuthFeaturesConfig`, `AuthProviderInfo`, `DeviceRequestResponse`, `DeviceTokenResponse`, `EmailPasswordConfigPublic`, `GetAuthConfigResponse`, `OneTimeTokenHandoffQuery`, `OneTimeTokenVerifyRequest`, `OneTimeTokenVerifyResponse`, `OrganizationEditionChoice` | -| [`automation-api.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/automation-api.md) | `AutomationApiErrorCode`, `AutomationFlowPathParams`, `AutomationRunPathParams`, `CloneFlowRequest`, `CloneFlowResponse`, `CreateFlowRequest`, `CreateFlowResponse`, `DeleteFlowRequest`, `DeleteFlowResponse`, `FlowFailureDetails`, `FlowInnerRefusal`, `GetFlowRequest`, `GetFlowResponse`, `GetRunRequest`, `GetRunResponse`, `ListRunsRequest`, `ListRunsResponse`, `RecordUpdateStart`, `RecordUpdateStartsRequest`, `RecordUpdateStartsResponse`, `ResumeFailureDetails`, `ToggleFlowRequest`, `ToggleFlowResponse`, `TriggerFlowRequest`, `TriggerFlowResponse`, `UpdateFlowRequest`, `UpdateFlowResponse` | +| [`automation-api.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/automation-api.md) | `AutomationApiErrorCode`, `AutomationFlowPathParams`, `AutomationRunPathParams`, `CloneFlowRequest`, `CloneFlowResponse`, `DeleteFlowRequest`, `DeleteFlowResponse`, `FlowFailureDetails`, `FlowInnerRefusal`, `GetFlowRequest`, `GetFlowResponse`, `GetRunRequest`, `GetRunResponse`, `ListRunsRequest`, `ListRunsResponse`, `RecordUpdateStart`, `RecordUpdateStartsRequest`, `RecordUpdateStartsResponse`, `ResumeFailureDetails`, `ToggleFlowRequest`, `ToggleFlowResponse`, `TriggerFlowRequest`, `TriggerFlowResponse`, `UpdateFlowRequest`, `UpdateFlowResponse` | | [`batch.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/batch.md) | `BatchConfig`, `BatchOperationResult`, `BatchOperationType`, `BatchOptions`, `BatchRecord`, `BatchUpdateRequest`, `BatchUpdateResponse`, `CrossObjectBatchDroppedFields`, `CrossObjectBatchOperation`, `CrossObjectBatchRequest`, `CrossObjectBatchResponse`, `DeleteManyRequest`, `UpdateManyRecord`, `UpdateManyRequest` | | [`comment-threads.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/comment-threads.md) | `CommentThread`, `CommentThreadRecord`, `CommentThreadReplier`, `CommentThreadsQueryRequest`, `CommentThreadsQueryResponse` | | [`contract.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/contract.md) | `ApiError`, `BaseResponse`, `BatchLoadingStrategy`, `BulkRequest`, `BulkResponse`, `CreateRequest`, `DataLoaderConfig`, `DeleteResponse`, `ExportRequest`, `IdRequest`, `ListRecordResponse`, `ModificationResult`, `QueryOptimizationConfig`, `RecordData`, `SingleRecordResponse`, `UpdateRequest` | diff --git a/docs/qa/platform-checklist/FOLLOW-UPS.md b/docs/qa/platform-checklist/FOLLOW-UPS.md index feead8af512..14ae163c2d7 100644 --- a/docs/qa/platform-checklist/FOLLOW-UPS.md +++ b/docs/qa/platform-checklist/FOLLOW-UPS.md @@ -1445,3 +1445,7 @@ No security finding was made, and none is withheld. ## 20. Checklist drift 2026-11-29 — Studio's package-less scope is retired (#38150) Not a sweep: one follow-up, recorded by the change that retired the scope (ADR-0084's amendment of 2026-11-26, `#amendment-2026-11-26-org`), which edited no item. Every `/studio/~org/…` address now lands on `/studio/~all/metadata/flow?source=loose`, a flow that belongs to no package opens on its item page on the cross-package leg and not in the flow designer, and the scope's Changes row and batch publish are gone, so the live text of five items no longer describes the product: `studio-authoring.org-scope-flows` (the whole item: its title, steps[0], [4] and [5] and its three acceptance clauses describe the retired scope, so it is re-authored against the Loose list or retired), `automation.flow-run-step-nesting` steps[4], `automation.flow-error-handling` fixtures.requires[1], `automation.packaged-flow-clone-contract` steps[7], acceptance[6].verify and negative[4], and `integration-system.flow-connector-picker` steps[1]; `automation.flow-node-type-matrix` names the scope in a history row only and needs nothing. Each is re-measured with the product running before its text is changed. + +## 21. Checklist drift 2026-12-03 — the kernel refuses a package-less create; `POST /api/v1/automation` is retired (#38174) + +Not a sweep: one follow-up, recorded by the change that closed the kernel (ADR-0070 D1; Q-g C), which edited no item. A metadata save naming no package, of a new name, now answers `422 WRITABLE_PACKAGE_REQUIRED`, and `POST /api/v1/automation` is not served (a flow is created with `PUT /api/v1/meta/flow/{name}?package=PKG`). Seventeen items create a flow through the retired door, most because it needed no writable package: `access-security.walled-environment-metadata-operator-only`, `api-backend.automation-namespace-address`, `api-backend.client-sdk-namespace-address`, `approvals.ooo-delegation-reroute`, `approvals.sla-escalation`, `approvals.pending-count-surfaces`, `approvals.approver-resolution-matrix`, `approvals.status-mirror-field`, `automation.flow-node-type-matrix`, `automation.flow-error-handling`, `automation.trigger-status-contract`, `automation.packaged-flow-subflow-disable-refusal`, `automation.flow-run-semantics-v18`, `integration-system.flow-connector-picker`, `integration-system.email-template-render`, `integration-system.notify-inbox-delivery` and `integration-system.connector-auth-kind-application`. Each needs a writable package (a flow triggered on an app's object needs one that declares the app's package as a dependency), or, where the item's subject is a package-less row, the test fixture: the row inserted directly through the engine with the system context (as `packages/qa/dogfood/test/flow-shipped-name-layered-read.dogfood.test.ts` does), which is a fixture and not an exemption. Other items that describe a package-less save of a new name (the `_env` reads of `api-backend.json`) drift the same way. Each is re-measured with the product running before its text is changed. diff --git a/packages/lint/src/validate-flow-notify-channels.test.ts b/packages/lint/src/validate-flow-notify-channels.test.ts new file mode 100644 index 00000000000..a8346c639a5 --- /dev/null +++ b/packages/lint/src/validate-flow-notify-channels.test.ts @@ -0,0 +1,95 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38174, ruling 6810493176 letter B] One predicate judges a `notify` node's + * channels on both flow write doors: `/automation` (runtime) and the metadata + * door's runtime publish gate (this rule). The rule judges only against a + * roster its caller hands in once the boot has settled; with none it judges + * nothing. + * + * Ablation: making `unregisteredNotifyChannels` return `[]` turns the refused + * cases RED and leaves the controls GREEN. + */ + +import { describe, it, expect } from 'vitest'; +import { + FLOW_NOTIFY_CHANNEL_UNREGISTERED, + notifyChannelEntries, + unregisteredNotifyChannels, + validateFlowNotifyChannels, +} from './validate-flow-notify-channels.js'; + +const KNOWN = ['email', 'inbox', 'push', 'sms']; + +const flow = (channels: unknown, extraNodes: unknown[] = []) => ({ + name: 'notify_probe', + label: 'Notify probe', + type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'tell', type: 'notify', label: 'Tell', config: { channels } }, + ...extraNodes, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [], +}); + +describe('notifyChannelEntries reads channels the way the executor does', () => { + it('a string, a list, trimmed, blanks and nulls dropped; absent names none', () => { + expect(notifyChannelEntries(' email ')).toEqual([{ channel: 'email', at: [] }]); + expect(notifyChannelEntries(['sms', ' ', null, ' push'])).toEqual([ + { channel: 'sms', at: [0] }, + { channel: 'push', at: [3] }, + ]); + expect(notifyChannelEntries(undefined)).toEqual([]); + expect(notifyChannelEntries('')).toEqual([]); + }); +}); + +describe('unregisteredNotifyChannels', () => { + it('names an unknown channel with its node, field path and nearest known name', () => { + const [hit, ...rest] = unregisteredNotifyChannels(flow(['email', 'smss']), KNOWN); + expect(rest).toEqual([]); + expect(hit).toMatchObject({ nodeId: 'tell', channel: 'smss', field: 'nodes.1.config.channels.1', near: 'sms' }); + expect(hit.line).toContain("names channel 'smss'"); + expect(hit.line).toContain("did you mean 'sms'?"); + }); + + it('CONTROL — every channel known: nothing', () => { + expect(unregisteredNotifyChannels(flow(['email', 'sms']), KNOWN)).toEqual([]); + expect(unregisteredNotifyChannels(flow(undefined), KNOWN)).toEqual([]); + }); + + it('judges non-notify nodes not at all', () => { + const f = { ...flow('email'), nodes: [{ id: 'x', type: 'assignment', config: { channels: ['nope'] } }] }; + expect(unregisteredNotifyChannels(f, KNOWN)).toEqual([]); + }); +}); + +describe('validateFlowNotifyChannels (the metadata door\'s runtime gate rule)', () => { + it('flags an unknown channel against a settled roster', () => { + const findings = validateFlowNotifyChannels({ flows: [flow('smss')] }, new Set(KNOWN)); + expect(findings).toHaveLength(1); + expect(findings[0]).toMatchObject({ + severity: 'error', + rule: FLOW_NOTIFY_CHANNEL_UNREGISTERED, + where: "flow 'notify_probe' · node 'tell'", + path: 'flows[0].nodes.1.config.channels', + }); + expect(findings[0].hint).toContain('email, inbox, push, sms'); + }); + + it('an empty roster refuses every named channel, with the install hint', () => { + const findings = validateFlowNotifyChannels({ flows: [flow('email')] }, new Set()); + expect(findings).toHaveLength(1); + expect(findings[0].hint).toContain('registers no channel'); + }); + + it('CONTROL — no roster (the boot has not settled, or a CLI stack): judges nothing', () => { + expect(validateFlowNotifyChannels({ flows: [flow('smss')] }, undefined)).toEqual([]); + }); + + it('CONTROL — a known channel: nothing', () => { + expect(validateFlowNotifyChannels({ flows: [flow(['email', 'push'])] }, new Set(KNOWN))).toEqual([]); + }); +}); diff --git a/packages/spec/docs/references/api/automation-api.md b/packages/spec/docs/references/api/automation-api.md index e11571fa00e..bb5fb15cbb0 100644 --- a/packages/spec/docs/references/api/automation-api.md +++ b/packages/spec/docs/references/api/automation-api.md @@ -53,8 +53,8 @@ POST /api/v1/automation/_record-starts — Flows a proposed record updat ## TypeScript Usage ```typescript -import { AutomationApiErrorCode, AutomationFlowPathParamsSchema, AutomationRunPathParamsSchema, CloneFlowRequestSchema, CloneFlowResponseSchema, CreateFlowRequestSchema, CreateFlowResponseSchema, DeleteFlowRequestSchema, DeleteFlowResponseSchema, FlowFailureDetailsSchema, FlowInnerRefusalSchema, GetFlowRequestSchema, GetFlowResponseSchema, GetRunRequestSchema, GetRunResponseSchema, ListRunsRequestSchema, ListRunsResponseSchema, RecordUpdateStartSchema, RecordUpdateStartsRequestSchema, RecordUpdateStartsResponseSchema, ResumeFailureDetailsSchema, ToggleFlowRequestSchema, ToggleFlowResponseSchema, TriggerFlowRequestSchema, TriggerFlowResponseSchema, UpdateFlowRequestSchema, UpdateFlowResponseSchema } from '@objectstack/spec/api'; -import type { AutomationApiErrorCode, AutomationFlowPathParams, AutomationRunPathParams, CloneFlowRequest, CloneFlowResponse, CreateFlowRequest, CreateFlowResponse, DeleteFlowRequest, DeleteFlowResponse, FlowFailureDetails, FlowInnerRefusal, GetFlowRequest, GetFlowResponse, GetRunRequest, GetRunResponse, ListRunsRequest, ListRunsResponse, RecordUpdateStart, RecordUpdateStartsRequest, RecordUpdateStartsResponse, ResumeFailureDetails, ToggleFlowRequest, ToggleFlowResponse, TriggerFlowRequest, TriggerFlowResponse, UpdateFlowRequest, UpdateFlowResponse } from '@objectstack/spec/api'; +import { AutomationApiErrorCode, AutomationFlowPathParamsSchema, AutomationRunPathParamsSchema, CloneFlowRequestSchema, CloneFlowResponseSchema, DeleteFlowRequestSchema, DeleteFlowResponseSchema, FlowFailureDetailsSchema, FlowInnerRefusalSchema, GetFlowRequestSchema, GetFlowResponseSchema, GetRunRequestSchema, GetRunResponseSchema, ListRunsRequestSchema, ListRunsResponseSchema, RecordUpdateStartSchema, RecordUpdateStartsRequestSchema, RecordUpdateStartsResponseSchema, ResumeFailureDetailsSchema, ToggleFlowRequestSchema, ToggleFlowResponseSchema, TriggerFlowRequestSchema, TriggerFlowResponseSchema, UpdateFlowRequestSchema, UpdateFlowResponseSchema } from '@objectstack/spec/api'; +import type { AutomationApiErrorCode, AutomationFlowPathParams, AutomationRunPathParams, CloneFlowRequest, CloneFlowResponse, DeleteFlowRequest, DeleteFlowResponse, FlowFailureDetails, FlowInnerRefusal, GetFlowRequest, GetFlowResponse, GetRunRequest, GetRunResponse, ListRunsRequest, ListRunsResponse, RecordUpdateStart, RecordUpdateStartsRequest, RecordUpdateStartsResponse, ResumeFailureDetails, ToggleFlowRequest, ToggleFlowResponse, TriggerFlowRequest, TriggerFlowResponse, UpdateFlowRequest, UpdateFlowResponse } from '@objectstack/spec/api'; // Validate data const result = AutomationApiErrorCode.parse(data); @@ -159,170 +159,6 @@ const result = AutomationApiErrorCode.parse(data); | **noticeCode** | `string` | optional | A stable code naming the `notice` sentence beside it, so a client can show that sentence in its own language: a client maps a code it knows to its own translated sentence, and falls back to `notice` verbatim for a code it does not know or when this key is absent (an older server sends none). The values are the server's; `notice` stays the English fallback. | ---- - -## CreateFlowRequest - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **name** | `string` | ✅ | Machine name | -| **label** | `string` | ✅ | Flow label | -| **description** | `string` | optional | | -| **successMessage** | `string` | optional | Text for a terminal success, carried on AutomationResult for every terminal run (not only screen flows); the screen-flow UI shows it as a toast instead of a generic "Done". A `{{ }}` template over the run's variables (`{{ enrolledCount }} contacts enrolled`), rendered when the run completes. | -| **errorMessage** | `string` | optional | Text for a terminal failure, carried on AutomationResult for every terminal run (not only screen flows); the screen-flow UI shows it as a toast instead of the raw error. A `{{ }}` template over the run's variables, rendered over the variables at the failure point. | -| **version** | `integer` | optional (default: `1`) | Version number | -| **status** | `Enum<'draft' \| 'active' \| 'obsolete' \| 'invalid'>` | optional (default: `"draft"`) | Deployment status | -| **defaultActive** | `boolean` | optional | Packaged flows only: `false` ships the flow switched off, so it is not armed on an installation until an administrator turns it on with the packaged-flow switch (the activation ledger); the administrator's choice, once made, wins over this default across restarts and upgrades. Absent or `true`: switched on. `status` stays the author's switch: `obsolete`/`invalid` disarm the flow everywhere. A flow authored in the environment is switched by `status` and may not declare this key. | -| **type** | `Enum<'autolaunched' \| 'record_change' \| 'schedule' \| 'screen' \| 'api'>` | ✅ | Flow type | -| **variables** | `{ name: string; type: string; isInput?: boolean; isOutput?: boolean; … }[]` | optional | Flow variables | -| **nodes** | `{ id: string; type: string; label: string; config?: Record; … }[]` | ✅ | Flow nodes | -| **edges** | `{ id: string; source: string; target: string; condition?: string \| object; … }[]` | ✅ | Flow connections | -| **runAs** | `Enum<'system' \| 'user'>` | optional (default: `"user"`) | Execution identity for the run: system = elevated (bypasses RLS) — system flows keep system privileges; after an approval decision their attribution user is the decider; user = the human whose act is running this segment: the trigger user until a human decision, the decider after it (RLS-respecting; the nodes after an approval decision run with the decider's identity and permissions, so a node the decider may not perform is refused). Elevation does not reach identity assignment: a system run's governed writes (insert, update, delete, transfer, restore, purge) to sys_user_position, sys_user_permission_set, sys_invitation and sys_member are refused with PERMISSION_DENIED; declare user for position holdings and permission-set grants (the ADR-0090 D12 delegated-administration gate then judges the user the run acts for), and change invitations and memberships through the organization endpoints. Nor does it reach a ledger: a system run's update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' (the audit log, the activity feed and their siblings) is refused with PERMISSION_DENIED, and so is its delete of a record such a ledger row references, because that delete would change the ledger row; an insert is not judged by this rule. Nor does it lift the organization wall: a system run for a user has its reads and writes judged by that user's organization wall. A write whose own data names an organization outside it, or empties a record's organization, is refused with PERMISSION_DENIED. Where the wall denies the user (no active organization under isolated, no membership under group), its reads of an organization's records return none, its deletes remove none, and its other writes are refused with PERMISSION_DENIED. A run that began for no caller is not judged by it, after an approval decision too. A run with no trigger user has no identity to scope to, so under user its data operations are REFUSED — declare system to make the elevation explicit. This covers schedule/time-relative/api triggers AND any record-change flow fired by a write that carried no user. Except behind an anonymous door: publish refuses system on a flow that an authRequired: false endpoint of type flow triggers (ADR-0138 D2b); serve that caller through an authenticated endpoint, the flow's signed inbound hook, or a public form. | -| **requiredPermissions** | `string[]` | optional | [ADR-0066 D4] Capabilities required to START this flow, the flow-level twin of an action's requiredPermissions. Checked at every door that starts a flow by name (the trigger route, an action of type flow over REST and MCP run_action, a declared endpoint of type flow): a caller that is not the system principal must hold every named capability, or the door answers 403 PERMISSION_DENIED and nothing runs. An action that starts this flow inherits the list even when it declares none; one that declares its own needs both. A parent flow's subflow node is not a door and is not checked again. Use this, not current_user.positions inside the flow, to say who may start an elevated (runAs: system) screen or api flow. | -| **errorHandling** | `{ strategy?: Enum<'fail' \| 'retry' \| 'continue'>; maxRetries?: integer; backoffMs?: integer; backoffMultiplier?: number; … }` | optional | Flow-level error handling configuration. A durable pause ends the retry-governed segment: strategy: 'retry' describes one synchronous dispatch, so a run that parks on an approval/screen/wait node and later resumes gets one attempt for anything that fails after the pause. Protect the post-pause half with its own failure handling in the flow — a try_catch node's retry around the post-resume work, or fault edges to a handler node. | -| **protection** | `{ lock: Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>; reason: string; docsUrl?: string }` | optional | Package author protection block — lock policy for this flow. | -| **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | -| **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | -| **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | -| **_provenance** | `Enum<'package' \| 'org' \| 'env-forced' \| 'platform'>` | optional | Origin of the item (package \| org \| env-forced \| platform). | -| **_packageId** | `string` | optional | Owning package machine id. | -| **_packageVersion** | `string` | optional | Owning package version. | -| **_lockDocsUrl** | `string` | optional | Optional documentation link surfaced next to _lockReason. | -| **overrides** | `{ package: string; basedOn: string }` | optional | Override declaration (ADR-0146 D2): `{ package, basedOn }` — this item of "``.custom" replaces the base package's same-named item whole. `basedOn` is recorded and never gates; a base's upgrade plan reads it only as advice. | - -### Nested Shape: `CreateFlowRequest.variables[number]` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **name** | `string` | ✅ | Variable name — a name without a leading `$` (the `$` names are the flow engine's own), read as `{{ name }}` | -| **type** | `string` | ✅ | Data type (text, number, boolean, object, list) | -| **isInput** | `boolean` | optional (default: `false`) | Is input parameter | -| **isOutput** | `boolean` | optional (default: `false`) | Is output parameter | -| **defaultValue** | `any` | optional | Value bound at run start when no parameter supplies one — this is what makes a declared variable always bound. An explicitly supplied param wins, including `false` and `null`; the boundary is `params[name] !== undefined`. | -| **objectName** | `string` | optional | Declares this input a record reference: its value is the id of one record of the named object (the object's snake_case name, e.g. `crm_account`). Only on an input (`isInput: true`). The contract: every door that starts the flow by name (the trigger route, an action of type flow over REST and MCP run_action, a declared endpoint of type flow) loads a declared input from this object in the caller's own scope before the run exists; an id the caller cannot read there is refused 404 RECORD_NOT_FOUND, and a value that is not an id is refused 400 naming the input. The load is added beside any read the flow's own definition makes of the input, never in place of one. An input without this declaration is judged as a record only where the flow's own definition reads it as a record id. `type` stays the data type: the variable holds the id the caller sent. | - -### Nested Shape: `CreateFlowRequest.nodes[number]` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **id** | `string` | ✅ | Node unique ID | -| **type** | `string` | ✅ | Action type — a built-in FlowNodeAction id or a plugin-registered node type. Validated against the live action registry at registerFlow() (ADR-0018), not by a closed enum. The retired callout names 'http_request', 'http_call' and 'webhook' are reserved and refused: use 'http'. | -| **label** | `string` | ✅ | Node label | -| **config** | `Record` | optional | Node configuration | -| **connectorConfig** | `{ connectorId: string; actionId: string; input?: Record }` | optional | | -| **position** | `{ x: number; y: number }` | optional | | -| **timeoutMs** | `integer` | optional | Maximum execution time for this node in milliseconds | -| **inputSchema** | `Record; required?: boolean; description?: string }>` | optional | Input parameter schema for this node | -| **waitEventConfig** | `{ eventType: Enum<'timer' \| 'signal' \| 'webhook' \| 'manual' \| 'condition'>; timerDuration?: string; signalName?: string }` | optional | Configuration for wait node event resumption. REQUIRED on a `type: 'wait'` node — the block is the whole contract, and a wait node without one parses into a run that parks forever reporting success. Under `eventType: 'timer'` a `timerDuration` is required too. | -| **boundaryConfig** | `{ attachedToNodeId: string; eventType: Enum<'error' \| 'timer' \| 'signal' \| 'cancel'>; interrupting?: boolean; errorCode?: string; … }` | optional | Configuration for boundary events attached to host nodes. REQUIRED on a `type: 'boundary_event'` node — without it the node names neither the activity it watches nor what fires it. | - -### Nested Shape: `CreateFlowRequest.edges[number]` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **id** | `string` | ✅ | Edge unique ID | -| **source** | `string` | ✅ | Source Node ID | -| **target** | `string` | ✅ | Target Node ID | -| **condition** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) returning boolean used for branching. An evaluated slot: a bare non-blank CEL string, or an envelope carrying a non-blank `source` — an `ast`-only envelope, and a `source` that is blank after trimming, are refused at authoring because the engine evaluates `source` alone and would otherwise answer a silent `false`. | -| **type** | `Enum<'default' \| 'fault' \| 'conditional' \| 'back'>` | optional (default: `"default"`) | Connection type: default (normal flow), fault (error path), conditional (expression-guarded), or back (ADR-0044 declared back-edge — traversed normally at run time, but excluded from DAG cycle validation so a revise/rework loop can re-enter an earlier node) | -| **label** | `string` | optional | Label on the connector | -| **isDefault** | `boolean` | optional (default: `false`) | BPMN default flow: traverse this edge only when no sibling conditional edge of the same source node matched. Mutually exclusive with `condition`; at most one per source node. | - -### Nested Shape: `CreateFlowRequest.errorHandling` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **strategy** | `Enum<'fail' \| 'retry' \| 'continue'>` | optional (default: `"fail"`) | How to handle node execution errors. 'retry' governs ONE synchronous dispatch: a durable pause (approval/screen/wait) ends the retry-governed segment, so a failure after the run resumes is not retried. | -| **maxRetries** | `integer` | optional (default: `0`) | Retry attempts after the initial one. Read only under strategy: 'retry', which requires >= 1; 0 (the default) means no retry. | -| **backoffMs** | `integer` | optional (default: `1000`) | Base delay before the first retry (ms); subsequent delays multiply by backoffMultiplier | -| **backoffMultiplier** | `number` | optional (default: `1`) | Exponential backoff multiplier; 1 (the default) keeps the delay flat | -| **maxRetryDelayMs** | `integer` | optional (default: `30000`) | Ceiling for a single backoff delay (ms) | -| **jitter** | `boolean` | optional (default: `false`) | Randomize each delay within [50%, 100%] of its computed value — spreads a thundering herd of simultaneous retries | - -### Nested Shape: `CreateFlowRequest.protection` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | ✅ | Lock policy — none \| no-overlay \| no-delete \| full. | -| **reason** | `string` | ✅ | User-visible reason shown when the lock blocks an action. | -| **docsUrl** | `string` | optional | Optional URL the App Studio banner links to for more context. | - -### Nested Shape: `CreateFlowRequest.overrides` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **package** | `string` | ✅ | The base package id whose same-named item this item replaces whole (e.g. "com.acme.crm"). Only an item of the base's paired "``.custom" package declares an override. | -| **basedOn** | `string` | ✅ | Recorded, never a gate: the base package's `manifest.version` this override was taken from (e.g. "3.2.0"), not a history version of the item. Nothing is refused, merged or rebased on it; it tells a person re-basing the override where it started. One reader, as advice: a base's upgrade plan lists an override whose `basedOn` is not the installed base version as stale, beside each override whose base item the upgrade changes (ADR-0146 D2, as amended). | - - ---- - -## CreateFlowResponse - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **success** | `boolean` | ✅ | Operation success status | -| **error** | `{ code: Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| …>; declaredCode?: string; message: string; userMessage?: string; … }` | optional | Error details if success is false | -| **meta** | `{ timestamp: string; duration?: integer; requestId?: string; traceId?: string }` | optional | Response metadata | -| **data** | `{ name: string; label: string; description?: string; successMessage?: string; … }` | ✅ | The created flow, canonicalized — the parsed shape the engine stored, identical to what a subsequent GET answers | - -### Nested Shape: `CreateFlowResponse.error` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| …>` | ✅ | Error code (e.g. VALIDATION_ERROR; StandardErrorCode ∪ the ledger the serving side registers — ERROR_CODE_LEDGER for framework packages) | -| **declaredCode** | `string` | optional | The producer-declared code, verbatim, when it is not a member of the closed `code` vocabulary — the open, author-authored channel (app-specific spellings; ADR-0112) | -| **message** | `string` | ✅ | Readable error message | -| **userMessage** | `string` | optional | Producer-marked user-facing refusal text, verbatim, in the request's locale: platform-composed text falls back to the workspace default locale, then `en`; an app-authored refusal falls back to its declared wording. Present exactly when the producer opted in at throw time; consumers render it to end users as received and keep their generic substitution for anything unmarked. Status-agnostic; never replaces `message`. | -| **refusal** | `true` | optional | Producer-declared: the 5xx this envelope carries is a deliberate refusal whose `message` is authored for the caller, so a boundary that reads the declaration keeps it verbatim (until the withhold arms read it, a declared refusal is still withheld). Absent (the default) on a declared fault, whose `message` is withheld from the body and logged for the operator; redundant on a 4xx. Presence is the declaration — `true` is the only value. | -| **category** | `string` | optional | Error category (e.g. validation, authorization) | -| **httpStatus** | `integer` | optional | HTTP status of the response carrying this error | -| **details** | `any` | optional | Additional error context (e.g. field validation errors) | -| **requestId** | `string` | optional | Request ID for tracking | - -### Nested Shape: `CreateFlowResponse.meta` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **timestamp** | `string` | ✅ | | -| **duration** | `integer` | optional | Server-side processing duration in milliseconds | -| **requestId** | `string` | optional | | -| **traceId** | `string` | optional | | - -### Nested Shape: `CreateFlowResponse.data` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **name** | `string` | ✅ | Machine name | -| **label** | `string` | ✅ | Flow label | -| **description** | `string` | optional | | -| **successMessage** | `string` | optional | Text for a terminal success, carried on AutomationResult for every terminal run (not only screen flows); the screen-flow UI shows it as a toast instead of a generic "Done". A `{{ }}` template over the run's variables (`{{ enrolledCount }} contacts enrolled`), rendered when the run completes. | -| **errorMessage** | `string` | optional | Text for a terminal failure, carried on AutomationResult for every terminal run (not only screen flows); the screen-flow UI shows it as a toast instead of the raw error. A `{{ }}` template over the run's variables, rendered over the variables at the failure point. | -| **version** | `integer` | optional (default: `1`) | Version number | -| **status** | `Enum<'draft' \| 'active' \| 'obsolete' \| 'invalid'>` | optional (default: `"draft"`) | Deployment status | -| **defaultActive** | `boolean` | optional | Packaged flows only: `false` ships the flow switched off, so it is not armed on an installation until an administrator turns it on with the packaged-flow switch (the activation ledger); the administrator's choice, once made, wins over this default across restarts and upgrades. Absent or `true`: switched on. `status` stays the author's switch: `obsolete`/`invalid` disarm the flow everywhere. A flow authored in the environment is switched by `status` and may not declare this key. | -| **type** | `Enum<'autolaunched' \| 'record_change' \| 'schedule' \| 'screen' \| 'api'>` | ✅ | Flow type | -| **variables** | `{ name: string; type: string; isInput?: boolean; isOutput?: boolean; … }[]` | optional | Flow variables | -| **nodes** | `{ id: string; type: string; label: string; config?: Record; … }[]` | ✅ | Flow nodes | -| **edges** | `{ id: string; source: string; target: string; condition?: string \| object; … }[]` | ✅ | Flow connections | -| **runAs** | `Enum<'system' \| 'user'>` | optional (default: `"user"`) | Execution identity for the run: system = elevated (bypasses RLS) — system flows keep system privileges; after an approval decision their attribution user is the decider; user = the human whose act is running this segment: the trigger user until a human decision, the decider after it (RLS-respecting; the nodes after an approval decision run with the decider's identity and permissions, so a node the decider may not perform is refused). Elevation does not reach identity assignment: a system run's governed writes (insert, update, delete, transfer, restore, purge) to sys_user_position, sys_user_permission_set, sys_invitation and sys_member are refused with PERMISSION_DENIED; declare user for position holdings and permission-set grants (the ADR-0090 D12 delegated-administration gate then judges the user the run acts for), and change invitations and memberships through the organization endpoints. Nor does it reach a ledger: a system run's update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' (the audit log, the activity feed and their siblings) is refused with PERMISSION_DENIED, and so is its delete of a record such a ledger row references, because that delete would change the ledger row; an insert is not judged by this rule. Nor does it lift the organization wall: a system run for a user has its reads and writes judged by that user's organization wall. A write whose own data names an organization outside it, or empties a record's organization, is refused with PERMISSION_DENIED. Where the wall denies the user (no active organization under isolated, no membership under group), its reads of an organization's records return none, its deletes remove none, and its other writes are refused with PERMISSION_DENIED. A run that began for no caller is not judged by it, after an approval decision too. A run with no trigger user has no identity to scope to, so under user its data operations are REFUSED — declare system to make the elevation explicit. This covers schedule/time-relative/api triggers AND any record-change flow fired by a write that carried no user. Except behind an anonymous door: publish refuses system on a flow that an authRequired: false endpoint of type flow triggers (ADR-0138 D2b); serve that caller through an authenticated endpoint, the flow's signed inbound hook, or a public form. | -| **requiredPermissions** | `string[]` | optional | [ADR-0066 D4] Capabilities required to START this flow, the flow-level twin of an action's requiredPermissions. Checked at every door that starts a flow by name (the trigger route, an action of type flow over REST and MCP run_action, a declared endpoint of type flow): a caller that is not the system principal must hold every named capability, or the door answers 403 PERMISSION_DENIED and nothing runs. An action that starts this flow inherits the list even when it declares none; one that declares its own needs both. A parent flow's subflow node is not a door and is not checked again. Use this, not current_user.positions inside the flow, to say who may start an elevated (runAs: system) screen or api flow. | -| **errorHandling** | `{ strategy?: Enum<'fail' \| 'retry' \| 'continue'>; maxRetries?: integer; backoffMs?: integer; backoffMultiplier?: number; … }` | optional | Flow-level error handling configuration. A durable pause ends the retry-governed segment: strategy: 'retry' describes one synchronous dispatch, so a run that parks on an approval/screen/wait node and later resumes gets one attempt for anything that fails after the pause. Protect the post-pause half with its own failure handling in the flow — a try_catch node's retry around the post-resume work, or fault edges to a handler node. | -| **protection** | `{ lock: Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>; reason: string; docsUrl?: string }` | optional | Package author protection block — lock policy for this flow. | -| **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | -| **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | -| **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | -| **_provenance** | `Enum<'package' \| 'org' \| 'env-forced' \| 'platform'>` | optional | Origin of the item (package \| org \| env-forced \| platform). | -| **_packageId** | `string` | optional | Owning package machine id. | -| **_packageVersion** | `string` | optional | Owning package version. | -| **_lockDocsUrl** | `string` | optional | Optional documentation link surfaced next to _lockReason. | -| **overrides** | `{ package: string; basedOn: string }` | optional | Override declaration (ADR-0146 D2): `{ package, basedOn }` — this item of "``.custom" replaces the base package's same-named item whole. `basedOn` is recorded and never gates; a base's upgrade plan reads it only as advice. | - - --- ## DeleteFlowRequest diff --git a/packages/spec/export-origins/api.json b/packages/spec/export-origins/api.json index 1a486d19140..af5c55eac0d 100644 --- a/packages/spec/export-origins/api.json +++ b/packages/spec/export-origins/api.json @@ -254,12 +254,6 @@ "CreateDataRequestSchema": "src/api/protocol.zod.ts#CreateDataRequestSchema (const)", "CreateDataResponse": "src/api/protocol.zod.ts#CreateDataResponse (type)", "CreateDataResponseSchema": "src/api/protocol.zod.ts#CreateDataResponseSchema (const)", - "CreateFlowRequest": "src/api/automation-api.zod.ts#CreateFlowRequest (type)", - "CreateFlowRequestParsed": "src/api/automation-api.zod.ts#CreateFlowRequestParsed (type)", - "CreateFlowRequestSchema": "src/api/automation-api.zod.ts#CreateFlowRequestSchema (const)", - "CreateFlowResponse": "src/api/automation-api.zod.ts#CreateFlowResponse (type)", - "CreateFlowResponseParsed": "src/api/automation-api.zod.ts#CreateFlowResponseParsed (type)", - "CreateFlowResponseSchema": "src/api/automation-api.zod.ts#CreateFlowResponseSchema (const)", "CreateImportJobRequest": "src/api/export.zod.ts#CreateImportJobRequest (type)", "CreateImportJobRequestParsed": "src/api/export.zod.ts#CreateImportJobRequestParsed (type)", "CreateImportJobRequestSchema": "src/api/export.zod.ts#CreateImportJobRequestSchema (const)", From c5add451fb83b2686c203f798017fb68c32e6b94 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 14:54:02 +0000 Subject: [PATCH 05/23] feat: the ceremony's loose conversions (fifth exemption, ruling 7380917604); package-bound drafts hold a name (#38174) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CasbvyQnz4st6s79P9 --- .../commands/meta/register-package.test.ts | 30 ++++++++--- .../migrate/organization-ownership.ts | 6 ++- .../organization-ownership-apply.test.ts | 10 ++-- .../src/utils/organization-ownership-apply.ts | 31 +++++++++-- .../src/protocol-door-requests.ts | 11 ++++ .../src/protocol-packageless-create.ts | 17 +++++- .../meta-packageless-create-refused.test.ts | 53 +++++++++++++++++++ 7 files changed, 140 insertions(+), 18 deletions(-) diff --git a/packages/cli/src/commands/meta/register-package.test.ts b/packages/cli/src/commands/meta/register-package.test.ts index ad08a2a67f3..c7c47dc0814 100644 --- a/packages/cli/src/commands/meta/register-package.test.ts +++ b/packages/cli/src/commands/meta/register-package.test.ts @@ -341,20 +341,36 @@ describe('[#23350] the `--package` flag `os meta register` declares', () => { // --------------------------------------------------------------------------- describe('[#23350] `os meta register --package` against the real save door', () => { - it('UNFLAGGED, an item with no package: an ACTIVE save, with no query string — the request this command always sent', async () => { + it('[#38174] UNFLAGGED, a NEW item: the save is refused 422 WRITABLE_PACKAGE_REQUIRED, the exit is non-zero, the server\'s sentence is printed, and nothing is stored', async () => { const { engine, saveRequests, wire } = await bootDoor(); - const run = await runCli(['view', '--data', dataFile(VIEW('plain_probe', 'A'))]); + const run = await runCli(['view', '--data', dataFile(VIEW('plain_probe', 'A')), '--format', 'json']); - expect(run.exitCode).toBe(0); - expect(run.out).toContain('Metadata registered: view/plain_probe'); + expect(run.exitCode).toBe(1); + const payload = JSON.parse(run.out); + expect(payload.success).toBe(false); + expect(payload.code).toBe('WRITABLE_PACKAGE_REQUIRED'); + expect(payload.httpStatus).toBe(422); + // The kernel's own sentence (ADR-0070 D1), naming the CLI remedy and the writable packages. + expect(String(payload.error)).toContain('Cannot create view/plain_probe with no package'); + expect(String(payload.error)).toContain('--package PKG'); + expect(String(payload.error)).toContain(PKG); + // The request this command always sent: ACTIVE, no `?mode=draft`, no `?package=`. const sent = wire.filter((w) => w.method === 'PUT').at(-1)!; expect(sent.pathname).toBe('/api/v1/meta/view/plain_probe'); - // No `?mode=draft` and no `?package=`: the save is the active one. expect(sent.search).toBe(''); - expect(Object.keys(sent.headers).sort()).toEqual(['content-type']); expect(saveRequests.at(-1)).not.toHaveProperty('packageId'); - expect(await labelsByPackage(engine, 'plain_probe')).toEqual({ '': { label: 'A', state: 'active' } }); + expect(await labelsByPackage(engine, 'plain_probe')).toEqual({}); + }, 60_000); + + it('[#38174] CONTROL — the same new item with `--package P` is saved into P', async () => { + const { engine } = await bootDoor(); + + const run = await runCli(['view', '--data', dataFile(VIEW('plain_probe', 'A')), '--package', PKG]); + + expect(run.exitCode).toBe(0); + expect(run.out).toContain('Metadata registered: view/plain_probe'); + expect(await labelsByPackage(engine, 'plain_probe')).toEqual({ [PKG]: { label: 'A', state: 'active' } }); }, 60_000); it('UNFLAGGED, an item TWO packages hold: the active save is refused 409 RESOURCE_CONFLICT, and nothing is written', async () => { diff --git a/packages/cli/src/commands/migrate/organization-ownership.ts b/packages/cli/src/commands/migrate/organization-ownership.ts index 6c5afebe23f..e7b14113ec8 100644 --- a/packages/cli/src/commands/migrate/organization-ownership.ts +++ b/packages/cli/src/commands/migrate/organization-ownership.ts @@ -916,7 +916,11 @@ export default class OrganizationOwnershipCeremony extends Command { name, item: body, actor: CEREMONY_ACTOR, - ...(target ? { packageId: target.packageId } : {}), + ...(target && 'packageId' in target ? { packageId: target.packageId } : {}), + // [#38174, ruling 7380917604 (A)] A conversion that lands loose + // states the ceremony's provenance, which only the kernel's + // package-less create judgment reads (the fifth exemption). + ...(target && 'leftLoose' in target ? { packagelessCreateProvenance: 'organization-ownership-ceremony' } : {}), }); }, }, diff --git a/packages/cli/src/utils/organization-ownership-apply.test.ts b/packages/cli/src/utils/organization-ownership-apply.test.ts index 44709bacf5b..b08c86ece98 100644 --- a/packages/cli/src/utils/organization-ownership-apply.test.ts +++ b/packages/cli/src/utils/organization-ownership-apply.test.ts @@ -142,11 +142,11 @@ function catalog(opts: { adminSetDeclared?: boolean } = {}): CatalogPort & Metad }, async save(type, name, body, target) { if (type === 'view') { - viewSaves.push({ name, body, packageId: target?.packageId ?? null }); + viewSaves.push({ name, body, packageId: (target && "packageId" in target ? target.packageId : undefined) ?? null }); return; } if (type === 'form') { - formSaves.push({ name, body, packageId: target?.packageId ?? null }); + formSaves.push({ name, body, packageId: (target && "packageId" in target ? target.packageId : undefined) ?? null }); return; } if (type === 'email_template') { @@ -241,7 +241,7 @@ function storingDoor(c: ReturnType): ReturnType await c.save(type, name, body, target); // The catalog conversion and the template promotion keep the catalog double's own store. if (!['view', 'form', 'dashboard', 'report', 'translation'].includes(type)) return; - const pkg = target?.packageId ?? null; + const pkg = (target && "packageId" in target ? target.packageId : undefined) ?? null; let version = 1; if (has('sys_metadata_history')) { const scoped = has('sys_metadata_history', 'organization_id'); @@ -1439,7 +1439,7 @@ describe('ADR-0131 D10 --apply — organization customizations and form withdraw const refusing: ReturnType = { ...c, async save(type, name, body, target) { - if (type === 'form') throw new Error(`NOT_OVERRIDABLE: refused in ${String(target?.packageId)}`); + if (type === 'form') throw new Error(`NOT_OVERRIDABLE: refused in ${String((target && "packageId" in target ? target.packageId : undefined))}`); return c.save(type, name, body, target); }, }; @@ -1611,7 +1611,7 @@ describe('ADR-0131 D10 --apply — a customization conflict resolved by --metada const refusing: ReturnType = { ...c, async save(type, name, body, target) { - if (type === 'view' && target?.packageId === null) throw new Error('VALIDATION_ERROR: refused'); + if (type === 'view' && (target && "packageId" in target ? target.packageId : undefined) === null) throw new Error('VALIDATION_ERROR: refused'); return c.save(type, name, body, target); }, }; diff --git a/packages/cli/src/utils/organization-ownership-apply.ts b/packages/cli/src/utils/organization-ownership-apply.ts index 7d7cba9a4d7..35363c5f4a9 100644 --- a/packages/cli/src/utils/organization-ownership-apply.ts +++ b/packages/cli/src/utils/organization-ownership-apply.ts @@ -264,13 +264,32 @@ export interface CatalogPort { resolve(type: 'position' | 'permission', name: string): Promise<{ definition: Readonly> } | undefined>; } +/** + * [#38174, ruling 7380917604 (A)] The target of a save that converts a row + * stored before the upgrade into a NEW environment item with no package: the + * authored positions and permission sets, and a promoted email template. They + * land loose (Studio's "move into package" moves them later), under the + * kernel's fifth named exemption from the package-less create refusal; every + * other save gate still judges them. + */ +export const LEFT_LOOSE = Object.freeze({ leftLoose: true as const }); + +/** + * [#38174, ruling 7380917604 (A)] The report's note naming what a step left + * with no package, and the door that moves it into one. + */ +export function leftLooseNote(items: readonly string[]): string { + return `${items.length} new environment item(s) landed with no package: ${items.join(', ')}. A package-less item ` + + 'keeps working; move it into a package with Studio\'s "move into package" (POST /api/v1/packages/:id/move-in).'; +} + /** The metadata door: an environment metadata save. Throws when the door refuses. */ export interface MetadataDoorPort { save( type: 'position' | 'permission' | 'email_template' | 'view' | 'form' | 'dashboard' | 'report' | 'translation', name: string, body: Record, - target?: { packageId: string | null }, + target?: { packageId: string | null } | typeof LEFT_LOOSE, ): Promise; } @@ -834,7 +853,7 @@ async function resolveName(run: Run, type: 'position' | 'permission', name: stri } async function saveDefinition(run: Run, type: 'position' | 'permission', name: string, body: Record): Promise { - await run.opts.door.save(type, name, body); + await run.opts.door.save(type, name, body, LEFT_LOOSE); run.saved.set(`${type}|${name}`, body); } @@ -1215,6 +1234,7 @@ async function runAuthoredConversion(run: Run): Promise { try { await saveDefinition(run, type, name, body); summary.converted++; + leftLoose.push(`${type}/${name}`); run.opts.onProgress?.(`converted the authored ${type} ${name} to environment metadata`); } catch (error) { blockers.push( @@ -1226,6 +1246,7 @@ async function runAuthoredConversion(run: Run): Promise { return handled; }; + const leftLoose: string[] = []; await convert('permission', sets, (row) => permissionSetDefinitionFromRow(row)); const authoredPositions = await convert('position', positions, (row) => positionDefinitionFromRow(row)); @@ -1257,6 +1278,7 @@ async function runAuthoredConversion(run: Run): Promise { 'and are deleted with the other binding mirrors.', ); } + if (leftLoose.length > 0) notes.push(leftLooseNote(leftLoose)); return { step: 'authored-conversion', status: blockers.length ? 'blocked' : 'done', summary, blockers, notes }; } @@ -2162,6 +2184,7 @@ async function runTemplatePromotion(run: Run): Promise { const summary: Record = { promoted: 0, alreadyPromoted: 0, conflicts: 0 }; const blockers: string[] = []; const notes: string[] = []; + const promotedLoose: string[] = []; run.verifiedTemplateIds.clear(); const cols = await columnsOf(run, TEMPLATES); if (!cols) return { step: 'template-promotion', status: 'done', summary, blockers, notes }; @@ -2207,8 +2230,9 @@ async function runTemplatePromotion(run: Run): Promise { continue; } try { - await run.opts.door.save('email_template', name, body); + await run.opts.door.save('email_template', name, body, LEFT_LOOSE); run.saved.set(`email_template|${name}|${locale}`, body); + if (!existing) promotedLoose.push(`email_template/${name} (${locale})`); for (const r of group.rows) run.verifiedTemplateIds.add(String(r.id)); summary.promoted++; run.opts.onProgress?.(`promoted the template ${name} (${locale}) to environment metadata`); @@ -2219,6 +2243,7 @@ async function runTemplatePromotion(run: Run): Promise { ); } } + if (promotedLoose.length > 0) notes.push(leftLooseNote(promotedLoose)); return { step: 'template-promotion', status: blockers.length ? 'blocked' : 'done', summary, blockers, notes }; } diff --git a/packages/metadata-protocol/src/protocol-door-requests.ts b/packages/metadata-protocol/src/protocol-door-requests.ts index f558f5ad809..424385e68d2 100644 --- a/packages/metadata-protocol/src/protocol-door-requests.ts +++ b/packages/metadata-protocol/src/protocol-door-requests.ts @@ -28,6 +28,17 @@ type SaveMetaItemRequest = { * already holds. Set by server code only; no HTTP door forwards it. */ inheritedGrantObjects?: readonly string[], + /** + * [#38174, ruling 7380917604 (A)] The fifth named exemption from the + * package-less create refusal: a create the organization-ownership + * ceremony (`os migrate organization-ownership --apply`) makes when it + * converts rows stored before the upgrade (an organization's authored + * positions and permission sets, and a promoted email template). Read by + * the create judgment alone ({@link packagelessCreateRefusal}); no other + * gate branches on it, and `source` stays unset, so every validation still + * judges the save. Set by server code only; no HTTP door forwards it. + */ + packagelessCreateProvenance?: 'organization-ownership-ceremony', /** * [#35143, #38595] The names of the flows the same package copy plans to * write, under the names it writes them as: the copy door's plan. Both diff --git a/packages/metadata-protocol/src/protocol-packageless-create.ts b/packages/metadata-protocol/src/protocol-packageless-create.ts index f7e7e174714..03209de9f3e 100644 --- a/packages/metadata-protocol/src/protocol-packageless-create.ts +++ b/packages/metadata-protocol/src/protocol-packageless-create.ts @@ -28,7 +28,9 @@ * (a package-less save of a name a package holds customizes that holder, * ADR-0150 D4, and keeps its answer); * - no package-less row of it is stored, active or draft (saving a loose row - * that already exists, in place, stays open: the ruling's sibling clause). + * that already exists, in place, stays open: the ruling's sibling clause); + * - no draft row of it is bound to a package (the draft address binds the + * save into that package, #23657, or refuses it 409 when two hold one). * * ## The named exemptions, and no other * @@ -38,6 +40,11 @@ * stored flow-credential move), server-stated, never on the wire; * - W3, the kernel-item overlay: intent `override-artifact`, above. * + * W5 (ruling 7380917604, A), the organization-ownership ceremony's + * conversions of rows stored before the upgrade: `packagelessCreateProvenance: + * 'organization-ownership-ceremony'`, server-stated, read here and nowhere + * else (`source` stays unset, so every other gate still judges the save). + * * W13, platform registration (`MetadataManager.register(…, { origin: * 'platform' })`), writes the metadata service's own store and never reaches * this path. `package-duplicate` always names its target, so it never arrives @@ -60,6 +67,7 @@ export interface PackagelessCreateRequest { readonly packageId?: string | null; readonly source?: unknown; readonly writeFace?: string; + readonly packagelessCreateProvenance?: 'organization-ownership-ceremony'; } /** @@ -78,11 +86,16 @@ export async function packagelessCreateRefusal( if (request.packageId != null && request.packageId !== '') return undefined; if (request.source !== undefined) return undefined; if (request.writeFace === 'external-import' || request.writeFace === 'package-duplicate') return undefined; + if (request.packagelessCreateProvenance === 'organization-ownership-ceremony') return undefined; const active = await host.packagelessAddress(singularType, request.name, member, 'active'); if (active.candidates.length > 0 || active.unbound) return undefined; + // A draft row of the name, bound or loose, holds it as well: the draft + // address rules bind the save into the one package a draft names (#23657), + // refuse it 409 when two do, or save the loose draft in place. None of + // those is a create, and each keeps its own answer. const drafts = await host.packagelessAddress(singularType, request.name, member, 'draft'); - if (drafts.unbound) return undefined; + if (drafts.unbound || drafts.candidates.length > 0) return undefined; return packagelessCreateError(singularType, request.name, writablePackageIds(host)); } diff --git a/packages/runtime/src/meta-packageless-create-refused.test.ts b/packages/runtime/src/meta-packageless-create-refused.test.ts index 9c47fb917d6..df007ef2841 100644 --- a/packages/runtime/src/meta-packageless-create-refused.test.ts +++ b/packages/runtime/src/meta-packageless-create-refused.test.ts @@ -187,9 +187,62 @@ describe('[#38174] controls — what the close does not reach', () => { expect(answer.status, JSON.stringify(answer)).toBe(200); }); + it('a package-less draft save of a name whose only draft a package holds saves into that package (#23657), not a create', async () => { + const { put, rows } = await boot(); + expect((await put('view', 'drafted_grid', viewBody('drafted_grid', 'A'), { package: PKG, mode: 'draft' })).status).toBe(200); + const answer = await put('view', 'drafted_grid', viewBody('drafted_grid', 'B'), { mode: 'draft' }); + expect(answer.code).not.toBe('WRITABLE_PACKAGE_REQUIRED'); + expect(answer.status, JSON.stringify(answer)).toBe(200); + expect((await rows('view', 'drafted_grid')).map((r) => r.package_id)).toEqual([PKG]); + }); + it('a binding-preserving migration (server-stated `source`) is exempt', async () => { const { protocol, rows } = await boot(); await protocol.saveMetaItem({ type: 'view', name: 'migrated_grid', item: viewBody('migrated_grid', 'A'), source: 'migrate-stored' }); expect((await rows('view', 'migrated_grid')).map((r) => r.package_id)).toEqual([null]); }); }); + +describe('[#38174, ruling 7380917604 (A)] the fifth exemption: the organization-ownership ceremony\'s conversions land loose', () => { + const CEREMONY = { packagelessCreateProvenance: 'organization-ownership-ceremony' } as const; + const set = (name: string, object: string) => ({ name, label: 'Legacy set', objects: { [object]: { allowRead: true } } }); + const position = (name: string) => ({ name, label: 'Legacy position' }); + const template = (name: string) => ({ name, label: 'Welcome', subject: 'Welcome', bodyHtml: '

Hi

' }); + + it.each([ + ['permission', 'legacy_reader', set('legacy_reader', 'task')], + ['position', 'legacy_clerk', position('legacy_clerk')], + ['email_template', 'legacy_welcome', template('legacy_welcome')], + ] as const)('%s: refused without the provenance, saved loose with it', async (type, name, body) => { + const { protocol, rows } = await boot(); + await expect(protocol.saveMetaItem({ type, name, item: body })) + .rejects.toMatchObject({ code: 'WRITABLE_PACKAGE_REQUIRED' }); + await protocol.saveMetaItem({ type, name, item: body, ...CEREMONY }); + expect((await rows(type, name)).map((r) => r.package_id)).toEqual([null]); + }); + + it('every other gate still judges the save: a set granting on an object that does not exist is still refused', async () => { + const { protocol, rows } = await boot(); + const refused = await protocol.saveMetaItem({ type: 'permission', name: 'legacy_ghost', item: set('legacy_ghost', 'no_such_object'), ...CEREMONY }) + .then(() => null, (error: unknown) => error as { code?: string; message?: string }); + expect(refused, 'the unknown-grant refusal must still fire').not.toBeNull(); + expect(refused?.code).not.toBe('WRITABLE_PACKAGE_REQUIRED'); + expect(String(refused?.message)).toContain('no_such_object'); + expect(await rows('permission', 'legacy_ghost')).toEqual([]); + }); + + it('a wire save cannot state the provenance: the REST door builds its request field by field', async () => { + const { put, rows } = await boot(); + const answer = await put('position', 'legacy_clerk', { ...position('legacy_clerk'), packagelessCreateProvenance: 'organization-ownership-ceremony' }); + const query = await put('position', 'legacy_clerk2', position('legacy_clerk2'), { packagelessCreateProvenance: 'organization-ownership-ceremony' }); + // In the body it is an unknown key of the item (refused by the spec's + // own parse, never read as a request field); in the query it is a + // parameter the door does not take (400). Neither reaches the save. + expect(answer.status, JSON.stringify(answer)).toBe(422); + expect(answer.code).toBe('INVALID_METADATA'); + expect(query.status, JSON.stringify(query)).toBe(400); + expect(query.code).toBe('VALIDATION_ERROR'); + expect(await rows('position', 'legacy_clerk')).toEqual([]); + expect(await rows('position', 'legacy_clerk2')).toEqual([]); + }); +}); From ae4818233327736c9d225475c92f347f54f6e831 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 14:54:09 +0000 Subject: [PATCH 06/23] docs(changeset): the fifth exemption and the draft-held name (#38174) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CasbvyQnz4st6s79P9 --- .changeset/38174-packageless-create-refused.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/38174-packageless-create-refused.md b/.changeset/38174-packageless-create-refused.md index 99054a07bd5..b582150881a 100644 --- a/.changeset/38174-packageless-create-refused.md +++ b/.changeset/38174-packageless-create-refused.md @@ -19,7 +19,7 @@ Skills-docs: none — no skill teaches a package-less create, `POST /api/v1/auto **BREAKING** accept-set narrowing (ADR-0070 D1; ruling 7184753035; Q-g C, ruling 7234518908). - **A package-less create is refused.** FROM a metadata save naming no package, of a name no package holds and no stored row carries, answering `200` and storing a new package-less ("loose") row, TO `422 WRITABLE_PACKAGE_REQUIRED` naming the writable packages, nothing stored. It holds on every door that reaches the kernel save: `PUT /api/v1/meta/{type}/{name}` publish and `?mode=draft`, `os meta register` (non-zero exit, the server's sentence printed), `client.meta.saveItem`, the MCP and AI authoring doors, the automation definition door, and the permission-set clone door (a copy with no package to land in; its sentence names the body's `package`). -- **Not reached.** An in-place save, draft save, delete and per-item publish of an existing package-less item; a package-less save of a name a package holds; the four named exemptions: the kernel-item overlay, the external-datasource import, the binding-preserving migrations (`os migrate meta --stored`, the flow-credential move) and platform registration at boot. There is no flag or environment switch. Sharing rules, queues and assignment rules are data rows (Q-d A) and are not reached. +- **Not reached.** An in-place save, draft save, delete and per-item publish of an existing package-less item; a package-less save of a name a package holds, as an item or as a draft (the draft address binds it into that package, as before); the five named exemptions: the kernel-item overlay, the external-datasource import, the binding-preserving migrations (`os migrate meta --stored`, the flow-credential move), platform registration at boot, and (ruling 7380917604) `os migrate organization-ownership --apply`'s conversions of rows stored before the upgrade (an organization's authored positions and permission sets, a promoted email template), which land loose under a server-stated provenance only the create judgment reads, every other save gate still judging them, and the ceremony's report lists them and names the move door (`POST /api/v1/packages/:id/move-in`). There is no flag or environment switch. Sharing rules, queues and assignment rules are data rows (Q-d A) and are not reached. - **`POST /api/v1/automation` is retired** with `client.automation.create`, `AutomationApiContracts.createFlow`, `CreateFlowRequestSchema` and `CreateFlowResponseSchema`. The door held no package, so it is retired rather than given one. `PUT /api/v1/automation/{name}` still updates a flow that exists; for a new name it answers `422 WRITABLE_PACKAGE_REQUIRED` naming the metadata door. - **One notify-channel judge on both flow doors.** A flow saved through `PUT /api/v1/meta/flow/{name}` whose `notify` node names a channel no plugin registers was stored and armed (the `/automation` door refused it). The metadata door's runtime publish gate now refuses it too (rule `flow-notify-channel-unregistered`), once the boot has settled; both doors ask the one predicate `unregisteredNotifyChannels` (`@objectstack/lint`). From f85efae96e9483ab7e1d0ecc5e8c9185b49ccc97 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 15:18:06 +0000 Subject: [PATCH 07/23] test: migrate the save-path suites to name a package or seed the loose row (#38174) Mechanical: tests that created a new item with no package as setup now name an installed writable package; tests whose subject is a package-less row seed it through the engine with the system context (a fixture, not an exemption); tests that drove POST /api/v1/automation pin that it is not served or move to PUT. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CasbvyQnz4st6s79P9 --- .../meta/delete-reset-carriers.test.ts | 41 ++-- .../src/commands/meta/register-draft.test.ts | 9 + .../src/commands/meta/register-force.test.ts | 16 +- ...ed-legacy-organization.integration.test.ts | 12 +- .../rls-policy-authoring-admission.test.ts | 12 +- ...atalog-echo-env-kernel.integration.test.ts | 11 + ...tocol.active-save-namespace-prefix.test.ts | 13 + ...ocol.adr0005-org-override-rollback.test.ts | 9 + .../protocol.audit-field-governance.test.ts | 10 +- ...protocol.cached-item-last-modified.test.ts | 13 +- .../protocol.capability-write-door.test.ts | 12 +- ...ol.cbp-master-not-writable-refusal.test.ts | 9 +- .../protocol.cluster-mutation-fanout.test.ts | 55 +++-- ...tocol.code-defined-datasource-door.test.ts | 20 +- .../src/protocol.code-only-types.test.ts | 16 +- .../protocol.container-issue-descent.test.ts | 8 +- .../src/protocol.credential-channel.test.ts | 22 +- ...col.dashboard-dataset-publish-gate.test.ts | 20 +- ...plicate-global-filter-name-refusal.test.ts | 9 +- ...urce-credentials-ref-own-reference.test.ts | 7 +- ...urce-credentials-ref-restore-doors.test.ts | 14 +- ...col.datasource-delete-prolongation.test.ts | 24 +- .../protocol.extension-field-suffix.test.ts | 6 + ...l-binding-named-datasource-refusal.test.ts | 83 ++++--- ...binding-primary-datasource-refusal.test.ts | 12 +- .../protocol.flow-org-override-closed.test.ts | 10 +- ...rotocol.graft-folded-form-sections.test.ts | 35 ++- .../protocol.injected-system-columns.test.ts | 15 +- ...nvalid-metadata-422-face-inventory.test.ts | 66 +++-- .../src/protocol.item-name-every-door.test.ts | 82 +++++-- .../src/protocol.item-name-grammar.test.ts | 17 +- .../src/protocol.lifecycle-audit-rows.test.ts | 28 ++- .../protocol.lock-gate-fail-closed.test.ts | 27 ++- ...col.meta-types-mint-door-agreement.test.ts | 12 +- .../src/protocol.metadata-redaction.test.ts | 21 +- .../protocol.named-base-every-type.test.ts | 12 +- ...protocol.named-base-stored-binding.test.ts | 13 +- ...ject-duplicate-action-name-refusal.test.ts | 10 +- .../protocol.org-scoped-write-refused.test.ts | 21 +- .../src/protocol.package-closure-gate.test.ts | 18 +- ...rotocol.package-publish-audit-rows.test.ts | 2 +- ...l.packageless-layered-read-refusal.test.ts | 10 + .../protocol.packageless-save-address.test.ts | 109 ++++++--- ....permission-set-name-cross-package.test.ts | 15 +- .../protocol.platform-mark-rollback.test.ts | 31 ++- ...rotocol.platform-schedule-org-gate.test.ts | 19 +- ...tocol.platform-store-system-opt-in.test.ts | 17 +- .../src/protocol.read-decorations.test.ts | 42 ++-- ....recovery-doors-mutation-projector.test.ts | 13 +- .../src/protocol.refusal-audit-rows.test.ts | 6 + ....restore-doors-save-refusal-family.test.ts | 30 +++ .../protocol.runtime-authoring-gate.test.ts | 225 ++++++++++-------- ...tocol.runtime-gate-stored-universe.test.ts | 41 ++-- .../protocol.save-door-lock-family.test.ts | 16 +- .../src/protocol.save-door-protection.test.ts | 10 +- ...rotocol.save-flow-canonicalization.test.ts | 20 +- .../src/protocol.save-receipt-wording.test.ts | 29 ++- .../src/protocol.save-union-issues.test.ts | 58 +++-- .../protocol.seed-external-id-refusal.test.ts | 4 +- .../protocol.select-shorthand-refusal.test.ts | 17 +- .../src/protocol.served-content-hash.test.ts | 71 +++--- ...otocol.stored-action-gate-lowering.test.ts | 25 +- ...otocol.translation-apps-door-38649.test.ts | 9 +- ...ocol.translation-target-door-38623.test.ts | 9 +- ...rotocol.unknown-datasource-refusal.test.ts | 26 +- ...tocol.unknown-grant-object-refusal.test.ts | 42 ++-- ...l.unknown-picklist-binding-refusal.test.ts | 11 +- .../protocol.unrecognised-meta-type.test.ts | 15 +- ...ol.view-container-reset-expansions.test.ts | 15 +- ...ata-repository.package-writability.test.ts | 10 +- .../view-container-runtime-expansion.test.ts | 85 +++++-- .../src/bound-action-foreign-object.test.ts | 17 +- .../src/default-record-page-save-door.test.ts | 51 ++-- .../delete-meta-response-conformance.test.ts | 20 +- ...gine-security-catalog-package-door.test.ts | 7 +- ...est-service-residual-security-seal.test.ts | 7 +- ...ject-primary-designation-roundtrip.test.ts | 7 +- ...-object-search-companion-roundtrip.test.ts | 7 +- ...meta-object-tenant-index-roundtrip.test.ts | 7 +- .../src/metadata-validation-sweep.test.ts | 7 + .../objectql/src/overlay-precedence.test.ts | 17 ++ ...lugin-runtime-object-metadata-copy.test.ts | 11 +- .../src/plugin.authoring-channel.test.ts | 19 +- ...protocol-batch-object-registration.test.ts | 4 +- ...otocol-boot-object-package-binding.test.ts | 8 +- .../src/protocol-commit-history.test.ts | 49 +++- ...l-delete-boot-hydrated-object-heal.test.ts | 12 +- .../protocol-destructive-null-master.test.ts | 8 +- .../protocol-destructive-unit-mode.test.ts | 5 +- ...ment-kernel-registry-write-through.test.ts | 24 +- .../protocol-meta-effective-schema.test.ts | 19 +- packages/objectql/src/protocol-meta.test.ts | 69 ++++-- .../src/protocol-metadata-row-actor.test.ts | 16 +- ...rate-stored-draft-permission-grant.test.ts | 12 +- .../src/protocol-object-overlay-layer.test.ts | 12 +- ...protocol-org-overlay-registry-gate.test.ts | 15 ++ ...ocol-packageless-overlay-migration.test.ts | 5 +- ...rmission-set-name-registry-reading.test.ts | 9 +- ...protocol-picklist-served-roundtrip.test.ts | 12 +- .../protocol-publish-canonical-fold.test.ts | 16 +- .../src/protocol-publish-rollback.test.ts | 29 ++- .../src/protocol-recorded-by-null.test.ts | 27 ++- .../src/protocol-registry-shadow.test.ts | 7 +- ...ore-publish-drained-connector-keys.test.ts | 15 +- ...ol-save-meta-repo-path-real-engine.test.ts | 25 +- .../src/protocol-save-meta-repo-path.test.ts | 19 ++ ...-sentinel-owner-draft-save-address.test.ts | 7 + ...entinel-owner-package-save-refusal.test.ts | 12 + ...-validation-rule-copy-save-refusal.test.ts | 8 +- .../protocol-view-identity-overlay.test.ts | 16 ++ ...rotocol-writepath-object-ownership.test.ts | 18 +- .../publish-meta-response-conformance.test.ts | 13 +- .../save-meta-response-conformance.test.ts | 23 +- .../meta-diff-default-range-labels.test.ts | 5 +- ...eta-draft-head-package-inheritance.test.ts | 22 +- .../meta-draft-read-author-exemption.test.ts | 5 +- .../src/meta-draft-read-builder-gate.test.ts | 5 +- .../meta-flow-save-retired-spelling.test.ts | 5 +- .../meta-history-diff-authoring-door.test.ts | 5 +- .../src/meta-item-publish-version-pin.test.ts | 5 +- .../src/meta-item-version-token-occ.test.ts | 5 +- .../rest/src/meta-object-owd-gate.test.ts | 9 +- .../src/meta-page-record-no-component.test.ts | 5 +- ...meta-view-audience-save-round-trip.test.ts | 5 +- .../rest/src/meta-view-chart-binding.test.ts | 5 +- .../src/meta-view-overlay-options-bag.test.ts | 5 +- .../src/meta-write-actor-identity.test.ts | 5 +- .../src/public-form-routes.stored-row.test.ts | 12 +- .../public-form-two-type-withdrawal.test.ts | 15 +- .../rest-meta-save-receipt-envelope.test.ts | 14 +- ...server-meta-history-diff-org-scope.test.ts | 25 +- .../rest-server-meta-read-org-scope.test.ts | 25 +- ...tadata-mutation-resync.integration.test.ts | 17 +- ...r-anonymous-floor.hono.integration.test.ts | 5 +- ...-plugin.anonymous-gate.integration.test.ts | 57 ++--- .../domains/actions-disabled-package.test.ts | 10 +- ...automation-authoring-doors-durable.test.ts | 36 +-- .../automation-body-validation.test.ts | 23 +- ...omation-flow-credential-projection.test.ts | 11 +- ...tomation-flow-door-package-address.test.ts | 64 ++++- .../automation-flow-save-actor.test.ts | 25 +- ...utomation-notify-slack-composition.test.ts | 8 +- .../automation-packaged-base-lock.test.ts | 16 +- .../automation-put-post-error-parity.test.ts | 43 ++-- .../automation-register-error-class.test.ts | 16 +- .../automation-tenant-authored-write.test.ts | 18 +- .../automation-toggle-deny-message.test.ts | 18 +- ...automation-walled-definition-write.test.ts | 5 +- .../automation-write-capability-gate.test.ts | 30 +-- ...tomation-write-doors-durable-34145.test.ts | 9 +- .../domains/field-error-code-catalog.test.ts | 8 +- .../mcp-package-object-discovery.test.ts | 16 +- .../domains/meta-app-package-id-key.test.ts | 6 +- ...e-save-dependent-only-member-35524.test.ts | 5 +- ...ironment-action-other-object-33904.test.ts | 9 + .../domains/meta-layers-draft-layer.test.ts | 10 +- .../src/domains/meta-package-all-fold.test.ts | 27 ++- .../src/domains/meta-save-actor.test.ts | 12 +- .../meta-save-preconditions-parity.test.ts | 13 +- .../meta-save-user-text-locale.test.ts | 11 +- .../hook-handler-package-scope.pin.test.ts | 16 +- packages/runtime/src/http-dispatcher.test.ts | 16 +- .../mcp-record-context-tools-bridge.test.ts | 12 +- .../src/meta-compound-arity-mint-door.test.ts | 7 +- .../src/meta-field-overlay-lock.test.ts | 9 +- .../src/meta-managed-content-seal.test.ts | 9 +- .../src/meta-overlay-read-your-writes.test.ts | 34 ++- .../src/meta-sharing-rule-door.test.ts | 8 +- .../runtime/src/meta-write-org-scope.test.ts | 45 ++-- ...licate-adopt-org-scope.integration.test.ts | 13 +- ...-runtime-owner-refusal.integration.test.ts | 10 +- .../standalone-stack-hydrate-metadata.test.ts | 32 ++- ...-stack-security-catalog-one-holder.test.ts | 15 +- .../stored-metadata-body-boundary.pin.test.ts | 18 +- ...tored-metadata-reader-contexts.pin.test.ts | 17 +- 175 files changed, 2499 insertions(+), 1045 deletions(-) diff --git a/packages/cli/src/commands/meta/delete-reset-carriers.test.ts b/packages/cli/src/commands/meta/delete-reset-carriers.test.ts index 0d594069580..93c00d5a2f9 100644 --- a/packages/cli/src/commands/meta/delete-reset-carriers.test.ts +++ b/packages/cli/src/commands/meta/delete-reset-carriers.test.ts @@ -433,17 +433,20 @@ describe('[#13024] the flags `os meta delete` declares', () => { // Part 2 — the real door: what `--if-match` actually does to a concurrent edit // --------------------------------------------------------------------------- +// [#38174] A package-less CREATE is refused (ADR-0070 D1): every item below is +// saved into the installed writable package `PKG`, and the command's delete +// naming no package addresses that one holder's row. describe('[#13024] `os meta delete --if-match` against the real reset door', () => { it('UNPINNED (the only reset this command could express before): the stale reset SUCCEEDS and the row is gone', async () => { const { engine, client, deleteRequests, wire } = await bootDoor(); // Author A writes, and reads back the OCC token the pin echoes. - const first: any = await client.meta.saveItem('view', 'race_probe', VIEW('race_probe', 'A')); + const first: any = await client.meta.saveItem('view', 'race_probe', VIEW('race_probe', 'A'), { packageId: PKG }); const staleToken = first.version; expect(typeof staleToken).toBe('string'); // Author B edits the same item. A's token is now stale. - const second: any = await client.meta.saveItem('view', 'race_probe', VIEW('race_probe', 'B')); + const second: any = await client.meta.saveItem('view', 'race_probe', VIEW('race_probe', 'B'), { packageId: PKG }); expect(second.version).not.toBe(staleToken); expect(await overlayRows(engine, 'race_probe')).toHaveLength(1); @@ -471,9 +474,9 @@ describe('[#13024] `os meta delete --if-match` against the real reset door', () it('PINNED with a STALE version: the command FAILS with the conflict, and the other author\'s row survives', async () => { const { engine, client, deleteRequests, wire } = await bootDoor(); - const first: any = await client.meta.saveItem('view', 'race_probe', VIEW('race_probe', 'A')); + const first: any = await client.meta.saveItem('view', 'race_probe', VIEW('race_probe', 'A'), { packageId: PKG }); const staleToken = first.version; - const second: any = await client.meta.saveItem('view', 'race_probe', VIEW('race_probe', 'B')); + const second: any = await client.meta.saveItem('view', 'race_probe', VIEW('race_probe', 'B'), { packageId: PKG }); expect(second.version).not.toBe(staleToken); const run = await runCli(['view', 'race_probe', '--if-match', staleToken]); @@ -512,7 +515,7 @@ describe('[#13024] `os meta delete --if-match` against the real reset door', () // The other half of the pin — it refuses a stale write, not every write. // Without this, "always 409" would pass the case above. const { engine, client } = await bootDoor(); - const saved: any = await client.meta.saveItem('view', 'fresh_probe', VIEW('fresh_probe', 'A')); + const saved: any = await client.meta.saveItem('view', 'fresh_probe', VIEW('fresh_probe', 'A'), { packageId: PKG }); const run = await runCli(['view', 'fresh_probe', '--if-match', saved.version]); expect(run.exitCode).toBe(0); @@ -522,8 +525,8 @@ describe('[#13024] `os meta delete --if-match` against the real reset door', () it('`--format json` reports the pinned refusal in the machine-readable envelope too', async () => { const { engine, client } = await bootDoor(); - const first: any = await client.meta.saveItem('view', 'json_probe', VIEW('json_probe', 'A')); - await client.meta.saveItem('view', 'json_probe', VIEW('json_probe', 'B')); + const first: any = await client.meta.saveItem('view', 'json_probe', VIEW('json_probe', 'A'), { packageId: PKG }); + await client.meta.saveItem('view', 'json_probe', VIEW('json_probe', 'B'), { packageId: PKG }); const run = await runCli(['view', 'json_probe', '--format', 'json', '--if-match', first.version]); expect(run.exitCode).toBe(1); @@ -550,8 +553,8 @@ describe('[#13024] `os meta delete --draft` against the real reset door', () => const { engine, client, deleteRequests, wire } = await bootDoor(); // A published overlay, then a pending draft on top of it. - await client.meta.saveItem('view', 'draft_probe', VIEW('draft_probe', 'published')); - await client.meta.saveItem('view', 'draft_probe', VIEW('draft_probe', 'pending'), { mode: 'draft' }); + await client.meta.saveItem('view', 'draft_probe', VIEW('draft_probe', 'published'), { packageId: PKG }); + await client.meta.saveItem('view', 'draft_probe', VIEW('draft_probe', 'pending'), { mode: 'draft', packageId: PKG }); const before = await overlayRows(engine, 'draft_probe'); expect(before).toHaveLength(2); expect(before.map((r: any) => r.state).sort()).toEqual(['active', 'draft']); @@ -593,8 +596,8 @@ describe('[#13024] `os meta delete --draft` against the real reset door', () => it('both carriers at once: pinned AND narrow, without disturbing either', async () => { const { engine, client, deleteRequests, wire } = await bootDoor(); - await client.meta.saveItem('view', 'both_probe', VIEW('both_probe', 'published')); - const draft: any = await client.meta.saveItem('view', 'both_probe', VIEW('both_probe', 'pending'), { mode: 'draft' }); + await client.meta.saveItem('view', 'both_probe', VIEW('both_probe', 'published'), { packageId: PKG }); + const draft: any = await client.meta.saveItem('view', 'both_probe', VIEW('both_probe', 'pending'), { mode: 'draft', packageId: PKG }); const run = await runCli(['view', 'both_probe', '--draft', '--if-match', draft.version]); expect(run.exitCode).toBe(0); @@ -618,7 +621,7 @@ describe('[#13024] `os meta delete --draft` against the real reset door', () => describe('[#13024] an empty `--if-match` is refused, never silently downgraded', () => { it('refuses BEFORE the client is built — nothing reaches the door', async () => { const { engine, client, deleteRequests } = await bootDoor(); - await client.meta.saveItem('view', 'empty_pin', VIEW('empty_pin', 'A')); + await client.meta.saveItem('view', 'empty_pin', VIEW('empty_pin', 'A'), { packageId: PKG }); const requestsBefore = deleteRequests.length; stub.createCalls = 0; @@ -649,7 +652,7 @@ describe('[#13024] an empty `--if-match` is refused, never silently downgraded', it('a whitespace-only pin is refused the same way', async () => { const { engine, client, deleteRequests } = await bootDoor(); - await client.meta.saveItem('view', 'blank_pin', VIEW('blank_pin', 'A')); + await client.meta.saveItem('view', 'blank_pin', VIEW('blank_pin', 'A'), { packageId: PKG }); const requestsBefore = deleteRequests.length; const run = await runCli(['view', 'blank_pin', '--if-match', ' ']); @@ -672,7 +675,7 @@ describe('[#13024] an empty `--if-match` is refused, never silently downgraded', const { client, wire } = await bootDoor(); // Surrounding whitespace inside a real token is the door's business, not // this command's: `DeleteMetaItemOptions.ifMatch` says echo it verbatim. - await client.meta.saveItem('view', 'verbatim_probe', VIEW('verbatim_probe', 'A')); + await client.meta.saveItem('view', 'verbatim_probe', VIEW('verbatim_probe', 'A'), { packageId: PKG }); const token = ' sha256:deadbeef '; await runCli(['view', 'verbatim_probe', '--if-match', token]); const sent = wire.filter((w) => w.method === 'DELETE').at(-1)!; @@ -704,7 +707,7 @@ describe('[#13024] an empty `--if-match` is refused, never silently downgraded', describe('[#13024] the CLI\'s option bag behaves identically through both SDK twins', () => { it('the command reaches the UNSCOPED twin — stated as a measurement, not an assumption', async () => { const { client, wire } = await bootDoor(); - await client.meta.saveItem('view', 'mount_probe', VIEW('mount_probe', 'A')); + await client.meta.saveItem('view', 'mount_probe', VIEW('mount_probe', 'A'), { packageId: PKG }); await runCli(['view', 'mount_probe', '--draft']); const sent = wire.filter((w) => w.method === 'DELETE').at(-1)!; expect(sent.pathname).toBe('/api/v1/meta/view/mount_probe'); @@ -715,8 +718,8 @@ describe('[#13024] the CLI\'s option bag behaves identically through both SDK tw const { engine, client, deleteRequests } = await bootDoor(); const scoped = client.environment('env-13024').meta; - const first: any = await scoped.saveItem('view', 'scoped_race', VIEW('scoped_race', 'A')); - await scoped.saveItem('view', 'scoped_race', VIEW('scoped_race', 'B')); + const first: any = await scoped.saveItem('view', 'scoped_race', VIEW('scoped_race', 'A'), { packageId: PKG }); + await scoped.saveItem('view', 'scoped_race', VIEW('scoped_race', 'B'), { packageId: PKG }); // The bag the CLI builds for `--if-match `, handed to declaration #2. const options = metaDeleteOptions({ 'if-match': first.version }); @@ -734,8 +737,8 @@ describe('[#13024] the CLI\'s option bag behaves identically through both SDK tw const { engine, client, deleteRequests } = await bootDoor(); const scoped = client.environment('env-13024').meta; - await scoped.saveItem('view', 'scoped_draft', VIEW('scoped_draft', 'published')); - await scoped.saveItem('view', 'scoped_draft', VIEW('scoped_draft', 'pending'), { mode: 'draft' }); + await scoped.saveItem('view', 'scoped_draft', VIEW('scoped_draft', 'published'), { packageId: PKG }); + await scoped.saveItem('view', 'scoped_draft', VIEW('scoped_draft', 'pending'), { mode: 'draft', packageId: PKG }); const options = metaDeleteOptions({ draft: true }); const discarded: any = await scoped.deleteItem('view', 'scoped_draft', options); diff --git a/packages/cli/src/commands/meta/register-draft.test.ts b/packages/cli/src/commands/meta/register-draft.test.ts index 256293f7954..68f8cebbf9c 100644 --- a/packages/cli/src/commands/meta/register-draft.test.ts +++ b/packages/cli/src/commands/meta/register-draft.test.ts @@ -453,6 +453,15 @@ describe('[#34777] `os meta register --mode draft` against the real save door', it('UNFLAGGED and `--mode publish`: no query string, an active row, and no draft — the request this command always sent', async () => { const { engine, client, saveRequests, wire } = await bootDoor(); + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the two loose + // rows are seeded directly, and the unflagged / `--mode publish` registers + // run in place over them. + for (const name of ['plain_view', 'published_view']) { + await engine.insert('sys_metadata', { + type: 'view', name, state: 'active', package_id: null, + metadata: JSON.stringify(VIEW(name, 'Seeded')), + }, { context: { isSystem: true } }); + } const plain = await runCli(['view', '--data', dataFile(VIEW('plain_view', 'P'))]); expect(plain.exitCode).toBe(0); diff --git a/packages/cli/src/commands/meta/register-force.test.ts b/packages/cli/src/commands/meta/register-force.test.ts index 482e85bdb2c..41e827c8654 100644 --- a/packages/cli/src/commands/meta/register-force.test.ts +++ b/packages/cli/src/commands/meta/register-force.test.ts @@ -238,6 +238,14 @@ async function bootDoor() { engine.registry.registerObject(SysMetadataObject as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataHistoryObject as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataAuditObject as any, TEST_PACKAGE_ID); + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the item the + // command re-registers is first saved into this installed writable package, + // as `register-package.test.ts` installs its packages; the command's + // package-less re-register then addresses that one holder's row. + engine.registry.installPackage( + { id: PKG, name: PKG, version: '1.0.0', dependencies: { [TEST_PACKAGE_ID]: '*' } } as any, + 'authored', + ); await engine.syncSchemas(); const protocol: any = new ObjectStackProtocolImplementation(engine as any); @@ -339,7 +347,7 @@ describe('[#23480] the `--force` flag `os meta register` declares', () => { describe('[#23480] `os meta register --force` against the real save door', () => { it('UNFLAGGED, a field removed: refused 409 DESTRUCTIVE_CHANGE, the server message verbatim plus a hint naming --force, and nothing is written', async () => { const { engine, client, saveRequests, wire } = await bootDoor(); - await client.meta.saveItem('object', 'probe_obj', PROBE('probe_obj', { title: TITLE, note: NOTE })); + await client.meta.saveItem('object', 'probe_obj', PROBE('probe_obj', { title: TITLE, note: NOTE }), { packageId: PKG }); const before = await storedBody(engine, 'probe_obj'); expect(Object.keys(before.fields).sort()).toEqual(['note', 'title']); @@ -372,7 +380,7 @@ describe('[#23480] `os meta register --force` against the real save door', () => it('`--force`, the same re-register: `?force=true` on the wire, and the save lands without the field', async () => { const { engine, client, saveRequests, wire } = await bootDoor(); - await client.meta.saveItem('object', 'probe_obj', PROBE('probe_obj', { title: TITLE, note: NOTE })); + await client.meta.saveItem('object', 'probe_obj', PROBE('probe_obj', { title: TITLE, note: NOTE }), { packageId: PKG }); const run = await runCli(['object', '--data', dataFile(PROBE('probe_obj', { title: TITLE })), '--force']); @@ -388,8 +396,8 @@ describe('[#23480] `os meta register --force` against the real save door', () => it('`--force` on a NON-destructive re-register lands exactly as the same re-register without it', async () => { const { engine, client, saveRequests } = await bootDoor(); const seed = { title: TITLE, note: NOTE }; - await client.meta.saveItem('object', 'plain_obj', PROBE('plain_obj', seed)); - await client.meta.saveItem('object', 'forced_obj', PROBE('forced_obj', seed)); + await client.meta.saveItem('object', 'plain_obj', PROBE('plain_obj', seed), { packageId: PKG }); + await client.meta.saveItem('object', 'forced_obj', PROBE('forced_obj', seed), { packageId: PKG }); const grown = { title: TITLE, note: NOTE, extra: EXTRA }; const plainRun = await runCli(['object', '--data', dataFile(PROBE('plain_obj', grown))]); diff --git a/packages/cli/src/commands/migrate/meta-stored-legacy-organization.integration.test.ts b/packages/cli/src/commands/migrate/meta-stored-legacy-organization.integration.test.ts index e638d64e109..d7f3f98626d 100644 --- a/packages/cli/src/commands/migrate/meta-stored-legacy-organization.integration.test.ts +++ b/packages/cli/src/commands/migrate/meta-stored-legacy-organization.integration.test.ts @@ -241,9 +241,17 @@ async function onCeremonyBoot(db: string, fn: (kernel: { getService(name: str } } -/** The ceremony's `door.save` (`protocol.saveMetaItem`, no `source`): `null`, or what it threw. */ +/** + * The ceremony's `door.save` (`protocol.saveMetaItem`, no `source`): `null`, or what it threw. + * [#38174] As the template promotion calls it: a `LEFT_LOOSE` target, so the + * save states the ceremony's package-less create provenance (the kernel's + * fifth exemption from the WRITABLE_PACKAGE_REQUIRED refusal). + */ const doorSave = (kernel: { getService(name: string): any }, type: string, name: string, item: unknown) => - kernel.getService('protocol').saveMetaItem({ type, name, item, actor: 'os migrate organization-ownership' }) + kernel.getService('protocol').saveMetaItem({ + type, name, item, actor: 'os migrate organization-ownership', + packagelessCreateProvenance: 'organization-ownership-ceremony', + }) .then(() => null, (error: unknown) => error); async function saveTemplateOnCeremonyBoot(db: string, subject: string): Promise { diff --git a/packages/cli/test/rls-policy-authoring-admission.test.ts b/packages/cli/test/rls-policy-authoring-admission.test.ts index 9fe07e24e6a..5c7c708c605 100644 --- a/packages/cli/test/rls-policy-authoring-admission.test.ts +++ b/packages/cli/test/rls-policy-authoring-admission.test.ts @@ -78,6 +78,9 @@ const permissionSet = (using: string, policy: Record = { operat const RLS = (f: { rule: string }) => f.rule.startsWith('rls-predicate-'); +/** The writable package the runtime door saves into ([#38174]); the CLI door's app id. */ +const RLS_PKG = 'com.example.rls'; + /** `os validate` step 3, in process — see the file header. */ function cliDoor(using: string, set = permissionSet(using)): AuthoringFinding[] { const config = { @@ -120,6 +123,13 @@ async function runtimeHost(services: () => Map = () => new Map( engine.registry.registerObject(structuredClone(obj) as never, 'objectstack-test'); } await engine.syncSchemas(); + // [#38174] A package-less CREATE is refused (ADR-0070 D1), so the runtime + // door saves into a writable package the registry holds — the same app id + // the CLI door validates — depending on the package holding the objects. + engine.registry.installPackage( + { id: RLS_PKG, name: RLS_PKG, version: '1.0.0', dependencies: { 'objectstack-test': '*' } } as never, + 'authored' as never, + ); return { engine, protocol: new ObjectStackProtocolImplementation(engine, services as () => Map, 'env_test') }; } @@ -137,7 +147,7 @@ async function runtimeDoor( ): Promise { const { protocol } = await runtimeHost(services); try { - await protocol.saveMetaItem({ type: 'permission', name: 'sales', item: set }); + await protocol.saveMetaItem({ type: 'permission', name: 'sales', item: set, packageId: RLS_PKG }); return { accepted: true, issues: [] }; } catch (err) { const e = err as { code?: string; status?: number; issues?: SaveOutcome['issues'] }; diff --git a/packages/cli/test/security-catalog-echo-env-kernel.integration.test.ts b/packages/cli/test/security-catalog-echo-env-kernel.integration.test.ts index 582ad941903..121fb4aff94 100644 --- a/packages/cli/test/security-catalog-echo-env-kernel.integration.test.ts +++ b/packages/cli/test/security-catalog-echo-env-kernel.integration.test.ts @@ -149,6 +149,17 @@ function scenario(kind: Kind) { await protocol.saveMetaItem({ type: 'permission', name: PKG_SET, item: set(PKG_SET), packageId: RUNTIME_PKG, mode: 'draft' }); const published = await protocol.publishPackageDrafts({ packageId: RUNTIME_PKG, actor: 'system' }); expect(published, JSON.stringify(published)).toMatchObject({ outcome: 'published', failed: [] }); + // [#38174] A package-less CREATE is refused (ADR-0070 D1), so each + // no-package item is first held by an engine-seeded loose row (a + // placeholder body, as a pre-ADR-0070 row would be), and the metadata + // door's save — the path under test — writes its real body over it. + const seedLoose = (type: string, name: string) => ql.insert('sys_metadata', { + type, name, state: 'active', package_id: null, + metadata: JSON.stringify({ name, label: 'Seeded loose row' }), + }, SYS); + await seedLoose('permission', LOOSE_SET); + await seedLoose('position', POSITION); + if (kind === 'environment') await seedLoose('position', STACK_POSITION); await protocol.saveMetaItem({ type: 'permission', name: LOOSE_SET, item: { ...set(LOOSE_SET), isDefault: false } }); await protocol.saveMetaItem({ type: 'position', name: POSITION, item: { name: POSITION, label: 'Echo position', permissionSets: [DECLARED_SET] }, diff --git a/packages/metadata-protocol/src/protocol.active-save-namespace-prefix.test.ts b/packages/metadata-protocol/src/protocol.active-save-namespace-prefix.test.ts index d65505f8a66..d18050c7ec3 100644 --- a/packages/metadata-protocol/src/protocol.active-save-namespace-prefix.test.ts +++ b/packages/metadata-protocol/src/protocol.active-save-namespace-prefix.test.ts @@ -226,6 +226,18 @@ describe('[#24547 · ADR-0129 D2] the active save door refuses an object without it('control: a save naming no package (and resolving to none) saves the unprefixed name', async () => { const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + // [#38174] a package-less CREATE is refused (ADR-0070 D1): the loose + // row is seeded directly, and the package-less save runs in place. + await engine.insert('sys_metadata', { + type: 'object', + name: 'v1_report', + organization_id: null, + package_id: null, + state: 'active', + metadata: JSON.stringify(objectBody('v1_report', 'Seeded')), + checksum: 'sha256:stored', + version: 1, + }); await protocol.saveMetaItem({ type: 'object', @@ -234,6 +246,7 @@ describe('[#24547 · ADR-0129 D2] the active save door refuses an object without }); expect(rowsFor(rows, 'v1_report')).toEqual([{ state: 'active', package_id: null }]); + expect(JSON.parse(Array.from(rows.values()).find((r) => r.name === 'v1_report')!.metadata).label).toBe('Object v1_report'); }); it('judges a package-less publish save against the namespaced package it resolves into', async () => { diff --git a/packages/metadata-protocol/src/protocol.adr0005-org-override-rollback.test.ts b/packages/metadata-protocol/src/protocol.adr0005-org-override-rollback.test.ts index b8570c69922..66f31adbd84 100644 --- a/packages/metadata-protocol/src/protocol.adr0005-org-override-rollback.test.ts +++ b/packages/metadata-protocol/src/protocol.adr0005-org-override-rollback.test.ts @@ -117,6 +117,9 @@ interface Row { metadata: string; } +/** The writable package a brand-new item is saved into. */ +const TEST_PKG = 'test_pkg'; + function makeStubEngine(artifacts: Array<{ type: string; name: string }> = []) { const rows = new Map(); let nextId = 0; @@ -159,6 +162,9 @@ function makeStubEngine(artifacts: Array<{ type: string; name: string }> = []) { // name is shipped by a code package (`_packageId` provenance). getArtifactItem: (type: string, name: string) => artifactKeys.has(`${type}|${name}`) ? { name, _packageId: 'showcase' } : undefined, + // [#38174] installs {@link TEST_PKG}: a new item is saved into a + // writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), }, }; return { engine, rows }; @@ -318,12 +324,15 @@ describe('#6483 — the nine ADR-0005 divergences: allowEnvironmentOverlay rolle // boot never reads, so the app went back to hidden on restart). // Not papered over here — pinning a green org-scoped `app` write // would be pinning that phantom. + // [#38174] A new item is saved into a writable package (ADR-0070 D1); + // the row stays env-wide. const { protocol } = makeProtocol([], 'env_prod'); const result = await protocol.saveMetaItem({ type, name: 'probe_item', item: BODIES[type], + packageId: TEST_PKG, }); expect(result.success).toBe(true); diff --git a/packages/metadata-protocol/src/protocol.audit-field-governance.test.ts b/packages/metadata-protocol/src/protocol.audit-field-governance.test.ts index 8931bd1e8bc..ebccd328b2b 100644 --- a/packages/metadata-protocol/src/protocol.audit-field-governance.test.ts +++ b/packages/metadata-protocol/src/protocol.audit-field-governance.test.ts @@ -82,6 +82,9 @@ function keyOf(w: Record) { return `${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}|${w.package_id ?? '__nopkg__'}`; } +/** [#38174] An installed writable package: a save of a NEW item names one (ADR-0070 D1). */ +const TEST_PKG = 'test_pkg'; + function makeStubEngine() { const rows = new Map(); let nextId = 0; @@ -128,7 +131,8 @@ function makeStubEngine() { getItem: () => undefined, registerItem: () => {}, registerObject: () => {}, - getPackage: () => undefined, + // [#38174] the installed writable package a create names (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), }, }; return { engine, rows }; @@ -232,7 +236,7 @@ async function seed(mode: 'active' | 'draft', name: string) { const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); await protocol.saveMetaItem({ - type: 'object', name, item: artifactObject(name), + type: 'object', name, item: artifactObject(name), packageId: TEST_PKG, ...(mode === 'draft' ? { mode: 'draft' as const } : {}), }); return { protocol, rows }; @@ -292,7 +296,7 @@ describe('[#4513] the /meta read surface agrees with the enforced write behaviou ...artifactObject('legacy_ledger'), systemFields: { audit: false }, }; - await protocol.saveMetaItem({ type: 'object', name: 'legacy_ledger', item: optedOut }); + await protocol.saveMetaItem({ type: 'object', name: 'legacy_ledger', item: optedOut, packageId: TEST_PKG }); const served: any = (await protocol.getMetaItem({ type: 'object', name: 'legacy_ledger' })).item; expect(served.fields.created_at.readonly).toBe(false); diff --git a/packages/metadata-protocol/src/protocol.cached-item-last-modified.test.ts b/packages/metadata-protocol/src/protocol.cached-item-last-modified.test.ts index 4981135a7b2..de70e77866c 100644 --- a/packages/metadata-protocol/src/protocol.cached-item-last-modified.test.ts +++ b/packages/metadata-protocol/src/protocol.cached-item-last-modified.test.ts @@ -96,12 +96,17 @@ function makeStubEngine(code: Record = {}) { getItem: (type: string, name: string) => (type === 'object' ? code[name] : undefined), registerItem: () => {}, registerObject: () => {}, - getPackage: () => undefined, + // [#38174] installs {@link TEST_PKG}: a new item is saved into a + // writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), }, }; return { engine, rows }; } +/** The writable package each case's first save creates its item in. */ +const TEST_PKG = 'test_pkg'; + /** A runtime-created business object (no artifact), so the save door writes a stored row. */ const authored = (name: string, label = 'Invoice') => ({ name, @@ -130,7 +135,7 @@ describe('[#31196] the cached by-name read answers the item\'s own change time, const { engine } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); vi.setSystemTime(new Date(T_SAVE)); - await protocol.saveMetaItem({ type: 'object', name: 'invoice', item: authored('invoice') }); + await protocol.saveMetaItem({ type: 'object', name: 'invoice', item: authored('invoice'), packageId: TEST_PKG }); vi.setSystemTime(new Date(T_READ_1)); const first = await protocol.getMetaItemCached({ type: 'object', name: 'invoice' }); @@ -150,7 +155,7 @@ describe('[#31196] the cached by-name read answers the item\'s own change time, const { engine } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); vi.setSystemTime(new Date(T_SAVE)); - await protocol.saveMetaItem({ type: 'object', name: 'invoice', item: authored('invoice') }); + await protocol.saveMetaItem({ type: 'object', name: 'invoice', item: authored('invoice'), packageId: TEST_PKG }); vi.setSystemTime(new Date(T_READ_1)); const before = await protocol.getMetaItemCached({ type: 'object', name: 'invoice' }); @@ -195,7 +200,7 @@ describe('[#31196] the cached by-name read answers the item\'s own change time, const { engine } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); vi.setSystemTime(new Date(T_SAVE)); - await protocol.saveMetaItem({ type: 'object', name: 'invoice', item: authored('invoice') }); + await protocol.saveMetaItem({ type: 'object', name: 'invoice', item: authored('invoice'), packageId: TEST_PKG }); const envelope = await protocol.getMetaItem({ type: 'object', name: 'invoice' }); expect(JSON.stringify(envelope)).not.toContain(T_SAVE); diff --git a/packages/metadata-protocol/src/protocol.capability-write-door.test.ts b/packages/metadata-protocol/src/protocol.capability-write-door.test.ts index ac0a18d7b23..476423798ad 100644 --- a/packages/metadata-protocol/src/protocol.capability-write-door.test.ts +++ b/packages/metadata-protocol/src/protocol.capability-write-door.test.ts @@ -82,6 +82,8 @@ interface Row { metadata: string; } +const TEST_PKG = 'test_pkg'; + function makeStubEngine( registeredTypes: string[] = [], packageHeld: Array<{ catalogType: string; name: string; packageIds: string[] }> = [], @@ -135,6 +137,8 @@ function makeStubEngine( // The registry's own package-held reading (`@objectstack/objectql` // `packageHeldSecurityCatalogNames`), which the save door asks. packageHeldSecurityCatalogNames: () => packageHeld, + // [#38174] a new item is saved into an installed writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), }, }; return { engine, rows }; @@ -204,7 +208,7 @@ describe('#5961 / #35157 — capability: runtime-creatable, schema-judged, one n // The control for the case above, and the acceptance criterion of // #35157: an unmanaged copy writes its capabilities through this door. const { protocol, rows } = makeProtocol([], 'env_prod'); - const result = await protocol.saveMetaItem({ type: 'capability', name: 'billing.refund', item: CAPABILITY }); + const result = await protocol.saveMetaItem({ type: 'capability', name: 'billing.refund', packageId: TEST_PKG, item: CAPABILITY }); expect(result.success).toBe(true); expect(rows.size).toBe(1); }); @@ -256,16 +260,16 @@ describe('#5961 / #35157 — capability: runtime-creatable, schema-judged, one n const { protocol, rows } = makeProtocol([], 'env_prod', [ { catalogType: 'permission', name: 'billing.refund', packageIds: ['com.acme.billing'] }, ]); - const result = await protocol.saveMetaItem({ type: 'capability', name: 'billing.refund', item: CAPABILITY }); + const result = await protocol.saveMetaItem({ type: 'capability', name: 'billing.refund', packageId: TEST_PKG, item: CAPABILITY }); expect(result.success).toBe(true); expect(rows.size).toBe(1); }); it('re-saving the environment\'s own capability is untouched — the owner meets itself', async () => { const { protocol, rows } = makeProtocol([], 'env_prod'); - await protocol.saveMetaItem({ type: 'capability', name: 'billing.refund', item: CAPABILITY }); + await protocol.saveMetaItem({ type: 'capability', name: 'billing.refund', packageId: TEST_PKG, item: CAPABILITY }); const again = await protocol.saveMetaItem({ - type: 'capability', name: 'billing.refund', item: { ...CAPABILITY, label: 'Refund payments' }, + type: 'capability', name: 'billing.refund', packageId: TEST_PKG, item: { ...CAPABILITY, label: 'Refund payments' }, }); expect(again.success).toBe(true); expect(rows.size).toBe(1); diff --git a/packages/metadata-protocol/src/protocol.cbp-master-not-writable-refusal.test.ts b/packages/metadata-protocol/src/protocol.cbp-master-not-writable-refusal.test.ts index 3a297873742..5ef47025635 100644 --- a/packages/metadata-protocol/src/protocol.cbp-master-not-writable-refusal.test.ts +++ b/packages/metadata-protocol/src/protocol.cbp-master-not-writable-refusal.test.ts @@ -15,6 +15,8 @@ import { describe, expect, it } from 'vitest'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate, type EngineFindOneQueryInput } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from './protocol.js'; +const TEST_PKG = 'test_pkg'; + /** The engine surface the repository write path touches (as the container-issue-descent harness). */ function makeProtocol() { const rows = new Map>(); @@ -36,7 +38,8 @@ function makeProtocol() { assertEngineDeleteDispatch(opts); return { deleted: 0 }; }, - registry: { registerItem: () => {}, registerObject: () => {} }, + // [#38174] a create names an installed writable package (ADR-0070 D1). + registry: { registerItem: () => {}, registerObject: () => {}, getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined) }, }; const protocol: any = new ObjectStackProtocolImplementation(engine, () => new Map()); return { protocol, rows }; @@ -69,7 +72,7 @@ describe('#25092 the save door refuses a controlled_by_parent detail whose one m const { protocol, rows } = makeProtocol(); const err = await rejection(protocol.saveMetaItem({ - type: 'object', name: 'work_order_item', item: detailWith(flags), + type: 'object', name: 'work_order_item', packageId: TEST_PKG, item: detailWith(flags), })); expect(err.code).toBe('INVALID_METADATA'); @@ -86,7 +89,7 @@ describe('#25092 the save door refuses a controlled_by_parent detail whose one m const { protocol, rows } = makeProtocol(); const result = await protocol.saveMetaItem({ - type: 'object', name: 'work_order_item', item: detailWith({}), + type: 'object', name: 'work_order_item', packageId: TEST_PKG, item: detailWith({}), }); expect(result.success).toBe(true); diff --git a/packages/metadata-protocol/src/protocol.cluster-mutation-fanout.test.ts b/packages/metadata-protocol/src/protocol.cluster-mutation-fanout.test.ts index 2819d4ba08d..f0e39ebe77d 100644 --- a/packages/metadata-protocol/src/protocol.cluster-mutation-fanout.test.ts +++ b/packages/metadata-protocol/src/protocol.cluster-mutation-fanout.test.ts @@ -90,6 +90,24 @@ function matchesWhere(r: Row, where: Record): boolean { return true; } +/** + * [#38174] A package-less CREATE is refused (ADR-0070 D1): a runtime-authored + * object is saved into this installed writable package. The cases that pin a + * PACKAGE-LESS row's address seed that loose row instead ({@link seedLooseObject}), + * and their package-less save runs in place. + */ +const TEST_PKG = 'test_pkg'; + +/** [#38174] A loose (package-less) object row, as the store writes it. */ +function seedLooseObject(store: ReturnType, name: string): void { + const row = { + type: 'object', name, organization_id: null, package_id: null, state: 'active', + metadata: JSON.stringify(objectBody(name, 'Seeded')), checksum: 'sha256:seeded', version: 1, + }; + store.nextId.value += 1; + store.rows.set(keyOf(row), { ...row, id: `r_${store.nextId.value}` }); +} + /** The SHARED database — what every replica of the deployment reads. */ function makeSharedStore() { return { @@ -231,7 +249,8 @@ function makeReplica(store: ReturnType) { listItems: () => [], getItem: () => undefined, getObject: () => undefined, - getPackage: () => undefined, + // [#38174] a new item is saved into an installed writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), getArtifactItem: () => undefined, }, }; @@ -307,7 +326,7 @@ describe('[#13331] ⭐ two-arm: peer registry convergence is the bridge’s doin const { writer, peer } = makeCluster({ attach: true }); const res = await writer.protocol.saveMetaItem({ - type: 'object', name: 'gadget', item: objectBody('gadget'), mode: 'publish', + type: 'object', name: 'gadget', packageId: TEST_PKG, item: objectBody('gadget'), mode: 'publish', }); expect(res.success).toBe(true); @@ -325,7 +344,7 @@ describe('[#13331] ⭐ two-arm: peer registry convergence is the bridge’s doin const { writer, peer } = makeCluster({ attach: false }); const res = await writer.protocol.saveMetaItem({ - type: 'object', name: 'gadget', item: objectBody('gadget'), mode: 'publish', + type: 'object', name: 'gadget', packageId: TEST_PKG, item: objectBody('gadget'), mode: 'publish', }); expect(res.success).toBe(true); await settle(); @@ -341,7 +360,8 @@ describe('[#13331] ⭐ two-arm: peer registry convergence is the bridge’s doin describe('[#13331] the payload is a signal, never content', () => { it('publishes the row ADDRESS only — no body rides the channel', async () => { - const { writer, published } = makeCluster({ attach: true }); + const { store, writer, published } = makeCluster({ attach: true }); + seedLooseObject(store, 'gadget'); await writer.protocol.saveMetaItem({ type: 'object', name: 'gadget', item: objectBody('gadget'), mode: 'publish', @@ -368,7 +388,7 @@ describe('[#13331] the payload is a signal, never content', () => { const { writer, peer, published } = makeCluster({ attach: true }); const res = await writer.protocol.saveMetaItem({ - type: 'object', name: 'gadget', item: objectBody('gadget'), mode: 'draft', + type: 'object', name: 'gadget', packageId: TEST_PKG, item: objectBody('gadget'), mode: 'draft', }); expect(res.success).toBe(true); await settle(); @@ -383,7 +403,7 @@ describe('[#13331] loopback and idempotency', () => { const { writer } = makeCluster({ attach: true }); await writer.protocol.saveMetaItem({ - type: 'object', name: 'gadget', item: objectBody('gadget'), mode: 'publish', + type: 'object', name: 'gadget', packageId: TEST_PKG, item: objectBody('gadget'), mode: 'publish', }); await settle(); @@ -395,7 +415,7 @@ describe('[#13331] loopback and idempotency', () => { it('duplicate delivery converges to the same state (at-least-once is harmless)', async () => { const { writer, peer, bus, published } = makeCluster({ attach: true }); await writer.protocol.saveMetaItem({ - type: 'object', name: 'gadget', item: objectBody('gadget'), mode: 'publish', + type: 'object', name: 'gadget', packageId: TEST_PKG, item: objectBody('gadget'), mode: 'publish', }); await vi.waitFor(() => expect(peer.registeredObjects).toEqual(['gadget'])); @@ -421,7 +441,7 @@ describe('[#13331] loopback and idempotency', () => { it('after detach, deliveries are no longer applied', async () => { const { writer, peer, bus, published } = makeCluster({ attach: true }); await writer.protocol.saveMetaItem({ - type: 'object', name: 'gadget', item: objectBody('gadget'), mode: 'publish', + type: 'object', name: 'gadget', packageId: TEST_PKG, item: objectBody('gadget'), mode: 'publish', }); await vi.waitFor(() => expect(peer.registeredObjects).toEqual(['gadget'])); @@ -437,7 +457,7 @@ describe('[#13331] delete fan-out — the peer heals from its own read', () => { it('a delete on the writer retires the peer’s registry entry', async () => { const { writer, peer } = makeCluster({ attach: true }); await writer.protocol.saveMetaItem({ - type: 'object', name: 'gadget', item: objectBody('gadget'), mode: 'publish', + type: 'object', name: 'gadget', packageId: TEST_PKG, item: objectBody('gadget'), mode: 'publish', }); await vi.waitFor(() => expect(peer.registeredObjects).toEqual(['gadget'])); @@ -454,10 +474,10 @@ describe('[#13331] delete fan-out — the peer heals from its own read', () => { it('a draft DISCARD leaves the peer’s active registration standing', async () => { const { writer, peer } = makeCluster({ attach: true }); await writer.protocol.saveMetaItem({ - type: 'object', name: 'gadget', item: objectBody('gadget'), mode: 'publish', + type: 'object', name: 'gadget', packageId: TEST_PKG, item: objectBody('gadget'), mode: 'publish', }); await writer.protocol.saveMetaItem({ - type: 'object', name: 'gadget', item: objectBody('gadget', 'Draft rename'), mode: 'draft', + type: 'object', name: 'gadget', packageId: TEST_PKG, item: objectBody('gadget', 'Draft rename'), mode: 'draft', }); await vi.waitFor(() => expect(peer.registeredObjects).toEqual(['gadget'])); @@ -474,7 +494,8 @@ describe('[#13331] delete fan-out — the peer heals from its own read', () => { describe('[#13331] listener replay — boot-cached consumers hear remote mutations', () => { it('the peer’s onMetadataMutation listeners receive the remote event, once, after convergence', async () => { - const { writer, peer } = makeCluster({ attach: true }); + const { store, writer, peer } = makeCluster({ attach: true }); + seedLooseObject(store, 'gadget'); const writerSeen: MetadataMutationEvent[] = []; const peerSeen: MetadataMutationEvent[] = []; writer.protocol.onMetadataMutation((evt: MetadataMutationEvent) => { writerSeen.push(evt); }); @@ -524,7 +545,7 @@ describe('[#31722] cluster.resync — the peer re-converges what a lost hint wou } const save = (replica: ReturnType, name: string, label?: string) => - replica.protocol.saveMetaItem({ type: 'object', name, item: objectBody(name, label), mode: 'publish' }); + replica.protocol.saveMetaItem({ type: 'object', name, packageId: TEST_PKG, item: objectBody(name, label), mode: 'publish' }); it('⭐ an object authored while the hint was lost is served by the peer after its resync', async () => { const { writer, peer, outage } = makeLossyCluster(); @@ -667,7 +688,8 @@ describe('[#31722] cluster.resync — the peer re-converges what a lost hint wou expect(report).toMatchObject({ rows: 0, deleted: 0, kept: 2 }); const lines = error.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('metadata.mutated resync')); expect(lines).toHaveLength(1); - expect(lines[0]).toContain('could not re-read 2 stored item(s) (object/gadget, object/widget)'); + // [#38174] The items are saved into `TEST_PKG`, so each address names its package. + expect(lines[0]).toContain(`could not re-read 2 stored item(s) (object/gadget (package '${TEST_PKG}'), object/widget (package '${TEST_PKG}'))`); } finally { error.mockRestore(); } @@ -692,7 +714,7 @@ describe('[#31722] cluster.resync — the peer re-converges what a lost hint wou it('CONTROL — no transport attached (a single node): the seam reads nothing and does nothing', async () => { const store = makeSharedStore(); const solo = makeReplica(store); - await solo.protocol.saveMetaItem({ type: 'object', name: 'gadget', item: objectBody('gadget'), mode: 'publish' }); + await solo.protocol.saveMetaItem({ type: 'object', name: 'gadget', packageId: TEST_PKG, item: objectBody('gadget'), mode: 'publish' }); solo.readFault.mode = 'all'; await expect(solo.protocol.resyncMetadataMutationPubSub()).resolves.toBeUndefined(); @@ -1016,7 +1038,8 @@ describe('[#32451] the peer converges a slotted item at the package the signal n }); it('the writer stamps the package its write resolved, on the local event and the wire alike', async () => { - const { writer, published } = makeCluster({ attach: true }); + const { store, writer, published } = makeCluster({ attach: true }); + seedLooseObject(store, 'gadget'); const seen: MetadataMutationEvent[] = []; writer.protocol.onMetadataMutation((evt: MetadataMutationEvent) => { seen.push({ ...evt }); }); vi.spyOn(writer.protocol, 'applyRegistryWriteThrough').mockResolvedValue(undefined); diff --git a/packages/metadata-protocol/src/protocol.code-defined-datasource-door.test.ts b/packages/metadata-protocol/src/protocol.code-defined-datasource-door.test.ts index 128dc927170..624c149bdf4 100644 --- a/packages/metadata-protocol/src/protocol.code-defined-datasource-door.test.ts +++ b/packages/metadata-protocol/src/protocol.code-defined-datasource-door.test.ts @@ -49,6 +49,11 @@ const CODE_DS = 'showcase_external'; const PACKAGE_ID = 'com.example.showcase'; /** A name no package declares: a runtime datasource. */ const RUNTIME_DS = 'dogfood_rt_21899'; +/** + * [#38174] The installed writable package a runtime datasource is saved into: + * a package-less create is refused (ADR-0070 D1). + */ +const TEST_PKG = 'test_pkg'; /** * What the two refusals say: the admin door's verdict as the first sentence, in @@ -198,6 +203,7 @@ function makeSession(opts: { // artifact-only lookup misses it, exactly as on a booted showcase. getArtifactItem: () => undefined, getAllPackages: () => opts.packages ?? [], + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), removeRuntimeShadow: () => false, removeOverlayEntry: () => {}, }, @@ -353,26 +359,26 @@ for (const { label, environmentId } of KERNELS) { it('control: a runtime datasource still saves and deletes through this door', async () => { const { protocol, rows } = session(); - const saved = await protocol.saveMetaItem({ type: 'datasource', name: RUNTIME_DS, item: body(RUNTIME_DS, 'Runtime') }); + const saved = await protocol.saveMetaItem({ type: 'datasource', name: RUNTIME_DS, packageId: TEST_PKG, item: body(RUNTIME_DS, 'Runtime') }); expect(saved).toMatchObject({ success: true }); expect(Array.from(rows.values()).filter((r) => r.name === RUNTIME_DS)).toHaveLength(1); - const updated = await protocol.saveMetaItem({ type: 'datasource', name: RUNTIME_DS, item: body(RUNTIME_DS, 'Runtime 2') }); + const updated = await protocol.saveMetaItem({ type: 'datasource', name: RUNTIME_DS, packageId: TEST_PKG, item: body(RUNTIME_DS, 'Runtime 2') }); expect(updated).toMatchObject({ success: true }); - const removed = await protocol.deleteMetaItem({ type: 'datasource', name: RUNTIME_DS }); + const removed = await protocol.deleteMetaItem({ type: 'datasource', name: RUNTIME_DS, packageId: TEST_PKG }); expect(removed).toMatchObject({ success: true, reset: true }); expect(Array.from(rows.values()).filter((r) => r.name === RUNTIME_DS)).toEqual([]); // A DELETE that removes nothing on a RUNTIME name keeps its no-op answer. - const none = await protocol.deleteMetaItem({ type: 'datasource', name: RUNTIME_DS }); + const none = await protocol.deleteMetaItem({ type: 'datasource', name: RUNTIME_DS, packageId: TEST_PKG }); expect(none).toMatchObject({ success: true, reset: false }); }); it('control: a runtime datasource whose body asserts `origin: code` is still a runtime datasource', async () => { const { protocol, rows } = session(); const saved = await protocol.saveMetaItem({ - type: 'datasource', name: RUNTIME_DS, item: { ...body(RUNTIME_DS, 'Runtime'), origin: 'code' }, + type: 'datasource', name: RUNTIME_DS, packageId: TEST_PKG, item: { ...body(RUNTIME_DS, 'Runtime'), origin: 'code' }, }); expect(saved).toMatchObject({ success: true }); expect(rows.size).toBe(1); @@ -398,7 +404,7 @@ for (const { label, environmentId } of KERNELS) { + 'See docs/adr/0062-external-datasource-runtime.md.', ); expect(rows.size).toBe(0); - const runtime = await protocol.saveMetaItem({ type: 'datasource', name: RUNTIME_DS, item: body(RUNTIME_DS, 'Hatch') }); + const runtime = await protocol.saveMetaItem({ type: 'datasource', name: RUNTIME_DS, packageId: TEST_PKG, item: body(RUNTIME_DS, 'Hatch') }); expect(runtime).toMatchObject({ success: true }); expect(rows.size).toBe(1); }); @@ -565,7 +571,7 @@ for (const { label, environmentId } of KERNELS) { it('control: a runtime datasource still saves with the set registered', async () => { const { protocol, rows } = session(); - const saved = await protocol.saveMetaItem({ type: 'datasource', name: RUNTIME_DS, item: body(RUNTIME_DS, 'Runtime') }); + const saved = await protocol.saveMetaItem({ type: 'datasource', name: RUNTIME_DS, packageId: TEST_PKG, item: body(RUNTIME_DS, 'Runtime') }); expect(saved).toMatchObject({ success: true }); expect(Array.from(rows.values()).filter((r) => r.name === RUNTIME_DS)).toHaveLength(1); }); diff --git a/packages/metadata-protocol/src/protocol.code-only-types.test.ts b/packages/metadata-protocol/src/protocol.code-only-types.test.ts index 9b29d585a63..8976288bcb9 100644 --- a/packages/metadata-protocol/src/protocol.code-only-types.test.ts +++ b/packages/metadata-protocol/src/protocol.code-only-types.test.ts @@ -197,6 +197,10 @@ const PROBES: Record }> = }, }; +/** [#38174] An installed writable package a create names, and the `task` object its items bind. */ +const TEST_PKG = 'test_pkg'; +const TASK_IN_TEST_PKG = { name: 'task', label: 'Task', _packageId: TEST_PKG, fields: { name: { name: 'name', type: 'text', label: 'Name' } } }; + function makeStubEngine(artifacts: Array<{ type: string; name: string }> = []) { const rows = new Map(); let nextId = 0; @@ -240,7 +244,10 @@ function makeStubEngine(artifacts: Array<{ type: string; name: string }> = []) { registry: { registerItem: () => {}, registerObject: () => {}, - listItems: () => [], + // [#38174] A create names an installed writable package (ADR-0070 + // D1), and an item bound to `task` is judged inside its closure. + listItems: (type: string) => (type === 'object' ? [TASK_IN_TEST_PKG] : []), + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), getItem: () => undefined, // `isArtifactBacked` prefers this lookup — a hit here means the // name is shipped by a code package (`_packageId` provenance). @@ -403,6 +410,7 @@ describe('code-only metadata types are refused on every kernel (#5086)', () => { const result = await protocol.saveMetaItem({ type: 'view', name: 'rc3_probe_view', + packageId: TEST_PKG, item: { name: 'rc3_probe_view', label: 'Probe', @@ -432,6 +440,7 @@ describe('code-only metadata types are refused on every kernel (#5086)', () => { const result = await protocol.saveMetaItem({ type: 'hook', name: 'rc3_probe_hook', + packageId: TEST_PKG, // [#21689] A body-carrying hook: the save door refuses a hook // with no `body` (it could never run), and this case measures // the code-only gate, not that refusal. @@ -454,6 +463,7 @@ describe('code-only metadata types are refused on every kernel (#5086)', () => { const result = await protocol.saveMetaItem({ type: 'webhook', name: 'rc3_probe_webhook', + packageId: TEST_PKG, item: { name: 'rc3_probe_webhook', label: 'Probe', object: 'task', triggers: ['create'], url: 'https://example.com/hook' }, }); expect(result.success).toBe(true); @@ -475,7 +485,7 @@ describe('code-only metadata types are refused on every kernel (#5086)', () => { // Only the gate is under test — a later stage may still object // to the body, but never with the code-only verdict. const err = await protocol - .saveMetaItem({ type, name: probe.name, item: probe.item }) + .saveMetaItem({ type, name: probe.name, item: probe.item, packageId: TEST_PKG }) .then(() => null, (e: any) => e); expect(err?.code).not.toBe('NOT_CREATABLE'); @@ -570,6 +580,7 @@ describe('code-only metadata types are refused on every kernel (#5086)', () => { const result = await protocol.saveMetaItem({ type, name: 'rc3_receipt_view', + packageId: TEST_PKG, item, }); @@ -602,6 +613,7 @@ describe('code-only metadata types are refused on every kernel (#5086)', () => { type, name: probe.name, item: probe.item, + packageId: TEST_PKG, }); expect(result.success).toBe(true); diff --git a/packages/metadata-protocol/src/protocol.container-issue-descent.test.ts b/packages/metadata-protocol/src/protocol.container-issue-descent.test.ts index bf6908b254d..ecc40998ce5 100644 --- a/packages/metadata-protocol/src/protocol.container-issue-descent.test.ts +++ b/packages/metadata-protocol/src/protocol.container-issue-descent.test.ts @@ -73,6 +73,8 @@ interface Row { const keyOf = (w: Record) => `${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}`; +const TEST_PKG = 'test_pkg'; + /** The engine surface the repository write path touches (as #5364's harness). */ function makeProtocol() { // ⚠️ Keyed BY TABLE. `find`/`findOne` below answer nothing, so this harness @@ -108,7 +110,8 @@ function makeProtocol() { assertEngineDeleteDispatch(opts); return { deleted: 0 }; }, - registry: { registerItem: () => {}, registerObject: () => {} }, + // [#38174] a create names an installed writable package (ADR-0070 D1). + registry: { registerItem: () => {}, registerObject: () => {}, getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined) }, }; const protocol: any = new ObjectStackProtocolImplementation(engine, () => new Map()); return { protocol, rows }; @@ -224,7 +227,7 @@ describe('#8783 the 422 an author actually receives', () => { const { protocol, rows } = makeProtocol(); const err = await rejection( - protocol.saveMetaItem({ type: 'object', name: 'contact', item: authoredObject('firstName') }), + protocol.saveMetaItem({ type: 'object', name: 'contact', packageId: TEST_PKG, item: authoredObject('firstName') }), ); // The ADR-0112 envelope, both halves. @@ -257,6 +260,7 @@ describe('#8783 the 422 an author actually receives', () => { const result = await protocol.saveMetaItem({ type: 'object', name: 'contact', + packageId: TEST_PKG, item: authoredObject('first_name'), }); diff --git a/packages/metadata-protocol/src/protocol.credential-channel.test.ts b/packages/metadata-protocol/src/protocol.credential-channel.test.ts index a261d4948d5..217275a154b 100644 --- a/packages/metadata-protocol/src/protocol.credential-channel.test.ts +++ b/packages/metadata-protocol/src/protocol.credential-channel.test.ts @@ -33,6 +33,7 @@ import { registerMetadataTypeRedactor } from '@objectstack/spec/kernel'; import { ObjectStackProtocolImplementation, type MetadataCredentialChannel } from './protocol.js'; +const TEST_PKG = 'test_pkg'; const V1 = 'pin-protocol-secret-v1-3f1a'; const V2 = 'pin-protocol-secret-v2-b07c'; const DRAFT = 'pin-protocol-secret-draft-77e2'; @@ -95,7 +96,8 @@ function makeEngine() { getItem: () => undefined, registerItem: () => {}, registerObject: () => {}, - getPackage: () => undefined, + // [#38174] a new item is saved into an installed writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), }, }; return { engine, rows, historyRows }; @@ -180,7 +182,7 @@ describe('[#20790] the save door stores the body the credential channel returns' const { channel, held } = makeChannel(); protocol.registerCredentialChannel('flows', channel); - await protocol.saveMetaItem({ type: 'flow', name: 'channel_intake', item: inbound(V1) }); + await protocol.saveMetaItem({ type: 'flow', name: 'channel_intake', packageId: TEST_PKG, item: inbound(V1) }); expect(held.get('channel_intake|active')).toBe(V1); expect(bodiesOf(rows)).toHaveLength(1); @@ -195,11 +197,11 @@ describe('[#20790] the save door stores the body the credential channel returns' const protocol = new ObjectStackProtocolImplementation(engine); const { channel, held, calls } = makeChannel(); protocol.registerCredentialChannel('flow', channel); - await protocol.saveMetaItem({ type: 'flow', name: 'channel_intake', item: inbound(V1) }); + await protocol.saveMetaItem({ type: 'flow', name: 'channel_intake', packageId: TEST_PKG, item: inbound(V1) }); // The served form round-trips: no secret in the body, none refused. await expect( - protocol.saveMetaItem({ type: 'flow', name: 'channel_intake', item: inbound(undefined, 'Edited') }), + protocol.saveMetaItem({ type: 'flow', name: 'channel_intake', packageId: TEST_PKG, item: inbound(undefined, 'Edited') }), ).resolves.toMatchObject({ success: true }); expect(calls).toContain('heldPaths:active'); expect(held.get('channel_intake|active')).toBe(V1); @@ -211,7 +213,7 @@ describe('[#20790] the save door stores the body the credential channel returns' protocol.registerCredentialChannel('flow', makeChannel({ refuse: true }).channel); const refusal = await protocol - .saveMetaItem({ type: 'flow', name: 'channel_intake', item: inbound(V1) }) + .saveMetaItem({ type: 'flow', name: 'channel_intake', packageId: TEST_PKG, item: inbound(V1) }) .then(() => undefined, (e: any) => e); expect(refusal?.code).toBe('SERVICE_UNAVAILABLE'); expect(refusal?.status).toBe(503); @@ -229,8 +231,8 @@ describe('[#20790] the draft → active promotion reads the channel\'s held posi const { channel, held, calls } = makeChannel(); protocol.registerCredentialChannel('flow', channel); - await protocol.saveMetaItem({ type: 'flow', name: 'channel_intake', item: inbound(V1) }); - await protocol.saveMetaItem({ type: 'flow', name: 'channel_intake', item: inbound(DRAFT, 'Drafted'), mode: 'draft' }); + await protocol.saveMetaItem({ type: 'flow', name: 'channel_intake', packageId: TEST_PKG, item: inbound(V1) }); + await protocol.saveMetaItem({ type: 'flow', name: 'channel_intake', packageId: TEST_PKG, item: inbound(DRAFT, 'Drafted'), mode: 'draft' }); expect(held.get('channel_intake|draft')).toBe(DRAFT); // The live row is untouched by the draft save. expect(held.get('channel_intake|active')).toBe(V1); @@ -249,18 +251,18 @@ describe('[#20790] R2 — a rollback past the move keeps the channel\'s current const protocol = new ObjectStackProtocolImplementation(engine); // v1 — stored the way every flow was before the channel existed. - await protocol.saveMetaItem({ type: 'flow', name: 'channel_intake', item: inbound(V1) }); + await protocol.saveMetaItem({ type: 'flow', name: 'channel_intake', packageId: TEST_PKG, item: inbound(V1) }); expect(bodiesOf(historyRows).join()).toContain(V1); // The channel arrives; v2 moves the secret (rotated) out of the body. const { channel, held, calls } = makeChannel(); protocol.registerCredentialChannel('flow', channel); - await protocol.saveMetaItem({ type: 'flow', name: 'channel_intake', item: inbound(V2, 'Moved') }); + await protocol.saveMetaItem({ type: 'flow', name: 'channel_intake', packageId: TEST_PKG, item: inbound(V2, 'Moved') }); expect(held.get('channel_intake|active')).toBe(V2); const historyBefore = historyRows.length; calls.length = 0; - const result: any = await protocol.rollbackMetaItem({ type: 'flow', name: 'channel_intake', toVersion: 1 }); + const result: any = await protocol.rollbackMetaItem({ type: 'flow', name: 'channel_intake', packageId: TEST_PKG, toVersion: 1 }); expect(result?.success ?? true).toBe(true); // The restored row is version 1's body WITHOUT its credential … diff --git a/packages/metadata-protocol/src/protocol.dashboard-dataset-publish-gate.test.ts b/packages/metadata-protocol/src/protocol.dashboard-dataset-publish-gate.test.ts index 7055ba24e81..8bb40c04555 100644 --- a/packages/metadata-protocol/src/protocol.dashboard-dataset-publish-gate.test.ts +++ b/packages/metadata-protocol/src/protocol.dashboard-dataset-publish-gate.test.ts @@ -118,6 +118,9 @@ interface Row { const keyOf = (w: Record) => `${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}`; +/** The writable package a new board or report is saved into; it declares no dependencies. */ +const TEST_PKG = 'test_pkg'; + function makeStubEngine() { // ⚠️ Keyed BY TABLE, and that is a correctness property of this harness // rather than tidiness. One flat row map answers a read of `sys_metadata` @@ -217,6 +220,9 @@ function makeStubEngine() { return []; }, getItem: () => undefined, + // [#38174] installs {@link TEST_PKG}: a new item is saved into a + // writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), }, }; return { engine, rows, tableOf }; @@ -280,7 +286,7 @@ describe('dashboard dataset bindings at the publish door (#7529)', () => { it('lets the identical body through as a DRAFT — the forward-reference workflow', async () => { const { protocol, rows } = makeProtocol(); - const result = await save(protocol, danglingBoard(), { mode: 'draft' }); + const result = await save(protocol, danglingBoard(), { mode: 'draft', packageId: TEST_PKG }); expect( result.success, @@ -294,7 +300,7 @@ describe('dashboard dataset bindings at the publish door (#7529)', () => { it('gates the draft→active PROMOTION, so the draft door is not a bypass', async () => { const { protocol } = makeProtocol(); - await save(protocol, danglingBoard(), { mode: 'draft' }); + await save(protocol, danglingBoard(), { mode: 'draft', packageId: TEST_PKG }); const err = await protocol .publishMetaItem({ type: 'dashboard', name: 'ops_board' }) @@ -314,7 +320,7 @@ describe('dashboard dataset bindings at the publish door (#7529)', () => { it('publishes a fully legitimate 3-widget board — the datasets really reach the gate', async () => { const { protocol, rows } = makeProtocol(); - const result = await save(protocol, legitBoard()); + const result = await save(protocol, legitBoard(), { packageId: TEST_PKG }); expect( result.success, @@ -328,7 +334,7 @@ describe('dashboard dataset bindings at the publish door (#7529)', () => { it('publishes a clean draft of the same legitimate board', async () => { const { protocol } = makeProtocol(); - await save(protocol, legitBoard(), { mode: 'draft' }); + await save(protocol, legitBoard(), { mode: 'draft', packageId: TEST_PKG }); const result = await protocol.publishMetaItem({ type: 'dashboard', name: 'ops_board' }); expect(result.success).toBe(true); }); @@ -347,7 +353,7 @@ describe('dashboard dataset bindings at the publish door (#7529)', () => { const protocol: any = new ObjectStackProtocolImplementation(engine, () => new Map(), 'env_test'); await protocol.saveMetaItem({ - type: 'dashboard', name: 'ops_board', item: legitBoard(), mode: 'draft', + type: 'dashboard', name: 'ops_board', item: legitBoard(), mode: 'draft', packageId: TEST_PKG, }); // Publishing while the dataset does not exist anywhere: refused. @@ -416,7 +422,7 @@ const filteredReport = (runtimeFilter: Record) => ({ /** Draft PUT, then POST publish: the two calls the card's reproduction makes. */ async function draftThenPublish(type: 'report' | 'dashboard', name: string, item: unknown) { const { protocol, rows } = makeReportProtocol(); - const draft = await protocol.saveMetaItem({ type, name, item, mode: 'draft' }); + const draft = await protocol.saveMetaItem({ type, name, item, mode: 'draft', packageId: TEST_PKG }); const published = await protocol.publishMetaItem({ type, name }).catch((e: any) => e); return { draft, published, rows }; } @@ -673,7 +679,7 @@ describe('#16225 a `sys_metadata` read is not answered from the journal tables', it('serves the store row only, never the history/audit rows the same save wrote', async () => { const { protocol, engine, tableOf } = makeProtocol(); - const saved = await save(protocol, legitBoard(), { mode: 'draft' }); + const saved = await save(protocol, legitBoard(), { mode: 'draft', packageId: TEST_PKG }); expect(saved.success).toBe(true); expect(saved.state, 'the artifact exists as a DRAFT and nothing else').toBe('draft'); diff --git a/packages/metadata-protocol/src/protocol.dashboard-duplicate-global-filter-name-refusal.test.ts b/packages/metadata-protocol/src/protocol.dashboard-duplicate-global-filter-name-refusal.test.ts index 217d91746b9..8ef6d2326f8 100644 --- a/packages/metadata-protocol/src/protocol.dashboard-duplicate-global-filter-name-refusal.test.ts +++ b/packages/metadata-protocol/src/protocol.dashboard-duplicate-global-filter-name-refusal.test.ts @@ -16,6 +16,8 @@ import { describe, expect, it } from 'vitest'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate, type EngineFindOneQueryInput } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from './protocol.js'; +const TEST_PKG = 'test_pkg'; + /** The engine surface the repository write path touches (as the container-issue-descent harness). */ function makeProtocol() { const rows = new Map>(); @@ -37,7 +39,8 @@ function makeProtocol() { assertEngineDeleteDispatch(opts); return { deleted: 0 }; }, - registry: { registerItem: () => {}, registerObject: () => {} }, + // [#38174] a create names an installed writable package (ADR-0070 D1). + registry: { registerItem: () => {}, registerObject: () => {}, getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined) }, }; const protocol: any = new ObjectStackProtocolImplementation(engine, () => new Map()); return { protocol, rows }; @@ -71,7 +74,7 @@ describe('#29212 the save door refuses a dashboard that declares one global filt const { protocol, rows } = makeProtocol(); const err = await rejection(protocol.saveMetaItem({ - type: 'dashboard', name: 'dup_board', ...mode, item: boardWith([ + type: 'dashboard', name: 'dup_board', packageId: TEST_PKG, ...mode, item: boardWith([ { name: 'r', field: 'region', type: 'text' }, { name: 'r', field: 'status', type: 'text' }, ]), @@ -90,7 +93,7 @@ describe('#29212 the save door refuses a dashboard that declares one global filt const { protocol, rows } = makeProtocol(); const result = await protocol.saveMetaItem({ - type: 'dashboard', name: 'dup_board', ...mode, item: boardWith([ + type: 'dashboard', name: 'dup_board', packageId: TEST_PKG, ...mode, item: boardWith([ { name: 'r', field: 'region', type: 'text' }, { name: 's', field: 'status', type: 'text' }, ]), diff --git a/packages/metadata-protocol/src/protocol.datasource-credentials-ref-own-reference.test.ts b/packages/metadata-protocol/src/protocol.datasource-credentials-ref-own-reference.test.ts index da9b411de71..bbb37bd9f2a 100644 --- a/packages/metadata-protocol/src/protocol.datasource-credentials-ref-own-reference.test.ts +++ b/packages/metadata-protocol/src/protocol.datasource-credentials-ref-own-reference.test.ts @@ -56,6 +56,8 @@ const matches = (r: Row, where: Record): boolean => const keyOf = (w: Record) => `${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}|${w.package_id ?? '__nopkg__'}`; +const TEST_PKG = 'test_pkg'; + /** A stub engine over one `sys_metadata` map, logging every write it is asked for. */ function makeStubEngine() { const rows = new Map(); @@ -102,7 +104,8 @@ function makeStubEngine() { getItem: () => undefined, registerItem: () => {}, registerObject: () => {}, - getPackage: () => undefined, + // [#38174] a new item is saved into an installed writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), }, }; return { engine, rows, writes }; @@ -257,7 +260,7 @@ describe('[#27762] datasource `external.credentialsRef`: a non-system save may o it('a body that names no reference saves as before', async () => { const s = session(); - await s.protocol.saveMetaItem({ type: 'datasource', name: 'fresh', item: datasourceBody('fresh', 'Fresh') }); + await s.protocol.saveMetaItem({ type: 'datasource', name: 'fresh', packageId: TEST_PKG, item: datasourceBody('fresh', 'Fresh') }); expect(rowOf(s.rows, 'fresh')).toBeDefined(); expect(storedRefOf(s.rows, 'fresh')).toBeUndefined(); }); diff --git a/packages/metadata-protocol/src/protocol.datasource-credentials-ref-restore-doors.test.ts b/packages/metadata-protocol/src/protocol.datasource-credentials-ref-restore-doors.test.ts index 0016a067d1d..84713aa2ead 100644 --- a/packages/metadata-protocol/src/protocol.datasource-credentials-ref-restore-doors.test.ts +++ b/packages/metadata-protocol/src/protocol.datasource-credentials-ref-restore-doors.test.ts @@ -83,6 +83,9 @@ function matchesWhere(r: Row, where: Record): boolean { return true; } +/** The writable package the staged datasources are saved into. */ +const TEST_PKG = 'test_pkg'; + /** A double that STORES rows and history, and whose registry keys an item by its own `name`. */ function makeStubEngine() { const rows = new Map(); @@ -182,7 +185,9 @@ function makeStubEngine() { getItem: (type: string, name: string) => registered.get(type)?.get(name), getAllObjects: () => [], getObject: () => undefined, - getPackage: () => undefined, + // [#38174] installs {@link TEST_PKG}: a new item is saved into a + // writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), getArtifactItem: () => undefined, isPackageDisabled: () => false, }, @@ -246,12 +251,13 @@ function bindVersion(h: Harness, name: string, version: number, credentialsRef: /** * `ledger` saved three times through the save door (history versions 1–3), * then bound by the admin door to `OWN_REF`; `vault` bound to `OTHER_REF`. + * [#38174] Both are saved into {@link TEST_PKG} (ADR-0070 D1). */ async function stage(h: Harness): Promise { for (const label of ['Ledger v1', 'Ledger v2', 'Ledger v3']) { - await h.protocol.saveMetaItem({ type: 'datasource', name: 'ledger', item: datasource('ledger', label) }); + await h.protocol.saveMetaItem({ type: 'datasource', name: 'ledger', item: datasource('ledger', label), packageId: TEST_PKG }); } - await h.protocol.saveMetaItem({ type: 'datasource', name: 'vault', item: datasource('vault', 'Vault') }); + await h.protocol.saveMetaItem({ type: 'datasource', name: 'vault', item: datasource('vault', 'Vault'), packageId: TEST_PKG }); bindRow(h, 'ledger', OWN_REF); bindRow(h, 'vault', OTHER_REF); } @@ -266,6 +272,8 @@ const snapshot = (h: Harness) => JSON.stringify({ const commitRow = (prevVersion: number) => ({ id: 'c1', commit_id: 'c1', + // The package the commit is recorded for, whose rows a revert addresses. + package_id: TEST_PKG, organization_id: null, operation: 'apply', message: 'the commit under revert', diff --git a/packages/metadata-protocol/src/protocol.datasource-delete-prolongation.test.ts b/packages/metadata-protocol/src/protocol.datasource-delete-prolongation.test.ts index 19a8349b70b..61bc0f7948a 100644 --- a/packages/metadata-protocol/src/protocol.datasource-delete-prolongation.test.ts +++ b/packages/metadata-protocol/src/protocol.datasource-delete-prolongation.test.ts @@ -603,6 +603,19 @@ async function measureProlongationMs( return null; } +/** + * [#38174] A package-less create is refused (ADR-0070 D1), and the datasource + * this file measures is a package-less (runtime-authored) row. It is seeded + * directly through the writer's engine, as the store writes an active row. + */ +async function seedLooseDatasource(replica: { engine: any }, name: string): Promise { + const res = await replica.engine.insert('sys_metadata', { + type: 'datasource', name, organization_id: null, package_id: null, state: 'active', + metadata: JSON.stringify(datasourceBody(name)), checksum: `sha256:seed_${name}`, version: 1, + }); + expect(res.id).toBeTruthy(); +} + /** * Bring both replicas to the QA-observed pre-condition: runtime-authored * datasources that BOTH replicas are serving on their own read door. @@ -624,12 +637,7 @@ async function seedServedDatasources( cluster: ReturnType, names: string[], ): Promise { - for (const name of names) { - const res = await cluster.writer.protocol.saveMetaItem({ - type: 'datasource', name, item: datasourceBody(name), mode: 'publish', - }); - expect(res.success).toBe(true); - } + for (const name of names) await seedLooseDatasource(cluster.writer, name); await settle(); for (const name of names) { expect(await serves(cluster.writer, name)).toBe(true); @@ -640,9 +648,7 @@ async function seedServedDatasources( describe('[#13609] the read door under measurement', () => { it('`datasource` takes the EMITTING repository delete exit — the premise this card rests on', async () => { const { writer, published } = makeCluster({ attach: true }); - await writer.protocol.saveMetaItem({ - type: 'datasource', name: 'billing_db', item: datasourceBody('billing_db'), mode: 'publish', - }); + await seedLooseDatasource(writer, 'billing_db'); await settle(); published.length = 0; diff --git a/packages/metadata-protocol/src/protocol.extension-field-suffix.test.ts b/packages/metadata-protocol/src/protocol.extension-field-suffix.test.ts index 2412d80e23c..d08ed5943a6 100644 --- a/packages/metadata-protocol/src/protocol.extension-field-suffix.test.ts +++ b/packages/metadata-protocol/src/protocol.extension-field-suffix.test.ts @@ -426,6 +426,12 @@ describe('[ADR-0146 D10] the save door refuses an object field spelled `__c` out const h = makeProtocol(); await h.protocol.saveMetaItem({ type: 'object', name: 'probe_ticket', item: obj('probe_ticket', 'Ticket', 'x__c'), packageId: PAIR }); await h.protocol.saveMetaItem({ type: 'object', name: 'probe_plain', item: obj('probe_plain', 'Plain', 'region'), packageId: BOUND }); + // [#38174] a package-less CREATE is refused (ADR-0070 D1): the loose + // row is seeded directly, and the package-less save runs in place. + await h.engine.insert('sys_metadata', { + type: 'object', name: 'probe_env', organization_id: null, package_id: null, state: 'active', + metadata: JSON.stringify(obj('probe_env', 'Env')), checksum: 'sha256:seed', version: 1, + }); await h.protocol.saveMetaItem({ type: 'object', name: 'probe_env', item: obj('probe_env', 'Env', 'x__c') }); expect(storedObjects(h)).toEqual([ { row: 'probe_ticket', state: 'active', binding: PAIR, fields: ['title', 'x__c'] }, diff --git a/packages/metadata-protocol/src/protocol.external-binding-named-datasource-refusal.test.ts b/packages/metadata-protocol/src/protocol.external-binding-named-datasource-refusal.test.ts index 3c12677ef17..74878519bcb 100644 --- a/packages/metadata-protocol/src/protocol.external-binding-named-datasource-refusal.test.ts +++ b/packages/metadata-protocol/src/protocol.external-binding-named-datasource-refusal.test.ts @@ -47,6 +47,13 @@ interface Row { [key: string]: unknown; } +/** + * [#38174] The installed writable package the environment's items are saved + * into: a package-less create is refused (ADR-0070 D1). The #25279 rows the + * migration pass reads stay planted loose, and their saves run in place. + */ +const TEST_PKG = 'test_pkg'; + /** [#24371] One `where` value as the store reads it: `{ $in: [...] }` or equality. */ const whereValueMatches = (actual: unknown, want: unknown): boolean => want !== null && typeof want === 'object' && Array.isArray((want as { $in?: unknown }).$in) @@ -121,6 +128,8 @@ function makeSession(opts: { applyNavContributions: (app: unknown) => app, getArtifactItem: () => undefined, getAllPackages: () => [], + // [#38174] a new item is saved into an installed writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), removeRuntimeShadow: () => false, removeOverlayEntry: () => {}, }, @@ -183,9 +192,9 @@ describe('[#25211] the object save door — `external` on a managed datasource t ['publish under `force`', { force: true }], ])(`a stored datasource with ${shape}: %s is refused 422 at \`external\`, and no object row is stored`, async (_mode, saveOpts) => { const { protocol, rows } = makeSession(); - await protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource('wh', dsExtra) }); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh', item: datasource('wh', dsExtra) }); - const err = await refusalOf(protocol.saveMetaItem({ type: 'object', name: 'wh_order', item: object('wh_order'), ...saveOpts })); + const err = await refusalOf(protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'wh_order', item: object('wh_order'), ...saveOpts })); expectRefusal(err, 'object/wh_order', 'external', ['wh_order']); expect(stored(rows, 'object', 'wh_order')).toEqual([]); @@ -195,7 +204,7 @@ describe('[#25211] the object save door — `external` on a managed datasource t it('a datasource the code layer registers as managed refuses the binding the same way', async () => { const { protocol, rows } = makeSession({ registryDatasources: { wh: datasource('wh', { schemaMode: 'managed' }) } }); - const err = await refusalOf(protocol.saveMetaItem({ type: 'object', name: 'wh_order', item: object('wh_order') })); + const err = await refusalOf(protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'wh_order', item: object('wh_order') })); expectRefusal(err, 'object/wh_order', 'external', ['wh_order']); expect(rows.size).toBe(0); @@ -205,9 +214,9 @@ describe('[#25211] the object save door — `external` on a managed datasource t // Registered federated, stored managed: the door reads the stored row // first, as its own by-name read serves the datasource. const { protocol, rows } = makeSession({ registryDatasources: { wh: datasource('wh', FEDERATED) } }); - await protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource('wh', { schemaMode: 'managed' }) }); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh', item: datasource('wh', { schemaMode: 'managed' }) }); - const err = await refusalOf(protocol.saveMetaItem({ type: 'object', name: 'wh_order', item: object('wh_order') })); + const err = await refusalOf(protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'wh_order', item: object('wh_order') })); expectRefusal(err, 'object/wh_order', 'external', ['wh_order']); expect(stored(rows, 'object', 'wh_order')).toEqual([]); @@ -221,10 +230,10 @@ describe('[#25211] the datasource save door — managed while objects bind it wi ['draft', { mode: 'draft' }], ])(`re-saving a federated datasource with ${shape} under a stored external object: %s is refused 422 at \`schemaMode\`, and the row is unchanged`, async (_mode, saveOpts) => { const { protocol, rows } = makeSession(); - await protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource('wh', FEDERATED) }); - await protocol.saveMetaItem({ type: 'object', name: 'wh_order', item: object('wh_order') }); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh', item: datasource('wh', FEDERATED) }); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'wh_order', item: object('wh_order') }); - const err = await refusalOf(protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource('wh', dsExtra), ...saveOpts })); + const err = await refusalOf(protocol.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh', item: datasource('wh', dsExtra), ...saveOpts })); expectRefusal(err, 'datasource/wh', 'schemaMode', ['wh_order']); expect(stored(rows, 'datasource', 'wh')).toEqual(['active|external']); @@ -233,10 +242,10 @@ describe('[#25211] the datasource save door — managed while objects bind it wi it('one finding per bound object, a stored row and a registered object alike', async () => { const { protocol, rows } = makeSession({ registryObjects: [object('wh_shipment')] }); - await protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource('wh', FEDERATED) }); - await protocol.saveMetaItem({ type: 'object', name: 'wh_order', item: object('wh_order') }); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh', item: datasource('wh', FEDERATED) }); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'wh_order', item: object('wh_order') }); - const err = await refusalOf(protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource('wh') })); + const err = await refusalOf(protocol.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh', item: datasource('wh') })); expectRefusal(err, 'datasource/wh', 'schemaMode', ['wh_order', 'wh_shipment']); expect(stored(rows, 'datasource', 'wh')).toEqual(['active|external']); @@ -246,9 +255,9 @@ describe('[#25211] the datasource save door — managed while objects bind it wi // The stored row is the object's base layer (ADR-0029 D9): it dropped // `external`, so the registered binding binds nothing here. const { protocol, rows } = makeSession({ registryObjects: [object('wh_order')] }); - await protocol.saveMetaItem({ type: 'object', name: 'wh_order', item: object('wh_order', { datasource: 'default', external: undefined }) }); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'wh_order', item: object('wh_order', { datasource: 'default', external: undefined }) }); - const result = await protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource('wh') }); + const result = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh', item: datasource('wh') }); expect(result.success).toBe(true); expect(stored(rows, 'datasource', 'wh')).toEqual(['active|-']); @@ -256,10 +265,10 @@ describe('[#25211] the datasource save door — managed while objects bind it wi it("an object's draft binds nothing until its publish", async () => { const { protocol, rows } = makeSession(); - await protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource('wh', FEDERATED) }); - await protocol.saveMetaItem({ type: 'object', name: 'wh_order', item: object('wh_order'), mode: 'draft' }); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh', item: datasource('wh', FEDERATED) }); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'wh_order', item: object('wh_order'), mode: 'draft' }); - const result = await protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource('wh') }); + const result = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh', item: datasource('wh') }); expect(result.success).toBe(true); expect(stored(rows, 'datasource', 'wh')).toEqual(['active|-']); @@ -269,11 +278,11 @@ describe('[#25211] the datasource save door — managed while objects bind it wi describe('[#25211] the publish of a draft is judged again, against the other half as it stands', () => { it('an object draft saved on a federated datasource is refused at publish once the datasource is managed', async () => { const { protocol, rows } = makeSession(); - await protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource('wh', FEDERATED) }); - await protocol.saveMetaItem({ type: 'object', name: 'wh_order', item: object('wh_order'), mode: 'draft' }); - await protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource('wh', { schemaMode: 'managed' }) }); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh', item: datasource('wh', FEDERATED) }); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'wh_order', item: object('wh_order'), mode: 'draft' }); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh', item: datasource('wh', { schemaMode: 'managed' }) }); - const err = await refusalOf(protocol.publishMetaItem({ type: 'object', name: 'wh_order' })); + const err = await refusalOf(protocol.publishMetaItem({ packageId: TEST_PKG, type: 'object', name: 'wh_order' })); expectRefusal(err, 'object/wh_order', 'external', ['wh_order']); expect(stored(rows, 'object', 'wh_order')).toEqual(['draft|external']); @@ -281,11 +290,11 @@ describe('[#25211] the publish of a draft is judged again, against the other hal it('a datasource draft saved as managed is refused at publish once an object binds it with `external`', async () => { const { protocol, rows } = makeSession(); - await protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource('wh', FEDERATED) }); - await protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource('wh', { schemaMode: 'managed' }), mode: 'draft' }); - await protocol.saveMetaItem({ type: 'object', name: 'wh_order', item: object('wh_order') }); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh', item: datasource('wh', FEDERATED) }); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh', item: datasource('wh', { schemaMode: 'managed' }), mode: 'draft' }); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'wh_order', item: object('wh_order') }); - const err = await refusalOf(protocol.publishMetaItem({ type: 'datasource', name: 'wh' })); + const err = await refusalOf(protocol.publishMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh' })); expectRefusal(err, 'datasource/wh', 'schemaMode', ['wh_order']); expect(stored(rows, 'datasource', 'wh').sort()).toEqual(['active|external', 'draft|managed']); @@ -298,33 +307,33 @@ describe('[#25211] controls — what the doors do not refuse', () => { ["`schemaMode: 'validate-only'`", { schemaMode: 'validate-only', external: { allowWrites: false } }], ])('a datasource with %s: the datasource and the bound object both save, and the datasource re-saves', async (_label, dsExtra) => { const { protocol, rows } = makeSession(); - expect((await protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource('wh', dsExtra) })).success).toBe(true); - expect((await protocol.saveMetaItem({ type: 'object', name: 'wh_order', item: object('wh_order') })).success).toBe(true); - expect((await protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource('wh', { ...dsExtra, label: 'Renamed' }) })).success).toBe(true); + expect((await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh', item: datasource('wh', dsExtra) })).success).toBe(true); + expect((await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'wh_order', item: object('wh_order') })).success).toBe(true); + expect((await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh', item: datasource('wh', { ...dsExtra, label: 'Renamed' }) })).success).toBe(true); expect(stored(rows, 'object', 'wh_order')).toEqual(['active|external']); }); it('an object bound to a datasource no layer holds saves (absence is no evidence about `schemaMode`)', async () => { const { protocol, rows } = makeSession(); - const result = await protocol.saveMetaItem({ type: 'object', name: 'wh_order', item: object('wh_order', { datasource: 'lake' }) }); + const result = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'wh_order', item: object('wh_order', { datasource: 'lake' }) }); expect(result.success).toBe(true); expect(stored(rows, 'object', 'wh_order')).toEqual(['active|external']); }); it('an object without `external` saves on a managed datasource, and the datasource re-saves managed under it', async () => { const { protocol, rows } = makeSession(); - await protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource('wh') }); - expect((await protocol.saveMetaItem({ type: 'object', name: 'wh_order', item: object('wh_order', { external: undefined }) })).success).toBe(true); - expect((await protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource('wh', { schemaMode: 'managed' }) })).success).toBe(true); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh', item: datasource('wh') }); + expect((await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'wh_order', item: object('wh_order', { external: undefined }) })).success).toBe(true); + expect((await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh', item: datasource('wh', { schemaMode: 'managed' }) })).success).toBe(true); expect(stored(rows, 'datasource', 'wh')).toEqual(['active|managed']); }); it('a datasource saves managed while external objects bind ANOTHER datasource', async () => { const { protocol } = makeSession({ registryObjects: [object('lake_order', { datasource: 'lake' })] }); - await protocol.saveMetaItem({ type: 'datasource', name: 'lake', item: datasource('lake', FEDERATED) }); - await protocol.saveMetaItem({ type: 'object', name: 'lake_item', item: object('lake_item', { datasource: 'lake' }) }); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'lake', item: datasource('lake', FEDERATED) }); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'lake_item', item: object('lake_item', { datasource: 'lake' }) }); - expect((await protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource('wh') })).success).toBe(true); + expect((await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh', item: datasource('wh') })).success).toBe(true); }); }); @@ -353,7 +362,7 @@ describe('[#25279] the stored-migration pass lists the object rows that door ref for (const [shape, dsExtra] of MANAGED_SHAPES) { it(`a stored object on a stored datasource with ${shape} is listed, and its next save is refused`, async () => { const { protocol, rows } = makeSession(); - await protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource('wh', dsExtra) }); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh', item: datasource('wh', dsExtra) }); plantObjectRow(rows, object('wh_order')); const report = await protocol.migrateStoredMetadata({}); @@ -376,7 +385,7 @@ describe('[#25279] the stored-migration pass lists the object rows that door ref it("the environment's stored datasource row is the one judged, over the registered definition", async () => { const { protocol, rows } = makeSession({ registryDatasources: { wh: datasource('wh', { schemaMode: 'managed' }) } }); - await protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource('wh', FEDERATED) }); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh', item: datasource('wh', FEDERATED) }); plantObjectRow(rows, object('wh_order')); const report = await protocol.migrateStoredMetadata({}); @@ -387,7 +396,7 @@ describe('[#25279] the stored-migration pass lists the object rows that door ref }); it.each([ - ['a federated stored datasource', (p: any) => p.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource('wh', FEDERATED) })], + ['a federated stored datasource', (p: any) => p.saveMetaItem({ packageId: TEST_PKG, type: 'datasource', name: 'wh', item: datasource('wh', FEDERATED) })], ['a datasource no layer holds', async () => {}], ])('a stored object on %s is not listed', async (_label, seed) => { const { protocol, rows } = makeSession(); diff --git a/packages/metadata-protocol/src/protocol.external-binding-primary-datasource-refusal.test.ts b/packages/metadata-protocol/src/protocol.external-binding-primary-datasource-refusal.test.ts index 4e6ca616fe7..cdbd4bc1735 100644 --- a/packages/metadata-protocol/src/protocol.external-binding-primary-datasource-refusal.test.ts +++ b/packages/metadata-protocol/src/protocol.external-binding-primary-datasource-refusal.test.ts @@ -23,6 +23,9 @@ import { describe, expect, it } from 'vitest'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate, type EngineFindOneQueryInput } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from './protocol.js'; +/** The writable package the control saves name. */ +const TEST_PKG = 'test_pkg'; + /** The engine surface the repository write path touches (as the select-shorthand harness). */ function makeProtocol() { const rows = new Map>(); @@ -46,7 +49,12 @@ function makeProtocol() { }, // [#25211] `getItem` for the save door's read of a named datasource: // this harness holds none. - registry: { registerItem: () => {}, registerObject: () => {}, getItem: () => undefined }, + // [#38174] `getPackage` installs {@link TEST_PKG}: a new item is saved + // into a writable package (ADR-0070 D1). + registry: { + registerItem: () => {}, registerObject: () => {}, getItem: () => undefined, + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), + }, }; const protocol: any = new ObjectStackProtocolImplementation(engine, () => new Map()); return { protocol, rows }; @@ -93,7 +101,7 @@ describe('#25168 the object save door refuses an `external` binding on the prima ])('control — %s saves', async (_label, extra) => { const { protocol, rows } = makeProtocol(); - const result = await protocol.saveMetaItem({ type: 'object', name: 'wh_order', item: order(extra) }); + const result = await protocol.saveMetaItem({ type: 'object', name: 'wh_order', item: order(extra), packageId: TEST_PKG }); expect(result.success).toBe(true); expect(rows.size).toBe(1); diff --git a/packages/metadata-protocol/src/protocol.flow-org-override-closed.test.ts b/packages/metadata-protocol/src/protocol.flow-org-override-closed.test.ts index 2391be018f3..c6748431583 100644 --- a/packages/metadata-protocol/src/protocol.flow-org-override-closed.test.ts +++ b/packages/metadata-protocol/src/protocol.flow-org-override-closed.test.ts @@ -96,6 +96,9 @@ interface Row { metadata: string; } +const TEST_PKG = 'test_pkg'; +const TASK_OBJECT = { name: 'task', label: 'Task', fields: { name: { name: 'name', type: 'text', label: 'Name' } }, _packageId: TEST_PKG }; + function makeStubEngine(artifacts: Array<{ type: string; name: string }> = []) { const rows = new Map(); let nextId = 0; @@ -132,12 +135,16 @@ function makeStubEngine(artifacts: Array<{ type: string; name: string }> = []) { registry: { registerItem: () => {}, registerObject: () => {}, - listItems: () => [], + // [#38174] The flow trigger's object, in the test package: a flow + // saved into a package (ADR-0070 D1) is judged against its closure. + listItems: (type: string) => (type === 'object' ? [TASK_OBJECT] : []), getItem: () => undefined, // `isArtifactBacked` prefers this lookup — a hit here means the // name is shipped by a code package (`_packageId` provenance). getArtifactItem: (type: string, name: string) => artifactKeys.has(`${type}|${name}`) ? { name, _packageId: 'showcase' } : undefined, + // [#38174] a new item is saved into an installed writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), }, }; return { engine, rows }; @@ -262,6 +269,7 @@ describe('#6283 — flow: allowEnvironmentOverlay rolled back to false', () => { const result = await protocol.saveMetaItem({ type: 'flow', name: 'escalate_overdue', + packageId: TEST_PKG, item: FLOW, }); diff --git a/packages/metadata-protocol/src/protocol.graft-folded-form-sections.test.ts b/packages/metadata-protocol/src/protocol.graft-folded-form-sections.test.ts index 6b09c585036..2bcffdbc775 100644 --- a/packages/metadata-protocol/src/protocol.graft-folded-form-sections.test.ts +++ b/packages/metadata-protocol/src/protocol.graft-folded-form-sections.test.ts @@ -75,6 +75,10 @@ interface Row { const keyOf = (w: Record) => `${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}`; +/** [#38174] An installed writable package a create names, and the objects its views bind. */ +const TEST_PKG = 'test_pkg'; +const OBJECTS_IN_TEST_PKG = [{ name: 'crm_lead', _packageId: TEST_PKG }, { name: 'lead', _packageId: TEST_PKG }]; + /** * The engine surface the repository write path touches — the same stub shape * `protocol.save-flow-canonicalization.test.ts` uses, for the same reason: a fix @@ -147,7 +151,16 @@ function makeProtocol() { tableOf(table).delete(found.key); return { deleted: 1 }; }, - registry: { registerItem: () => {}, registerObject: () => {} }, + registry: { + registerItem: () => {}, + registerObject: () => {}, + // [#38174] A create names an installed writable package (ADR-0070 + // D1), and a packaged view's `object` is judged inside its closure: + // the bound objects are the package's own (no field map, so no + // field reference is judged against them, as before). + listItems: (type: string) => (type === 'object' ? OBJECTS_IN_TEST_PKG : []), + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), + }, }; return { protocol: new ObjectStackProtocolImplementation(engine, () => new Map()), rows }; } @@ -155,7 +168,7 @@ function makeProtocol() { /** Save a view through the real write path and return the body the ROW holds. */ async function storedViewBody(name: string, item: unknown): Promise { const { protocol, rows } = makeProtocol(); - const result: any = await (protocol as any).saveMetaItem({ type: 'view', name, item }); + const result: any = await (protocol as any).saveMetaItem({ type: 'view', packageId: TEST_PKG, name, item }); expect(result.success, JSON.stringify(result)).toBe(true); const row = Array.from(rows.values()).find((r) => r.type === 'view'); expect(row, 'the save persisted no view row at all').toBeDefined(); @@ -165,7 +178,7 @@ async function storedViewBody(name: string, item: unknown): Promise { /** Save a `form` item through the real write path and return the body the ROW holds. */ async function storedFormBody(name: string, item: unknown): Promise { const { protocol, rows } = makeProtocol(); - const result: any = await (protocol as any).saveMetaItem({ type: 'form', name, item }); + const result: any = await (protocol as any).saveMetaItem({ type: 'form', packageId: TEST_PKG, name, item }); expect(result.success, JSON.stringify(result)).toBe(true); const row = Array.from(rows.values()).find((r) => r.type === 'form'); expect(row, 'the save persisted no form row at all').toBeDefined(); @@ -184,7 +197,7 @@ async function refusedFormInView( const { protocol, rows } = makeProtocol(); let err: any; try { - await (protocol as any).saveMetaItem({ type: 'view', name: item.name as string, item }); + await (protocol as any).saveMetaItem({ type: 'view', packageId: TEST_PKG, name: item.name as string, item }); } catch (e) { err = e; } expect(err?.code).toBe('INVALID_METADATA'); expect(err?.status).toBe(422); @@ -207,7 +220,7 @@ async function refusedUndeclared(item: Record, type: 'view' | ' const { protocol, rows } = makeProtocol(); let err: any; try { - await (protocol as any).saveMetaItem({ type, name: item.name as string, item }); + await (protocol as any).saveMetaItem({ type, packageId: TEST_PKG, name: item.name as string, item }); } catch (e) { err = e; } expect(err?.code).toBe('INVALID_METADATA'); expect(err?.status).toBe(422); @@ -494,7 +507,7 @@ describe('[#25923] the save door refuses a flat list overlay\'s `options` bag', const { protocol, rows } = makeProtocol(); let err: any; try { - await (protocol as any).saveMetaItem({ type: 'view', name: 'crm_lead.timeline', item }); + await (protocol as any).saveMetaItem({ type: 'view', packageId: TEST_PKG, name: 'crm_lead.timeline', item }); } catch (e) { err = e; } return { err, rowsWritten: Array.from(rows.values()).filter((r) => r.type === 'view').length }; } @@ -543,7 +556,7 @@ describe('#20186 the save door judges a flattened overlay by the member its view const { protocol, rows } = makeProtocol(); let err: any; try { - await (protocol as any).saveMetaItem({ type: 'view', name: item.name as string, item }); + await (protocol as any).saveMetaItem({ type: 'view', packageId: TEST_PKG, name: item.name as string, item }); } catch (e) { err = e; } expect(err?.code).toBe('INVALID_METADATA'); expect(err?.status).toBe(422); @@ -605,7 +618,7 @@ describe('#20186 the save door judges a flattened overlay by the member its view // form's column count, so a list's column array is refused there. const { protocol, rows } = makeProtocol(); const err: any = await (protocol as any) - .saveMetaItem({ type: 'form', name: ID.name, item: { ...ID, type: 'simple', columns: ['name'] } }) + .saveMetaItem({ type: 'form', packageId: TEST_PKG, name: ID.name, item: { ...ID, type: 'simple', columns: ['name'] } }) .catch((e: unknown) => e); expect([err?.code, err?.status]).toEqual(['INVALID_METADATA', 422]); expect(rows.size).toBe(0); @@ -793,7 +806,7 @@ describe('[#20051] stage (iv): a ViewItem record\'s top-level `options` bag is r const { protocol, rows } = makeProtocol(); let err: any; try { - await (protocol as any).saveMetaItem({ type: 'view', name: item.name as string, item }); + await (protocol as any).saveMetaItem({ type: 'view', packageId: TEST_PKG, name: item.name as string, item }); } catch (e) { err = e; } expect(err?.code).toBe('INVALID_METADATA'); expect(err?.status).toBe(422); @@ -841,7 +854,7 @@ describe('[#20051] stage (iv): the projection is view-only', () => { const component = { type: 'record:details', visibleWhen: 'record.stage == "open"' }; const page = { name: 'lead_record', label: 'Lead', type: 'record', object: 'lead', regions: [{ name: 'main', components: [component] }] }; const { protocol, rows } = makeProtocol(); - const result: any = await (protocol as any).saveMetaItem({ type: 'page', name: page.name, item: page }); + const result: any = await (protocol as any).saveMetaItem({ type: 'page', packageId: TEST_PKG, name: page.name, item: page }); expect(result.success, JSON.stringify(result)).toBe(true); const row = Array.from(rows.values()).find((r) => r.type === 'page'); const stored = JSON.parse(row!.metadata); @@ -876,7 +889,7 @@ describe('[#20051] stage (iv): the non-converging fallback stores the parse outp try { const { protocol, rows } = makeProtocol(); const save = (name: string, n: number) => (protocol as any).saveMetaItem({ - type: 'view', name, item: { name, object: 'crm_lead', viewKind: 'list', n }, + type: 'view', packageId: TEST_PKG, name, item: { name, object: 'crm_lead', viewKind: 'list', n }, }); await save('crm_lead.a', 1); await save('crm_lead.a', 5); diff --git a/packages/metadata-protocol/src/protocol.injected-system-columns.test.ts b/packages/metadata-protocol/src/protocol.injected-system-columns.test.ts index 99d2745a909..239e09d5c67 100644 --- a/packages/metadata-protocol/src/protocol.injected-system-columns.test.ts +++ b/packages/metadata-protocol/src/protocol.injected-system-columns.test.ts @@ -82,6 +82,9 @@ function keyOf(w: Record) { return `${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}|${w.package_id ?? '__nopkg__'}`; } +/** [#38174] An installed writable package: a save of a NEW item names one (ADR-0070 D1). */ +const TEST_PKG = 'test_pkg'; + function makeStubEngine() { const rows = new Map(); let nextId = 0; @@ -128,7 +131,7 @@ function makeStubEngine() { getItem: () => undefined, registerItem: () => {}, registerObject: () => {}, - getPackage: () => undefined, + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), }, }; return { engine, rows }; @@ -164,7 +167,7 @@ const INJECTED = [ async function seed(name: string, item: Record = authored(name), mode?: 'draft') { const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); - await protocol.saveMetaItem({ type: 'object', name, item, ...(mode ? { mode } : {}) }); + await protocol.saveMetaItem({ type: 'object', packageId: TEST_PKG, name, item, ...(mode ? { mode } : {}) }); return { protocol, rows, engine }; } @@ -431,7 +434,7 @@ describe('[#6562] the write path takes back exactly what the read added (#4326)' // Edit one label and PUT the whole thing back, as the designer does. await protocol.saveMetaItem({ - type: 'object', name: 'crm_invoice', item: { ...served, label: 'Invoice (edited)' }, + type: 'object', packageId: TEST_PKG, name: 'crm_invoice', item: { ...served, label: 'Invoice (edited)' }, }); const stored = storedBody(rows, 'crm_invoice'); @@ -447,7 +450,7 @@ describe('[#6562] the write path takes back exactly what the read added (#4326)' const before = Array.from(rows.values()).find((r) => r.name === 'crm_lead')!.checksum; const served: any = (await protocol.getMetaItem({ type: 'object', name: 'crm_lead' })).item; - await protocol.saveMetaItem({ type: 'object', name: 'crm_lead', item: served }); + await protocol.saveMetaItem({ type: 'object', packageId: TEST_PKG, name: 'crm_lead', item: served }); expect(Array.from(rows.values()).find((r) => r.name === 'crm_lead')!.checksum).toBe(before); }); @@ -460,7 +463,7 @@ describe('[#6562] the write path takes back exactly what the read added (#4326)' expect(draft._draft).toBe(true); expect(draft.fields.created_at).toBeDefined(); - await protocol.saveMetaItem({ type: 'object', name: 'crm_quote', item: draft, mode: 'draft' }); + await protocol.saveMetaItem({ type: 'object', packageId: TEST_PKG, name: 'crm_quote', item: draft, mode: 'draft' }); const stored = storedBody(rows, 'crm_quote'); expect(Object.keys(stored.fields)).toEqual(['amount']); @@ -480,7 +483,7 @@ describe('[#6562] the write path takes back exactly what the read added (#4326)' }; const { protocol, rows } = await seed('crm_asset', item); const served: any = (await protocol.getMetaItem({ type: 'object', name: 'crm_asset' })).item; - await protocol.saveMetaItem({ type: 'object', name: 'crm_asset', item: served }); + await protocol.saveMetaItem({ type: 'object', packageId: TEST_PKG, name: 'crm_asset', item: served }); const stored = storedBody(rows, 'crm_asset'); expect(Object.keys(stored.fields).sort()).toEqual(['amount', 'owner_id']); diff --git a/packages/metadata-protocol/src/protocol.invalid-metadata-422-face-inventory.test.ts b/packages/metadata-protocol/src/protocol.invalid-metadata-422-face-inventory.test.ts index e29e524ad27..b8338d5e4a9 100644 --- a/packages/metadata-protocol/src/protocol.invalid-metadata-422-face-inventory.test.ts +++ b/packages/metadata-protocol/src/protocol.invalid-metadata-422-face-inventory.test.ts @@ -99,7 +99,20 @@ interface Row { const keyOf = (w: Record) => `${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}`; -function makeProtocol(opts: { datasets?: readonly unknown[] } = {}) { +/** + * [#38174] A new item is saved into an installed writable package (ADR-0070 + * D1): a package-less create is refused. `packaged` installs `TEST_PKG` and + * registers the objects the CONTROL bodies bind (no package provenance, so the + * package closure keeps them); the CONTROLs save into `TEST_PKG`. + */ +const TEST_PKG = 'test_pkg'; +const TEST_OBJECTS = [ + { name: 'task', label: 'Task', fields: { title: { name: 'title', type: 'text' }, status: { name: 'status', type: 'text' } } }, + { name: 'hks_note', label: 'Note', fields: { status: { name: 'status', type: 'text' } } }, + { name: 'deal', label: 'Deal', fields: { name: { name: 'name', type: 'text' } } }, +]; + +function makeProtocol(opts: { datasets?: readonly unknown[]; packaged?: boolean } = {}) { // ⚠️ Keyed BY TABLE. `find`/`findOne` below answer nothing, so this harness // cannot serve a `sys_metadata_history` row as a `sys_metadata` row the way // #16223 measured — but one flat map still made `rows.size` the total of @@ -139,8 +152,15 @@ function makeProtocol(opts: { datasets?: readonly unknown[] } = {}) { // `datasets` (section 5 only) is the registered dataset universe the // author-time gate resolves a report's bindings against; every other // caller passes none, so the registry lists nothing, as before. - ...(opts.datasets - ? { listItems: (type: string) => (type === 'dataset' ? [...opts.datasets!] : []) } + ...(opts.datasets || opts.packaged + ? { + listItems: (type: string) => (type === 'dataset' + ? [...(opts.datasets ?? [])] + : type === 'object' && opts.packaged ? TEST_OBJECTS : []), + } + : {}), + ...(opts.packaged + ? { getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined) } : {}), }, }; @@ -339,12 +359,13 @@ describe('[#10888 · GUARD] a face that carries no `issues[]` keeps the whole se // shipped bundles). Rides this file's pinned engine double rather than a new // one, since the gate under test is the same `saveMetaItem` refusal. -async function saveTranslation(protocol: any, item: Record): Promise { +async function saveTranslation(protocol: any, item: Record, packageId?: string): Promise { try { return await protocol.saveMetaItem({ type: 'translation', name: 'zh_cn', item, + ...(packageId ? { packageId } : {}), writeFace: 'meta-envelope', }); } catch (e: any) { @@ -370,12 +391,12 @@ describe('[#19620] a `translation` item carrying `settings` is refused at the me }); it('CONTROL — the same item without `settings` is stored (the refusal is the key, not the item)', async () => { - const { protocol, rows } = makeProtocol(); + const { protocol, rows } = makeProtocol({ packaged: true }); const result = await saveTranslation(protocol, { locale: 'zh-CN', settingsCommon: { sourceLabels: { tenant: '租户' } }, apps: { crm: { label: '客户关系管理' } }, - }); + }, TEST_PKG); expect(result).not.toBeInstanceOf(Error); expect([...rows.values()].map((r) => r.type)).toEqual(['translation']); @@ -394,12 +415,13 @@ describe('[#19620] a `translation` item carrying `settings` is refused at the me // with the ADR-0112 envelope (`code` + `status`) and the refusal located at the // key. Rides this file's pinned engine double, as section 4 does. -async function saveReport(protocol: any, item: Record): Promise { +async function saveReport(protocol: any, item: Record, packageId?: string): Promise { try { return await protocol.saveMetaItem({ type: 'report', name: 'task_overview', item, + ...(packageId ? { packageId } : {}), writeFace: 'meta-envelope', }); } catch (e: any) { @@ -441,8 +463,8 @@ describe('[#20161] a `joined` report\'s `chart` is refused at the metadata door' }); it('CONTROL — the same joined report without a `chart` is stored (the refusal is the key, not the report)', async () => { - const { protocol, rows } = makeProtocol({ datasets }); - const result = await saveReport(protocol, joined); + const { protocol, rows } = makeProtocol({ datasets, packaged: true }); + const result = await saveReport(protocol, joined, TEST_PKG); expect(result instanceof Error ? `${result.message} ${JSON.stringify((result as any).issues ?? [])}` : 'stored').toBe('stored'); expect([...rows.values()].map((r) => r.type)).toEqual(['report']); @@ -464,12 +486,13 @@ describe('[#20161] a `joined` report\'s `chart` is refused at the metadata door' // double, as sections 4 and 5 do. ⛔ No check of its own lives in // `protocol.ts`: the refusal is the registered type schema's. -async function saveHookAsAdministrator(protocol: any, item: Record): Promise { +async function saveHookAsAdministrator(protocol: any, item: Record, packageId?: string): Promise { try { return await protocol.saveMetaItem({ type: 'hook', name: item.name, item, + ...(packageId ? { packageId } : {}), writeFace: 'meta-envelope', actor: 'usr_admin', }); @@ -505,8 +528,8 @@ describe('[#21565] a hook body bound to a stored-metadata table is refused at th }); it('CONTROL — the same body hook on an ordinary object saves as before', async () => { - const { protocol, rows } = makeProtocol(); - const result = await saveHookAsAdministrator(protocol, hookOn('hks_note')); + const { protocol, rows } = makeProtocol({ packaged: true }); + const result = await saveHookAsAdministrator(protocol, hookOn('hks_note'), TEST_PKG); expect(result instanceof Error ? `${result.message} ${JSON.stringify((result as any).issues ?? [])}` : 'stored').toBe('stored'); expect([...rows.values()].map((r) => [r.type, r.name])).toEqual([['hook', 'stamp_status']]); @@ -564,17 +587,17 @@ describe('[#21658] a hook naming a function in `handler` with no `body` is refus }); it('CONTROL — the same hook with a `body` saves', async () => { - const { protocol, rows } = makeProtocol(); + const { protocol, rows } = makeProtocol({ packaged: true }); const { handler: _dropped, ...withoutHandler } = handlerOnly(); - const result = await saveHookAsAdministrator(protocol, { ...withoutHandler, body }); + const result = await saveHookAsAdministrator(protocol, { ...withoutHandler, body }, TEST_PKG); expect(result instanceof Error ? `${result.message} ${JSON.stringify((result as any).issues ?? [])}` : 'stored').toBe('stored'); expect([...rows.values()].map((r) => [r.type, r.name])).toEqual([['hook', 'stamp_status']]); }); it('a `body` beside the `handler` saves: the binder runs the body and never consults the name', async () => { - const { protocol, rows } = makeProtocol(); - const result = await saveHookAsAdministrator(protocol, { ...handlerOnly(), body }); + const { protocol, rows } = makeProtocol({ packaged: true }); + const result = await saveHookAsAdministrator(protocol, { ...handlerOnly(), body }, TEST_PKG); expect(result instanceof Error ? `${result.message} ${JSON.stringify((result as any).issues ?? [])}` : 'stored').toBe('stored'); expect([...rows.values()].map((r) => [r.type, r.name])).toEqual([['hook', 'stamp_status']]); @@ -654,12 +677,13 @@ describe('[#21689] a hook with no `body` and no function in `handler` is refused // file's pinned engine double, as sections 4 to 8 do. ⛔ No check of its own // lives in `protocol.ts`: the refusal is the registered type schema's. -async function saveFlowAsAdministrator(protocol: any, item: Record, mode?: 'draft'): Promise { +async function saveFlowAsAdministrator(protocol: any, item: Record, mode?: 'draft', packageId?: string): Promise { try { return await protocol.saveMetaItem({ type: 'flow', name: item.name, item, + ...(packageId ? { packageId } : {}), writeFace: 'meta-envelope', actor: 'usr_admin', ...(mode ? { mode } : {}), @@ -725,11 +749,11 @@ describe('[#22088] a flow edge that names no node, or repeats an earlier edge, i }); it('CONTROL — the same flow with one edge per hop, each into a declared node, is stored', async () => { - const { protocol, rows } = makeProtocol(); + const { protocol, rows } = makeProtocol({ packaged: true }); const result = await saveFlowAsAdministrator(protocol, flowWith([start, node1, end], [ { id: 'e1', source: 'start', target: 'node_1' }, { id: 'edge_2', source: 'node_1', target: 'end' }, - ])); + ]), undefined, TEST_PKG); expect(result instanceof Error ? `${result.message} ${JSON.stringify((result as any).issues ?? [])}` : 'stored').toBe('stored'); expect([...rows.values()].map((r) => [r.type, r.name])).toEqual([['flow', 'repro_edges']]); @@ -783,8 +807,8 @@ describe('[#28806] a save_notice reachable from a suspending node is refused at }); it('CONTROL — the same flow with the notice ahead of the approval is stored', async () => { - const { protocol, rows } = makeProtocol(); - const result = await saveFlowAsAdministrator(protocol, NOTICE_FLOW('before')); + const { protocol, rows } = makeProtocol({ packaged: true }); + const result = await saveFlowAsAdministrator(protocol, NOTICE_FLOW('before'), undefined, TEST_PKG); expect(result instanceof Error ? `${result.message} ${JSON.stringify((result as any).issues ?? [])}` : 'stored').toBe('stored'); expect([...rows.values()].map((r) => [r.type, r.name])).toEqual([['flow', 'deal_submit']]); }); diff --git a/packages/metadata-protocol/src/protocol.item-name-every-door.test.ts b/packages/metadata-protocol/src/protocol.item-name-every-door.test.ts index c60b0c2b7ce..3d054182cd1 100644 --- a/packages/metadata-protocol/src/protocol.item-name-every-door.test.ts +++ b/packages/metadata-protocol/src/protocol.item-name-every-door.test.ts @@ -64,6 +64,7 @@ import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate, + hashSpec, } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from './protocol.js'; @@ -356,13 +357,16 @@ describe('[#21470] the save door refuses a body whose `name` is not its row\'s, it('CONTROL: an equal `name` passes; an absent one passes the judge (a view is stamped, a dashboard meets its schema)', async () => { const h = makeProtocol(); - await h.protocol.saveMetaItem({ type: 'dashboard', name: 'dash_a', item: dash('dash_a') }); - await h.protocol.saveMetaItem({ type: 'view', name: 'crm_lead.mine', item: recordView('crm_lead.mine') }); - await h.protocol.saveMetaItem({ type: 'view', name: 'crm_lead.stamped', item: recordView(undefined) }); + // [#38174] A new item is saved into a writable package (ADR-0070 D1), + // and the object its views bind is in that package's closure. + h.engine.registry.registerItem('object', { name: 'crm_lead', label: 'Lead', fields: {} }); + await h.protocol.saveMetaItem({ type: 'dashboard', name: 'dash_a', item: dash('dash_a'), packageId: DASH_PKG }); + await h.protocol.saveMetaItem({ type: 'view', name: 'crm_lead.mine', item: recordView('crm_lead.mine'), packageId: DASH_PKG }); + await h.protocol.saveMetaItem({ type: 'view', name: 'crm_lead.stamped', item: recordView(undefined), packageId: DASH_PKG }); // The judge passes an absent dashboard `name`; the dashboard schema // requires one, and answers in its own envelope. const { error } = await attempt(() => h.protocol.saveMetaItem({ - type: 'dashboard', name: 'dash_none', item: dash(undefined), + type: 'dashboard', name: 'dash_none', item: dash(undefined), packageId: DASH_PKG, })); expect([error?.code, error?.status]).toEqual(['INVALID_METADATA', 422]); @@ -381,11 +385,17 @@ describe('[#21470] the save door refuses a body whose `name` is not its row\'s, // 2. The restore doors (R1, R2) // ═══════════════════════════════════════════════════════════════════════════ -/** dash_a at v1, v2, v3 through the real door; v2's stored body then carries `name` dash_b. */ +/** + * [#38174] The installed package a new dashboard or view is saved into: a + * package-less create is refused (ADR-0070 D1). + */ +const DASH_PKG = 'app.dash'; + +/** dash_a at v1, v2, v3 through the real door, into {@link DASH_PKG}; v2's stored body then carries `name` dash_b. */ async function threeVersionsWithResidueAtV2(h: Harness) { - await h.protocol.saveMetaItem({ type: 'dashboard', name: 'dash_a', item: dash('dash_a', 'v1') }); - await h.protocol.saveMetaItem({ type: 'dashboard', name: 'dash_a', item: dash('dash_a', 'v2') }); - await h.protocol.saveMetaItem({ type: 'dashboard', name: 'dash_a', item: dash('dash_a', 'v3') }); + await h.protocol.saveMetaItem({ type: 'dashboard', name: 'dash_a', item: dash('dash_a', 'v1'), packageId: DASH_PKG }); + await h.protocol.saveMetaItem({ type: 'dashboard', name: 'dash_a', item: dash('dash_a', 'v2'), packageId: DASH_PKG }); + await h.protocol.saveMetaItem({ type: 'dashboard', name: 'dash_a', item: dash('dash_a', 'v3'), packageId: DASH_PKG }); residue(h, { type: 'dashboard', name: 'dash_a', version: 2 }, 'dash_b'); h.saveDoor.mockClear(); return { historyBefore: h.historyRows.length, activeBefore: JSON.stringify(stored(h, 'dashboard')) }; @@ -438,7 +448,7 @@ describe('[#21470] the restore doors refuse a stored version whose `name` is not it('R2: revertCommit\'s restore limb reports it in failed[] with the envelope\'s code; nothing is written', async () => { const h = makeProtocol(); const before = await threeVersionsWithResidueAtV2(h); - h.serveCommit(commitRow([{ type: 'dashboard', name: 'dash_a', existedBefore: true, prevVersion: 2 }])); + h.serveCommit(commitRow([{ type: 'dashboard', name: 'dash_a', existedBefore: true, prevVersion: 2 }], DASH_PKG)); vi.spyOn(console, 'warn').mockImplementation(() => {}); const res = await h.protocol.revertCommit({ commitId: 'c1' }); @@ -456,7 +466,7 @@ describe('[#21470] the restore doors refuse a stored version whose `name` is not it('R2 CONTROL: the restore limb restores a clean version', async () => { const h = makeProtocol(); await threeVersionsWithResidueAtV2(h); - h.serveCommit(commitRow([{ type: 'dashboard', name: 'dash_a', existedBefore: true, prevVersion: 1 }])); + h.serveCommit(commitRow([{ type: 'dashboard', name: 'dash_a', existedBefore: true, prevVersion: 1 }], DASH_PKG)); const res = await h.protocol.revertCommit({ commitId: 'c1' }); @@ -473,7 +483,7 @@ describe('[#21470] the restore doors refuse a stored version whose `name` is not describe('[#21470] the draft promotion refuses a stored draft whose `name` is not its row\'s', () => { it('D1: publishMetaItem of it is refused; no active row, no registry key, the draft kept', async () => { const h = makeProtocol(); - await h.protocol.saveMetaItem({ type: 'dashboard', name: 'dash_d', item: dash('dash_d'), mode: 'draft' }); + await h.protocol.saveMetaItem({ type: 'dashboard', name: 'dash_d', item: dash('dash_d'), mode: 'draft', packageId: DASH_PKG }); residue(h, { type: 'dashboard', name: 'dash_d', state: 'draft' }, 'dash_e'); h.saveDoor.mockClear(); @@ -488,7 +498,7 @@ describe('[#21470] the draft promotion refuses a stored draft whose `name` is no it('D1 CONTROL: a clean draft publishes under the row\'s one key', async () => { const h = makeProtocol(); - await h.protocol.saveMetaItem({ type: 'dashboard', name: 'dash_d', item: dash('dash_d'), mode: 'draft' }); + await h.protocol.saveMetaItem({ type: 'dashboard', name: 'dash_d', item: dash('dash_d'), mode: 'draft', packageId: DASH_PKG }); const res = await h.protocol.publishMetaItem({ type: 'dashboard', name: 'dash_d' }); @@ -665,6 +675,9 @@ describe('[ADR-0086 D3] the save door refuses a permission set whose body `packa await h.protocol.saveMetaItem({ type: 'permission', name: 'agree_live', item: perm('agree_live', BOUND), packageId: BOUND }); await h.protocol.saveMetaItem({ type: 'permission', name: 'agree_draft', item: perm('agree_draft', BOUND), packageId: BOUND, mode: 'draft' }); await h.protocol.saveMetaItem({ type: 'permission', name: 'bare_bound', item: perm('bare_bound'), packageId: BOUND }); + // [#38174] a package-less CREATE is refused (ADR-0070 D1): the loose + // row is seeded directly, and the package-less save runs in place. + await seedLooseSetV1(h, 'bare_env', perm('bare_env')); await h.protocol.saveMetaItem({ type: 'permission', name: 'bare_env', item: perm('bare_env') }); expect(storedSets(h)).toEqual([ { row: 'agree_live', state: 'active', binding: BOUND, body: BOUND }, @@ -738,7 +751,10 @@ async function threeSetVersionsWithOwnerResidueAtV2(h: Harness, binding: string type: 'permission', name: 'probe_member', item: { ...perm('probe_member'), label }, ...(binding === null ? {} : { packageId: binding }), }); - await save('v1'); + // [#38174] a package-less CREATE is refused (ADR-0070 D1): a set bound to + // no package is a loose row, seeded at v1 directly; v2 and v3 save in place. + if (binding === null) await seedLooseSetV1(h, 'probe_member', { ...perm('probe_member'), label: 'v1' }); + else await save('v1'); await save('v2'); await save('v3'); const v2 = h.historyRows.find((r) => r.type === 'permission' && r.name === 'probe_member' && r.version === 2); @@ -748,6 +764,23 @@ async function threeSetVersionsWithOwnerResidueAtV2(h: Harness, binding: string return { historyBefore: h.historyRows.length, activeBefore: JSON.stringify(storedSets(h)) }; } +/** + * [#38174] A loose (package-unbound) permission set at v1, as the store holds + * one written before a package-less create was refused: its active row and + * its v1 history row, inserted through the engine with the system context. + */ +async function seedLooseSetV1(h: Harness, name: string, body: Record) { + const checksum = hashSpec(body, 'permission'); + await h.engine.insert('sys_metadata', { + type: 'permission', name, organization_id: null, package_id: null, state: 'active', + metadata: JSON.stringify(body), checksum, version: 1, + }, { context: { isSystem: true } }); + await h.engine.insert('sys_metadata_history', { + type: 'permission', name, organization_id: null, package_id: null, version: 1, + operation_type: 'create', metadata: JSON.stringify(body), checksum, + }, { context: { isSystem: true } }); +} + /** The label of the active stored set — which version a restore left active. */ const activeLabel = (h: Harness) => { const row = Array.from(h.rows.values()).find((r) => r.type === 'permission' && r.name === 'probe_member' && r.state === 'active'); @@ -893,6 +926,9 @@ const d2bEndpoint = (authRequired: boolean) => ({ ...(authRequired ? {} : { rateLimit: { enabled: true, windowMs: 60_000, maxRequests: 100 } }), }); +/** [#38174] The installed package a new flow is saved into (ADR-0070 D1). */ +const D2B_PKG = 'app.intake'; + /** A protocol over this file's double, with an optional `metadata` service answering `list('api')`. */ function makeD2bProtocol(metadataList?: (type: string) => Promise, installedPackage?: string) { const h = makeStubEngine(); @@ -938,20 +974,20 @@ describe('[ADR-0138 D2b] the save door refuses a flow published as `system` whil }); it('CONTROL: the same flow under `user` beside the anonymous endpoint saves', async () => { - const h = makeD2bProtocol(); + const h = makeD2bProtocol(undefined, D2B_PKG); h.engine.registry.registerItem('api', d2bEndpoint(false)); - const res = await h.protocol.saveMetaItem({ type: 'flow', name: D2B_FLOW, item: d2bFlow('user') }); + const res = await h.protocol.saveMetaItem({ type: 'flow', name: D2B_FLOW, item: d2bFlow('user'), packageId: D2B_PKG }); expect(res.success).toBe(true); expect(storedFlows(h)).toEqual([{ row: D2B_FLOW, state: 'active', runAs: 'user' }]); }); it('CONTROL: the flow under `system` behind an AUTHENTICATED endpoint saves', async () => { - const h = makeD2bProtocol(); + const h = makeD2bProtocol(undefined, D2B_PKG); h.engine.registry.registerItem('api', d2bEndpoint(true)); - const res = await h.protocol.saveMetaItem({ type: 'flow', name: D2B_FLOW, item: d2bFlow('system') }); + const res = await h.protocol.saveMetaItem({ type: 'flow', name: D2B_FLOW, item: d2bFlow('system'), packageId: D2B_PKG }); expect(res.success).toBe(true); expect(storedFlows(h)).toEqual([{ row: D2B_FLOW, state: 'active', runAs: 'system' }]); @@ -977,10 +1013,10 @@ describe('[ADR-0138 D2b] the save door refuses a flow published as `system` whil }); it('draft mode is let through (a draft does not execute); a `migrate-stored` re-save is not judged', async () => { - const h = makeD2bProtocol(); + const h = makeD2bProtocol(undefined, D2B_PKG); h.engine.registry.registerItem('api', d2bEndpoint(false)); - const draft = await h.protocol.saveMetaItem({ type: 'flow', name: D2B_FLOW, item: d2bFlow('system'), mode: 'draft' }); + const draft = await h.protocol.saveMetaItem({ type: 'flow', name: D2B_FLOW, item: d2bFlow('system'), mode: 'draft', packageId: D2B_PKG }); expect(draft.success).toBe(true); const migrated = await h.protocol.saveMetaItem({ @@ -993,9 +1029,9 @@ describe('[ADR-0138 D2b] the save door refuses a flow published as `system` whil describe('[ADR-0138 D2b] the draft promotion refuses a `system` flow draft an anonymous endpoint names', () => { it('publishMetaItem: refused with the envelope; the draft is kept, nothing goes live', async () => { - const h = makeD2bProtocol(); + const h = makeD2bProtocol(undefined, D2B_PKG); h.engine.registry.registerItem('api', d2bEndpoint(false)); - await h.protocol.saveMetaItem({ type: 'flow', name: D2B_FLOW, item: d2bFlow('system'), mode: 'draft' }); + await h.protocol.saveMetaItem({ type: 'flow', name: D2B_FLOW, item: d2bFlow('system'), mode: 'draft', packageId: D2B_PKG }); const { error } = await attempt(() => h.protocol.publishMetaItem({ type: 'flow', name: D2B_FLOW })); @@ -1004,9 +1040,9 @@ describe('[ADR-0138 D2b] the draft promotion refuses a `system` flow draft an an }); it('publishMetaItem CONTROL: a `user` draft beside the anonymous endpoint publishes', async () => { - const h = makeD2bProtocol(); + const h = makeD2bProtocol(undefined, D2B_PKG); h.engine.registry.registerItem('api', d2bEndpoint(false)); - await h.protocol.saveMetaItem({ type: 'flow', name: D2B_FLOW, item: d2bFlow('user'), mode: 'draft' }); + await h.protocol.saveMetaItem({ type: 'flow', name: D2B_FLOW, item: d2bFlow('user'), mode: 'draft', packageId: D2B_PKG }); const res = await h.protocol.publishMetaItem({ type: 'flow', name: D2B_FLOW }); diff --git a/packages/metadata-protocol/src/protocol.item-name-grammar.test.ts b/packages/metadata-protocol/src/protocol.item-name-grammar.test.ts index 03b8f897ce3..b6b53218453 100644 --- a/packages/metadata-protocol/src/protocol.item-name-grammar.test.ts +++ b/packages/metadata-protocol/src/protocol.item-name-grammar.test.ts @@ -56,6 +56,10 @@ interface Row { metadata: string; } +/** [#38174] An installed writable package a create names, and the `task` object its views list. */ +const TEST_PKG = 'test_pkg'; +const TASK_IN_TEST_PKG = { name: 'task', label: 'Task', _packageId: TEST_PKG, fields: { name: { name: 'name', type: 'text', label: 'Name' } } }; + function makeProtocol(seedRows: Array> = []) { const rows = new Map(); let nextId = 0; @@ -126,9 +130,12 @@ function makeProtocol(seedRows: Array> = []) { registerItem: () => {}, registerObject: () => {}, unregisterItem: () => {}, - listItems: () => [], + // [#38174] A create names an installed writable package (ADR-0070 + // D1), and a packaged view's `object` is judged inside its closure. + listItems: (type: string) => (type === 'object' ? [TASK_IN_TEST_PKG] : []), getItem: () => undefined, getArtifactItem: () => undefined, + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), }, }; const protocol = new ObjectStackProtocolImplementation( @@ -161,7 +168,7 @@ const GRAMMAR_MESSAGE = /is not a legal metadata item name/; describe('#12194 — the names that must keep working', () => { it('accepts flat snake_case (`crm_lead`)', async () => { const { protocol, rows } = makeProtocol(); - const result = await protocol.saveMetaItem({ type: 'view', name: 'crm_lead', item: VIEW_BODY }); + const result = await protocol.saveMetaItem({ type: 'view', name: 'crm_lead', packageId: TEST_PKG, item: VIEW_BODY }); expect(result.success).toBe(true); expect(metaRows(rows)).toHaveLength(1); expect(metaRows(rows)[0]!.name).toBe('crm_lead'); @@ -169,7 +176,7 @@ describe('#12194 — the names that must keep working', () => { it('accepts the dotted qualified form (`crm_lead.pipeline`) — the ruling keeps the dot', async () => { const { protocol, rows } = makeProtocol(); - const result = await protocol.saveMetaItem({ type: 'view', name: 'crm_lead.pipeline', item: VIEW_BODY }); + const result = await protocol.saveMetaItem({ type: 'view', name: 'crm_lead.pipeline', packageId: TEST_PKG, item: VIEW_BODY }); expect(result.success).toBe(true); expect(metaRows(rows)).toHaveLength(1); expect(metaRows(rows)[0]!.name).toBe('crm_lead.pipeline'); @@ -177,7 +184,7 @@ describe('#12194 — the names that must keep working', () => { it('accepts a multi-dot qualified name (`a.b.c` family)', async () => { const { protocol, rows } = makeProtocol(); - const result = await protocol.saveMetaItem({ type: 'view', name: 'crm_lead.kanban.v2_board', item: VIEW_BODY }); + const result = await protocol.saveMetaItem({ type: 'view', name: 'crm_lead.kanban.v2_board', packageId: TEST_PKG, item: VIEW_BODY }); expect(result.success).toBe(true); expect(metaRows(rows)).toHaveLength(1); }); @@ -317,7 +324,7 @@ describe('#26128 — a translation item is named in snake_case, the BCP-47 tag g it('accepts the snake_case name (`zh_cn`) with `locale: \'zh-CN\'`', async () => { const { protocol, rows } = makeProtocol(); - const result = await protocol.saveMetaItem({ type: 'translation', name: 'zh_cn', item: { ...TRANSLATION_BODY, name: 'zh_cn' } }); + const result = await protocol.saveMetaItem({ type: 'translation', name: 'zh_cn', packageId: TEST_PKG, item: { ...TRANSLATION_BODY, name: 'zh_cn' } }); expect(result.success).toBe(true); expect(metaRows(rows)).toHaveLength(1); expect(metaRows(rows)[0]!.name).toBe('zh_cn'); diff --git a/packages/metadata-protocol/src/protocol.lifecycle-audit-rows.test.ts b/packages/metadata-protocol/src/protocol.lifecycle-audit-rows.test.ts index 5a0ad4f3f45..274ed9c6889 100644 --- a/packages/metadata-protocol/src/protocol.lifecycle-audit-rows.test.ts +++ b/packages/metadata-protocol/src/protocol.lifecycle-audit-rows.test.ts @@ -152,6 +152,9 @@ type Harness = { auditAttempts: any[]; }; +/** The writable package `case_grid` is saved into. */ +const TEST_PKG = 'test_pkg'; + function makeStubEngine(opts: { failAudit?: boolean } = {}): Harness { const rows = new Map(); const historyRows: HistoryRow[] = []; @@ -254,7 +257,12 @@ function makeStubEngine(opts: { failAudit?: boolean } = {}): Harness { registry: { registerItem: () => {}, registerObject: () => {}, - getPackage: () => undefined, + // [#38174] installs {@link TEST_PKG}: a new item is saved into a + // writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), + // The objects the saves here name, held by that package, so its + // closure reaches them. + listItems: (type: string) => (type === 'object' ? [{ name: 'case', label: 'case', _packageId: TEST_PKG, fields: {} }] : []), }, }; return { engine, rows, historyRows, auditRows, auditAttempts }; @@ -304,7 +312,7 @@ describe('[#7748] the audit trail records the whole lifecycle, not only `save`', expect(h.auditRows).toHaveLength(0); await protocol.saveMetaItem({ - type: 'view', name: 'case_grid', + type: 'view', name: 'case_grid', packageId: TEST_PKG, item: viewBody('v1'), actor: 'admin', } as any); @@ -325,7 +333,7 @@ describe('[#7748] the audit trail records the whole lifecycle, not only `save`', const protocol = new ObjectStackProtocolImplementation(h.engine); await protocol.saveMetaItem({ - type: 'view', name: 'case_grid', + type: 'view', name: 'case_grid', packageId: TEST_PKG, item: viewBody('staged'), mode: 'draft', actor: 'admin', } as any); @@ -356,7 +364,7 @@ describe('[#7748] the audit trail records the whole lifecycle, not only `save`', for (const label of ['v1', 'v2']) { await protocol.saveMetaItem({ - type: 'view', name: 'case_grid', + type: 'view', name: 'case_grid', packageId: TEST_PKG, item: viewBody(label), mode: 'draft', actor: 'admin', } as any); await protocol.publishMetaItem({ @@ -383,11 +391,11 @@ describe('[#7748] the audit trail records the whole lifecycle, not only `save`', const protocol = new ObjectStackProtocolImplementation(h.engine); await protocol.saveMetaItem({ - type: 'view', name: 'case_grid', + type: 'view', name: 'case_grid', packageId: TEST_PKG, item: viewBody('v1'), actor: 'admin', } as any); await protocol.saveMetaItem({ - type: 'view', name: 'case_grid', + type: 'view', name: 'case_grid', packageId: TEST_PKG, item: viewBody('v2'), actor: 'admin', } as any); @@ -422,13 +430,13 @@ describe('[#7748] the audit trail records the whole lifecycle, not only `save`', const protocol = new ObjectStackProtocolImplementation(h.engine); await protocol.saveMetaItem({ - type: 'view', name: 'case_grid', + type: 'view', name: 'case_grid', packageId: TEST_PKG, item: viewBody('head'), actor: 'admin', } as any); const auditedBefore = h.auditRows.length; const caught = await rejection(() => protocol.saveMetaItem({ - type: 'view', name: 'case_grid', + type: 'view', name: 'case_grid', packageId: TEST_PKG, item: viewBody('should not land'), parentVersion: 'sha256:stale', actor: 'admin', } as any)); @@ -464,7 +472,7 @@ describe('[#7748] the audit trail records the whole lifecycle, not only `save`', const protocol = new ObjectStackProtocolImplementation(h.engine); await protocol.saveMetaItem({ - type: 'view', name: 'case_grid', + type: 'view', name: 'case_grid', packageId: TEST_PKG, item: viewBody('staged'), mode: 'draft', actor: 'admin', } as any); await protocol.publishMetaItem({ @@ -490,7 +498,7 @@ describe('[#7748] the audit trail records the whole lifecycle, not only `save`', const protocol = new ObjectStackProtocolImplementation(h.engine); await protocol.saveMetaItem({ - type: 'view', name: 'case_grid', + type: 'view', name: 'case_grid', packageId: TEST_PKG, item: viewBody('staged'), mode: 'draft', actor: 'admin', } as any); const res = await protocol.publishMetaItem({ diff --git a/packages/metadata-protocol/src/protocol.lock-gate-fail-closed.test.ts b/packages/metadata-protocol/src/protocol.lock-gate-fail-closed.test.ts index 6eb6832e568..c6f36679aaf 100644 --- a/packages/metadata-protocol/src/protocol.lock-gate-fail-closed.test.ts +++ b/packages/metadata-protocol/src/protocol.lock-gate-fail-closed.test.ts @@ -90,15 +90,22 @@ import { ErrorCode } from '@objectstack/spec/api'; import { ObjectStackProtocolImplementation } from './protocol.js'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; +/** [#38174] An installed writable package: a save of a NEW item names one (ADR-0070 D1). */ +const TEST_PKG = 'test_pkg'; +/** [#38174] The `task` object the saved view lists, inside that package's closure. */ +const TASK_IN_TEST_PKG = { name: 'task', label: 'Task', _packageId: TEST_PKG, fields: { name: { name: 'name', type: 'text', label: 'Name' } } }; + /** A registry holding only what the test explicitly puts in it. */ -function registry(items: Record = {}) { +function registry(items: Record = {}, objects: unknown[] = []) { return { getObject: () => undefined, getItem: (_type: string, name: string) => items[name], - listItems: () => [], + listItems: (type: string) => (type === 'object' ? objects : []), applyNavContributions: (x: unknown) => x, isPackageDisabled: () => false, getObjectOwner: () => undefined, + // [#38174] the writable package a create names (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), }; } @@ -149,6 +156,8 @@ function engineWithTransientLockReadFault(opts: { failFirstRead: boolean; error?: () => unknown; registryItems?: Record; + /** [#38174] Objects the registry lists (a packaged view's `object` is judged inside its package closure). */ + registryObjects?: unknown[]; /** Omit the overlay row entirely — a genuine "nothing is locked" miss. */ noOverlayRow?: boolean; }): Harness { @@ -172,7 +181,7 @@ function engineWithTransientLockReadFault(opts: { return row; }; const engine: any = { - registry: registry(opts.registryItems ?? {}), + registry: registry(opts.registryItems ?? {}, opts.registryObjects ?? []), findOne: vi.fn(async (object: string, query: any) => { assertEngineFindOnePredicate(object, query); if (object !== 'sys_metadata') { @@ -229,10 +238,11 @@ function protocolFor(h: Harness) { // because its union had a member that stripped unknown keys and required none — // the hole #5599 closed. Nothing here needs a contentless body: this file's // subject is WHICH writes the lock gate admits, not what a view looks like. -const save = (p: ObjectStackProtocolImplementation) => +const save = (p: ObjectStackProtocolImplementation, packageId?: string) => p.saveMetaItem({ type: 'view', name: 'v1', + ...(packageId ? { packageId } : {}), // [#7741] carries the object binding the inline arm now requires. item: { name: 'v1', label: 'Edited', type: 'grid', columns: ['name'], object: 'task', viewKind: 'list' }, } as any); @@ -355,9 +365,10 @@ describe('[#5706] the gate still reaches the verdicts it could actually establis it('a genuine miss — healthy store, no lock row — still allows the write', async () => { // "Fail closed" must not become "refuse everything". Nothing is locked // here and the gate established that fact, so the save proceeds. - const h = engineWithTransientLockReadFault({ lock: 'none', failFirstRead: false, noOverlayRow: true }); + const h = engineWithTransientLockReadFault({ lock: 'none', failFirstRead: false, noOverlayRow: true, registryObjects: [TASK_IN_TEST_PKG] }); - const res: any = await save(protocolFor(h)); + // [#38174] no row of `v1` is stored, so this save is a create: it names a package. + const res: any = await save(protocolFor(h), TEST_PKG); expect(res.success).toBe(true); expect(h.calls).toContain('insert:sys_metadata'); @@ -374,9 +385,11 @@ describe('[#5706] the benign unprovisioned store is still not an outage', () => failFirstRead: true, error: missingTable, noOverlayRow: true, + registryObjects: [TASK_IN_TEST_PKG], }); - const res: any = await save(protocolFor(h)); + // [#38174] no row of `v1` is stored, so this save is a create: it names a package. + const res: any = await save(protocolFor(h), TEST_PKG); expect(res.success).toBe(true); expect(h.calls[0]).toBe(GATE_READ); diff --git a/packages/metadata-protocol/src/protocol.meta-types-mint-door-agreement.test.ts b/packages/metadata-protocol/src/protocol.meta-types-mint-door-agreement.test.ts index 34f1d2b5aaf..b7e932fa9d3 100644 --- a/packages/metadata-protocol/src/protocol.meta-types-mint-door-agreement.test.ts +++ b/packages/metadata-protocol/src/protocol.meta-types-mint-door-agreement.test.ts @@ -79,6 +79,9 @@ const LIVE_TYPES = [ 'policy', 'data', 'package', 'kind', ]; +const TEST_PKG = 'test_pkg'; +const TASK_OBJECT = { name: 'task', label: 'Task', fields: { name: { name: 'name', type: 'text', label: 'Name' } }, _packageId: TEST_PKG }; + function makeProtocol() { const rows = new Map>(); let nextId = 0; @@ -109,9 +112,12 @@ function makeProtocol() { registerItem: () => {}, registerObject: () => {}, unregisterItem: () => {}, - listItems: () => [], + // [#38174] A new item is saved into an installed writable package + // (ADR-0070 D1); the `task` the samples bind is that package's. + listItems: (type: string) => (type === 'object' ? [TASK_OBJECT] : []), getItem: () => undefined, getArtifactItem: () => undefined, + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), }, }; const protocol = new ObjectStackProtocolImplementation( @@ -236,7 +242,7 @@ describe('#8421 — the read door and the mint door agree, across all three clas '$klass `$type`: PUT /meta/:type/:name behaves as advertised', async ({ type, creatable, item }) => { const { protocol, rows } = makeProtocol(); - const save = protocol.saveMetaItem({ type, name: item.name, item }); + const save = protocol.saveMetaItem({ type, name: item.name, packageId: TEST_PKG, item }); if (creatable) { await expect(save).resolves.toMatchObject({ success: true }); @@ -269,7 +275,7 @@ describe('#8421 — the read door and the mint door agree, across all three clas const fresh = makeProtocol(); let honoured: boolean; try { - await fresh.protocol.saveMetaItem({ type, name: item.name, item }); + await fresh.protocol.saveMetaItem({ type, name: item.name, packageId: TEST_PKG, item }); honoured = true; } catch { honoured = false; diff --git a/packages/metadata-protocol/src/protocol.metadata-redaction.test.ts b/packages/metadata-protocol/src/protocol.metadata-redaction.test.ts index 2bd3dc17feb..9a283f811b7 100644 --- a/packages/metadata-protocol/src/protocol.metadata-redaction.test.ts +++ b/packages/metadata-protocol/src/protocol.metadata-redaction.test.ts @@ -90,6 +90,9 @@ function keyOf(w: Record) { return `${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}|${w.package_id ?? '__nopkg__'}`; } +/** The writable package a first save of a new item names. */ +const TEST_PKG = 'test_pkg'; + function makeStubEngine() { const rows = new Map(); let nextId = 0; @@ -136,7 +139,9 @@ function makeStubEngine() { getItem: () => undefined, registerItem: () => {}, registerObject: () => {}, - getPackage: () => undefined, + // [#38174] installs {@link TEST_PKG}: a new item is saved into a + // writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), }, }; return { engine, rows }; @@ -704,10 +709,13 @@ describe('#20552 — first save of a registry-only (code-authored) flow keeps it expect(allStrings(served)).not.toContain(FLOW_SECRET); const { _diagnostics: _d, ...editable } = served; void _d; + // [#38174] The first stored row of the name is a create: it names a + // writable package (ADR-0070 D1). await protocol.saveMetaItem({ type: 'flow', name: 'inbound_hook', item: { ...editable, label: 'Edited in the designer', nodes: [editable.nodes[1], editable.nodes[0]] }, + packageId: TEST_PKG, }); const row = overlayRow(rows, 'active'); @@ -724,7 +732,7 @@ describe('#20552 — first save of a registry-only (code-authored) flow keeps it const served: any = (await protocol.getMetaItem({ type: 'flow', name: 'inbound_hook' })).item; const { _diagnostics: _d, ...editable } = served; void _d; - await protocol.saveMetaItem({ type: 'flow', name: 'inbound_hook', mode: 'draft', item: { ...editable, label: 'Draft edit' } }); + await protocol.saveMetaItem({ type: 'flow', name: 'inbound_hook', mode: 'draft', item: { ...editable, label: 'Draft edit' }, packageId: TEST_PKG }); expect(startNodeOf(JSON.parse(overlayRow(rows, 'draft')!.metadata)).config.secret).toBe(FLOW_SECRET); await protocol.publishMetaItem({ type: 'flow', name: 'inbound_hook' }); @@ -743,7 +751,7 @@ describe('#20552 — first save of a registry-only (code-authored) flow keeps it const { _diagnostics: _d, ...rotated } = served; void _d; startNodeOf(rotated).config.secret = ROTATED; - await protocol.saveMetaItem({ type: 'flow', name: 'inbound_hook', item: rotated }); + await protocol.saveMetaItem({ type: 'flow', name: 'inbound_hook', item: rotated, packageId: TEST_PKG }); expect(startNodeOf(JSON.parse(overlayRow(rows, 'active')!.metadata)).config.secret).toBe(ROTATED); }); }); @@ -1277,7 +1285,7 @@ describe('#20611 — the runtime authoring gate reads a withheld-and-stored secr const protocol = new ObjectStackProtocolImplementation(engine); const err: any = await protocol - .saveMetaItem({ type: 'flow', name: 'fresh_hook', item: freshInboundFlow() }) + .saveMetaItem({ type: 'flow', name: 'fresh_hook', item: freshInboundFlow(), packageId: TEST_PKG }) .catch((e: unknown) => e); expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); expect(err.issues.map((i: any) => [i.rule, i.path])).toEqual([ @@ -1304,6 +1312,7 @@ describe('#20611 — the runtime authoring gate reads a withheld-and-stored secr type: 'flow', name: 'fresh_hook', item: freshInboundFlow({ triggerType: 'api', hookId: 'intake', secret: ROTATED }), + packageId: TEST_PKG, }), ).resolves.toMatchObject({ success: true }); }); @@ -1312,7 +1321,7 @@ describe('#20611 — the runtime authoring gate reads a withheld-and-stored secr const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); - await protocol.saveMetaItem({ type: 'flow', name: 'fresh_hook', mode: 'draft', item: freshInboundFlow() }); + await protocol.saveMetaItem({ type: 'flow', name: 'fresh_hook', mode: 'draft', item: freshInboundFlow(), packageId: TEST_PKG }); expect(flowRowsNamed(rows, 'fresh_hook').map((r) => r.state)).toEqual(['draft']); const err: any = await protocol.publishMetaItem({ type: 'flow', name: 'fresh_hook' }).catch((e: unknown) => e); @@ -1913,7 +1922,7 @@ describe('the connector doors judge a provider URL the way a URL parser reads it const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); const url = `${UNIT_SEPARATOR}https:/api.vendor.example/v1?page=2`; - await protocol.saveMetaItem({ type: 'connector', name: 'vendor_clean', item: connectorWith('vendor_clean', url) }); + await protocol.saveMetaItem({ type: 'connector', name: 'vendor_clean', item: connectorWith('vendor_clean', url), packageId: TEST_PKG }); expect(readPath(storedConnector(rows), path)).toBe(url); }); diff --git a/packages/metadata-protocol/src/protocol.named-base-every-type.test.ts b/packages/metadata-protocol/src/protocol.named-base-every-type.test.ts index ace3f48693f..54615573fba 100644 --- a/packages/metadata-protocol/src/protocol.named-base-every-type.test.ts +++ b/packages/metadata-protocol/src/protocol.named-base-every-type.test.ts @@ -190,8 +190,8 @@ describe('[#26708] a save naming a package no installed package has is refused, expect(refusal.message).toBe( `Cannot save flow 'orphan_flow' into package '${PHANTOM}': no package with that id is ` + `installed in this deployment, so the flow would be stored bound to a package that does not ` - + `exist. Name an installed writable package as the flow's base (or create one first), or save ` - + `the flow without naming a package. Nothing was written.`, + + `exist. Name an installed writable package as the flow's base, or create one first. ` + + `Nothing was written.`, ); }); @@ -224,6 +224,14 @@ describe('[#26708] controls — the saves the rule does not judge are unchanged' for (const packageId of ['sys_metadata', null, undefined]) { const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + // [#38174] a package-less CREATE is refused (ADR-0070 D1): the + // package-less saves run in place over a loose row seeded directly. + if (packageId !== 'sys_metadata') { + await engine.insert('sys_metadata', { + type: 'object', name: 'plain_obj', organization_id: null, package_id: null, state: 'active', + metadata: JSON.stringify(BODIES.object('plain_obj')), + }); + } expect(await save(protocol, { type: 'object', name: 'plain_obj', item: BODIES.object('plain_obj'), packageId }), String(packageId)).toBe('saved'); expect(rowsFor(rows, 'object', 'plain_obj'), String(packageId)) .toEqual([{ state: 'active', package_id: packageId === 'sys_metadata' ? 'sys_metadata' : null }]); diff --git a/packages/metadata-protocol/src/protocol.named-base-stored-binding.test.ts b/packages/metadata-protocol/src/protocol.named-base-stored-binding.test.ts index eb5f3ec1a61..6fd7942c5d5 100644 --- a/packages/metadata-protocol/src/protocol.named-base-stored-binding.test.ts +++ b/packages/metadata-protocol/src/protocol.named-base-stored-binding.test.ts @@ -272,6 +272,12 @@ describe('[#26921] controls — doors over rows the rule does not judge are unch it('a save naming no package for an item with no binding still saves package-less, draft and active', async () => { const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + // [#38174] a package-less create is refused (ADR-0070 D1): the loose + // row is seeded directly, and the package-less saves run in place. + await engine.insert('sys_metadata', { + type: 'dashboard', name: 'plain', organization_id: null, package_id: null, state: 'active', + metadata: JSON.stringify(BODIES.dashboard('plain', 'Seed')), checksum: 'sha256:seed', version: 1, + }); expect(await save(protocol, { type: 'dashboard', name: 'plain', item: BODIES.dashboard('plain', 'Live') })).toBe('saved'); expect(await save(protocol, { type: 'dashboard', name: 'plain', item: BODIES.dashboard('plain', 'Draft'), mode: 'draft' })).toBe('saved'); expect(rowsFor(rows, 'dashboard', 'plain')).toEqual([ @@ -294,7 +300,12 @@ describe('[#26921] controls — doors over rows the rule does not judge are unch it('the per-item publish of a package-less draft still promotes it', async () => { const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); - expect(await save(protocol, { type: 'dashboard', name: 'plain', item: BODIES.dashboard('plain', 'Draft'), mode: 'draft' })).toBe('saved'); + // [#38174] a package-less create is refused (ADR-0070 D1): the loose + // draft is seeded directly, and the publish promotes it. + await engine.insert('sys_metadata', { + type: 'dashboard', name: 'plain', organization_id: null, package_id: null, state: 'draft', + metadata: JSON.stringify(BODIES.dashboard('plain', 'Draft')), checksum: 'sha256:seed', version: 1, + }); expect(await publish(protocol, { type: 'dashboard', name: 'plain' })).toBe('published'); expect(rowsFor(rows, 'dashboard', 'plain')).toEqual([{ state: 'active', package_id: null, label: 'Draft' }]); }); diff --git a/packages/metadata-protocol/src/protocol.object-duplicate-action-name-refusal.test.ts b/packages/metadata-protocol/src/protocol.object-duplicate-action-name-refusal.test.ts index 15c63820470..cf5547ae599 100644 --- a/packages/metadata-protocol/src/protocol.object-duplicate-action-name-refusal.test.ts +++ b/packages/metadata-protocol/src/protocol.object-duplicate-action-name-refusal.test.ts @@ -18,6 +18,8 @@ import { ObjectStackProtocolImplementation } from './protocol.js'; // Paid at collection, not inside a clocked case (check:test-source-alias). import '@objectstack/lint'; +const TEST_PKG = 'test_pkg'; + /** The engine surface the repository write path touches (as the container-issue-descent harness). */ function makeProtocol() { const rows = new Map>(); @@ -39,7 +41,11 @@ function makeProtocol() { assertEngineDeleteDispatch(opts); return { deleted: 0 }; }, - registry: { registerItem: () => {}, registerObject: () => {} }, + // [#38174] a new item is saved into an installed writable package (ADR-0070 D1). + registry: { + registerItem: () => {}, registerObject: () => {}, + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), + }, }; const protocol: any = new ObjectStackProtocolImplementation(engine, () => new Map()); return { protocol, rows }; @@ -85,7 +91,7 @@ describe('#26725 the save door refuses an object that declares one action name t const { protocol, rows } = makeProtocol(); const result = await protocol.saveMetaItem({ - type: 'object', name: 'dup_item', item: itemWith([act('dup', 'Dup A'), act('dup_b', 'Dup B')]), + type: 'object', name: 'dup_item', packageId: TEST_PKG, item: itemWith([act('dup', 'Dup A'), act('dup_b', 'Dup B')]), }); expect(result.success).toBe(true); diff --git a/packages/metadata-protocol/src/protocol.org-scoped-write-refused.test.ts b/packages/metadata-protocol/src/protocol.org-scoped-write-refused.test.ts index e8e4b6dffad..1c4a6059b4f 100644 --- a/packages/metadata-protocol/src/protocol.org-scoped-write-refused.test.ts +++ b/packages/metadata-protocol/src/protocol.org-scoped-write-refused.test.ts @@ -370,22 +370,23 @@ describe('[ADR-0131 D6] no organization-scoped metadata write is accepted', () = } // ── the controls: environment-wide writes are accepted ───────────────── + // [#38174] Each create names an installed writable package (ADR-0070 D1). it('control — an environment-wide view save succeeds and stores no organization_id', async () => { const { protocol, rows } = makeProtocol([], 'env_prod'); - expect((await protocol.saveMetaItem({ type: 'view', name: 'org_grid', item: VIEW })).success).toBe(true); + expect((await protocol.saveMetaItem({ type: 'view', name: 'org_grid', item: VIEW, packageId: 'app.demo' })).success).toBe(true); expect(orgRows(rows)).toEqual([{ type: 'view', name: 'org_grid', org: false, state: 'active' }]); }); it('control — an environment-wide object save succeeds', async () => { const { protocol, rows } = makeProtocol([], 'env_prod'); - expect((await protocol.saveMetaItem({ type: 'object', name: 'org_widget', item: OBJECT })).success).toBe(true); + expect((await protocol.saveMetaItem({ type: 'object', name: 'org_widget', item: OBJECT, packageId: 'app.demo' })).success).toBe(true); expect(orgRows(rows)).toEqual([{ type: 'object', name: 'org_widget', org: false, state: 'active' }]); }); it('control — an environment-wide brand-new flow saves (the runtime-create tier is intact)', async () => { const { protocol, rows } = makeProtocol([], 'env_prod'); - expect((await protocol.saveMetaItem({ type: 'flow', name: 'org_sweep', item: FLOW })).success).toBe(true); + expect((await protocol.saveMetaItem({ type: 'flow', name: 'org_sweep', item: FLOW, packageId: 'app.demo' })).success).toBe(true); expect(orgRows(rows)).toEqual([{ type: 'flow', name: 'org_sweep', org: false, state: 'active' }]); }); @@ -540,6 +541,8 @@ describe('two packages shipping a form name', () => { // promotion is handed the judged draft's hash, so a draft saved between the // two reads is refused as a conflict, never promoted unjudged. describe('a publish promotes only the draft its gate judged', () => { + // [#38174] a create names an installed writable package (ADR-0070 D1). + const PUBLISH_PKG = 'app.demo'; const judged = { ...VIEW, label: 'Org grid (judged)' }; const later = { ...VIEW, label: 'Org grid (saved after the gate read)' }; @@ -548,7 +551,7 @@ describe('a publish promotes only the draft its gate judged', () => { const repo = protocol.getOverlayRepo(null); const promote = repo.promoteDraft.bind(repo); repo.promoteDraft = async (...args: unknown[]) => { - expect((await protocol.saveMetaItem({ type: 'view', name: VIEW.name, item: body, mode: 'draft' })).success) + expect((await protocol.saveMetaItem({ type: 'view', name: VIEW.name, item: body, mode: 'draft', packageId: PUBLISH_PKG })).success) .toBe(true); return promote(...args); }; @@ -560,11 +563,11 @@ describe('a publish promotes only the draft its gate judged', () => { it('a draft saved after the gate read is not promoted, and the conflict answers', async () => { const { protocol, rows } = makeProtocol(); - expect((await protocol.saveMetaItem({ type: 'view', name: VIEW.name, item: judged, mode: 'draft' })).success) + expect((await protocol.saveMetaItem({ type: 'view', name: VIEW.name, item: judged, mode: 'draft', packageId: PUBLISH_PKG })).success) .toBe(true); saveBeforePromotion(protocol, later); - await expect(protocol.publishMetaItem({ type: 'view', name: VIEW.name })) + await expect(protocol.publishMetaItem({ type: 'view', name: VIEW.name, packageId: PUBLISH_PKG })) .rejects.toMatchObject({ code: 'METADATA_CONFLICT', status: 409 }); expect(labelsIn(rows, 'active')).toEqual([]); expect(labelsIn(rows, 'draft')).toEqual([later.label]); @@ -574,7 +577,7 @@ describe('a publish promotes only the draft its gate judged', () => { const { protocol, rows } = makeProtocol(); saveBeforePromotion(protocol, later); - await expect(protocol.publishMetaItem({ type: 'view', name: VIEW.name })) + await expect(protocol.publishMetaItem({ type: 'view', name: VIEW.name, packageId: PUBLISH_PKG })) .rejects.toMatchObject({ code: 'METADATA_CONFLICT', status: 409 }); expect(labelsIn(rows, 'active')).toEqual([]); expect(labelsIn(rows, 'draft')).toEqual([later.label]); @@ -582,10 +585,10 @@ describe('a publish promotes only the draft its gate judged', () => { it('control: with no save in between, the judged draft is promoted and its draft row drained', async () => { const { protocol, rows } = makeProtocol(); - expect((await protocol.saveMetaItem({ type: 'view', name: VIEW.name, item: judged, mode: 'draft' })).success) + expect((await protocol.saveMetaItem({ type: 'view', name: VIEW.name, item: judged, mode: 'draft', packageId: PUBLISH_PKG })).success) .toBe(true); - expect((await protocol.publishMetaItem({ type: 'view', name: VIEW.name })).success).toBe(true); + expect((await protocol.publishMetaItem({ type: 'view', name: VIEW.name, packageId: PUBLISH_PKG })).success).toBe(true); expect(labelsIn(rows, 'active')).toEqual([judged.label]); expect(labelsIn(rows, 'draft')).toEqual([]); }); diff --git a/packages/metadata-protocol/src/protocol.package-closure-gate.test.ts b/packages/metadata-protocol/src/protocol.package-closure-gate.test.ts index c7b3879999e..007b9f3cf04 100644 --- a/packages/metadata-protocol/src/protocol.package-closure-gate.test.ts +++ b/packages/metadata-protocol/src/protocol.package-closure-gate.test.ts @@ -213,9 +213,19 @@ function makeStubEngine() { function makeProtocol() { const { engine, rows, packages } = makeStubEngine(); - return { protocol: new ObjectStackProtocolImplementation(engine, () => new Map(), 'env_test') as any, rows, packages }; + return { protocol: new ObjectStackProtocolImplementation(engine, () => new Map(), 'env_test') as any, rows, packages, engine }; } +/** + * [#38174] A package-less CREATE is refused (ADR-0070 D1), so a write that + * names no package is a save of a loose row that already exists: seeded here + * directly through the engine, then saved in place. + */ +const seedLooseFlow = (engine: any, item: any) => engine.insert('sys_metadata', { + type: 'flow', name: item.name, organization_id: null, package_id: null, state: 'active', + metadata: JSON.stringify(item), checksum: 'sha256:seed', +}); + const save = (protocol: any, item: any, extra: Record = {}) => protocol.saveMetaItem({ type: 'flow', name: item.name, item, ...extra }); @@ -341,7 +351,8 @@ describe('the write package closure reaches the gate (#9612)', () => { // less. The identical body that is refused above is silent here, // because the gate is handed the whole collection exactly as before // #9612. - const { protocol } = makeProtocol(); + const { protocol, engine } = makeProtocol(); + await seedLooseFlow(engine, flowOn('crm_on_stranger', 'other_widget')); const result = await save(protocol, flowOn('crm_on_stranger', 'other_widget')); @@ -352,7 +363,8 @@ describe('the write package closure reaches the gate (#9612)', () => { // [#24669] The overlay door states no closure, so the hedge stands: // advised on a 2xx, never refused, at both positions. for (const body of [flowOn('crm_on_ghost', 'nosuch_obj'), sweepOf('crm_sweep_ghost', 'nosuch_obj')]) { - const { protocol } = makeProtocol(); + const { protocol, engine } = makeProtocol(); + await seedLooseFlow(engine, body); const result = await save(protocol, body); expect(result.success, body.name).toBe(true); expect(triggerAdvisories(result), body.name).toEqual(['flow-trigger-unknown-object']); diff --git a/packages/metadata-protocol/src/protocol.package-publish-audit-rows.test.ts b/packages/metadata-protocol/src/protocol.package-publish-audit-rows.test.ts index 7333f9469f2..4c0ff10230c 100644 --- a/packages/metadata-protocol/src/protocol.package-publish-audit-rows.test.ts +++ b/packages/metadata-protocol/src/protocol.package-publish-audit-rows.test.ts @@ -431,7 +431,7 @@ describe('[#8400] publishPackageDrafts audits the batch it publishes', () => { expect(h.auditRows).toHaveLength(0); await protocol.saveMetaItem({ - type: 'view', name: 'case_grid', + type: 'view', name: 'case_grid', packageId: PKG, // [#38174] a create names a package (ADR-0070 D1) item: viewBody('case_grid', 'v1'), actor: 'admin', } as any); diff --git a/packages/metadata-protocol/src/protocol.packageless-layered-read-refusal.test.ts b/packages/metadata-protocol/src/protocol.packageless-layered-read-refusal.test.ts index a34c9c0adf6..ec4e4dc3003 100644 --- a/packages/metadata-protocol/src/protocol.packageless-layered-read-refusal.test.ts +++ b/packages/metadata-protocol/src/protocol.packageless-layered-read-refusal.test.ts @@ -104,6 +104,16 @@ function makeProtocol() { /** Store one dashboard row per package named (`null`: the package-unbound row). */ async function store(protocol: ObjectStackProtocolImplementation, name: string, packages: Array) { for (const pkg of packages) { + if (pkg === null) { + // [#38174] a package-less create is refused (ADR-0070 D1): the + // package-unbound row is seeded directly through the engine. + const item = { name, label: 'local copy', widgets: [] }; + await (protocol as any).engine.insert('sys_metadata', { + type: 'dashboard', name, organization_id: null, package_id: null, state: 'active', + metadata: JSON.stringify(item), checksum: 'sha256:seed', version: 1, + }); + continue; + } await protocol.saveMetaItem({ type: 'dashboard', name, item: { name, label: `${pkg ?? 'local'} copy`, widgets: [] }, ...(pkg ? { packageId: pkg } : {}), 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 d129312447c..e6565e402e0 100644 --- a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts +++ b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts @@ -742,10 +742,13 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder // delete naming no package removes the environment's row, never P's. for (const order of ['P first', 'environment first'] as const) { it(`[#33904] ${order}: the list names both items, the layered and published reads serve the environment's, and the delete naming no package removes the environment's row`, async () => { - const { protocol, rows } = makeProtocol(); + const { protocol, rows, seedRow } = makeProtocol(); const saveP = () => protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); const saveEnv = () => protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') }); - if (order === 'P first') { await saveP(); await saveEnv(); } else { await saveEnv(); await saveP(); } + // [#38174] A package-less CREATE is refused (ADR-0070 D1): environment + // first, the environment's row is seeded loose and its save runs in place. + const seedEnv = () => seedRow({ type: 'action', name: NAME, package_id: null, metadata: JSON.stringify(action(NAME, 'seeded', 'task')), checksum: 'sha-seeded' }); + if (order === 'P first') { await saveP(); await saveEnv(); } else { seedEnv(); await saveEnv(); await saveP(); } expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [null, 'task', 'env']]); const face = (item: any) => [item?.objectName ?? null, item?.label ?? null]; @@ -945,8 +948,11 @@ describe('an item TWO packages hold: a save naming neither is refused', () => { describe('CONTROL: what the resolution leaves alone', () => { it('an item with no package binding keeps the package-unbound row, and its receipt reads as before', async () => { - const { protocol, rows } = makeProtocol(); + const { protocol, rows, seedRow } = makeProtocol(); const name = 'plain_app'; + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the item's + // package-unbound row is seeded, and the package-less saves run in place. + seedRow({ type: 'app', name, package_id: null, metadata: JSON.stringify(app(name, { label: 'Seeded' })), checksum: 'sha-seeded' }); const first = await protocol.saveMetaItem({ type: 'app', name, item: app(name) }); const second = await protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'Edited' }) }); @@ -1195,8 +1201,11 @@ describe('an item TWO packages hold: a delete naming neither is refused', () => describe('CONTROL: what the delete resolution leaves alone', () => { it('an item with no package binding: the package-unbound row is removed, and the receipt reads as before', async () => { - const { protocol, rows } = makeProtocol(); + const { protocol, rows, seedRow } = makeProtocol(); const name = 'plain_delete_app'; + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the + // package-unbound row is seeded, and the package-less save runs in place. + seedRow({ type: 'app', name, package_id: null, metadata: JSON.stringify(app(name, { label: 'Seeded' })), checksum: 'sha-seeded' }); await protocol.saveMetaItem({ type: 'app', name, item: app(name) }); const receipt = await protocol.deleteMetaItem({ type: 'app', name }); @@ -1334,8 +1343,11 @@ describe('[#23297] CONTROL: one package and a package-less active row — the dr */ describe('[#23291] the read naming no package serves the row the save naming none writes', () => { it('the card\'s five steps: every read serves the row the save addressed', async () => { - const { protocol, rows } = makeProtocol(); + const { protocol, rows, seedRow } = makeProtocol(); const name = 's6_app'; + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the + // package-unbound row is seeded, and the package-less save runs in place. + seedRow({ type: 'app', name, package_id: null, metadata: JSON.stringify(app(name, { label: 'Seeded' })), checksum: 'sha-seeded' }); // 1. A package-less save of an item with no binding: the unbound row. const first = await protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'unbound' }) }); @@ -1417,8 +1429,11 @@ describe('[#23291] the read naming no package serves the row the save naming non } it('the layered read naming a package with no row of its own still reports the package-unbound row (the stand-in)', async () => { - const { protocol } = makeProtocol(); + const { protocol, seedRow } = makeProtocol(); const name = 's6_layered_standin_app'; + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the + // package-unbound row is seeded, and the package-less save runs in place. + seedRow({ type: 'app', name, package_id: null, metadata: JSON.stringify(app(name, { label: 'Seeded' })), checksum: 'sha-seeded' }); await protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'unbound' }) }); await protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'pkg' }), packageId: WRITABLE }); @@ -1448,8 +1463,11 @@ describe('[#23291] the read naming no package serves the row the save naming non }); it('the package-unbound row still stands in for a package with no row of its own (ADR-0048 prefer-local)', async () => { - const { protocol } = makeProtocol(); + const { protocol, seedRow } = makeProtocol(); const name = 's6_standin_app'; + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the + // package-unbound row is seeded, and the package-less save runs in place. + seedRow({ type: 'app', name, package_id: null, metadata: JSON.stringify(app(name, { label: 'Seeded' })), checksum: 'sha-seeded' }); await protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'unbound' }) }); await protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'pkg' }), packageId: WRITABLE }); @@ -1459,6 +1477,9 @@ describe('[#23291] the read naming no package serves the row the save naming non it('the draft reads serve the draft a package-less draft save writes: the package\'s', async () => { const { protocol, rows, seedRow } = makeProtocol(); const name = 's6_draft_app'; + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the + // package-unbound row is seeded, and the package-less save runs in place. + seedRow({ type: 'app', name, package_id: null, metadata: JSON.stringify(app(name, { label: 'Seeded' })), checksum: 'sha-seeded' }); await protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'unbound' }) }); await protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'pkg' }), packageId: WRITABLE }); // Drafts stored before this: the package-unbound one first, the package's beside it. @@ -1481,8 +1502,11 @@ describe('[#23291] the read naming no package serves the row the save naming non }); it('edge: another package holds a row too — the read is ADR-0048 §3.3\'s best effort, and the package-less save and delete are refused', async () => { - const { protocol, rows } = makeProtocol(); + const { protocol, rows, seedRow } = makeProtocol(); const name = 's6_shared_app'; + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the + // package-unbound row is seeded, and the package-less save runs in place. + seedRow({ type: 'app', name, package_id: null, metadata: JSON.stringify(app(name, { label: 'Seeded' })), checksum: 'sha-seeded' }); await protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'unbound' }) }); await protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'pkg' }), packageId: WRITABLE }); await protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'other' }), packageId: OTHER_WRITABLE }); @@ -1631,7 +1655,8 @@ describe('[#23495] the draft doors naming no package act on the draft the draft async function stateOne(name: string, unboundFirst: boolean): Promise { const f = { ...makeProtocol(), name }; if (unboundFirst) { - await saveDraft(f, 'stale'); + // [#38174] Seeded: a package-less draft CREATE is refused (ADR-0070 D1). + f.seedRow({ type: 'app', name, state: 'draft', package_id: null, metadata: JSON.stringify(app(name, { label: 'stale' })), checksum: 'sha-stale' }); await f.protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'live' }), packageId: P }); await f.protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'pending' }), packageId: P, mode: 'draft' }); } else { @@ -1733,7 +1758,8 @@ describe('[#23495] the draft doors naming no package act on the draft the draft const name = 's3_unbound_draft'; const build = async (): Promise => { const f = { ...makeProtocol(), name }; - await saveDraft(f, 'stale'); + // [#38174] Seeded: a package-less draft CREATE is refused (ADR-0070 D1). + f.seedRow({ type: 'app', name, state: 'draft', package_id: null, metadata: JSON.stringify(app(name, { label: 'stale' })), checksum: 'sha-stale' }); await f.protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'live' }), packageId: P }); return f; }; @@ -1794,7 +1820,8 @@ describe('[#23495] the draft doors naming no package act on the draft the draft const name = `s4_${unboundFirst ? 'unbound_first' : 'pkg_first'}`; const build = async (): Promise => { const f = { ...makeProtocol(), name }; - if (unboundFirst) await saveDraft(f, 'unbound'); + // [#38174] Seeded: a package-less draft CREATE is refused (ADR-0070 D1). + if (unboundFirst) f.seedRow({ type: 'app', name, state: 'draft', package_id: null, metadata: JSON.stringify(app(name, { label: 'unbound' })), checksum: 'sha-unbound' }); await f.protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'other' }), packageId: Q, mode: 'draft' }); // [#23657] Seeded, as an older build left it: a draft save naming // no package over Q's only draft now updates Q's draft. @@ -1882,7 +1909,8 @@ describe('[#23715] the strict draft read naming no package serves its content fr */ async function unboundBesideQ(name: string, unboundFirst: boolean): Promise { const f = { ...makeProtocol(), name }; - if (unboundFirst) await f.protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'unbound' }), mode: 'draft' }); + // [#38174] Seeded: a package-less draft CREATE is refused (ADR-0070 D1). + if (unboundFirst) unboundDraft(f, 'unbound'); await f.protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'q' }), packageId: Q, mode: 'draft' }); if (!unboundFirst) unboundDraft(f, 'unbound'); return f; @@ -1924,7 +1952,8 @@ describe('[#23715] the strict draft read naming no package serves its content fr for (const unboundFirst of [true, false]) { const name = `u23715_two_active_${unboundFirst ? 'unbound_first' : 'p_first'}`; const f = { ...makeProtocol(), name }; - if (unboundFirst) await f.protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'unbound' }), mode: 'draft' }); + // [#38174] Seeded: a package-less draft CREATE is refused (ADR-0070 D1). + if (unboundFirst) unboundDraft(f, 'unbound'); await f.protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'live P' }), packageId: P }); await f.protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'live Q' }), packageId: Q }); await f.protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'p' }), packageId: P, mode: 'draft' }); @@ -1940,6 +1969,8 @@ describe('[#23715] the strict draft read naming no package serves its content fr it('CONTROL: a single draft is served as before — the package-unbound one, or the one package\'s', async () => { const u = { ...makeProtocol(), name: 'u23715_only_unbound' }; + // [#38174] Seeded: a package-less draft CREATE is refused (ADR-0070 D1); the save runs in place. + unboundDraft(u, 'seeded'); const saved = await u.protocol.saveMetaItem({ type: 'app', name: u.name, item: app(u.name, { label: 'unbound' }), mode: 'draft' }); const ur = await readDraft(u); expect(ur.item.label).toBe('unbound'); @@ -1981,6 +2012,8 @@ describe('[#23715] the strict draft read naming no package serves its content fr * grammar, keep rule, stored form) are `draft-changes.test.ts`'s. */ describe('[#24395] the draft save records per-key provenance, the strict draft read serves it', () => { + // [#38174] A new item is saved into an installed writable package (ADR-0070 D1): + // every authoring save here names `WRITABLE`. const view = (name: string, extra: Record = {}) => ({ ...viewBody(name, 'Base'), ...extra }); const TWO_COLUMNS = [{ field: 'name', label: 'Name' }, { field: 'title', label: 'Title' }]; const readDraft = (protocol: any, name: string) => protocol.getMetaItem({ type: 'view', name, state: 'draft' }); @@ -1991,28 +2024,28 @@ describe('[#24395] the draft save records per-key provenance, the strict draft r for (const surface of ['copilot', 'mcp', 'studio', 'api', undefined] as const) { const name = `v_${surface ?? 'none'}`; await protocol.saveMetaItem({ - type: 'view', name, item: view(name), mode: 'draft', actor: 'u_1', ...(surface ? { surface } : {}), + packageId: WRITABLE, type: 'view', name, item: view(name), mode: 'draft', actor: 'u_1', ...(surface ? { surface } : {}), }); const read = await readDraft(protocol, name); expect(read.draftChanges).toEqual([{ path: [], by: surface ?? 'api', actor: 'u_1', at: expect.stringMatching(ISO_Z) }]); expect(GetMetaItemResponseSchema.safeParse(read).success).toBe(true); } // No actor recorded → `null`, never a sentinel. - await protocol.saveMetaItem({ type: 'view', name: 'v_anon', item: view('v_anon'), mode: 'draft' }); + await protocol.saveMetaItem({ packageId: WRITABLE, type: 'view', name: 'v_anon', item: view('v_anon'), mode: 'draft' }); expect((await readDraft(protocol, 'v_anon')).draftChanges[0].actor).toBeNull(); }); it('the first save is compared with the active row; the second replaces at or under what it changes', async () => { const { protocol } = makeProtocol(); - await protocol.saveMetaItem({ type: 'view', name: 'v_b', item: view('v_b', { description: 'pub' }) }); + await protocol.saveMetaItem({ packageId: WRITABLE, type: 'view', name: 'v_b', item: view('v_b', { description: 'pub' }) }); await protocol.saveMetaItem({ - type: 'view', name: 'v_b', mode: 'draft', surface: 'copilot', actor: 'u_1', + packageId: WRITABLE, type: 'view', name: 'v_b', mode: 'draft', surface: 'copilot', actor: 'u_1', item: view('v_b', { description: 'pub', label: 'AI', columns: TWO_COLUMNS }), }); const first = (await readDraft(protocol, 'v_b')).draftChanges; expect(first.map((e: any) => [e.path, e.by])).toEqual([[['label'], 'copilot'], [['columns'], 'copilot']]); await protocol.saveMetaItem({ - type: 'view', name: 'v_b', mode: 'draft', surface: 'studio', actor: 'u_1', + packageId: WRITABLE, type: 'view', name: 'v_b', mode: 'draft', surface: 'studio', actor: 'u_1', item: view('v_b', { description: 'pub', label: 'Hand', columns: TWO_COLUMNS }), }); const second = (await readDraft(protocol, 'v_b')).draftChanges; @@ -2023,16 +2056,16 @@ describe('[#24395] the draft save records per-key provenance, the strict draft r it('a save that changes no key path leaves the entries as they were', async () => { const { protocol, rows } = makeProtocol(); - await protocol.saveMetaItem({ type: 'view', name: 'v_same', item: view('v_same'), mode: 'draft', surface: 'copilot' }); + await protocol.saveMetaItem({ packageId: WRITABLE, type: 'view', name: 'v_same', item: view('v_same'), mode: 'draft', surface: 'copilot' }); const stored = rows('view', 'v_same', 'draft')[0].draft_changes; - await protocol.saveMetaItem({ type: 'view', name: 'v_same', item: view('v_same'), mode: 'draft', surface: 'studio' }); + await protocol.saveMetaItem({ packageId: WRITABLE, type: 'view', name: 'v_same', item: view('v_same'), mode: 'draft', surface: 'studio' }); expect(rows('view', 'v_same', 'draft')[0].draft_changes).toBe(stored); }); it('ABSENT on the active read, the ?preview=draft read, and a draft row saved before the writer', async () => { const { protocol, seedRow } = makeProtocol(); - await protocol.saveMetaItem({ type: 'view', name: 'v_abs', item: view('v_abs') }); - await protocol.saveMetaItem({ type: 'view', name: 'v_abs', item: view('v_abs', { label: 'D' }), mode: 'draft', surface: 'studio' }); + await protocol.saveMetaItem({ packageId: WRITABLE, type: 'view', name: 'v_abs', item: view('v_abs') }); + await protocol.saveMetaItem({ packageId: WRITABLE, type: 'view', name: 'v_abs', item: view('v_abs', { label: 'D' }), mode: 'draft', surface: 'studio' }); expect((await readDraft(protocol, 'v_abs')).draftChanges).toHaveLength(1); expect('draftChanges' in (await protocol.getMetaItem({ type: 'view', name: 'v_abs' }))).toBe(false); expect('draftChanges' in (await protocol.getMetaItem({ type: 'view', name: 'v_abs', previewDrafts: true }))).toBe(false); @@ -2044,24 +2077,24 @@ describe('[#24395] the draft save records per-key provenance, the strict draft r it('publish and discard leave no entry behind: the next draft starts from the published body', async () => { const { protocol, rows } = makeProtocol(); - await protocol.saveMetaItem({ type: 'view', name: 'v_p', item: view('v_p') }); - await protocol.saveMetaItem({ type: 'view', name: 'v_p', item: view('v_p', { label: 'AI' }), mode: 'draft', surface: 'copilot' }); - await protocol.publishMetaItem({ type: 'view', name: 'v_p' }); + await protocol.saveMetaItem({ packageId: WRITABLE, type: 'view', name: 'v_p', item: view('v_p') }); + await protocol.saveMetaItem({ packageId: WRITABLE, type: 'view', name: 'v_p', item: view('v_p', { label: 'AI' }), mode: 'draft', surface: 'copilot' }); + await protocol.publishMetaItem({ packageId: WRITABLE, type: 'view', name: 'v_p' }); expect(rows('view', 'v_p', 'draft')).toEqual([]); expect(rows('view', 'v_p', 'active').map((r) => r.draft_changes ?? null)).toEqual([null]); - await protocol.saveMetaItem({ type: 'view', name: 'v_p', item: view('v_p', { label: 'AI', description: 'd' }), mode: 'draft', surface: 'studio' }); + await protocol.saveMetaItem({ packageId: WRITABLE, type: 'view', name: 'v_p', item: view('v_p', { label: 'AI', description: 'd' }), mode: 'draft', surface: 'studio' }); expect((await readDraft(protocol, 'v_p')).draftChanges.map((e: any) => [e.path, e.by])).toEqual([[['description'], 'studio']]); - expect((await protocol.deleteMetaItem({ type: 'view', name: 'v_p', state: 'draft' })).reset).toBe(true); + expect((await protocol.deleteMetaItem({ packageId: WRITABLE, type: 'view', name: 'v_p', state: 'draft' })).reset).toBe(true); expect(rows('view', 'v_p', 'draft')).toEqual([]); - await protocol.saveMetaItem({ type: 'view', name: 'v_p', item: view('v_p', { label: 'AI', columns: TWO_COLUMNS }), mode: 'draft' }); + await protocol.saveMetaItem({ packageId: WRITABLE, type: 'view', name: 'v_p', item: view('v_p', { label: 'AI', columns: TWO_COLUMNS }), mode: 'draft' }); expect((await readDraft(protocol, 'v_p')).draftChanges.map((e: any) => [e.path, e.by])).toEqual([[['columns'], 'api']]); }); it('a draft whose body equals the published one records nothing, and the read answers it ABSENT, never []', async () => { const { protocol } = makeProtocol(); - await protocol.saveMetaItem({ type: 'view', name: 'v_eq', item: view('v_eq') }); - await protocol.saveMetaItem({ type: 'view', name: 'v_eq', item: view('v_eq'), mode: 'draft', surface: 'copilot' }); + await protocol.saveMetaItem({ packageId: WRITABLE, type: 'view', name: 'v_eq', item: view('v_eq') }); + await protocol.saveMetaItem({ packageId: WRITABLE, type: 'view', name: 'v_eq', item: view('v_eq'), mode: 'draft', surface: 'copilot' }); const read = await readDraft(protocol, 'v_eq'); expect(read.item.name).toBe('v_eq'); expect('draftChanges' in read).toBe(false); @@ -2069,16 +2102,16 @@ describe('[#24395] the draft save records per-key provenance, the strict draft r it('a `migrate-stored` rewrite of a draft row records no path: it is not authoring', async () => { const { protocol, rows } = makeProtocol(); - await protocol.saveMetaItem({ type: 'view', name: 'v_m', item: view('v_m'), mode: 'draft', surface: 'copilot' }); + await protocol.saveMetaItem({ packageId: WRITABLE, type: 'view', name: 'v_m', item: view('v_m'), mode: 'draft', surface: 'copilot' }); const stored = rows('view', 'v_m', 'draft')[0].draft_changes; - await protocol.saveMetaItem({ type: 'view', name: 'v_m', item: view('v_m', { label: 'Rewritten' }), mode: 'draft', source: 'migrate-stored' }); + await protocol.saveMetaItem({ packageId: WRITABLE, type: 'view', name: 'v_m', item: view('v_m', { label: 'Rewritten' }), mode: 'draft', source: 'migrate-stored' }); expect(JSON.parse(rows('view', 'v_m', 'draft')[0].metadata).label).toBe('Rewritten'); expect(rows('view', 'v_m', 'draft')[0].draft_changes).toBe(stored); }); it('an active save records nothing', async () => { const { protocol, rows } = makeProtocol(); - await protocol.saveMetaItem({ type: 'view', name: 'v_a', item: view('v_a'), surface: 'studio' }); + await protocol.saveMetaItem({ packageId: WRITABLE, type: 'view', name: 'v_a', item: view('v_a'), surface: 'studio' }); expect(rows('view', 'v_a', 'active')[0].draft_changes ?? null).toBeNull(); }); @@ -2094,9 +2127,9 @@ describe('[#24395] the draft save records per-key provenance, the strict draft r it('[#27176] an `mcp` save stamps its OAuth client beside `by` on every path it changes; a later save keeps it on the paths it leaves', async () => { const { protocol } = makeProtocol(); const client = { id: 'cli_claude', name: 'Claude' }; - await protocol.saveMetaItem({ type: 'view', name: 'v_mcp', item: view('v_mcp', { description: 'pub' }) }); + await protocol.saveMetaItem({ packageId: WRITABLE, type: 'view', name: 'v_mcp', item: view('v_mcp', { description: 'pub' }) }); await protocol.saveMetaItem({ - type: 'view', name: 'v_mcp', mode: 'draft', surface: 'mcp', client, actor: 'u_1', + packageId: WRITABLE, type: 'view', name: 'v_mcp', mode: 'draft', surface: 'mcp', client, actor: 'u_1', item: view('v_mcp', { description: 'pub', label: 'Agent', columns: TWO_COLUMNS }), }); const first = (await readDraft(protocol, 'v_mcp')); @@ -2106,7 +2139,7 @@ describe('[#24395] the draft save records per-key provenance, the strict draft r ]); expect(GetMetaItemResponseSchema.safeParse(first).success).toBe(true); await protocol.saveMetaItem({ - type: 'view', name: 'v_mcp', mode: 'draft', surface: 'studio', actor: 'u_1', + packageId: WRITABLE, type: 'view', name: 'v_mcp', mode: 'draft', surface: 'studio', actor: 'u_1', item: view('v_mcp', { description: 'pub', label: 'Hand', columns: TWO_COLUMNS }), }); const second = (await readDraft(protocol, 'v_mcp')).draftChanges; @@ -2114,11 +2147,11 @@ describe('[#24395] the draft save records per-key provenance, the strict draft r expect(second[1]).toEqual({ path: ['label'], by: 'studio', actor: 'u_1', at: expect.stringMatching(ISO_Z) }); // A client with no registered name is recorded by its id alone. await protocol.saveMetaItem({ - type: 'view', name: 'v_mcp_id', item: view('v_mcp_id'), mode: 'draft', surface: 'mcp', client: { id: 'cli_x' }, + packageId: WRITABLE, type: 'view', name: 'v_mcp_id', item: view('v_mcp_id'), mode: 'draft', surface: 'mcp', client: { id: 'cli_x' }, }); expect((await readDraft(protocol, 'v_mcp_id')).draftChanges[0].client).toEqual({ id: 'cli_x' }); // An `mcp` save that states no client records none — absent, never a placeholder. - await protocol.saveMetaItem({ type: 'view', name: 'v_mcp_none', item: view('v_mcp_none'), mode: 'draft', surface: 'mcp' }); + await protocol.saveMetaItem({ packageId: WRITABLE, type: 'view', name: 'v_mcp_none', item: view('v_mcp_none'), mode: 'draft', surface: 'mcp' }); expect('client' in (await readDraft(protocol, 'v_mcp_none')).draftChanges[0]).toBe(false); }); diff --git a/packages/metadata-protocol/src/protocol.permission-set-name-cross-package.test.ts b/packages/metadata-protocol/src/protocol.permission-set-name-cross-package.test.ts index a3e589155a1..8121e2faee2 100644 --- a/packages/metadata-protocol/src/protocol.permission-set-name-cross-package.test.ts +++ b/packages/metadata-protocol/src/protocol.permission-set-name-cross-package.test.ts @@ -269,6 +269,17 @@ async function stagedBeforeTheHardening(h: Harness, writes: () => Promise vi.restoreAllMocks()); +/** + * [#38174] A package-less CREATE is refused (ADR-0070 D1): a loose row is + * seeded directly, as the store writes it, and later saves of it run in place. + */ +async function seedLooseSet(h: Harness, name: string): Promise { + await h.engine.insert('sys_metadata', { + type: 'permission', name, organization_id: null, package_id: null, state: 'active', + metadata: JSON.stringify(perm(name)), version: 1, + }); +} + const SET = 'project_editor'; // ═══════════════════════════════════════════════════════════════════════════ @@ -356,6 +367,7 @@ describe('the save door refuses a permission set whose name another owner alread it('CONTROL: an environment author owns and edits its own runtime set', async () => { const h = makeProtocol(); + await seedLooseSet(h, 'env_editor'); await h.protocol.saveMetaItem({ type: 'permission', name: 'env_editor', item: perm('env_editor') }); const edit = await h.protocol.saveMetaItem({ type: 'permission', name: 'env_editor', item: { ...perm('env_editor'), label: 'Edited' } }); expect(edit.success).toBe(true); @@ -427,8 +439,8 @@ describe('the save door judges the binding the write lands in, not the request\' describe('a package-less row stored beside exactly one package\'s row is not a second owner', () => { /** The residue of the direct save before #23165: an environment-wide row of the name, then B's row beside it. */ async function residueBesideB(h: Harness) { + await seedLooseSet(h, SET); await stagedBeforeTheHardening(h, async () => { - await h.protocol.saveMetaItem({ type: 'permission', name: SET, item: perm(SET) }); await h.protocol.saveMetaItem({ type: 'permission', name: SET, item: perm(SET), packageId: OWNER_B }); }); expect(storedSets(h)).toEqual([ @@ -560,6 +572,7 @@ describe('the draft promotion refuses a permission-set draft whose name another describe('the restore door refuses to make a set a second holder of a name', () => { /** The environment's set, saved and then deleted: its first version stays in the history. */ async function savedThenDeleted(h: Harness): Promise { + await seedLooseSet(h, SET); await h.protocol.saveMetaItem({ type: 'permission', name: SET, item: perm(SET) }); await h.protocol.deleteMetaItem({ type: 'permission', name: SET }); expect(storedSets(h)).toEqual([]); diff --git a/packages/metadata-protocol/src/protocol.platform-mark-rollback.test.ts b/packages/metadata-protocol/src/protocol.platform-mark-rollback.test.ts index 5d99140bddd..bb0c242b968 100644 --- a/packages/metadata-protocol/src/protocol.platform-mark-rollback.test.ts +++ b/packages/metadata-protocol/src/protocol.platform-mark-rollback.test.ts @@ -86,13 +86,31 @@ function makeEngine() { } +/** + * [#38174] A package-less create is refused (ADR-0070 D1), and the loose rows + * this file pins are the platform's own registration (W13, which never reaches + * the save door). The name's loose row and its v1 history snapshot are seeded + * directly through the engine, as the store writes them; later saves run in place. + */ +async function seedLooseV1(engine: any, item: { name: string } & Record): Promise { + const metadata = JSON.stringify(item); + await engine.insert('sys_metadata', { + type: 'skill', name: item.name, state: 'active', organization_id: null, package_id: null, + version: 1, checksum: `seed_${item.name}_v1`, source: 'database', metadata, + }); + await engine.insert('sys_metadata_history', { + id: `hist_${item.name}_v1`, type: 'skill', name: item.name, version: 1, organization_id: null, package_id: null, + operation_type: 'create', checksum: `seed_${item.name}_v1`, metadata, + }); +} + const skill = (label: string) => ({ name: 'helper', label, instructions: 'help', tools: ['query_records'] }); describe('[#37013] the protocol\'s save and restore doors write a body without the platform\'s mark', () => { it('a version that held the mark is restored without it (BASE: the row was marked again)', async () => { const { engine, rows, historyRows } = makeEngine(); const protocol = new ObjectStackProtocolImplementation(engine); - await protocol.saveMetaItem({ type: 'skill', name: 'helper', item: skill('v1') }); + await seedLooseV1(engine, skill('v1')); // The version as the platform's own registration stored it. const v1 = historyRows.find((r) => r.name === 'helper')!; v1.metadata = JSON.stringify({ ...JSON.parse(String(v1.metadata)), _provenance: 'platform' }); @@ -108,6 +126,7 @@ describe('[#37013] the protocol\'s save and restore doors write a body without t it('the save door stores a body that carried the mark without it (BASE: stored as sent)', async () => { const { engine, rows } = makeEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseV1(engine, skill('v0')); await protocol.saveMetaItem({ type: 'skill', name: 'helper', item: { ...skill('v1'), _provenance: 'platform' } }); const stored = JSON.parse(String(rows.find((r) => r.name === 'helper')!.metadata)); expect(stored.label).toBe('v1'); @@ -117,7 +136,7 @@ describe('[#37013] the protocol\'s save and restore doors write a body without t it('revertCommit\'s restore limb writes a version that held the mark back without it (BASE: the row was marked again)', async () => { const { engine, rows, historyRows, serveCommit } = makeEngine(); const protocol = new ObjectStackProtocolImplementation(engine); - await protocol.saveMetaItem({ type: 'skill', name: 'helper', item: skill('v1') }); + await seedLooseV1(engine, skill('v1')); const v1 = historyRows.find((r) => r.name === 'helper')!; v1.metadata = JSON.stringify({ ...JSON.parse(String(v1.metadata)), _provenance: 'platform' }); await protocol.saveMetaItem({ type: 'skill', name: 'helper', item: skill('v2') }); @@ -156,7 +175,7 @@ describe('[#37130] the protocol\'s restore doors refuse a restore whose row is t async function platformRecord(name = 'helper') { const harness = makeEngine(); const protocol = new ObjectStackProtocolImplementation(harness.engine); - await protocol.saveMetaItem({ type: 'skill', name, item: { ...skill('platform v1'), name } }); + await seedLooseV1(harness.engine, { ...skill('platform v1'), name }); await protocol.saveMetaItem({ type: 'skill', name, item: { ...skill('platform v2'), name } }); const mark = (row: Row) => { row.metadata = JSON.stringify({ ...JSON.parse(String(row.metadata)), _provenance: 'platform' }); }; for (const row of harness.historyRows.filter((r) => r.name === name)) mark(row); @@ -176,8 +195,8 @@ describe('[#37130] the protocol\'s restore doors refuse a restore whose row is t }); it('revertCommit\'s restore limb: the item lands in failed[] 409-coded, nothing written, and the commit\'s other item still reverts (BASE: written back without the mark)', async () => { - const { protocol, rows, serveCommit } = await platformRecord(); - await protocol.saveMetaItem({ type: 'skill', name: 'other', item: { ...skill('other v1'), name: 'other' } }); + const { protocol, engine, rows, serveCommit } = await platformRecord(); + await seedLooseV1(engine, { ...skill('other v1'), name: 'other' }); await protocol.saveMetaItem({ type: 'skill', name: 'other', item: { ...skill('other v2'), name: 'other' } }); const helperBefore = JSON.stringify(rows.find((r) => r.name === 'helper')); serveCommit({ @@ -241,7 +260,7 @@ describe('[#37604] a version the platform registered is never restored into a pa async function withdrawnPlatformRecord() { const harness = makeEngine(); const protocol = new ObjectStackProtocolImplementation(harness.engine); - await protocol.saveMetaItem({ type: 'skill', name: 'helper', item: skill('platform v1') }); + await seedLooseV1(harness.engine, skill('platform v1')); await protocol.saveMetaItem({ type: 'skill', name: 'helper', item: skill('platform v2') }); const mark = (row: Row) => { row.metadata = JSON.stringify({ ...JSON.parse(String(row.metadata)), _provenance: 'platform' }); }; for (const row of harness.historyRows.filter((r) => r.name === 'helper')) mark(row); diff --git a/packages/metadata-protocol/src/protocol.platform-schedule-org-gate.test.ts b/packages/metadata-protocol/src/protocol.platform-schedule-org-gate.test.ts index 7713cac8bbd..fdd1c87eb87 100644 --- a/packages/metadata-protocol/src/protocol.platform-schedule-org-gate.test.ts +++ b/packages/metadata-protocol/src/protocol.platform-schedule-org-gate.test.ts @@ -322,6 +322,9 @@ interface Row { const keyOf = (w: Record) => `${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}`; +/** The writable package an admitted new flow is saved into. */ +const TEST_PKG = 'test_pkg'; + function makeStubEngine() { // ⚠️ Keyed BY TABLE, and that is a correctness property of this harness // rather than tidiness. One flat row map answers a read of `sys_metadata` @@ -398,6 +401,8 @@ function makeStubEngine() { ? [{ name: 'sweep_log', label: 'Sweep Log', + // [#38174] held by the package a new flow is saved into. + _packageId: TEST_PKG, fields: { note: { type: 'text', label: 'Note' }, due_date: { type: 'date', label: 'Due' }, @@ -405,6 +410,9 @@ function makeStubEngine() { }] : [], getItem: () => undefined, + // [#38174] installs {@link TEST_PKG}: a new item is saved into a + // writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), }, }; return { engine, rows }; @@ -469,7 +477,7 @@ describe('#6285 refusal through saveMetaItem / publishMetaItem', () => { it('allows the same flow once the author declares fields.organization_id', async () => { const { protocol, rows } = makeProtocol(); - const result = await save(protocol, scheduledSweepWithOrg()); + const result = await save(protocol, scheduledSweepWithOrg(), { packageId: TEST_PKG }); expect(result.success).toBe(true); expect(flowRows(rows).length).toBe(1); }); @@ -477,7 +485,7 @@ describe('#6285 refusal through saveMetaItem / publishMetaItem', () => { it('allows it on a single-organization deployment', async () => { process.env.OS_TENANCY_POSTURE = 'single'; const { protocol, rows } = makeProtocol(); - const result = await save(protocol, scheduledSweep()); + const result = await save(protocol, scheduledSweep(), { packageId: TEST_PKG }); expect(result.success).toBe(true); expect(flowRows(rows).length).toBe(1); }); @@ -523,7 +531,7 @@ describe('#6285 refusal through saveMetaItem / publishMetaItem', () => { const { protocol, rows } = makeProtocol(); // D1 — a draft is allowed to be half-finished and cannot execute. - const draft = await save(protocol, scheduledSweep(), { mode: 'draft' }); + const draft = await save(protocol, scheduledSweep(), { mode: 'draft', packageId: TEST_PKG }); expect(draft.success).toBe(true); expect(flowRows(rows).map((r) => r.state)).toContain('draft'); @@ -541,7 +549,7 @@ describe('#6285 refusal through saveMetaItem / publishMetaItem', () => { process.env.OS_ALLOW_UNLINTED_METADATA_WRITES = '1'; const { protocol, rows } = makeProtocol(); - const result = await save(protocol, scheduledSweep()); + const result = await save(protocol, scheduledSweep(), { packageId: TEST_PKG }); expect(result.success).toBe(true); expect(flowRows(rows).length).toBe(1); @@ -570,6 +578,7 @@ describe('#6285 refusal through saveMetaItem / publishMetaItem', () => { type: 'flow', name: 'nightly_sweep', item: scheduledSweep(), + packageId: TEST_PKG, }); expect(result.success).toBe(true); expect(flowRows(rows).length).toBe(1); @@ -615,6 +624,6 @@ describe('#6285 refusal through saveMetaItem / publishMetaItem', () => { // …and a clean body is still publishable, so the fail-closed reading // never becomes "refuse everything". const { protocol: p2 } = makeProtocol(); - await expect(save(p2, scheduledSweepWithOrg())).resolves.toMatchObject({ success: true }); + await expect(save(p2, scheduledSweepWithOrg(), { packageId: TEST_PKG })).resolves.toMatchObject({ success: true }); }); }); diff --git a/packages/metadata-protocol/src/protocol.platform-store-system-opt-in.test.ts b/packages/metadata-protocol/src/protocol.platform-store-system-opt-in.test.ts index 9bdbdc611df..79cd693a70e 100644 --- a/packages/metadata-protocol/src/protocol.platform-store-system-opt-in.test.ts +++ b/packages/metadata-protocol/src/protocol.platform-store-system-opt-in.test.ts @@ -293,9 +293,12 @@ describe('platform-store calls carry the explicit system opt-in (#21911)', () => const { engine, calls } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); - await protocol.saveMetaItem({ - type: 'view', name: 'orphan_grid', item: viewBody('orphan_grid'), mode: 'publish', - }); + // [#38174] a package-less CREATE is refused (ADR-0070 D1): the loose + // row the move door judges is seeded directly through the engine. + await engine.insert('sys_metadata', { + type: 'view', name: 'orphan_grid', organization_id: null, package_id: null, state: 'active', + metadata: JSON.stringify(viewBody('orphan_grid')), + }, { context: { isSystem: true } }); await protocol.saveMetaItem({ type: 'view', name: 'pin_grid', item: viewBody('pin_grid'), packageId: 'app.pin', mode: 'publish', }); @@ -326,7 +329,7 @@ describe('[#21908] row 23 — the repository reads the engine-lane slice left ca const { engine, calls, historyRows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); await protocol.saveMetaItem({ - type: 'view', name: 'proj_task_grid', item: viewBody('proj_task_grid'), mode: 'publish', + type: 'view', name: 'proj_task_grid', item: viewBody('proj_task_grid'), packageId: 'app.pin', mode: 'publish', }); // The population the reads below must find, written by the save above. expect(historyRows.length).toBeGreaterThan(0); @@ -365,7 +368,7 @@ describe('[#21908] the deny round — the platform-store calls still reaching th it('the publish path: the promotion draft read', async () => { const { engine, calls } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine) as any; - await protocol.saveMetaItem({ type: 'view', name: 'proj_task_grid', item: viewBody('proj_task_grid'), mode: 'draft' }); + await protocol.saveMetaItem({ type: 'view', name: 'proj_task_grid', item: viewBody('proj_task_grid'), packageId: 'app.pin', mode: 'draft' }); // No package stated: the promotion reads the draft row's own binding. await expectSystemOptIn(calls, 'publishMetaItem', async () => { @@ -378,7 +381,7 @@ describe('[#21908] the deny round — the platform-store calls still reaching th it('the readers behind the history, audit, diff and commit doors', async () => { const { engine, calls } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine) as any; - await protocol.saveMetaItem({ type: 'view', name: 'proj_task_grid', item: viewBody('proj_task_grid'), mode: 'publish' }); + await protocol.saveMetaItem({ type: 'view', name: 'proj_task_grid', item: viewBody('proj_task_grid'), packageId: 'app.pin', mode: 'publish' }); await expectSystemOptIn(calls, 'auditMetaItem', () => protocol.auditMetaItem({ type: 'view', name: 'proj_task_grid' })); @@ -395,7 +398,7 @@ describe('[#21908] the deny round — the platform-store calls still reaching th it('the namespace probe, the migration scan and the legacy (code-only) delete', async () => { const { engine, calls } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine) as any; - await protocol.saveMetaItem({ type: 'view', name: 'proj_task_grid', item: viewBody('proj_task_grid'), mode: 'publish' }); + await protocol.saveMetaItem({ type: 'view', name: 'proj_task_grid', item: viewBody('proj_task_grid'), packageId: 'app.pin', mode: 'publish' }); await expectSystemOptIn(calls, 'metaTypeNamespaceExists', () => protocol.metaTypeNamespaceExists('view')); await expectSystemOptIn(calls, 'migrateStoredMetadata', () => protocol.migrateStoredMetadata({})); diff --git a/packages/metadata-protocol/src/protocol.read-decorations.test.ts b/packages/metadata-protocol/src/protocol.read-decorations.test.ts index dfb49573715..72dc01dfb2a 100644 --- a/packages/metadata-protocol/src/protocol.read-decorations.test.ts +++ b/packages/metadata-protocol/src/protocol.read-decorations.test.ts @@ -72,6 +72,9 @@ function keyOf(w: Record) { return `${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}|${w.package_id ?? '__nopkg__'}`; } +/** [#38174] An installed writable package: a save of a NEW item names one (ADR-0070 D1). */ +const TEST_PKG = 'test_pkg'; + function makeStubEngine() { const rows = new Map(); let nextId = 0; @@ -116,7 +119,7 @@ function makeStubEngine() { getItem: () => undefined, registerItem: () => {}, registerObject: () => {}, - getPackage: () => undefined, + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), }, }; return { engine, rows }; @@ -190,7 +193,7 @@ describe('saveMetaItem — the Studio round-trip persists a byte-identical body const protocol = new ObjectStackProtocolImplementation(engine); const authored = objectBody('crm_invoice'); - await protocol.saveMetaItem({ type: 'object', name: 'crm_invoice', item: authored }); + await protocol.saveMetaItem({ type: 'object', packageId: TEST_PKG, name: 'crm_invoice', item: authored }); const firstStored = storedBody(rows, 'crm_invoice'); // What Studio actually holds: the SERVED document, decorations included. @@ -199,7 +202,7 @@ describe('saveMetaItem — the Studio round-trip persists a byte-identical body // Edit one label and PUT the whole thing back, as the designer does. await protocol.saveMetaItem({ - type: 'object', + type: 'object', packageId: TEST_PKG, name: 'crm_invoice', item: { ...served, label: 'Invoice (edited)' }, }); @@ -216,7 +219,7 @@ describe('saveMetaItem — the Studio round-trip persists a byte-identical body const protocol = new ObjectStackProtocolImplementation(engine); await protocol.saveMetaItem({ - type: 'object', name: 'crm_quote', item: objectBody('crm_quote'), mode: 'draft', + type: 'object', packageId: TEST_PKG, name: 'crm_quote', item: objectBody('crm_quote'), mode: 'draft', }); // The badge comes from the PREVIEW read (`previewDrafts`), which is what // the designer's "preview pending changes" surface calls — a plain @@ -227,7 +230,7 @@ describe('saveMetaItem — the Studio round-trip persists a byte-identical body expect(draft._draft).toBe(true); // precondition — the preview read badges await protocol.saveMetaItem({ - type: 'object', name: 'crm_quote', item: draft, mode: 'draft', + type: 'object', packageId: TEST_PKG, name: 'crm_quote', item: draft, mode: 'draft', }); const stored = storedBody(rows, 'crm_quote'); @@ -241,13 +244,13 @@ describe('saveMetaItem — the Studio round-trip persists a byte-identical body const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); - await protocol.saveMetaItem({ type: 'object', name: 'crm_lead', item: objectBody('crm_lead') }); + await protocol.saveMetaItem({ type: 'object', packageId: TEST_PKG, name: 'crm_lead', item: objectBody('crm_lead') }); const before = Array.from(rows.values()).find((r) => r.name === 'crm_lead')!.checksum; // Re-save the served document unchanged — the only difference is our own // decoration, so the content hash must not move. const served: any = (await protocol.getMetaItem({ type: 'object', name: 'crm_lead' })).item; - await protocol.saveMetaItem({ type: 'object', name: 'crm_lead', item: served }); + await protocol.saveMetaItem({ type: 'object', packageId: TEST_PKG, name: 'crm_lead', item: served }); const after = Array.from(rows.values()).find((r) => r.name === 'crm_lead')!.checksum; expect(after).toBe(before); @@ -307,7 +310,7 @@ describe('[#34901] the served object carries `_withheldFields`; a GET → edit it('the served read stamps it, the layered (editor) read does not, and the PUT stores none of it', async () => { const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(withWithheldReader(engine)); - await protocol.saveMetaItem({ type: 'object', name: 'crm_invoice', item: objectBody('crm_invoice') }); + await protocol.saveMetaItem({ type: 'object', packageId: TEST_PKG, name: 'crm_invoice', item: objectBody('crm_invoice') }); const firstStored = storedBody(rows, 'crm_invoice'); const served: any = (await protocol.getMetaItem({ type: 'object', name: 'crm_invoice' })).item; @@ -316,7 +319,7 @@ describe('[#34901] the served object carries `_withheldFields`; a GET → edit const layered: any = await (protocol as any).getMetaItemLayered({ type: 'object', name: 'crm_invoice' }); expect(JSON.stringify(layered ?? null)).not.toContain('_withheldFields'); - await protocol.saveMetaItem({ type: 'object', name: 'crm_invoice', item: { ...served, label: 'Invoice (edited)' } }); + await protocol.saveMetaItem({ type: 'object', packageId: TEST_PKG, name: 'crm_invoice', item: { ...served, label: 'Invoice (edited)' } }); const stored = storedBody(rows, 'crm_invoice'); expect('_withheldFields' in stored).toBe(false); expect({ ...stored, label: firstStored.label }).toEqual(firstStored); @@ -325,7 +328,7 @@ describe('[#34901] the served object carries `_withheldFields`; a GET → edit it('control: nothing withheld ⇒ no marker on the served read', async () => { const { engine } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(withWithheldReader(engine)); - await protocol.saveMetaItem({ type: 'object', name: 'crm_other', item: objectBody('crm_other') }); + await protocol.saveMetaItem({ type: 'object', packageId: TEST_PKG, name: 'crm_other', item: objectBody('crm_other') }); const served: any = (await protocol.getMetaItem({ type: 'object', name: 'crm_other' })).item; expect('_withheldFields' in served).toBe(false); }); @@ -335,8 +338,11 @@ describe('a served document survives its own (closed) schema — cloud#971', () /** Serve `flowBody(name)` back through the real read path. */ async function serveFlow(name: string): Promise> { const { engine } = makeStubEngine(); + // [#38174] The flow is saved into a package, so its trigger object is + // judged inside that package's closure: the registry serves `task`. + engine.registry.listItems = (type: string) => (type === 'object' ? [{ name: 'task', label: 'Task' }] : []); const protocol = new ObjectStackProtocolImplementation(engine); - await protocol.saveMetaItem({ type: 'flow', name, item: flowBody(name) }); + await protocol.saveMetaItem({ type: 'flow', packageId: TEST_PKG, name, item: flowBody(name) }); const res: any = await protocol.getMetaItems({ type: 'flow' }); const items: any[] = Array.isArray(res) ? res : (res?.items ?? []); const served = items.find((i) => i?.name === name); @@ -454,7 +460,7 @@ describe('draft preview diagnostics do not judge the injected `_draft` badge (#7 const { engine } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); await protocol.saveMetaItem({ - type: 'object', name: 'crm_quote', item: objectBody('crm_quote'), mode: 'draft', + type: 'object', packageId: TEST_PKG, name: 'crm_quote', item: objectBody('crm_quote'), mode: 'draft', }); const served: any = (await protocol.getMetaItem({ @@ -505,7 +511,7 @@ describe('draft preview diagnostics do not judge the injected `_draft` badge (#7 const { engine } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); await protocol.saveMetaItem({ - type: 'object', name: 'crm_quote', item: objectBody('crm_quote'), mode: 'draft', + type: 'object', packageId: TEST_PKG, name: 'crm_quote', item: objectBody('crm_quote'), mode: 'draft', }); const served = await listed(protocol, 'crm_quote'); @@ -606,9 +612,9 @@ describe('[#20101] a page saved without `type` stores and serves the declared de const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); - await protocol.saveMetaItem({ type: 'page', name: 'invoice_record', item: typelessPage('invoice_record') }); + await protocol.saveMetaItem({ type: 'page', packageId: TEST_PKG, name: 'invoice_record', item: typelessPage('invoice_record') }); await protocol.saveMetaItem({ - type: 'page', name: 'invoice_record_next', item: typelessPage('invoice_record_next'), mode: 'draft', + type: 'page', packageId: TEST_PKG, name: 'invoice_record_next', item: typelessPage('invoice_record_next'), mode: 'draft', }); expect(JSON.parse(rowOf(rows, 'invoice_record').metadata)).toEqual({ ...typelessPage('invoice_record'), type: DECLARED }); @@ -627,7 +633,7 @@ describe('[#20101] a page saved without `type` stores and serves the declared de const protocol = new ObjectStackProtocolImplementation(engine); const appPage = { name: 'launchpad', label: 'Launchpad', type: 'app' }; - await protocol.saveMetaItem({ type: 'page', name: 'launchpad', item: appPage }); + await protocol.saveMetaItem({ type: 'page', packageId: TEST_PKG, name: 'launchpad', item: appPage }); expect(JSON.parse(rowOf(rows, 'launchpad').metadata)).toEqual(appPage); const single: any = await protocol.getMetaItem({ type: 'page', name: 'launchpad' }); @@ -638,12 +644,12 @@ describe('[#20101] a page saved without `type` stores and serves the declared de const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); - await protocol.saveMetaItem({ type: 'page', name: 'invoice_record', item: typelessPage('invoice_record') }); + await protocol.saveMetaItem({ type: 'page', packageId: TEST_PKG, name: 'invoice_record', item: typelessPage('invoice_record') }); const before = { ...rowOf(rows, 'invoice_record') }; const served: any = (await protocol.getMetaItem({ type: 'page', name: 'invoice_record' })).item; expect(served.type).toBe(DECLARED); // precondition — the served body carries the default - await protocol.saveMetaItem({ type: 'page', name: 'invoice_record', item: served }); + await protocol.saveMetaItem({ type: 'page', packageId: TEST_PKG, name: 'invoice_record', item: served }); const after = rowOf(rows, 'invoice_record'); expect(after.metadata).toBe(before.metadata); diff --git a/packages/metadata-protocol/src/protocol.recovery-doors-mutation-projector.test.ts b/packages/metadata-protocol/src/protocol.recovery-doors-mutation-projector.test.ts index be50cc93037..8e60d14d722 100644 --- a/packages/metadata-protocol/src/protocol.recovery-doors-mutation-projector.test.ts +++ b/packages/metadata-protocol/src/protocol.recovery-doors-mutation-projector.test.ts @@ -448,15 +448,22 @@ describe('door 3 — deleteMetaItem’s legacy raw-engine exit projects state: d describe('no projector registered: unchanged behavior, best-effort by contract', () => { it('rollbackMetaItem succeeds exactly as before when the type has no registered projector', async () => { - const { protocol, projected } = makeProtocol(); + const { protocol, projected, engine } = makeProtocol(); + // [#38174] The view is saved into `PKG` (ADR-0070 D1), so the object + // it lists is stored in `PKG` too: a list view's object is judged + // against the package closure. + await engine.insert('sys_metadata', { + type: 'object', name: 'case', organization_id: null, package_id: PKG, state: 'active', + metadata: JSON.stringify(objectBody('case', 'Case')), + }); // `view` has no projector registered by this harness (only `object` // and `api` do) — the exact "nothing registered for this type" arm // `runMutationProjector` itself documents. await protocol.saveMetaItem({ - type: 'view', name: 'cases', item: { name: 'cases', type: 'grid', label: 'A', columns: ['id'], object: 'case', viewKind: 'list' }, + type: 'view', name: 'cases', item: { name: 'cases', type: 'grid', label: 'A', columns: ['id'], object: 'case', viewKind: 'list' }, packageId: PKG, }); await protocol.saveMetaItem({ - type: 'view', name: 'cases', item: { name: 'cases', type: 'grid', label: 'B', columns: ['id'], object: 'case', viewKind: 'list' }, + type: 'view', name: 'cases', item: { name: 'cases', type: 'grid', label: 'B', columns: ['id'], object: 'case', viewKind: 'list' }, packageId: PKG, }); const res = await protocol.rollbackMetaItem({ type: 'view', name: 'cases', toVersion: 1 }); diff --git a/packages/metadata-protocol/src/protocol.refusal-audit-rows.test.ts b/packages/metadata-protocol/src/protocol.refusal-audit-rows.test.ts index 195f0470deb..77eec82e38a 100644 --- a/packages/metadata-protocol/src/protocol.refusal-audit-rows.test.ts +++ b/packages/metadata-protocol/src/protocol.refusal-audit-rows.test.ts @@ -48,6 +48,8 @@ const row = (o: Partial & { type: string; name: string }): Row => ({ }); const PARENT = 'crm_task'; +/** The writable package the control's create names. */ +const TEST_PKG = 'test_pkg'; const FIELD = 'zz_probe'; const DOTTED = `${PARENT}.${FIELD}`; @@ -120,6 +122,9 @@ function makeKernel(seed: Row[] = [], artifacts: Record = {}) { getItem: () => undefined, getArtifactItem: (t: string, n: string) => artifacts[`${t}|${n}`], removeRuntimeShadow: () => false, removeOverlayEntry: () => {}, uninstallPackage: () => {}, + // [#38174] installs {@link TEST_PKG}: a new item is saved into a + // writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), }, }; @@ -154,6 +159,7 @@ describe('[#28355] CONTROL — an allowed save leaves its allowed row and no den type: 'object', name: PARENT, item: { name: PARENT, label: PARENT, sharingModel: 'private', fields: { a: { name: 'a', type: 'text' } } }, + packageId: TEST_PKG, actor: 'usr_author', }); expect(audit).toEqual([ diff --git a/packages/metadata-protocol/src/protocol.restore-doors-save-refusal-family.test.ts b/packages/metadata-protocol/src/protocol.restore-doors-save-refusal-family.test.ts index 7d003ac0c1b..a963ebc1d1a 100644 --- a/packages/metadata-protocol/src/protocol.restore-doors-save-refusal-family.test.ts +++ b/packages/metadata-protocol/src/protocol.restore-doors-save-refusal-family.test.ts @@ -228,6 +228,21 @@ function makeProtocol() { type Harness = ReturnType; +/** + * [#38174] A package-less CREATE is refused (ADR-0070 D1). The items these + * restores act on are the environment's loose rows, so each is seeded loose + * directly, as the store writes it (relabelled, so the first save is a change), + * and the stage's package-less saves then run in place. History versions are + * counted from the history table, which the seed leaves empty: the stage's + * saves are still versions 1, 2 and 3. + */ +async function seedLoose(h: Harness, type: string, name: string, item: Record, state: 'active' | 'draft' = 'active') { + await h.engine.insert('sys_metadata', { + type, name, organization_id: null, package_id: null, state, + metadata: JSON.stringify({ ...item, label: 'Seeded' }), + }); +} + /** The active row of one item, as stored, or `null`. */ const activeBody = (h: Harness, type: string, name: string) => { const row = Array.from(h.rows.values()).find((r) => r.type === type && r.name === name && r.state === 'active'); @@ -408,6 +423,7 @@ pinBothDoors({ code: 'VALIDATION_ERROR', status: 400, async stage(h) { + await seedLoose(h, 'hook', 'stamp_assignee', hook('v1')); await h.protocol.saveMetaItem({ type: 'hook', name: 'stamp_assignee', item: hook('v1') }); await h.protocol.saveMetaItem({ type: 'hook', name: 'stamp_assignee', item: hook('v2') }); await h.protocol.saveMetaItem({ type: 'hook', name: 'stamp_assignee', item: hook('v3') }); @@ -425,10 +441,12 @@ pinBothDoors({ code: 'DEFAULT_RECORD_PAGE_CONFLICT', status: 422, async stage(h) { + await seedLoose(h, 'page', 'org_detail_a', recordPage('org_detail_a', true)); await h.protocol.saveMetaItem({ type: 'page', name: 'org_detail_a', item: recordPage('org_detail_a', true) }); await h.protocol.saveMetaItem({ type: 'page', name: 'org_detail_a', item: recordPage('org_detail_a', false) }); await h.protocol.saveMetaItem({ type: 'page', name: 'org_detail_a', item: recordPage('org_detail_a', false, 'A v3') }); // Another page took the default after v1 was saved. + await seedLoose(h, 'page', 'org_detail_b', recordPage('org_detail_b', false)); await h.protocol.saveMetaItem({ type: 'page', name: 'org_detail_b', item: recordPage('org_detail_b', true) }); return { refused: 1, accepted: 2 }; }, @@ -445,9 +463,11 @@ pinBothDoors({ code: 'INVALID_METADATA', status: 422, async stage(h) { + await seedLoose(h, 'datasource', 'wh', datasource({ schemaMode: 'managed' })); await h.protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource({ schemaMode: 'managed' }) }); await h.protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource(FEDERATED) }); await h.protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource({ ...FEDERATED, label: 'Warehouse v3' }) }); + await seedLoose(h, 'object', 'wh_order', order()); await h.protocol.saveMetaItem({ type: 'object', name: 'wh_order', item: order(EXTERNAL) }); return { refused: 1, accepted: 2 }; }, @@ -464,7 +484,9 @@ pinBothDoors({ code: 'INVALID_METADATA', status: 422, async stage(h) { + await seedLoose(h, 'datasource', 'wh', datasource(FEDERATED)); await h.protocol.saveMetaItem({ type: 'datasource', name: 'wh', item: datasource(FEDERATED) }); + await seedLoose(h, 'object', 'wh_order', order()); await h.protocol.saveMetaItem({ type: 'object', name: 'wh_order', item: order(EXTERNAL) }); await h.protocol.saveMetaItem({ type: 'object', name: 'wh_order', item: order() }); await h.protocol.saveMetaItem({ type: 'object', name: 'wh_order', item: order({ label: 'Order v3' }) }); @@ -485,6 +507,7 @@ pinBothDoors({ code: 'INVALID_METADATA', status: 422, async stage(h) { + await seedLoose(h, 'flow', FLOW, flow('user')); await h.protocol.saveMetaItem({ type: 'flow', name: FLOW, item: flow('system') }); await h.protocol.saveMetaItem({ type: 'flow', name: FLOW, item: flow('user') }); await h.protocol.saveMetaItem({ type: 'flow', name: FLOW, item: flow('user', 'Partner intake v3') }); @@ -503,6 +526,7 @@ pinBothDoors({ status: 422, async stage(h) { h.drivers.add('rt_store'); + await seedLoose(h, 'object', 'wh_order', order({ datasource: undefined })); await h.protocol.saveMetaItem({ type: 'object', name: 'wh_order', item: order({ datasource: 'rt_store' }) }); await h.protocol.saveMetaItem({ type: 'object', name: 'wh_order', item: order({ datasource: undefined }) }); await h.protocol.saveMetaItem({ type: 'object', name: 'wh_order', item: order({ datasource: undefined, label: 'Order v3' }) }); @@ -525,6 +549,7 @@ pinBothDoors({ async stage(h) { h.objects.set('qa_widget', { name: 'qa_widget' }); const set = (objects: Record, label = 'Widget editor') => ({ name: 'qa_widget_editor', label, objects }); + await seedLoose(h, 'permission', 'qa_widget_editor', set({})); await h.protocol.saveMetaItem({ type: 'permission', name: 'qa_widget_editor', item: set({ qa_widget: { allowRead: true } }) }); await h.protocol.saveMetaItem({ type: 'permission', name: 'qa_widget_editor', item: set({}) }); await h.protocol.saveMetaItem({ type: 'permission', name: 'qa_widget_editor', item: set({}, 'Widget editor v3') }); @@ -549,6 +574,7 @@ pinBothDoors({ const deal = (fields: Record, label = 'Deal') => ({ name: 'qa_deal', label, sharingModel: 'private', fields: { name: { type: 'text', label: 'Name' }, ...fields }, }); + await seedLoose(h, 'object', 'qa_deal', deal({})); await h.protocol.saveMetaItem({ type: 'object', name: 'qa_deal', item: deal({ tier: { type: 'select', label: 'Tier', picklist: 'qa_tier' } }) }); // v2 drops the field (a destructive change, so `force`). await h.protocol.saveMetaItem({ type: 'object', name: 'qa_deal', item: deal({}), force: true }); @@ -575,6 +601,7 @@ pinBothDoors({ ...(label ? { label } : {}), }); h.objects.set('wh_order', { name: 'wh_order', fields: { name: { type: 'text' }, code: { type: 'text' } } }); + await seedLoose(h, 'seed', 'wh_order_seed', seedOf('name'), 'draft'); await h.protocol.saveMetaItem({ type: 'seed', name: 'wh_order_seed', item: seedOf('code'), mode: 'draft' }); await h.protocol.saveMetaItem({ type: 'seed', name: 'wh_order_seed', item: seedOf('name'), mode: 'draft' }); await h.protocol.publishMetaItem({ type: 'seed', name: 'wh_order_seed' }); @@ -595,6 +622,7 @@ pinBothDoors({ code: 'INVALID_METADATA', status: 422, async stage(h) { + await seedLoose(h, 'object', 'acme_task', task(false)); await h.protocol.saveMetaItem({ type: 'object', name: 'acme_task', item: task(false) }); await h.protocol.saveMetaItem({ type: 'object', name: 'acme_task', item: { ...task(false), label: 'Task v2' } }); await h.protocol.saveMetaItem({ type: 'object', name: 'acme_task', item: { ...task(false), label: 'Task v3' } }); @@ -612,6 +640,7 @@ pinBothDoors({ code: 'PERMISSION_DENIED', status: 403, async stage(h) { + await seedLoose(h, 'dashboard', 'dash_a', dash('v0')); await h.protocol.saveMetaItem({ type: 'dashboard', name: 'dash_a', item: dash('Refused by the gate') }); await h.protocol.saveMetaItem({ type: 'dashboard', name: 'dash_a', item: dash('v2') }); await h.protocol.saveMetaItem({ type: 'dashboard', name: 'dash_a', item: dash('v3') }); @@ -662,6 +691,7 @@ pinBothDoors({ code: 'INVALID_METADATA', status: 422, async stage(h) { + await seedLoose(h, 'flow', LEGACY_FLOW, fetchFlow('v0', 'filter')); await h.protocol.saveMetaItem({ type: 'flow', name: LEGACY_FLOW, item: fetchFlow('v1', 'filter') }); await h.protocol.saveMetaItem({ type: 'flow', name: LEGACY_FLOW, item: fetchFlow('v2', 'filter') }); await h.protocol.saveMetaItem({ type: 'flow', name: LEGACY_FLOW, item: fetchFlow('v3', 'filter') }); diff --git a/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts b/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts index c2c8cecb2e0..f0ce2c5e285 100644 --- a/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts +++ b/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts @@ -65,7 +65,12 @@ import { * before any gate this file pins is reached. Each answers a manifest that * declares no dependencies, as an authored base does. */ -const INSTALLED_PACKAGES: ReadonlySet = new Set(['app.fx', 'com.example.pages']); +const INSTALLED_PACKAGES: ReadonlySet = new Set(['app.fx', 'com.example.pages', 'test_pkg']); +/** + * [#38174] The package a save of a NEW item names: the kernel refuses a + * package-less create (ADR-0070 D1), so this file's creates name this one. + */ +const TEST_PKG = 'test_pkg'; const installedPackage = (id: string) => (INSTALLED_PACKAGES.has(id) ? { manifest: { id } } : undefined); @@ -231,7 +236,7 @@ const flowRows = (rows: Map) => Array.from(rows.values()).filter((r) => r.type === 'flow'); const save = (protocol: any, item: unknown, extra: Record = {}) => - protocol.saveMetaItem({ type: 'flow', name: 'leave_approval', item, ...extra }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'flow', name: 'leave_approval', item, ...extra }); /** [#24371] One `where` value as the store reads it: `{ $in: [...] }` (the by-name read's both-spellings `type`) or equality. */ const whereValueMatches = (actual: unknown, want: unknown): boolean => @@ -357,7 +362,7 @@ describe('runtime authoring gate on saveMetaItem (#4463)', () => { // has to SAY SO — this is the one posture in the matrix below that // may skip all 26 rules. const { protocol, rows } = makeProtocolOn(undefined, 'package-author'); - const result = await protocol.saveMetaItem({ + const result = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'flow', name: 'leave_approval', item: brokenApprovalFlow(), @@ -404,7 +409,7 @@ describe('runtime authoring gate on saveMetaItem (#4463)', () => { // here: `runtime-gate.test.ts` pins `runtimeAuthoringRulesFor` on an // undeclared type returning [], at the layer that owns dispatch. const { protocol } = makeProtocol(); - const result = await protocol.saveMetaItem({ + const result = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'leave_request', item: { @@ -426,13 +431,13 @@ describe('runtime authoring gate on saveMetaItem (#4463)', () => { const protocol = new ObjectStackProtocolImplementation(engine, () => new Map(), 'env_test') as any; await expect( - protocol.saveMetaItem({ type: 'flow', name: 'leave_approval', item: validApprovalFlow() }), + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'flow', name: 'leave_approval', item: validApprovalFlow() }), ).resolves.toMatchObject({ success: true }); expect(flowRows(rows).length).toBe(1); // …and the refusal still happens without that context. const err = await protocol - .saveMetaItem({ type: 'flow', name: 'other_flow', item: { ...brokenApprovalFlow(), name: 'other_flow' } }) + .saveMetaItem({ packageId: TEST_PKG, type: 'flow', name: 'other_flow', item: { ...brokenApprovalFlow(), name: 'other_flow' } }) .catch((e: any) => e); expect(err.status).toBe(422); }); @@ -516,7 +521,7 @@ describe('#6710 — gate activation is keyed on the declared authoring channel', it(label, async () => { const { protocol, rows } = makeProtocolOn(environmentId, channel); const outcome = await protocol - .saveMetaItem({ type: 'flow', name: 'leave_approval', item: brokenApprovalFlow() }) + .saveMetaItem({ packageId: TEST_PKG, type: 'flow', name: 'leave_approval', item: brokenApprovalFlow() }) .then((r: any) => ({ ok: true as const, r })) .catch((e: any) => ({ ok: false as const, e })); @@ -546,7 +551,7 @@ describe('#6710 — gate activation is keyed on the declared authoring channel', // must accept the valid flow. for (const environmentId of [undefined, 'env_test']) { const { protocol, rows } = makeProtocolOn(environmentId, undefined); - const result = await protocol.saveMetaItem({ + const result = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'flow', name: 'leave_approval', item: validApprovalFlow(), }); expect(result.success, `environmentId=${String(environmentId)}`).toBe(true); @@ -563,7 +568,7 @@ describe('#6710 — gate activation is keyed on the declared authoring channel', process.env.OS_ALLOW_UNLINTED_METADATA_WRITES = '1'; const { protocol, rows } = makeProtocolOn(undefined, undefined); - const result = await protocol.saveMetaItem({ + const result = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'flow', name: 'leave_approval', item: brokenApprovalFlow(), }); expect(result.success).toBe(true); @@ -629,7 +634,7 @@ describe('#6710 — gate activation is keyed on the declared authoring channel', // #3050 dispatch alone: a broken body would be refused upstream on the // two `'environment'` rows and the gate would never be reached, which // would make the two keys look identical again. - await protocol.saveMetaItem({ type: 'flow', name: 'leave_approval', item: validApprovalFlow() }); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'flow', name: 'leave_approval', item: validApprovalFlow() }); expect(seen).toEqual(gated ? ['flow/leave_approval'] : []); }); @@ -647,7 +652,7 @@ describe('#6710 — gate activation is keyed on the declared authoring channel', const host = makeProtocolOn(undefined); host.protocol.registerAuthoringGate('flow', gate); const err = await host.protocol - .saveMetaItem({ type: 'flow', name: 'leave_approval', item: brokenApprovalFlow() }) + .saveMetaItem({ packageId: TEST_PKG, type: 'flow', name: 'leave_approval', item: brokenApprovalFlow() }) .catch((e: any) => e); expect(err.status).toBe(422); expect(err.code).toBe('INVALID_METADATA'); @@ -656,7 +661,7 @@ describe('#6710 — gate activation is keyed on the declared authoring channel', // …and the same host config, given a body the rules accept, runs the // #3050 gate and stores the row. "Gated" must not mean "refuses // everything". - await host.protocol.saveMetaItem({ type: 'flow', name: 'leave_approval', item: validApprovalFlow() }); + await host.protocol.saveMetaItem({ packageId: TEST_PKG, type: 'flow', name: 'leave_approval', item: validApprovalFlow() }); expect(seen).toEqual(['flow/leave_approval']); expect(flowRows(host.rows)).toHaveLength(1); }); @@ -688,7 +693,7 @@ describe('runtime authoring gate on OBJECT writes (#4716)', () => { Array.from(rows.values()).filter((r) => r.type === 'object'); const saveObject = (protocol: any, item: unknown, extra: Record = {}) => - protocol.saveMetaItem({ type: 'object', name: 'task', item, ...extra }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'task', item, ...extra }); /** * Zod-green at the per-type parse, broken only where `lintAutonumberFormats` @@ -876,7 +881,7 @@ describe('runtime authoring gate on PERMISSION writes — retired lifecycle resi }); const savePermission = (protocol: any, item: unknown, extra: Record = {}) => - protocol.saveMetaItem({ type: 'permission', name: 'sales_team', item, ...extra }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'permission', name: 'sales_team', item, ...extra }); it('advises on a residue write, in the door\'s existing envelope, and STILL PUBLISHES', async () => { const { protocol, rows } = makeProtocol(); @@ -979,7 +984,7 @@ describe('runtime authoring gate on PERMISSION writes — retired lifecycle resi // spent that key — a dedupe working exactly as designed, misread as a // missing log. const { protocol } = makeProtocol(); - await protocol.saveMetaItem({ + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'permission', name: 'audit_team', item: { ...residuePermissionSet(), name: 'audit_team' }, @@ -1051,7 +1056,7 @@ describe('runtime authoring gate on PERMISSION writes — the engine judge (#201 it('probes the host engine for `judgeFilter` and hands it through, BOUND to that engine', async () => { const { engine, rows, calls, protocol } = hostWithJudge({ ok: true }); - const result = await protocol.saveMetaItem({ + const result = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'permission', name: 'sales_team', item: policySet('owner == current_user.id'), }); @@ -1068,7 +1073,7 @@ describe('runtime authoring gate on PERMISSION writes — the engine judge (#201 it('a judge refusal refuses the publish in the gate\'s own 422 envelope, the engine\'s sentence verbatim', async () => { const { rows, protocol } = hostWithJudge(REFUSAL); - const err = await protocol.saveMetaItem({ + const err = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'permission', name: 'sales_team', item: policySet("owner == '{current_user_id}'"), }).then(() => null, (e: unknown) => e); @@ -1087,7 +1092,7 @@ describe('runtime authoring gate on PERMISSION writes — the engine judge (#201 const { engine, rows } = makeStubEngine(); expect(typeof engine.judgeFilter).toBe('undefined'); const protocol = new ObjectStackProtocolImplementation(engine, () => new Map(), 'env_test') as any; - const kept = await protocol.saveMetaItem({ + const kept = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'permission', name: 'sales_team', item: policySet("owner == '{current_user_id}'"), }); expect(kept.success).toBe(true); @@ -1095,7 +1100,7 @@ describe('runtime authoring gate on PERMISSION writes — the engine judge (#201 // …while the rule itself now runs at this door: a predicate that does // not parse as CEL was ACCEPTED here before this crossing. - const err = await protocol.saveMetaItem({ + const err = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'permission', name: 'audit_team', item: { ...policySet("owner = 'x' AND owner = 'y'"), name: 'audit_team' }, }).then(() => null, (e: unknown) => e); @@ -1107,7 +1112,7 @@ describe('runtime authoring gate on PERMISSION writes — the engine judge (#201 it('a DRAFT save is not judged (D1 unchanged)', async () => { const { calls, protocol } = hostWithJudge(REFUSAL); - const result = await protocol.saveMetaItem({ + const result = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'permission', name: 'sales_team', item: policySet("owner == '{current_user_id}'"), mode: 'draft', }); expect(result.success).toBe(true); @@ -1151,7 +1156,7 @@ describe('html page source compiled at the save door against the SDUI manifest ( return row ? JSON.parse(row.metadata) : undefined; }; const savePage = (protocol: any, item: unknown, extra: Record = {}) => - protocol.saveMetaItem({ type: 'page', name: 'landing', item, ...extra }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'page', name: 'landing', item, ...extra }); const refusal = (e: any) => ({ code: e?.code, status: e?.status }); let warn: ReturnType; @@ -1351,7 +1356,7 @@ describe('stored html page `requires` at load and at draft promotion (#20312)', return row ? JSON.parse(row.metadata) : undefined; }; const savePage = (protocol: any, item: unknown, extra: Record = {}) => - protocol.saveMetaItem({ type: 'page', name: 'landing', item, ...extra }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'page', name: 'landing', item, ...extra }); const loadReports = (warn: ReturnType) => (warn.mock.calls as unknown[][]).map((c) => String(c[0])).filter((m) => m.includes('[page_requires_plugin_absent]')); @@ -1559,7 +1564,7 @@ describe('public-form intake advisory on save and publish (#21476)', () => { } const put = (protocol: any, extra: Record = {}) => - protocol.saveMetaItem({ type: 'form', name: FORM, item: contactForm(), ...extra }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'form', name: FORM, item: contactForm(), ...extra }); const publish = async (protocol: any) => { await expect(put(protocol, { mode: 'draft' })).resolves.toMatchObject({ success: true }); return protocol.publishMetaItem({ type: 'form', name: FORM }); @@ -1603,7 +1608,7 @@ describe('public-form intake advisory on save and publish (#21476)', () => { it('[ADR-0159 D7] the same form held by a `view` container is refused at `formViews` on a walled posture, with no advisory and no row', async () => { const { protocol, rows } = hostOn('isolated'); - const err = await protocol.saveMetaItem({ type: 'view', name: NAME, item: contactContainer() }).catch((e: any) => e); + const err = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'view', name: NAME, item: contactContainer() }).catch((e: any) => e); expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); expect(err.issues.map((i: any) => i.path)).toContain('formViews'); expect(rows.size).toBe(0); @@ -1701,7 +1706,7 @@ describe('runtime authoring gate on OBJECT writes — the formula field verdict const { protocol, rows } = makeProtocol(); const err = await protocol - .saveMetaItem({ type: 'object', name: 'fx_sqrt', item: fxSqrt(UNREGISTERED) }) + .saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_sqrt', item: fxSqrt(UNREGISTERED) }) .catch((e: any) => e); expect(err, 'the save resolved — the door still accepts an unregistered function').toBeInstanceOf(Error); @@ -1723,7 +1728,7 @@ describe('runtime authoring gate on OBJECT writes — the formula field verdict const { protocol } = makeProtocol(); // A draft save is never gated (#4463 D1): the author may keep a half-finished object. await expect( - protocol.saveMetaItem({ type: 'object', name: 'fx_sqrt', item: fxSqrt(UNREGISTERED), mode: 'draft' }), + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_sqrt', item: fxSqrt(UNREGISTERED), mode: 'draft' }), ).resolves.toMatchObject({ success: true }); const err = await protocol.publishMetaItem({ type: 'object', name: 'fx_sqrt' }).catch((e: any) => e); @@ -1738,7 +1743,7 @@ describe('runtime authoring gate on OBJECT writes — the formula field verdict it('(b) a registered call — `floor(record.amount)` — still saves, and the row lands', async () => { const { protocol, rows } = makeProtocol(); - const result = await protocol.saveMetaItem({ type: 'object', name: 'fx_sqrt', item: fxSqrt(REGISTERED) }); + const result = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_sqrt', item: fxSqrt(REGISTERED) }); expect(result.success).toBe(true); expect(fxRows(rows).map((r) => r.state)).toEqual(['active']); @@ -1747,7 +1752,7 @@ describe('runtime authoring gate on OBJECT writes — the formula field verdict it('(d) the door and `os build` give the SAME finding for the same expression', async () => { const { protocol } = makeProtocol(); const err = await protocol - .saveMetaItem({ type: 'object', name: 'fx_sqrt', item: fxSqrt(UNREGISTERED) }) + .saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_sqrt', item: fxSqrt(UNREGISTERED) }) .catch((e: any) => e); const atDoor = (err.issues ?? []).filter((i: any) => i.rule === EXPRESSION_INVALID); @@ -1842,7 +1847,7 @@ describe('runtime authoring gate on OBJECT writes — the validation-rule verdic const { protocol, rows } = makeProtocol(); const err = await protocol - .saveMetaItem({ type: 'object', name: 'fx_rule', item: fxRule(condition) }) + .saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_rule', item: fxRule(condition) }) .catch((e: any) => e); expect(err, 'the save resolved — the door still accepts the rule').toBeInstanceOf(Error); @@ -1865,7 +1870,7 @@ describe('runtime authoring gate on OBJECT writes — the validation-rule verdic const { protocol } = makeProtocol(); // A draft save is never gated (#4463 D1): the author may keep a half-finished object. await expect( - protocol.saveMetaItem({ type: 'object', name: 'fx_rule', item: fxRule(REFUSED[0].condition), mode: 'draft' }), + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_rule', item: fxRule(REFUSED[0].condition), mode: 'draft' }), ).resolves.toMatchObject({ success: true }); const err = await protocol.publishMetaItem({ type: 'object', name: 'fx_rule' }).catch((e: any) => e); @@ -1882,7 +1887,7 @@ describe('runtime authoring gate on OBJECT writes — the validation-rule verdic for (const { condition } of REFUSED) { const { protocol } = makeProtocol(); await expect( - protocol.saveMetaItem({ type: 'object', name: 'fx_rule', item: fxRule(condition), mode: 'draft' }), + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_rule', item: fxRule(condition), mode: 'draft' }), ).resolves.toMatchObject({ success: true }); const read: any = await protocol.getMetaItem({ type: 'object', name: 'fx_rule', state: 'draft' }); @@ -1898,7 +1903,7 @@ describe('runtime authoring gate on OBJECT writes — the validation-rule verdic it('(b) a valid, guarded `condition` still saves, and the row lands', async () => { const { protocol, rows } = makeProtocol(); - const result = await protocol.saveMetaItem({ type: 'object', name: 'fx_rule', item: fxRule(VALID) }); + const result = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_rule', item: fxRule(VALID) }); expect(result.success).toBe(true); expect(ruleRows(rows).map((r) => r.state)).toEqual(['active']); @@ -1908,7 +1913,7 @@ describe('runtime authoring gate on OBJECT writes — the validation-rule verdic for (const { condition } of REFUSED) { const { protocol } = makeProtocol(); const err = await protocol - .saveMetaItem({ type: 'object', name: 'fx_rule', item: fxRule(condition) }) + .saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_rule', item: fxRule(condition) }) .catch((e: any) => e); const atDoor = (err.issues ?? []).filter((i: any) => i.rule === EXPRESSION_INVALID); @@ -2015,7 +2020,7 @@ describe('runtime authoring gate on OBJECT writes — the field-rule-slot verdic const { protocol, rows } = makeProtocol(); const err = await protocol - .saveMetaItem({ type: 'object', name: 'fx_field', item: fxField(slots) }) + .saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_field', item: fxField(slots) }) .catch((e: any) => e); expect(err, 'the save resolved — the door still accepts the slot').toBeInstanceOf(Error); @@ -2038,7 +2043,7 @@ describe('runtime authoring gate on OBJECT writes — the field-rule-slot verdic const { protocol } = makeProtocol(); // A draft save is never gated (#4463 D1): the author may keep a half-finished object. await expect( - protocol.saveMetaItem({ type: 'object', name: 'fx_field', item: fxField(REFUSED[0].slots), mode: 'draft' }), + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_field', item: fxField(REFUSED[0].slots), mode: 'draft' }), ).resolves.toMatchObject({ success: true }); const err = await protocol.publishMetaItem({ type: 'object', name: 'fx_field' }).catch((e: any) => e); @@ -2069,7 +2074,7 @@ describe('runtime authoring gate on OBJECT writes — the field-rule-slot verdic it('(b) valid predicates on the three slots still save, and the row lands', async () => { const { protocol, rows } = makeProtocol(); - const result = await protocol.saveMetaItem({ type: 'object', name: 'fx_field', item: fxField(VALID) }); + const result = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_field', item: fxField(VALID) }); expect(result.success).toBe(true); expect(fieldRows(rows).map((r) => r.state)).toEqual(['active']); @@ -2079,7 +2084,7 @@ describe('runtime authoring gate on OBJECT writes — the field-rule-slot verdic for (const { slots } of REFUSED) { const { protocol } = makeProtocol(); const err = await protocol - .saveMetaItem({ type: 'object', name: 'fx_field', item: fxField(slots) }) + .saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_field', item: fxField(slots) }) .catch((e: any) => e); const atDoor = (err.issues ?? []).filter((i: any) => i.rule === EXPRESSION_INVALID); @@ -2197,7 +2202,7 @@ describe('runtime authoring gate on OBJECT writes — the option visibleWhen ver const { protocol, rows } = makeProtocol(); const err = await protocol - .saveMetaItem({ type: 'object', name: 'fx_option', item: fxOption(body) }) + .saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_option', item: fxOption(body) }) .catch((e: any) => e); expect(err, 'the save resolved — the door still accepts the option predicate').toBeInstanceOf(Error); @@ -2220,7 +2225,7 @@ describe('runtime authoring gate on OBJECT writes — the option visibleWhen ver const { protocol } = makeProtocol(); // A draft save is never gated (#4463 D1): the author may keep a half-finished object. await expect( - protocol.saveMetaItem({ type: 'object', name: 'fx_option', item: fxOption(REFUSED[0].body), mode: 'draft' }), + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_option', item: fxOption(REFUSED[0].body), mode: 'draft' }), ).resolves.toMatchObject({ success: true }); const err = await protocol.publishMetaItem({ type: 'object', name: 'fx_option' }).catch((e: any) => e); @@ -2251,7 +2256,7 @@ describe('runtime authoring gate on OBJECT writes — the option visibleWhen ver it("(b) the showcase's cascade and its `current_user` role gate still save, and the row lands", async () => { const { protocol, rows } = makeProtocol(); - const result = await protocol.saveMetaItem({ type: 'object', name: 'fx_option', item: fxOption(CASCADE) }); + const result = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_option', item: fxOption(CASCADE) }); expect(result.success).toBe(true); expect(optionRows(rows).map((r) => r.state)).toEqual(['active']); @@ -2261,7 +2266,7 @@ describe('runtime authoring gate on OBJECT writes — the option visibleWhen ver for (const { body } of REFUSED) { const { protocol } = makeProtocol(); const err = await protocol - .saveMetaItem({ type: 'object', name: 'fx_option', item: fxOption(body) }) + .saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_option', item: fxOption(body) }) .catch((e: any) => e); const atDoor = (err.issues ?? []).filter((i: any) => i.rule === EXPRESSION_INVALID); @@ -2345,7 +2350,7 @@ describe('runtime authoring gate on OBJECT writes — an option visibleWhen read const lineRows = (rows: Map) => Array.from(rows.values()).filter((r) => r.type === 'object' && r.name === 'fx_line'); const saveLine = (protocol: any, item: unknown, extra: Record = {}) => - protocol.saveMetaItem({ type: 'object', name: 'fx_line', item, ...extra }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_line', item, ...extra }); const buildFindings = (obj: unknown) => { const stack = { objects: [header, obj] }; return runAuthoringRules('build', { normalized: stack, parsed: stack }) @@ -2482,7 +2487,7 @@ describe('runtime authoring gate on OBJECT writes — an option visibleWhen read const itemRows = (rows: Map) => Array.from(rows.values()).filter((r) => r.type === 'object' && r.name === 'fx_item'); const save = (protocol: any, visibleWhen: unknown) => - protocol.saveMetaItem({ type: 'object', name: 'fx_item', item: item(visibleWhen) }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_item', item: item(visibleWhen) }); const buildFindings = (visibleWhen: unknown) => { const stack = { objects: [item(visibleWhen)] }; return runAuthoringRules('build', { normalized: stack, parsed: stack }) @@ -2601,7 +2606,7 @@ describe('runtime authoring gate on OBJECT writes — an option visibleWhen read const itemRows = (rows: Map) => Array.from(rows.values()).filter((r) => r.type === 'object' && r.name === 'fx_item'); const save = (protocol: any, visibleWhen: unknown) => - protocol.saveMetaItem({ type: 'object', name: 'fx_item', item: item(visibleWhen) }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_item', item: item(visibleWhen) }); const buildFindings = (visibleWhen: unknown) => { const stack = { objects: [item(visibleWhen)] }; return runAuthoringRules('build', { normalized: stack, parsed: stack }) @@ -2728,7 +2733,7 @@ describe('runtime authoring gate on OBJECT writes — the stored-self baseline ( const masterRows = (rows: Map) => Array.from(rows.values()).filter((r) => r.type === 'object' && r.name === 'fx_master'); const saveMaster = (protocol: any, item: unknown) => - protocol.saveMetaItem({ type: 'object', name: 'fx_master', item }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_master', item }); for (const [label, detail] of [ ['an unknown `lookupColumns` entry on a detail', pickerDetail(['nope_col'])], @@ -2872,7 +2877,7 @@ describe('runtime authoring gate on OBJECT writes — a conditional rule\'s nest const { protocol, rows } = makeProtocol(); const err = await protocol - .saveMetaItem({ type: 'object', name: 'fx_nested', item: fxNested(rule) }) + .saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_nested', item: fxNested(rule) }) .catch((e: any) => e); expect(err, 'the save resolved — the door still accepts the nested predicate').toBeInstanceOf(Error); @@ -2896,7 +2901,7 @@ describe('runtime authoring gate on OBJECT writes — a conditional rule\'s nest const { protocol } = makeProtocol(); // A draft save is never gated (#4463 D1): the author may keep a half-finished object. await expect( - protocol.saveMetaItem({ type: 'object', name: 'fx_nested', item: fxNested(REFUSED[0].rule), mode: 'draft' }), + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_nested', item: fxNested(REFUSED[0].rule), mode: 'draft' }), ).resolves.toMatchObject({ success: true }); const err = await protocol.publishMetaItem({ type: 'object', name: 'fx_nested' }).catch((e: any) => e); @@ -2911,7 +2916,7 @@ describe('runtime authoring gate on OBJECT writes — a conditional rule\'s nest it('(b) valid nested predicates — both branches, two levels down — still save, and the row lands', async () => { const { protocol, rows } = makeProtocol(); - const result = await protocol.saveMetaItem({ type: 'object', name: 'fx_nested', item: fxNested(VALID) }); + const result = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_nested', item: fxNested(VALID) }); expect(result.success).toBe(true); expect(nestedRows(rows).map((r) => r.state)).toEqual(['active']); @@ -2921,7 +2926,7 @@ describe('runtime authoring gate on OBJECT writes — a conditional rule\'s nest for (const { label, rule } of REFUSED) { const { protocol } = makeProtocol(); const err = await protocol - .saveMetaItem({ type: 'object', name: 'fx_nested', item: fxNested(rule) }) + .saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_nested', item: fxNested(rule) }) .catch((e: any) => e); const atDoor = (err.issues ?? []).filter((i: any) => i.rule === EXPRESSION_INVALID); @@ -3041,7 +3046,7 @@ describe('runtime authoring gate on OBJECT writes — the object action predicat const { protocol, rows } = makeProtocol(); const err = await protocol - .saveMetaItem({ type: 'object', name: 'fx_action', item: bodyFor(refused) }) + .saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_action', item: bodyFor(refused) }) .catch((e: any) => e); expect(err, 'the save resolved — the door still accepts the action predicate').toBeInstanceOf(Error); @@ -3063,7 +3068,7 @@ describe('runtime authoring gate on OBJECT writes — the object action predicat const { protocol } = makeProtocol(); // A draft save is never gated (#4463 D1): the author may keep a half-finished object. await expect( - protocol.saveMetaItem({ type: 'object', name: 'fx_action', item: bodyFor(REFUSED[0]), mode: 'draft' }), + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_action', item: bodyFor(REFUSED[0]), mode: 'draft' }), ).resolves.toMatchObject({ success: true }); const err = await protocol.publishMetaItem({ type: 'object', name: 'fx_action' }).catch((e: any) => e); @@ -3094,7 +3099,7 @@ describe('runtime authoring gate on OBJECT writes — the object action predicat it(`(b) a shipped action shape still saves, and the row lands (#${i}: ${JSON.stringify(item.actions[0].visible)})`, async () => { const { protocol, rows } = makeProtocol(); - const result = await protocol.saveMetaItem({ type: 'object', name: 'fx_action', item }); + const result = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_action', item }); expect(result.success).toBe(true); expect(actionRows(rows).map((r) => r.state)).toEqual(['active']); @@ -3111,7 +3116,7 @@ describe('runtime authoring gate on OBJECT writes — the object action predicat engine.registry.listItems = (type: string) => (type === 'object' ? [sibling] : []); const protocol = new ObjectStackProtocolImplementation(engine, () => new Map(), 'env_test') as any; - const result = await protocol.saveMetaItem({ type: 'object', name: 'fx_action', item: fxAction(OPEN) }); + const result = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_action', item: fxAction(OPEN) }); expect(result.success).toBe(true); expect(actionRows(rows).map((r) => r.state)).toEqual(['active']); @@ -3121,7 +3126,7 @@ describe('runtime authoring gate on OBJECT writes — the object action predicat for (const refused of REFUSED) { const { protocol } = makeProtocol(); const err = await protocol - .saveMetaItem({ type: 'object', name: 'fx_action', item: bodyFor(refused) }) + .saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_action', item: bodyFor(refused) }) .catch((e: any) => e); const atDoor = (err.issues ?? []).filter((i: any) => i.rule === EXPRESSION_INVALID); @@ -3195,7 +3200,7 @@ describe('runtime authoring gate on OBJECT writes — a relationship into a stor const { protocol, rows } = makeProtocol(); const err = await protocol - .saveMetaItem({ type: 'object', name: 'fx_ref', item: fxRef(type, target) }) + .saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_ref', item: fxRef(type, target) }) .catch((e: any) => e); expect(err, 'the save resolved — the door still accepts the reference').toBeInstanceOf(Error); @@ -3216,7 +3221,7 @@ describe('runtime authoring gate on OBJECT writes — a relationship into a stor it("(a) REFUSES the same body on a draft's PROMOTION — the draft door is not a bypass", async () => { const { protocol, rows } = makeProtocol(); await expect( - protocol.saveMetaItem({ type: 'object', name: 'fx_ref', item: fxRef('master_detail', 'sys_metadata'), mode: 'draft' }), + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_ref', item: fxRef('master_detail', 'sys_metadata'), mode: 'draft' }), ).resolves.toMatchObject({ success: true }); const err = await protocol.publishMetaItem({ type: 'object', name: 'fx_ref' }).catch((e: any) => e); @@ -3231,7 +3236,7 @@ describe('runtime authoring gate on OBJECT writes — a relationship into a stor it(`(b) the control: a \`${type}\` to an ordinary platform table (\`sys_user\`) still saves, and the row lands`, async () => { const { protocol, rows } = makeProtocol(); - const result = await protocol.saveMetaItem({ type: 'object', name: 'fx_ref', item: fxRef(type, 'sys_user') }); + const result = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_ref', item: fxRef(type, 'sys_user') }); expect(result.success).toBe(true); expect(refRows(rows).map((r) => r.state)).toEqual(['active']); @@ -3241,7 +3246,7 @@ describe('runtime authoring gate on OBJECT writes — a relationship into a stor it('(d) the door and `os build` give the SAME finding for the same field', async () => { const { protocol } = makeProtocol(); const err = await protocol - .saveMetaItem({ type: 'object', name: 'fx_ref', item: fxRef('lookup', 'sys_metadata') }) + .saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_ref', item: fxRef('lookup', 'sys_metadata') }) .catch((e: any) => e); const atDoor = (err.issues ?? []).filter((i: any) => i.rule === EXPRESSION_INVALID && i.where === WHERE); @@ -3280,7 +3285,7 @@ describe('runtime authoring gate on PAGE writes — the component props and type const reservedTypePage = () => page([{ type: 'page:headr', properties: { title: 'Deals' } }]); const savePage = (protocol: any, item: unknown, extra: Record = {}) => - protocol.saveMetaItem({ type: 'page', name: 'deals_home', item, ...extra }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'page', name: 'deals_home', item, ...extra }); const activePageRows = (rows: Map) => Array.from(rows.values()).filter((r) => r.type === 'page' && r.state === 'active'); @@ -3427,7 +3432,7 @@ describe('runtime authoring gate on PAGE writes — the component visibleWhen ve ]; const savePage = (protocol: any, item: unknown, extra: Record = {}) => - protocol.saveMetaItem({ type: 'page', name: 'pipeline_home', item, ...extra }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'page', name: 'pipeline_home', item, ...extra }); const activePageRows = (rows: Map) => Array.from(rows.values()).filter((r) => r.type === 'page' && r.state === 'active'); /** The build's error findings for one page, through the build's own entry. */ @@ -3583,7 +3588,7 @@ describe('runtime authoring gate on APP and PAGE writes — nav `visible` syntax const { protocol, rows } = makeProtocol(); const item = app("'org_owner' in"); - const err = await protocol.saveMetaItem({ type: 'app', name: 'qa_app', item }).catch((e: any) => e); + const err = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'app', name: 'qa_app', item }).catch((e: any) => e); expect(err, 'the save resolved — the door still accepts the nav predicate').toBeInstanceOf(Error); expect({ code: err.code, status: err.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); @@ -3601,7 +3606,7 @@ describe('runtime authoring gate on APP and PAGE writes — nav `visible` syntax const { protocol, rows } = makeProtocol(); const item = app(Array.from({ length: 90 }, () => 'features.cloudManaged != true').join(' || ')); - const err = await protocol.saveMetaItem({ type: 'app', name: 'qa_app', item }).catch((e: any) => e); + const err = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'app', name: 'qa_app', item }).catch((e: any) => e); expect(err, 'the save resolved — the door still accepts the over-budget nav predicate').toBeInstanceOf(Error); expect({ code: err.code, status: err.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); @@ -3619,7 +3624,7 @@ describe('runtime authoring gate on APP and PAGE writes — nav `visible` syntax const { protocol, rows } = makeProtocol(); const item = app(Array.from({ length: 51 }, () => 'features.cloudManaged != true').join(' || ')); - await expect(protocol.saveMetaItem({ type: 'app', name: 'qa_app', item })).resolves.toMatchObject({ success: true }); + await expect(protocol.saveMetaItem({ packageId: TEST_PKG, type: 'app', name: 'qa_app', item })).resolves.toMatchObject({ success: true }); expect(activeRows(rows, 'app')).toHaveLength(1); }); @@ -3628,7 +3633,7 @@ describe('runtime authoring gate on APP and PAGE writes — nav `visible` syntax const { protocol, rows } = makeProtocol(); await expect( - protocol.saveMetaItem({ type: 'app', name: 'qa_app', item: app("'org_owner' in current_user.positions") }), + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'app', name: 'qa_app', item: app("'org_owner' in current_user.positions") }), ).resolves.toMatchObject({ success: true }); expect(activeRows(rows, 'app')).toHaveLength(1); @@ -3643,7 +3648,7 @@ describe('runtime authoring gate on APP and PAGE writes — nav `visible` syntax const { protocol, rows } = makeProtocol(); const err = await protocol - .saveMetaItem({ type: 'page', name: 'vars_page', item: page([...variables]) }) + .saveMetaItem({ packageId: TEST_PKG, type: 'page', name: 'vars_page', item: page([...variables]) }) .catch((e: any) => e); expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); @@ -3655,7 +3660,7 @@ describe('runtime authoring gate on APP and PAGE writes — nav `visible` syntax it('a page with clean variables saves, and the row lands', async () => { const { protocol, rows } = makeProtocol(); - await expect(protocol.saveMetaItem({ + await expect(protocol.saveMetaItem({ packageId: TEST_PKG, type: 'page', name: 'vars_page', item: page([{ name: 'count', type: 'number', defaultValue: 0 }, { name: 'picked', type: 'record_id' }]), @@ -3680,7 +3685,7 @@ describe('runtime authoring gate on APP and PAGE writes — nav `visible` syntax it(`[#28725] REFUSES an active page save carrying [${rule}], located at the reference; nothing stored`, async () => { const { protocol, rows } = makeProtocol(); - const err = await protocol.saveMetaItem({ type: 'page', name: 'vars_page', item }).catch((e: any) => e); + const err = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'page', name: 'vars_page', item }).catch((e: any) => e); expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); expect(err.issues.filter((i: any) => i.rule === rule).map((i: any) => i.path)).toEqual([path]); @@ -3693,7 +3698,7 @@ describe('runtime authoring gate on APP and PAGE writes — nav `visible` syntax it('[#28725] a page whose `source` names its picker and whose predicate reads a declared variable saves', async () => { const { protocol, rows } = makeProtocol(); - await expect(protocol.saveMetaItem({ + await expect(protocol.saveMetaItem({ packageId: TEST_PKG, type: 'page', name: 'vars_page', item: referencing('project_picker', "page.picked != ''"), })).resolves.toMatchObject({ success: true }); @@ -3744,7 +3749,7 @@ describe('runtime authoring gate on PAGE writes — a props-bag CEL slot over th }); const savePage = (protocol: any, item: unknown, extra: Record = {}) => - protocol.saveMetaItem({ type: 'page', name: 'deal_home', item, ...extra }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'page', name: 'deal_home', item, ...extra }); const activePageRows = (rows: Map) => Array.from(rows.values()).filter((r) => r.type === 'page' && r.state === 'active'); @@ -3842,7 +3847,7 @@ describe('runtime authoring gate on PAGE writes — a component `data` naming th ...extra, }); const savePage = (protocol: any, item: unknown) => - protocol.saveMetaItem({ type: 'page', name: 'partner_page', item }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'page', name: 'partner_page', item }); const activePageRows = (rows: Map) => Array.from(rows.values()).filter((r) => r.type === 'page' && r.state === 'active'); const retirementIssues = (err: any) => @@ -4247,6 +4252,16 @@ describe('runtime authoring gate on VIEW writes that name no package — the who const saveView = (protocol: any, item: { name: string }, extra: Record = {}) => protocol.saveMetaItem({ type: 'view', name: item.name, item, ...extra }); + /** + * [#38174] A package-less create is refused (ADR-0070 D1), so a package-less + * save this block admits runs in place over a loose row seeded straight into + * the store, as (e) seeds its stored view. + */ + const seedLooseView = (rows: Map, body: { name: string; [key: string]: unknown }, state: 'active' | 'draft' = 'active') => + rows.set(keyOf({ type: 'view', name: body.name, organization_id: null, state }), { + id: `r_seed_${state}`, type: 'view', name: body.name, organization_id: null, state, + metadata: JSON.stringify(body), + }); const activeViewRows = (rows: Map) => Array.from(rows.values()).filter((r) => r.type === 'view' && r.state === 'active'); const rulesOf = (findings: any[] | undefined) => (findings ?? []).map((f: any) => f.rule); @@ -4282,6 +4297,7 @@ describe('runtime authoring gate on VIEW writes that name no package — the who it('(a) the control: a binding that resolves is admitted — package, stranger, platform and stored overlay objects', async () => { for (const bound of ['crm_account', 'showcase_task', 'sys_widget_log', 'tenant_ticket']) { const { protocol, rows } = makeOverlayProtocol(); + seedLooseView(rows, { ...listView(bound, ['title']), label: 'seeded' }); const result = await saveView(protocol, listView(bound, ['title'])); @@ -4305,6 +4321,7 @@ describe('runtime authoring gate on VIEW writes that name no package — the who it('(c) a DRAFT save of the same body is not gated; its promotion is judged and refused', async () => { const { protocol, rows } = makeOverlayProtocol(); + seedLooseView(rows, { ...listView('nosuch_obj'), label: 'seeded' }, 'draft'); await expect(saveView(protocol, listView('nosuch_obj'), { mode: 'draft' })).resolves.toMatchObject({ success: true }); const promoted = await protocol @@ -4410,7 +4427,7 @@ describe('runtime authoring gate on OBJECT writes — a validations[] predicate const lineRows = (rows: Map) => Array.from(rows.values()).filter((r) => r.type === 'object' && r.name === 'fx_line'); const saveLine = (protocol: any, item: unknown, extra: Record = {}) => - protocol.saveMetaItem({ type: 'object', name: 'fx_line', item, ...extra }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_line', item, ...extra }); it('(a) REFUSES an active save with a 422 carrying the build\'s located finding, and nothing lands', async () => { const { protocol, rows } = hostWithHeader(); @@ -4530,7 +4547,7 @@ describe('runtime authoring gate on VIEW writes — a bulk confirmText template return { protocol, rows }; } const saveView = (protocol: any, item: unknown, extra: Record = {}) => - protocol.saveMetaItem({ type: 'view', name: NAME, item, ...extra }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'view', name: NAME, item, ...extra }); const activeViewRows = (rows: Map) => Array.from(rows.values()).filter((r) => r.type === 'view' && r.state === 'active'); const confirmIssues = (issues: any[] | undefined) => @@ -4657,7 +4674,7 @@ describe('runtime authoring gate on PAGE and ACTION writes — an action\'s copy ] }], }); const savePage = (protocol: any, item: unknown, extra: Record = {}) => - protocol.saveMetaItem({ type: 'page', name: NAME, item, ...extra }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'page', name: NAME, item, ...extra }); const activePageRows = (rows: Map) => Array.from(rows.values()).filter((r) => r.type === 'page' && r.state === 'active'); const copyIssues = (issues: any[] | undefined) => @@ -4697,7 +4714,7 @@ describe('runtime authoring gate on PAGE and ACTION writes — an action\'s copy const { protocol, rows } = makeProtocol(); const action = { name: 'invite', label: 'Invite', type: 'api', target: '/api/v1/invite', successMessage: 'Sent to {{ owner.email }}' }; - const err = await protocol.saveMetaItem({ type: 'action', name: 'invite', item: action }).catch((e: any) => e); + const err = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'action', name: 'invite', item: action }).catch((e: any) => e); expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); expect(copyIssues(err.issues)).toHaveLength(1); @@ -4800,7 +4817,7 @@ describe('runtime authoring gate on PERMISSION writes — membership-key ownersh const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine, services as any, 'env_test') as any; const saved = protocol - .saveMetaItem({ type: 'permission', name: 'portal_team', item: policySet() }) + .saveMetaItem({ packageId: TEST_PKG, type: 'permission', name: 'portal_team', item: policySet() }) .then((r: unknown) => ({ result: r, err: null }), (e: unknown) => ({ result: null, err: e })); return { rows, saved }; }; @@ -4901,7 +4918,7 @@ describe('runtime authoring gate on FORM writes — a public form declaring a fi return { protocol, rows }; } const saveView = (protocol: any, item: unknown, extra: Record = {}) => - protocol.saveMetaItem({ type: 'form', name: FORM, item, ...extra }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'form', name: FORM, item, ...extra }); const activeViewRows = (rows: Map) => Array.from(rows.values()).filter((r) => r.type === 'form' && r.state === 'active'); @@ -4963,7 +4980,7 @@ describe('runtime authoring gate on FORM writes — a public form declaring a fi it('[ADR-0159 D7] the same form held by a `view` container is refused at `formViews`, file field or none, and nothing is stored', async () => { for (const fields of [[{ field: 'company' }, { field: 'certificate' }], [{ field: 'company' }]]) { const { protocol, rows } = viewProtocol(); - const err = await protocol.saveMetaItem({ type: 'view', name: NAME, item: container(fields) }).catch((e: any) => e); + const err = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'view', name: NAME, item: container(fields) }).catch((e: any) => e); expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); expect(err.issues.map((i: any) => i.path)).toContain('formViews'); expect(rows.size).toBe(0); @@ -5012,7 +5029,7 @@ describe('runtime authoring gate on PERMISSION writes — hierarchy scope withou it('no resolver, publish: refused 422 INVALID_METADATA naming the grant, and nothing is written', async () => { const { protocol, rows } = permissionProtocol(NO_RESOLVER); - const { err } = await settle(protocol.saveMetaItem({ type: 'permission', name: 'sales_manager', item: managerSet() })); + const { err } = await settle(protocol.saveMetaItem({ packageId: TEST_PKG, type: 'permission', name: 'sales_manager', item: managerSet() })); expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); const findings = hierarchyFindings(err.issues); expect(findings).toEqual([expect.objectContaining({ @@ -5025,9 +5042,9 @@ describe('runtime authoring gate on PERMISSION writes — hierarchy scope withou it('no resolver, draft: saved (200) with the same finding as a warning advisory; publishing it is refused', async () => { const { protocol, rows } = permissionProtocol(NO_RESOLVER); - const refused = await settle(protocol.saveMetaItem({ type: 'permission', name: 'sales_manager', item: managerSet() })); + const refused = await settle(protocol.saveMetaItem({ packageId: TEST_PKG, type: 'permission', name: 'sales_manager', item: managerSet() })); const { result, err } = await settle( - protocol.saveMetaItem({ type: 'permission', name: 'sales_manager', item: managerSet(), mode: 'draft' }), + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'permission', name: 'sales_manager', item: managerSet(), mode: 'draft' }), ); expect(err).toBeNull(); expect(result).toMatchObject({ success: true, state: 'draft' }); @@ -5044,11 +5061,11 @@ describe('runtime authoring gate on PERMISSION writes — hierarchy scope withou it('a resolver mounted: the same grant publishes, and neither door says anything about it', async () => { const { protocol, rows } = permissionProtocol(RESOLVER); const draft = await settle( - protocol.saveMetaItem({ type: 'permission', name: 'sales_manager', item: managerSet(), mode: 'draft' }), + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'permission', name: 'sales_manager', item: managerSet(), mode: 'draft' }), ); expect(draft.err).toBeNull(); expect(hierarchyFindings(draft.result.advisories)).toEqual([]); - const live = await settle(protocol.saveMetaItem({ type: 'permission', name: 'sales_manager', item: managerSet() })); + const live = await settle(protocol.saveMetaItem({ packageId: TEST_PKG, type: 'permission', name: 'sales_manager', item: managerSet() })); expect(live.err).toBeNull(); expect(live.result).toMatchObject({ success: true, state: 'active' }); expect(hierarchyFindings(live.result.advisories)).toEqual([]); @@ -5114,7 +5131,7 @@ describe('runtime authoring gate on OBJECT writes — the field group visibleWhe const { protocol, rows } = makeProtocol(); const err = await protocol - .saveMetaItem({ type: 'object', name: 'qa_fg_probe', item: fxGroup(CARD_BODY) }) + .saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'qa_fg_probe', item: fxGroup(CARD_BODY) }) .catch((e: any) => e); expect(err, 'the save resolved — the door still accepts the group predicate').toBeInstanceOf(Error); @@ -5133,7 +5150,7 @@ describe('runtime authoring gate on OBJECT writes — the field group visibleWhe it("(a) REFUSES the card's probe on a draft's PROMOTION — the draft door is not a bypass", async () => { const { protocol, rows } = makeProtocol(); await expect( - protocol.saveMetaItem({ type: 'object', name: 'qa_fg_probe', item: fxGroup(CARD_BODY), mode: 'draft' }), + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'qa_fg_probe', item: fxGroup(CARD_BODY), mode: 'draft' }), ).resolves.toMatchObject({ success: true }); const err = await protocol.publishMetaItem({ type: 'object', name: 'qa_fg_probe' }).catch((e: any) => e); @@ -5148,7 +5165,7 @@ describe('runtime authoring gate on OBJECT writes — the field group visibleWhe it('(b) a group whose predicate reads a declared field still saves, and the row lands', async () => { const { protocol, rows } = makeProtocol(); - const result = await protocol.saveMetaItem({ type: 'object', name: 'qa_fg_probe', item: fxGroup(VALID) }); + const result = await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'qa_fg_probe', item: fxGroup(VALID) }); expect(result.success).toBe(true); expect(groupRows(rows).map((r) => r.state)).toEqual(['active']); @@ -5160,7 +5177,7 @@ describe('runtime authoring gate on OBJECT writes — the field group visibleWhe const atBuild = buildFindings(fxGroup(CARD_BODY)); const err = await protocol - .saveMetaItem({ type: 'object', name: 'qa_fg_probe', item: fxGroup(CARD_BODY) }) + .saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'qa_fg_probe', item: fxGroup(CARD_BODY) }) .catch((e: any) => e); // Non-vacuous: the build refuses it. @@ -5199,7 +5216,7 @@ describe('the object save door judges related-list names against the live regist }; const quoteRows = (rows: Map) => Array.from(rows.values()).filter((r) => r.type === 'object' && r.name === 'rl_quote'); - const save = (protocol: any, item: unknown) => protocol.saveMetaItem({ type: 'object', name: 'rl_quote', item }); + const save = (protocol: any, item: unknown) => protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'rl_quote', item }); it('REFUSES a relatedLists entry naming a registry child with no FK to the object, with the 422 envelope', async () => { const { protocol, rows } = hostWith([line({})]); @@ -5292,7 +5309,7 @@ describe('the connector save door carries connector-credential-literal as an adv }); const saveConnector = (protocol: any, item: { name: string }, extra: Record = {}) => - protocol.saveMetaItem({ type: 'connector', name: item.name, item, ...extra }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'connector', name: item.name, item, ...extra }); const connectorRows = (rows: Map) => Array.from(rows.values()).filter((r) => r.type === 'connector'); @@ -5371,7 +5388,7 @@ describe('runtime authoring gate — a stored sort on a `sortable: false` field columns: [{ field: 'subject' }], sort, }); const saveView = (protocol: any, item: unknown) => - protocol.saveMetaItem({ type: 'view', name: 'ticket_inbox', item }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'view', name: 'ticket_inbox', item }); /** One page per stored page slot, each sorting by `field`. */ const pages = (field: string): Array<[slot: string, page: Record]> => [ @@ -5407,7 +5424,7 @@ describe('runtime authoring gate — a stored sort on a `sortable: false` field 'app page record.sort': 'pages[0].record.sort[0]', }; const savePage = (protocol: any, item: unknown) => - protocol.saveMetaItem({ type: 'page', name: 'ticket_page', item }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'page', name: 'ticket_page', item }); let warn: ReturnType; beforeEach(() => { @@ -5492,7 +5509,7 @@ describe('runtime authoring gate — a stored page sort naming an unknown field const activePages = (rows: Map) => Array.from(rows.values()).filter((r) => r.type === 'page' && r.state === 'active'); const savePage = (protocol: any, item: unknown) => - protocol.saveMetaItem({ type: 'page', name: 'ticket_page', item }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'page', name: 'ticket_page', item }); /** One page per stored page slot, each sorting by `field`. */ const pages = (field: string): Array<[slot: string, path: string, page: Record]> => [ @@ -5590,7 +5607,7 @@ describe('runtime authoring gate — an object list view sort the list door refu }, }); const saveTicket = (protocol: any, field: string) => - protocol.saveMetaItem({ type: 'object', name: OBJECT, item: ticket(field) }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: OBJECT, item: ticket(field) }); const sortIssues = (err: any) => (err?.issues ?? []).filter((i: any) => String(i.rule).startsWith('sort-field-')); const activeObjects = (rows: Map) => Array.from(rows.values()).filter((r) => r.type === 'object' && r.state === 'active'); @@ -5693,11 +5710,21 @@ describe('ai_context author defects at save (ADR-0160 D1)', () => { }); const savePack = (protocol: any, item: unknown, extra: Record = {}) => - protocol.saveMetaItem({ type: 'ai_context', name: 'policy_document', item, ...extra }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'ai_context', name: 'policy_document', item, ...extra }); const packRows = (rows: Map) => Array.from(rows.values()).filter((r) => r.type === 'ai_context'); /** What `os validate` prints for the same pack over the same objects: the CLI command's own entry. */ + /** + * [#38174] A package-less create is refused (ADR-0070 D1): a runtime-created + * (package-less) pack is saved in place over a loose row seeded into the store. + */ + const seedLoosePack = (rows: Map) => + rows.set(keyOf({ type: 'ai_context', name: 'policy_document', organization_id: null, state: 'active' }), { + id: 'r_seed_pack', type: 'ai_context', name: 'policy_document', organization_id: null, state: 'active', + metadata: JSON.stringify({ ...pack(), label: 'seeded' }), + }); + const validateFindings = (item: Record) => runAuthoringRules('validate', { normalized: { objects: POLICY_OBJECTS, aiContexts: [item] } }) .filter((f) => f.rule.startsWith('ai-context-')) @@ -5713,8 +5740,9 @@ describe('ai_context author defects at save (ADR-0160 D1)', () => { for (const [what, item, rule] of FAMILIES) { it(`a runtime-created pack with ${what} is saved and told ${rule}, in os validate's words`, async () => { const { protocol, rows } = makePackProtocol(); + seedLoosePack(rows); - const result = await savePack(protocol, item); + const result = await savePack(protocol, item, { packageId: undefined }); expect(result.success).toBe(true); expect(packRows(rows)).toHaveLength(1); @@ -5750,9 +5778,10 @@ describe('ai_context author defects at save (ADR-0160 D1)', () => { }); it('with no package, an unknown object keeps the os validate words', async () => { - const { protocol } = makePackProtocol(); + const { protocol, rows } = makePackProtocol(); + seedLoosePack(rows); const item = pack({ related: [{ object: 'polcy_revision' }] }); - const result = await savePack(protocol, item); + const result = await savePack(protocol, item, { packageId: undefined }); const advisories = (result.advisories ?? []) as Array>; expect(advisories.map((a) => ({ rule: a.rule, where: a.where, message: a.message, hint: a.hint }))) .toEqual(validateFindings(item)); @@ -5840,7 +5869,7 @@ describe('runtime authoring gate on a subflow call to an unknown flow (#35143)', return { protocol: protocol as any, rows, namesReads }; }; const publish = (protocol: any, item: { name: string; [key: string]: unknown }) => - protocol.saveMetaItem({ type: 'flow', name: item.name, item }); + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'flow', name: item.name, item }); it('refuses an active save calling a flow nothing in the deployment holds', async () => { const { protocol, rows } = protocolWith(['child'], ['packaged_child']); @@ -5859,7 +5888,7 @@ describe('runtime authoring gate on a subflow call to an unknown flow (#35143)', const { protocol } = protocolWith(['engine_child'], ['packaged_child']); expect((await publish(protocol, calling('a', 'engine_child'))).success).toBe(true); expect((await publish(protocol, calling('b', 'packaged_child'))).success).toBe(true); - await protocol.saveMetaItem({ type: 'flow', name: 'draft_child', item: calling('draft_child', 'a'), mode: 'draft' }); + await protocol.saveMetaItem({ packageId: TEST_PKG, type: 'flow', name: 'draft_child', item: calling('draft_child', 'a'), mode: 'draft' }); expect((await publish(protocol, calling('c', 'draft_child'))).success).toBe(true); // …and a flow published earlier is a stored active row. expect((await publish(protocol, calling('d', 'a'))).success).toBe(true); diff --git a/packages/metadata-protocol/src/protocol.runtime-gate-stored-universe.test.ts b/packages/metadata-protocol/src/protocol.runtime-gate-stored-universe.test.ts index c447e8f6e10..abf7c9b6e8c 100644 --- a/packages/metadata-protocol/src/protocol.runtime-gate-stored-universe.test.ts +++ b/packages/metadata-protocol/src/protocol.runtime-gate-stored-universe.test.ts @@ -68,6 +68,11 @@ import { import { ObjectStackProtocolImplementation } from './protocol.js'; const WIDGET_DATASET_UNKNOWN = 'widget-dataset-unknown'; +/** + * [#38174] The installed writable package the saves below name: a new item is + * saved into one (ADR-0070 D1), and a package-less create is refused. + */ +const SMOKE_PKG = 'com.pin2008.smoke'; /** * The card's own hint, verbatim, is the list of code-package datasets this @@ -367,12 +372,12 @@ describe('#15950 — the authoring gate resolves against runtime-authored metada // would publish a board that cannot render, which is the ruling // inverted rather than implemented. const { protocol } = makeHarness(); - const draft = await protocol.saveMetaItem({ + const draft = await protocol.saveMetaItem({ packageId: SMOKE_PKG, type: 'dataset', name: 'p2008_users', item: datasetBody('p2008_users'), mode: 'draft', }); expect(draft.success).toBe(true); - const err = await protocol.saveMetaItem({ + const err = await protocol.saveMetaItem({ packageId: SMOKE_PKG, type: 'dashboard', name: 'p2008_dash', item: threeWidgetBoard('p2008_users'), }).catch((e: unknown) => e); @@ -380,8 +385,8 @@ describe('#15950 — the authoring gate resolves against runtime-authored metada expect(issuesOf(err, WIDGET_DATASET_UNKNOWN).length).toBe(3); // …and the same board publishes once the dataset itself is published. - await protocol.saveMetaItem({ type: 'dataset', name: 'p2008_users' , item: datasetBody('p2008_users') }); - const result = await protocol.saveMetaItem({ + await protocol.saveMetaItem({ packageId: SMOKE_PKG, type: 'dataset', name: 'p2008_users' , item: datasetBody('p2008_users') }); + const result = await protocol.saveMetaItem({ packageId: SMOKE_PKG, type: 'dashboard', name: 'p2008_dash', item: threeWidgetBoard('p2008_users'), }); expect(result.success).toBe(true); @@ -491,7 +496,7 @@ describe('#16224 — an overlay that REDEFINES a code-package item is judged fro ).toEqual(['order_count']); // ── The redefinition ───────────────────────────────────────────────── - const saved = await protocol.saveMetaItem({ + const saved = await protocol.saveMetaItem({ packageId: SMOKE_PKG, type: 'dataset', name: OVERRIDDEN, item: overlayBody(), }); expect(saved.success).toBe(true); @@ -508,7 +513,7 @@ describe('#16224 — an overlay that REDEFINES a code-package item is judged fro ).toEqual(['row_count']); // ── The residual ───────────────────────────────────────────────────── - const err = await protocol.saveMetaItem({ + const err = await protocol.saveMetaItem({ packageId: SMOKE_PKG, type: 'dashboard', name: 'p16224_dash', item: oneWidgetBoard(OVERRIDDEN, 'order_count'), }).catch((e: unknown) => e); @@ -531,9 +536,9 @@ describe('#16224 — an overlay that REDEFINES a code-package item is judged fro // the false acceptance would leave this one refused. const { protocol } = makeHarness(); - await protocol.saveMetaItem({ type: 'dataset', name: OVERRIDDEN, item: overlayBody() }); + await protocol.saveMetaItem({ packageId: SMOKE_PKG, type: 'dataset', name: OVERRIDDEN, item: overlayBody() }); - const result = await protocol.saveMetaItem({ + const result = await protocol.saveMetaItem({ packageId: SMOKE_PKG, type: 'dashboard', name: 'p16224_dash', item: oneWidgetBoard(OVERRIDDEN, 'row_count'), }); expect( @@ -551,9 +556,9 @@ describe('#16224 — an overlay that REDEFINES a code-package item is judged fro // switching the rule off. const { protocol, rows } = makeHarness(); - await protocol.saveMetaItem({ type: 'dataset', name: OVERRIDDEN, item: overlayBody() }); + await protocol.saveMetaItem({ packageId: SMOKE_PKG, type: 'dataset', name: OVERRIDDEN, item: overlayBody() }); - const err = await protocol.saveMetaItem({ + const err = await protocol.saveMetaItem({ packageId: SMOKE_PKG, type: 'dashboard', name: 'p16224_dash', item: oneWidgetBoard(OVERRIDDEN, 'no_such_measure_xyz'), }).catch((e: unknown) => e); @@ -570,8 +575,8 @@ describe('#16224 — an overlay that REDEFINES a code-package item is judged fro // two arms of one merge are measured together. const { protocol, engine } = makeHarness(); - await protocol.saveMetaItem({ type: 'dataset', name: OVERRIDDEN, item: overlayBody() }); - await protocol.saveMetaItem({ + await protocol.saveMetaItem({ packageId: SMOKE_PKG, type: 'dataset', name: OVERRIDDEN, item: overlayBody() }); + await protocol.saveMetaItem({ packageId: SMOKE_PKG, type: 'dataset', name: 'p2008_users', item: datasetBody('p2008_users'), }); @@ -581,13 +586,13 @@ describe('#16224 — an overlay that REDEFINES a code-package item is judged fro ).toEqual([...CODE_DATASET_NAMES]); // The store-only name resolves, with its own measure… - const additive = await protocol.saveMetaItem({ + const additive = await protocol.saveMetaItem({ packageId: SMOKE_PKG, type: 'dashboard', name: 'p2008_dash', item: oneWidgetBoard('p2008_users', 'order_count', 'p2008_dash'), }); expect(additive.success, '#16223: a store-only name is contributed to the universe').toBe(true); // …and the redefined name is judged from the overlay in the same gather. - const err = await protocol.saveMetaItem({ + const err = await protocol.saveMetaItem({ packageId: SMOKE_PKG, type: 'dashboard', name: 'p16224_dash', item: oneWidgetBoard(OVERRIDDEN, 'order_count'), }).catch((e: unknown) => e); expect((err as any)?.status).toBe(422); @@ -610,7 +615,7 @@ describe('#16224 — an overlay that REDEFINES a code-package item is judged fro // The base layer as an author writes it: the code package's own columns // plus one of the tenant's, and NO `priority` — that field exists only // as an `extend` contributor in the registry. - await protocol.saveMetaItem({ + await protocol.saveMetaItem({ packageId: SMOKE_PKG, type: 'object', name: 'orders', item: { name: 'orders', label: 'Orders', @@ -624,7 +629,7 @@ describe('#16224 — an overlay that REDEFINES a code-package item is judged fro }, }); - const onOverlayField = await protocol.saveMetaItem({ + const onOverlayField = await protocol.saveMetaItem({ packageId: SMOKE_PKG, type: 'dashboard', name: 'p16224_obj', item: filterBoard('p16224_obj', 'channel'), }); expect( @@ -633,7 +638,7 @@ describe('#16224 — an overlay that REDEFINES a code-package item is judged fro ).not.toContain(DASHBOARD_FILTER_FIELD_UNKNOWN); expect(onOverlayField.success).toBe(true); - const onExtenderField = await protocol.saveMetaItem({ + const onExtenderField = await protocol.saveMetaItem({ packageId: SMOKE_PKG, type: 'dashboard', name: 'p16224_ext', item: filterBoard('p16224_ext', 'priority'), }); expect( @@ -645,7 +650,7 @@ describe('#16224 — an overlay that REDEFINES a code-package item is judged fro // The firing control: a column on NEITHER layer is still reported, so // the two readings above are not a rule that stopped running. - const err = await protocol.saveMetaItem({ + const err = await protocol.saveMetaItem({ packageId: SMOKE_PKG, type: 'dashboard', name: 'p16224_bad', item: filterBoard('p16224_bad', 'no_such_column_xyz'), }).catch((e: unknown) => e); const reported = (err instanceof Error) diff --git a/packages/metadata-protocol/src/protocol.save-door-lock-family.test.ts b/packages/metadata-protocol/src/protocol.save-door-lock-family.test.ts index 90c1834dd98..d98fa03cde0 100644 --- a/packages/metadata-protocol/src/protocol.save-door-lock-family.test.ts +++ b/packages/metadata-protocol/src/protocol.save-door-lock-family.test.ts @@ -74,6 +74,9 @@ function matches(row: Row, where: Record = {}): boolean { return true; } +/** [#38174] An installed writable package: a save of a NEW item names one (ADR-0070 D1). */ +const TEST_PKG = 'test_pkg'; + /** * A stub engine that keeps rows, and a registry holding what a code package's * loader registered: each artifact as `applyProtection` leaves it. @@ -131,7 +134,8 @@ function makeProtocol(artifacts: Array<{ type: string; item: Record shipped(type, name)[0], listItems: (type: string) => artifacts.filter((a) => a.type === type).map((a) => a.item), getObject: () => undefined, - getPackage: () => undefined, + // [#38174] the installed writable package a create names (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), isPackageDisabled: () => false, applyNavContributions: (app: unknown) => app, }, @@ -224,7 +228,7 @@ for (const writeFace of AUTHOR_FACES) { expect(rows('app', name)).toEqual([]); expect(metadataWrites()).toEqual([]); // The same body without the family saves, and binds nothing. - expect((await protocol.saveMetaItem({ type: 'app', name, item: app(name), writeFace })).success).toBe(true); + expect((await protocol.saveMetaItem({ type: 'app', name, item: app(name), writeFace, packageId: TEST_PKG })).success).toBe(true); const read = await protocol.getMetaItem({ type: 'app', name }); expect(read).toMatchObject({ lock: 'none', editable: true, deletable: true }); expect((await protocol.saveMetaItem({ type: 'app', name, item: app(name, { label: 'Edited' }), writeFace })).success).toBe(true); @@ -236,7 +240,7 @@ for (const writeFace of AUTHOR_FACES) { it('the add on an existing item with no lock — every lock state, and a lone prose key', async () => { const { protocol, storedFamily } = makeProtocol(); const name = 'plain_app'; - await protocol.saveMetaItem({ type: 'app', name, item: app(name), writeFace }); + await protocol.saveMetaItem({ type: 'app', name, item: app(name), writeFace, packageId: TEST_PKG }); for (const family of [{ _lock: 'full' }, { _lock: 'no-overlay' }, { _lock: 'no-delete' }, { _lock: 'none' }, { _lockReason: 'why' }]) { const err = await refusalOf(() => protocol.saveMetaItem({ type: 'app', name, item: app(name, family), writeFace })); // A lone prose key, or `none`, binds nothing: it adds keys, not a lock. @@ -334,9 +338,9 @@ for (const writeFace of AUTHOR_FACES) { it("on a clone: an unlocked item's body saved under a new name is accepted; a clone carrying another item's lock is refused", async () => { const { protocol, storedFamily, rows } = makeProtocol(); - await protocol.saveMetaItem({ type: 'app', name: 'source_open', item: app('source_open'), writeFace }); + await protocol.saveMetaItem({ type: 'app', name: 'source_open', item: app('source_open'), writeFace, packageId: TEST_PKG }); const open = await protocol.getMetaItem({ type: 'app', name: 'source_open' }); - const ok = await protocol.saveMetaItem({ type: 'app', name: 'clone_open', item: { ...open.item, name: 'clone_open' }, writeFace }); + const ok = await protocol.saveMetaItem({ type: 'app', name: 'clone_open', item: { ...open.item, name: 'clone_open' }, writeFace, packageId: TEST_PKG }); expect(ok.success).toBe(true); expect(storedFamily('app', 'clone_open')).toEqual({}); @@ -391,7 +395,7 @@ describe('CONTROLS — what the rule leaves as it was', () => { const { protocol, storedFamily } = makeProtocol(); for (const writeFace of [...AUTHOR_FACES, undefined]) { const name = `plain_${writeFace ?? 'in_process'}`.replace(/-/g, '_'); - expect((await protocol.saveMetaItem({ type: 'app', name, item: app(name), ...(writeFace ? { writeFace } : {}) })).success).toBe(true); + expect((await protocol.saveMetaItem({ type: 'app', name, item: app(name), packageId: TEST_PKG, ...(writeFace ? { writeFace } : {}) })).success).toBe(true); expect(storedFamily('app', name)).toEqual({}); expect(await protocol.getMetaItem({ type: 'app', name })).toMatchObject({ lock: 'none', editable: true, deletable: true }); expect((await protocol.deleteMetaItem({ type: 'app', name })).success).toBe(true); diff --git a/packages/metadata-protocol/src/protocol.save-door-protection.test.ts b/packages/metadata-protocol/src/protocol.save-door-protection.test.ts index 021bba5a114..24e090dba2d 100644 --- a/packages/metadata-protocol/src/protocol.save-door-protection.test.ts +++ b/packages/metadata-protocol/src/protocol.save-door-protection.test.ts @@ -48,6 +48,7 @@ import { resetEnvWritableMetadataTypes } from './sys-metadata-repository.js'; type Row = Record; const PACKAGE_ID = 'com.example.dash'; +const TEST_PKG = 'test_pkg'; const LOCK = { lock: 'full', reason: 'probe: locked by hand' } as const; /** Equality and `null`; any other operator is refused, so a matcher that ignored one cannot prove anything. */ @@ -118,7 +119,8 @@ function makeProtocol(artifacts: Array<{ type: string; item: Record shipped(type, name)[0], listItems: (type: string) => artifacts.filter((a) => a.type === type).map((a) => a.item), getObject: () => undefined, - getPackage: () => undefined, + // [#38174] a new item is saved into an installed writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), isPackageDisabled: () => false, applyNavContributions: (app: unknown) => app, }, @@ -194,17 +196,17 @@ describe('the save door refuses a `protection` block — the card\'s probes', () it(`${probe.type}: CONTROL — the same body without \`protection\` saves, its row carries none, and the item stays editable and deletable`, async () => { const { protocol, stored } = makeProtocol(); - const first = await protocol.saveMetaItem({ type: probe.type, name: probe.name, item: probe.body() }); + const first = await protocol.saveMetaItem({ type: probe.type, name: probe.name, packageId: TEST_PKG, item: probe.body() }); expect(first.success).toBe(true); const [row] = stored(probe.type, probe.name).filter((r) => r.state === 'active'); const body = JSON.parse(row!.metadata); expect(body).not.toHaveProperty('protection'); expect(body.label).toBe(probe.body().label); const second = await protocol.saveMetaItem({ - type: probe.type, name: probe.name, item: probe.body({ label: 'Edited' }), + type: probe.type, name: probe.name, packageId: TEST_PKG, item: probe.body({ label: 'Edited' }), }); expect(second.success).toBe(true); - const removed = await protocol.deleteMetaItem({ type: probe.type, name: probe.name }); + const removed = await protocol.deleteMetaItem({ type: probe.type, name: probe.name, packageId: TEST_PKG }); expect(removed.success).toBe(true); }); } diff --git a/packages/metadata-protocol/src/protocol.save-flow-canonicalization.test.ts b/packages/metadata-protocol/src/protocol.save-flow-canonicalization.test.ts index 4d7c3694e06..a97f8b7905d 100644 --- a/packages/metadata-protocol/src/protocol.save-flow-canonicalization.test.ts +++ b/packages/metadata-protocol/src/protocol.save-flow-canonicalization.test.ts @@ -182,11 +182,20 @@ function makeStubEngine() { ...NO_PACKAGE_SCOPED_READS, registerItem: () => {}, registerObject: () => {}, + // [#38174] installs {@link TEST_PKG}: a new item is saved into a + // writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), + // The objects the saves here name, held by that package, so its + // closure reaches them. + listItems: (type: string) => (type === 'object' ? [{ name: 'lead', label: 'lead', _packageId: TEST_PKG, fields: {} }, { name: 'case', label: 'case', _packageId: TEST_PKG, fields: {} }] : []), }, }; return { engine, rows }; } +/** The writable package a NEW item here is saved into. */ +const TEST_PKG = 'test_pkg'; + function makeProtocol(services: Map = new Map()) { const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine, () => services); @@ -309,7 +318,7 @@ describe('saveMetaItem canonicalizes flow bodies (#4542)', () => { ); const body = flowBody({ objectName: 'lead', filter: { status: 'stale' } }); - await save(protocol, body); + await save(protocol, body, { packageId: TEST_PKG }); expect(spy).toHaveBeenCalledTimes(1); expect(storedFlow(rows)!.body).toEqual(body); @@ -536,6 +545,7 @@ describe('saveMetaItem canonicalizes flow bodies (#4542)', () => { name: 'case_grid', // [#7741] carries the object binding the inline arm now requires. item: { name: 'case_grid', type: 'grid', label: 'Cases', columns: ['id', 'title'], object: 'case', viewKind: 'list' }, + packageId: TEST_PKG, }); expect(spy).not.toHaveBeenCalled(); }); @@ -594,7 +604,7 @@ describe('saveMetaItem canonicalizes flow bodies (#4542)', () => { const { protocol, rows } = makeProtocol(services()); const body = flowBody({ objectName: 'lead', filter: { status: 'stale' } }); - const result = await save(protocol, body); + const result = await save(protocol, body, { packageId: TEST_PKG }); expect(result.success).toBe(true); expect(storedFlow(rows)!.body).toEqual(body); @@ -627,7 +637,7 @@ describe('saveMetaItem canonicalizes flow bodies (#4542)', () => { const { protocol, engine } = makeProtocol(new Map([['automation', { canonicalizeStoredFlow: spy }]])); const body = flowBody({ objectName: 'lead', filter: { status: 'stale' } }); - await save(protocol, body); + await save(protocol, body, { packageId: TEST_PKG }); expect(spy.mock.lastCall?.[2]).toEqual({ includeRetired: false }); await seedStoredFlow(engine, legacyBody(), 'draft'); @@ -650,7 +660,9 @@ describe('saveMetaItem canonicalizes flow bodies (#4542)', () => { it(`a server-stated write (\`${writeFace}\`) carries a body at rest: judged in the full chain on a host with no automation service, as an engine host's caller canonicalizes it`, async () => { const { protocol, rows } = makeProtocol(new Map()); - const result = await save(protocol, legacyBody(), { writeFace }); + // [#38174] Both faces write into a named target package, as + // their one door (`protocol-package-commits.ts`) states it. + const result = await save(protocol, legacyBody(), { writeFace, packageId: TEST_PKG }); expect(result.success).toBe(true); expect(storedFlow(rows)!.body.nodes[0].config).toHaveProperty('filters'); diff --git a/packages/metadata-protocol/src/protocol.save-receipt-wording.test.ts b/packages/metadata-protocol/src/protocol.save-receipt-wording.test.ts index d1bbfd68aad..ab30f0c0015 100644 --- a/packages/metadata-protocol/src/protocol.save-receipt-wording.test.ts +++ b/packages/metadata-protocol/src/protocol.save-receipt-wording.test.ts @@ -60,6 +60,9 @@ interface Row { metadata: string; } +/** The writable package a brand-new item is saved into. */ +const TEST_PKG = 'test_pkg'; + function makeStubEngine(artifacts: Array<{ type: string; name: string }> = []) { const rows = new Map(); let nextId = 0; @@ -96,8 +99,13 @@ function makeStubEngine(artifacts: Array<{ type: string; name: string }> = []) { registry: { registerItem: () => {}, registerObject: () => {}, - listItems: () => [], + // [#38174] `task`, held by {@link TEST_PKG}, so an item saved into + // that package names an object inside its closure. + listItems: (type: string) => (type === 'object' ? [{ name: 'task', label: 'Task', _packageId: TEST_PKG, fields: {} }] : []), getItem: () => undefined, + // [#38174] installs {@link TEST_PKG}: a new item is saved into a + // writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), // `isArtifactBacked` prefers this lookup — a hit here means the // name is shipped by a code package (`_packageId` provenance). getArtifactItem: (type: string, name: string) => @@ -195,14 +203,15 @@ describe('#5265 — a save receipt names what was actually written', () => { it(`a brand-new ${type} is not reported as a customization overlay`, async () => { const { protocol } = makeProtocol(); - const result = await protocol.saveMetaItem({ type, name: 'rc5_acct', item }); + const result = await protocol.saveMetaItem({ type, name: 'rc5_acct', item, packageId: TEST_PKG }); expect(result.success).toBe(true); expect(result.message).not.toContain('customization overlay'); // Still carries every fact the overlay sentence carried: the type, - // the name, the org dimension, the state and the change-log cursor. + // the name, the org dimension, the package, the state and the + // change-log cursor. expect(result.message).toBe( - `Saved ${type} 'rc5_acct' (env-wide, state=active) [seq=${result.seq}]`, + `Saved ${type} 'rc5_acct' (env-wide, package=${TEST_PKG}, state=active) [seq=${result.seq}]`, ); }); } @@ -211,12 +220,12 @@ describe('#5265 — a save receipt names what was actually written', () => { const { protocol } = makeProtocol(); const result = await protocol.saveMetaItem({ - type: 'flow', name: 'rc5_acct', item: OVERLAYLESS_PROBES.flow, mode: 'draft', + type: 'flow', name: 'rc5_acct', item: OVERLAYLESS_PROBES.flow, mode: 'draft', packageId: TEST_PKG, }); expect(result.state).toBe('draft'); expect(result.message).toBe( - `Saved flow 'rc5_acct' (env-wide, state=draft) [seq=${result.seq}]`, + `Saved flow 'rc5_acct' (env-wide, package=${TEST_PKG}, state=draft) [seq=${result.seq}]`, ); }); @@ -227,17 +236,17 @@ describe('#5265 — a save receipt names what was actually written', () => { // artifact backing. const { protocol } = makeProtocol(); - const result = await protocol.saveMetaItem({ type: 'view', name: 'rc5_probe_view', item: VIEW }); + const result = await protocol.saveMetaItem({ type: 'view', name: 'rc5_probe_view', item: VIEW, packageId: TEST_PKG }); expect(result.message).toBe( - `Saved view 'rc5_probe_view' (env-wide, state=active) [seq=${result.seq}]`, + `Saved view 'rc5_probe_view' (env-wide, package=${TEST_PKG}, state=active) [seq=${result.seq}]`, ); }); it('the phrase spells the canonical singular type, not the plural the caller sent', async () => { const { protocol } = makeProtocol(); - const result = await protocol.saveMetaItem({ type: 'views', name: 'rc5_probe_view', item: VIEW }); + const result = await protocol.saveMetaItem({ type: 'views', name: 'rc5_probe_view', item: VIEW, packageId: TEST_PKG }); expect(result.message).toContain("Saved view 'rc5_probe_view'"); }); @@ -308,7 +317,7 @@ describe('#5265 — a save receipt names what was actually written', () => { const { protocol: plain } = makeProtocol(); const { protocol: overlaid } = makeProtocol([{ type: 'view', name: 'rc5_probe_view' }]); - const runtimeOnly = await plain.saveMetaItem({ type: 'view', name: 'rc5_probe_view', item: VIEW }); + const runtimeOnly = await plain.saveMetaItem({ type: 'view', name: 'rc5_probe_view', item: VIEW, packageId: TEST_PKG }); const override = await overlaid.saveMetaItem({ type: 'view', name: 'rc5_probe_view', item: VIEW }); expect(runtimeOnly.message.length).toBeLessThan(200); diff --git a/packages/metadata-protocol/src/protocol.save-union-issues.test.ts b/packages/metadata-protocol/src/protocol.save-union-issues.test.ts index 3d97c6cb6e5..2cf42e9e94c 100644 --- a/packages/metadata-protocol/src/protocol.save-union-issues.test.ts +++ b/packages/metadata-protocol/src/protocol.save-union-issues.test.ts @@ -68,7 +68,22 @@ const whereValueMatches = (actual: unknown, want: unknown): boolean => * that path consults — answering nothing, so the served item is the stored row * after the rehydration seam and nothing else. */ -function makeProtocol(seed: Array<{ type: string; name: string; metadata: Record }> = []) { +/** + * [#38174] A new item is saved into an installed writable package (ADR-0070 + * D1): a package-less create is refused. `packaged` installs `TEST_PKG` and + * registers the objects the control bodies bind (no package provenance, so the + * package closure keeps them), for the controls that save through `saveIn`. + */ +const TEST_PKG = 'test_pkg'; +const TEST_OBJECTS = [ + { name: 'task', label: 'Task', fields: { title: { name: 'title', type: 'text' }, status: { name: 'status', type: 'text' }, amount: { name: 'amount', type: 'number' } } }, + { name: 'lead', label: 'Lead', fields: { name: { name: 'name', type: 'text' }, email: { name: 'email', type: 'text' }, owner: { name: 'owner', type: 'text' } } }, +]; + +function makeProtocol( + seed: Array<{ type: string; name: string; metadata: Record }> = [], + opts: { packaged?: boolean } = {}, +) { // ⚠️ Keyed BY TABLE. `find`/`findOne` below answer nothing, so this harness // cannot serve a `sys_metadata_history` row as a `sys_metadata` row the way // #16223 measured — but one flat map still made `rows.size` the total of @@ -117,9 +132,17 @@ function makeProtocol(seed: Array<{ type: string; name: string; metadata: Record assertEngineDeleteDispatch(opts); return { deleted: 0 }; }, - registry: seed.length === 0 - ? { registerItem: () => {}, registerObject: () => {} } - : { registerItem: () => {}, registerObject: () => {}, getItem: () => undefined, getObject: () => undefined }, + registry: { + ...(seed.length === 0 + ? { registerItem: () => {}, registerObject: () => {} } + : { registerItem: () => {}, registerObject: () => {}, getItem: () => undefined, getObject: () => undefined }), + ...(opts.packaged + ? { + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), + listItems: (type: string) => (type === 'object' ? TEST_OBJECTS : []), + } + : {}), + }, }; const protocol: any = new ObjectStackProtocolImplementation(engine, () => new Map()); return { protocol, rows }; @@ -127,6 +150,9 @@ function makeProtocol(seed: Array<{ type: string; name: string; metadata: Record const save = (protocol: any, item: unknown, name = 'task_list', type = 'view') => protocol.saveMetaItem({ type, name, item }); +/** [#38174] `save`, into `TEST_PKG` — for a harness built with `{ packaged: true }`. */ +const saveIn = (protocol: any, item: unknown, name = 'task_list', type = 'view') => + protocol.saveMetaItem({ type, name, item, packageId: TEST_PKG }); async function rejection(promise: Promise): Promise { try { @@ -213,9 +239,9 @@ describe('#5364 saveMetaItem 422 expands union branches', () => { }); it('a spec-valid view still saves — the expansion never invents a rejection', async () => { - const { protocol, rows } = makeProtocol(); + const { protocol, rows } = makeProtocol([], { packaged: true }); - const result = await save(protocol, { + const result = await saveIn(protocol, { // [#7741] carries the object binding the inline arm now requires. name: 'task_list', object: 'task', viewKind: 'list', type: 'grid', label: 'Tasks', columns: [{ field: 'title' }], @@ -351,8 +377,8 @@ describe('#7510 the 422 for a broken ViewItem names its own key, not the contain delete form.sections[0].fields[0].keyField.sort; for (const [item, name, type] of [[list, 'lead.all', 'view'], [form, 'lead.contact', 'form']] as const) { - const { protocol, rows } = makeProtocol(); - const result = await save(protocol, item, name, type); + const { protocol, rows } = makeProtocol([], { packaged: true }); + const result = await saveIn(protocol, item, name, type); expect(result.success, `${type}/${name}`).toBe(true); expect(rows.size).toBe(1); } @@ -572,7 +598,7 @@ describe('#35400 an explained union head is dropped only when it says nothing of // (`list-columns-mix.ts`); this walker keeps such a head by the same // rule `zodIssuesToFields` follows, so the save door's 422 opens on the // sentence and not on `columns.0: expected string, received object`. - const { protocol, rows } = makeProtocol(); + const { protocol, rows } = makeProtocol([], { packaged: true }); const body = { name: 'task_list', object: 'task', viewKind: 'list', type: 'grid', columns: ['title', { field: 'status' }] }; const err = await rejection(save(protocol, body)); @@ -587,7 +613,7 @@ describe('#35400 an explained union head is dropped only when it says nothing of // …first among the `columns` entries: nothing located below it precedes it. expect(head).toBe(err.issues.findIndex((i: any) => i.path === 'columns' || i.path.startsWith('columns.'))); // CONTROL — the same view in one spelling saves. - await save(protocol, { ...body, columns: ['title', 'status'] }); + await saveIn(protocol, { ...body, columns: ['title', 'status'] }); expect(rows.size).toBe(1); }); @@ -673,8 +699,8 @@ describe('#20230 a flattened overlay carrying a retired owner/hidden is refused it('RESIDUE CONTROL: the same stripped row plus a real view key (a toolbar toggle) saves', async () => { const served = applyConversionsToStoredItem('view', { name: 'task_list', ...BOUND_LIST, hidden: true }) as Record; - const { protocol, rows } = makeProtocol(); - const result = await save(protocol, { ...served, isDefault: true }); + const { protocol, rows } = makeProtocol([], { packaged: true }); + const result = await saveIn(protocol, { ...served, isDefault: true }); expect(result.success).toBe(true); expect(rows.size).toBe(1); }); @@ -705,8 +731,8 @@ describe('#20230 a flattened overlay carrying a retired owner/hidden is refused }); it('CONTROL: the same bound list overlay without the keys still saves, one row', async () => { - const { protocol, rows } = makeProtocol(); - const result = await save(protocol, { name: 'task_list', ...BOUND_LIST, isDefault: true, order: 2 }); + const { protocol, rows } = makeProtocol([], { packaged: true }); + const result = await saveIn(protocol, { name: 'task_list', ...BOUND_LIST, isDefault: true, order: 2 }); expect(result.success).toBe(true); expect(rows.size).toBe(1); }); @@ -753,8 +779,8 @@ describe('#26711 the view write door refuses an unknown top-level key', () => { ['an inline list view', OVERLAY, 'task_list'], ['a view item record', RECORD, 'task.mine'], ] as const)('CONTROL: %s without the key saves, one row', async (_label, body, name) => { - const { protocol, rows } = makeProtocol(); - const result = await protocol.saveMetaItem({ type: 'view', name, item: body, mode: 'draft' }); + const { protocol, rows } = makeProtocol([], { packaged: true }); + const result = await protocol.saveMetaItem({ type: 'view', name, item: body, mode: 'draft', packageId: TEST_PKG }); expect(result.success).toBe(true); expect(rows.size).toBe(1); }); diff --git a/packages/metadata-protocol/src/protocol.seed-external-id-refusal.test.ts b/packages/metadata-protocol/src/protocol.seed-external-id-refusal.test.ts index ce5a4fd4549..5a0be679ca8 100644 --- a/packages/metadata-protocol/src/protocol.seed-external-id-refusal.test.ts +++ b/packages/metadata-protocol/src/protocol.seed-external-id-refusal.test.ts @@ -343,7 +343,7 @@ describe('[#28952] controls — an `externalId` the object has is not refused', expect(res, JSON.stringify(res.failed)).toMatchObject({ outcome: 'published', publishedCount: 1 }); // The publish loaded the seed: the double records the row it wrote. expect(dataInserts).toEqual(['seedkey_other']); - expect((await protocol.saveMetaItem({ type: 'seed', name: 'r_ok2', item: seed('seedkey_other', externalId) })).success).toBe(true); + expect((await protocol.saveMetaItem({ type: 'seed', name: 'r_ok2', item: seed('seedkey_other', externalId), packageId: PKG })).success).toBe(true); expect(stored(rows, 'seed', 'r_ok')).toEqual([`active|${PKG}|${JSON.stringify(externalId ?? null)}`]); }); @@ -423,7 +423,7 @@ describe('[#34864] the seed save door — an `object` that names no object', () it('a registered object (a dependency package\'s object answers the same registry read): saves as a draft and live', async () => { const { protocol, rows } = makeSession({ objects: OBJECTS }); expect((await protocol.saveMetaItem({ type: 'seed', name: 'r_reg', item: seed('seedkey_other', 'sku'), mode: 'draft', packageId: PKG })).success).toBe(true); - expect((await protocol.saveMetaItem({ type: 'seed', name: 'r_reg_live', item: seed('seedkey_other', 'sku') })).success).toBe(true); + expect((await protocol.saveMetaItem({ type: 'seed', name: 'r_reg_live', item: seed('seedkey_other', 'sku'), packageId: PKG })).success).toBe(true); expect(stored(rows, 'seed', 'r_reg')).toEqual([`draft|${PKG}|"sku"`]); }); diff --git a/packages/metadata-protocol/src/protocol.select-shorthand-refusal.test.ts b/packages/metadata-protocol/src/protocol.select-shorthand-refusal.test.ts index 10f20f54b08..a5c728c45ab 100644 --- a/packages/metadata-protocol/src/protocol.select-shorthand-refusal.test.ts +++ b/packages/metadata-protocol/src/protocol.select-shorthand-refusal.test.ts @@ -20,6 +20,8 @@ import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFin import { Field } from '@objectstack/spec/data'; import { ObjectStackProtocolImplementation } from './protocol.js'; +const TEST_PKG = 'test_pkg'; + /** The engine surface the repository write path touches (as the container-issue-descent harness). */ function makeProtocol() { const rows = new Map>(); @@ -41,7 +43,8 @@ function makeProtocol() { assertEngineDeleteDispatch(opts); return { deleted: 0 }; }, - registry: { registerItem: () => {}, registerObject: () => {} }, + // [#38174] a create names an installed writable package (ADR-0070 D1). + registry: { registerItem: () => {}, registerObject: () => {}, getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined) }, }; const protocol: any = new ObjectStackProtocolImplementation(engine, () => new Map()); return { protocol, rows }; @@ -68,7 +71,7 @@ describe('#25013 the save door refuses a shorthand option that is no system iden const { protocol, rows } = makeProtocol(); const err = await rejection(protocol.saveMetaItem({ - type: 'object', name: 'ticket', item: objectWith(Field.select(['open', 'no-overlay'])), + type: 'object', name: 'ticket', packageId: TEST_PKG, item: objectWith(Field.select(['open', 'no-overlay'])), })); expect(err.code).toBe('INVALID_METADATA'); @@ -81,10 +84,10 @@ describe('#25013 the save door refuses a shorthand option that is no system iden it('the explicit `{ value: \'no-overlay\' }` meets the identical refusal — one refusal set, not two', async () => { const shorthand = await rejection(makeProtocol().protocol.saveMetaItem({ - type: 'object', name: 'ticket', item: objectWith(Field.select(['open', 'no-overlay'])), + type: 'object', name: 'ticket', packageId: TEST_PKG, item: objectWith(Field.select(['open', 'no-overlay'])), })); const explicit = await rejection(makeProtocol().protocol.saveMetaItem({ - type: 'object', name: 'ticket', + type: 'object', name: 'ticket', packageId: TEST_PKG, item: objectWith(Field.select({ options: ['open', { label: 'no-overlay', value: 'no-overlay' }] })), })); @@ -96,7 +99,7 @@ describe('#25013 the save door refuses a shorthand option that is no system iden const { protocol, rows } = makeProtocol(); const result = await protocol.saveMetaItem({ - type: 'object', name: 'ticket', item: objectWith(Field.select(['Open', 'In Progress'])), + type: 'object', name: 'ticket', packageId: TEST_PKG, item: objectWith(Field.select(['Open', 'In Progress'])), }); expect(result.success).toBe(true); @@ -109,7 +112,7 @@ describe('a one-character option value saves at the object door', () => { const { protocol, rows } = makeProtocol(); const result = await protocol.saveMetaItem({ - type: 'object', name: 'ticket', item: objectWith(Field.select(['A', 'B', 'C'])), + type: 'object', name: 'ticket', packageId: TEST_PKG, item: objectWith(Field.select(['A', 'B', 'C'])), }); expect(result.success).toBe(true); @@ -123,7 +126,7 @@ describe('a one-character option value saves at the object door', () => { const { protocol, rows } = makeProtocol(); const err = await rejection(protocol.saveMetaItem({ - type: 'object', name: 'ticket', + type: 'object', name: 'ticket', packageId: TEST_PKG, item: objectWith({ type: 'select', options: [{ label: 'A', value: 'a' }, { label: 'X', value }] }), })); diff --git a/packages/metadata-protocol/src/protocol.served-content-hash.test.ts b/packages/metadata-protocol/src/protocol.served-content-hash.test.ts index cf08f64864d..035ff194da8 100644 --- a/packages/metadata-protocol/src/protocol.served-content-hash.test.ts +++ b/packages/metadata-protocol/src/protocol.served-content-hash.test.ts @@ -96,6 +96,11 @@ function matchesWhere(r: Record, where: Record return true; } +/** The writable package `case_grid` is created in. */ +const TEST_PKG = 'test_pkg'; +/** The registry's objects: the one `case_grid` binds, unpackaged. */ +const listCaseObject = (type: string) => (type === 'object' ? [{ name: 'case', label: 'Case', fields: {} }] : []); + function makeEngine(opts: { provider?: boolean } = {}) { const rows = new Map(); const historyRows: Array> = []; @@ -162,7 +167,13 @@ function makeEngine(opts: { provider?: boolean } = {}) { async transaction(cb: (ctx: any, info: { owned: boolean }) => Promise): Promise { return cb(undefined, { owned: true }); }, - registry: { registerItem: () => {}, registerObject: () => {}, getPackage: () => undefined }, + registry: { + registerItem: () => {}, registerObject: () => {}, + // [#38174] installs {@link TEST_PKG}, and lists the object the view + // binds, so a new view saved into that package resolves it. + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), + listItems: listCaseObject, + }, }; if (opts.provider !== false) engine.getKeyedDigest = () => keyedDigest; return { engine, rows, historyRows, auditRows }; @@ -177,6 +188,12 @@ const viewBody = (label: string) => ({ viewKind: 'list', }); const ref = { type: 'view', name: 'case_grid', actor: 'admin' } as const; +/** + * [#38174] The first save of `case_grid` creates it, and a package-less create + * is refused (ADR-0070 D1): it names {@link TEST_PKG}. Later saves naming no + * package write that holder's row. + */ +const created = { ...ref, packageId: TEST_PKG } as const; /** Every stored content hash the double holds, active rows and history alike. */ function storedHashes(h: ReturnType): Set { @@ -222,7 +239,7 @@ describe('[#21207] /meta receipts serve the keyed form of the stored content has const h = makeEngine(); const p = new ObjectStackProtocolImplementation(h.engine); - const first: any = await p.saveMetaItem({ ...ref, item: viewBody('v1') } as any); + const first: any = await p.saveMetaItem({ ...created, item: viewBody('v1') } as any); const stored1 = activeHash(h); expect(first.version).toMatch(KEYED); expect(first.version).not.toBe(stored1); @@ -243,7 +260,7 @@ describe('[#21207] /meta receipts serve the keyed form of the stored content has const h = makeEngine(); const p = new ObjectStackProtocolImplementation(h.engine); - await p.saveMetaItem({ ...ref, item: viewBody('v1') } as any); + await p.saveMetaItem({ ...created, item: viewBody('v1') } as any); await p.saveMetaItem({ ...ref, item: viewBody('staged'), mode: 'draft' } as any); const published: any = await p.publishMetaItem({ ...ref } as any); expect(published.version).toMatch(KEYED); @@ -261,7 +278,7 @@ describe('[#21207] the history read serves keyed hashes per event', () => { it('every event hash and parent hash is keyed, none is stored, and two reads agree', async () => { const h = makeEngine(); const p = new ObjectStackProtocolImplementation(h.engine); - const v1: any = await p.saveMetaItem({ ...ref, item: viewBody('v1') } as any); + const v1: any = await p.saveMetaItem({ ...created, item: viewBody('v1') } as any); await p.saveMetaItem({ ...ref, item: viewBody('v2'), parentVersion: v1.version } as any); const read1 = await p.historyMetaItem({ type: 'view', name: 'case_grid' }); @@ -283,7 +300,7 @@ describe('[#21207] inbound version tokens are compared in keyed form', () => { it('save door: the served token is accepted, the raw stored hash is refused (METADATA_CONFLICT / 409)', async () => { const h = makeEngine(); const p = new ObjectStackProtocolImplementation(h.engine); - const v1: any = await p.saveMetaItem({ ...ref, item: viewBody('v1') } as any); + const v1: any = await p.saveMetaItem({ ...created, item: viewBody('v1') } as any); const raw = activeHash(h); const refused = await rejection(() => @@ -300,7 +317,7 @@ describe('[#21207] inbound version tokens are compared in keyed form', () => { it('save door: a stale keyed token is refused, and the refusal carries the keyed value or none', async () => { const h = makeEngine(); const p = new ObjectStackProtocolImplementation(h.engine); - const v1: any = await p.saveMetaItem({ ...ref, item: viewBody('v1') } as any); + const v1: any = await p.saveMetaItem({ ...created, item: viewBody('v1') } as any); const v2: any = await p.saveMetaItem({ ...ref, item: viewBody('v2'), parentVersion: v1.version } as any); const stale = await rejection(() => @@ -317,7 +334,7 @@ describe('[#21207] inbound version tokens are compared in keyed form', () => { it('the decision-audit note of a refused write names no hash, stored or keyed', async () => { const h = makeEngine(); const p = new ObjectStackProtocolImplementation(h.engine); - const v1: any = await p.saveMetaItem({ ...ref, item: viewBody('v1') } as any); + const v1: any = await p.saveMetaItem({ ...created, item: viewBody('v1') } as any); await p.saveMetaItem({ ...ref, item: viewBody('v2'), parentVersion: v1.version } as any); await rejection(() => p.saveMetaItem({ ...ref, item: viewBody('lost'), parentVersion: v1.version } as any)); @@ -332,7 +349,7 @@ describe('[#21207] inbound version tokens are compared in keyed form', () => { it('reset door: the served token is accepted, the raw stored hash is refused', async () => { const h = makeEngine(); const p = new ObjectStackProtocolImplementation(h.engine); - const v1: any = await p.saveMetaItem({ ...ref, item: viewBody('v1') } as any); + const v1: any = await p.saveMetaItem({ ...created, item: viewBody('v1') } as any); const refused = await rejection(() => p.deleteMetaItem({ ...ref, parentVersion: activeHash(h) } as any)); @@ -349,7 +366,7 @@ describe('[#21207] no crypto provider: tokens keyed under a process-scoped ephem it('receipts and history serve a keyed token: never empty, never stored, distinct per content, stable', async () => { const h = makeEngine({ provider: false }); const p = new ObjectStackProtocolImplementation(h.engine); - const v1: any = await p.saveMetaItem({ ...ref, item: viewBody('v1') } as any); + const v1: any = await p.saveMetaItem({ ...created, item: viewBody('v1') } as any); const stored1 = activeHash(h); expect(v1.version).toMatch(KEYED); expect(v1.version).not.toBe(stored1); @@ -373,7 +390,7 @@ describe('[#21207] no crypto provider: tokens keyed under a process-scoped ephem it('the served token is accepted on both doors; a stale, raw, empty or withheld token is refused (METADATA_CONFLICT / 409)', async () => { const h = makeEngine({ provider: false }); const p = new ObjectStackProtocolImplementation(h.engine); - const v1: any = await p.saveMetaItem({ ...ref, item: viewBody('v1') } as any); + const v1: any = await p.saveMetaItem({ ...created, item: viewBody('v1') } as any); const v2: any = await p.saveMetaItem({ ...ref, item: viewBody('v2'), parentVersion: v1.version } as any); expect(v2.success).toBe(true); const raw = activeHash(h); @@ -399,7 +416,7 @@ describe('[#21207] no crypto provider: tokens keyed under a process-scoped ephem const h = makeEngine({ provider: false }); const first = new ObjectStackProtocolImplementation(h.engine); const second = new ObjectStackProtocolImplementation(h.engine); - const v1: any = await first.saveMetaItem({ ...ref, item: viewBody('v1') } as any); + const v1: any = await first.saveMetaItem({ ...created, item: viewBody('v1') } as any); const v2: any = await second.saveMetaItem({ ...ref, item: viewBody('v2'), parentVersion: v1.version } as any); expect(v2.success).toBe(true); }); @@ -407,7 +424,7 @@ describe('[#21207] no crypto provider: tokens keyed under a process-scoped ephem it('a provider registered later moves the tokens: the held token is refused once, the next served one is accepted', async () => { const h = makeEngine({ provider: false }); const p = new ObjectStackProtocolImplementation(h.engine); - const before: any = await p.saveMetaItem({ ...ref, item: viewBody('v1') } as any); + const before: any = await p.saveMetaItem({ ...created, item: viewBody('v1') } as any); h.engine.getKeyedDigest = () => keyedDigest; const refused = await rejection(() => @@ -429,7 +446,7 @@ describe('[#21207] a sent token is never read as no pin', () => { it('an empty or withheld token is refused on both doors with a provider registered (METADATA_CONFLICT / 409)', async () => { const h = makeEngine(); const p = new ObjectStackProtocolImplementation(h.engine); - await p.saveMetaItem({ ...ref, item: viewBody('v1') } as any); + await p.saveMetaItem({ ...created, item: viewBody('v1') } as any); const raw = activeHash(h); for (const token of ['', '(withheld)']) { for (const run of [ @@ -449,7 +466,7 @@ describe('[#21207] a change note that quotes a stored hash', () => { it('the publish door writes a note that quotes no hash', async () => { const h = makeEngine(); const p = new ObjectStackProtocolImplementation(h.engine); - await p.saveMetaItem({ ...ref, item: viewBody('staged'), mode: 'draft' } as any); + await p.saveMetaItem({ ...created, item: viewBody('staged'), mode: 'draft' } as any); await p.publishMetaItem({ ...ref } as any); const notes = h.historyRows.map((r) => r.change_note).filter((n) => typeof n === 'string') as string[]; expect(notes.length).toBeGreaterThan(0); @@ -460,7 +477,7 @@ describe('[#21207] a change note that quotes a stored hash', () => { for (const provider of [true, false]) { const h = makeEngine({ provider }); const p = new ObjectStackProtocolImplementation(h.engine); - const saved: any = await p.saveMetaItem({ ...ref, item: viewBody('v1') } as any); + const saved: any = await p.saveMetaItem({ ...created, item: viewBody('v1') } as any); const stored = activeHash(h); // A row written before the publish door stated its own message. for (const row of h.historyRows) row.change_note = `publish draft (hash ${stored})`; @@ -710,7 +727,7 @@ function withReadRegistry(h: ReturnType): ReturnType undefined, getArtifactItem: () => undefined, - listItems: () => [], + listItems: listCaseObject, getObject: () => undefined, isPackageDisabled: () => false, applyNavContributions: (app: unknown) => app, @@ -724,7 +741,7 @@ describe('[#22114] the item read serves the version token the save door accepts' it('active and draft: the read\'s `version` is the receipt\'s token, keyed, never the stored hash — and it pins the next save', async () => { const h = withReadRegistry(makeEngine()); const p = new ObjectStackProtocolImplementation(h.engine); - const active: any = await p.saveMetaItem({ ...ref, item: viewBody('v1') } as any); + const active: any = await p.saveMetaItem({ ...created, item: viewBody('v1') } as any); const draft: any = await p.saveMetaItem({ ...ref, item: viewBody('staged'), mode: 'draft' } as any); const readActive: any = await p.getMetaItem({ ...READ }); @@ -743,7 +760,7 @@ describe('[#22114] the item read serves the version token the save door accepts' it('a `previewDrafts` read publishes no `version` — it serves two lifecycles', async () => { const h = withReadRegistry(makeEngine()); const p = new ObjectStackProtocolImplementation(h.engine); - await p.saveMetaItem({ ...ref, item: viewBody('v1') } as any); + await p.saveMetaItem({ ...created, item: viewBody('v1') } as any); const withoutDraft: any = await p.getMetaItem({ ...READ, previewDrafts: true }); expect(withoutDraft).not.toHaveProperty('version'); await p.saveMetaItem({ ...ref, item: viewBody('staged'), mode: 'draft' } as any); @@ -755,7 +772,7 @@ describe('[#22114] the item read serves the version token the save door accepts' it('the conflict refusal states `currentVersion`: the keyed head the next read serves, or `null` with no row', async () => { const h = withReadRegistry(makeEngine()); const p = new ObjectStackProtocolImplementation(h.engine); - const v1: any = await p.saveMetaItem({ ...ref, item: viewBody('v1') } as any); + const v1: any = await p.saveMetaItem({ ...created, item: viewBody('v1') } as any); const v2: any = await p.saveMetaItem({ ...ref, item: viewBody('v2'), parentVersion: v1.version } as any); const stale = await rejection(() => @@ -776,7 +793,7 @@ describe('[#22114] the item read serves the version token the save door accepts' // No row in either lifecycle: the head is `null`, stated as such. const noRow = await rejection(() => - p.saveMetaItem({ ...ref, name: 'never_saved', item: { ...viewBody('n'), name: 'never_saved' }, mode: 'draft', parentVersion: v2.version } as any)); + p.saveMetaItem({ ...created, name: 'never_saved', item: { ...viewBody('n'), name: 'never_saved' }, mode: 'draft', parentVersion: v2.version } as any)); expect(noRow.code).toBe('METADATA_CONFLICT'); expect(noRow.status).toBe(409); expect(noRow).toHaveProperty('currentVersion', null); @@ -798,7 +815,7 @@ describe('[#37628] a first draft pinned with the published version a read served it('accepted the first time: the draft is written over the unchanged published row', async () => { const h = withReadRegistry(makeEngine()); const p = new ObjectStackProtocolImplementation(h.engine); - await p.saveMetaItem({ ...ref, item: viewBody('v1') } as any); + await p.saveMetaItem({ ...created, item: viewBody('v1') } as any); const published = activeHash(h); const read: any = await p.getMetaItem({ ...READ, state: 'active' }); expect(read.version).toMatch(KEYED); @@ -817,7 +834,7 @@ describe('[#37628] a first draft pinned with the published version a read served it('refused when the published row changed after the read, naming the current version — which is then accepted', async () => { const h = withReadRegistry(makeEngine()); const p = new ObjectStackProtocolImplementation(h.engine); - await p.saveMetaItem({ ...ref, item: viewBody('v1') } as any); + await p.saveMetaItem({ ...created, item: viewBody('v1') } as any); const read: any = await p.getMetaItem({ ...READ, state: 'active' }); const moved: any = await p.saveMetaItem({ ...ref, item: viewBody('v2'), parentVersion: read.version } as any); @@ -837,7 +854,7 @@ describe('[#37628] a first draft pinned with the published version a read served it('refused when another caller saved a draft after the read, naming that draft\'s version', async () => { const h = withReadRegistry(makeEngine()); const p = new ObjectStackProtocolImplementation(h.engine); - await p.saveMetaItem({ ...ref, item: viewBody('v1') } as any); + await p.saveMetaItem({ ...created, item: viewBody('v1') } as any); const read: any = await p.getMetaItem({ ...READ, state: 'active' }); const theirs: any = await p.saveMetaItem({ ...ref, item: viewBody('theirs'), mode: 'draft' } as any); @@ -851,7 +868,7 @@ describe('[#37628] a first draft pinned with the published version a read served it('a draft written between the head read and the write is still refused by the repository\'s lock', async () => { const h = withReadRegistry(makeEngine()); const p = new ObjectStackProtocolImplementation(h.engine); - await p.saveMetaItem({ ...ref, item: viewBody('v1') } as any); + await p.saveMetaItem({ ...created, item: viewBody('v1') } as any); const read: any = await p.getMetaItem({ ...READ, state: 'active' }); // The other caller's draft lands after this save read its heads and @@ -904,7 +921,7 @@ describe('[#23406] a refused first-write pin is told what it asserted', () => { it('draft: a first draft over a pending draft — the sentence states the assertion; code, status and keyed fields unchanged', async () => { const h = makeEngine(); const p = new ObjectStackProtocolImplementation(h.engine); - const first: any = await p.saveMetaItem({ ...ref, item: viewBody('first'), parentVersion: null, mode: 'draft' } as any); + const first: any = await p.saveMetaItem({ ...created, item: viewBody('first'), parentVersion: null, mode: 'draft' } as any); const refused = await rejection(() => p.saveMetaItem({ ...ref, item: viewBody('second'), parentVersion: null, mode: 'draft' } as any)); @@ -919,7 +936,7 @@ describe('[#23406] a refused first-write pin is told what it asserted', () => { it('active: a first write of the live row over an existing one — the same, naming the active lifecycle', async () => { const h = makeEngine(); const p = new ObjectStackProtocolImplementation(h.engine); - const first: any = await p.saveMetaItem({ ...ref, item: viewBody('first'), parentVersion: null } as any); + const first: any = await p.saveMetaItem({ ...created, item: viewBody('first'), parentVersion: null } as any); const refused = await rejection(() => p.saveMetaItem({ ...ref, item: viewBody('second'), parentVersion: null } as any)); @@ -932,7 +949,7 @@ describe('[#23406] a refused first-write pin is told what it asserted', () => { it('control: a conflict that is no first-write pin (a stale token) keeps the door\'s own sentence', async () => { const h = makeEngine(); const p = new ObjectStackProtocolImplementation(h.engine); - const v1: any = await p.saveMetaItem({ ...ref, item: viewBody('v1') } as any); + const v1: any = await p.saveMetaItem({ ...created, item: viewBody('v1') } as any); const v2: any = await p.saveMetaItem({ ...ref, item: viewBody('v2'), parentVersion: v1.version } as any); const stale = await rejection(() => diff --git a/packages/metadata-protocol/src/protocol.stored-action-gate-lowering.test.ts b/packages/metadata-protocol/src/protocol.stored-action-gate-lowering.test.ts index c4f5ee4dfc3..5b0169d6af4 100644 --- a/packages/metadata-protocol/src/protocol.stored-action-gate-lowering.test.ts +++ b/packages/metadata-protocol/src/protocol.stored-action-gate-lowering.test.ts @@ -21,6 +21,9 @@ import { ObjectStackProtocolImplementation } from './protocol.js'; // Paid at collection, not inside a clocked case (check:test-source-alias). import '@objectstack/lint'; +/** The writable package every save here names. */ +const TEST_PKG = 'test_pkg'; + /** The engine surface the repository write path touches (as the external-binding harness). */ function makeProtocol() { const rows: Record[] = []; @@ -42,7 +45,15 @@ function makeProtocol() { assertEngineDeleteDispatch(opts); return { deleted: 0 }; }, - registry: { registerItem: () => {}, registerObject: () => {}, getItem: () => undefined }, + // [#38174] `getPackage` installs {@link TEST_PKG}: a new item is saved + // into a writable package (ADR-0070 D1). + registry: { + registerItem: () => {}, registerObject: () => {}, getItem: () => undefined, + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), + // The object a standalone action names, held by that package, so + // the action's package closure reaches it. + listItems: (type: string) => (type === 'object' ? [{ name: 'gap_order', label: 'Order', _packageId: TEST_PKG, fields: {} }] : []), + }, }; const protocol: any = new ObjectStackProtocolImplementation(engine, () => new Map()); return { protocol, rows }; @@ -87,7 +98,7 @@ describe('#26723 the save door stores an action as its ActionSchema parse', () = async (mode) => { const { protocol, rows } = makeProtocol(); const result = await protocol.saveMetaItem({ - type: 'object', name: 'gap_order', mode, + type: 'object', name: 'gap_order', packageId: TEST_PKG, mode, item: order([structuredClone(SSO_ONLY), structuredClone(OWNER_ONLY)]), }); expect(result.success).toBe(true); @@ -108,7 +119,7 @@ describe('#26723 the save door stores an action as its ActionSchema parse', () = it('control: an action without the gate keys is stored as its parse, and the rest of the body as written', async () => { const { protocol, rows } = makeProtocol(); const item = order([structuredClone(PLAIN)]); - await protocol.saveMetaItem({ type: 'object', name: 'gap_order', item }); + await protocol.saveMetaItem({ type: 'object', name: 'gap_order', packageId: TEST_PKG, item }); const stored = storedBody(rows, 'object', 'gap_order'); expect(stored.actions).toEqual([parsedAction(PLAIN)]); @@ -118,18 +129,18 @@ describe('#26723 the save door stores an action as its ActionSchema parse', () = it('re-saving a stored body is a no-op: the parse is idempotent over its own output', async () => { const first = makeProtocol(); - await first.protocol.saveMetaItem({ type: 'object', name: 'gap_order', item: order([structuredClone(SSO_ONLY)]) }); + await first.protocol.saveMetaItem({ type: 'object', name: 'gap_order', packageId: TEST_PKG, item: order([structuredClone(SSO_ONLY)]) }); const once = storedBody(first.rows, 'object', 'gap_order'); const second = makeProtocol(); - await second.protocol.saveMetaItem({ type: 'object', name: 'gap_order', item: structuredClone(once) }); + await second.protocol.saveMetaItem({ type: 'object', name: 'gap_order', packageId: TEST_PKG, item: structuredClone(once) }); expect(storedBody(second.rows, 'object', 'gap_order').actions).toEqual(once.actions); }); it('an object with no `actions` key is stored without one', async () => { const { protocol, rows } = makeProtocol(); const { actions: _none, ...bare } = order([]); - await protocol.saveMetaItem({ type: 'object', name: 'gap_order', item: bare }); + await protocol.saveMetaItem({ type: 'object', name: 'gap_order', packageId: TEST_PKG, item: bare }); expect(storedBody(rows, 'object', 'gap_order')).not.toHaveProperty('actions'); }); @@ -138,7 +149,7 @@ describe('#26723 the save door stores an action as its ActionSchema parse', () = async (mode) => { const { protocol, rows } = makeProtocol(); const result = await protocol.saveMetaItem({ - type: 'action', name: 'sso_only', mode, + type: 'action', name: 'sso_only', packageId: TEST_PKG, mode, item: { ...structuredClone(SSO_ONLY), objectName: 'gap_order' }, }); expect(result.success).toBe(true); diff --git a/packages/metadata-protocol/src/protocol.translation-apps-door-38649.test.ts b/packages/metadata-protocol/src/protocol.translation-apps-door-38649.test.ts index 9bf2813340c..8977659895a 100644 --- a/packages/metadata-protocol/src/protocol.translation-apps-door-38649.test.ts +++ b/packages/metadata-protocol/src/protocol.translation-apps-door-38649.test.ts @@ -47,6 +47,9 @@ const whereValueMatches = (actual: unknown, want: unknown): boolean => ? (want as { $in: unknown[] }).$in.includes(actual) : actual === want; +/** [#38174] A save of a new item names an installed writable package (ADR-0070 D1). */ +const TEST_PKG = 'test_pkg'; + const LIVE_OBJECTS = [{ name: 'crm_lead', fields: { name: { type: 'text' } } }]; /** The app as the registry holds it: its own navigation only. */ @@ -131,7 +134,8 @@ function makeProtocol() { applyNavContributions: (app: any) => app?.name === 'crm' ? { ...app, navigation: [...app.navigation, CONTRIBUTED_ITEM] } : app, getItem: () => undefined, - getPackage: () => undefined, + // [#38174] the installed writable package a create names (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), }, }; const protocol = new ObjectStackProtocolImplementation(engine, () => new Map(), 'env_test'); @@ -141,7 +145,7 @@ function makeProtocol() { } const saveTranslation = (protocol: any, name: string, groups: Record, extra: Record = {}) => - protocol.saveMetaItem({ type: 'translation', name, item: { name, locale: 'zh-CN', ...groups }, ...extra }); + protocol.saveMetaItem({ type: 'translation', name, packageId: TEST_PKG, item: { name, locale: 'zh-CN', ...groups }, ...extra }); const REMOVED_NAV = { apps: { crm: { navigation: { nav_leads: { label: '线索' }, nav_zzz_gone: { label: '旧菜单' } } } } }; const LIVE_NAV = { @@ -209,6 +213,7 @@ describe('the metadata door judges a translation\'s apps keys against the served await protocol.saveMetaItem({ type: 'permission', name: 'sales_rep', + packageId: TEST_PKG, item: { name: 'sales_rep', label: 'Sales Rep', objects: {} }, }); expect(listedTypes).not.toContain('app'); diff --git a/packages/metadata-protocol/src/protocol.translation-target-door-38623.test.ts b/packages/metadata-protocol/src/protocol.translation-target-door-38623.test.ts index 429216b3792..e52560add51 100644 --- a/packages/metadata-protocol/src/protocol.translation-target-door-38623.test.ts +++ b/packages/metadata-protocol/src/protocol.translation-target-door-38623.test.ts @@ -62,6 +62,8 @@ const LIVE_OBJECTS = [ ]; const LIVE_PERMISSION_SETS = [{ name: 'sales_rep', label: 'Sales Rep', objects: {} }]; +const TEST_PKG = 'test_pkg'; + function makeProtocol() { // Keyed BY TABLE: one flat map would answer a `sys_metadata` read with the // history and commit journals' rows (see `protocol.runtime-authoring-gate.test.ts`). @@ -129,7 +131,8 @@ function makeProtocol() { listItems: (type: string) => type === 'object' ? LIVE_OBJECTS : type === 'permission' ? LIVE_PERMISSION_SETS : [], getItem: () => undefined, - getPackage: () => undefined, + // [#38174] a new item is saved into an installed writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), }, }; const protocol = new ObjectStackProtocolImplementation(engine, () => new Map(), 'env_test'); @@ -141,7 +144,7 @@ function makeProtocol() { const translation = (name: string, groups: Record) => ({ name, locale: 'zh-CN', ...groups }); const saveTranslation = (protocol: any, name: string, groups: Record, extra: Record = {}) => - protocol.saveMetaItem({ type: 'translation', name, item: translation(name, groups), ...extra }); + protocol.saveMetaItem({ type: 'translation', name, packageId: TEST_PKG, item: translation(name, groups), ...extra }); const REMOVED_FIELD = { objects: { crm_lead: { fields: { zzz_removed: { label: '旧字段' } } } } }; const LIVE_KEYS = { @@ -187,7 +190,7 @@ describe('the metadata save door advises on a translation key nothing declares ( // D1: a draft is never gated, so its save says nothing about the key. expect(advisoryPaths(draft)).toEqual([]); - const published = await protocol.publishMetaItem({ type: 'translation', name: 'zh_cn' }); + const published = await protocol.publishMetaItem({ type: 'translation', name: 'zh_cn', packageId: TEST_PKG }); expect(published.success).toBe(true); expect(advisoryPaths(published)).toEqual(['translations[0].objects.crm_lead.fields.zzz_removed']); expect(activeTranslations().map((r) => r.name)).toEqual(['zh_cn']); diff --git a/packages/metadata-protocol/src/protocol.unknown-datasource-refusal.test.ts b/packages/metadata-protocol/src/protocol.unknown-datasource-refusal.test.ts index 838473bd606..13856b88532 100644 --- a/packages/metadata-protocol/src/protocol.unknown-datasource-refusal.test.ts +++ b/packages/metadata-protocol/src/protocol.unknown-datasource-refusal.test.ts @@ -220,14 +220,15 @@ describe('[#26724] the object save door — a `datasource` that names nothing', it('a draft save does not count a datasource draft that is gone by its publish: the per-item publish is refused', async () => { const { protocol, rows } = makeSession(); - await protocol.saveMetaItem({ type: 'datasource', name: 'lake', item: datasource('lake'), mode: 'draft' }); - await protocol.saveMetaItem({ type: 'object', name: 'lake_item', item: object('lake_item', 'lake'), mode: 'draft' }); + // [#38174] a new item is saved into a writable package (ADR-0070 D1). + await protocol.saveMetaItem({ type: 'datasource', name: 'lake', item: datasource('lake'), mode: 'draft', packageId: PKG }); + await protocol.saveMetaItem({ type: 'object', name: 'lake_item', item: object('lake_item', 'lake'), mode: 'draft', packageId: PKG }); // The object alone goes live; its datasource stays a draft. const err = await refusalOf(protocol.publishMetaItem({ type: 'object', name: 'lake_item' })); expectRefusal(err, 'lake_item', 'lake'); - expect(stored(rows, 'object', 'lake_item')).toEqual(['draft|-|lake']); + expect(stored(rows, 'object', 'lake_item')).toEqual([`draft|${PKG}|lake`]); }); }); @@ -267,7 +268,7 @@ describe('[#26724] controls — a datasource that exists is not refused', () => const { protocol, rows } = makeSession(); await protocol.saveMetaItem({ type: 'object', name: 'gapdata_ok', item: object('gapdata_ok', ds), mode: 'draft', packageId: PKG }); expect((await protocol.publishPackageDrafts({ packageId: PKG })).outcome).toBe('published'); - expect((await protocol.saveMetaItem({ type: 'object', name: 'gapdata_ok2', item: object('gapdata_ok2', ds) })).success).toBe(true); + expect((await protocol.saveMetaItem({ type: 'object', name: 'gapdata_ok2', item: object('gapdata_ok2', ds), packageId: PKG })).success).toBe(true); expect(stored(rows, 'object', 'gapdata_ok')).toEqual([`active|${PKG}|${ds ?? '-'}`]); }); @@ -275,7 +276,7 @@ describe('[#26724] controls — a datasource that exists is not refused', () => const { protocol, rows } = makeSession({ drivers: ['rt_store'] }); await protocol.saveMetaItem({ type: 'object', name: 'rt_item', item: object('rt_item', 'rt_store'), mode: 'draft', packageId: PKG }); expect((await protocol.publishPackageDrafts({ packageId: PKG })).outcome).toBe('published'); - expect((await protocol.saveMetaItem({ type: 'object', name: 'rt_item2', item: object('rt_item2', 'rt_store') })).success).toBe(true); + expect((await protocol.saveMetaItem({ type: 'object', name: 'rt_item2', item: object('rt_item2', 'rt_store'), packageId: PKG })).success).toBe(true); expect(stored(rows, 'object', 'rt_item')).toEqual([`active|${PKG}|rt_store`]); }); @@ -288,8 +289,14 @@ describe('[#26724] controls — a datasource that exists is not refused', () => it('a datasource stored in this environment', async () => { const { protocol, rows } = makeSession(); - await protocol.saveMetaItem({ type: 'datasource', name: 'lake', item: datasource('lake') }); - await protocol.saveMetaItem({ type: 'object', name: 'lake_item', item: object('lake_item', 'lake'), mode: 'draft' }); + // [#38174] a package-less CREATE is refused (ADR-0070 D1): the loose + // datasource row and the loose object draft are seeded directly. + const ds = { + type: 'datasource', name: 'lake', organization_id: null, package_id: null, + state: 'active', metadata: JSON.stringify(datasource('lake')), + }; + rows.set(keyOf(ds), { ...ds, id: 'planted_lake' }); + plantDraft(rows, object('lake_item', 'lake'), null); expect((await protocol.publishMetaItem({ type: 'object', name: 'lake_item' })).success).toBe(true); expect(stored(rows, 'object', 'lake_item')).toEqual(['active|-|lake']); }); @@ -328,7 +335,8 @@ describe('[#26724] controls — a datasource that exists is not refused', () => it('an engine that cannot name its registered drivers refuses nothing', async () => { const { protocol, rows } = makeSession({ namesDrivers: false }); - expect((await protocol.saveMetaItem({ type: 'object', name: 'gapdata_badds', item: object('gapdata_badds', 'gapdata_nosuch') })).success).toBe(true); - expect(stored(rows, 'object', 'gapdata_badds')).toEqual(['active|-|gapdata_nosuch']); + // [#38174] a new item is saved into a writable package (ADR-0070 D1). + expect((await protocol.saveMetaItem({ type: 'object', name: 'gapdata_badds', item: object('gapdata_badds', 'gapdata_nosuch'), packageId: PKG })).success).toBe(true); + expect(stored(rows, 'object', 'gapdata_badds')).toEqual([`active|${PKG}|gapdata_nosuch`]); }); }); diff --git a/packages/metadata-protocol/src/protocol.unknown-grant-object-refusal.test.ts b/packages/metadata-protocol/src/protocol.unknown-grant-object-refusal.test.ts index 9ffedce70c7..42ead009ca4 100644 --- a/packages/metadata-protocol/src/protocol.unknown-grant-object-refusal.test.ts +++ b/packages/metadata-protocol/src/protocol.unknown-grant-object-refusal.test.ts @@ -246,14 +246,15 @@ describe('[#28990] the permission-set save door — a grant on an object that do it('a draft save does not count an object draft that is gone by its publish: the per-item publish is refused', async () => { const { protocol, rows } = makeSession(); - await protocol.saveMetaItem({ type: 'object', name: 'qa_widget', item: object('qa_widget'), mode: 'draft' }); - await protocol.saveMetaItem({ type: 'permission', name: 'qa_probe', item: set('qa_probe', ['qa_widget']), mode: 'draft' }); + // [#38174] a new item is saved into an installed writable package (ADR-0070 D1). + await protocol.saveMetaItem({ type: 'object', name: 'qa_widget', item: object('qa_widget'), mode: 'draft', packageId: PKG }); + await protocol.saveMetaItem({ type: 'permission', name: 'qa_probe', item: set('qa_probe', ['qa_widget']), mode: 'draft', packageId: PKG }); // The set alone goes live; its object stays a draft. - const err = await refusalOf(protocol.publishMetaItem({ type: 'permission', name: 'qa_probe' })); + const err = await refusalOf(protocol.publishMetaItem({ type: 'permission', name: 'qa_probe', packageId: PKG })); expectRefusal(err, 'qa_probe', ['qa_widget'], 'publish'); - expect(stored(rows, 'permission', 'qa_probe')).toEqual(['draft|-|qa_widget']); + expect(stored(rows, 'permission', 'qa_probe')).toEqual([`draft|${PKG}|qa_widget`]); }); }); @@ -325,16 +326,24 @@ describe('[#28990] controls — a grant on an object that exists is not refused' await protocol.saveMetaItem({ type: 'permission', name: 'qa_ok', item: set('qa_ok', grants), mode: 'draft', packageId: PKG }); const res = await protocol.publishPackageDrafts({ packageId: PKG }); expect(res.outcome, JSON.stringify(res.failed)).toBe('published'); - expect((await protocol.saveMetaItem({ type: 'permission', name: 'qa_ok2', item: set('qa_ok2', grants) })).success).toBe(true); + // [#38174] a new item is saved into an installed writable package (ADR-0070 D1). + expect((await protocol.saveMetaItem({ type: 'permission', name: 'qa_ok2', item: set('qa_ok2', grants), packageId: PKG })).success).toBe(true); expect(stored(rows, 'permission', 'qa_ok')).toEqual([`active|${PKG}|${grants.join(',')}`]); }); it('an object stored in this environment that the registry has not registered', async () => { const { protocol, rows } = makeSession(); - await protocol.saveMetaItem({ type: 'object', name: 'qa_widget', item: object('qa_widget') }); - await protocol.saveMetaItem({ type: 'permission', name: 'qa_ok', item: set('qa_ok', ['qa_widget']), mode: 'draft' }); - expect((await protocol.publishMetaItem({ type: 'permission', name: 'qa_ok' })).success).toBe(true); - expect(stored(rows, 'permission', 'qa_ok')).toEqual(['active|-|qa_widget']); + // [#38174] A package-less create is refused (ADR-0070 D1): the object + // stored in this environment is seeded as the store writes it, and the + // set is saved into an installed writable package. + const objectRow = { + type: 'object', name: 'qa_widget', organization_id: null, package_id: null, state: 'active', + metadata: JSON.stringify(object('qa_widget')), + }; + rows.set(keyOf(objectRow), { ...objectRow, id: 'planted_object_qa_widget' }); + await protocol.saveMetaItem({ type: 'permission', name: 'qa_ok', item: set('qa_ok', ['qa_widget']), mode: 'draft', packageId: PKG }); + expect((await protocol.publishMetaItem({ type: 'permission', name: 'qa_ok', packageId: PKG })).success).toBe(true); + expect(stored(rows, 'permission', 'qa_ok')).toEqual([`active|${PKG}|qa_widget`]); }); it('an object drafted in the same package publishes with the set, even promoted after it', async () => { @@ -372,13 +381,14 @@ describe('[#28990] controls — a grant on an object that exists is not refused' it('[#30255] a copy that inherits a grant on an object not registered here (the clone door): saved; a grant the copy adds is still refused', async () => { const { protocol, rows } = makeSession({ objects: ['qa_widget'] }); + // [#38174] a new item is saved into an installed writable package (ADR-0070 D1). const result = await protocol.saveMetaItem({ type: 'permission', name: 'qa_copy', item: set('qa_copy', ['qa_widget', 'qa_plugin_object']), - inheritedGrantObjects: ['qa_widget', 'qa_plugin_object'], + inheritedGrantObjects: ['qa_widget', 'qa_plugin_object'], packageId: PKG, }); expect(result.success).toBe(true); - expect(stored(rows, 'permission', 'qa_copy')).toEqual(['active|-|qa_widget,qa_plugin_object']); + expect(stored(rows, 'permission', 'qa_copy')).toEqual([`active|${PKG}|qa_widget,qa_plugin_object`]); // …while an unknown object the copy does not inherit is this save's grant, and refused. const err = await refusalOf(protocol.saveMetaItem({ type: 'permission', name: 'qa_copy2', item: set('qa_copy2', ['qa_plugin_object', 'qa_typo']), @@ -390,8 +400,9 @@ describe('[#28990] controls — a grant on an object that exists is not refused' it('a registry that cannot look an object up refuses nothing', async () => { const { protocol, rows } = makeSession({ looksUpObjects: false }); - expect((await protocol.saveMetaItem({ type: 'permission', name: 'qa_probe', item: set('qa_probe', ['qa_no_such_object']) })).success).toBe(true); - expect(stored(rows, 'permission', 'qa_probe')).toEqual(['active|-|qa_no_such_object']); + // [#38174] a new item is saved into an installed writable package (ADR-0070 D1). + expect((await protocol.saveMetaItem({ type: 'permission', name: 'qa_probe', item: set('qa_probe', ['qa_no_such_object']), packageId: PKG })).success).toBe(true); + expect(stored(rows, 'permission', 'qa_probe')).toEqual([`active|${PKG}|qa_no_such_object`]); }); }); @@ -524,7 +535,10 @@ describe('[#32162] the held-grants read is the landing package\'s own set', () = }); it('the doors hand the landing package: a save naming it, a draft publish into it, a restore bound to it', async () => { - const { protocol } = makeSession({ objects: ['qa_widget'] }); + const { protocol, rows } = makeSession({ objects: ['qa_widget'] }); + // [#38174] A package-less create is refused (ADR-0070 D1): the + // environment's set is seeded loose, and its package-less save runs in place. + plant(rows, set('qa_env', ['qa_widget']), 'active', null); const spy = vi.spyOn(protocol, 'unknownGrantObjectSaveRefusal'); const landing = () => spy.mock.calls[spy.mock.calls.length - 1]?.[7]; await protocol.saveMetaItem({ type: 'permission', name: 'qa_ok', item: set('qa_ok', ['qa_widget']), mode: 'draft', packageId: PKG }); diff --git a/packages/metadata-protocol/src/protocol.unknown-picklist-binding-refusal.test.ts b/packages/metadata-protocol/src/protocol.unknown-picklist-binding-refusal.test.ts index f1d3e12c227..ca6b245265c 100644 --- a/packages/metadata-protocol/src/protocol.unknown-picklist-binding-refusal.test.ts +++ b/packages/metadata-protocol/src/protocol.unknown-picklist-binding-refusal.test.ts @@ -279,7 +279,9 @@ describe('[#29898] the publish doors — an object draft stored before the rule' it('a list that goes between the draft save and its publish: the per-item publish is refused', async () => { const { protocol, rows, picklists } = makeSession({ picklists: ['qa_tier'] }); - await protocol.saveMetaItem({ type: 'object', name: 'qa_probe', item: object('qa_probe', [['tier', 'qa_tier']]), mode: 'draft' }); + // [#38174] a package-less create is refused (ADR-0070 D1): the loose + // draft (saved while the list existed) is planted directly. + plant(rows, object('qa_probe', [['tier', 'qa_tier']]), 'draft', null); picklists.delete('qa_tier'); const err = await refusalOf(protocol.publishMetaItem({ type: 'object', name: 'qa_probe' })); @@ -322,7 +324,7 @@ describe('[#29898] controls — a binding the door does not refuse', () => { await protocol.saveMetaItem({ type: 'object', name: 'qa_ok', item: object('qa_ok', bindings), mode: 'draft', packageId: PKG }); const res = await protocol.publishPackageDrafts({ packageId: PKG }); expect(res.outcome, JSON.stringify(res.failed)).toBe('published'); - expect((await protocol.saveMetaItem({ type: 'object', name: 'qa_ok2', item: object('qa_ok2', bindings) })).success).toBe(true); + expect((await protocol.saveMetaItem({ type: 'object', name: 'qa_ok2', item: object('qa_ok2', bindings), packageId: PKG })).success).toBe(true); expect(stored(rows, 'qa_ok')).toEqual([`active|${PKG}|${bindings.map(([f, p]) => `${f}:${p}`).join(',')}`]); }); @@ -349,7 +351,8 @@ describe('[#29898] controls — a binding the door does not refuse', () => { it('a registry that cannot resolve a list refuses nothing', async () => { const { protocol, rows } = makeSession({ resolvesPicklists: false }); - expect((await protocol.saveMetaItem({ type: 'object', name: 'qa_probe', item: object('qa_probe', [['t', 'nope_list']]) })).success).toBe(true); - expect(stored(rows, 'qa_probe')).toEqual(['active|-|t:nope_list']); + // [#38174] a create names an installed writable package (ADR-0070 D1). + expect((await protocol.saveMetaItem({ type: 'object', name: 'qa_probe', item: object('qa_probe', [['t', 'nope_list']]), packageId: PKG })).success).toBe(true); + expect(stored(rows, 'qa_probe')).toEqual([`active|${PKG}|t:nope_list`]); }); }); diff --git a/packages/metadata-protocol/src/protocol.unrecognised-meta-type.test.ts b/packages/metadata-protocol/src/protocol.unrecognised-meta-type.test.ts index af66dd87807..a7e717b1d45 100644 --- a/packages/metadata-protocol/src/protocol.unrecognised-meta-type.test.ts +++ b/packages/metadata-protocol/src/protocol.unrecognised-meta-type.test.ts @@ -74,6 +74,9 @@ interface Row { metadata: string; } +/** The writable package the accepted creates name. */ +const TEST_PKG = 'test_pkg'; + function makeProtocol(seedRows: Array> = []) { const rows = new Map(); let nextId = 0; @@ -138,9 +141,14 @@ function makeProtocol(seedRows: Array> = []) { registerItem: () => {}, registerObject: () => {}, unregisterItem: () => {}, - listItems: () => [], + // [#38174] `task`, held by {@link TEST_PKG}, so a view saved into + // that package names an object inside its closure. + listItems: (type: string) => (type === 'object' ? [{ name: 'task', label: 'Task', _packageId: TEST_PKG, fields: {} }] : []), getItem: () => undefined, getArtifactItem: () => undefined, + // [#38174] installs {@link TEST_PKG}: a new item is saved into a + // writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), }, }; const protocol = new ObjectStackProtocolImplementation( @@ -248,7 +256,7 @@ describe('#8421 — the traffic that must keep working', () => { for (const { type, item, why } of ACCEPTED) { it(`still saves ${type} (${why})`, async () => { const { protocol, rows } = makeProtocol(); - const result = await protocol.saveMetaItem({ type, name: 'probe_item', item }); + const result = await protocol.saveMetaItem({ type, name: 'probe_item', item, packageId: TEST_PKG }); expect(result.success).toBe(true); expect(metaRows(rows).length).toBe(1); expect(metaRows(rows)[0]!.type).toBe(type); @@ -268,6 +276,7 @@ describe('#8421 — the traffic that must keep working', () => { type: 'webhook', name: 'first_hook', item: { name: 'first_hook', label: 'First', object: 'task', triggers: ['create'], url: 'https://example.com/hook' }, + packageId: TEST_PKG, }); expect(result.success).toBe(true); expect(metaRows(rows)[0]!.type).toBe('webhook'); @@ -368,7 +377,7 @@ describe('#8421 — a namespace that ALREADY EXISTS is not being minted', () => const { protocol, rows } = makeProtocol([{ type: 'fieldz', name: 'showcase_task.title' }]); const result = await protocol.saveMetaItem({ - type: 'fieldz', name: 'showcase_task.due_at', item: { name: 'showcase_task.due_at' }, + type: 'fieldz', name: 'showcase_task.due_at', item: { name: 'showcase_task.due_at' }, packageId: TEST_PKG, }); expect(result.success).toBe(true); diff --git a/packages/metadata-protocol/src/protocol.view-container-reset-expansions.test.ts b/packages/metadata-protocol/src/protocol.view-container-reset-expansions.test.ts index 150d853d9ec..5360581a79d 100644 --- a/packages/metadata-protocol/src/protocol.view-container-reset-expansions.test.ts +++ b/packages/metadata-protocol/src/protocol.view-container-reset-expansions.test.ts @@ -503,6 +503,17 @@ const rtContainer = (listViews: Record) => ({ listViews, }); const rtMember = (label: string) => ({ label, type: 'grid', data: rtData, columns: [{ field: 'title' }] }); +/** + * [#38174] a package-less create is refused (ADR-0070 D1): the loose container + * row is seeded directly (no members), and the package-less save runs in place. + */ +const seedLooseRtRow = (rows: Map) => { + const row: Row = { + id: 'seed_rt', type: 'view', name: RT_OBJ, organization_id: null, + package_id: null, state: 'active', metadata: JSON.stringify(rtContainer({})), + }; + rows.set(keyOf(row), row); +}; describe('[#23198] after every write the registry holds the expansion set the stored container row implies', () => { it('a republish that adds a member serves it on every door', async () => { @@ -571,7 +582,8 @@ describe('[#23198] after every write the registry holds the expansion set the st }); it('a delete of a container no package ships retires the set its last publish registered', async () => { - const { protocol, registry } = boot(); + const { protocol, registry, rows } = boot(); + seedLooseRtRow(rows); const OPEN = `${RT_OBJ}.open`; const CLOSED = `${RT_OBJ}.closed`; const RT_DEFAULT = `${RT_OBJ}.default`; @@ -655,6 +667,7 @@ const RT_CLOSED = `${RT_OBJ}.closed`; describe('[#23198] a rebind moves the row\'s record of its expansions to the new binding', () => { it("the rebind moves the row's record: a package-less row of that name, written later, heals only what it registered", async () => { const { protocol, registry, rows } = boot(); + seedLooseRtRow(rows); expect(await protocol.saveMetaItem({ type: 'view', name: RT_OBJ, item: rtContainer({ open: rtMember('Open'), closed: rtMember('Closed') }), })).toMatchObject({ success: true }); diff --git a/packages/metadata-protocol/src/sys-metadata-repository.package-writability.test.ts b/packages/metadata-protocol/src/sys-metadata-repository.package-writability.test.ts index 642a61587ee..87e753f1cfb 100644 --- a/packages/metadata-protocol/src/sys-metadata-repository.package-writability.test.ts +++ b/packages/metadata-protocol/src/sys-metadata-repository.package-writability.test.ts @@ -1203,13 +1203,13 @@ describe('#8361 — the create-side hatch clause reaches saveMetaItem', () => { ); }, 30_000); - it('a package-less runtime-only create still lands, bound to NO package', async () => { - // The other admitted direction: D1's `packageId != null` limb is untouched. + it('a package-less runtime-only create is refused, and nothing is stored', async () => { + // [#38174] a package-less create is refused (ADR-0070 D1) openHatch('permission'); const { engine, protocol } = boot(); - expect(await createPermission(protocol)).toBeNull(); - expect(metaRowsOf(engine)).toContainEqual( - expect.objectContaining({ name: 'runtime_reviewer', package_id: null }), + expect(await createPermission(protocol)).toMatchObject({ code: 'WRITABLE_PACKAGE_REQUIRED', status: 422 }); + expect(metaRowsOf(engine)).not.toContainEqual( + expect.objectContaining({ name: 'runtime_reviewer' }), ); }, 30_000); diff --git a/packages/metadata-protocol/src/view-container-runtime-expansion.test.ts b/packages/metadata-protocol/src/view-container-runtime-expansion.test.ts index f90c0b256a6..29bafa9813a 100644 --- a/packages/metadata-protocol/src/view-container-runtime-expansion.test.ts +++ b/packages/metadata-protocol/src/view-container-runtime-expansion.test.ts @@ -136,6 +136,24 @@ async function plantEnvRow(engine: any, name: string, item: unknown): Promise<{ return { success: true }; } +/** + * [#38174] A package-less CREATE is refused (ADR-0070 D1). A case whose subject + * is a package-less, environment-wide save seeds the loose row first, directly + * through the engine with the system context (no `organization_id`, as this + * double's store writes none), so the save runs in place over it. The + * placeholder body is what that save replaces; a name already stored is left + * as it is. + */ +async function seedLooseRow(engine: any, name: string, type = 'view'): Promise { + if ((await engine.find('sys_metadata', { where: { type, name } })).length > 0) return; + await engine.insert('sys_metadata', { + type, name, package_id: null, state: 'active', metadata: JSON.stringify({ name }), + }, { context: { isSystem: true } }); +} + +/** The engine a protocol under test writes through. */ +const engineOf = (protocol: unknown): unknown => (protocol as { engine: unknown }).engine; + /** The card's repro body: a `defineView` container, as `defineView` emits it. */ const leadContainer = { list: { @@ -163,6 +181,7 @@ describe('#7736 a runtime-authored view container is served', () => { const { engine } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseRow(engine, 'crm_lead'); await protocol.saveMetaItem({ type: 'view', name: 'crm_lead', item: leadContainer }); const list: any = await protocol.getMetaItems({ type: 'view' }); @@ -180,6 +199,7 @@ describe('#7736 a runtime-authored view container is served', () => { const { engine } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseRow(engine, 'crm_lead'); await protocol.saveMetaItem({ type: 'view', name: 'crm_lead', item: leadContainer }); const list: any = await protocol.getMetaItems({ type: 'view' }); const byName = Object.fromEntries(list.items.map((v: any) => [v.name, v])); @@ -196,6 +216,7 @@ describe('#7736 a runtime-authored view container is served', () => { const { engine } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseRow(engine, 'crm_lead'); await protocol.saveMetaItem({ type: 'view', name: 'crm_lead', item: leadContainer }); const list: any = await protocol.getMetaItems({ type: 'view' }); @@ -220,6 +241,7 @@ describe('#7736 a runtime-authored view container is served', () => { // A container authored for crm_lead must not make crm_account — // an object nobody authored a view for — start answering non-empty. + await seedLooseRow(engine, 'crm_lead'); await protocol.saveMetaItem({ type: 'view', name: 'crm_lead', item: leadContainer }); const list: any = await protocol.getMetaItems({ type: 'view' }); @@ -251,6 +273,7 @@ describe('#7736 a runtime-authored view container is served', () => { name: 'crm_lead.mine', object: 'crm_lead', viewKind: 'list', label: 'My Leads', config: { type: 'grid', data: { provider: 'object', object: 'crm_lead' }, columns: [{ field: 'name' }] }, }; + await seedLooseRow(engine, 'crm_lead.mine'); await protocol.saveMetaItem({ type: 'view', name: 'crm_lead.mine', item: record }); const list: any = await protocol.getMetaItems({ type: 'view' }); @@ -268,6 +291,7 @@ describe('#7736 a runtime-authored view container is served', () => { // OWD-less custom object once #8310 declares `object` in // `runtimeTypes`; this case pins byte-identical storage, not that. const authored = { name: 'crm_invoice', label: 'Invoice', sharingModel: 'private', fields: { amount: { type: 'currency', label: 'Amount' } } }; + await seedLooseRow(engine, 'crm_invoice', 'object'); await protocol.saveMetaItem({ type: 'object', name: 'crm_invoice', item: authored }); const stored = Array.from(rows.values()).find((r) => r.name === 'crm_invoice')!; @@ -278,6 +302,7 @@ describe('#7736 a runtime-authored view container is served', () => { const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseRow(engine, 'crm_lead'); await protocol.saveMetaItem({ type: 'view', name: 'crm_lead', item: leadContainer }); // Exactly ONE row: the container as authored (plus the `name` the @@ -327,6 +352,7 @@ describe('#13407 environment-scoped runtime containers are served', () => { object: 'crm_lead', list: { label: 'All Leads', type: 'grid', columns: [{ field: 'name' }] }, }; + await seedLooseRow(engine, 'lead_views'); await protocol.saveMetaItem({ type: 'view', name: 'lead_views', item: bound }); const list: any = await protocol.getMetaItems({ type: 'view' }); @@ -381,6 +407,7 @@ describe('#13407 environment-scoped runtime containers are served', () => { // constructs the OTHER real shape. const protocol = new ObjectStackProtocolImplementation(engine, undefined, 'env_prod_1'); + await seedLooseRow(engine, 'crm_lead'); await protocol.saveMetaItem({ type: 'view', name: 'crm_lead', item: leadContainer }); const list: any = await protocol.getMetaItems({ type: 'view' }); const served = switcherMatches(list.items, 'crm_lead').map((v: any) => v.name).sort(); @@ -741,10 +768,14 @@ describe('#21334 a container on another package\'s object never takes that packa * row it can only be on protocol 19 ({@link seedStoredContainer}). */ const save = async ( - harness: { protocol: Protocol; rows: Map }, name: string, item: Record, + harness: { protocol: Protocol; rows: Map; engine: unknown }, name: string, item: Record, c: (typeof CONTAINERS)[number], ) => { - if (!holdsForm(item)) return saveThroughTheDoor(harness.protocol, name, item, c); + if (!holdsForm(item)) { + // [#38174] The package-less arm saves in place over its loose row. + if (!c.packageId) await seedLooseRow(harness.engine, name); + return saveThroughTheDoor(harness.protocol, name, item, c); + } await expectFormMemberRefused(harness, name, item, c); seedStoredContainer(harness.rows, name, item, c); return { success: true }; @@ -1503,6 +1534,11 @@ describe('#21334 a container on another package\'s object never takes that packa protocol: Protocol, name: string, item: unknown, organizationId?: string, mode?: 'draft' | 'publish', ) => protocol.saveMetaItem({ type: 'view', name, item, ...scoped(organizationId), ...(mode ? { mode } : {}) } as any); const saved = async (write: Promise) => expect(((await write) as any)?.success).toBe(true); + /** [#38174] An accepted environment-wide save, in place over its seeded loose row. */ + const savedLoose = async (protocol: Protocol, name: string, item: unknown, organizationId?: string) => { + await seedLooseRow(engineOf(protocol), name); + await saved(saveIn(protocol, name, item, organizationId)); + }; const refusalOf = (write: Promise) => write.then(() => null, (e: any) => e); const leadDoor = async (protocol: Protocol, organizationId?: string) => switcherMatches(((await protocol.getMetaItems({ type: 'view', ...scoped(organizationId) } as any)) as any).items, LEAD); @@ -1560,7 +1596,7 @@ describe('#21334 a container on another package\'s object never takes that packa await expectFormMemberRefused(harness, FIRST, firstBody, { packageId: undefined }); seedStoredContainer(rows, FIRST, firstBody, { packageId: undefined }); } else { - await saved(saveIn(protocol, FIRST, firstBody, organizationId)); + await savedLoose(protocol, FIRST, firstBody, organizationId); } expectRefused(await refusalOf(saveIn(protocol, name, secondKeyed(name), organizationId)), name, FIRST); @@ -1585,7 +1621,7 @@ describe('#21334 a container on another package\'s object never takes that packa it(`${scope}: the card's save — '${LEAD}' stored with listViews.pipeline, then a second container saved as ${LEAD}.pipeline — is refused in publish and draft mode, with or without a body \`name\``, async () => { const { protocol, rows, registry } = showcaseHarness(environmentId); const first = { name: LEAD, object: LEAD, list: leadList('All Leads'), listViews: { pipeline: leadList('Lead Pipeline') } }; - await saved(saveIn(protocol, LEAD, first, organizationId)); + await savedLoose(protocol, LEAD, first, organizationId); const PIPELINE = `${LEAD}.pipeline`; expectRefused(await refusalOf(saveIn(protocol, PIPELINE, second(PIPELINE), organizationId)), PIPELINE, LEAD); @@ -1623,11 +1659,11 @@ describe('#21334 a container on another package\'s object never takes that packa it(`${scope}: CONTROL — a container under its object's name saves and expands as before, beside a sibling, and re-saves`, async () => { const { protocol } = showcaseHarness(environmentId); - await saved(saveIn(protocol, 'lead_hot_views', { name: 'lead_hot_views', object: LEAD, listViews: { hot: leadList('Hot Leads') } }, organizationId)); + await savedLoose(protocol, 'lead_hot_views', { name: 'lead_hot_views', object: LEAD, listViews: { hot: leadList('Hot Leads') } }, organizationId); const own = { name: LEAD, object: LEAD, list: leadList('All Leads'), listViews: { pipeline: leadList('Lead Pipeline') } }; - await saved(saveIn(protocol, LEAD, own, organizationId)); + await savedLoose(protocol, LEAD, own, organizationId); // Its own row is the row a re-save replaces, never a sibling. - await saved(saveIn(protocol, LEAD, { ...own, list: leadList('All Leads, edited') }, organizationId)); + await savedLoose(protocol, LEAD, { ...own, list: leadList('All Leads, edited') }, organizationId); await expectServed(protocol, `${LEAD}.default`, organizationId, 'All Leads, edited'); await expectServed(protocol, `${LEAD}.pipeline`, organizationId, 'Lead Pipeline'); await expectServed(protocol, `${LEAD}.hot`, organizationId, 'Hot Leads'); @@ -1635,17 +1671,17 @@ describe('#21334 a container on another package\'s object never takes that packa it(`${scope}: CONTROL — a view item saved under a sibling's expanded name saves, as that name's sanctioned override`, async () => { const { protocol } = showcaseHarness(environmentId); - await saved(saveIn(protocol, LEAD, { name: LEAD, object: LEAD, listViews: { pipeline: leadList('Lead Pipeline') } }, organizationId)); + await savedLoose(protocol, LEAD, { name: LEAD, object: LEAD, listViews: { pipeline: leadList('Lead Pipeline') } }, organizationId); const PIPELINE = `${LEAD}.pipeline`; const item = { name: PIPELINE, object: LEAD, viewKind: 'list', label: 'ByNameRow', config: { type: 'grid', data: leadData, columns: [{ field: 'name' }] } }; - await saved(saveIn(protocol, PIPELINE, item, organizationId)); + await savedLoose(protocol, PIPELINE, item, organizationId); await expectServed(protocol, PIPELINE, organizationId, 'ByNameRow'); }); it(`${scope}: CONTROL (the census) — a container saved under a name of its own, neither its object's nor a sibling's expansion, still saves and serves`, async () => { const { protocol } = showcaseHarness(environmentId); - await saved(saveIn(protocol, LEAD, { name: LEAD, object: LEAD, list: leadList('All Leads'), listViews: { pipeline: leadList('Lead Pipeline') } }, organizationId)); - await saved(saveIn(protocol, 'lead_hot_views', { object: LEAD, listViews: { hot: leadList('Hot Leads') } }, organizationId)); + await savedLoose(protocol, LEAD, { name: LEAD, object: LEAD, list: leadList('All Leads'), listViews: { pipeline: leadList('Lead Pipeline') } }, organizationId); + await savedLoose(protocol, 'lead_hot_views', { object: LEAD, listViews: { hot: leadList('Hot Leads') } }, organizationId); await expectServed(protocol, `${LEAD}.hot`, organizationId, 'Hot Leads'); await expectServed(protocol, `${LEAD}.pipeline`, organizationId, 'Lead Pipeline'); }); @@ -1653,7 +1689,7 @@ describe('#21334 a container on another package\'s object never takes that packa it('the prescription names the sibling container that expands the name and never prescribes a save under it — in the card\'s pair the object\'s own name IS that sibling', async () => { const { protocol, rows, registry } = showcaseHarness(environmentId); - await saved(saveIn(protocol, LEAD, { name: LEAD, object: LEAD, listViews: { pipeline: leadList('Lead Pipeline') } })); + await savedLoose(protocol, LEAD, { name: LEAD, object: LEAD, listViews: { pipeline: leadList('Lead Pipeline') } }); const PIPELINE = `${LEAD}.pipeline`; const error = await refusalOf(saveIn(protocol, PIPELINE, second(PIPELINE))); // The envelope, and the sibling named as the container that expands the name. @@ -1977,6 +2013,11 @@ describe('#21334 a container on another package\'s object never takes that packa ...(mode ? { mode } : {}), } as any); }; + /** [#38174] An accepted write: one naming no package runs in place over its seeded loose row. */ + const writeLoose = async (protocol: Protocol, write: Write, callerOrganizationId: string | undefined) => { + if (!write.packageId) await seedLooseRow(engineOf(protocol), write.name); + return writeIn(protocol, write, callerOrganizationId); + }; const refusalOf = (write: Promise) => write.then(() => null, (e: any) => e); const viewRowsOf = (rows: Map) => [...rows.values()].filter((r) => r.type === 'view').map((r) => [r.name, r.state, r.metadata]).sort(); @@ -2003,10 +2044,10 @@ describe('#21334 a container on another package\'s object never takes that packa it(`${scope}: ${row.shape} — ${row.refused ? 'REFUSED' : 'ALLOWED'}`, async () => { const { protocol, rows, registry } = collisionHarness(environmentId); for (const given of row.given ?? []) { - expect(((await writeIn(protocol, given, organizationId)) as any)?.success, `${given.name} is stored first`).toBe(true); + expect(((await writeLoose(protocol, given, organizationId)) as any)?.success, `${given.name} is stored first`).toBe(true); } if (row.allowed) { - expect(((await writeIn(protocol, row.save, organizationId)) as any)?.success, 'the save is accepted').toBe(true); + expect(((await writeLoose(protocol, row.save, organizationId)) as any)?.success, 'the save is accepted').toBe(true); for (const served of row.allowed.serves) await expectServed(protocol, served, organizationId); return; } @@ -2157,9 +2198,11 @@ describe('#21334 a container on another package\'s object never takes that packa * too, and a container under its object's name still saves. */ describe('#21558 a container under its own expanded name, on a runtime-authored object', () => { - async function saveCrm(name: string, item: unknown) { + async function saveCrm(name: string, item: unknown, seedLoose = false) { const harness = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(harness.engine); + // [#38174] An accepted package-less save runs in place over its loose row. + if (seedLoose) await seedLooseRow(harness.engine, name); const error = await protocol.saveMetaItem({ type: 'view', name, item }).then(() => null, (e: any) => e); const viewRows = Array.from(harness.rows.values()).filter((r) => r.type === 'view'); return { ...harness, protocol, error, viewRows }; @@ -2193,7 +2236,7 @@ describe('#21558 a container under its own expanded name, on a runtime-authored }); it('CONTROL: the same container under its object\'s name saves, and its expansion fills crm_lead.default', async () => { - const { error, protocol } = await saveCrm('crm_lead', { name: 'crm_lead', object: 'crm_lead', list }); + const { error, protocol } = await saveCrm('crm_lead', { name: 'crm_lead', object: 'crm_lead', list }, true); expect(error).toBeNull(); const listed: any = await protocol.getMetaItems({ type: 'view' }); expect(switcherMatches(listed.items, 'crm_lead').map((v: any) => [v.name, v.label])).toEqual([['crm_lead.default', 'All Leads']]); @@ -2227,9 +2270,11 @@ describe('#21412 the save door refuses a container whose own name disagrees with /** No binding but whatever `name` it carries. */ const unbound = { list: { label: 'All', type: 'grid', columns: [{ field: 'name' }] } }; - async function save(name: string, item: unknown) { + async function save(name: string, item: unknown, seedLoose = false) { const harness = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(harness.engine); + // [#38174] An accepted package-less save runs in place over its loose row. + if (seedLoose) await seedLooseRow(harness.engine, name); let error: any = null; try { await protocol.saveMetaItem({ type: 'view', name, item }); @@ -2292,7 +2337,7 @@ describe('#21412 the save door refuses a container whose own name disagrees with }); it('P2: a `name` equal to the row passes though the container binds elsewhere — one key, the row\'s', async () => { - const outcome = await save('lead_views', named('lead_views', objectBound)); + const outcome = await save('lead_views', named('lead_views', objectBound), true); expect(outcome.error).toBeNull(); expect(outcome.viewRows.map((r) => [r.name, JSON.parse(r.metadata).name])).toEqual([['lead_views', 'lead_views']]); expect(outcome.containerKeys).toEqual(['lead_views']); @@ -2301,7 +2346,7 @@ describe('#21412 the save door refuses a container whose own name disagrees with }); it('P2b: an absent `name` passes and is stamped with the row name — and the stamped body passes when sent back', async () => { - const outcome = await save('lead_views', named(undefined, objectBound)); + const outcome = await save('lead_views', named(undefined, objectBound), true); expect(outcome.error).toBeNull(); expect(outcome.viewRows.map((r) => JSON.parse(r.metadata).name)).toEqual(['lead_views']); expect(outcome.containerKeys).toEqual(['lead_views']); @@ -2313,7 +2358,7 @@ describe('#21412 the save door refuses a container whose own name disagrees with }); it('CONTROL: a `name` equal to the row and the binding passes, under one key', async () => { - const outcome = await save('crm_lead', named('crm_lead', leadContainer)); + const outcome = await save('crm_lead', named('crm_lead', leadContainer), true); expect(outcome.error).toBeNull(); expect(outcome.containerKeys).toEqual(['crm_lead']); }); diff --git a/packages/objectql/src/bound-action-foreign-object.test.ts b/packages/objectql/src/bound-action-foreign-object.test.ts index 98eada08b5b..829cabd5190 100644 --- a/packages/objectql/src/bound-action-foreign-object.test.ts +++ b/packages/objectql/src/bound-action-foreign-object.test.ts @@ -180,6 +180,10 @@ const CONTROL = { const actionNames = (body: any): string[] => (Array.isArray(body?.actions) ? body.actions.map((a: any) => a?.name) : []); async function hostWith(packages: any[]) { + return hostWithPackages(packages); +} + +async function hostWithPackages(packages: any[]) { const engine = new ObjectQL(); engine.registerDriver(makeStubDriver().driver, true); await engine.init(); @@ -438,8 +442,17 @@ describe('a bound action saved at runtime through the metadata door reaches its name: 'rt_action', label: 'Runtime', objectName: 'ba_org', type: 'url', target: 'https://example.com/rt', locations: ['record_page'], }; + // [#38174] a package-less create is refused (ADR-0070 D1): the runtime + // action is authored into a writable, installed package that depends on + // the owner of its object. + const PKG = 'test_pkg'; + const hostWith = async (packages: any[]) => { + const host = await hostWithPackages(packages); + host.engine.registry.installPackage({ id: PKG, name: PKG, version: '1.0.0', dependencies: { [OWNER.id]: '^1.0.0' } } as any, 'authored'); + return host; + }; const save = (protocol: ObjectStackProtocolImplementation, item: any, extra: Record = {}) => - protocol.saveMetaItem({ type: 'action', name: item.name, item: structuredClone(item), ...extra } as any); + protocol.saveMetaItem({ type: 'action', name: item.name, item: structuredClone(item), packageId: PKG, ...extra } as any); const listedActions = async (protocol: ObjectStackProtocolImplementation, name: string): Promise => { const listed: any = await protocol.getMetaItems({ type: 'object' } as any); const items: any[] = Array.isArray(listed) ? listed : listed?.items ?? []; @@ -476,7 +489,7 @@ describe('a bound action saved at runtime through the metadata door reaches its const resaved: any = engine.registry.getObject('ba_org')?.actions?.find((a: any) => a.name === 'rt_action'); expect(resaved?.label).toBe('Runtime v2'); - const deleted: any = await protocol.deleteMetaItem({ type: 'action', name: 'rt_action' } as any); + const deleted: any = await protocol.deleteMetaItem({ type: 'action', name: 'rt_action', packageId: PKG } as any); expect(deleted).toMatchObject({ success: true }); expect(engine.registry.getItem('action', 'rt_action')).toBeUndefined(); expect(actionNames(engine.registry.getObject('ba_org'))).toEqual(['own_action']); diff --git a/packages/objectql/src/default-record-page-save-door.test.ts b/packages/objectql/src/default-record-page-save-door.test.ts index f8045f41a24..bb66f54db8f 100644 --- a/packages/objectql/src/default-record-page-save-door.test.ts +++ b/packages/objectql/src/default-record-page-save-door.test.ts @@ -28,6 +28,12 @@ import { SysMetadataAuditObject, SysMetadataCommitObject, SysMetadataHistoryObje import { ObjectQL } from './engine.js'; const PKG = 'com.acme.auth'; +/** + * [#38174] A package-less create is refused (ADR-0070 D1): a NEW page a control + * saves is authored into this writable, installed package; a page the + * environment "already stored" (no package) is laid in the store directly. + */ +const ENV_PKG = 'env_pkg'; /** A record page; `object` and `isDefault` are what a case varies. */ const recordPage = (name: string, object: string, isDefault = true, extra: Record = {}) => ({ @@ -159,6 +165,7 @@ async function boot(topology: Topology) { engine.registry.registerObject(o as any, 'test-package'); } engine.registerApp({ id: PKG, name: 'auth', pages: [recordPage('acme_org_detail', 'acme_org')] }); + engine.registry.installPackage({ id: ENV_PKG, name: ENV_PKG, version: '1.0.0' } as any, 'authored'); const protocol = new ObjectStackProtocolImplementation( engine, () => new Map(), @@ -169,8 +176,8 @@ async function boot(topology: Topology) { .filter((r: any) => r.type === 'page') .map((r: any) => r.name) .sort(); - const save = (name: string, item: Record) => - protocol.saveMetaItem({ type: 'page', name, item }).then( + const save = (name: string, item: Record, packageId?: string) => + protocol.saveMetaItem({ type: 'page', name, item, ...(packageId ? { packageId } : {}) }).then( (result: any) => ({ ok: true as const, result }), (error: any) => ({ ok: false as const, error }), ); @@ -208,8 +215,8 @@ describe.each(TOPOLOGIES)('%s kernel — a page saved as a second default record }); it('is refused over a page the environment already stored, naming it', async () => { - const { save, storedPages } = await boot(topology); - expect((await save('env_task_a', recordPage('env_task_a', 'acme_task'))).ok).toBe(true); + const { save, storedPages, storeRow } = await boot(topology); + await storeRow('env_task_a', recordPage('env_task_a', 'acme_task')); const outcome = await save('env_task_b', recordPage('env_task_b', 'acme_task')); expectRefusal(outcome, 'env_task_b', 'acme_task', "page 'env_task_a', authored in this system"); expect(String((outcome as { error?: any }).error?.message)).toContain( @@ -220,13 +227,13 @@ describe.each(TOPOLOGIES)('%s kernel — a page saved as a second default record }); it('a draft is judged again when it is published: another page took the default in between', async () => { - const { protocol, save } = await boot(topology); + const { protocol, storeRow } = await boot(topology); const draft = await protocol - .saveMetaItem({ type: 'page', name: 'env_task_a', item: recordPage('env_task_a', 'acme_task'), mode: 'draft' }) + .saveMetaItem({ type: 'page', name: 'env_task_a', item: recordPage('env_task_a', 'acme_task'), mode: 'draft', packageId: ENV_PKG }) .then(() => true, (e: any) => e); expect(draft, String(draft?.message)).toBe(true); - expect((await save('env_task_b', recordPage('env_task_b', 'acme_task'))).ok).toBe(true); - const published = await protocol.publishMetaItem({ type: 'page', name: 'env_task_a' }).then( + await storeRow('env_task_b', recordPage('env_task_b', 'acme_task')); + const published = await protocol.publishMetaItem({ type: 'page', name: 'env_task_a', packageId: ENV_PKG }).then( (result: any) => ({ ok: true as const, result }), (error: any) => ({ ok: false as const, error }), ); @@ -248,8 +255,8 @@ describe.each(TOPOLOGIES)('%s kernel — a page saved as a second default record // ── controls ───────────────────────────────────────────────────────── it('control: a save under the existing default\'s own name (an overlay by name) stays accepted', async () => { - const { save, storedPages } = await boot(topology); - expect((await save('env_task_a', recordPage('env_task_a', 'acme_task'))).ok).toBe(true); + const { save, storedPages, storeRow } = await boot(topology); + await storeRow('env_task_a', recordPage('env_task_a', 'acme_task')); const again = await save('env_task_a', recordPage('env_task_a', 'acme_task', true, { label: 'Renamed' })); expect(again.ok, String((again as any).error?.message)).toBe(true); expect(storedPages()).toEqual(['env_task_a']); @@ -264,14 +271,14 @@ describe.each(TOPOLOGIES)('%s kernel — a page saved as a second default record it('control: a non-default record page for the object saves', async () => { const { save, storedPages } = await boot(topology); - const outcome = await save('env_org_detail', recordPage('env_org_detail', 'acme_org', false)); + const outcome = await save('env_org_detail', recordPage('env_org_detail', 'acme_org', false), ENV_PKG); expect(outcome.ok, String((outcome as any).error?.message)).toBe(true); expect(storedPages()).toEqual(['env_org_detail']); }); it('control: a default record page for another object saves', async () => { const { save } = await boot(topology); - const outcome = await save('env_env_detail', recordPage('env_env_detail', 'acme_env')); + const outcome = await save('env_env_detail', recordPage('env_env_detail', 'acme_env'), ENV_PKG); expect(outcome.ok, String((outcome as any).error?.message)).toBe(true); }); @@ -287,15 +294,15 @@ describe.each(TOPOLOGIES)('%s kernel — a page saved as a second default record it('control: the same home page without the flag saves', async () => { const { save } = await boot(topology); - const outcome = await save('env_home', { name: 'env_home', label: 'Home', type: 'home', regions: [] }); + const outcome = await save('env_home', { name: 'env_home', label: 'Home', type: 'home', regions: [] }, ENV_PKG); expect(outcome.ok, String((outcome as any).error?.message)).toBe(true); }); it('control: demote the stored default, then the new page may be the default', async () => { - const { save, storedPages } = await boot(topology); - expect((await save('env_task_a', recordPage('env_task_a', 'acme_task'))).ok).toBe(true); + const { save, storedPages, storeRow } = await boot(topology); + await storeRow('env_task_a', recordPage('env_task_a', 'acme_task')); expect((await save('env_task_a', recordPage('env_task_a', 'acme_task', false))).ok).toBe(true); - const promoted = await save('env_task_b', recordPage('env_task_b', 'acme_task')); + const promoted = await save('env_task_b', recordPage('env_task_b', 'acme_task'), ENV_PKG); expect(promoted.ok, String((promoted as any).error?.message)).toBe(true); expect(storedPages()).toEqual(['env_task_a', 'env_task_b']); }); @@ -381,8 +388,8 @@ describe.each(TOPOLOGIES)('%s kernel — a page saved as a second record page of }); it('is refused over a page the environment already stored for that app, naming it', async () => { - const { save, storedPages } = await boot(topology); - expect((await save('env_member_a', scopedPage('env_member_a', 'acme_task', ['duly']))).ok).toBe(true); + const { save, storedPages, storeRow } = await boot(topology); + await storeRow('env_member_a', scopedPage('env_member_a', 'acme_task', ['duly'])); const outcome = await save('env_member_b', scopedPage('env_member_b', 'acme_task', ['crm', 'duly'])); expectAppRefusal(outcome, 'env_member_b', 'acme_task', 'duly', "page 'env_member_a', authored in this system"); expect(storedPages()).toEqual(['env_member_a']); @@ -391,20 +398,20 @@ describe.each(TOPOLOGIES)('%s kernel — a page saved as a second record page of it('control: the same page scoped to another app is accepted', async () => { const { engine, save, storedPages } = await boot(topology); engine.registerApp({ id: DULY, name: 'duly', pages: [scopedPage('duly_member', 'sys_user', ['duly'])] }); - const outcome = await save('env_member', scopedPage('env_member', 'sys_user', ['crm'])); + const outcome = await save('env_member', scopedPage('env_member', 'sys_user', ['crm']), ENV_PKG); expect(outcome.ok, String((outcome as any).error?.message)).toBe(true); expect(storedPages()).toEqual(['env_member']); }); it('control: an app\'s page is saved beside the package\'s default for the same object — two slots', async () => { const { save } = await boot(topology); - const outcome = await save('env_org_member', scopedPage('env_org_member', 'acme_org', ['duly'])); + const outcome = await save('env_org_member', scopedPage('env_org_member', 'acme_org', ['duly']), ENV_PKG); expect(outcome.ok, String((outcome as any).error?.message)).toBe(true); }); it('control: a save under the app page\'s own name (an overlay by name) stays accepted', async () => { - const { save } = await boot(topology); - expect((await save('env_member_a', scopedPage('env_member_a', 'acme_task', ['duly']))).ok).toBe(true); + const { save, storeRow } = await boot(topology); + await storeRow('env_member_a', scopedPage('env_member_a', 'acme_task', ['duly'])); const again = await save('env_member_a', scopedPage('env_member_a', 'acme_task', ['duly'], { label: 'Renamed' })); expect(again.ok, String((again as any).error?.message)).toBe(true); }); diff --git a/packages/objectql/src/delete-meta-response-conformance.test.ts b/packages/objectql/src/delete-meta-response-conformance.test.ts index 4501419e7ce..64b346dabe4 100644 --- a/packages/objectql/src/delete-meta-response-conformance.test.ts +++ b/packages/objectql/src/delete-meta-response-conformance.test.ts @@ -160,9 +160,13 @@ async function makeProtocol() { await engine.init(); engine.registry.registerObject(sysMetadataObject, 'test-package'); for (const o of [SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) engine.registry.registerObject(o as any, 'test-package'); + engine.registry.installPackage({ id: PKG, name: PKG, version: '1.0.0' } as any, 'authored'); return { p: new ObjectStackProtocolImplementation(engine), stores }; } +/** [#38174] A package-less create is refused (ADR-0070 D1): the view is saved into this writable package. */ +const PKG = 'test_pkg'; + // [#7741] the inline arm requires the object binding pair // [#24668] Bound to `sys_metadata`, an object this harness registers: the overlay save door refuses a list view bound to an object that exists nowhere (it read `case`). const viewBody = (label: string) => ({ @@ -179,11 +183,11 @@ describe('deleteMetaItem response conforms to DeleteMetaItemResponseSchema (#131 it('repository path, row deleted: parses green, strips nothing, and carries seq', async () => { const { p } = await makeProtocol(); await (p as any).saveMetaItem({ - type: 'view', name: 'cases', item: viewBody('A'), + type: 'view', name: 'cases', packageId: PKG, item: viewBody('A'), }); const raw: any = await (p as any).deleteMetaItem({ - type: 'view', name: 'cases', + type: 'view', name: 'cases', packageId: PKG, }); // The assertion that was red before the declaration: `seq` rode the @@ -204,14 +208,14 @@ describe('deleteMetaItem response conforms to DeleteMetaItemResponseSchema (#131 it('with an ADR-0094 projector registered: projectionApplied is carried through', async () => { const { p } = await makeProtocol(); await (p as any).saveMetaItem({ - type: 'view', name: 'cases', item: viewBody('P'), + type: 'view', name: 'cases', packageId: PKG, item: viewBody('P'), }); // Registered AFTER the save so the save's own projection is not what // this case reads — the delete's is. (p as any).registerMutationProjector('view', async () => { throw new Error('boom-from-projector'); }); const raw: any = await (p as any).deleteMetaItem({ - type: 'view', name: 'cases', + type: 'view', name: 'cases', packageId: PKG, }); expect(Object.keys(raw)).toContain('projectionApplied'); @@ -228,11 +232,11 @@ describe('deleteMetaItem response conforms to DeleteMetaItemResponseSchema (#131 it('no projector registered → projectionApplied is absent, which is why it is optional', async () => { const { p } = await makeProtocol(); await (p as any).saveMetaItem({ - type: 'view', name: 'cases', item: viewBody('N'), + type: 'view', name: 'cases', packageId: PKG, item: viewBody('N'), }); const raw: any = await (p as any).deleteMetaItem({ - type: 'view', name: 'cases', + type: 'view', name: 'cases', packageId: PKG, }); expect(raw.projectionApplied).toBeUndefined(); @@ -262,10 +266,10 @@ describe('deleteMetaItem response conforms to DeleteMetaItemResponseSchema (#131 it('seq really is the history event sequence: it advances across the item\'s writes', async () => { const { p } = await makeProtocol(); const saved: any = await (p as any).saveMetaItem({ - type: 'view', name: 'cases', item: viewBody('S'), + type: 'view', name: 'cases', packageId: PKG, item: viewBody('S'), }); const raw: any = await (p as any).deleteMetaItem({ - type: 'view', name: 'cases', + type: 'view', name: 'cases', packageId: PKG, }); // The delete's tombstone event comes after the save's write event on diff --git a/packages/objectql/src/engine-security-catalog-package-door.test.ts b/packages/objectql/src/engine-security-catalog-package-door.test.ts index 89c93c2f799..1a4eafd19a2 100644 --- a/packages/objectql/src/engine-security-catalog-package-door.test.ts +++ b/packages/objectql/src/engine-security-catalog-package-door.test.ts @@ -264,10 +264,13 @@ describe('[#22203] security-domain allowEnvironmentOverlay:false — the package // ── controls ───────────────────────────────────────────────────────── it.each(TOPOLOGIES)('%s: a position no package declares still saves (the allowRuntimeCreate tier)', async (topology) => { - const { protocol, storedRows } = await boot(topology); + const { engine, protocol, storedRows } = await boot(topology); + // [#38174] a package-less create is refused (ADR-0070 D1): the new + // position is saved into a writable, installed package. + engine.registry.installPackage({ id: 'env_pkg', name: 'env_pkg', version: '1.0.0' } as any, 'authored'); const result: any = await protocol.saveMetaItem({ - type: 'position', name: 'env_only_position', item: { name: 'env_only_position', label: 'Env only' }, + type: 'position', name: 'env_only_position', packageId: 'env_pkg', item: { name: 'env_only_position', label: 'Env only' }, }); expect(result?.success).toBe(true); diff --git a/packages/objectql/src/manifest-service-residual-security-seal.test.ts b/packages/objectql/src/manifest-service-residual-security-seal.test.ts index acb62124a9f..87ba9fa2df6 100644 --- a/packages/objectql/src/manifest-service-residual-security-seal.test.ts +++ b/packages/objectql/src/manifest-service-residual-security-seal.test.ts @@ -231,9 +231,12 @@ describe('[ADR-0130 D4, ADR-0131 D6] a residual top-level security rule is seale }); it('CONTROL: a position the stack does not declare still saves (the allowRuntimeCreate tier)', async () => { - const { protocol, storedRows } = await boot(['position']); + const { engine, protocol, storedRows } = await boot(['position']); + // [#38174] a package-less create is refused (ADR-0070 D1): the new + // position is saved into a writable, installed package. + engine.registry.installPackage({ id: 'env_pkg', name: 'env_pkg', version: '1.0.0' } as any, 'authored'); const result: any = await protocol.saveMetaItem({ - type: 'position', name: 'env_only_position', item: { name: 'env_only_position', label: 'Env only' }, + type: 'position', name: 'env_only_position', packageId: 'env_pkg', item: { name: 'env_only_position', label: 'Env only' }, }); expect(result?.success).toBe(true); expect(storedRows().map((r: any) => `${r.type}/${r.name}`)).toEqual(['position/env_only_position']); diff --git a/packages/objectql/src/meta-object-primary-designation-roundtrip.test.ts b/packages/objectql/src/meta-object-primary-designation-roundtrip.test.ts index fee77785dbf..18f03c485ce 100644 --- a/packages/objectql/src/meta-object-primary-designation-roundtrip.test.ts +++ b/packages/objectql/src/meta-object-primary-designation-roundtrip.test.ts @@ -108,10 +108,15 @@ function keyOf(w: Record) { } /** A `sys_metadata` store over a REAL {@link SchemaRegistry}. */ +const SEED_PKG = 'seed_pkg'; + function makeHost() { // Companions OFF: this file is about the title designation, and leaving the // other stamp out keeps a failure here unambiguous about which half moved. const registry = new SchemaRegistry({ multiTenant: false, searchCompanion: false } as never); + // [#38174] A package-less create is refused (ADR-0070 D1): the seed saves into + // this writable package; the round-trip saves naming none address its row. + registry.installPackage({ id: SEED_PKG, name: SEED_PKG, version: '1.0.0' } as any, 'authored'); const rows = new Map(); let nextId = 0; const findRow = (w: Record) => { @@ -171,7 +176,7 @@ function makeHost() { async function seed(item: Record = clone(AUTHORED)) { const host = makeHost(); await host.protocol.saveMetaItem({ - type: 'object', name: AUTHORED.name, item, + type: 'object', name: AUTHORED.name, item, packageId: SEED_PKG, } as never); return host; } diff --git a/packages/objectql/src/meta-object-search-companion-roundtrip.test.ts b/packages/objectql/src/meta-object-search-companion-roundtrip.test.ts index 12d7f684563..561e5b7a9b6 100644 --- a/packages/objectql/src/meta-object-search-companion-roundtrip.test.ts +++ b/packages/objectql/src/meta-object-search-companion-roundtrip.test.ts @@ -78,8 +78,13 @@ function keyOf(w: Record) { } /** A `sys_metadata` store over a REAL {@link SchemaRegistry}. */ +const SEED_PKG = 'seed_pkg'; + function makeHost() { const registry = new SchemaRegistry({ multiTenant: false, searchCompanion: true } as never); + // [#38174] A package-less create is refused (ADR-0070 D1): the seed saves into + // this writable package; the round-trip saves naming none address its row. + registry.installPackage({ id: SEED_PKG, name: SEED_PKG, version: '1.0.0' } as any, 'authored'); const rows = new Map(); let nextId = 0; const findRow = (w: Record) => { @@ -138,7 +143,7 @@ function makeHost() { async function seed() { const host = makeHost(); await host.protocol.saveMetaItem({ - type: 'object', name: AUTHORED.name, item: clone(AUTHORED), + type: 'object', name: AUTHORED.name, item: clone(AUTHORED), packageId: SEED_PKG, } as never); return host; } diff --git a/packages/objectql/src/meta-object-tenant-index-roundtrip.test.ts b/packages/objectql/src/meta-object-tenant-index-roundtrip.test.ts index ed5ddbd6ae1..1c696eaa6ea 100644 --- a/packages/objectql/src/meta-object-tenant-index-roundtrip.test.ts +++ b/packages/objectql/src/meta-object-tenant-index-roundtrip.test.ts @@ -98,11 +98,16 @@ function keyOf(w: Record) { } /** A `sys_metadata` store over a REAL {@link SchemaRegistry}. */ +const SEED_PKG = 'seed_pkg'; + function makeHost(multiTenant: boolean) { // Companions OFF: this file is about the tenant index, and leaving the other // stamps' deployment gate out keeps a failure here unambiguous about which // half moved. The title designation still travels — it is not gated. const registry = new SchemaRegistry({ multiTenant, searchCompanion: false } as never); + // [#38174] A package-less create is refused (ADR-0070 D1): the seed saves into + // this writable package; the round-trip saves naming none address its row. + registry.installPackage({ id: SEED_PKG, name: SEED_PKG, version: '1.0.0' } as any, 'authored'); const rows = new Map(); let nextId = 0; const findRow = (w: Record) => { @@ -161,7 +166,7 @@ function makeHost(multiTenant: boolean) { async function seed(multiTenant: boolean, item: Record = clone(AUTHORED)) { const host = makeHost(multiTenant); - await host.protocol.saveMetaItem({ type: 'object', name: AUTHORED.name, item } as never); + await host.protocol.saveMetaItem({ type: 'object', name: AUTHORED.name, item, packageId: SEED_PKG } as never); return host; } diff --git a/packages/objectql/src/metadata-validation-sweep.test.ts b/packages/objectql/src/metadata-validation-sweep.test.ts index bf9498b5eaf..e105c6087f4 100644 --- a/packages/objectql/src/metadata-validation-sweep.test.ts +++ b/packages/objectql/src/metadata-validation-sweep.test.ts @@ -82,6 +82,8 @@ const SWEEP_ACCOUNT_METRICS: any = { measures: [{ name: 'amount_sum', label: 'Amount', aggregate: 'sum', field: 'amount' }], }; +const SWEEP_PKG = 'sweep_pkg'; + function makeProtocol() { const registry = new SchemaRegistry({ multiTenant: false }); // [#19542] The live resolution universe this harness hands the runtime @@ -108,6 +110,9 @@ function makeProtocol() { // an object this tenant does not declare is refused exactly as before. registry.registerObject(structuredClone(SWEEP_ACCOUNT)); registry.registerItem('dataset', structuredClone(SWEEP_ACCOUNT_METRICS)); + // [#38174] A package-less create is refused (ADR-0070 D1) before the body + // is judged: every sweep save names this writable, installed package. + registry.installPackage({ id: SWEEP_PKG, name: SWEEP_PKG, version: '1.0.0' } as any, 'authored'); const mockEngine: any = { registry, find: vi.fn().mockResolvedValue([]), @@ -397,6 +402,7 @@ async function runOne(type: string, fx: Fixture | undefined): Promise { type, name: fx.valid.name ?? `sweep_${type}`, item: fx.valid, + packageId: SWEEP_PKG, }); if (res?.success) validOk = 'ok'; else validNote = `save returned ${JSON.stringify(res)}`; @@ -411,6 +417,7 @@ async function runOne(type: string, fx: Fixture | undefined): Promise { type, name: fx.invalid.name ?? 'sweep_invalid', item: fx.invalid, + packageId: SWEEP_PKG, }); invalidNote = hasSchema ? 'expected 422 but save succeeded' : 'no schema → fall-through (OK)'; invalidRejected = hasSchema ? 'fail' : 'ok'; diff --git a/packages/objectql/src/overlay-precedence.test.ts b/packages/objectql/src/overlay-precedence.test.ts index 22df74ec489..bcf3640ef71 100644 --- a/packages/objectql/src/overlay-precedence.test.ts +++ b/packages/objectql/src/overlay-precedence.test.ts @@ -73,6 +73,8 @@ const validReport = { values: ['amount_sum'], }; +const PKG = 'test_pkg'; + function makeProtocol(opts: { environmentId?: string } = {}) { const registry = new SchemaRegistry({ multiTenant: false }); // [#19542] The live resolution universe the runtime publish gate reads @@ -96,6 +98,14 @@ function makeProtocol(opts: { environmentId?: string } = {}) { dimensions: [{ name: 'month', label: 'Month', field: 'invoice_date', type: 'date' }], measures: [{ name: 'amount_sum', label: 'Amount', aggregate: 'sum', field: 'amount' }], }); + // [#38174] A package-less create is refused (ADR-0070 D1): the brand-new + // items the accepting cases save are saved into this writable package. + registry.installPackage({ id: PKG, name: PKG, version: '1.0.0' } as any, 'authored'); + // The view's object, in that package, so the view's binding is inside its closure. + registry.registerObject({ + name: 'case', label: 'Case', + fields: { name: { name: 'name', type: 'text', label: 'Name' }, status: { name: 'status', type: 'text', label: 'Status' } }, + } as any, PKG); const mockEngine: any = { registry, find: vi.fn().mockResolvedValue([]), @@ -139,6 +149,7 @@ describe('overlay whitelist enforcement (shared-DB invariant)', () => { type: 'view', name: 'case_grid', item: validView, + packageId: PKG, }); expect(result.success).toBe(true); }); @@ -148,6 +159,7 @@ describe('overlay whitelist enforcement (shared-DB invariant)', () => { type: 'dashboard', name: 'sales_overview', item: validDashboard, + packageId: PKG, }); expect(result.success).toBe(true); }); @@ -159,6 +171,7 @@ describe('overlay whitelist enforcement (shared-DB invariant)', () => { type: 'report', name: 'monthly_revenue', item: validReport, + packageId: PKG, }); expect(result.success).toBe(true); }); @@ -168,6 +181,7 @@ describe('overlay whitelist enforcement (shared-DB invariant)', () => { type: 'email_template', name: 'welcome', item: { name: 'welcome', label: 'Welcome', subject: 'Hi', bodyHtml: '

Hello

' }, + packageId: PKG, }); expect(result.success).toBe(true); }); @@ -177,6 +191,7 @@ describe('overlay whitelist enforcement (shared-DB invariant)', () => { type: 'views', name: 'case_grid', item: validView, + packageId: PKG, }); expect(result.success).toBe(true); }); @@ -326,6 +341,7 @@ describe('overlay whitelist enforcement (shared-DB invariant)', () => { type, name: item.name, item, + packageId: PKG, }); expect(result.success).toBe(true); }); @@ -351,6 +367,7 @@ describe('overlay whitelist enforcement (shared-DB invariant)', () => { name: 'my_hook', // [#21689] With a `body`: the door refuses a hook without one. item: { name: 'my_hook', object: 'case', events: ['beforeUpdate'], body: { language: 'js', source: 'return;' } }, + packageId: PKG, }); expect(result.success).toBe(true); }); diff --git a/packages/objectql/src/plugin-runtime-object-metadata-copy.test.ts b/packages/objectql/src/plugin-runtime-object-metadata-copy.test.ts index 09f65b6daa4..6e4efffd7ba 100644 --- a/packages/objectql/src/plugin-runtime-object-metadata-copy.test.ts +++ b/packages/objectql/src/plugin-runtime-object-metadata-copy.test.ts @@ -133,6 +133,11 @@ const NAME = 'qa_probe_gadget'; const OTHER = 'qa_probe_other'; const SHIPPED_PKG = 'com.qa.shipped'; const SHIPPED = 'qa_shipped_widget'; +/** + * [#38174] A package-less create is refused (ADR-0070 D1): the runtime object + * is authored into this writable (DB, non-code) package, installed on every boot. + */ +const RUNTIME_PKG = 'qa_runtime_pkg'; /** A runtime object body; `label` tells the writes apart, `enable` is the exposure under test. */ const objectBody = (name: string, label: string, enable?: Record) => ({ @@ -182,6 +187,7 @@ describe('the metadata service\'s copy of a runtime-authored object follows the await kernel.use(new MetadataPlugin({ watch: false, rootDir: root })); await kernel.use(new ObjectQLPlugin({ ql: engine })); beforeBoot?.(engine); + engine.registry.installPackage({ id: RUNTIME_PKG, name: RUNTIME_PKG, version: '1.0.0' } as any, 'authored'); await kernel.bootstrap(); return { kernel, @@ -192,7 +198,7 @@ describe('the metadata service\'s copy of a runtime-authored object follows the } const save = (k: Booted, name: string, label: string, enable?: Record) => - k.protocol.saveMetaItem({ type: 'object', name, item: objectBody(name, label, enable) }); + k.protocol.saveMetaItem({ type: 'object', name, item: objectBody(name, label, enable), packageId: RUNTIME_PKG }); /** The copy as the service answers it, and the entry the listing carries for the name. */ async function copyOf(k: Booted, name: string) { @@ -365,12 +371,13 @@ describe('on a kernel with an environmentId, a runtime-authored object has a cop })); await kernel.use(new ObjectQLPlugin({ ql: engine, environmentId: ENV, hydrateMetadataFromDb: true })); beforeBoot?.(engine); + engine.registry.installPackage({ id: RUNTIME_PKG, name: RUNTIME_PKG, version: '1.0.0' } as any, 'authored'); await kernel.bootstrap(); return { kernel, engine, protocol: kernel.getService('protocol'), metadata: kernel.getService('metadata') }; } const save = (k: Booted, name: string, label: string, enable?: Record) => - k.protocol.saveMetaItem({ type: 'object', name, item: objectBody(name, label, enable) }); + k.protocol.saveMetaItem({ type: 'object', name, item: objectBody(name, label, enable), packageId: RUNTIME_PKG }); async function copyOf(k: Booted, name: string) { const listed = ((await k.metadata.listObjects()) as Array<{ name?: string }>).find((o) => o?.name === name); diff --git a/packages/objectql/src/plugin.authoring-channel.test.ts b/packages/objectql/src/plugin.authoring-channel.test.ts index 0b4657e97eb..e22e874dee9 100644 --- a/packages/objectql/src/plugin.authoring-channel.test.ts +++ b/packages/objectql/src/plugin.authoring-channel.test.ts @@ -155,11 +155,22 @@ function makeEngine() { const flowRows = (stores: Map>>) => Array.from(stores.get('sys_metadata')?.values() ?? []).filter((r) => r.type === 'flow'); +/** + * [#38174] A package-less create is refused (ADR-0070 D1): the flow is saved + * into this writable package, installed on the kernel's engine first. + */ +const PKG = 'test_pkg'; +function installTestPackage(protocol: any) { + const registry = protocol.engine.registry; + if (!registry.getPackage(PKG)) registry.installPackage({ id: PKG, name: PKG, version: '1.0.0' } as any, 'authored'); +} + /** Attempt the end-user publish and report the verdict without throwing. */ async function publish(protocol: any) { try { + installTestPackage(protocol); const r = await protocol.saveMetaItem({ - type: 'flow', name: 'leave_approval', item: brokenApprovalFlow(), + type: 'flow', name: 'leave_approval', item: brokenApprovalFlow(), packageId: PKG, }); return { refused: false as const, result: r }; } catch (e: any) { @@ -275,8 +286,10 @@ describe('#6710 — the authoring channel is threaded from plugin option to prot (flow.nodes[1] as any).config = { approvers: [{ type: 'expression', value: 'current.owner' }], }; - const result = await (kernel.getService('protocol') as any).saveMetaItem({ - type: 'flow', name: 'leave_approval', item: flow, + const protocol = kernel.getService('protocol') as any; + installTestPackage(protocol); + const result = await protocol.saveMetaItem({ + type: 'flow', name: 'leave_approval', item: flow, packageId: PKG, }); expect(result.success).toBe(true); expect(flowRows(stores).length).toBe(1); diff --git a/packages/objectql/src/protocol-batch-object-registration.test.ts b/packages/objectql/src/protocol-batch-object-registration.test.ts index d4d989cdcaa..79ef865867b 100644 --- a/packages/objectql/src/protocol-batch-object-registration.test.ts +++ b/packages/objectql/src/protocol-batch-object-registration.test.ts @@ -421,7 +421,9 @@ describe('publishPackageDrafts: a promoted unit the registry refuses refuses the describe('the external-import face saves one object, so it asks against the registry (#32369)', () => { it('answers 422 for a pair the follow door refuses, and stores nothing', async () => { const h = await boot(); - await h.protocol.saveMetaItem({ type: 'object', name: 'ext_invoice', item: invoice('ext') }); + // [#38174] A package-less create is refused (ADR-0070 D1) unless it is an + // external import: the invoice arrives through the same face as its line. + await h.protocol.saveMetaItem({ type: 'object', name: 'ext_invoice', item: invoice('ext'), writeFace: 'external-import' }); let error: any; try { await h.protocol.saveMetaItem({ diff --git a/packages/objectql/src/protocol-boot-object-package-binding.test.ts b/packages/objectql/src/protocol-boot-object-package-binding.test.ts index 5ba15a19113..636688c92eb 100644 --- a/packages/objectql/src/protocol-boot-object-package-binding.test.ts +++ b/packages/objectql/src/protocol-boot-object-package-binding.test.ts @@ -198,14 +198,18 @@ const owner = (registry: SchemaRegistry, name: string) => registry.getObjectOwne */ async function persistThenRestart(opts: { name: string; packageId?: string }) { const first = makeSession(); + // [#38174] A package-less create is refused (ADR-0070 D1): a package-less + // row is written through the real path into APP_PKG and then unbound, so + // every other column is still the repository's own spelling. const res = await first.protocol.saveMetaItem({ type: 'object', name: opts.name, - ...(opts.packageId ? { packageId: opts.packageId } : {}), + packageId: opts.packageId || APP_PKG, item: objectBody(opts.name), }); expect(res.success).toBe(true); - const persisted = Array.from(first.rows.values()); + const persisted = Array.from(first.rows.values()) + .map((r) => (opts.packageId ? r : { ...r, package_id: null })); return { persisted, reboot: () => makeSession({ rows: persisted, history: first.historyRows }), diff --git a/packages/objectql/src/protocol-commit-history.test.ts b/packages/objectql/src/protocol-commit-history.test.ts index d337ac5b8bb..7c2ce5d264f 100644 --- a/packages/objectql/src/protocol-commit-history.test.ts +++ b/packages/objectql/src/protocol-commit-history.test.ts @@ -453,6 +453,23 @@ function makeRealRepoHarness(seedCommits: any[] = [], opts: { controlPlane?: boo return { protocol, engine, rows, historyRows, commits, registry }; } +/** + * [#38174] A package-less create is refused (ADR-0070 D1), so a package-less + * row is no longer authored through the save door. The legacy shape is laid + * down by writing the item into APP_PKG through the real path and then + * unbinding its stored row and history in the store: every other column is the + * repository's own spelling, and later package-less saves run in place. + */ +function unbindToLoose(h: { rows: Map; historyRows: any[] }, name: string) { + for (const [key, row] of [...h.rows]) { + if (row.name !== name) continue; + h.rows.delete(key); + const loose = { ...row, package_id: null }; + h.rows.set(rowKey(loose), loose); + } + for (const hist of h.historyRows) if (hist.name === name) hist.package_id = null; +} + /** * The reverted artifact is a `view`, not an `object`, and deliberately: the * repository's `assertAllowed` refuses `override-artifact` on `object` (not @@ -510,13 +527,15 @@ describe('#6215 — revertCommit restores a PACKAGE-BOUND overlay row', () => { }); it('a package-LESS row still reverts — the legacy shape is not regressed', async () => { - const { protocol, rows } = makeRealRepoHarness([applyCommit({ + const h = makeRealRepoHarness([applyCommit({ id: 'cmt_global', package_id: null, items: [{ type: 'view', name: 'myapp_case_grid', existedBefore: true, prevVersion: 1 }], created_at: '2026-08-08T00:00:00.000Z', })]); - await protocol.saveMetaItem({ type: 'view', name: 'myapp_case_grid', item: gridBody('Cases') }); + const { protocol, rows } = h; + await protocol.saveMetaItem({ type: 'view', name: 'myapp_case_grid', packageId: APP_PKG, item: gridBody('Cases') }); + unbindToLoose(h, 'myapp_case_grid'); await protocol.saveMetaItem({ type: 'view', name: 'myapp_case_grid', item: gridBody('Renamed') }); const res = await protocol.revertCommit({ commitId: 'cmt_global' }); @@ -622,8 +641,16 @@ const evolvedInvoiceBody = (name: string) => { }; /** The exact measured repro: saved twice through `saveMetaItem`, then reverted. */ -async function seedObjectEdit(protocol: any, name: string, packageId?: string) { +async function seedObjectEdit(protocol: any, name: string, packageId?: string, loose?: { engine: any }) { const pkg = packageId ? { packageId } : {}; + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the package-less + // row is laid down through the engine first, and v1 is saved in place over it. + if (!packageId && loose) { + await loose.engine.insert('sys_metadata', { + type: 'object', name, organization_id: null, package_id: null, state: 'active', + metadata: JSON.stringify({ ...invoiceBody(name), label: 'Seeded' }), + }, { context: { isSystem: true } }); + } await protocol.saveMetaItem({ type: 'object', name, ...pkg, item: invoiceBody(name) }); await protocol.saveMetaItem({ type: 'object', name, ...pkg, item: evolvedInvoiceBody(name) }); } @@ -663,12 +690,13 @@ describe('#6563 — revertCommit restores a runtime-created `object`', () => { }); it('a package-LESS object reverts identically — the binding was never the cause', async () => { - const { protocol, rows } = makeRealRepoHarness([objectCommit({ + const h = makeRealRepoHarness([objectCommit({ id: 'cmt_obj_global', package_id: null, items: [{ type: 'object', name: 'global_invoice', existedBefore: true, prevVersion: 1 }], })]); - await seedObjectEdit(protocol, 'global_invoice'); + const { protocol, rows } = h; + await seedObjectEdit(protocol, 'global_invoice', undefined, h); const res = await protocol.revertCommit({ commitId: 'cmt_obj_global' }); @@ -822,10 +850,12 @@ const createdItem = (name: string) => ({ }); /** The first-build shape: authored ONCE, never edited — nothing to restore to. */ -async function seedCreatedObject(protocol: any, name: string, packageId?: string) { +async function seedCreatedObject(protocol: any, name: string, packageId?: string, loose?: Parameters[0]) { + // [#38174] A package-less create is written into APP_PKG and unbound (`unbindToLoose`). await protocol.saveMetaItem({ - type: 'object', name, ...(packageId ? { packageId } : {}), item: invoiceBody(name), + type: 'object', name, packageId: packageId ?? APP_PKG, item: invoiceBody(name), }); + if (!packageId && loose) unbindToLoose(loose, name); } const storedRows = (rows: Map, name: string) => @@ -860,12 +890,13 @@ describe('#6620 — revertCommit soft-removes a runtime-CREATED `object`', () => }); it('a package-LESS created object reverts identically — the binding was never the cause', async () => { - const { protocol, rows } = makeRealRepoHarness([objectCommit({ + const h = makeRealRepoHarness([objectCommit({ id: 'cmt_new_global', package_id: null, items: [createdItem('global_invoice')], })]); - await seedCreatedObject(protocol, 'global_invoice'); + const { protocol, rows } = h; + await seedCreatedObject(protocol, 'global_invoice', undefined, h); const res = await protocol.revertCommit({ commitId: 'cmt_new_global' }); diff --git a/packages/objectql/src/protocol-delete-boot-hydrated-object-heal.test.ts b/packages/objectql/src/protocol-delete-boot-hydrated-object-heal.test.ts index e58924ff640..78a8f872f1a 100644 --- a/packages/objectql/src/protocol-delete-boot-hydrated-object-heal.test.ts +++ b/packages/objectql/src/protocol-delete-boot-hydrated-object-heal.test.ts @@ -236,10 +236,20 @@ describe('#23645 — a runtime object hydrated at boot, then deleted', () => { /** The object saved under `binding` (or none), two records in its table, then a second boot. */ async function bootHydrated(stores: Stores, drops: string[], binding: string | undefined): Promise { const k1 = await boot(stores, drops); - expect((await save(k1, binding, 'Gadget')).success).toBe(true); + // [#38174] A package-less create is refused (ADR-0070 D1): the + // package-less row is written into P through the real path and, with + // the kernel down, unbound in the store, so the boot hydrates a loose row. + expect((await save(k1, binding ?? P, 'Gadget')).success).toBe(true); await k1.engine.insert(NAME, { name: 'rec-1' }, SYSTEM); await k1.engine.insert(NAME, { name: 'rec-2' }, SYSTEM); await k1.kernel.shutdown(); + if (binding === undefined) { + for (const table of ['sys_metadata', 'sys_metadata_history']) { + for (const row of stores.get(table)?.values() ?? []) { + if (row.type === 'object' && row.name === NAME) row.package_id = null; + } + } + } const k2 = await boot(stores, drops); expect(await served(k2)).toEqual({ diff --git a/packages/objectql/src/protocol-destructive-null-master.test.ts b/packages/objectql/src/protocol-destructive-null-master.test.ts index 913fea4f029..8fae300856d 100644 --- a/packages/objectql/src/protocol-destructive-null-master.test.ts +++ b/packages/objectql/src/protocol-destructive-null-master.test.ts @@ -62,6 +62,10 @@ describe('[#28665] the controlled_by_parent master finding counts the rows with function boot(stored: Record = storedTask()) { registry = new SchemaRegistry({ multiTenant: false }); + // [#38174] A package-less create is refused (ADR-0070 D1): `pkg`, which + // holds both objects, is an installed writable package the saves that + // land name. + registry.installPackage({ id: 'pkg', name: 'pkg', version: '1.0.0' } as any, 'authored'); registry.registerObject({ name: 'qow_project', label: 'Project', _provenance: 'org', sharingModel: 'private', fields: { name: { name: 'name', type: 'text' } }, @@ -155,7 +159,7 @@ describe('[#28665] the controlled_by_parent master finding counts the rows with }); it('force=true still saves, and asks the table nothing', async () => { - const saved = await protocol.saveMetaItem({ type: 'object', name: 'qow_task', item: controlledTask(), force: true }); + const saved = await protocol.saveMetaItem({ type: 'object', name: 'qow_task', item: controlledTask(), force: true, packageId: 'pkg' }); expect(saved).toMatchObject({ success: true }); expect(mockEngine.count).not.toHaveBeenCalled(); }); @@ -182,7 +186,7 @@ describe('[#28665] the controlled_by_parent master finding counts the rows with }); it('an ordinary save with no destructive change: no count', async () => { - const saved = await protocol.saveMetaItem({ type: 'object', name: 'qow_task', item: storedTask({ label: 'Tasks', _provenance: undefined }) }); + const saved = await protocol.saveMetaItem({ type: 'object', name: 'qow_task', item: storedTask({ label: 'Tasks', _provenance: undefined }), packageId: 'pkg' }); expect(saved).toMatchObject({ success: true }); expect(mockEngine.count).not.toHaveBeenCalled(); }); diff --git a/packages/objectql/src/protocol-destructive-unit-mode.test.ts b/packages/objectql/src/protocol-destructive-unit-mode.test.ts index d8fa65f370d..5ab3f0f359c 100644 --- a/packages/objectql/src/protocol-destructive-unit-mode.test.ts +++ b/packages/objectql/src/protocol-destructive-unit-mode.test.ts @@ -53,7 +53,7 @@ describe('ObjectStackProtocolImplementation - unit_code_field_declared and unit_ }; /** The save under test. `sharingModel` set, so a save the detector admits is admitted for real. */ const save = (name: string, fields: Record, extra: Record = {}) => - protocol.saveMetaItem({ type: 'object', name, ...extra, item: { name, label: name, sharingModel: 'private', fields } } as any); + protocol.saveMetaItem({ type: 'object', name, packageId: 'pkg', ...extra, item: { name, label: name, sharingModel: 'private', fields } } as any); /** The refusal a save raised, or null when it was admitted. */ const refusalOf = (p: Promise): Promise => p.then(() => null, (e: unknown) => e); /** The finding codes a save raised: `[]` when it was admitted. */ @@ -78,6 +78,9 @@ describe('ObjectStackProtocolImplementation - unit_code_field_declared and unit_ beforeEach(() => { registry = new SchemaRegistry({ multiTenant: false }); + // [#38174] A package-less create is refused (ADR-0070 D1): `pkg`, which + // holds every object here, is an installed writable package the saves name. + registry.installPackage({ id: 'pkg', name: 'pkg', version: '1.0.0' } as any, 'authored'); for (const [name, fields] of Object.entries(STORED)) register(name, fields); mockEngine = { registry, diff --git a/packages/objectql/src/protocol-environment-kernel-registry-write-through.test.ts b/packages/objectql/src/protocol-environment-kernel-registry-write-through.test.ts index b57709bfbaf..11027625746 100644 --- a/packages/objectql/src/protocol-environment-kernel-registry-write-through.test.ts +++ b/packages/objectql/src/protocol-environment-kernel-registry-write-through.test.ts @@ -201,9 +201,15 @@ async function makeEngine(stores: Stores): Promise { engine.registry.registerObject(o as any, 'test-package'); } engine.registerApp(crmManifest()); + // [#38174] A package-less create is refused (ADR-0070 D1): the items the + // saves below author live in this writable package, which depends on the + // CRM package whose object they reference. Installed on every boot. + engine.registry.installPackage({ id: AUTHORED_PKG, name: AUTHORED_PKG, version: '1.0.0', dependencies: { [PKG]: '^1.0.0' } } as any, 'authored'); return engine; } +const AUTHORED_PKG = 'env_authored'; + /** * One environment kernel over `stores`, booted as `ObjectQLPlugin.start()` * boots a kernel with `hydrateMetadataFromDb`: the package registered, then @@ -239,7 +245,7 @@ describe('#23298 — an environment kernel that hydrates its own store takes the it('a narrowed permission set\'s next resolution reads the new body, with no rebuild — the body a rebuild reads', async () => { const stores: Stores = new Map(); const first = await bootEnvironmentKernel(stores); - expect(await first.protocol.saveMetaItem({ type: 'permission', name: SET, item: wideSet() })) + expect(await first.protocol.saveMetaItem({ packageId: AUTHORED_PKG, type: 'permission', name: SET, item: wideSet() })) .toMatchObject({ success: true }); // The kernel the administrator works on: its boot put the wide body @@ -250,7 +256,7 @@ describe('#23298 — an environment kernel that hydrates its own store takes the expect(before?.definition).toMatchObject({ objects: { crm_account: { allowDelete: true } } }); expect(before?.definition).not.toHaveProperty('isDefault', true); - expect(await kernel.protocol.saveMetaItem({ type: 'permission', name: SET, item: narrowedSet(), mode: 'publish' })) + expect(await kernel.protocol.saveMetaItem({ packageId: AUTHORED_PKG, type: 'permission', name: SET, item: narrowedSet(), mode: 'publish' })) .toMatchObject({ success: true }); const after = await kernel.catalog.resolve('permission', SET); @@ -265,14 +271,14 @@ describe('#23298 — an environment kernel that hydrates its own store takes the it('a published view reaches the registry with no rebuild — the body a rebuild reads', async () => { const stores: Stores = new Map(); const first = await bootEnvironmentKernel(stores); - expect(await first.protocol.saveMetaItem({ type: 'view', name: VIEW, item: viewBody(VIEW, 'Accounts') })) + expect(await first.protocol.saveMetaItem({ packageId: AUTHORED_PKG, type: 'view', name: VIEW, item: viewBody(VIEW, 'Accounts') })) .toMatchObject({ success: true }); const kernel = await bootEnvironmentKernel(stores); expect(kernel.engine.registry.getItem('view', VIEW), 'anti-vacuity: the boot-time body') .toMatchObject({ label: 'Accounts' }); - expect(await kernel.protocol.saveMetaItem({ type: 'view', name: VIEW, item: viewBody(VIEW, 'Accounts (admin)') })) + expect(await kernel.protocol.saveMetaItem({ packageId: AUTHORED_PKG, type: 'view', name: VIEW, item: viewBody(VIEW, 'Accounts (admin)') })) .toMatchObject({ success: true }); const after = kernel.engine.registry.getItem('view', VIEW) as Row | undefined; expect(after).toMatchObject({ label: 'Accounts (admin)' }); @@ -288,11 +294,11 @@ describe('#23298 — an environment kernel that hydrates its own store takes the const kernel = await bootEnvironmentKernel(stores, metadata); expect(kernel.engine.registry.getItem('view', BASELINE_VIEW), 'precondition: no package ships it').toBeUndefined(); - expect(await kernel.protocol.saveMetaItem({ type: 'view', name: BASELINE_VIEW, item: viewBody(BASELINE_VIEW, 'Saved accounts') })) + expect(await kernel.protocol.saveMetaItem({ packageId: AUTHORED_PKG, type: 'view', name: BASELINE_VIEW, item: viewBody(BASELINE_VIEW, 'Saved accounts') })) .toMatchObject({ success: true }); expect(kernel.engine.registry.getItem('view', BASELINE_VIEW)).toMatchObject({ label: 'Saved accounts' }); - await kernel.protocol.deleteMetaItem({ type: 'view', name: BASELINE_VIEW }); + await kernel.protocol.deleteMetaItem({ type: 'view', name: BASELINE_VIEW, packageId: AUTHORED_PKG }); expect(Array.from(stores.get('sys_metadata')?.values() ?? []).filter((r) => r.name === BASELINE_VIEW && r.state === 'active')) .toEqual([]); // Not the deleted body: the baseline, as a rebuild serves it. @@ -322,9 +328,9 @@ describe('#23298 — a shared registry never receives a project-scoped row', () it('a permission set and a view published by the environment protocol stay out of the shared registry', async () => { const { stores, engine, environment } = await sharedRegistry(); - expect(await environment.saveMetaItem({ type: 'permission', name: SET, item: wideSet(), mode: 'publish' })) + expect(await environment.saveMetaItem({ packageId: AUTHORED_PKG, type: 'permission', name: SET, item: wideSet(), mode: 'publish' })) .toMatchObject({ success: true }); - expect(await environment.saveMetaItem({ type: 'view', name: VIEW, item: viewBody(VIEW, 'Accounts'), mode: 'publish' })) + expect(await environment.saveMetaItem({ packageId: AUTHORED_PKG, type: 'view', name: VIEW, item: viewBody(VIEW, 'Accounts'), mode: 'publish' })) .toMatchObject({ success: true }); // Anti-vacuity: both writes landed and are live. @@ -337,7 +343,7 @@ describe('#23298 — a shared registry never receives a project-scoped row', () it('CONTROL: the control-plane protocol\'s own publish reaches the same registry', async () => { const { engine, controlPlane } = await sharedRegistry(); - expect(await controlPlane.saveMetaItem({ type: 'permission', name: SET, item: wideSet(), mode: 'publish' })) + expect(await controlPlane.saveMetaItem({ packageId: AUTHORED_PKG, type: 'permission', name: SET, item: wideSet(), mode: 'publish' })) .toMatchObject({ success: true }); expect(engine.registry.getItem('permission', SET)).toMatchObject({ name: SET }); }); diff --git a/packages/objectql/src/protocol-meta-effective-schema.test.ts b/packages/objectql/src/protocol-meta-effective-schema.test.ts index 7115f4a3b63..b8528c7d2ef 100644 --- a/packages/objectql/src/protocol-meta-effective-schema.test.ts +++ b/packages/objectql/src/protocol-meta-effective-schema.test.ts @@ -78,8 +78,15 @@ function keyOf(w: Record) { * A `sys_metadata` store over a real {@link SchemaRegistry} — the two layers * whose disagreement is the subject. */ +/** + * [#38174] A package-less create is refused (ADR-0070 D1): a NEW object these + * tests author is saved into this writable package, installed on every host. + */ +const PKG = 'test_pkg'; + function makeHost(multiTenant: boolean) { const registry = new SchemaRegistry({ multiTenant }); + registry.installPackage({ id: PKG, name: PKG, version: '1.0.0' } as any, 'authored'); const rows = new Map(); let nextId = 0; const findRow = (w: Record) => { @@ -383,7 +390,7 @@ describe('[#29673] a zh-CN read echoed back is stored as its source, and publish it('the echo stores no injected column, the new field registers, and an en read is English again', async () => { const host = makeHost(false); - await host.protocol.saveMetaItem({ type: 'object', name: 'crm_invoice', item: { ...authored(), sharingModel: 'private' }, mode: 'publish' } as any); + await host.protocol.saveMetaItem({ type: 'object', name: 'crm_invoice', item: { ...authored(), sharingModel: 'private' }, mode: 'publish', packageId: PKG } as any); const echo = await zhRead(host, 'crm_invoice'); // The precondition: the read really translated the injected columns. @@ -443,7 +450,7 @@ describe('[#29673] a zh-CN read echoed back is stored as its source, and publish const host = makeHost(false); const bundle = { 'zh-CN': { objects: { crm_invoice: { fields: { amount: { label: '金额' } } } } } }; const protocol = withServices(host, bundle); - await protocol.saveMetaItem({ type: 'object', name: 'crm_invoice', item: { ...authored(), sharingModel: 'private' }, mode: 'publish' } as any); + await protocol.saveMetaItem({ type: 'object', name: 'crm_invoice', item: { ...authored(), sharingModel: 'private' }, mode: 'publish', packageId: PKG } as any); const echo: any = translateMetadataDocument('object', (await protocol.getMetaItem({ type: 'object', name: 'crm_invoice' })).item as any, bundle as any, { locale: 'zh-CN' }); expect(echo.fields.amount.label).toBe('金额'); @@ -500,7 +507,7 @@ describe('[#29673] a zh-CN read echoed back is stored as its source, and publish getDiagnosed: async () => ({ data: undefined, degraded: true, errors: ['metadata store unreachable'] }), }; const protocol = withServices(host, {}, degraded); - const saved: any = await protocol.saveMetaItem({ type: 'object', name: 'crm_fresh', item: { ...authored(), name: 'crm_fresh', sharingModel: 'private' }, mode: 'draft' } as any); + const saved: any = await protocol.saveMetaItem({ type: 'object', name: 'crm_fresh', item: { ...authored(), name: 'crm_fresh', sharingModel: 'private' }, mode: 'draft', packageId: PKG } as any); expect(saved.success).toBe(true); expect(storedBody(host, 'crm_fresh', 'draft').fields.amount.label).toBe('Amount'); }); @@ -608,7 +615,7 @@ describe('a zh-CN read of a field a code dependent adds, echoed back, is stored ['i18n', { getLocales: () => Object.keys(bundle), getTranslations: (locale: string) => (bundle as any)[locale] }], ])); protocol.getPackagedObjectBase = (name: string) => (name === 'crm_account' ? packagedBase() : undefined); - const saved: any = await protocol.saveMetaItem({ type: 'object', name: 'crm_account', item: echo, mode: 'publish' } as any); + const saved: any = await protocol.saveMetaItem({ type: 'object', name: 'crm_account', item: echo, mode: 'publish', ...(withStoredRow ? {} : { packageId: PKG }) } as any); const stored = storedOf(host); expect(stored.fields.cb_market.label).toBe('Market'); @@ -702,7 +709,7 @@ describe('[#33952] a zh-CN read of a patched field label, echoed back, is stored // The precondition: the read serves the patched label in the dependent's zh-CN. expect(echo.fields.registration_number.label).toBe('税号'); - await protocol.saveMetaItem({ type: 'object', name: 'crm_account', item: echo, mode: 'publish' } as any); + await protocol.saveMetaItem({ type: 'object', name: 'crm_account', item: echo, mode: 'publish', ...(withStoredRow ? {} : { packageId: PKG }) } as any); const stored = storedOf(host); expect(stored.fields.registration_number.label).toBe('Tax ID'); @@ -770,7 +777,7 @@ describe('[#35707] an object save or migration over translations that cannot be const saveOver = async (i18n: unknown) => { const host = makeHost(false); const protocol: any = new ObjectStackProtocolImplementation(host.engine, () => new Map([['i18n', i18n]])); - const outcome = await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: body(), mode: 'publish' } as any) + const outcome = await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: body(), mode: 'publish', packageId: PKG } as any) .then(() => null, (e: unknown) => e); return { outcome, stored: Array.from(host.rows.values()).some((r) => r.name === 'crm_note') }; }; diff --git a/packages/objectql/src/protocol-meta.test.ts b/packages/objectql/src/protocol-meta.test.ts index 68f829e9e87..3c636fbd058 100644 --- a/packages/objectql/src/protocol-meta.test.ts +++ b/packages/objectql/src/protocol-meta.test.ts @@ -11,6 +11,24 @@ import { SchemaRegistry } from './registry.js'; * Validates dual-write strategy (SchemaRegistry + database), DB fallback for reads, * graceful degradation when DB is unavailable, and the loadMetaFromDb() bootstrap method. */ +const PKG = 'test_pkg'; + +/** + * [#38174] A package-less create is refused (ADR-0070 D1). A case that pins a + * package-less save keeps it by answering the store reads with the item's + * package-less row (the row it saves in place over), as a stored row would. + */ +function answerLooseRow(engine: any, type: string, name: string, body: Record) { + const row = { id: `loose-${name}`, type, name, package_id: null, organization_id: null, state: 'active', metadata: JSON.stringify(body) }; + engine.find.mockImplementation(async (table: string, opts: any) => { + const where = opts?.where ?? {}; + if (table !== 'sys_metadata' || where.name !== name) return []; + if (where.state !== undefined && where.state !== 'active') return []; + if (where.package_id !== undefined && where.package_id !== null) return []; + return [row]; + }); +} + describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { let protocol: ObjectStackProtocolImplementation; let mockEngine: any; @@ -39,6 +57,9 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { // Each test owns a fresh registry instance — the protocol reads it // via `engine.registry`, mirroring the real ObjectQL contract. registry = new SchemaRegistry({ multiTenant: false }); + // [#38174] A package-less create is refused (ADR-0070 D1): the new items + // the accepting cases save are saved into this writable, installed package. + registry.installPackage({ id: PKG, name: PKG, version: '1.0.0' } as any, 'authored'); mockEngine = { registry, @@ -217,7 +238,7 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { // the registry (#4432 F1 → #4521). The rest of ADR-0005 is intact: // `sys_metadata` is still the authoritative store and `getMetaItem` // still consults it first. - await protocol.saveMetaItem({ type: 'app', name: 'test_app', item: sampleApp }); + await protocol.saveMetaItem({ packageId: PKG, type: 'app', name: 'test_app', item: sampleApp }); const stored = registry.getItem('app', 'test_app'); expect(stored).toBeDefined(); @@ -225,7 +246,7 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { }); it('should register `object` type items in SchemaRegistry (engine schema-sync needs it)', async () => { - await protocol.saveMetaItem({ + await protocol.saveMetaItem({ packageId: PKG, type: 'object', name: 'test_obj', // [#8310] The runtime object door requires an authored OWD. @@ -240,11 +261,12 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { it('should insert a new record in the database when item does not exist', async () => { mockEngine.findOne.mockResolvedValue(null); // not existing - await protocol.saveMetaItem({ type: 'app', name: 'test_app', item: sampleApp }); + await protocol.saveMetaItem({ packageId: PKG, type: 'app', name: 'test_app', item: sampleApp }); expect(mockEngine.findOne).toHaveBeenCalledWith('sys_metadata', { - // ADR-0048 — package-less save scopes the lookup to the global row. - where: { type: 'app', name: 'test_app', state: 'active', package_id: null }, + // ADR-0048 — the save scopes the lookup to its package's row + // ([#38174] a package-less create is refused, ADR-0070 D1). + where: { type: 'app', name: 'test_app', state: 'active', package_id: PKG }, // [#21911] The platform store read carries the explicit system opt-in. context: { isSystem: true }, }); @@ -292,7 +314,7 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { // parentVersion: null because the mock row has no checksum column // (existingHash = existing?.checksum ?? null = null). - await protocol.saveMetaItem({ type: 'app', name: 'test_app', item: sampleApp, parentVersion: null }); + await protocol.saveMetaItem({ packageId: PKG, type: 'app', name: 'test_app', item: sampleApp, parentVersion: null }); expect(mockEngine.update).toHaveBeenCalledWith('sys_metadata', expect.objectContaining({ metadata: JSON.stringify(sampleApp), @@ -306,6 +328,7 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { }); it('should return success=true on DB success (control-plane path)', async () => { + answerLooseRow(mockEngine, 'app', 'test_app', { ...sampleApp, label: 'Seeded' }); const result = await protocol.saveMetaItem({ type: 'app', name: 'test_app', item: sampleApp }); expect(result.success).toBe(true); @@ -367,14 +390,14 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { mockEngine.insert.mockRejectedValue(new Error('Table not found')); await expect( - protocol.saveMetaItem({ type: 'app', name: 'test_app', item: sampleApp }) + protocol.saveMetaItem({ packageId: PKG, type: 'app', name: 'test_app', item: sampleApp }) ).rejects.toThrow(/Table not found/); }); it('should use version=1 for initial insert when existing record has no version', async () => { mockEngine.findOne.mockResolvedValue(null); - await protocol.saveMetaItem({ type: 'app', name: 'test_app', item: sampleApp }); + await protocol.saveMetaItem({ packageId: PKG, type: 'app', name: 'test_app', item: sampleApp }); expect(mockEngine.insert).toHaveBeenCalledWith('sys_metadata', expect.objectContaining({ version: 1, @@ -385,7 +408,7 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { mockEngine.findOne.mockResolvedValue({ id: 'uuid', version: 0 }); // parentVersion: null because the mock row has no checksum column. - await protocol.saveMetaItem({ type: 'app', name: 'test_app', item: sampleApp, parentVersion: null }); + await protocol.saveMetaItem({ packageId: PKG, type: 'app', name: 'test_app', item: sampleApp, parentVersion: null }); expect(mockEngine.update).toHaveBeenCalledWith('sys_metadata', expect.objectContaining({ version: 1, // history-based counter (empty history → 1) @@ -418,6 +441,7 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { }; it('accepts a spec-conformant view payload', async () => { + answerLooseRow(mockEngine, 'view', 'all_leads', { ...validView, label: 'Seeded' }); await expect( protocol.saveMetaItem({ type: 'view', name: 'all_leads', item: validView }) ).resolves.toMatchObject({ success: true }); @@ -448,6 +472,7 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { }, _packageId: 'com.objectstack.service-ai', }; + answerLooseRow(mockEngine, 'view', 'ai_traces', { ...containerView, _packageId: undefined, listViews: {} }); await expect( protocol.saveMetaItem({ type: 'view', name: 'ai_traces', item: containerView }) ).resolves.toMatchObject({ success: true }); @@ -472,7 +497,7 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { // Protocol 19: the form is its own item, named `OBJECT.KEY`. await expect( - protocol.saveMetaItem({ type: 'form', name: 'lead.form', item: { name: 'lead.form', object: 'lead', ...body } }) + protocol.saveMetaItem({ packageId: PKG, type: 'form', name: 'lead.form', item: { name: 'lead.form', object: 'lead', ...body } }) ).resolves.toMatchObject({ success: true }); }); @@ -494,7 +519,7 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { }, 'name'); await expect( - protocol.saveMetaItem({ + protocol.saveMetaItem({ packageId: PKG, type: 'dashboard', name: 'sales_dashboard', item: validDashboard, @@ -519,6 +544,7 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { sortOrder: 5, }; + answerLooseRow(mockEngine, 'view', 'all_leads', { ...validView, label: 'Seeded' }); await protocol.saveMetaItem({ type: 'view', name: 'all_leads', @@ -632,6 +658,7 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { }); it('accepts plural type strings (e.g. `views`, `dashboards`)', async () => { + answerLooseRow(mockEngine, 'view', 'all_leads', { ...validView, label: 'Seeded' }); await expect( protocol.saveMetaItem({ type: 'views', name: 'all_leads', item: validView }) ).resolves.toMatchObject({ success: true }); @@ -1508,7 +1535,7 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { it('accepts brand-new hook (no artifact at this name)', async () => { mockEngine.findOne.mockResolvedValue(null); - const result = await scoped.saveMetaItem({ + const result = await scoped.saveMetaItem({ packageId: PKG, type: 'hook', name: 'my_user_hook', // [#21689] With a `body`: the door refuses a hook without one. @@ -1528,6 +1555,9 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { { name: 'my_user_hook', object: 'case', events: ['beforeUpdate'] }, 'name' as any, ); // no packageId arg — DB-rehydration parity + // [#38174] …and its package-less row is stored (a package-less + // CREATE is refused, ADR-0070 D1; this edit of it runs in place). + answerLooseRow(mockEngine, 'hook', 'my_user_hook', { name: 'my_user_hook', object: 'case', events: ['beforeUpdate'], body: { language: 'js', source: 'return;' } }); mockEngine.findOne.mockResolvedValue(null); @@ -1561,7 +1591,7 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { // whose object nothing resolves. registry.registerObject({ name: 'case', label: 'Case', fields: { name: { type: 'text', label: 'Name' } } } as never); - const mappingResult = await scoped.saveMetaItem({ + const mappingResult = await scoped.saveMetaItem({ packageId: PKG, type: 'mapping', name: 'my_mapping', item: { @@ -1570,7 +1600,7 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { fieldMapping: [{ source: 'Title', target: 'title' }], }, }); - const seedResult = await scoped.saveMetaItem({ + const seedResult = await scoped.saveMetaItem({ packageId: PKG, type: 'seed', name: 'my_seed', item: { object: 'case', records: [] }, @@ -1673,7 +1703,7 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { it('accepts brand-new plugin-registered type (no static registry entry)', async () => { mockEngine.findOne.mockResolvedValue(null); - const result = await scoped.saveMetaItem({ + const result = await scoped.saveMetaItem({ packageId: PKG, type: 'connector', name: 'my_plugin_kind_item', item: { name: 'my_plugin_kind_item', label: 'Test', type: 'api' }, @@ -1756,7 +1786,7 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { it('accepts a spec-valid `webhook` item (write door unchanged by the schema binding)', async () => { mockEngine.findOne.mockResolvedValue(null); - const result = await scoped.saveMetaItem({ + const result = await scoped.saveMetaItem({ packageId: PKG, type: 'webhook', name: 'my_webhook', item: { @@ -1793,7 +1823,7 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { it('accepts a spec-valid `connector` item (write door unchanged by the schema binding)', async () => { mockEngine.findOne.mockResolvedValue(null); - const result = await scoped.saveMetaItem({ + const result = await scoped.saveMetaItem({ packageId: PKG, type: 'connector', name: 'my_connector', item: { name: 'my_connector', label: 'My Connector', type: 'api' }, @@ -1899,7 +1929,7 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { it('accepts a spec-valid `webhook` item (write door unchanged by the schema binding)', async () => { mockEngine.findOne.mockResolvedValue(null); - const result = await scoped.saveMetaItem({ + const result = await scoped.saveMetaItem({ packageId: PKG, type: 'webhook', name: 'my_hook', item: { @@ -1950,7 +1980,7 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { it('accepts a spec-valid `analytics_cube` item (write door unchanged by the schema binding)', async () => { mockEngine.findOne.mockResolvedValue(null); - const result = await scoped.saveMetaItem({ + const result = await scoped.saveMetaItem({ packageId: PKG, type: 'analytics_cube', name: 'orders', item: { @@ -2166,6 +2196,7 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { 'sys_metadata', ); mockEngine.findOne.mockResolvedValue(null); + answerLooseRow(mockEngine, 'object', 'crm_quote', { name: 'crm_quote', label: 'Quote', sharingModel: 'private', fields: { name: { type: 'text' } } }); const result = await scoped.saveMetaItem({ type: 'object', diff --git a/packages/objectql/src/protocol-metadata-row-actor.test.ts b/packages/objectql/src/protocol-metadata-row-actor.test.ts index 5222acd5066..62dc2b9c951 100644 --- a/packages/objectql/src/protocol-metadata-row-actor.test.ts +++ b/packages/objectql/src/protocol-metadata-row-actor.test.ts @@ -124,6 +124,7 @@ function makeMemoryDriver(stores: Stores) { const ALICE = 'usr_alice'; const BOB = 'usr_bob'; const NAME = 'case_grid'; +const PKG = 'test_pkg'; // [#21470] `name` is the row's: a body `name` that is not its row's is refused by the write doors. // [#24668] Bound to `sys_metadata`, an object this harness registers: the overlay save door refuses a list view bound to an object that exists nowhere (it read `case`). @@ -144,6 +145,9 @@ describe('#23033 — the sys_metadata row records who created it and who last ch await kernel.use(new ObjectQLPlugin({ ql: engine })); await kernel.bootstrap(); protocol = kernel.getService('protocol'); + // [#38174] A package-less create is refused (ADR-0070 D1): the view is + // saved into this writable, installed package. + engine.registry.installPackage({ id: PKG, name: PKG, version: '1.0.0' } as any, 'authored'); }); afterEach(async () => { if (kernel.getState() === 'running') await kernel.shutdown(); @@ -166,7 +170,7 @@ describe('#23033 — the sys_metadata row records who created it and who last ch .map((h) => h.recorded_by ?? null); it('a first write with actor A stores created_by A and updated_by A', async () => { - await protocol.saveMetaItem({ type: 'view', name: NAME, item: viewBody('A'), actor: ALICE }); + await protocol.saveMetaItem({ type: 'view', name: NAME, packageId: PKG, item: viewBody('A'), actor: ALICE }); const row = parentRow(); expect(row.created_by).toBe(ALICE); @@ -175,8 +179,8 @@ describe('#23033 — the sys_metadata row records who created it and who last ch }); it('a second write with actor B keeps created_by A and moves updated_by to B', async () => { - await protocol.saveMetaItem({ type: 'view', name: NAME, item: viewBody('A'), actor: ALICE }); - await protocol.saveMetaItem({ type: 'view', name: NAME, item: viewBody('B'), actor: BOB }); + await protocol.saveMetaItem({ type: 'view', name: NAME, packageId: PKG, item: viewBody('A'), actor: ALICE }); + await protocol.saveMetaItem({ type: 'view', name: NAME, packageId: PKG, item: viewBody('B'), actor: BOB }); const row = parentRow(); expect(row.created_by, 'created_by never changes after the insert').toBe(ALICE); @@ -186,7 +190,7 @@ describe('#23033 — the sys_metadata row records who created it and who last ch }); it('CONTROL: a write with no actor stores both columns null — no placeholder user', async () => { - await protocol.saveMetaItem({ type: 'view', name: NAME, item: viewBody('A') }); + await protocol.saveMetaItem({ type: 'view', name: NAME, packageId: PKG, item: viewBody('A') }); const row = parentRow(); expect(row.created_by ?? null).toBeNull(); @@ -195,8 +199,8 @@ describe('#23033 — the sys_metadata row records who created it and who last ch }); it('the door reads the row back: listDrafts answers updatedBy from the draft row', async () => { - await protocol.saveMetaItem({ type: 'view', name: NAME, item: viewBody('A'), actor: ALICE, mode: 'draft' }); - await protocol.saveMetaItem({ type: 'view', name: NAME, item: viewBody('B'), actor: BOB, mode: 'draft' }); + await protocol.saveMetaItem({ type: 'view', name: NAME, packageId: PKG, item: viewBody('A'), actor: ALICE, mode: 'draft' }); + await protocol.saveMetaItem({ type: 'view', name: NAME, packageId: PKG, item: viewBody('B'), actor: BOB, mode: 'draft' }); const row = parentRow('draft'); expect(row.created_by).toBe(ALICE); diff --git a/packages/objectql/src/protocol-migrate-stored-draft-permission-grant.test.ts b/packages/objectql/src/protocol-migrate-stored-draft-permission-grant.test.ts index b738354aafc..a4332b47cbc 100644 --- a/packages/objectql/src/protocol-migrate-stored-draft-permission-grant.test.ts +++ b/packages/objectql/src/protocol-migrate-stored-draft-permission-grant.test.ts @@ -110,6 +110,7 @@ const object = { name: 'qa_widget', label: 'Widget', sharingModel: 'private', fields: { full_name: { name: 'full_name', type: 'text', label: 'Full name' } }, }; +const PKG = 'test_pkg'; const set = { name: 'qa_probe', label: 'Grant probe', objects: { qa_widget: { allowRead: true } } }; describe('migrate-stored re-saves a draft-only permission set whose object draft is gone', () => { @@ -127,6 +128,9 @@ describe('migrate-stored re-saves a draft-only permission set whose object draft await kernel.use(new ObjectQLPlugin({ ql: engine })); await kernel.bootstrap(); protocol = kernel.getService('protocol'); + // [#38174] A package-less create is refused (ADR-0070 D1): the drafts are + // saved into this writable, installed package. + engine.registry.installPackage({ id: PKG, name: PKG, version: '1.0.0' } as any, 'authored'); }); afterEach(async () => { if (kernel.getState() === 'running') await kernel.shutdown(); @@ -143,8 +147,8 @@ describe('migrate-stored re-saves a draft-only permission set whose object draft * at-rest shape of a set drafted before that key was retired. */ async function seed(): Promise { - expect((await protocol.saveMetaItem({ type: 'object', name: object.name, item: object, mode: 'draft' })).success).toBe(true); - expect((await protocol.saveMetaItem({ type: 'permission', name: set.name, item: set, mode: 'draft' })).success).toBe(true); + expect((await protocol.saveMetaItem({ type: 'object', name: object.name, item: object, mode: 'draft', packageId: PKG })).success).toBe(true); + expect((await protocol.saveMetaItem({ type: 'permission', name: set.name, item: set, mode: 'draft', packageId: PKG })).success).toBe(true); const [row] = rowsOf('permission', set.name); expect(row?.state).toBe('draft'); const legacy = { ...bodyOf(row!), managedBy: 'user' }; @@ -187,7 +191,7 @@ describe('migrate-stored re-saves a draft-only permission set whose object draft dropObjectDraft(); await protocol.migrateStoredMetadata({ apply: true, types: ['permission'] }); - const err = await protocol.publishMetaItem({ type: 'permission', name: set.name }).then(() => null, (e: any) => e); + const err = await protocol.publishMetaItem({ type: 'permission', name: set.name, packageId: PKG }).then(() => null, (e: any) => e); expect({ code: err?.code, status: err?.status }, String(err?.message)).toEqual({ code: 'INVALID_METADATA', status: 422 }); expect(err.issues.map((i: any) => i.path)).toEqual(['objects.qa_widget']); @@ -207,7 +211,7 @@ describe('migrate-stored re-saves a draft-only permission set whose object draft await seed(); dropObjectDraft(); - const err = await protocol.saveMetaItem({ type: 'permission', name: set.name, item: set, mode: 'draft' }) + const err = await protocol.saveMetaItem({ type: 'permission', name: set.name, item: set, mode: 'draft', packageId: PKG }) .then(() => null, (e: any) => e); expect({ code: err?.code, status: err?.status }, String(err?.message)).toEqual({ code: 'INVALID_METADATA', status: 422 }); diff --git a/packages/objectql/src/protocol-object-overlay-layer.test.ts b/packages/objectql/src/protocol-object-overlay-layer.test.ts index 642a446f68d..47295138334 100644 --- a/packages/objectql/src/protocol-object-overlay-layer.test.ts +++ b/packages/objectql/src/protocol-object-overlay-layer.test.ts @@ -210,16 +210,22 @@ async function persistOverlayRow(name: string, packageId?: string): Promise ({ ...r })); + return Array.from(s.rows.values()).map((r) => ({ ...r, ...(packageId ? {} : { package_id: null }) })); } +const LOOSE_SCRATCH_PKG = 'loose_scratch'; + /** The installed-package record `registerApp` writes before it registers the objects. */ const installPackage = (registry: SchemaRegistry, id: string) => registry.installPackage({ id, name: 'My App', version: '1.0.0' } as any, 'code'); diff --git a/packages/objectql/src/protocol-org-overlay-registry-gate.test.ts b/packages/objectql/src/protocol-org-overlay-registry-gate.test.ts index 859c7e90bad..be816608fbf 100644 --- a/packages/objectql/src/protocol-org-overlay-registry-gate.test.ts +++ b/packages/objectql/src/protocol-org-overlay-registry-gate.test.ts @@ -250,6 +250,9 @@ describe('#6602 — WRITE seam: applyRegistryWriteThrough refuses org-scoped row }); it('an ENV-WIDE write still writes through — #4521 read-your-writes is untouched', async () => { + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the env-wide + // row is planted, and the package-less save runs in place. + engine.plant(metaRow('view', viewBody('env_grid', 'Seeded grid'))); const saved = await protocol.saveMetaItem({ type: 'view', name: 'env_grid', @@ -264,6 +267,9 @@ describe('#6602 — WRITE seam: applyRegistryWriteThrough refuses org-scoped row }); it('an env-wide entry survives a LATER org write of the same name', async () => { + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the env-wide + // row is planted, and the package-less save runs in place. + engine.plant(metaRow('view', viewBody('shared_grid', 'Seeded grid'))); await protocol.saveMetaItem({ type: 'view', name: 'shared_grid', @@ -319,6 +325,9 @@ describe('#6602 — the delete chain needs no re-keying under this fix', () => { }); it('an env-wide delete still retires its plain-key entry (#5079 / #6687 intact)', async () => { + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the env-wide + // row is planted, and the package-less save runs in place. + engine.plant(metaRow('view', viewBody('env_grid', 'Seeded grid'))); await protocol.saveMetaItem({ type: 'view', name: 'env_grid', @@ -443,6 +452,9 @@ describe('#6780 — the registry heal is org-gated: an org DELETE never evicts t // ran the heal. Measured on `origin/main`: // delete receipt : {"success":true,"reset":false,"…nothing to delete."} // after org DELETE : undefined + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the env-wide + // row is planted, and the package-less save runs in place. + engine.plant(metaRow('view', viewBody('shared_grid', 'Seeded grid'))); await protocol.saveMetaItem({ type: 'view', name: 'shared_grid', item: viewBody('shared_grid', 'Env grid') }); expect((registry.getItem('view', 'shared_grid') as any)?.label).toBe('Env grid'); @@ -486,6 +498,9 @@ describe('#6780 — the registry heal is org-gated: an org DELETE never evicts t }); it('an ENV-WIDE delete of a runtime-only item still RETIRES the entry — #5079 tier 3 not regressed', async () => { + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the env-wide + // row is planted, and the package-less save runs in place. + engine.plant(metaRow('view', viewBody('env_grid', 'Seeded grid'))); await protocol.saveMetaItem({ type: 'view', name: 'env_grid', item: viewBody('env_grid', 'Env grid') }); expect(registry.getItem('view', 'env_grid')).toBeDefined(); diff --git a/packages/objectql/src/protocol-packageless-overlay-migration.test.ts b/packages/objectql/src/protocol-packageless-overlay-migration.test.ts index a575fe4963b..f194831fa2c 100644 --- a/packages/objectql/src/protocol-packageless-overlay-migration.test.ts +++ b/packages/objectql/src/protocol-packageless-overlay-migration.test.ts @@ -483,7 +483,10 @@ describe('[#28576] after the close: a package-less write onto a packaged item is }); it('CONTROL: a package-less save and DELETE of a name no package ships (environment metadata) still succeed', async () => { - const { protocol, rows } = await boot(); + const { engine, protocol, rows } = await boot(); + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the environment + // row is laid down through the engine, and the package-less save runs in place. + await storeRow(engine, ENV_VIEW, 'showcase_task', BASE_COLUMNS); await protocol.saveMetaItem({ type: 'view', name: ENV_VIEW, item: listBody(ENV_VIEW, 'showcase_task', UNBOUND_COLUMNS) } as any); expect(rows(ENV_VIEW)).toEqual([[null, 'active']]); await protocol.deleteMetaItem({ type: 'view', name: ENV_VIEW } as any); diff --git a/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts b/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts index 2fa9f271ab4..31ade7d995b 100644 --- a/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts +++ b/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts @@ -213,11 +213,18 @@ describe('the metadata doors read who holds a permission-set name through the re it('CONTROL: a name no package declares saves, for another package and for the environment', async () => { const stores: Stores = new Map(); - const { protocol } = await boot(stores); + const { engine, protocol } = await boot(stores); const packaged = await protocol.saveMetaItem({ type: 'permission', name: 'qa_other_editor', item: permissionSet('qa_other_editor'), packageId: OTHER, }); + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the + // environment's row is laid down through the engine, and the + // package-less save runs in place. + await engine.insert('sys_metadata', { + type: 'permission', name: 'qa_env_editor', package_id: null, state: 'active', version: 1, + metadata: JSON.stringify({ ...permissionSet('qa_env_editor'), label: 'Seeded' }), + }, { context: { isSystem: true } }); const environment = await protocol.saveMetaItem({ type: 'permission', name: 'qa_env_editor', item: permissionSet('qa_env_editor'), }); diff --git a/packages/objectql/src/protocol-picklist-served-roundtrip.test.ts b/packages/objectql/src/protocol-picklist-served-roundtrip.test.ts index 4d7207fd515..433fc80610c 100644 --- a/packages/objectql/src/protocol-picklist-served-roundtrip.test.ts +++ b/packages/objectql/src/protocol-picklist-served-roundtrip.test.ts @@ -142,6 +142,8 @@ function makeStubDriver() { } +const AUTHORED_PKG = 'test_pkg'; + describe('picklist — the protocol object read and the authoring door', () => { let engine: ObjectQL; let protocol: ObjectStackProtocolImplementation; @@ -164,11 +166,17 @@ describe('picklist — the protocol object read and the authoring door', () => { picklists: [{ name: 'industry', label: 'Industry', options: [{ label: 'Tech', value: 'tech' }] }], }); engine.registerApp({ id: 'com.test.more', name: 'more', picklistExtensions: [{ extend: 'industry', options: [{ label: 'Health', value: 'health' }] }] }); + // [#38174] A package-less create is refused (ADR-0070 D1): the object is + // authored into a writable package that depends on the picklist's packages. + engine.registry.installPackage({ + id: AUTHORED_PKG, name: AUTHORED_PKG, version: '1.0.0', + dependencies: { 'com.test.lists': '^1.0.0', 'com.test.more': '^1.0.0' }, + } as any, 'authored'); protocol = new ObjectStackProtocolImplementation(engine); }); it('an authored body (`picklist`, no `options`) saves, and the read serves the resolved options beside `picklist`', async () => { - await expect(protocol.saveMetaItem({ type: 'object', name: 'pp_obj', item: authored } as any)).resolves.toMatchObject({ success: true }); + await expect(protocol.saveMetaItem({ type: 'object', name: 'pp_obj', item: authored, packageId: AUTHORED_PKG } as any)).resolves.toMatchObject({ success: true }); const served: any = await protocol.getMetaItem({ type: 'object', name: 'pp_obj' } as any); expect(served.item.fields.industry).toMatchObject({ picklist: 'industry', @@ -177,7 +185,7 @@ describe('picklist — the protocol object read and the authoring door', () => { }); it('writing the SERVED body back is refused 422 INVALID_METADATA, naming the two keys — never stripped silently', async () => { - await protocol.saveMetaItem({ type: 'object', name: 'pp_obj', item: authored } as any); + await protocol.saveMetaItem({ type: 'object', name: 'pp_obj', item: authored, packageId: AUTHORED_PKG } as any); const served: any = await protocol.getMetaItem({ type: 'object', name: 'pp_obj' } as any); const err: any = await protocol.saveMetaItem({ type: 'object', name: 'pp_obj', item: served.item } as any).then(() => undefined, (e) => e); expect(err).toMatchObject({ code: 'INVALID_METADATA', status: 422 }); diff --git a/packages/objectql/src/protocol-publish-canonical-fold.test.ts b/packages/objectql/src/protocol-publish-canonical-fold.test.ts index 0a14d0f3c0a..0220a50436d 100644 --- a/packages/objectql/src/protocol-publish-canonical-fold.test.ts +++ b/packages/objectql/src/protocol-publish-canonical-fold.test.ts @@ -237,6 +237,8 @@ function makeMemoryDriver() { * cannot reach the gate cannot pin it. Groups A and B are indifferent to the * topology and share it rather than carrying a second one. */ +const PKG = 'test_pkg'; + async function makeProtocol() { const engine = new ObjectQL(); const { driver, stores } = makeMemoryDriver(); @@ -244,6 +246,10 @@ async function makeProtocol() { await engine.init(); engine.registry.registerObject(sysMetadataObject, 'test-package'); for (const o of [SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) engine.registry.registerObject(o as any, 'test-package'); + // [#38174] A package-less create is refused (ADR-0070 D1): an item's FIRST + // save names this writable, installed package; the later saves, publishes + // and rollbacks naming none address the one row it holds. + engine.registry.installPackage({ id: PKG, name: PKG, version: '1.0.0' } as any, 'authored'); const protocol = new ObjectStackProtocolImplementation(engine, undefined, 'env_prod'); const rows = () => Array.from(stores.get('sys_metadata')?.values() ?? []) as any[]; // [#8819] The history table, for the rollback verb in group D — it restores @@ -289,7 +295,7 @@ describe('#8769 · publish addressed with a manifest-absent plural resolves the it('`translations` promotes the draft written under `translation`', async () => { const { protocol, rows } = await makeProtocol(); await (protocol as any).saveMetaItem({ - type: 'translation', name: 'zh_cn', + type: 'translation', name: 'zh_cn', packageId: PKG, item: translationBody('A'), mode: 'draft', }); @@ -311,7 +317,7 @@ describe('#8769 · publish addressed with a manifest-absent plural resolves the it('CONTROL — the canonical spelling still publishes (a fold was added, not a lookup loosened)', async () => { const { protocol, rows } = await makeProtocol(); await (protocol as any).saveMetaItem({ - type: 'translation', name: 'zh_cn', + type: 'translation', name: 'zh_cn', packageId: PKG, item: translationBody('A'), mode: 'draft', }); @@ -331,7 +337,7 @@ describe('#8769 · publish addressed with a manifest-absent plural resolves the // `metaUrlSpellingRefusal` documents) and must still miss. const { protocol } = await makeProtocol(); await (protocol as any).saveMetaItem({ - type: 'translation', name: 'zh_cn', + type: 'translation', name: 'zh_cn', packageId: PKG, item: translationBody('A'), mode: 'draft', }); @@ -406,7 +412,7 @@ describe('#8769 · a plural-addressed publish cannot address around the overlay async function stageLockedActiveWithPendingDraft() { const { protocol, rows } = await makeProtocol(); await (protocol as any).saveMetaItem({ - type: 'view', name: 'case_grid', item: viewBody('v1'), mode: 'draft', + type: 'view', name: 'case_grid', item: viewBody('v1'), mode: 'draft', packageId: PKG, }); await (protocol as any).publishMetaItem({ type: 'view', name: 'case_grid' }); await (protocol as any).saveMetaItem({ @@ -483,7 +489,7 @@ describe('#8819 · a plural-addressed rollback cannot address around the overlay async function stageLockedActiveOverRestorableHistory(opts: { locked: boolean }) { const { protocol, rows, historyRows } = await makeProtocol(); await (protocol as any).saveMetaItem({ - type: 'view', name: 'case_grid', item: viewBody('v1'), mode: 'draft', + type: 'view', name: 'case_grid', item: viewBody('v1'), mode: 'draft', packageId: PKG, }); await (protocol as any).publishMetaItem({ type: 'view', name: 'case_grid' }); await (protocol as any).saveMetaItem({ diff --git a/packages/objectql/src/protocol-publish-rollback.test.ts b/packages/objectql/src/protocol-publish-rollback.test.ts index 9ee428df858..33f02daea87 100644 --- a/packages/objectql/src/protocol-publish-rollback.test.ts +++ b/packages/objectql/src/protocol-publish-rollback.test.ts @@ -51,6 +51,21 @@ function keyOf(w: Record) { return `${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}`; } +/** + * [#38174] A package-less create is refused (ADR-0070 D1). The views' first + * save runs in place over a package-less row laid down through the engine + * (this double's registry knows no objects, so a view named into a package + * would be judged outside its closure); the object and dashboard creates name + * this package, which the double's registry holds. + */ +const PKG = 'test_pkg'; + +/** The package-less `case_grid` row, as a row stored before the refusal is, with a body the saves replace. */ +const seedLooseView = (engine: any) => engine.insert('sys_metadata', { + type: 'view', name: 'case_grid', organization_id: null, package_id: null, state: 'active', version: 1, + metadata: JSON.stringify({ name: 'case_grid', type: 'grid', label: 'Seeded', columns: ['id'], object: 'case', viewKind: 'list' }), +}); + function makeStubEngine() { const rows = new Map(); const historyRows: HistoryRow[] = []; @@ -165,6 +180,8 @@ function makeStubEngine() { registry: { registerItem: () => {}, registerObject: () => {}, + // [#38174] The one installed (writable) package the first saves name. + getPackage: (id: string) => (id === PKG ? { manifest: { id } } : undefined), }, }; return { engine, rows, historyRows }; @@ -185,6 +202,7 @@ describe('publishMetaItem / rollbackMetaItem / diffMetaItem', () => { it('saveMetaItem with mode=draft creates a draft row, active read sees published', async () => { const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseView(engine); await protocol.saveMetaItem({ type: 'view', name: 'case_grid', item: sampleBody('Published'), @@ -209,6 +227,7 @@ describe('publishMetaItem / rollbackMetaItem / diffMetaItem', () => { it('publishMetaItem promotes the draft body to active and clears the draft', async () => { const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseView(engine); await protocol.saveMetaItem({ type: 'view', name: 'case_grid', item: sampleBody('v1'), @@ -231,6 +250,7 @@ describe('publishMetaItem / rollbackMetaItem / diffMetaItem', () => { it('publishMetaItem returns 404 no_draft when nothing is pending', async () => { const { engine } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseView(engine); await protocol.saveMetaItem({ type: 'view', name: 'case_grid', item: sampleBody('v1'), @@ -250,6 +270,7 @@ describe('publishMetaItem / rollbackMetaItem / diffMetaItem', () => { // had to disambiguate by sniffing keys. const { engine } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseView(engine); await protocol.saveMetaItem({ type: 'view', name: 'case_grid', item: sampleBody('v1'), @@ -275,6 +296,7 @@ describe('publishMetaItem / rollbackMetaItem / diffMetaItem', () => { it('getMetaItem(state=draft) returns the draft body when one is pending', async () => { const { engine } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseView(engine); await protocol.saveMetaItem({ type: 'view', name: 'case_grid', item: sampleBody('v1'), @@ -299,6 +321,7 @@ describe('publishMetaItem / rollbackMetaItem / diffMetaItem', () => { it('rollbackMetaItem restores a previous version with op=revert', async () => { const { engine, historyRows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseView(engine); await protocol.saveMetaItem({ type: 'view', name: 'case_grid', item: sampleBody('v1'), @@ -325,6 +348,7 @@ describe('publishMetaItem / rollbackMetaItem / diffMetaItem', () => { it('rollbackMetaItem returns 404 version_not_found for missing version', async () => { const { engine } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseView(engine); await protocol.saveMetaItem({ type: 'view', name: 'case_grid', item: sampleBody('v1'), @@ -340,6 +364,7 @@ describe('publishMetaItem / rollbackMetaItem / diffMetaItem', () => { it('diffMetaItem returns structured top-level key diff between two versions', async () => { const { engine } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseView(engine); await protocol.saveMetaItem({ type: 'view', name: 'case_grid', item: { name: 'case_grid', type: 'grid', label: 'A', columns: ['id'], object: 'case', viewKind: 'list' }, // [#7741] the inline arm requires the object binding pair @@ -369,7 +394,7 @@ describe('deleteMetaItem — storage teardown (dropStorage)', () => { engine.dropObjectSchema = vi.fn(); const protocol = new ObjectStackProtocolImplementation(engine); // [#8310] The runtime object door requires an authored OWD. - await protocol.saveMetaItem({ type: 'object', name, item: { name, label: name, sharingModel: 'private', fields: { title: { type: 'text' } } } }); + await protocol.saveMetaItem({ type: 'object', name, packageId: PKG, item: { name, label: name, sharingModel: 'private', fields: { title: { type: 'text' } } } }); return { engine, rows, protocol }; }; @@ -397,7 +422,7 @@ describe('deleteMetaItem — storage teardown (dropStorage)', () => { const { engine, rows } = makeStubEngine(); engine.dropObjectSchema = vi.fn(); const protocol = new ObjectStackProtocolImplementation(engine); - await protocol.saveMetaItem({ type: 'dashboard', name: 'sales', item: { name: 'sales', label: 'Sales', widgets: [] } }); + await protocol.saveMetaItem({ type: 'dashboard', name: 'sales', packageId: PKG, item: { name: 'sales', label: 'Sales', widgets: [] } }); await protocol.deleteMetaItem({ type: 'dashboard', name: 'sales', dropStorage: true }); expect(engine.dropObjectSchema).not.toHaveBeenCalled(); }); diff --git a/packages/objectql/src/protocol-recorded-by-null.test.ts b/packages/objectql/src/protocol-recorded-by-null.test.ts index e030e2494cf..e26e31bd4f4 100644 --- a/packages/objectql/src/protocol-recorded-by-null.test.ts +++ b/packages/objectql/src/protocol-recorded-by-null.test.ts @@ -190,6 +190,8 @@ function makeStubDriver() { // [#24668] Bound to `sys_metadata`, an object this harness registers: the overlay save door refuses a list view bound to an object that exists nowhere (it read `case`). const viewBody = (label: string, name = 'cases') => ({ name, type: 'grid', label, columns: ['id'], object: 'sys_metadata', viewKind: 'list' }); // [#7741] the inline arm requires the object binding pair +const PKG = 'test_pkg'; + describe('#4556 — protocol write paths store NULL, not the sentinel string', () => { let engine: ObjectQL; let protocol: ObjectStackProtocolImplementation; @@ -206,12 +208,15 @@ describe('#4556 — protocol write paths store NULL, not the sentinel string', ( engine.registry.registerObject(sysMetadataObject); engine.registry.registerObject(sysMetadataHistoryObject); await engine.insert('sys_user', { id: 'usr_alice', name: 'Alice' }, { context: { isSystem: true } } as any); + // [#38174] A package-less create is refused (ADR-0070 D1): the views are + // saved into this writable, installed package. + engine.registry.installPackage({ id: PKG, name: PKG, version: '1.0.0' } as any, 'authored'); protocol = new ObjectStackProtocolImplementation(engine); }); it('saveMetaItem with NO actor lands recorded_by = NULL', async () => { await protocol.saveMetaItem({ - type: 'view', name: 'cases', item: viewBody('A'), + type: 'view', name: 'cases', packageId: PKG, item: viewBody('A'), }); const rows = await historyRows(); @@ -224,7 +229,7 @@ describe('#4556 — protocol write paths store NULL, not the sentinel string', ( it('saveMetaItem WITH an actor still stores that user id', async () => { await protocol.saveMetaItem({ - type: 'view', name: 'cases', item: viewBody('A'), actor: 'usr_alice', + type: 'view', name: 'cases', packageId: PKG, item: viewBody('A'), actor: 'usr_alice', }); const rows = await historyRows(); expect(rows[0].recorded_by).toBe('usr_alice'); @@ -232,9 +237,9 @@ describe('#4556 — protocol write paths store NULL, not the sentinel string', ( it('deleteMetaItem with NO actor writes a tombstone with recorded_by = NULL', async () => { await protocol.saveMetaItem({ - type: 'view', name: 'cases', item: viewBody('A'), actor: 'usr_alice', + type: 'view', name: 'cases', packageId: PKG, item: viewBody('A'), actor: 'usr_alice', }); - await protocol.deleteMetaItem({ type: 'view', name: 'cases' }); + await protocol.deleteMetaItem({ type: 'view', name: 'cases', packageId: PKG }); const tombstone = (await historyRows()).find((h) => h.operation_type === 'delete'); expect(tombstone).toBeDefined(); @@ -244,9 +249,9 @@ describe('#4556 — protocol write paths store NULL, not the sentinel string', ( it('publishMetaItem with NO actor records the publish event with recorded_by = NULL', async () => { await protocol.saveMetaItem({ - type: 'view', name: 'cases', item: viewBody('draft'), mode: 'draft', + type: 'view', name: 'cases', packageId: PKG, item: viewBody('draft'), mode: 'draft', }); - await protocol.publishMetaItem({ type: 'view', name: 'cases' }); + await protocol.publishMetaItem({ type: 'view', name: 'cases', packageId: PKG }); const publishRow = (await historyRows()).find((h) => h.operation_type === 'publish'); expect(publishRow).toBeDefined(); @@ -257,13 +262,13 @@ describe('#4556 — protocol write paths store NULL, not the sentinel string', ( it('no history row on ANY path carries a value that is not a sys_user id', async () => { // The three authoring paths #4441 was bitten by: create, publish, delete. await protocol.saveMetaItem({ - type: 'view', name: 'a', item: viewBody('a', 'a'), mode: 'draft', + type: 'view', name: 'a', packageId: PKG, item: viewBody('a', 'a'), mode: 'draft', }); - await protocol.publishMetaItem({ type: 'view', name: 'a' }); + await protocol.publishMetaItem({ type: 'view', name: 'a', packageId: PKG }); await protocol.saveMetaItem({ - type: 'view', name: 'b', item: viewBody('b', 'b'), actor: 'usr_alice', + type: 'view', name: 'b', packageId: PKG, item: viewBody('b', 'b'), actor: 'usr_alice', }); - await protocol.deleteMetaItem({ type: 'view', name: 'b' }); + await protocol.deleteMetaItem({ type: 'view', name: 'b', packageId: PKG }); const rows = await historyRows(); expect(rows.length).toBeGreaterThan(0); @@ -298,7 +303,7 @@ describe('#4556 — protocol write paths store NULL, not the sentinel string', ( // field was target-less, so the guard skipped it whether or not the // exemption existed. Delete the exemption now and this goes red. await protocol.saveMetaItem({ - type: 'view', name: 'cases', item: viewBody('A'), actor: 'usr_not_a_row', + type: 'view', name: 'cases', packageId: PKG, item: viewBody('A'), actor: 'usr_not_a_row', }); const rows = await historyRows(); diff --git a/packages/objectql/src/protocol-registry-shadow.test.ts b/packages/objectql/src/protocol-registry-shadow.test.ts index fc8ca969ee2..df9ef784bad 100644 --- a/packages/objectql/src/protocol-registry-shadow.test.ts +++ b/packages/objectql/src/protocol-registry-shadow.test.ts @@ -243,7 +243,12 @@ describe('registry shadow — control-plane PUT → GET → DELETE keeps the art * protection declaration, ADR-0010 §3.3). */ async function overlayRowThenLockedArtifact(lock: 'full' | 'no-overlay'): Promise { - await protocol.saveMetaItem({ type: 'app', name: 'setup', item: { ...overlayBody } }); + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the + // package-less overlay row is laid down through the engine. + await engine.insert('sys_metadata', { + type: 'app', name: 'setup', organization_id: null, package_id: null, state: 'active', version: 1, + metadata: JSON.stringify({ ...overlayBody }), + }, { context: { isSystem: true } } as any); engine.registry.registerItem('app', artifactApp(lock), 'name', PKG); } diff --git a/packages/objectql/src/protocol-restore-publish-drained-connector-keys.test.ts b/packages/objectql/src/protocol-restore-publish-drained-connector-keys.test.ts index bdd56f0baa0..e6df7543426 100644 --- a/packages/objectql/src/protocol-restore-publish-drained-connector-keys.test.ts +++ b/packages/objectql/src/protocol-restore-publish-drained-connector-keys.test.ts @@ -174,6 +174,8 @@ function makeStubEngine() { registerObject: () => {}, // The connector door reads the registry for a shipped item of the name. getItem: () => undefined, + // [#38174] The one installed (writable) package the first saves name. + getPackage: (id: string) => (id === PKG ? { manifest: { id } } : undefined), }, }; return { engine, rows, historyRows }; @@ -185,6 +187,13 @@ const whereValueMatches = (actual: unknown, want: unknown): boolean => ? (want as { $in: unknown[] }).$in.includes(actual) : actual === want; +/** + * [#38174] A package-less create is refused (ADR-0070 D1): the connector's + * FIRST save names this package; the later saves, publish and rollbacks naming + * none address the one row it holds. + */ +const PKG = 'test_pkg'; + const LEGACY_AUTH_VALUE = 'TEST_PLACEHOLDER_LEGACY_AUTH_VALUE'; const DECLARED_AUTH = { type: 'bearer', credentialRef: 'VENDOR_API_TOKEN' }; @@ -210,7 +219,7 @@ describe('rollbackMetaItem and publishMetaItem write a connector live row withou it('rollbackMetaItem to a version that holds an undeclared `auth` key', async () => { const { engine, rows, historyRows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); - await protocol.saveMetaItem({ type: 'connector', name: 'vendor_api', item: connector('v1') }); + await protocol.saveMetaItem({ type: 'connector', name: 'vendor_api', item: connector('v1'), packageId: PKG }); await protocol.saveMetaItem({ type: 'connector', name: 'vendor_api', item: connector('v2') }); const v1 = historyRows.find((h) => h.type === 'connector' && h.version === 1)!; v1.metadata = withLegacyKey(v1.metadata!); @@ -226,7 +235,7 @@ describe('rollbackMetaItem and publishMetaItem write a connector live row withou it('publishMetaItem of a stored draft that holds an undeclared `auth` key', async () => { const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); - await protocol.saveMetaItem({ type: 'connector', name: 'vendor_api', item: connector('v1') }); + await protocol.saveMetaItem({ type: 'connector', name: 'vendor_api', item: connector('v1'), packageId: PKG }); await protocol.saveMetaItem({ type: 'connector', name: 'vendor_api', item: connector('v2-draft'), mode: 'draft' } as any); const draft = liveConnectorRow(rows, 'draft')!; draft.metadata = withLegacyKey(draft.metadata); @@ -243,7 +252,7 @@ describe('rollbackMetaItem and publishMetaItem write a connector live row withou it('CONTROL: rollbackMetaItem to a version with nothing undeclared restores it as written', async () => { const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); - await protocol.saveMetaItem({ type: 'connector', name: 'vendor_api', item: connector('v1') }); + await protocol.saveMetaItem({ type: 'connector', name: 'vendor_api', item: connector('v1'), packageId: PKG }); const v1Stored = liveConnectorRow(rows)!.metadata; await protocol.saveMetaItem({ type: 'connector', name: 'vendor_api', item: connector('v2') }); diff --git a/packages/objectql/src/protocol-save-meta-repo-path-real-engine.test.ts b/packages/objectql/src/protocol-save-meta-repo-path-real-engine.test.ts index 80c33d14ad3..b9d66f4d40e 100644 --- a/packages/objectql/src/protocol-save-meta-repo-path-real-engine.test.ts +++ b/packages/objectql/src/protocol-save-meta-repo-path-real-engine.test.ts @@ -137,6 +137,9 @@ function makeStubDriver() { return { driver, stores }; } +/** [#38174] A package-less create is refused (ADR-0070 D1): the view is saved into this writable, installed package. */ +const PKG = 'test_pkg'; + function viewBody(label: string) { // [#24668] Bound to `sys_metadata`, an object this harness registers: the overlay save door refuses a list view bound to an object that exists nowhere (it read `case`). return { name: 'cases', type: 'grid', label, columns: ['id'], object: 'sys_metadata', viewKind: 'list' }; // [#7741] the inline arm requires the object binding pair @@ -153,16 +156,17 @@ describe('saveMetaItem — repository write path against real ObjectQL (PR-10d.4 await engine.init(); engine.registry.registerObject(sysMetadataObject); for (const o of [SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) engine.registry.registerObject(o as any); + engine.registry.installPackage({ id: PKG, name: PKG, version: '1.0.0' } as any, 'authored'); protocol = new ObjectStackProtocolImplementation(engine); }); it('insert → update writes the second body and bumps version (id-based update on real engine)', async () => { await protocol.saveMetaItem({ - type: 'view', name: 'cases', + type: 'view', name: 'cases', packageId: PKG, item: viewBody('A'), }); await protocol.saveMetaItem({ - type: 'view', name: 'cases', + type: 'view', name: 'cases', packageId: PKG, item: viewBody('B'), }); @@ -178,13 +182,13 @@ describe('saveMetaItem — repository write path against real ObjectQL (PR-10d.4 it('stale parentVersion → 409 metadata_conflict; stored body unchanged', async () => { await protocol.saveMetaItem({ - type: 'view', name: 'cases', + type: 'view', name: 'cases', packageId: PKG, item: viewBody('Original'), }); await expect( protocol.saveMetaItem({ - type: 'view', name: 'cases', + type: 'view', name: 'cases', packageId: PKG, item: viewBody('Should not land'), parentVersion: 'sha256:stale', }), @@ -199,7 +203,7 @@ describe('saveMetaItem — repository write path against real ObjectQL (PR-10d.4 it('checksum column holds the full sha256: hash (71 chars)', async () => { await protocol.saveMetaItem({ - type: 'view', name: 'cases', + type: 'view', name: 'cases', packageId: PKG, item: viewBody('A'), }); const rows = await engine.find('sys_metadata', { @@ -212,7 +216,7 @@ describe('saveMetaItem — repository write path against real ObjectQL (PR-10d.4 it('plural type "views" is normalized to singular and stored as "view"', async () => { await protocol.saveMetaItem({ - type: 'views', name: 'cases', + type: 'views', name: 'cases', packageId: PKG, item: viewBody('Plural'), }); const rows = await engine.find('sys_metadata', { @@ -255,18 +259,19 @@ describe('deleteMetaItem — repository write path against real ObjectQL (PR-10d engine.registry.registerObject(sysMetadataObject); for (const o of [SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) engine.registry.registerObject(o as any); engine.registry.registerObject(sysMetadataHistoryObject); + engine.registry.installPackage({ id: PKG, name: PKG, version: '1.0.0' } as any, 'authored'); protocol = new ObjectStackProtocolImplementation(engine); }); it('deletes the overlay row AND appends a delete tombstone to sys_metadata_history', async () => { const save = await protocol.saveMetaItem({ - type: 'view', name: 'cases', + type: 'view', name: 'cases', packageId: PKG, item: viewBody('A'), actor: 'alice', }); expect((save as any).seq).toBe(1); const result = await protocol.deleteMetaItem({ - type: 'view', name: 'cases', actor: 'alice', + type: 'view', name: 'cases', packageId: PKG, actor: 'alice', }); expect(result.success).toBe(true); expect(result.reset).toBe(true); @@ -311,10 +316,10 @@ describe('deleteMetaItem — repository write path against real ObjectQL (PR-10d it('plural type "views" is normalized to singular for the tombstone', async () => { await protocol.saveMetaItem({ - type: 'view', name: 'cases', item: viewBody('A'), + type: 'view', name: 'cases', packageId: PKG, item: viewBody('A'), }); await protocol.deleteMetaItem({ - type: 'views', name: 'cases', + type: 'views', name: 'cases', packageId: PKG, }); const tombstone = await engine.findOne('sys_metadata_history', { where: { name: 'cases', operation_type: 'delete' }, diff --git a/packages/objectql/src/protocol-save-meta-repo-path.test.ts b/packages/objectql/src/protocol-save-meta-repo-path.test.ts index f1c2a27e20d..fa38c47a447 100644 --- a/packages/objectql/src/protocol-save-meta-repo-path.test.ts +++ b/packages/objectql/src/protocol-save-meta-repo-path.test.ts @@ -30,6 +30,17 @@ interface Row { created_at?: string; } +/** + * [#38174] A package-less create is refused (ADR-0070 D1): each view's first + * save runs in place over a package-less row laid down through the engine (this + * double's registry knows no objects, so a view named into a package would be + * judged outside its closure). The seeded body differs from every saved one. + */ +const seedLooseView = (engine: any, name: string) => engine.insert('sys_metadata', { + type: 'view', name, organization_id: null, package_id: null, state: 'active', version: 1, + metadata: JSON.stringify({ name, type: 'grid', label: 'Seeded', columns: ['id'], object: 'case', viewKind: 'list' }), +}); + function keyOf(w: Record) { return `${w.type}|${w.name}|${w.organization_id ?? '__env__'}`; } @@ -122,6 +133,7 @@ describe('saveMetaItem — repository write path (post PR-10d.6)', () => { // types unconditionally route through SysMetadataRepository.put. const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseView(engine, 'case_grid'); const result = await protocol.saveMetaItem({ type: 'view', name: 'case_grid', @@ -137,6 +149,7 @@ describe('saveMetaItem — repository write path (post PR-10d.6)', () => { it('repository path writes the checksum and surfaces seq', async () => { const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseView(engine, 'case_grid'); const body = { name: 'case_grid', type: 'grid', label: 'Cases', columns: ['id', 'title'], object: 'case', viewKind: 'list' }; const result = await protocol.saveMetaItem({ type: 'view', @@ -154,6 +167,7 @@ describe('saveMetaItem — repository write path (post PR-10d.6)', () => { it('repository path increments seq across writes and updates the body', async () => { const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseView(engine, 'v'); const r1 = await protocol.saveMetaItem({ type: 'view', name: 'v', item: { name: 'v', type: 'grid', label: 'A', columns: ['id'], object: 'case', viewKind: 'list' }, @@ -171,6 +185,7 @@ describe('saveMetaItem — repository write path (post PR-10d.6)', () => { it('repository path returns 409 on parentVersion mismatch', async () => { const { engine } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseView(engine, 'v'); // First write establishes a HEAD. await protocol.saveMetaItem({ type: 'view', name: 'v', @@ -192,6 +207,7 @@ describe('saveMetaItem — repository write path (post PR-10d.6)', () => { it('repository path no-ops when body is identical (idempotent put)', async () => { const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseView(engine, 'v'); const body = { name: 'v', type: 'grid', label: 'A', columns: ['id'], object: 'case', viewKind: 'list' }; const r1 = await protocol.saveMetaItem({ type: 'view', name: 'v', item: body, @@ -209,6 +225,7 @@ describe('saveMetaItem — repository write path (post PR-10d.6)', () => { it('plural type (e.g. "views") is normalized to singular before the repo gate (rubber-duck #5)', async () => { const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseView(engine, 'case_grid'); // 'views' must succeed — the repo only knows the singular form, so // without normalization this would throw 403 not_overridable. const result = await protocol.saveMetaItem({ @@ -252,6 +269,7 @@ describe('saveMetaItem — repository write path (post PR-10d.6)', () => { it('on ConflictError the overlay row body is unchanged (rubber-duck #3 invariant)', async () => { const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseView(engine, 'cases'); // Establish a HEAD overlay. await protocol.saveMetaItem({ @@ -409,6 +427,7 @@ describe('#16225 a `sys_metadata` read is not answered from the journal tables', it('serves the store row only, never the history/audit rows the same save wrote', async () => { const { engine, tableOf } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseView(engine, 'case_grid'); const result = await protocol.saveMetaItem({ type: 'view', diff --git a/packages/objectql/src/protocol-sentinel-owner-draft-save-address.test.ts b/packages/objectql/src/protocol-sentinel-owner-draft-save-address.test.ts index 4920450e35c..1a675d6352b 100644 --- a/packages/objectql/src/protocol-sentinel-owner-draft-save-address.test.ts +++ b/packages/objectql/src/protocol-sentinel-owner-draft-save-address.test.ts @@ -239,6 +239,13 @@ describe('#23712 — a draft save naming no package of an object its package-les stores: Stores, drops: string[], rows: readonly string[], drafts: ReadonlyArray, ): Promise { const k0 = await boot(stores, drops); + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the + // package-less row is laid down through the engine first, and the + // package-less save runs in place over it. + await k0.engine.insert('sys_metadata', { + type: 'object', name: NAME, package_id: null, state: 'active', version: 1, + metadata: JSON.stringify(gadgetBody('Gadget seeded')), + }, SYSTEM); expect((await k0.protocol.saveMetaItem({ type: 'object', name: NAME, item: gadgetBody('Gadget unbound') })).success) .toBe(true); await k0.engine.insert(NAME, { name: 'rec-1' }, SYSTEM); diff --git a/packages/objectql/src/protocol-sentinel-owner-package-save-refusal.test.ts b/packages/objectql/src/protocol-sentinel-owner-package-save-refusal.test.ts index 67eb30d4618..7ee7fc712a9 100644 --- a/packages/objectql/src/protocol-sentinel-owner-package-save-refusal.test.ts +++ b/packages/objectql/src/protocol-sentinel-owner-package-save-refusal.test.ts @@ -255,9 +255,20 @@ describe('#23514 — a save naming a package beside an object its package-less d }; } + /** + * [#38174] A package-less CREATE is refused (ADR-0070 D1): the package-less + * row is laid down through the engine first, so the package-less save + * below runs in place over it (the live save path, not a boot hydration). + */ + const insertLooseRow = (k: Booted) => k.engine.insert('sys_metadata', { + type: 'object', name: NAME, package_id: null, state: 'active', version: 1, + metadata: JSON.stringify(gadgetBody('Gadget seeded')), + }, SYSTEM); + /** The object saved naming no package, with two records in its table. */ async function seedPackagelessOwner(stores: Stores, drops: string[]): Promise { const k = await boot(stores, drops); + await insertLooseRow(k); const res = await save(k, undefined, 'Gadget unbound'); expect(res.success).toBe(true); await k.engine.insert(NAME, { name: 'rec-1' }, SYSTEM); @@ -827,6 +838,7 @@ describe('#23514 — a save naming a package beside an object its package-less d type: 'object', name: NAME, packageId: Q, mode: 'draft', item: gadgetBody('Gadget Q draft'), })).success).toBe(true); // Then the package-less definition, which the sentinel owns, with two records. + await insertLooseRow(k); expect((await save(k, undefined, 'Gadget unbound')).success).toBe(true); await k.engine.insert(NAME, { name: 'rec-1' }, SYSTEM); await k.engine.insert(NAME, { name: 'rec-2' }, SYSTEM); diff --git a/packages/objectql/src/protocol-validation-rule-copy-save-refusal.test.ts b/packages/objectql/src/protocol-validation-rule-copy-save-refusal.test.ts index 594fc9e9e73..a4624e53f48 100644 --- a/packages/objectql/src/protocol-validation-rule-copy-save-refusal.test.ts +++ b/packages/objectql/src/protocol-validation-rule-copy-save-refusal.test.ts @@ -79,8 +79,11 @@ function keyOf(w: Record) { } /** A `sys_metadata` store over a REAL {@link SchemaRegistry}. */ +const TENANT_PKG = 'tenant_pkg'; + function makeHost() { const registry = new SchemaRegistry({ multiTenant: false, searchCompanion: false } as never); + registry.installPackage({ id: TENANT_PKG, name: TENANT_PKG, version: '1.0.0' } as any, 'authored'); const rows = new Map(); let nextId = 0; const findRow = (w: Record) => { @@ -135,7 +138,10 @@ function makeHost() { /** The tenant's object saved, then extended by a code package with one rule. */ async function seeded() { const host = makeHost(); - await host.protocol.saveMetaItem({ type: 'object', name: OBJ, item: clone(AUTHORED) } as never); + // [#38174] A package-less create is refused (ADR-0070 D1): the tenant's + // object is saved into its writable package; the saves below naming none + // address that one row. + await host.protocol.saveMetaItem({ type: 'object', name: OBJ, item: clone(AUTHORED), packageId: TENANT_PKG } as never); host.registry.registerObject({ name: OBJ, validations: [extRule()] } as never, EXT_PKG, undefined, 'extend'); return host; } diff --git a/packages/objectql/src/protocol-view-identity-overlay.test.ts b/packages/objectql/src/protocol-view-identity-overlay.test.ts index 706947ec07a..36adbdafc36 100644 --- a/packages/objectql/src/protocol-view-identity-overlay.test.ts +++ b/packages/objectql/src/protocol-view-identity-overlay.test.ts @@ -42,6 +42,16 @@ const personalization = { sort: [{ id: '29200fa8-c416-471e-9ca3-913f9308ad89', field: 'estimate_hours', order: 'desc' }], }; +/** + * [#38174] A package-less create is refused (ADR-0070 D1), and this stub + * registry marks no entry a package artifact, so a save that must land runs in + * place over a package-less row laid down through the engine first (the + * personalization row's at-rest shape, as the 3777 repro stored it). + */ +const seedLooseView = (engine: any, name: string, body: Record) => engine.insert('sys_metadata', { + type: 'view', name, organization_id: null, package_id: null, state: 'active', metadata: JSON.stringify(body), +}); + interface Row { id: string; type: string; @@ -140,6 +150,7 @@ describe('view overlay identity (#2555)', () => { it('write path: saveMetaItem inherits viewKind/object/label from the shadowed registry entry', async () => { const { engine, rows } = makeStubEngine({ 'showcase_task.default': flattened }); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseView(engine, 'showcase_task.default', { ...personalization, sort: [] }); const result = await protocol.saveMetaItem({ type: 'view', name: 'showcase_task.default', @@ -228,6 +239,10 @@ describe('view overlay identity (#2555)', () => { it('write path accepts a well-formed ViewItem record', async () => { const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseView(engine, 'crm_lead.all', { + name: 'crm_lead.all', object: 'crm_lead', viewKind: 'list', label: 'Seeded', + config: { type: 'grid', columns: ['name'], data: { provider: 'object', object: 'crm_lead' } }, + }); const result = await protocol.saveMetaItem({ type: 'view', name: 'crm_lead.all', @@ -326,6 +341,7 @@ describe('view overlay identity (#2555)', () => { // platform itself writes. `personalization` is the captured console PUT. const { engine, rows } = makeStubEngine({ 'showcase_task.default': flattened }); const protocol = new ObjectStackProtocolImplementation(engine); + await seedLooseView(engine, 'showcase_task.default', { ...personalization, sort: [] }); const result = await protocol.saveMetaItem({ type: 'view', name: 'showcase_task.default', diff --git a/packages/objectql/src/protocol-writepath-object-ownership.test.ts b/packages/objectql/src/protocol-writepath-object-ownership.test.ts index 16df550cf70..4b3d531b72e 100644 --- a/packages/objectql/src/protocol-writepath-object-ownership.test.ts +++ b/packages/objectql/src/protocol-writepath-object-ownership.test.ts @@ -165,6 +165,18 @@ function makeHarness() { return { registry, protocol, rows, historyRows, synced, engine }; } +/** + * [#38174] A package-less CREATE is refused (ADR-0070 D1): the package-less row + * is laid down through the engine (a body the saves below then replace in + * place), as a row stored before that refusal is. + */ +async function seedLooseRow(engine: any, name: string): Promise { + await engine.insert('sys_metadata', { + type: 'object', name, organization_id: null, package_id: null, state: 'active', version: 1, + metadata: JSON.stringify({ ...objectBody(name), label: 'Seeded' }), + }, { context: { isSystem: true } }); +} + function objectBody(name: string, extra?: Record): ServiceObject { return { name, @@ -199,7 +211,8 @@ describe('#4636 — object write path keys ownership by the real package id', () }); it('keeps the sentinel for a package-less write', async () => { - const { registry, protocol } = makeHarness(); + const { registry, protocol, engine } = makeHarness(); + await seedLooseRow(engine, 'global_invoice'); await protocol.saveMetaItem({ type: 'object', @@ -332,7 +345,8 @@ describe('#4636 — cloud#970 counter-example: a freshly created app stays edita describe('#4636 — rollback re-registers under the row\'s own package binding', () => { it('resolves the ownership key from the ROW: a package-less rollback keeps the sentinel', async () => { - const { registry, protocol } = makeHarness(); + const { registry, protocol, engine } = makeHarness(); + await seedLooseRow(engine, 'global_invoice'); await protocol.saveMetaItem({ type: 'object', diff --git a/packages/objectql/src/publish-meta-response-conformance.test.ts b/packages/objectql/src/publish-meta-response-conformance.test.ts index 9b1b92a7f4c..53eb18c24a5 100644 --- a/packages/objectql/src/publish-meta-response-conformance.test.ts +++ b/packages/objectql/src/publish-meta-response-conformance.test.ts @@ -163,9 +163,14 @@ async function makeProtocol() { // [#35143] The object the advisory flow's delete node is bound to: the flow // door refuses a CRUD node bound to an object the deployment does not serve. engine.registry.registerObject({ name: 'audit_logs', label: 'Audit logs', fields: { name: { type: 'text', label: 'Name' } } } as any, 'test-package'); + // The package depends on the harness's own (`test-package`), which owns `audit_logs`. + engine.registry.installPackage({ id: PKG, name: PKG, version: '1.0.0', dependencies: { 'test-package': '^1.0.0' } } as any, 'authored'); return new ObjectStackProtocolImplementation(engine); } +/** [#38174] A package-less create is refused (ADR-0070 D1): new items are saved into this writable package. */ +const PKG = 'test_pkg'; + // [#24668] Bound to `sys_metadata`, an object this harness registers: the overlay save door refuses a list view bound to an object that exists nowhere (it read `case`). const viewBody = (label: string) => ({ name: 'cases', type: 'grid', label, columns: ['id'], object: 'sys_metadata', viewKind: 'list' }); // [#7741] the inline arm requires the object binding pair @@ -196,8 +201,8 @@ async function stageAndPublish( // any type has. const scope = opts.org === undefined ? null : opts.org; const orgArg = scope === null ? {} : { organizationId: scope }; - await (p as any).saveMetaItem({ type, name, ...orgArg, item, mode: 'draft' }); - return (p as any).publishMetaItem({ type, name, ...orgArg }); + await (p as any).saveMetaItem({ type, name, ...orgArg, item, mode: 'draft', packageId: PKG }); + return (p as any).publishMetaItem({ type, name, ...orgArg, packageId: PKG }); } /** Keys the producer emitted that the schema refused to carry through. */ @@ -522,12 +527,12 @@ describe('publishMetaItem carries the runtime authoring gate\'s advisories (#917 // Staging the draft succeeds — a draft save is never gated (D1). await (p as any).saveMetaItem({ - type: 'flow', name: 'leave_approval', item: brokenApproval, mode: 'draft', + type: 'flow', name: 'leave_approval', item: brokenApproval, mode: 'draft', packageId: PKG, }); // Promoting it is where the gate runs, and it refuses with the same // envelope the save door's direct-active refusal carries. await expect( - (p as any).publishMetaItem({ type: 'flow', name: 'leave_approval' }), + (p as any).publishMetaItem({ type: 'flow', name: 'leave_approval', packageId: PKG }), ).rejects.toMatchObject({ code: 'INVALID_METADATA', status: 422 }); }); diff --git a/packages/objectql/src/save-meta-response-conformance.test.ts b/packages/objectql/src/save-meta-response-conformance.test.ts index fe931c0a61f..6af8c6e7500 100644 --- a/packages/objectql/src/save-meta-response-conformance.test.ts +++ b/packages/objectql/src/save-meta-response-conformance.test.ts @@ -168,9 +168,14 @@ async function makeProtocol() { // [#35143] The object the advisory flow's delete node is bound to: the flow // door refuses a CRUD node bound to an object the deployment does not serve. engine.registry.registerObject({ name: 'audit_logs', label: 'Audit logs', fields: { name: { type: 'text', label: 'Name' } } } as any, 'test-package'); + // The package depends on the harness's own (`test-package`), which owns `audit_logs`. + engine.registry.installPackage({ id: PKG, name: PKG, version: '1.0.0', dependencies: { 'test-package': '^1.0.0' } } as any, 'authored'); return new ObjectStackProtocolImplementation(engine); } +/** [#38174] A package-less create is refused (ADR-0070 D1): new items are saved into this writable package. */ +const PKG = 'test_pkg'; + // [#24668] Bound to `sys_metadata`, an object this harness registers: the overlay save door refuses a list view bound to an object that exists nowhere (it read `case`). const viewBody = (label: string) => ({ name: 'cases', type: 'grid', label, columns: ['id'], object: 'sys_metadata', viewKind: 'list' }); // [#7741] the inline arm requires the object binding pair @@ -184,7 +189,7 @@ describe('saveMetaItem response conforms to SaveMetaItemResponseSchema (#5745)', it('publish-mode save: parses green and strips nothing', async () => { const p = await makeProtocol(); const raw: any = await p.saveMetaItem({ - type: 'view', name: 'cases', item: viewBody('A'), + packageId: PKG, type: 'view', name: 'cases', item: viewBody('A'), }); expect(strippedKeys(raw)).toEqual([]); @@ -201,7 +206,7 @@ describe('saveMetaItem response conforms to SaveMetaItemResponseSchema (#5745)', it('draft-mode save: state is "draft" and still strips nothing', async () => { const p = await makeProtocol(); const raw: any = await p.saveMetaItem({ - type: 'view', name: 'cases', item: viewBody('D'), mode: 'draft', + packageId: PKG, type: 'view', name: 'cases', item: viewBody('D'), mode: 'draft', }); expect(strippedKeys(raw)).toEqual([]); @@ -213,7 +218,7 @@ describe('saveMetaItem response conforms to SaveMetaItemResponseSchema (#5745)', p.registerMutationProjector('view', async () => { throw new Error('boom-from-projector'); }); const raw: any = await p.saveMetaItem({ - type: 'view', name: 'cases', item: viewBody('P'), + packageId: PKG, type: 'view', name: 'cases', item: viewBody('P'), }); expect(Object.keys(raw)).toContain('projectionApplied'); @@ -228,7 +233,7 @@ describe('saveMetaItem response conforms to SaveMetaItemResponseSchema (#5745)', it('no projector registered → projectionApplied is absent, which is why it alone is optional', async () => { const p = await makeProtocol(); const raw: any = await p.saveMetaItem({ - type: 'view', name: 'cases', item: viewBody('N'), + packageId: PKG, type: 'view', name: 'cases', item: viewBody('N'), }); expect(raw.projectionApplied).toBeUndefined(); @@ -314,7 +319,7 @@ describe('saveMetaItem carries the runtime authoring gate\'s advisories (#4717 // Env-wide, not org-scoped: the protocol refuses every org-scoped // write (ADR-0131 D6), so an org-scoped write is refused 403 // NOT_OVERRIDABLE long before the authoring gate runs. - type: 'flow', name: 'nightly_purge', item: advisoryFlow(), + type: 'flow', name: 'nightly_purge', item: advisoryFlow(), packageId: PKG, }); // The write succeeded — this rides a 2xx, which is the whole point of @@ -358,7 +363,7 @@ describe('saveMetaItem carries the runtime authoring gate\'s advisories (#4717 it('zero advisories changes nothing: the key is absent, not empty', async () => { const p = await makeProtocol(); const raw: any = await p.saveMetaItem({ - type: 'flow', name: 'bounded_purge', item: cleanFlow(), + packageId: PKG, type: 'flow', name: 'bounded_purge', item: cleanFlow(), }); expect(raw.success).toBe(true); @@ -378,7 +383,7 @@ describe('saveMetaItem carries the runtime authoring gate\'s advisories (#4717 it('a draft save runs no rules, so it reports no advisories', async () => { const p = await makeProtocol(); const raw: any = await p.saveMetaItem({ - type: 'flow', name: 'nightly_purge', + packageId: PKG, type: 'flow', name: 'nightly_purge', item: advisoryFlow(), mode: 'draft', }); @@ -416,7 +421,7 @@ describe('saveMetaItem carries the runtime authoring gate\'s advisories (#4717 await expect( p.saveMetaItem({ - type: 'flow', name: 'leave_approval', item: brokenApproval, + packageId: PKG, type: 'flow', name: 'leave_approval', item: brokenApproval, }), ).rejects.toMatchObject({ code: 'INVALID_METADATA', status: 422 }); }); @@ -437,7 +442,7 @@ describe('saveMetaItem carries the runtime authoring gate\'s advisories (#4717 it('GUARD (green either way): a clean view save is untouched by the new field', async () => { const p = await makeProtocol(); const raw: any = await p.saveMetaItem({ - type: 'view', name: 'cases', item: viewBody('A'), + packageId: PKG, type: 'view', name: 'cases', item: viewBody('A'), }); expect('advisories' in raw).toBe(false); diff --git a/packages/rest/src/meta-diff-default-range-labels.test.ts b/packages/rest/src/meta-diff-default-range-labels.test.ts index 3fa372b151c..f2aa7ff4fef 100644 --- a/packages/rest/src/meta-diff-default-range-labels.test.ts +++ b/packages/rest/src/meta-diff-default-range-labels.test.ts @@ -109,6 +109,9 @@ async function boot() { owner: { name: 'owner', label: 'Owner', type: 'text' }, }, } as any, TEST_PACKAGE_ID); + // [#38174] The fixtures are saved into an installed, writable package: a + // package-less create is refused (ADR-0070 D1). + engine.registry.installPackage({ id: TEST_PACKAGE_ID, name: TEST_PACKAGE_ID, version: '1.0.0' } as any, 'code'); await engine.syncSchemas(); const protocol = new ObjectStackProtocolImplementation(engine as any); @@ -134,7 +137,7 @@ async function boot() { const res = await as('system', 'PUT', `${META}/:type/:name`, { path: `${META}/${type}/${body.name}`, params: { type, name: body.name }, - query: mode === 'draft' ? { mode: 'draft' } : {}, + query: mode === 'draft' ? { mode: 'draft', package: TEST_PACKAGE_ID } : { package: TEST_PACKAGE_ID }, body, }); if (res.statusCode !== 200) throw new Error(`seeding ${type}/${body.name} failed: ${JSON.stringify(res.body)}`); diff --git a/packages/rest/src/meta-draft-head-package-inheritance.test.ts b/packages/rest/src/meta-draft-head-package-inheritance.test.ts index 1094cc55151..025d850f364 100644 --- a/packages/rest/src/meta-draft-head-package-inheritance.test.ts +++ b/packages/rest/src/meta-draft-head-package-inheritance.test.ts @@ -250,7 +250,8 @@ describe('[#22128] a package-less draft of a package-owned item: one head row fo it('control: an env-local item with no package is unchanged — unbound rows, unpinned saves accepted, the read serves the receipt\'s token', async () => { const h = await boot(); - ok(await h.save(view('live'))); + // [#38174] the loose row is seeded: a package-less create is refused (ADR-0070 D1). + await h.seed('active', null, view('live')); const first = ok(await h.save(view('draft 1'), { mode: 'draft' })); ok(await h.save(view('draft 2'), { mode: 'draft' })); expect(await h.stored('draft')).toEqual([{ label: 'draft 2', packageId: null }]); @@ -268,6 +269,9 @@ describe('[#22128] a package-less draft of a package-owned item: one head row fo describe('[#22128] `?package=all`: the read resolves `all` the way the save does', () => { it('active: the read\'s `version` is the token the save compares against; `If-None-Match: *` is refused only because a row is there', async () => { const h = await boot(); + // [#38174] the loose row is seeded (a package-less create is refused, + // ADR-0070 D1); the save folding `all` then writes it in place. + await h.seed('active', null, view('seeded')); const created = ok(await h.save(view('live'), { package: 'all' })); // The save folds `all` to the env-local overlay. expect(await h.stored('active')).toEqual([{ label: 'live', packageId: null }]); @@ -428,6 +432,8 @@ describe('[#23165] a save or a delete naming no package addresses the one packag it('control: an item with no package binding is saved and deleted at the package-unbound row, as before', async () => { const h = await boot(); + // [#38174] the loose row is seeded: a package-less create is refused (ADR-0070 D1). + await h.seed('active', null, view('seeded')); ok(await h.save(view('plain'))); expect(await h.stored('active')).toEqual([{ label: 'plain', packageId: null }]); expect(ok(await h.remove()).reset).toBe(true); @@ -455,7 +461,8 @@ describe('[#23495] the draft doors naming no package act on the draft the draft /** Drafts `[package-unbound, PKG]` over an active row bound to `PKG`. */ const stateOne = async () => { const h = await boot(); - ok(await h.save(view('stale'), { mode: 'draft' })); + // [#38174] the loose row is seeded: a package-less create is refused (ADR-0070 D1). + await h.seed('draft', null, view('stale')); ok(await h.save(view('live'), { package: PKG })); ok(await h.save(view('pending'), { mode: 'draft', package: PKG })); return h; @@ -595,7 +602,8 @@ describe('[#23657] an item never published into a package: the draft save naming expect(bound.message).toContain(`(package=${Q})`); const u = await boot(); - ok(await u.save(view('plain'), { mode: 'draft' })); + // [#38174] the loose row is seeded: a package-less create is refused (ADR-0070 D1). + await u.seed('draft', null, view('plain')); const unbound = ok(await u.remove({ state: 'draft' })); expect(unbound.message).toBe(`Draft discarded — view/case_grid. [seq=${unbound.seq}]`); }, 60_000); @@ -639,13 +647,14 @@ describe('[#23657] an item never published into a package: the draft save naming it('control: a package-unbound draft is the address whatever packages\' drafts sit beside it, as for the publish and the discard', async () => { const only = await boot(); - ok(await only.save(view('plain'), { mode: 'draft' })); + // [#38174] the loose row is seeded: a package-less create is refused (ADR-0070 D1). + await only.seed('draft', null, view('plain')); const saved = ok(await only.save(view('plain 2'), { mode: 'draft' })); expect(saved.message).not.toContain('package='); expect(await only.stored('draft')).toEqual([{ label: 'plain 2', packageId: null }]); const beside = await boot(); - ok(await beside.save(view('plain'), { mode: 'draft' })); + await beside.seed('draft', null, view('plain')); ok(await beside.save(view('q'), { mode: 'draft', package: Q })); ok(await beside.save(view('r'), { mode: 'draft', package: R })); ok(await beside.save(view('plain 2'), { mode: 'draft' })); @@ -668,7 +677,8 @@ describe('[#23715] the strict draft read naming no package serves its content fr const ORDERS = { 'the package-unbound draft saved first': async () => { const h = await boot(); - ok(await h.save(view('unbound'), { mode: 'draft' })); + // [#38174] the loose row is seeded: a package-less create is refused (ADR-0070 D1). + await h.seed('draft', null, view('unbound')); ok(await h.save(view('q'), { mode: 'draft', package: Q })); return h; }, diff --git a/packages/rest/src/meta-draft-read-author-exemption.test.ts b/packages/rest/src/meta-draft-read-author-exemption.test.ts index 4c96668dbd1..9f34e4bca26 100644 --- a/packages/rest/src/meta-draft-read-author-exemption.test.ts +++ b/packages/rest/src/meta-draft-read-author-exemption.test.ts @@ -135,6 +135,9 @@ async function boot() { engine.registry.registerObject(SysMetadata as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataHistoryObject as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataAuditObject as any, TEST_PACKAGE_ID); + // [#38174] The fixtures are saved into an installed, writable package: a + // package-less create is refused (ADR-0070 D1). + engine.registry.installPackage({ id: TEST_PACKAGE_ID, name: TEST_PACKAGE_ID, version: '1.0.0' } as any, 'code'); await engine.syncSchemas(); const protocol = new ObjectStackProtocolImplementation(engine as any); @@ -164,7 +167,7 @@ async function boot() { ['system', PAYROLL, {}], ['system', { ...PAYROLL, label: 'Payroll (draft)' }, { mode: 'draft' }], ] as const) { - const res = await call(who, 'PUT', '', item.name, query, item); + const res = await call(who, 'PUT', '', item.name, { ...query, package: TEST_PACKAGE_ID }, item); if (res.statusCode !== 200) throw new Error(`seeding ${item.name} failed: ${JSON.stringify(res.body)}`); } return { engine, call }; diff --git a/packages/rest/src/meta-draft-read-builder-gate.test.ts b/packages/rest/src/meta-draft-read-builder-gate.test.ts index e8620352e3d..d279eaa1d40 100644 --- a/packages/rest/src/meta-draft-read-builder-gate.test.ts +++ b/packages/rest/src/meta-draft-read-builder-gate.test.ts @@ -165,6 +165,9 @@ async function boot() { amount: { type: 'number', label: 'Amount' }, }, } as any, TEST_PACKAGE_ID); + // [#38174] The fixtures are saved into an installed, writable package: a + // package-less create is refused (ADR-0070 D1). + engine.registry.installPackage({ id: TEST_PACKAGE_ID, name: TEST_PACKAGE_ID, version: '1.0.0' } as any, 'code'); await engine.syncSchemas(); const protocol = new ObjectStackProtocolImplementation(engine as any); @@ -203,7 +206,7 @@ async function boot() { as(who, 'POST', '/api/v1/analytics/dataset/query', { path: '/api/v1/analytics/dataset/query', body, query }); const save = async (type: string, item: { name: string }, query: Record) => { const res = await as('system', 'PUT', `${META}/:type/:name`, { - path: `${META}/${type}/${item.name}`, params: { type, name: item.name }, query, body: item, + path: `${META}/${type}/${item.name}`, params: { type, name: item.name }, query: { ...query, package: TEST_PACKAGE_ID }, body: item, }); if (res.statusCode !== 200) throw new Error(`seeding ${type}/${item.name} failed: ${JSON.stringify(res.body)}`); }; diff --git a/packages/rest/src/meta-flow-save-retired-spelling.test.ts b/packages/rest/src/meta-flow-save-retired-spelling.test.ts index cf1ae10dc97..b5165264aee 100644 --- a/packages/rest/src/meta-flow-save-retired-spelling.test.ts +++ b/packages/rest/src/meta-flow-save-retired-spelling.test.ts @@ -104,6 +104,9 @@ async function boot() { engine.registry.registerObject(SysMetadata as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataHistoryObject as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataAuditObject as any, TEST_PACKAGE_ID); + // [#38174] A new flow is saved into an installed, writable package: a + // package-less create is refused (ADR-0070 D1). + engine.registry.installPackage({ id: TEST_PACKAGE_ID, name: TEST_PACKAGE_ID, version: '1.0.0' } as any, 'code'); await engine.syncSchemas(); const protocol = new ObjectStackProtocolImplementation(engine as any); @@ -200,7 +203,7 @@ describe('[#23775] PUT /meta/flow/:name — a retired spelling on a NEW flow is it('a new flow in the canonical spelling saves', async () => { const h = await boot(); - ok(await h.save(canonical())); + ok(await h.save(canonical(), { package: TEST_PACKAGE_ID })); expect(await h.stored('active')).toEqual([canonical()]); }); diff --git a/packages/rest/src/meta-history-diff-authoring-door.test.ts b/packages/rest/src/meta-history-diff-authoring-door.test.ts index 2912dec3c09..9a742094d0a 100644 --- a/packages/rest/src/meta-history-diff-authoring-door.test.ts +++ b/packages/rest/src/meta-history-diff-authoring-door.test.ts @@ -190,6 +190,9 @@ async function boot() { amount: { type: 'number', label: 'Amount' }, }, } as any, TEST_PACKAGE_ID); + // [#38174] The fixtures are saved into an installed, writable package: a + // package-less create is refused (ADR-0070 D1). + engine.registry.installPackage({ id: TEST_PACKAGE_ID, name: TEST_PACKAGE_ID, version: '1.0.0' } as any, 'code'); await engine.syncSchemas(); const protocol: any = new ObjectStackProtocolImplementation(engine as any); @@ -218,7 +221,7 @@ async function boot() { const drafts = (who: CallerName) => as(who, 'GET', `${META}/_drafts`, { path: `${META}/_drafts` }); const save = async (type: string, item: { name: string }, query: Record, who: CallerName = 'system') => { const res = await as(who, 'PUT', `${META}/:type/:name`, { - path: `${META}/${type}/${item.name}`, params: { type, name: item.name }, query, body: item, + path: `${META}/${type}/${item.name}`, params: { type, name: item.name }, query: { ...query, package: TEST_PACKAGE_ID }, body: item, }); if (res.statusCode !== 200) throw new Error(`seeding ${type}/${item.name} failed: ${JSON.stringify(res.body)}`); }; diff --git a/packages/rest/src/meta-item-publish-version-pin.test.ts b/packages/rest/src/meta-item-publish-version-pin.test.ts index 613d869f723..6f33f71f5ae 100644 --- a/packages/rest/src/meta-item-publish-version-pin.test.ts +++ b/packages/rest/src/meta-item-publish-version-pin.test.ts @@ -92,6 +92,9 @@ async function boot() { engine.registry.registerObject(SysMetadata as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataHistoryObject as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataAuditObject as any, TEST_PACKAGE_ID); + // [#38174] The item is saved into an installed, writable package: a + // package-less create is refused (ADR-0070 D1). + engine.registry.installPackage({ id: TEST_PACKAGE_ID, name: TEST_PACKAGE_ID, version: '1.0.0' } as any, 'code'); await engine.syncSchemas(); const protocol = new ObjectStackProtocolImplementation(engine as any); @@ -123,7 +126,7 @@ async function boot() { const read = () => call('GET', `${META}/:type/:name`, { path, params: item }); /** `PUT /meta/view/case_grid` — active unless `mode: 'draft'`. */ const save = (body: unknown, query: Record = {}, headers: Record = {}) => - call('PUT', `${META}/:type/:name`, { path, params: item, query, headers, body }); + call('PUT', `${META}/:type/:name`, { path, params: item, query: { package: TEST_PACKAGE_ID, ...query }, headers, body }); /** `GET /meta/view/case_grid?state=draft` — the strict draft read. */ const readDraft = () => call('GET', `${META}/:type/:name`, { path, params: item, query: { state: 'draft' } }); /** `POST /meta/view/case_grid/publish`, with the body given (`{}` when none). */ diff --git a/packages/rest/src/meta-item-version-token-occ.test.ts b/packages/rest/src/meta-item-version-token-occ.test.ts index 7e7ec58f226..55a9e54ce34 100644 --- a/packages/rest/src/meta-item-version-token-occ.test.ts +++ b/packages/rest/src/meta-item-version-token-occ.test.ts @@ -103,6 +103,9 @@ async function boot(opts: { enableCache?: boolean } = {}) { engine.registry.registerObject(SysMetadata as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataHistoryObject as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataAuditObject as any, TEST_PACKAGE_ID); + // [#38174] The item is saved into an installed, writable package: a + // package-less create is refused (ADR-0070 D1). + engine.registry.installPackage({ id: TEST_PACKAGE_ID, name: TEST_PACKAGE_ID, version: '1.0.0' } as any, 'code'); await engine.syncSchemas(); const protocol = new ObjectStackProtocolImplementation(engine as any); @@ -132,7 +135,7 @@ async function boot(opts: { enableCache?: boolean } = {}) { call('GET', `${META}/:type/:name`, { path: `${META}/${type}/${name}`, params: { type, name }, query }); /** `PUT /meta/view/case_grid`. */ const save = (body: unknown, query: Record = {}, headers: Record = {}) => - call('PUT', `${META}/:type/:name`, { path, params: item, query, headers, body }); + call('PUT', `${META}/:type/:name`, { path, params: item, query: { package: TEST_PACKAGE_ID, ...query }, headers, body }); /** `POST /meta/view/case_grid/publish`. */ const publish = () => call('POST', `${META}/:type/:name/publish`, { path: `${path}/publish`, params: item, body: {} }); diff --git a/packages/rest/src/meta-object-owd-gate.test.ts b/packages/rest/src/meta-object-owd-gate.test.ts index d6bbd5c88a2..fff21bf8599 100644 --- a/packages/rest/src/meta-object-owd-gate.test.ts +++ b/packages/rest/src/meta-object-owd-gate.test.ts @@ -318,7 +318,8 @@ describe('[#8310] the 422 lint door through PUT /api/v1/meta/object/:name', () = // the same discipline defers now.) const { put, protocol } = await boot(); - const res = await put('qa_probe', probeObject(), { mode: 'draft' }); + // [#38174] a new object is saved into an installed package: a package-less create is refused (ADR-0070 D1). + const res = await put('qa_probe', probeObject(), { mode: 'draft', package: 'demo_pkg' }); expect(res._status, `draft save must pass ungated: ${JSON.stringify(res._json)}`).toBe(200); const err = await (protocol as any).publishMetaItem({ type: 'object', name: 'qa_probe' }) @@ -413,7 +414,8 @@ describe('[#7674] what the gate must still let through', () => { ])('a legal pair still saves — $pair', async ({ over }) => { const { put, storedRows } = await boot(); - const res = await put('qa_probe', probeObject(over)); + // [#38174] a new object is saved into an installed package: a package-less create is refused (ADR-0070 D1). + const res = await put('qa_probe', probeObject(over), { package: 'demo_pkg' }); expect(res._status, `unexpected refusal: ${JSON.stringify(res._json)}`).toBe(200); expect(res._json?.success).toBe(true); @@ -468,7 +470,8 @@ describe('[#7674] what the gate must still let through', () => { it('the `package-author` channel still bypasses the gate — the #6710 carve-out is intact', async () => { const { put, storedRows } = await boot({ channel: 'package-author' }); - const res = await put('qa_probe', probeObject()); + // [#38174] a new object is saved into an installed package: a package-less create is refused (ADR-0070 D1). + const res = await put('qa_probe', probeObject(), { package: 'demo_pkg' }); expect(res._status, `the control plane must still install its own packages: ${JSON.stringify(res._json)}`).toBe(200); expect(await storedRows('qa_probe')).toHaveLength(1); diff --git a/packages/rest/src/meta-page-record-no-component.test.ts b/packages/rest/src/meta-page-record-no-component.test.ts index 4c1fe99803d..d36701ed8b2 100644 --- a/packages/rest/src/meta-page-record-no-component.test.ts +++ b/packages/rest/src/meta-page-record-no-component.test.ts @@ -84,6 +84,9 @@ async function boot() { reason: { name: 'reason', label: 'Reason', type: 'text' }, }, } as any, 'objectstack-test'); + // [#38174] The pages are saved into an installed, writable package: a + // package-less create is refused (ADR-0070 D1). + engine.registry.installPackage({ id: 'objectstack-test', name: 'objectstack-test', version: '1.0.0' } as any, 'code'); await engine.syncSchemas(); const protocol = new ObjectStackProtocolImplementation(engine as any); @@ -99,7 +102,7 @@ async function boot() { }; const call = async (method: string, name: string, body?: unknown) => { const res = makeRes(); - await routeFor(method).handler({ params: { type: 'page', name }, query: {}, headers: {}, body } as any, res); + await routeFor(method).handler({ params: { type: 'page', name }, query: method === 'PUT' ? { package: 'objectstack-test' } : {}, headers: {}, body } as any, res); return res; }; const storedRows = async (name: string) => engine.find('sys_metadata', { where: { type: 'page', name } }); diff --git a/packages/rest/src/meta-view-audience-save-round-trip.test.ts b/packages/rest/src/meta-view-audience-save-round-trip.test.ts index 4a0a5389c29..f1f5bfe5a01 100644 --- a/packages/rest/src/meta-view-audience-save-round-trip.test.ts +++ b/packages/rest/src/meta-view-audience-save-round-trip.test.ts @@ -107,6 +107,9 @@ async function boot() { engine.registry.registerObject(SysMetadata as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataHistoryObject as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataAuditObject as any, TEST_PACKAGE_ID); + // [#38174] The view is saved into an installed, writable package: a + // package-less create is refused (ADR-0070 D1). + engine.registry.installPackage({ id: TEST_PACKAGE_ID, name: TEST_PACKAGE_ID, version: '1.0.0' } as any, 'code'); await engine.syncSchemas(); const protocol = new ObjectStackProtocolImplementation(engine as any); @@ -136,7 +139,7 @@ async function boot() { return { /** `PUT /meta/view/task.legal_queue` — active unless `mode: 'draft'`. */ save: (body: unknown, query: Record = {}, headers: Record = {}) => - call('author', 'PUT', `${META}/:type/:name`, { path, params: item, query, headers, body }), + call('author', 'PUT', `${META}/:type/:name`, { path, params: item, query: { package: TEST_PACKAGE_ID, ...query }, headers, body }), /** `GET /meta/view/task.legal_queue?state=draft` — the strict draft read. */ readDraft: () => call('author', 'GET', `${META}/:type/:name`, { path, params: item, query: { state: 'draft' } }), /** `POST /meta/view/task.legal_queue/publish`. */ diff --git a/packages/rest/src/meta-view-chart-binding.test.ts b/packages/rest/src/meta-view-chart-binding.test.ts index 7f0a8e179ac..5a1ee9253b9 100644 --- a/packages/rest/src/meta-view-chart-binding.test.ts +++ b/packages/rest/src/meta-view-chart-binding.test.ts @@ -88,6 +88,9 @@ async function boot() { amount: { name: 'amount', label: 'Amount', type: 'number' }, }, } as any, 'objectstack-test'); + // [#38174] The dataset and the views are saved into an installed, writable + // package: a package-less create is refused (ADR-0070 D1). + engine.registry.installPackage({ id: 'objectstack-test', name: 'objectstack-test', version: '1.0.0' } as any, 'code'); await engine.syncSchemas(); const protocol = new ObjectStackProtocolImplementation(engine as any); @@ -103,7 +106,7 @@ async function boot() { }; const call = async (method: string, name: string, body?: unknown, type = 'view') => { const res = makeRes(); - await routeFor(method).handler({ params: { type, name }, query: {}, headers: {}, body } as any, res); + await routeFor(method).handler({ params: { type, name }, query: method === 'PUT' ? { package: 'objectstack-test' } : {}, headers: {}, body } as any, res); return res; }; // [#26847] The dataset the fixture views bind, published through its own diff --git a/packages/rest/src/meta-view-overlay-options-bag.test.ts b/packages/rest/src/meta-view-overlay-options-bag.test.ts index f1a0d923390..5ec99f3cfbb 100644 --- a/packages/rest/src/meta-view-overlay-options-bag.test.ts +++ b/packages/rest/src/meta-view-overlay-options-bag.test.ts @@ -85,6 +85,9 @@ async function boot() { location: { name: 'location', label: 'Location', type: 'text' }, }, } as any, 'objectstack-test'); + // [#38174] The views are saved into an installed, writable package: a + // package-less create is refused (ADR-0070 D1). + engine.registry.installPackage({ id: 'objectstack-test', name: 'objectstack-test', version: '1.0.0' } as any, 'code'); await engine.syncSchemas(); const protocol = new ObjectStackProtocolImplementation(engine as any); @@ -98,7 +101,7 @@ async function boot() { const put = async (name: string, body: unknown) => { const res = makeRes(); - await route.handler({ params: { type: 'view', name }, query: {}, headers: {}, body } as any, res); + await route.handler({ params: { type: 'view', name }, query: { package: 'objectstack-test' }, headers: {}, body } as any, res); return res; }; const storedRows = async (name: string) => engine.find('sys_metadata', { where: { type: 'view', name } }); diff --git a/packages/rest/src/meta-write-actor-identity.test.ts b/packages/rest/src/meta-write-actor-identity.test.ts index d60145e3ffa..c8bb1ccfaa5 100644 --- a/packages/rest/src/meta-write-actor-identity.test.ts +++ b/packages/rest/src/meta-write-actor-identity.test.ts @@ -151,6 +151,9 @@ async function boot(execCtx: unknown, opts: { authServiceProvider?: any } = {}) engine.registry.registerObject(SysMetadata as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataHistoryObject as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataAuditObject as any, TEST_PACKAGE_ID); + // [#38174] The probe views are saved into an installed, writable package: + // a package-less create is refused (ADR-0070 D1). + engine.registry.installPackage({ id: TEST_PACKAGE_ID, name: TEST_PACKAGE_ID, version: '1.0.0' } as any, 'code'); // Real DDL — the audit and history tables the assertions read are // physically there, with their real column types. await engine.syncSchemas(); @@ -178,7 +181,7 @@ async function boot(execCtx: unknown, opts: { authServiceProvider?: any } = {}) const putMeta = async (route: any, name: string, headers: Record = {}) => { const res = makeRes(); await route.handler( - { params: { type: 'view', name }, query: {}, headers, body: VIEW(name) } as any, + { params: { type: 'view', name }, query: { package: TEST_PACKAGE_ID }, headers, body: VIEW(name) } as any, res, ); return res; diff --git a/packages/rest/src/public-form-routes.stored-row.test.ts b/packages/rest/src/public-form-routes.stored-row.test.ts index e0337417c8a..0ef06088fab 100644 --- a/packages/rest/src/public-form-routes.stored-row.test.ts +++ b/packages/rest/src/public-form-routes.stored-row.test.ts @@ -72,6 +72,9 @@ import '@objectstack/objectql'; // ─── the real save path ────────────────────────────────────────────────────── +/** [#38174] An installed, writable package (no namespace, so no name prefix is required). */ +const TEST_PACKAGE_ID = 'test_pkg'; + /** The slice of the engine the `sys_metadata` write path touches. */ function stubEngine() { const rows: Array> = []; @@ -96,7 +99,11 @@ function stubEngine() { assertEngineDeleteDispatch(options); return { deleted: 0 }; }, - registry: { registerItem: () => {}, registerObject: () => {}, listItems: () => [] }, + registry: { + registerItem: () => {}, registerObject: () => {}, listItems: () => [], + // [#38174] The writable package the form is saved into. + getPackage: (id: string) => (id === TEST_PACKAGE_ID ? { manifest: { id } } : undefined), + }, } as any, }; } @@ -110,7 +117,8 @@ function stubEngine() { async function persistedBody(name: string, item: unknown): Promise { const { engine, rows } = stubEngine(); const protocol = new ObjectStackProtocolImplementation(engine, () => new Map()) as any; - const result = await protocol.saveMetaItem({ type: 'form', name, item }); + // [#38174] a package-less create is refused (ADR-0070 D1): the form is saved into a package. + const result = await protocol.saveMetaItem({ type: 'form', name, item, packageId: TEST_PACKAGE_ID }); expect(result.success, JSON.stringify(result)).toBe(true); const row = rows.find((r) => r.type === 'form'); expect(row, 'the save persisted no form row').toBeDefined(); diff --git a/packages/rest/src/public-form-two-type-withdrawal.test.ts b/packages/rest/src/public-form-two-type-withdrawal.test.ts index 47b317ea24b..fcff45029ab 100644 --- a/packages/rest/src/public-form-two-type-withdrawal.test.ts +++ b/packages/rest/src/public-form-two-type-withdrawal.test.ts @@ -520,13 +520,14 @@ describe('[ADR-0159 D5] a package-less list at the name a read-only package auth it('refuses the publish of a list draft saved before the gate', async () => { const b = await booted({ forms: [formItem(true)] }); - const shipped = b.protocol.shippedArtifactsOf; - b.protocol.shippedArtifactsOf = (type: string, name: string) => (type === 'form' ? [] : shipped.call(b.protocol, type, name)); - try { - await b.protocol.saveMetaItem({ type: 'view', name: NAME, mode: 'draft', item: list }); - } finally { - b.protocol.shippedArtifactsOf = shipped; - } + // [#38174] The package-less draft a pre-gate save left is seeded straight + // into the store: a package-less create is refused (ADR-0070 D1). + const now = new Date().toISOString(); + await b.engine.insert('sys_metadata', { + id: `seed_view_${NAME}_draft_unbound`, type: 'view', name: NAME, + package_id: null, state: 'draft', metadata: JSON.stringify(list), checksum: hashSpec(list, 'view'), + version: 1, created_at: now, updated_at: now, + }, { context: { isSystem: true } }); await expect(b.protocol.publishMetaItem({ type: 'view', name: NAME })) .rejects.toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); }); diff --git a/packages/rest/src/rest-meta-save-receipt-envelope.test.ts b/packages/rest/src/rest-meta-save-receipt-envelope.test.ts index 26507925c50..5a4575799e3 100644 --- a/packages/rest/src/rest-meta-save-receipt-envelope.test.ts +++ b/packages/rest/src/rest-meta-save-receipt-envelope.test.ts @@ -74,6 +74,9 @@ const TASK = { }, }; +/** [#38174] The writable package the probe view is created in. */ +const TEST_PACKAGE_ID = 'objectstack-test'; + async function boot() { const engine = new ObjectQL(); liveEngines.push(engine); @@ -82,6 +85,9 @@ async function boot() { engine.registry.registerObject(TASK as any); engine.registry.registerObject(SysMetadata as any); engine.registry.registerObject(SysMetadataHistoryObject as any); + // [#38174] The probe view is saved into an installed, writable package: a + // package-less create is refused (ADR-0070 D1), so the receipt names it. + engine.registry.installPackage({ id: TEST_PACKAGE_ID, name: TEST_PACKAGE_ID, version: '1.0.0' } as any, 'code'); // Real DDL, `sys_metadata` included — the overlay store the PUT writes to. await engine.syncSchemas(); @@ -98,7 +104,7 @@ async function boot() { const putMeta = async (route: any, type: string, name: string, body: unknown) => { const res = makeRes(); - await route.handler({ params: { type, name }, query: {}, headers: {}, body } as any, res); + await route.handler({ params: { type, name }, query: { package: TEST_PACKAGE_ID }, headers: {}, body } as any, res); return res; }; @@ -120,7 +126,7 @@ describe('[#5265] PUT /meta receipt reaches the envelope truthfully', () => { // The exact sentence the issue measured, corrected. Asserted whole, so // a REST-layer paraphrase or a dropped suffix is a failure here. expect(res._json.message).toBe( - `Saved view 'rc5_probe_view' (env-wide, state=active) [seq=${res._json.seq}]`, + `Saved view 'rc5_probe_view' (env-wide, package=${TEST_PACKAGE_ID}, state=active) [seq=${res._json.seq}]`, ); expect(res._json.message).not.toContain('customization overlay'); }, 60_000); @@ -153,10 +159,10 @@ describe('[#5265] PUT /meta receipt reaches the envelope truthfully', () => { }); expect(first._json.message).toBe( - `Saved view 'rc5_probe_view' (env-wide, state=active) [seq=${first._json.seq}]`, + `Saved view 'rc5_probe_view' (env-wide, package=${TEST_PACKAGE_ID}, state=active) [seq=${first._json.seq}]`, ); expect(second._json.message).toBe( - `Saved view 'rc5_probe_view' (env-wide, state=active) [seq=${second._json.seq}]`, + `Saved view 'rc5_probe_view' (env-wide, package=${TEST_PACKAGE_ID}, state=active) [seq=${second._json.seq}]`, ); expect(second._json.seq).toBeGreaterThan(first._json.seq); }, 60_000); diff --git a/packages/rest/src/rest-server-meta-history-diff-org-scope.test.ts b/packages/rest/src/rest-server-meta-history-diff-org-scope.test.ts index 7f916844c5f..6a46bf5c7f1 100644 --- a/packages/rest/src/rest-server-meta-history-diff-org-scope.test.ts +++ b/packages/rest/src/rest-server-meta-history-diff-org-scope.test.ts @@ -42,6 +42,9 @@ const PRE_D6_ORG_SCOPED = ['view', 'dashboard', 'report', 'translation', 'email_ */ const NON_OVERRIDABLE = 'object'; +/** [#38174] The writable package the fixture writes are saved into (no namespace, no name prefix). */ +const TEST_PACKAGE_ID = 'test_pkg'; + const MARKER = 'AUTHORED_AT_RUNTIME'; const MARKER_2 = 'AUTHORED_AT_RUNTIME_REV2'; @@ -261,9 +264,25 @@ function makeStubEngine() { dimensions: [{ name: 'status', label: 'Status', field: 'status', type: 'string' }], measures: [{ name: 'order_count', label: 'Orders', aggregate: 'count' }], }] - : []), + // [#38174] The object the view fixture binds, with no package + // provenance: a view written into a package is judged against + // that package's closure, and an object that exists nowhere is + // outside it (`list-view-object-outside-closure`). + : type === 'object' + ? [{ + name: 'task', + label: 'Task', + fields: { + name: { name: 'name', type: 'text', label: 'Name' }, + status: { name: 'status', type: 'text', label: 'Status' }, + }, + }] + : []), getItem: () => undefined, - getObject: () => undefined, getPackage: () => undefined, + // [#38174] The fixture writes name this installed, writable package: a + // package-less create is refused (ADR-0070 D1). + getObject: () => undefined, + getPackage: (id: string) => (id === TEST_PACKAGE_ID ? { manifest: { id } } : undefined), getArtifactItem: () => undefined, isPackageDisabled: () => false, }, @@ -335,7 +354,7 @@ function boot() { : { userId: 'u1', systemPermissions: ['manage_metadata'], tenantId }; }, put: (type: string, name: string, label = MARKER) => - drive('PUT', `${META}/:type/:name`, { params: { type, name }, body: bodyFor(type, name, label) }), + drive('PUT', `${META}/:type/:name`, { params: { type, name }, query: { package: TEST_PACKAGE_ID }, body: bodyFor(type, name, label) }), get: (type: string, name: string) => drive('GET', `${META}/:type/:name`, { params: { type, name } }), history: (type: string, name: string, query: Record = {}) => diff --git a/packages/rest/src/rest-server-meta-read-org-scope.test.ts b/packages/rest/src/rest-server-meta-read-org-scope.test.ts index 6b409cb0dca..13da0e0c64c 100644 --- a/packages/rest/src/rest-server-meta-read-org-scope.test.ts +++ b/packages/rest/src/rest-server-meta-read-org-scope.test.ts @@ -53,6 +53,9 @@ const UNCACHED_ARM = 'dashboard'; // bypasses it via `isDashboardType` const NON_OVERRIDABLE = 'object'; /** The value every read assertion looks for. */ +/** [#38174] The writable package the fixture writes are saved into (no namespace, no name prefix). */ +const TEST_PACKAGE_ID = 'test_pkg'; + const MARKER = 'AUTHORED_AT_RUNTIME'; /** The second revision's marker — two PUTs, two history events. */ @@ -273,9 +276,25 @@ function makeStubEngine() { dimensions: [{ name: 'status', label: 'Status', field: 'status', type: 'string' }], measures: [{ name: 'order_count', label: 'Orders', aggregate: 'count' }], }] - : []), + // [#38174] The object the view fixture binds, with no package + // provenance: a view written into a package is judged against + // that package's closure, and an object that exists nowhere is + // outside it (`list-view-object-outside-closure`). + : type === 'object' + ? [{ + name: 'task', + label: 'Task', + fields: { + name: { name: 'name', type: 'text', label: 'Name' }, + status: { name: 'status', type: 'text', label: 'Status' }, + }, + }] + : []), getItem: () => undefined, - getObject: () => undefined, getPackage: () => undefined, + // [#38174] The fixture writes name this installed, writable package: a + // package-less create is refused (ADR-0070 D1). + getObject: () => undefined, + getPackage: (id: string) => (id === TEST_PACKAGE_ID ? { manifest: { id } } : undefined), getArtifactItem: () => undefined, // The LIST door prunes items belonging to disabled packages; a // registry double without this answers 500, which would have read @@ -356,7 +375,7 @@ function boot() { : { userId: 'u1', systemPermissions: ['manage_metadata'], tenantId }; }, put: (type: string, name: string, label = MARKER) => - drive('PUT', `${META}/:type/:name`, { params: { type, name }, body: bodyFor(type, name, label) }), + drive('PUT', `${META}/:type/:name`, { params: { type, name }, query: { package: TEST_PACKAGE_ID }, body: bodyFor(type, name, label) }), get: (type: string, name: string) => drive('GET', `${META}/:type/:name`, { params: { type, name } }), list: (type: string) => diff --git a/packages/runtime/src/cluster-metadata-mutation-resync.integration.test.ts b/packages/runtime/src/cluster-metadata-mutation-resync.integration.test.ts index 8b93954fb0c..8218b6302c9 100644 --- a/packages/runtime/src/cluster-metadata-mutation-resync.integration.test.ts +++ b/packages/runtime/src/cluster-metadata-mutation-resync.integration.test.ts @@ -68,6 +68,9 @@ function lossyBus() { return { bus, state }; } +/** The writable package each replica installs and every save below names. */ +const TEST_PKG = 'test_pkg'; + const METADATA_OBJECTS = [SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject] as never[]; /** One replica: a kernel with its own engine and protocol over `file`, a cluster on `bus`, and the real bridge. */ @@ -78,6 +81,8 @@ async function replica(file: string, nodeId: string, bus: IPubSub, driverName = engine.registerDriver(driver as never, true); await engine.init(); for (const o of METADATA_OBJECTS) engine.registry.registerObject(o, '@objectstack/platform-objects'); + // [#38174] A new item is saved into an installed, writable package (ADR-0070 D1). + engine.registry.installPackage({ id: TEST_PKG, name: TEST_PKG, version: '1.0.0', type: 'app' } as never, 'authored'); const protocol = new ObjectStackProtocolImplementation(engine as never, () => new Map(), 'env_prod'); const liveness = new ClusterDriverLiveness({ driver: driverName, nodeId, logger: { warn() {}, info() {} } }); @@ -143,7 +148,7 @@ describe('[#31722] lane 2 on cluster.resync — two kernels, one database', () = const { a, b, outage } = await twoReplicas(); outage.down = true; - const saved = await a.protocol.saveMetaItem({ type: 'object', name: 'gadget', item: gadget, mode: 'publish' }); + const saved = await a.protocol.saveMetaItem({ type: 'object', name: 'gadget', item: gadget, mode: 'publish', packageId: TEST_PKG }); expect(saved.success).toBe(true); await a.engine.insert('gadget', { title: 'first', organization_id: 'org_1' }, { context: { isSystem: true } } as never); outage.down = false; @@ -160,14 +165,14 @@ describe('[#31722] lane 2 on cluster.resync — two kernels, one database', () = it('CONTROL — a delivered hint still converges B per item, with no resync', async () => { const { a, b } = await twoReplicas(); - await a.protocol.saveMetaItem({ type: 'object', name: 'gadget', item: gadget, mode: 'publish' }); + await a.protocol.saveMetaItem({ type: 'object', name: 'gadget', item: gadget, mode: 'publish', packageId: TEST_PKG }); await vi.waitFor(() => expect(b.engine.registry.getObject('gadget')).toBeDefined()); }); it('CONTROL — on the in-process memory driver no lane attaches and no resync runs', async () => { const { a, b } = await twoReplicas('memory'); const seam = vi.spyOn(b.protocol, 'resyncMetadataMutationPubSub'); - await a.protocol.saveMetaItem({ type: 'object', name: 'gadget', item: gadget, mode: 'publish' }); + await a.protocol.saveMetaItem({ type: 'object', name: 'gadget', item: gadget, mode: 'publish', packageId: TEST_PKG }); b.outageEnds(); await new Promise((r) => setTimeout(r, 20)); expect(seam).not.toHaveBeenCalled(); @@ -203,7 +208,7 @@ const memberCtx = { context: { userId: 'usr_1', tenantId: 'org_1', roles: [], pe describe('[#32145] a delivered lane-2 hint prepares the object on the peer — two kernels, one database', () => { it('⭐ B numbers the autonumber of an object authored on A', async () => { const { a, b } = await twoReplicas(); - const saved = await a.protocol.saveMetaItem({ type: 'object', name: 'ticket', item: ticket, mode: 'publish' }); + const saved = await a.protocol.saveMetaItem({ type: 'object', name: 'ticket', item: ticket, mode: 'publish', packageId: TEST_PKG }); expect(saved.success).toBe(true); await vi.waitFor(() => expect(b.engine.registry.getObject('ticket')).toBeDefined()); @@ -213,7 +218,7 @@ describe('[#32145] a delivered lane-2 hint prepares the object on the peer — t it('⭐ B stamps the organization of a member write to an object authored on A', async () => { const { a, b } = await twoReplicas(); - await a.protocol.saveMetaItem({ type: 'object', name: 'ticket', item: ticket, mode: 'publish' }); + await a.protocol.saveMetaItem({ type: 'object', name: 'ticket', item: ticket, mode: 'publish', packageId: TEST_PKG }); await vi.waitFor(() => expect(b.engine.registry.getObject('ticket')).toBeDefined()); const row = await b.engine.insert('ticket', { title: 'on b' }, memberCtx); @@ -222,7 +227,7 @@ describe('[#32145] a delivered lane-2 hint prepares the object on the peer — t it('CONTROL — the authoring replica numbers and stamps the same writes', async () => { const { a } = await twoReplicas(); - await a.protocol.saveMetaItem({ type: 'object', name: 'ticket', item: ticket, mode: 'publish' }); + await a.protocol.saveMetaItem({ type: 'object', name: 'ticket', item: ticket, mode: 'publish', packageId: TEST_PKG }); const row = await a.engine.insert('ticket', { title: 'on a' }, memberCtx); expect(row).toMatchObject({ ticket_number: 'TK-0001', organization_id: 'org_1' }); diff --git a/packages/runtime/src/dispatcher-body-after-anonymous-floor.hono.integration.test.ts b/packages/runtime/src/dispatcher-body-after-anonymous-floor.hono.integration.test.ts index f00a1bc8585..c61324bb5d8 100644 --- a/packages/runtime/src/dispatcher-body-after-anonymous-floor.hono.integration.test.ts +++ b/packages/runtime/src/dispatcher-body-after-anonymous-floor.hono.integration.test.ts @@ -71,7 +71,7 @@ interface Site { const UNAUTHENTICATED: Answer = { status: 401, code: 'UNAUTHENTICATED' }; const SKILL_405: Answer = { status: 405, code: 'METHOD_NOT_ALLOWED' }; -/** The card's twenty `dispatcher.dispatch(… req.body …)` mounts, every verb of the method-parameterised ones. */ +/** The card's twenty `dispatcher.dispatch(… req.body …)` mounts (nineteen since #38174 unmounted `POST /automation`), every verb of the method-parameterised ones. */ const CARD_SITES: Site[] = [ { method: 'POST', path: '/analytics/query', scoped: false, anonymous: UNAUTHENTICATED, signedIn: 'refusal' }, { method: 'POST', path: '/analytics/sql', scoped: false, anonymous: UNAUTHENTICATED, signedIn: 'refusal' }, @@ -85,7 +85,8 @@ const CARD_SITES: Site[] = [ { method: 'DELETE', path: '/keys', scoped: false, anonymous: UNAUTHENTICATED, signedIn: 'refusal' }, { method: 'POST', path: '/notifications/read', scoped: false, anonymous: UNAUTHENTICATED, signedIn: 'refusal' }, { method: 'POST', path: '/notifications/read/all', scoped: false, anonymous: UNAUTHENTICATED, signedIn: 'refusal' }, - { method: 'POST', path: '/automation', scoped: true, anonymous: UNAUTHENTICATED, signedIn: 'refusal' }, + // [#38174] `POST /automation` (the create door) is retired and unmounted, so it reads no body; + // its unmatched answer is pinned in `dispatcher-plugin.anonymous-gate.integration.test.ts`. { method: 'PUT', path: '/automation/flow_x', scoped: true, anonymous: UNAUTHENTICATED, signedIn: 'refusal' }, { method: 'POST', path: '/automation/trigger/flow_x', scoped: true, anonymous: UNAUTHENTICATED, signedIn: 'refusal' }, { method: 'POST', path: '/automation/flow_x/trigger', scoped: true, anonymous: UNAUTHENTICATED, signedIn: 'refusal' }, diff --git a/packages/runtime/src/dispatcher-plugin.anonymous-gate.integration.test.ts b/packages/runtime/src/dispatcher-plugin.anonymous-gate.integration.test.ts index fc9c9fc5779..9cab83730de 100644 --- a/packages/runtime/src/dispatcher-plugin.anonymous-gate.integration.test.ts +++ b/packages/runtime/src/dispatcher-plugin.anonymous-gate.integration.test.ts @@ -178,50 +178,43 @@ describe('#5519 — the mounted /actions and /automation routes deny anonymous c expect(getFlowRuntimeStates).not.toHaveBeenCalled(); }, 60_000); - // ── #19543 door ④: the flow list is RETIRED, and on the wire that means ── - // `GET` is not mounted at the path at all. Flows are metadata (ADR-0106); - // the list is `GET /api/v1/meta/flow`. `POST` (createFlow) still lives at - // the same path, so the host answers its standard METHOD MISMATCH — `405` - // with an accurate `Allow` — exactly as it does for any path where only - // another verb was ever registered. No retirement-specific text, code or + // ── #19543 door ④ + #38174: the flow list AND the create door are RETIRED, + // and on the wire that means NOTHING is mounted at `/api/v1/automation` + // itself. Flows are metadata (ADR-0106): the list is `GET /api/v1/meta/flow` + // and a new flow is created by `PUT /api/v1/meta/flow/:name?package=`. The + // host answers its standard UNMATCHED answer — the same one any path no + // route was ever registered at gets. No retirement-specific text, code or // hint reaches the wire. - it('[#19543] GET /api/v1/automation answers the host\'s standard 405 + Allow: POST — anonymous AND with a session', async () => { + async function unmatched(res: Response, path: string): Promise { + return (await res.text()).split(path).join('PATH'); + } + + it('[#19543, #38174] GET and POST /api/v1/automation answer the host\'s standard unmatched 404 — anonymous AND with a session', async () => { listFlows.mockClear(); - // The control: a path of this domain where GET was NEVER registered - // and POST is (`/:name/runs/:runId/resume`). Same host, same answer - // shape. [ADR-0150 D5, child G1] Not a two-segment path: those now - // reach the domain under every verb (`/automation/:ns/:name`), which - // decides them, so the host's own 405 no longer answers there. - const control = await fetch(`${baseUrl}/api/v1/automation/crm_escalation_flow/runs/r1/resume`); - const controlBody: any = await control.json(); - expect(control.status).toBe(405); + // The control: a path no route was ever registered at. + const controlPath = '/api/v1/never_a_route_38174'; + const control = await fetch(`${baseUrl}${controlPath}`); + expect(control.status).toBe(404); + const controlBody = await unmatched(control, controlPath); for (const headers of [{}, { [SESSION_HEADER]: '1' }]) { const res = await fetch(`${baseUrl}/api/v1/automation`, { headers }); - expect(res.status).toBe(405); - expect(res.headers.get('allow')).toBe('POST'); - const body: any = await res.json(); - expect(body.success).toBe(false); - expect(body.error.code).toBe('METHOD_NOT_ALLOWED'); - expect(body.error.details).toEqual({ method: 'GET', path: '/api/v1/automation', allowed: ['POST'] }); - // Byte-identical to the never-a-GET control once the echoed path is - // factored out — the retired route left nothing of its own behind. - const echoless = (b: unknown, path: string) => JSON.stringify(b).split(path).join('PATH'); - expect(echoless(body, '/api/v1/automation')) - .toBe(echoless(controlBody, '/api/v1/automation/crm_escalation_flow/runs/r1/resume')); + expect(res.status).toBe(404); + // Byte-identical to the never-a-route control once the echoed path + // is factored out — the retired routes left nothing of their own behind. + expect(await unmatched(res, '/api/v1/automation')).toBe(controlBody); } // Answered by the host before any dispatch: the engine's name // enumeration is unreachable over HTTP. expect(listFlows).not.toHaveBeenCalled(); }, 60_000); - it('[#19543] POST /api/v1/automation (createFlow) is still MOUNTED at the same path — the retirement is one verb', async () => { - // Anonymous, so the domain floor answers 401 — an answer only a mounted - // route can give. A 404 or 405 here would mean the retirement took the - // create door with it. - const res = await post('/automation', { name: 'injected_flow' }); - expect(res.status).toBe(401); + it('[#38174] POST /api/v1/automation (the retired create door) is NOT mounted — the host\'s unmatched 404, anonymous AND with a session', async () => { + // Anonymous, a mounted route would answer the domain floor's 401; with + // a session it would reach the domain. Both get the unmatched 404. + expect((await post('/automation', { name: 'injected_flow' })).status).toBe(404); + expect((await post('/automation', { name: 'injected_flow' }, true)).status).toBe(404); }, 60_000); it('anonymous DELETE /api/v1/automation/:name → 401 — the destructive one', async () => { diff --git a/packages/runtime/src/domains/actions-disabled-package.test.ts b/packages/runtime/src/domains/actions-disabled-package.test.ts index 25f7bf63ae4..3c2e53dfd63 100644 --- a/packages/runtime/src/domains/actions-disabled-package.test.ts +++ b/packages/runtime/src/domains/actions-disabled-package.test.ts @@ -182,10 +182,18 @@ async function bootKernel( engine.registerAction(GLOBAL_ACTION_OBJECT_KEY, pkg.globalHandler, globalPings); const authoredPings = vi.fn(async () => ({ pong: 'authored' })); engine.registerAction(GLOBAL_ACTION_OBJECT_KEY, AUTHORED.handler, authoredPings); + const authored = { name: AUTHORED.name, label: 'Authored global ping', type: 'script', target: AUTHORED.handler }; + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the environment's + // loose row is laid straight into the store, and the save door's + // package-less save of it runs in place. + await engine.insert('sys_metadata', { + type: 'action', name: AUTHORED.name, namespace: 'default', package_id: null, scope: 'platform', strategy: 'merge', + state: 'active', version: 1, metadata: JSON.stringify(authored), + }, { context: { isSystem: true } } as any); await (kernel.getService('protocol') as any).saveMetaItem({ type: 'action', name: AUTHORED.name, - item: { name: AUTHORED.name, label: 'Authored global ping', type: 'script', target: AUTHORED.handler }, + item: authored, }); return { kernel, engine, root, pings, globalPings, authoredPings }; } diff --git a/packages/runtime/src/domains/automation-authoring-doors-durable.test.ts b/packages/runtime/src/domains/automation-authoring-doors-durable.test.ts index 0170338da8b..f985aa84212 100644 --- a/packages/runtime/src/domains/automation-authoring-doors-durable.test.ts +++ b/packages/runtime/src/domains/automation-authoring-doors-durable.test.ts @@ -130,11 +130,17 @@ const statusOf = (response: any): unknown => response?.status; const errorOf = (response: any): { code?: unknown } => response?.body?.error ?? {}; const dataOf = (response: any): any => response?.body?.data; +// [#38174] The create door `POST /` is retired. Its cases drive the remaining +// definition door, `PUT /:name`, onto a name the engine does not hold: the store +// double's `saveMetaItem` is mocked, so the door's register-then-save path (and +// its withdrawal of the new name on a refusal) is what runs. The kernel's own +// answer for a real package-less create (422 WRITABLE_PACKAGE_REQUIRED) is +// pinned in `automation-flow-door-package-address.test.ts`. describe('[#20862] the create and update doors save what they register', () => { - it('POST / registers the definition and saves the same definition through the protocol, env-wide, engine first', async () => { + it('PUT /:name of a new name registers the definition and saves the same definition through the protocol, env-wide, engine first', async () => { const h = boot(); const body = definitionOf(NEW, 'Created'); - const { response } = await h.dispatcher.handleAutomation('', 'POST', body, AUTHOR(), undefined); + const { response } = await h.dispatcher.handleAutomation(`/${NEW}`, 'PUT', body, AUTHOR(), undefined); expect(statusOf(response)).toBe(200); expect(dataOf(response)?.name).toBe(NEW); @@ -159,7 +165,7 @@ describe('[#20862] the create and update doors save what they register', () => { const h = boot(); h.saveMetaItem.mockRejectedValueOnce(storeRefusal()); - const { response } = await h.dispatcher.handleAutomation('', 'POST', definitionOf(NEW), AUTHOR(), undefined); + const { response } = await h.dispatcher.handleAutomation(`/${NEW}`, 'PUT', definitionOf(NEW), AUTHOR(), undefined); expect(statusOf(response)).toBe(422); expect(errorOf(response).code).toBe('INVALID_METADATA'); @@ -188,7 +194,7 @@ describe('[#20862] the create and update doors save what they register', () => { const h = boot(); h.registerFlow.mockImplementationOnce(() => { throw new Error("node 'n' (notify): unknown config key `x`"); }); - const { response } = await h.dispatcher.handleAutomation('', 'POST', definitionOf(NEW), AUTHOR(), undefined); + const { response } = await h.dispatcher.handleAutomation(`/${NEW}`, 'PUT', definitionOf(NEW), AUTHOR(), undefined); expect(statusOf(response)).toBe(400); expect(errorOf(response).code).toBe('VALIDATION_FAILED'); @@ -203,7 +209,7 @@ describe('[#20862] the create and update doors save what they register', () => { expect(errorOf(locked.response).code).toBe('NOT_OVERRIDABLE'); const claimed = await h.dispatcher.handleAutomation( - '', 'POST', { ...definitionOf(NEW), _packageId: PACKAGE_ID, _provenance: 'package' }, AUTHOR(), undefined, + `/${NEW}`, 'PUT', { ...definitionOf(NEW), _packageId: PACKAGE_ID, _provenance: 'package' }, AUTHOR(), undefined, ); expect(statusOf(claimed.response)).toBe(422); expect(errorOf(claimed.response).code).toBe('INVALID_METADATA'); @@ -215,7 +221,7 @@ describe('[#20862] the create and update doors save what they register', () => { it('no metadata protocol in the composition: the definition is registered in the engine only, as before', async () => { const h = boot({ protocol: 'absent' }); - const { response } = await h.dispatcher.handleAutomation('', 'POST', definitionOf(NEW), AUTHOR(), undefined); + const { response } = await h.dispatcher.handleAutomation(`/${NEW}`, 'PUT', definitionOf(NEW), AUTHOR(), undefined); expect(statusOf(response)).toBe(200); expect(h.held(NEW)).toEqual(definitionOf(NEW)); @@ -304,10 +310,10 @@ const fieldsOf = (response: any): Array<{ field?: string; code?: string }> => response?.body?.error?.details?.fields ?? []; describe('a notify node naming a channel no plugin registers is refused at the save doors (ruling 6810493176, letter B)', () => { - it('POST /: 400 VALIDATION_FAILED naming the node and the channel at its config path, listing the registered channels; nothing saved, the create withdrawn', async () => { + it('PUT /:name of a new name: 400 VALIDATION_FAILED naming the node and the channel at its config path, listing the registered channels; nothing saved, the create withdrawn', async () => { const h = boot({ messaging: STOCK_CHANNELS, ready: true }); - const { response } = await h.dispatcher.handleAutomation('', 'POST', notifyFlowOf(NEW, 'emial'), AUTHOR(), undefined); + const { response } = await h.dispatcher.handleAutomation(`/${NEW}`, 'PUT', notifyFlowOf(NEW, 'emial'), AUTHOR(), undefined); expect(statusOf(response)).toBe(400); expect(errorOf(response).code).toBe('VALIDATION_FAILED'); @@ -345,7 +351,7 @@ describe('a notify node naming a channel no plugin registers is refused at the s const h = boot({ messaging: STOCK_CHANNELS, ready: true }); const { response } = await h.dispatcher.handleAutomation( - '', 'POST', notifyFlowOf(NEW, 'teams', ['inbox', 'pager']), AUTHOR(), undefined, + `/${NEW}`, 'PUT', notifyFlowOf(NEW, 'teams', ['inbox', 'pager']), AUTHOR(), undefined, ); expect(statusOf(response)).toBe(400); @@ -363,9 +369,9 @@ describe('a notify node naming a channel no plugin registers is refused at the s it('the control: registered channels save, a provider with no transport yet among them, and so does a node naming none', async () => { const h = boot({ messaging: STOCK_CHANNELS, ready: true }); - const named = await h.dispatcher.handleAutomation('', 'POST', notifyFlowOf(NEW, [' email ', 'push'], 'sms'), AUTHOR(), undefined); + const named = await h.dispatcher.handleAutomation(`/${NEW}`, 'PUT', notifyFlowOf(NEW, [' email ', 'push'], 'sms'), AUTHOR(), undefined); expect(statusOf(named.response)).toBe(200); - const unnamed = await h.dispatcher.handleAutomation('', 'POST', notifyFlowOf('other_flow', undefined, undefined), AUTHOR(), undefined); + const unnamed = await h.dispatcher.handleAutomation('/other_flow', 'PUT', notifyFlowOf('other_flow', undefined, undefined), AUTHOR(), undefined); expect(statusOf(unnamed.response)).toBe(200); expect(h.saveMetaItem).toHaveBeenCalledTimes(2); }); @@ -377,7 +383,7 @@ describe('a notify node naming a channel no plugin registers is refused at the s { messaging: 'no-reader', ready: true }, ] as const) { const h = boot(composition); - const { response } = await h.dispatcher.handleAutomation('', 'POST', notifyFlowOf(NEW, 'emial'), AUTHOR(), undefined); + const { response } = await h.dispatcher.handleAutomation(`/${NEW}`, 'PUT', notifyFlowOf(NEW, 'emial'), AUTHOR(), undefined); expect(statusOf(response), JSON.stringify(composition)).toBe(200); expect(h.saveMetaItem).toHaveBeenCalledTimes(1); } @@ -386,7 +392,7 @@ describe('a notify node naming a channel no plugin registers is refused at the s it('a messaging reader that throws or answers no list is not judged: the save goes on, registered AND saved', async () => { for (const messaging of ['reader-throws', 'reader-not-a-list'] as const) { const h = boot({ messaging, ready: true }); - const { response } = await h.dispatcher.handleAutomation('', 'POST', notifyFlowOf(NEW, 'emial'), AUTHOR(), undefined); + const { response } = await h.dispatcher.handleAutomation(`/${NEW}`, 'PUT', notifyFlowOf(NEW, 'emial'), AUTHOR(), undefined); expect(statusOf(response), messaging).toBe(200); expect(h.saveMetaItem, messaging).toHaveBeenCalledTimes(1); expect(h.held(NEW), messaging).toBeDefined(); @@ -398,7 +404,7 @@ describe('a notify node naming a channel no plugin registers is refused at the s // member would leave a roster without it and refuse the node. for (const messaging of ['reader-bare-ids', 'reader-one-bare-id'] as const) { const h = boot({ messaging, ready: true }); - const { response } = await h.dispatcher.handleAutomation('', 'POST', notifyFlowOf(NEW, 'email'), AUTHOR(), undefined); + const { response } = await h.dispatcher.handleAutomation(`/${NEW}`, 'PUT', notifyFlowOf(NEW, 'email'), AUTHOR(), undefined); expect(statusOf(response), messaging).toBe(200); expect(h.saveMetaItem, messaging).toHaveBeenCalledTimes(1); expect(h.held(NEW), messaging).toBeDefined(); @@ -410,7 +416,7 @@ describe('a notify node naming a channel no plugin registers is refused at the s const before = h.held(CUSTOMER); await expect( - h.dispatcher.handleAutomation('', 'POST', notifyFlowOf(NEW, 'emial'), AUTHOR(), undefined), + h.dispatcher.handleAutomation(`/${NEW}`, 'PUT', notifyFlowOf(NEW, 'emial'), AUTHOR(), undefined), ).rejects.toThrow('boot phase unreadable'); expect(h.saveMetaItem).not.toHaveBeenCalled(); expect(h.held(NEW)).toBeUndefined(); diff --git a/packages/runtime/src/domains/automation-body-validation.test.ts b/packages/runtime/src/domains/automation-body-validation.test.ts index f7c85e484b6..c7b925ec318 100644 --- a/packages/runtime/src/domains/automation-body-validation.test.ts +++ b/packages/runtime/src/domains/automation-body-validation.test.ts @@ -73,7 +73,10 @@ async function expectValidationFailure(run: Promise, label: string) { return thrown as Error; } -describe('#3899 ③ — POST /automation (registerFlow) requires a named definition', () => { +// [#38174] The create door `POST /automation` is RETIRED (a new flow is +// created by `PUT /meta/flow/:name?package=`, ADR-0070 D1): no branch answers +// it, so no body — malformed or named — ever reaches `registerFlow` there. +describe('#3899 ③ — POST /automation (retired by #38174) registers nothing', () => { it.each([ ['missing name', { trigger: { type: 'manual' } }], ['empty name', { name: ' ' }], @@ -81,21 +84,13 @@ describe('#3899 ③ — POST /automation (registerFlow) requires a named definit ['array body', [{ name: 'f1' }]], ['string body', 'garbage'], ['null body', null], - ])('rejects %s — a flow must never register under the key `undefined`', async (_label, body) => { + ['a named definition', { name: 'welcome_flow', trigger: { type: 'manual' } }], + ])('is not served for %s — a flow must never register through it', async (_label, body) => { const { dispatcher, spies } = makeDispatcher(); - await expectValidationFailure( - dispatcher.handleAutomation('', 'POST', body, CTX), - JSON.stringify(body), - ); - expect(spies.registerFlow).not.toHaveBeenCalled(); - }); - - it('registers a named definition under its name', async () => { - const { dispatcher, spies } = makeDispatcher(); - const body = { name: 'welcome_flow', trigger: { type: 'manual' } }; const result = await dispatcher.handleAutomation('', 'POST', body, CTX); - expect(result.response?.status).toBe(200); - expect(spies.registerFlow).toHaveBeenCalledWith('welcome_flow', body); + expect(result.handled).toBe(false); + expect(result.response).toBeUndefined(); + expect(spies.registerFlow).not.toHaveBeenCalled(); }); }); diff --git a/packages/runtime/src/domains/automation-flow-credential-projection.test.ts b/packages/runtime/src/domains/automation-flow-credential-projection.test.ts index 13c31ae13bf..58f990edb22 100644 --- a/packages/runtime/src/domains/automation-flow-credential-projection.test.ts +++ b/packages/runtime/src/domains/automation-flow-credential-projection.test.ts @@ -102,10 +102,11 @@ describe('#20552 — a served definition withholds the hook secret', () => { expect(served.edges).toEqual(inboundFlow().edges); }); - it('POST / — the create answer withholds it; the engine is handed the body as written', async () => { + // [#38174] `POST /` is retired: the first write of a name goes through `PUT /:name`. + it('PUT /:name of a name the engine does not hold — the write answer withholds it; the engine is handed the body as written', async () => { const { dispatcher, spies } = makeDispatcher([]); const body = inboundFlow('fresh_hook'); - const result = await dispatcher.handleAutomation('', 'POST', body, AUTHOR); + const result = await dispatcher.handleAutomation('/fresh_hook', 'PUT', body, AUTHOR); expect(result.response?.status).toBe(200); expect(JSON.stringify(result.response?.body)).not.toContain(SECRET); expect(startOf(spies.registerFlow.mock.calls[0]![1]).config.secret).toBe(SECRET); @@ -142,10 +143,12 @@ describe('#20552 — the round trip keeps the stored secret; only an explicit va expect(JSON.stringify(result.response?.body)).not.toContain(SECRET); }); - it('POST / onto an existing name with the served body is the same overwrite, the same rule', async () => { + // [#38174] `POST /` is retired; `PUT /:name` is the one overwrite door left, + // driven here with the served body unchanged but for its label. + it('PUT /:name onto an existing name with the served body is the same overwrite, the same rule', async () => { const { dispatcher, spies } = makeDispatcher(); const served = dataOf(await dispatcher.handleAutomation('/inbound_hook', 'GET', undefined, MEMBER)); - await dispatcher.handleAutomation('', 'POST', { ...served, label: 'Recreated' }, AUTHOR); + await dispatcher.handleAutomation('/inbound_hook', 'PUT', { ...served, label: 'Recreated' }, AUTHOR); expect(startOf(spies.registerFlow.mock.calls.at(-1)![1]).config.secret).toBe(SECRET); }); diff --git a/packages/runtime/src/domains/automation-flow-door-package-address.test.ts b/packages/runtime/src/domains/automation-flow-door-package-address.test.ts index 55f4a581494..4fbbd3b1eaf 100644 --- a/packages/runtime/src/domains/automation-flow-door-package-address.test.ts +++ b/packages/runtime/src/domains/automation-flow-door-package-address.test.ts @@ -211,7 +211,13 @@ async function boot() { return { armed: contenders[0], contenders }; }; - return { call, refusal, restMeta, dispatcherMeta, rows, bindings, labelIn, armFromStore, flows, registerFlow, unregisterFlow }; + /** [#38174] A package-less (loose) flow row, laid straight into the store as the save door writes one. */ + const layLooseRow = (name: string, label: string) => engine.insert('sys_metadata', { + type: 'flow', name, namespace: 'default', package_id: null, scope: 'platform', strategy: 'merge', state: 'active', version: 1, + metadata: JSON.stringify(flowOf(name, label)), + }, { context: { isSystem: true } } as any); + + return { call, refusal, restMeta, dispatcherMeta, rows, bindings, labelIn, armFromStore, flows, registerFlow, unregisterFlow, layLooseRow }; } type Rig = Awaited>; @@ -239,14 +245,45 @@ describe('[#23292] a flow one package holds, or none: the door\'s save lands in expect(await rig.labelIn('solo_flow', ALPHA)).toBe('Edited at the door'); }, 60_000); - it('POST / of a flow no package holds saves the package-unbound row', async () => { + // [#38174] The create door `POST /` is retired; a package-less CREATE is + // refused (ADR-0070 D1). The package-unbound row a flow no package holds + // still takes `PUT /:name` in place, so the row is laid straight into the store. + it('PUT /:name of a flow no package holds saves the package-unbound row', async () => { const rig = await boot(); + await rig.layLooseRow('plain_flow', 'Seeded loose'); + await rig.armFromStore('plain_flow'); - const answer = await rig.call('POST', '/automation', flowOf('plain_flow', 'Created at the door')); + const answer = await rig.call('PUT', '/automation/plain_flow', flowOf('plain_flow', 'Edited at the door')); expect(answer.status).toBe(200); expect(await rig.bindings('plain_flow')).toEqual([null]); - expect(await rig.labelIn('plain_flow', null)).toBe('Created at the door'); + expect(await rig.labelIn('plain_flow', null)).toBe('Edited at the door'); + }, 60_000); + + it('[#38174] PUT /:name of a NEW name: 422 WRITABLE_PACKAGE_REQUIRED naming the /meta ?package= route, nothing stored, the name withdrawn; the route, followed, saves into that package', async () => { + const rig = await boot(); + + const answer = await rig.refusal('PUT', '/automation/plain_flow', flowOf('plain_flow', 'Created at the door')); + + expect({ status: answer.status, code: answer.code }).toEqual({ status: 422, code: 'WRITABLE_PACKAGE_REQUIRED' }); + expect(await rig.rows('plain_flow')).toEqual([]); + expect(rig.flows.has('plain_flow')).toBe(false); + const route = printedPackageRoute(answer.message); + expect(route).toEqual({ method: 'PUT', path: '/api/v1/meta/flow/plain_flow' }); + + expect(await rig.dispatcherMeta(route.method, route.path, ALPHA, flowOf('plain_flow', 'Created in a package'))) + .toEqual({ status: 200, code: undefined }); + expect(await rig.bindings('plain_flow')).toEqual([ALPHA]); + }, 60_000); + + it('[#38174] POST / — the retired create door — is not served and stores nothing', async () => { + const rig = await boot(); + + const answer = await rig.call('POST', '/automation', flowOf('plain_flow', 'Created at the door')); + + expect(answer).toEqual({ status: undefined, code: undefined }); + expect(rig.registerFlow).not.toHaveBeenCalled(); + expect(await rig.rows('plain_flow')).toEqual([]); }, 60_000); }); @@ -279,28 +316,29 @@ for (const order of [[ALPHA, BETA], [BETA, ALPHA]] as const) { expect(rig.flows.get(SHARED)).toBe(armed); }, 60_000); - it('POST / onto the name the engine holds (an overwrite): 409, neither row changes, the held definition is back', async () => { + // [#38174] `POST /` is retired: it is no longer a call site at all. + it('POST / onto the name the engine holds: not served, neither row changes, the held definition stays', async () => { const rig = await twoPackageFlow(order); const { armed } = await rig.armFromStore(SHARED); const before = await rig.rows(SHARED); const answer = await rig.call('POST', '/automation', flowOf(SHARED, 'Posted at the door')); - expect(answer).toEqual({ status: 409, code: 'RESOURCE_CONFLICT' }); + expect(answer).toEqual({ status: undefined, code: undefined }); expect(await rig.rows(SHARED)).toEqual(before); + expect(rig.registerFlow).not.toHaveBeenCalled(); expect(rig.flows.get(SHARED)).toBe(armed); }, 60_000); - it('POST / of the name while the engine holds none: 409, neither row changes, and the name is withdrawn', async () => { + it('POST / of the name while the engine holds none: not served, neither row changes, nothing registered', async () => { const rig = await twoPackageFlow(order); const before = await rig.rows(SHARED); const answer = await rig.call('POST', '/automation', flowOf(SHARED, 'Posted at the door')); - expect(answer).toEqual({ status: 409, code: 'RESOURCE_CONFLICT' }); + expect(answer).toEqual({ status: undefined, code: undefined }); expect(await rig.rows(SHARED)).toEqual(before); - expect(rig.registerFlow).toHaveBeenCalledTimes(1); - expect(rig.unregisterFlow).toHaveBeenCalledWith(SHARED); + expect(rig.registerFlow).not.toHaveBeenCalled(); expect(rig.flows.has(SHARED)).toBe(false); }, 60_000); @@ -358,10 +396,12 @@ for (const order of [[ALPHA, BETA], [BETA, ALPHA]] as const) { expect(await rig.labelIn(SHARED, BETA)).toBe('Saved through the dispatcher'); }, 60_000); - it('POST / names the same PUT ?package= route, which saves that package\'s row', async () => { + it('PUT /:name with the engine holding none names the same PUT ?package= route, which saves that package\'s row', async () => { + // [#38174] Was `POST /`, now retired: the remaining definition door + // reached while the engine holds no contender. const rig = await twoPackageFlow(order); - const answer = await rig.refusal('POST', '/automation', flowOf(SHARED, 'Posted at the door')); + const answer = await rig.refusal('PUT', `/automation/${SHARED}`, flowOf(SHARED, 'Posted at the door')); expect({ status: answer.status, code: answer.code }).toEqual({ status: 409, code: 'RESOURCE_CONFLICT' }); const route = printedPackageRoute(answer.message); diff --git a/packages/runtime/src/domains/automation-flow-save-actor.test.ts b/packages/runtime/src/domains/automation-flow-save-actor.test.ts index e25a4376ab1..41ce51a43ae 100644 --- a/packages/runtime/src/domains/automation-flow-save-actor.test.ts +++ b/packages/runtime/src/domains/automation-flow-save-actor.test.ts @@ -42,6 +42,12 @@ const SOURCE = 'customer_source_flow'; * `.custom`: its copy names this installed, writable package. */ const TARGET = { id: 'com.acme.workspace', name: 'Workspace', version: '1.0.0', type: 'app', namespace: 'ws' }; +/** + * [#38174] `POST /` is retired and `PUT /:name` updates flows that exist: a new + * flow is created in a package through the metadata door (ADR-0070 D1). The + * flows the update cases edit are created there, by {@link seedFlow}. + */ +const PKG = 'test_pkg'; const definitionOf = (name: string, label: string) => ({ name, @@ -85,6 +91,7 @@ async function boot() { engine.registry.registerObject(SysMetadataAuditObject as any, TEST_PACKAGE_ID); await engine.syncSchemas(); engine.registry.installPackage(TARGET as any, 'code'); + engine.registry.installPackage({ id: PKG, name: PKG, version: '1.0.0', type: 'app' } as any, 'authored'); const protocol = new ObjectStackProtocolImplementation(engine as any); const flows = new Map([[SOURCE, definitionOf(SOURCE, 'Source')]]); @@ -111,15 +118,22 @@ async function boot() { .map((h: any) => h.recorded_by ?? null), }; }; - return { dispatcher: new HttpDispatcher(kernel), recorded }; + /** Create `name` in {@link PKG} the way the metadata door does, as `actor` (or nobody). */ + const seedFlow = async (name: string, label: string, actor?: string) => { + const definition = definitionOf(name, label); + await protocol.saveMetaItem({ type: 'flow', name, item: definition, packageId: PKG, ...(actor ? { actor } : {}) } as any); + flows.set(name, definition); + }; + return { dispatcher: new HttpDispatcher(kernel), recorded, seedFlow }; } const statusOf = (r: { response?: { status?: number } }) => r.response?.status; describe('[#27414] the /automation definition doors record the user who saved', () => { - it('POST / records the creator; PUT /:name by another user records that user as the updater', async () => { + it('PUT /:name by another user records that user as the updater, keeping the creator', async () => { const h = await boot(); - expect(statusOf(await h.dispatcher.handleAutomation('', 'POST', definitionOf('new_flow', 'v1'), author('u_author'), undefined))).toBe(200); + // [#38174] Created through the metadata door, in a package (the create door is retired). + await h.seedFlow('new_flow', 'v1', 'u_author'); expect(await h.recorded('new_flow')).toEqual({ created_by: 'u_author', updated_by: 'u_author', recorded_by: ['u_author'] }); const definition = definitionOf('new_flow', 'v2'); @@ -136,9 +150,10 @@ describe('[#27414] the /automation definition doors record the user who saved', expect(await h.recorded('my_copy')).toEqual({ created_by: 'u_admin', updated_by: 'u_admin', recorded_by: ['u_admin'] }); }, 60_000); - it('CONTROL: a caller with no user records null on all three doors, never a label', async () => { + it('CONTROL: a caller with no user records null on both doors, never a label', async () => { const h = await boot(); - expect(statusOf(await h.dispatcher.handleAutomation('', 'POST', definitionOf('sys_flow', 'v1'), SYSTEM(), undefined))).toBe(200); + // [#38174] Created through the metadata door with no actor (the create door is retired). + await h.seedFlow('sys_flow', 'v1'); expect(statusOf(await h.dispatcher.handleAutomation('/sys_flow', 'PUT', { definition: definitionOf('sys_flow', 'v2') }, SYSTEM(), undefined))).toBe(200); expect(await h.recorded('sys_flow')).toEqual({ created_by: null, updated_by: null, recorded_by: [null, null] }); diff --git a/packages/runtime/src/domains/automation-notify-slack-composition.test.ts b/packages/runtime/src/domains/automation-notify-slack-composition.test.ts index 0da7b28a541..026a25e049d 100644 --- a/packages/runtime/src/domains/automation-notify-slack-composition.test.ts +++ b/packages/runtime/src/domains/automation-notify-slack-composition.test.ts @@ -97,23 +97,25 @@ async function boot(opts: { slack: boolean }) { return { dispatcher: new HttpDispatcher(kernel as never), saveMetaItem, flows }; } +// [#38174] `POST /` is retired: each first write goes through `PUT /:name` (the +// store double's save is mocked, so the door's register-then-save path runs). describe('a notify node naming slack at the /automation save doors (#34730)', () => { it('is refused 400 where connector-slack is not composed, and nothing is saved', async () => { const h = await boot({ slack: false }); - const { response } = await h.dispatcher.handleAutomation('', 'POST', notifyFlow('tell_slack', ['inbox', 'slack']), AUTHOR(), undefined); + const { response } = await h.dispatcher.handleAutomation('/tell_slack', 'PUT', notifyFlow('tell_slack', ['inbox', 'slack']), AUTHOR(), undefined); expect([(response as any)?.status, (response as any)?.body?.error?.code]).toEqual([400, 'VALIDATION_FAILED']); expect(String((response as any)?.body?.error?.message)).toContain("names channel 'slack' at nodes.1.config.channels.1"); expect(h.saveMetaItem).not.toHaveBeenCalled(); expect(h.flows.has('tell_slack')).toBe(false); // The control: the same composition saves a node naming only channels it knows. - const known = await h.dispatcher.handleAutomation('', 'POST', notifyFlow('tell_inbox', ['inbox', 'email']), AUTHOR(), undefined); + const known = await h.dispatcher.handleAutomation('/tell_inbox', 'PUT', notifyFlow('tell_inbox', ['inbox', 'email']), AUTHOR(), undefined); expect((known.response as any)?.status).toBe(200); }); it('saves where connector-slack is composed', async () => { const h = await boot({ slack: true }); - const { response } = await h.dispatcher.handleAutomation('', 'POST', notifyFlow('tell_slack', ['inbox', 'slack']), AUTHOR(), undefined); + const { response } = await h.dispatcher.handleAutomation('/tell_slack', 'PUT', notifyFlow('tell_slack', ['inbox', 'slack']), AUTHOR(), undefined); expect((response as any)?.status).toBe(200); expect(h.saveMetaItem).toHaveBeenCalledTimes(1); expect(h.flows.has('tell_slack')).toBe(true); diff --git a/packages/runtime/src/domains/automation-packaged-base-lock.test.ts b/packages/runtime/src/domains/automation-packaged-base-lock.test.ts index 78bc5d1e0ea..9d85849f3bf 100644 --- a/packages/runtime/src/domains/automation-packaged-base-lock.test.ts +++ b/packages/runtime/src/domains/automation-packaged-base-lock.test.ts @@ -272,26 +272,28 @@ describe('a PACKAGED flow — the base is locked at both /automation definition }); }); - it('POST / onto a packaged flow\'s name — a create that would overwrite — is refused as a locked base; a new name is created', async () => { + // [#38174] The create door `POST /` is RETIRED: no branch answers it, so + // neither a packaged name nor a new one is written through it (a new flow + // is created by `PUT /meta/flow/:name?package=`, ADR-0070 D1). + it('POST / — the retired create door — is not served: a packaged flow\'s name is not overwritten, and no new name is created', async () => { const h = boot(); const before = h.held(PACKAGED); const overwrite = await h.dispatcher.handleAutomation( '', 'POST', definitionOf(PACKAGED, 'Overwritten via create'), AUTHOR(), undefined, ); - expect(statusOf(overwrite.response)).toBe(403); - expect(errorOf(overwrite.response).code).toBe('NOT_OVERRIDABLE'); - expectRegimeCPrescription(overwrite.response, 'save'); + expect(overwrite.handled).toBe(false); + expect(overwrite.response).toBeUndefined(); expect(h.registerFlow).not.toHaveBeenCalled(); expect(h.held(PACKAGED)).toBe(before); - // Control: a name no code package ships is created exactly as before. h.standInStore(); const created = await h.dispatcher.handleAutomation( '', 'POST', definitionOf('brand_new_flow', 'New'), AUTHOR(), undefined, ); - expect(statusOf(created.response)).toBe(200); - expect(h.registerFlow).toHaveBeenCalledWith('brand_new_flow', expect.objectContaining({ label: 'New' })); + expect(created.handled).toBe(false); + expect(created.response).toBeUndefined(); + expect(h.registerFlow).not.toHaveBeenCalled(); }); it('keys on the NAME the artifact loader registered — provenance stamps in the request body decide nothing', async () => { diff --git a/packages/runtime/src/domains/automation-put-post-error-parity.test.ts b/packages/runtime/src/domains/automation-put-post-error-parity.test.ts index b671128d5b2..438a6975e46 100644 --- a/packages/runtime/src/domains/automation-put-post-error-parity.test.ts +++ b/packages/runtime/src/domains/automation-put-post-error-parity.test.ts @@ -219,9 +219,13 @@ function assertValidationEnvelope(res: any, label: string) { return fields; } +// [#38174] The create door `POST /automation` is RETIRED (a new flow is +// created by `PUT /meta/flow/:name?package=`, ADR-0070 D1), so there is no +// second definition door left to drift from `PUT /:name`: the parity pin +// becomes "POST is not served at all, and PUT keeps the whole envelope". describe('#8123 — POST and PUT agree on the class of an identical flow refusal', () => { it.each(Object.entries(BAD_BODIES))( - 'case "%s": POST and PUT answer the SAME envelope for the identical body', + 'case "%s": POST is not served (#38174) and PUT answers the whole envelope for the body', async (label, body) => { const post = makeDispatcher(); const postResult: any = await postFlow(post.dispatcher, body); @@ -229,25 +233,16 @@ describe('#8123 — POST and PUT agree on the class of an identical flow refusal const put = makeDispatcher(); const putResult: any = await putFlow(put.dispatcher, (body as any).name, body); - // Each door independently: the whole envelope, not just "not 500". - const postFields = assertValidationEnvelope(postResult.response, `POST ${label}`); - const putFields = assertValidationEnvelope(putResult.response, `PUT ${label}`); - - // THE PIN: the two doors compared directly, for the SAME body. - // A per-route assertion above would already have caught #8123 - // (PUT still 500) — this comparison is what keeps them from - // drifting apart again in either direction, on any future change - // to either branch. - expect(putResult.response.status, `${label}: status parity`).toBe(postResult.response.status); - expect(putResult.response.body.error.code, `${label}: code parity`).toBe(postResult.response.body.error.code); - expect(putFields, `${label}: fields parity`).toEqual(postFields); - expect(putResult.response.body.error.message, `${label}: message parity`) - .toBe(postResult.response.body.error.message); - - // The engine was still ASKED on both doors — a classification of - // its verdict, not a new pre-check that changed which bodies - // reach it. - expect(post.calls, `${label}: POST must still consult the engine`).toContain((body as any).name); + // The retired door answers nothing and never reaches the engine. + expect(postResult.handled, `POST ${label}: no branch answers the retired door`).toBe(false); + expect(postResult.response, `POST ${label}`).toBeUndefined(); + expect(post.calls, `${label}: POST must not consult the engine`).not.toContain((body as any).name); + + // The remaining door: the whole envelope, not just "not 500". + assertValidationEnvelope(putResult.response, `PUT ${label}`); + + // The engine was still ASKED on PUT — a classification of its + // verdict, not a new pre-check that changed which bodies reach it. expect(put.calls, `${label}: PUT must still consult the engine`).toContain((body as any).name); }, ); @@ -320,12 +315,12 @@ describe('#8123 — POST and PUT agree on the class of an identical flow refusal // --------------------------------------------------------------------------- describe('#8123 — what must not change', () => { - it('a well-formed body still registers, 200, on BOTH doors', async () => { + it('a well-formed body still registers, 200, on PUT — and the retired POST registers nothing (#38174)', async () => { const post = makeDispatcher(); const postResult: any = await postFlow(post.dispatcher, WELL_FORMED); - expect(postResult.response?.status).toBe(200); - expect(postResult.response?.body?.success).toBe(true); - expect(post.registered.has('welcome_flow')).toBe(true); + expect(postResult.handled).toBe(false); + expect(postResult.response).toBeUndefined(); + expect(post.registered.has('welcome_flow')).toBe(false); const put = makeDispatcher(); const putResult: any = await putFlow(put.dispatcher, WELL_FORMED.name, WELL_FORMED); diff --git a/packages/runtime/src/domains/automation-register-error-class.test.ts b/packages/runtime/src/domains/automation-register-error-class.test.ts index 02533451c36..63667cbabfd 100644 --- a/packages/runtime/src/domains/automation-register-error-class.test.ts +++ b/packages/runtime/src/domains/automation-register-error-class.test.ts @@ -218,8 +218,12 @@ const BAD_BODIES = { }, } as const; +// [#38174] The create door `POST /automation` is retired; the definition +// write door that remains, `PUT /automation/:name`, serves the same engine +// verdict through the same `flowDefinitionRefusal` (#8123), so the class +// these cases pin is driven through it. function postFlow(dispatcher: HttpDispatcher, body: unknown) { - return dispatcher.handleAutomation('', 'POST', body, CTX); + return dispatcher.handleAutomation(`/${WELL_FORMED.name}`, 'PUT', body, CTX); } /** @@ -393,13 +397,13 @@ describe('#8055 — what must not change', () => { }); it('the #3899 body checks still refuse BEFORE the engine is asked', async () => { - // A definition with no usable `name` must never reach `registerFlow` — - // it would register under the key `undefined`. That refusal is thrown, - // not returned, and this change must not have swallowed it into the new - // catch arm. + // A body that is not a definition object must never reach `registerFlow`. + // That refusal is thrown, not returned, and this change must not have + // swallowed it into the new catch arm. [#38174] On `PUT /:name` the name + // rides the path, so the #3899 check is the definition-shape one. const { dispatcher, spies } = makeDispatcher(); - await expect(postFlow(dispatcher, { label: 'x', type: 'autolaunched', nodes: [], edges: [] })) + await expect(postFlow(dispatcher, [{ label: 'x', type: 'autolaunched', nodes: [], edges: [] }])) .rejects.toThrow(); expect(spies.registerFlow).not.toHaveBeenCalled(); }); diff --git a/packages/runtime/src/domains/automation-tenant-authored-write.test.ts b/packages/runtime/src/domains/automation-tenant-authored-write.test.ts index 637dfc4e319..171e89affe0 100644 --- a/packages/runtime/src/domains/automation-tenant-authored-write.test.ts +++ b/packages/runtime/src/domains/automation-tenant-authored-write.test.ts @@ -122,10 +122,11 @@ const errorOf = (response: any): { code?: unknown } => response?.body?.error ?? const dataOf = (response: any): any => response?.body?.data; describe('[#20761] the /automation definition-write doors apply the one authoring rule', () => { - it('POST / refuses a definition claiming a package for a name no package ships, and registers nothing', async () => { + // [#38174] `POST /` is retired: the claim on a name no package ships is driven through `PUT /:name`. + it('PUT /:name refuses a definition claiming a package for a name no package ships, and registers nothing', async () => { const h = boot(); const { response } = await h.dispatcher.handleAutomation( - '', 'POST', { ...definitionOf('new_flow'), ...ASSERTED }, AUTHOR(), undefined, + '/new_flow', 'PUT', { ...definitionOf('new_flow'), ...ASSERTED }, AUTHOR(), undefined, ); expect(statusOf(response)).toBe(422); @@ -147,14 +148,15 @@ describe('[#20761] the /automation definition-write doors apply the one authorin expect(h.held(CUSTOMER)).toEqual(definitionOf(CUSTOMER)); }); - it('a round trip of a shipped flow is refused as a locked base, on both definition doors', async () => { + it('a round trip of a shipped flow is refused as a locked base at the definition door; the retired POST / answers nothing', async () => { const h = boot(); const served = h.held(PACKAGED) as Record; - for (const [path, method] of [[`/${PACKAGED}`, 'PUT'], ['', 'POST']] as const) { - const { response } = await h.dispatcher.handleAutomation(path, method, served, AUTHOR(), undefined); - expect(statusOf(response), `${method} ${path}`).toBe(403); - expect(errorOf(response).code).toBe('NOT_OVERRIDABLE'); - } + const { response } = await h.dispatcher.handleAutomation(`/${PACKAGED}`, 'PUT', served, AUTHOR(), undefined); + expect(statusOf(response)).toBe(403); + expect(errorOf(response).code).toBe('NOT_OVERRIDABLE'); + // [#38174] `POST /` is retired: no branch answers it. + const retired = await h.dispatcher.handleAutomation('', 'POST', served, AUTHOR(), undefined); + expect(retired.handled).toBe(false); expect(h.registerFlow).not.toHaveBeenCalled(); }); diff --git a/packages/runtime/src/domains/automation-toggle-deny-message.test.ts b/packages/runtime/src/domains/automation-toggle-deny-message.test.ts index 89da74a506c..36670d612cf 100644 --- a/packages/runtime/src/domains/automation-toggle-deny-message.test.ts +++ b/packages/runtime/src/domains/automation-toggle-deny-message.test.ts @@ -123,13 +123,10 @@ const statusOf = (r: any): unknown => r?.response?.status; const codeOf = (r: any): unknown => r?.response?.body?.error?.code ?? r?.response?.body?.error?.details?.code; const messageOf = (r: any): string => String(r?.response?.body?.error?.message ?? ''); -/** The three DEFINITION writes — the arm whose sentence must NOT move. */ +/** The DEFINITION writes — the arm whose sentence must NOT move. */ const DEFINITION_WRITES = [ - { - name: 'POST /automation (createFlow)', - drive: (h: Harness) => h.dispatch('POST', '/automation', { ...DEFINITION, name: 'probe_flow_x' }), - spy: (h: Harness) => h.registerFlow, - }, + // [#38174] `POST /automation` (createFlow) is retired — no branch answers it, + // so it has no refusal sentence; pinned as unhandled below. { name: 'PUT /automation/:name (updateFlow)', drive: (h: Harness) => h.dispatch('PUT', `/automation/${FLOW}`, { ...DEFINITION, label: 'clobbered' }), @@ -226,6 +223,15 @@ describe('#11666 — the enablement door refuses in its own words', () => { }); } + it('[#38174] POST /automation (the retired create door) answers nothing and registers nothing', async () => { + const h = boot(); + const result = await h.dispatch('POST', '/automation', { ...DEFINITION, name: 'probe_flow_x' }); + + expect(result?.handled).toBe(false); + expect(messageOf(result)).toBe(''); + expect(h.registerFlow).not.toHaveBeenCalled(); + }); + it('a flow literally NAMED `toggle` is still a definition write on PUT /automation/toggle', async () => { // The sentence is chosen by the OPERATION, never by a substring of // the flow name: `parts[1]` is what the enablement arm reads, and a diff --git a/packages/runtime/src/domains/automation-walled-definition-write.test.ts b/packages/runtime/src/domains/automation-walled-definition-write.test.ts index e16aa57cb19..03322a357d2 100644 --- a/packages/runtime/src/domains/automation-walled-definition-write.test.ts +++ b/packages/runtime/src/domains/automation-walled-definition-write.test.ts @@ -52,7 +52,8 @@ const OPERATOR = { userId: 'u_operator', systemPermissions: ['manage_metadata'], const SYSTEM = { userId: 'usr_system', isSystem: true }; const WRITES: Array<{ path: string; method: string; body?: unknown }> = [ - { path: '/', method: 'POST', body: { ...DEFINITION, name: 'tenant_flow' } }, + // [#38174] `POST /` is retired: a first write of a new name reaches `PUT /:name`. + { path: '/tenant_flow', method: 'PUT', body: { ...DEFINITION, name: 'tenant_flow' } }, { path: `/${FLOW}`, method: 'PUT', body: { ...DEFINITION, label: 'Edited' } }, { path: `/${FLOW}`, method: 'DELETE' }, { path: `/${FLOW}/clone`, method: 'POST', body: { name: 'my_router', label: 'My Router' } }, @@ -103,7 +104,7 @@ describe('[ADR-0131 D12 items 7–8] /automation definition writes — the walle it('the capability gate still answers first: a caller without `manage_metadata` gets its sentence, not the posture one', async () => { const stack = boot('isolated'); - const { response } = await stack.dispatcher.handleAutomation('/', 'POST', DEFINITION, ctx({ userId: 'u_x', systemPermissions: [] }), undefined); + const { response } = await stack.dispatcher.handleAutomation(`/${FLOW}`, 'PUT', DEFINITION, ctx({ userId: 'u_x', systemPermissions: [] }), undefined); expect((response as any)?.status).toBe(403); expect(String((response as any)?.body?.error?.message)).toContain('requires the `manage_metadata` capability'); expect(touched(stack)).toEqual([]); diff --git a/packages/runtime/src/domains/automation-write-capability-gate.test.ts b/packages/runtime/src/domains/automation-write-capability-gate.test.ts index f6e63651052..9f776dc6ab0 100644 --- a/packages/runtime/src/domains/automation-write-capability-gate.test.ts +++ b/packages/runtime/src/domains/automation-write-capability-gate.test.ts @@ -183,12 +183,8 @@ const codeOf = (response: unknown): unknown => { * subset someone remembered to copy. */ const AUTHORING_WRITES = [ - { - name: 'POST /automation (createFlow)', - drive: (h: Harness, ctx: HttpProtocolContext) => - h.dispatcher.handleAutomation('', 'POST', { ...DEFINITION, name: 'probe_flow_x' }, ctx, undefined), - spy: (h: Harness) => h.registerFlow, - }, + // [#38174] `POST /automation` (createFlow) is retired — no branch answers it, + // so there is no write left to gate; pinned as unhandled in the positive control. { name: 'PUT /automation/:name (updateFlow)', drive: (h: Harness, ctx: HttpProtocolContext) => @@ -235,8 +231,10 @@ describe('#10145 — /automation authoring writes require `manage_metadata`', () // The gate sits ahead of #3899's body checks, so an unentitled caller // learns nothing about the definition contract by probing it, and // nothing reaches the registry on any body. + // [#38174] Driven through `PUT /:name` (the create door is retired) + // with a body #3899's definition-shape check would refuse. const h = boot(); - const { response } = await h.dispatcher.handleAutomation('', 'POST', { label: 'no name' }, UNENTITLED(), undefined); + const { response } = await h.dispatcher.handleAutomation(`/${FLOW}`, 'PUT', 'not a definition', UNENTITLED(), undefined); expect(statusOf(response)).toBe(403); expect(codeOf(response)).toBe('PERMISSION_DENIED'); @@ -270,24 +268,28 @@ describe('#10145 — /automation authoring writes require `manage_metadata`', () // run-state gate in this domain already take. const bare = boot({ automation: false }); - const refused = await bare.dispatcher.handleAutomation('', 'POST', { ...DEFINITION }, UNENTITLED(), undefined); + // [#38174] Driven through `PUT /:name` — the create door is retired. + const refused = await bare.dispatcher.handleAutomation(`/${FLOW}`, 'PUT', { ...DEFINITION }, UNENTITLED(), undefined); expect(statusOf(refused.response)).toBe(403); expect(codeOf(refused.response)).toBe('PERMISSION_DENIED'); - const entitled = await bare.dispatcher.handleAutomation('', 'POST', { ...DEFINITION }, AUTHOR(), undefined); + const entitled = await bare.dispatcher.handleAutomation(`/${FLOW}`, 'PUT', { ...DEFINITION }, AUTHOR(), undefined); expect(statusOf(entitled.response)).toBe(501); }); }); describe('positive control — an entitled principal writes exactly what it wrote before', () => { - it('POST /automation registers the definition verbatim', async () => { + // [#38174] The create door is retired: even an entitled author gets + // no answer from `POST /automation`, and nothing is registered. + it('POST /automation — the retired create door — registers nothing, even for an author', async () => { const h = boot(); const body = { ...DEFINITION, name: 'probe_flow_x' }; - const { response } = await h.dispatcher.handleAutomation('', 'POST', body, AUTHOR(), undefined); + const result = await h.dispatcher.handleAutomation('', 'POST', body, AUTHOR(), undefined); - expect(statusOf(response)).toBe(200); - expect(h.registerFlow).toHaveBeenCalledWith('probe_flow_x', body); - expect(h.registered()).toEqual([FLOW, 'probe_flow_x'].sort()); + expect(result.handled).toBe(false); + expect(result.response).toBeUndefined(); + expect(h.registerFlow).not.toHaveBeenCalled(); + expect(h.registered()).toEqual([FLOW]); }); it('PUT /automation/:name updates through the same one argument shape', async () => { diff --git a/packages/runtime/src/domains/automation-write-doors-durable-34145.test.ts b/packages/runtime/src/domains/automation-write-doors-durable-34145.test.ts index 4f692138f07..0e185f27b3a 100644 --- a/packages/runtime/src/domains/automation-write-doors-durable-34145.test.ts +++ b/packages/runtime/src/domains/automation-write-doors-durable-34145.test.ts @@ -232,7 +232,8 @@ describe('[#34145] the clone door judges the new name taken over every holder', }); describe('[#34145] a refused definition write puts back what the engine held over every holder', () => { - for (const [door, method, path] of [['PUT /:name', 'PUT', '/' + SOLO], ['POST / onto the name', 'POST', '/']] as const) { + // [#38174] `POST /` (onto the name) is retired: `PUT /:name` is the definition write left. + for (const [door, method, path] of [['PUT /:name', 'PUT', '/' + SOLO]] as const) { it(`${door}: the held body is registered again (FROM: the name was withdrawn)`, async () => { const { call, automation, flows } = rig({ holder: 'disabled', saveRefuses: true }); const held = flows.get(SOLO); @@ -312,7 +313,8 @@ describe('[#34145] DELETE /:name finds a flow the engine holds over every holder * store's address: the booted-kernel describe below). */ describe('[#34145] a name two packages hold is read on its served holder at the definition writes', () => { - const doors = [['PUT /:name', 'PUT', '/' + SHARED], ['POST /', 'POST', '/']] as const; + // [#38174] `POST /` is retired: `PUT /:name` is the definition write left. + const doors = [['PUT /:name', 'PUT', '/' + SHARED]] as const; it.each(doors)('%s, no metadata store: admitted, 200, registered into the served holder (as on main)', async (_door, method, path) => { const { call, automation, flows } = rig({ holder: 'enabled', shared: 'withdrawn', store: false }); @@ -419,7 +421,8 @@ describe('[#34145] booted kernel: a package-less write onto a flow name an enabl if (root) rmSync(root, { recursive: true, force: true }); }); - it.each(['PUT', 'POST'] as const)('%s: 200, the enabled holder\'s row carries the edit, the disabled holder\'s row is byte-unchanged (as on main)', async (method) => { + // [#38174] `POST /` is retired: `PUT /:name` is the definition write left. + it.each(['PUT'] as const)('%s: 200, the enabled holder\'s row carries the edit, the disabled holder\'s row is byte-unchanged (as on main)', async (method) => { const before = await rows(); expect(Object.keys(before).sort()).toEqual([DISABLED, ENABLED].sort()); engine.registry.disablePackage(DISABLED); diff --git a/packages/runtime/src/domains/field-error-code-catalog.test.ts b/packages/runtime/src/domains/field-error-code-catalog.test.ts index ab15e6e6733..88dccbcb729 100644 --- a/packages/runtime/src/domains/field-error-code-catalog.test.ts +++ b/packages/runtime/src/domains/field-error-code-catalog.test.ts @@ -318,13 +318,11 @@ const CENSUS: CensusCase[] = [ { site: `automation.ts run-lifecycle body (${verb}) — \`reason\` not a string`, run: automationDoor(runLifecyclePath(verb), 'POST', { reason: 42 }, OPERATOR), rows: [{ field: 'reason', code: 'invalid_type' }] }, ]), - // automation.ts `POST /` (createFlow), `PUT /:name` (updateFlow) and `flowDefinitionRefusal`'s fallback row - { site: 'automation.ts POST / — body not an object', run: automationDoor('', 'POST', 'garbage', AUTHOR), rows: [{ field: '(body)', code: 'invalid_type' }] }, - { site: 'automation.ts POST / — `name` missing', run: automationDoor('', 'POST', { trigger: { type: 'manual' } }, AUTHOR), rows: [{ field: 'name', code: 'required' }] }, - { site: 'automation.ts POST / — `name` not a string', run: automationDoor('', 'POST', { name: 42 }, AUTHOR), rows: [{ field: 'name', code: 'invalid_type' }] }, + // automation.ts `PUT /:name` (updateFlow) and `flowDefinitionRefusal`'s fallback row. + // [#38174] `POST /` (createFlow) is retired with the rows it built; the fallback row is reached through PUT. { site: 'automation.ts flowDefinitionRefusal — an engine refusal with no status and no issues', - run: automationDoor('', 'POST', { name: 'new_flow', nodes: [] }, AUTHOR, { registerThrows: new Error('the engine refused this definition') }), + run: automationDoor('/welcome_flow', 'PUT', { name: 'welcome_flow', nodes: [] }, AUTHOR, { registerThrows: new Error('the engine refused this definition') }), rows: [{ field: '(body)', code: 'invalid_value' }], }, { site: 'automation.ts PUT /:name — definition not an object', run: automationDoor('/welcome_flow', 'PUT', 'garbage', AUTHOR), rows: [{ field: '(body)', code: 'invalid_type' }] }, diff --git a/packages/runtime/src/domains/mcp-package-object-discovery.test.ts b/packages/runtime/src/domains/mcp-package-object-discovery.test.ts index 68ad61f9281..bd8fe80aeaf 100644 --- a/packages/runtime/src/domains/mcp-package-object-discovery.test.ts +++ b/packages/runtime/src/domains/mcp-package-object-discovery.test.ts @@ -843,12 +843,24 @@ async function listedGlobalActions(bridge: any): Promise { */ async function saveAuthoredAction(kernel: ObjectKernel, boundTo?: string): Promise { const protocol: any = kernel.getService('protocol'); - await protocol.saveMetaItem({ type: 'action', name: AUTHORED, item: objectLessAction(AUTHORED, AUTHORED_HANDLER) }); + // [#38174] A package-less CREATE is refused (ADR-0070 D1): each + // environment-authored loose row is laid straight into the store, and the + // save door's package-less save of it runs in place. + const engine: any = kernel.getService('objectql'); + const layLooseRow = (name: string, item: Record) => engine.insert('sys_metadata', { + type: 'action', name, namespace: 'default', package_id: null, scope: 'platform', strategy: 'merge', + state: 'active', version: 1, metadata: JSON.stringify(item), + }, { context: { isSystem: true } }); + const authored = objectLessAction(AUTHORED, AUTHORED_HANDLER); + await layLooseRow(AUTHORED, authored); + await protocol.saveMetaItem({ type: 'action', name: AUTHORED, item: authored }); if (boundTo) { + const bound = { ...objectLessAction(AUTHORED_BOUND, AUTHORED_HANDLER), objectName: boundTo }; + await layLooseRow(AUTHORED_BOUND, bound); await protocol.saveMetaItem({ type: 'action', name: AUTHORED_BOUND, - item: { ...objectLessAction(AUTHORED_BOUND, AUTHORED_HANDLER), objectName: boundTo }, + item: bound, }); } } diff --git a/packages/runtime/src/domains/meta-app-package-id-key.test.ts b/packages/runtime/src/domains/meta-app-package-id-key.test.ts index 6275bbcb89f..811dafcf712 100644 --- a/packages/runtime/src/domains/meta-app-package-id-key.test.ts +++ b/packages/runtime/src/domains/meta-app-package-id-key.test.ts @@ -55,6 +55,8 @@ const PREFIX = '/api/v1'; const META = `${PREFIX}/meta`; /** `registry.registerObject` requires a package id (see the sibling real-stack tests). */ const TEST_PACKAGE_ID = 'objectstack-test'; +/** [#38174] The writable package the stored view is created in (ADR-0070 D1: a create names one). */ +const VIEW_PKG = 'test_pkg'; /** A package whose app the member does not hold (`requiredPermissions`). */ const PAYROLL_PKG = 'com.acme.payroll'; @@ -123,11 +125,12 @@ async function bootStore() { useNullAsDefault: true, }), true); await engine.init(); - engine.registry.registerObject(TASK as any, TEST_PACKAGE_ID); + engine.registry.registerObject(TASK as any, VIEW_PKG); engine.registry.registerObject(SysMetadata as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataHistoryObject as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataAuditObject as any, TEST_PACKAGE_ID); await engine.syncSchemas(); + engine.registry.installPackage({ id: VIEW_PKG, name: VIEW_PKG, version: '1.0.0', type: 'app' } as any, 'authored'); engine.registry.registerApp(clone(PAYROLL_APP), PAYROLL_PKG); engine.registry.registerApp(clone(BUILD_APP), BUILD_PKG); engine.registry.registerApp(clone(SHADOW_APP), VIEW_KEY); @@ -135,6 +138,7 @@ async function bootStore() { await protocol.saveMetaItem({ type: 'view', name: VIEW_KEY, + packageId: VIEW_PKG, item: { name: VIEW_KEY, label: 'Grid', object: 'task', viewKind: 'list', columns: [{ field: 'name', label: 'Name' }] }, } as any); return { protocol }; diff --git a/packages/runtime/src/domains/meta-bare-save-dependent-only-member-35524.test.ts b/packages/runtime/src/domains/meta-bare-save-dependent-only-member-35524.test.ts index d7f37580b79..1b72791f1e3 100644 --- a/packages/runtime/src/domains/meta-bare-save-dependent-only-member-35524.test.ts +++ b/packages/runtime/src/domains/meta-bare-save-dependent-only-member-35524.test.ts @@ -263,8 +263,9 @@ describe('[#35524] the bare save at a member only the dependent holds writes the // the package-unbound draft; the dependent's fr-FR row is stored after it. const lay = async (name: string) => { await layRow(b.engine, 'email_template', name, WA, template('en-US', 'base en')); - const drafted = await saveFr(b, name, 'unbound fr', { mode: 'draft' }); - expect(drafted.ok, JSON.stringify(drafted)).toBe(true); + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the + // package-unbound draft is laid straight into the store. + await layRow(b.engine, 'email_template', name, null, template('fr-FR', 'unbound fr'), 'draft'); await layRow(b.engine, 'email_template', name, WD, template('fr-FR', 'addon fr')); expect(await rowsOf(b.engine, name)).toEqual([`active:${WD}:fr-FR:addon fr`, `active:${WA}:-:base en`, 'draft:null:fr-FR:unbound fr']); }; diff --git a/packages/runtime/src/domains/meta-environment-action-other-object-33904.test.ts b/packages/runtime/src/domains/meta-environment-action-other-object-33904.test.ts index 583396f0794..90e2a94b73f 100644 --- a/packages/runtime/src/domains/meta-environment-action-other-object-33904.test.ts +++ b/packages/runtime/src/domains/meta-environment-action-other-object-33904.test.ts @@ -133,6 +133,15 @@ describe('[#33904] the environment\'s own action on an object no package\'s acti let booted = await boot(file); const saveP = () => booted.call('PUT', `/meta/action/${NAME}`, action('pkg', 'account'), { package: P }); const saveEnv = () => booted.call('PUT', `/meta/action/${NAME}`, action('env', 'contact')); + if (order === 'the environment\'s save first') { + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the + // environment's loose row is laid straight into the store, and + // its package-less save below runs in place. + await booted.engine.insert('sys_metadata', { + type: 'action', name: NAME, namespace: 'default', package_id: null, scope: 'platform', strategy: 'merge', + state: 'active', version: 1, metadata: JSON.stringify(action('env', 'contact')), + }, { context: { isSystem: true } } as any); + } for (const save of order === 'P\'s save first' ? [saveP, saveEnv] : [saveEnv, saveP]) { expect((await save()).status).toBe(200); } diff --git a/packages/runtime/src/domains/meta-layers-draft-layer.test.ts b/packages/runtime/src/domains/meta-layers-draft-layer.test.ts index cca8a636683..4a4fff28bb5 100644 --- a/packages/runtime/src/domains/meta-layers-draft-layer.test.ts +++ b/packages/runtime/src/domains/meta-layers-draft-layer.test.ts @@ -153,8 +153,14 @@ async function bootStore() { await draft('object', TASK_DRAFT, CRM); await draft('dashboard', { name: 'twin_dash', label: 'alpha draft', widgets: [] }, PKG_A); await draft('dashboard', { name: 'twin_dash', label: 'beta draft', widgets: [] }, PKG_B); - await draft('dashboard', BEACON_DRAFT); - await draft('app', LEDGER_APP_DRAFT); + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the two loose + // drafts these cases read are laid straight into the store, as the draft + // door wrote them before that refusal. + for (const [type, item] of [['dashboard', BEACON_DRAFT], ['app', LEDGER_APP_DRAFT]] as const) { + await engine.insert('sys_metadata', { + type, name: item.name, state: 'draft', package_id: null, metadata: JSON.stringify(item), + }); + } // No save door accepts a cleartext credential: a row written before that // refusal existed is stored as it was, which is what this seeds. await engine.insert('sys_metadata', { diff --git a/packages/runtime/src/domains/meta-package-all-fold.test.ts b/packages/runtime/src/domains/meta-package-all-fold.test.ts index 85c5f18d56a..e47d7d7c38c 100644 --- a/packages/runtime/src/domains/meta-package-all-fold.test.ts +++ b/packages/runtime/src/domains/meta-package-all-fold.test.ts @@ -118,6 +118,14 @@ async function bootStore() { protocol.saveMetaItem({ type, name, item, ...(packageId ? { packageId } : {}) } as any); await seed('view', 'case_grid', view('case_grid', 'live'), PROBE_PKG); await seed('view', 'other_grid', view('other_grid', 'other'), OTHER_PKG); + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the env-local + // loose row is laid straight into the store, and its package-less save + // runs in place. + const layLooseRow = (name: string, item: unknown) => engine.insert('sys_metadata', { + type: 'view', name, namespace: 'default', package_id: null, scope: 'platform', strategy: 'merge', + state: 'active', version: 1, metadata: JSON.stringify(item), + }, { context: { isSystem: true } } as any); + await layLooseRow('local_grid', view('local_grid', 'local')); await seed('view', 'local_grid', view('local_grid', 'local')); await seed('book', 'probe_book', { name: 'probe_book', label: 'Probe Book', groups: [{ key: 'pages', label: 'Pages', include: 'probe_*' }], @@ -128,7 +136,7 @@ async function bootStore() { const rows = await engine.find('sys_metadata', { where: { type: 'view', name } }); return (rows ?? []).map((r: any) => r.package_id ?? null); }; - return { protocol, boundTo }; + return { protocol, boundTo, layLooseRow }; } // ── The two doors ───────────────────────────────────────────────────────────── @@ -138,6 +146,8 @@ interface Door { read(path: string, query?: Record): Promise; put(path: string, item: unknown, query?: Record): Promise; boundTo(name: string): Promise>; + /** [#38174] Lay a package-less view row straight into the store. */ + layLooseRow(name: string, item: unknown): Promise; } /** The refusal's `code` in either door's envelope: nested under `error`, or beside a string `error`. */ @@ -168,7 +178,7 @@ function restRouteOf(path: string): { route: string; params: Record { - const { protocol, boundTo } = await bootStore(); + const { protocol, boundTo, layLooseRow } = await bootStore(); const noop = () => {}; const server = { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; const rest: any = new RestServer(server as any, protocol as any, { api: { requireAuth: false } } as any); @@ -184,6 +194,7 @@ async function bootRestServer(): Promise { }; return { boundTo, + layLooseRow, read: (path, query = {}) => drive('GET', path, query), put: (path, item, query = {}) => drive('PUT', path, query, item), }; @@ -208,7 +219,7 @@ async function catchAll(dispatcher: HttpDispatcher, raw: Request) { } async function bootCatchAll(): Promise { - const { protocol, boundTo } = await bootStore(); + const { protocol, boundTo, layLooseRow } = await bootStore(); const get = (n: string) => (n === 'protocol' ? protocol : null); const kernel: any = { context: { getService: get }, getService: get, getServiceAsync: async (n: string) => get(n) }; const dispatcher = new HttpDispatcher(kernel); @@ -230,6 +241,7 @@ async function bootCatchAll(): Promise { }; return { boundTo, + layLooseRow, read: (path, query = {}) => drive('GET', path, query), put: (path, item, query = {}) => drive('PUT', path, query, item), }; @@ -312,6 +324,15 @@ for (const [doorName, boot] of DOORS) { it('the save: PUT ?package=all writes the env-local row, as a save naming no package does; a real package id still binds', async () => { const door = await boot(); + // [#38174] A NEW name is a package-less create under ?package=all, + // as under no package: both refused, nothing stored (ADR-0070 D1). + const bare = await door.put('/meta/view/fresh_grid', view('fresh_grid', 'unscoped')); + const all = await door.put('/meta/view/fresh_grid', view('fresh_grid', 'unscoped'), { package: 'all' }); + expect([all.status, all.code]).toEqual([bare.status, bare.code]); + expect([all.status, all.code]).toEqual([422, 'WRITABLE_PACKAGE_REQUIRED']); + expect(await door.boundTo('fresh_grid')).toEqual([]); + // An env-local row that exists takes the ?package=all save in place. + await door.layLooseRow('fresh_grid', view('fresh_grid', 'seeded')); served(await door.put('/meta/view/fresh_grid', view('fresh_grid', 'unscoped'), { package: 'all' })); expect(await door.boundTo('fresh_grid')).toEqual([null]); // Control: the owning package binds the row. diff --git a/packages/runtime/src/domains/meta-save-actor.test.ts b/packages/runtime/src/domains/meta-save-actor.test.ts index 76ca5d3c9f2..e79a9e51193 100644 --- a/packages/runtime/src/domains/meta-save-actor.test.ts +++ b/packages/runtime/src/domains/meta-save-actor.test.ts @@ -42,6 +42,8 @@ const PREFIX = '/api/v1'; const META = `${PREFIX}/meta`; /** `registry.registerObject` requires a package id (see the sibling real-stack tests). */ const TEST_PACKAGE_ID = 'objectstack-test'; +/** [#38174] A new item is saved into an installed, writable package (ADR-0070 D1). */ +const PKG = 'test_pkg'; interface Caller { userId?: string; isSystem: boolean; systemPermissions?: string[] } /** Authors: `manage_metadata` saves, on both doors. */ @@ -87,11 +89,13 @@ async function bootStore() { useNullAsDefault: true, }), true); await engine.init(); - engine.registry.registerObject(TASK as any, TEST_PACKAGE_ID); + // [#38174] `task` belongs to the package the views are saved into, so it is inside that package's closure. + engine.registry.registerObject(TASK as any, PKG); engine.registry.registerObject(SysMetadata as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataHistoryObject as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataAuditObject as any, TEST_PACKAGE_ID); await engine.syncSchemas(); + engine.registry.installPackage({ id: PKG, name: PKG, version: '1.0.0', type: 'app' } as any, 'authored'); const protocol = new ObjectStackProtocolImplementation(engine as any); const recorded = async (name: string): Promise => { const rows = await engine.find('sys_metadata', { where: { type: 'view', name } }); @@ -137,12 +141,12 @@ async function bootDispatcher(): Promise { save: async (caller, name, label) => { (dispatcher as any).timedResolveExecutionContext = async () => clone(caller); const body = view(name, label); - const request = new Request(`http://localhost${META}/view/${name}`, { + const request = new Request(`http://localhost${META}/view/${name}?package=${PKG}`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), }); - const res = await dispatcher.dispatch('PUT', `/meta/view/${name}`, body, {}, { request }, PREFIX); + const res = await dispatcher.dispatch('PUT', `/meta/view/${name}`, body, { package: PKG }, { request }, PREFIX); return res.response?.status ?? 0; }, }; @@ -164,7 +168,7 @@ async function bootRestServer(): Promise { const res = makeRes(); await route.handler({ method: 'PUT', path: `${META}/view/${name}`, params: { type: 'view', name }, - headers: {}, query: {}, body: view(name, label), + headers: {}, query: { package: PKG }, body: view(name, label), }, res); return res.statusCode; }, diff --git a/packages/runtime/src/domains/meta-save-preconditions-parity.test.ts b/packages/runtime/src/domains/meta-save-preconditions-parity.test.ts index 1be13c9e1eb..45a2206f386 100644 --- a/packages/runtime/src/domains/meta-save-preconditions-parity.test.ts +++ b/packages/runtime/src/domains/meta-save-preconditions-parity.test.ts @@ -61,6 +61,12 @@ const PREFIX = '/api/v1'; const META = `${PREFIX}/meta`; /** `registry.registerObject` requires a package id (see the sibling real-stack tests). */ const TEST_PACKAGE_ID = 'objectstack-test'; +/** + * [#38174] The writable package every door's save names: a new item is saved + * into one (ADR-0070 D1), and `task` is registered in it so the views bind an + * object inside its closure. + */ +const PKG = 'test_pkg'; /** An author: `manage_metadata` saves, on both doors. */ const AUTHOR = { userId: 'u_author', isSystem: false, systemPermissions: ['manage_metadata'] }; @@ -100,11 +106,12 @@ async function bootStore() { useNullAsDefault: true, }), true); await engine.init(); - engine.registry.registerObject(TASK as any, TEST_PACKAGE_ID); + engine.registry.registerObject(TASK as any, PKG); engine.registry.registerObject(SysMetadata as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataHistoryObject as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataAuditObject as any, TEST_PACKAGE_ID); await engine.syncSchemas(); + engine.registry.installPackage({ id: PKG, name: PKG, version: '1.0.0', type: 'app' } as any, 'authored'); const protocol = new ObjectStackProtocolImplementation(engine as any); /** The stored labels of a view, by lifecycle — the store, not the door's word for it. */ const stored = async (name: string, state: 'active' | 'draft'): Promise => { @@ -169,7 +176,7 @@ async function bootRestServer(): Promise { method: 'PUT', path: `${META}/view/${name}`, params: { type: 'view', name }, // The adapter's header record is lowercased (`c.req.header()`). headers: Object.fromEntries(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v])), - query, body: view(name, label), + query: { package: PKG, ...query }, body: view(name, label), }, res); return { status: res.statusCode, code: codeOf(res.body), message: messageOf(res.body), receipt: res.body }; }, @@ -226,7 +233,7 @@ async function bootCatchAll(): Promise { return { status: res.response?.status ?? 0, envelope: res.response?.body?.data }; }, save: async (name, label, opts = {}) => { - const res = await catchAll(dispatcher, putRequest(name, label, opts)); + const res = await catchAll(dispatcher, putRequest(name, label, { ...opts, query: { package: PKG, ...opts.query } })); const body = res.response?.body; return { status: res.response?.status ?? 0, code: codeOf(body), message: messageOf(body), receipt: body?.data }; }, diff --git a/packages/runtime/src/domains/meta-save-user-text-locale.test.ts b/packages/runtime/src/domains/meta-save-user-text-locale.test.ts index b60f9c716b5..0c4729e2f73 100644 --- a/packages/runtime/src/domains/meta-save-user-text-locale.test.ts +++ b/packages/runtime/src/domains/meta-save-user-text-locale.test.ts @@ -33,6 +33,8 @@ import '@objectstack/metadata'; const PREFIX = '/api/v1'; const META = `${PREFIX}/meta`; const TEST_PACKAGE_ID = 'objectstack-test'; +/** [#38174] The writable package each door's save names: a new item is saved into one (ADR-0070 D1). */ +const PKG = 'test_pkg'; const RULE = 'security-private-no-readscope'; interface Caller { @@ -81,11 +83,12 @@ async function bootStore() { useNullAsDefault: true, }), true); await engine.init(); - engine.registry.registerObject(EXPENSE as any, TEST_PACKAGE_ID); + engine.registry.registerObject(EXPENSE as any, PKG); engine.registry.registerObject(SysMetadata as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataHistoryObject as any, TEST_PACKAGE_ID); engine.registry.registerObject(SysMetadataAuditObject as any, TEST_PACKAGE_ID); await engine.syncSchemas(); + engine.registry.installPackage({ id: PKG, name: PKG, version: '1.0.0', type: 'app' } as any, 'authored'); const protocol = new ObjectStackProtocolImplementation(engine as any); // What each save handed the protocol, read where the protocol receives it. const stated: unknown[] = []; @@ -132,12 +135,12 @@ async function bootDispatcher(): Promise { save: async (who, name) => { (dispatcher as any).timedResolveExecutionContext = async () => clone(who); const body = permissionSet(name); - const request = new Request(`http://localhost${META}/permission/${name}`, { + const request = new Request(`http://localhost${META}/permission/${name}?package=${PKG}`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), }); - const res = await dispatcher.dispatch('PUT', `/meta/permission/${name}`, body, {}, { request }, PREFIX); + const res = await dispatcher.dispatch('PUT', `/meta/permission/${name}`, body, { package: PKG }, { request }, PREFIX); const raw = res.response?.body as any; return { status: res.response?.status ?? 0, body: raw?.data ?? raw }; }, @@ -160,7 +163,7 @@ async function bootRestServer(): Promise { const res = makeRes(); await route.handler({ method: 'PUT', path: `${META}/permission/${name}`, params: { type: 'permission', name }, - headers: {}, query: {}, body: permissionSet(name), + headers: {}, query: { package: PKG }, body: permissionSet(name), }, res); return { status: res.statusCode, body: res.body }; }, diff --git a/packages/runtime/src/hook-handler-package-scope.pin.test.ts b/packages/runtime/src/hook-handler-package-scope.pin.test.ts index 1cfa18a34a5..0b90bb3a8d0 100644 --- a/packages/runtime/src/hook-handler-package-scope.pin.test.ts +++ b/packages/runtime/src/hook-handler-package-scope.pin.test.ts @@ -117,6 +117,13 @@ const Z_RUNTIME_MODULE = + ' },\n' + '};\n'; +/** + * [#38174] The writable package the runtime-authored hooks are created in: a + * new item is saved into one (ADR-0070 D1), and the apps' code packages are + * read-only bases. It depends on app Y, whose object the hooks bind. + */ +const AUTHORED_PKG = 'com.pin.scope.authored'; + const js = (source: string) => ({ language: 'js', source, capabilities: [], timeoutMs: 5000 }); /** The engine's logger: quiet, and read back for the binder's coded refusals. */ @@ -196,6 +203,11 @@ beforeAll(async () => { await kernel.use(createDispatcherPlugin({})); await kernel.bootstrap(); + (await engine()).registry.installPackage( + { id: AUTHORED_PKG, name: 'Scope authored', version: '1.0.0', type: 'app', dependencies: { [Y_APP.manifest.id]: '*' } }, + 'authored', + ); + httpServer = await kernel.getServiceAsync('http-server'); app = httpServer.getRawApp(); const res = await req('/auth/sign-in/email', { @@ -282,7 +294,7 @@ describe('a hook handler name resolves inside its own package only — composed }); it('②b a body hook authored through the metadata door saves, binds and runs; so does one carrying both a `body` and a `handler`', async () => { - const bodyHook = await asAdmin('PUT', '/meta/hook/scope_authored_body', { + const bodyHook = await asAdmin('PUT', `/meta/hook/scope_authored_body?package=${AUTHORED_PKG}`, { name: 'scope_authored_body', object: Y_NOTE, events: ['beforeInsert'], @@ -290,7 +302,7 @@ describe('a hook handler name resolves inside its own package only — composed }); expect(bodyHook.status, await bodyHook.text()).toBeLessThan(300); // A `body` beside a `handler` saves: the binder runs the body and never consults the name. - const bothHook = await asAdmin('PUT', '/meta/hook/scope_authored_both', { + const bothHook = await asAdmin('PUT', `/meta/hook/scope_authored_both?package=${AUTHORED_PKG}`, { name: 'scope_authored_both', object: Y_NOTE, events: ['beforeInsert'], diff --git a/packages/runtime/src/http-dispatcher.test.ts b/packages/runtime/src/http-dispatcher.test.ts index a58253c7ae0..c5a232df57a 100644 --- a/packages/runtime/src/http-dispatcher.test.ts +++ b/packages/runtime/src/http-dispatcher.test.ts @@ -391,10 +391,11 @@ describe('HttpDispatcher', () => { expect(result.handled).toBe(false); expect(result.response).toBeUndefined(); expect(mockAutomationService.listFlows).not.toHaveBeenCalled(); - // …while POST at the same path (createFlow) is untouched. + // [#38174] …and POST at the same path (the create door) is retired + // too: unhandled, and nothing is registered. const created = await dispatcher.handleAutomation('', 'POST', { name: 'flow_a' }, FLOW_AUTHOR()); - expect(created.handled).toBe(true); - expect(mockAutomationService.registerFlow).toHaveBeenCalledTimes(1); + expect(created.handled).toBe(false); + expect(mockAutomationService.registerFlow).not.toHaveBeenCalled(); }); it('should return per-flow runtime enable/bound state via GET /_status', async () => { @@ -421,11 +422,14 @@ describe('HttpDispatcher', () => { expect(result.response?.status).toBe(404); }); - it('should create a flow via POST /', async () => { + // [#38174] The create door is retired: a new flow is created by + // `PUT /meta/flow/:name?package=` (ADR-0070 D1), so `POST /` is unhandled. + it('does not create a flow via POST / — the create door is retired', async () => { const body = { name: 'new_flow', label: 'New Flow' }; const result = await dispatcher.handleAutomation('', 'POST', body, FLOW_AUTHOR()); - expect(result.handled).toBe(true); - expect(mockAutomationService.registerFlow).toHaveBeenCalledWith('new_flow', body); + expect(result.handled).toBe(false); + expect(result.response).toBeUndefined(); + expect(mockAutomationService.registerFlow).not.toHaveBeenCalled(); }); it('should update a flow via PUT /:name', async () => { diff --git a/packages/runtime/src/mcp-record-context-tools-bridge.test.ts b/packages/runtime/src/mcp-record-context-tools-bridge.test.ts index df1c273995b..82e33830a19 100644 --- a/packages/runtime/src/mcp-record-context-tools-bridge.test.ts +++ b/packages/runtime/src/mcp-record-context-tools-bridge.test.ts @@ -1067,10 +1067,14 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: }); it('a pack served from the metadata registry (saved at run time, not shipped by the stack) is read', async () => { - await protocol.saveMetaItem({ - type: 'ai_context', name: 'rc_registry', - item: { name: 'rc_registry', label: 'Registry brief', object: 'rc_policy', fields: ['title', 'status'] }, - } as never); + const item = { name: 'rc_registry', label: 'Registry brief', object: 'rc_policy', fields: ['title', 'status'] }; + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the run-time + // loose row is laid straight into the store, and the save runs in place. + await engine.insert('sys_metadata', { + type: 'ai_context', name: 'rc_registry', namespace: 'default', package_id: null, scope: 'platform', strategy: 'merge', + state: 'active', version: 1, metadata: JSON.stringify(item), + }, { context: { isSystem: true } } as never); + await protocol.saveMetaItem({ type: 'ai_context', name: 'rc_registry', item } as never); const listed: any = await protocol.getMetaItems({ type: 'ai_context' }); const row = listed.items.find((p: { name?: string }) => p.name === 'rc_registry'); expect(row).toBeDefined(); diff --git a/packages/runtime/src/meta-compound-arity-mint-door.test.ts b/packages/runtime/src/meta-compound-arity-mint-door.test.ts index eab5ea7e96c..13a237575ce 100644 --- a/packages/runtime/src/meta-compound-arity-mint-door.test.ts +++ b/packages/runtime/src/meta-compound-arity-mint-door.test.ts @@ -114,7 +114,8 @@ function makeEngine() { // Nothing here is package-stamped, so nothing is artifact-backed. getArtifactItem: () => undefined, getObject: (name: string) => runtimeItems.get('object')?.get(name), - getPackage: () => undefined, + // [#38174] installs {@link TEST_PKG}: a new item is saved into a writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), isPackageDisabled: () => false, applyNavContributions: (app: unknown) => app, registerItem: (type: string, item: any, keyStrategy?: string) => { @@ -193,6 +194,9 @@ const ctx = (): any => ({ executionContext: { userId: 'usr_1', systemPermissions: ['manage_metadata'] }, }); +/** The writable, installed package the CONTROL's create is saved into. */ +const TEST_PKG = 'test_pkg'; + function makeStack() { const engine = makeEngine(); const protocol: any = new ObjectStackProtocolImplementation(engine, () => new Map(), undefined); @@ -300,6 +304,7 @@ describe('#8421 — the compound `/meta` arity is not a metadata-type claim', () const res = responseOf(await dispatcher.handleMetadata( '/webhook/midnight_hook', ctx(), 'PUT', { name: 'midnight_hook', label: 'Midnight', object: 'task', triggers: ['create'], url: 'https://example.com/hook' }, + { package: TEST_PKG }, )); expect(res.status).toBe(200); diff --git a/packages/runtime/src/meta-field-overlay-lock.test.ts b/packages/runtime/src/meta-field-overlay-lock.test.ts index a4a30ec2317..a8981ce257e 100644 --- a/packages/runtime/src/meta-field-overlay-lock.test.ts +++ b/packages/runtime/src/meta-field-overlay-lock.test.ts @@ -251,7 +251,8 @@ function makeEngine() { getArtifactItem: (type: string, name: string) => artifacts.get(type)?.get(name), getObject: (name: string) => artifacts.get('object')?.get(name) ?? runtimeItems.get('object')?.get(name), - getPackage: () => undefined, + // [#38174] installs {@link TEST_PKG}: a new item is saved into a writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), isPackageDisabled: () => false, applyNavContributions: (app: unknown) => app, // [#7893] Signature mirrors the PRODUCER's call, not a convenient @@ -356,6 +357,9 @@ const ctx = (): any => ({ * it is where the bug was reported, and the one where `saveMetaItem`'s own * `NOT_OVERRIDABLE` block is skipped entirely. */ +/** The writable, installed package the POSITIVE CONTROLs' creates are saved into. */ +const TEST_PKG = 'test_pkg'; + function makeStack(environmentId?: string) { const engine = makeEngine(); const protocol: any = new ObjectStackProtocolImplementation(engine, () => new Map(), environmentId); @@ -515,6 +519,7 @@ describe('#7743 — PUT /meta/field/. honours the registry overla const res = responseOf(await dispatcher.handleMetadata( '/object/runtime_thing', ctx(), 'PUT', { ...RUNTIME_OBJECT, fields: { ...RUNTIME_OBJECT.fields, extra: { type: 'text', label: 'Extra' } } }, + { package: TEST_PKG }, )); expect(res.status).toBe(200); @@ -706,6 +711,7 @@ describe('#7743 — PUT /meta/field/. honours the registry overla const singular = responseOf(await dispatcher.handleMetadata( '/webhook/midnight_hook', ctx(), 'PUT', { name: 'midnight_hook', label: 'Midnight', object: 'task', triggers: ['create'], url: 'https://example.com/hook' }, + { package: TEST_PKG }, )); expect(singular.status).toBe(200); expect(metaRow(engine, 'webhook', 'midnight_hook')).toBeDefined(); @@ -715,6 +721,7 @@ describe('#7743 — PUT /meta/field/. honours the registry overla const plural = responseOf(await dispatcher.handleMetadata( '/webhooks/twilight_hook', ctx(), 'PUT', { name: 'twilight_hook', label: 'Twilight', object: 'task', triggers: ['create'], url: 'https://example.com/hook' }, + { package: TEST_PKG }, )); expect(plural.status).toBe(200); expect(metaRow(engine, 'webhook', 'twilight_hook')).toBeDefined(); diff --git a/packages/runtime/src/meta-managed-content-seal.test.ts b/packages/runtime/src/meta-managed-content-seal.test.ts index 8dc6ab4ae85..7def0299bb6 100644 --- a/packages/runtime/src/meta-managed-content-seal.test.ts +++ b/packages/runtime/src/meta-managed-content-seal.test.ts @@ -148,7 +148,8 @@ function makeEngine() { getObject: (name: string) => artifacts.get('object')?.get(name) ?? runtimeItems.get('object')?.get(name), // The type listing (`GET /meta/types`) reads the live types from here. getRegisteredTypes: () => ['flow', 'object', 'permission', 'position', 'view', 'job', 'picklist'], - getPackage: () => undefined, + // [#38174] installs {@link TEST_PKG}: a new item is saved into a writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), isPackageDisabled: () => false, applyNavContributions: (app: unknown) => app, // The producer's arity: `(type, item, keyStrategy, ownerId?)`. @@ -206,6 +207,9 @@ function makeEngine() { return engine; } +/** The writable, installed package the controls' creates are saved into. */ +const TEST_PKG = 'test_pkg'; + function makeStack(environmentId?: string) { const engine = makeEngine(); const protocol: any = new ObjectStackProtocolImplementation(engine, () => new Map(), environmentId); @@ -306,6 +310,7 @@ describe('[ADR-0131 D6] the dispatcher /meta door: the hatch opens no write onto const created = responseOf(await dispatcher.handleMetadata( '/flow/crm_new_alert', ctx(), 'PUT', { name: 'crm_new_alert', label: 'New Alert', type: 'autolaunched', nodes: [{ id: 'start', type: 'start', label: 'Start' }], edges: [] }, + { package: TEST_PKG }, )); expect(created.status, JSON.stringify(created.body)).toBe(200); expect(activeRow(engine, 'flow', 'crm_new_alert')).toBeDefined(); @@ -339,7 +344,7 @@ describe('[#22411] the dispatcher /meta door: the type listing and the save door return { allowEnvironmentOverlay: entry.allowEnvironmentOverlay, overrideSource: entry.overrideSource }; }; const save = async (type: string, body: { name: string }) => { - const res = responseOf(await dispatcher.handleMetadata(`/${type}/${body.name}`, ctx(), 'PUT', body)); + const res = responseOf(await dispatcher.handleMetadata(`/${type}/${body.name}`, ctx(), 'PUT', body, { package: TEST_PKG })); return { status: res.status, code: res.body?.error?.code, row: activeRow(engine, type, body.name) !== undefined }; }; return { diff --git a/packages/runtime/src/meta-overlay-read-your-writes.test.ts b/packages/runtime/src/meta-overlay-read-your-writes.test.ts index 41776b282a5..14e1dc5af84 100644 --- a/packages/runtime/src/meta-overlay-read-your-writes.test.ts +++ b/packages/runtime/src/meta-overlay-read-your-writes.test.ts @@ -93,6 +93,24 @@ function makeEngine(registry: SchemaRegistry) { return engine; } +/** + * [#38174] A package-less CREATE is refused (ADR-0070 D1), and every case here + * is about the runtime-created, package-less item (the "overlay"): the loose + * row a brand-new name is saved into is laid straight into the store first, as + * the save door wrote it before that refusal, so the save under test runs in + * place. A name the store already holds, or a shipped name, is not laid. + */ +async function layLooseRow(engine: any, registry: SchemaRegistry, type: string, item: { name: string }, mode?: 'draft' | 'publish') { + const held = (await engine.find('sys_metadata', { where: { type, name: item.name } })) + .some((r: any) => r.type === type && r.name === item.name && 'metadata' in r); + if (held || registry.getItem(type, item.name) !== undefined) return; + await engine.insert('sys_metadata', { + type, name: item.name, organization_id: null, package_id: null, + state: mode === 'draft' ? 'draft' : 'active', + metadata: JSON.stringify(item), checksum: 'sha256:seeded', version: 1, + }); +} + /** The routed object the showcase repro dispatched against. */ const OBJECT_DEF = { name: 'showcase_task', label: 'Task', fields: {}, actions: [] }; @@ -125,13 +143,15 @@ describe('#4521 — read-your-writes between saveMeta and the dispatch path', () requestContext = { request: {} } as any; }); - const saveAction = (item: any, mode?: 'draft' | 'publish') => - protocol.saveMetaItem({ + const saveAction = async (item: any, mode?: 'draft' | 'publish') => { + await layLooseRow(engine, registry, 'action', item, mode); + return protocol.saveMetaItem({ type: 'action', name: item.name, item, ...(mode ? { mode } : {}), }); + }; const resolve = (actionName: string) => resolveRouteActionDeclaration(deps, requestContext, { @@ -275,13 +295,15 @@ describe('#5079 — list / get / dispatch agree immediately after deleteMeta', ( requestContext = { request: {} } as any; }); - const saveAction = (item: any, mode?: 'draft' | 'publish') => - protocol.saveMetaItem({ + const saveAction = async (item: any, mode?: 'draft' | 'publish') => { + await layLooseRow(engine, registry, 'action', item, mode); + return protocol.saveMetaItem({ type: 'action', name: item.name, item, ...(mode ? { mode } : {}), }); + }; /** The three surfaces #4432 requires to agree, read in one go. */ const surfaces = async (actionName: string) => { @@ -426,10 +448,12 @@ describe('#5079 — list / get / dispatch agree immediately after deleteMeta', ( // `removeOverlayEntry` is addressed by (type, name); a `flow` named // `twin` must survive the delete of the `action` named `twin`. await saveAction({ name: 'twin', label: 'Action Twin', objectName: 'showcase_task', type: 'script', target: 'showcase.probe' }); + const flowTwin = { name: 'twin', label: 'Flow Twin', type: 'autolaunched', nodes: [{ id: 'start', type: 'start', label: 'Start' }], edges: [] }; + await layLooseRow(engine, registry, 'flow', flowTwin); await protocol.saveMetaItem({ type: 'flow', name: 'twin', - item: { name: 'twin', label: 'Flow Twin', type: 'autolaunched', nodes: [{ id: 'start', type: 'start', label: 'Start' }], edges: [] }, + item: flowTwin, }); await protocol.deleteMetaItem({ type: 'action', name: 'twin' }); diff --git a/packages/runtime/src/meta-sharing-rule-door.test.ts b/packages/runtime/src/meta-sharing-rule-door.test.ts index ad195dc9ad7..e3e357dbbcf 100644 --- a/packages/runtime/src/meta-sharing-rule-door.test.ts +++ b/packages/runtime/src/meta-sharing-rule-door.test.ts @@ -115,7 +115,8 @@ function makeEngine() { getObject: () => undefined, // The type listing (`GET /meta/types`) reads the live types from here. getRegisteredTypes: () => ['sharing_rule', 'position'], - getPackage: () => undefined, + // [#38174] installs {@link TEST_PKG}: a new item is saved into a writable package (ADR-0070 D1). + getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined), isPackageDisabled: () => false, applyNavContributions: (app: unknown) => app, // The producer's arity: `(type, item, keyStrategy, ownerId?)`. @@ -174,6 +175,9 @@ function makeEngine() { return engine; } +/** The writable, installed package the control's create is saved into. */ +const TEST_PKG = 'test_pkg'; + function makeStack(environmentId?: string) { const engine = makeEngine(); const protocol: any = new ObjectStackProtocolImplementation(engine, () => new Map(), environmentId); @@ -273,7 +277,7 @@ describe('[ADR-0131 D6] the dispatcher /meta door authors no sharing rule', () = it(`control: a new position is still created through the same door (${kernel})`, async () => { const { engine, dispatcher } = makeStack(environmentId); const res = responseOf(await dispatcher.handleMetadata( - '/position/crm_new_position', ctx(), 'PUT', { name: 'crm_new_position', label: 'New Position' }, + '/position/crm_new_position', ctx(), 'PUT', { name: 'crm_new_position', label: 'New Position' }, { package: TEST_PKG }, )); expect(res.status, JSON.stringify(res.body)).toBe(200); expect(rowsOf(engine, 'position', 'crm_new_position')).toHaveLength(1); diff --git a/packages/runtime/src/meta-write-org-scope.test.ts b/packages/runtime/src/meta-write-org-scope.test.ts index 27a9d11594f..16a01721f70 100644 --- a/packages/runtime/src/meta-write-org-scope.test.ts +++ b/packages/runtime/src/meta-write-org-scope.test.ts @@ -146,6 +146,12 @@ function matches(row: Row, where: Record | undefined): boolean return true; } +/** [#38174] `crm_pkg`'s object the FLOW and VIEW specimens bind. */ +const TASK_OBJECT = { + name: 'task', label: 'Task', sharingModel: 'private', _packageId: 'crm_pkg', + fields: { name: { name: 'name', type: 'text', label: 'Name' } }, +}; + function makeEngine() { const tables = new Map(); let nextId = 0; @@ -154,7 +160,11 @@ function makeEngine() { if (!t) { t = []; tables.set(name, t); } return t; }; - const registryItems = new Map>(); + // [#38174] The specimens are saved into `crm_pkg`, so the `task` object the + // flow and the view bind is one of that package's objects (inside its closure). + const registryItems = new Map>([ + ['object', new Map([['task', TASK_OBJECT]])], + ]); const engine: any = { registry: { // A registry that reads no type by package (ADR-0150): every by-name read stays @@ -171,7 +181,7 @@ function makeEngine() { // runtime-authored item, which is the tier the tenant scenario in // #6190 actually uses (`allowRuntimeCreate: true`). getArtifactItem: () => undefined, - getObject: () => undefined, + getObject: (name: string) => registryItems.get('object')?.get(name), // [#26708] The one package the specimens below save into is // installed: a save naming a package no installed package has is // refused before it is written. @@ -310,6 +320,13 @@ const ctx = (activeOrganizationId?: string): any => ({ }, }); +/** + * [#38174] Every specimen PUT names the installed package `crm_pkg`: a new + * item is saved into a writable package (ADR-0070 D1). The subject here is the + * organization column, which a package does not change. + */ +const PKG_QUERY = { package: 'crm_pkg' }; + function makeStack(activeOrganizationId: string | undefined, metadataService?: unknown) { const engine = makeEngine(); // `environmentId` set: an environment kernel, the topology ADR-0005's @@ -400,7 +417,7 @@ describe('#7018 — the registry decides whether a metadata write carries the se it('a NON-overridable type lands env-wide even though the session has an active org', async () => { const { engine, dispatcher } = makeStack(ACTIVE_ORG); - const res = responseOf(await dispatcher.handleMetadata(`/flow/${FLOW.name}`, ctx(ACTIVE_ORG), 'PUT', FLOW)); + const res = responseOf(await dispatcher.handleMetadata(`/flow/${FLOW.name}`, ctx(ACTIVE_ORG), 'PUT', FLOW, PKG_QUERY)); expect(res.status).toBe(200); const row = metaRow(engine, 'flow', FLOW.name); @@ -422,7 +439,7 @@ describe('#7018 — the registry decides whether a metadata write carries the se fields: { subject: { type: 'text', label: 'Subject' } }, }; - const res = responseOf(await dispatcher.handleMetadata(`/object/${OBJECT.name}`, ctx(ACTIVE_ORG), 'PUT', OBJECT)); + const res = responseOf(await dispatcher.handleMetadata(`/object/${OBJECT.name}`, ctx(ACTIVE_ORG), 'PUT', OBJECT, PKG_QUERY)); expect(res.status).toBe(200); expect('organization_id' in metaRow(engine, 'object', OBJECT.name)!).toBe(false); @@ -437,8 +454,8 @@ describe('#7018 — the registry decides whether a metadata write carries the se const withOrg = makeStack(ACTIVE_ORG); const withoutOrg = makeStack(undefined); - const a = responseOf(await withOrg.dispatcher.handleMetadata(`/flow/${FLOW.name}`, ctx(ACTIVE_ORG), 'PUT', FLOW)); - const b = responseOf(await withoutOrg.dispatcher.handleMetadata(`/flow/${FLOW.name}`, ctx(), 'PUT', FLOW)); + const a = responseOf(await withOrg.dispatcher.handleMetadata(`/flow/${FLOW.name}`, ctx(ACTIVE_ORG), 'PUT', FLOW, PKG_QUERY)); + const b = responseOf(await withoutOrg.dispatcher.handleMetadata(`/flow/${FLOW.name}`, ctx(), 'PUT', FLOW, PKG_QUERY)); expect(a.status).toBe(200); expect(a.body.data).toEqual(b.body.data); @@ -448,7 +465,7 @@ describe('#7018 — the registry decides whether a metadata write carries the se it('⭐ [ADR-0131 D6] an overlay-enabled type lands env-wide too, and the read serves it', async () => { const { engine, dispatcher } = makeStack(ACTIVE_ORG); - const res = responseOf(await dispatcher.handleMetadata(`/view/${VIEW.name}`, ctx(ACTIVE_ORG), 'PUT', VIEW)); + const res = responseOf(await dispatcher.handleMetadata(`/view/${VIEW.name}`, ctx(ACTIVE_ORG), 'PUT', VIEW, PKG_QUERY)); expect(res.status).toBe(200); // The per-organization overlay axis is retired: the Studio save of a @@ -461,7 +478,7 @@ describe('#7018 — the registry decides whether a metadata write carries the se it('[ADR-0131 D6] the plural URL spelling of an overridable type lands env-wide the same way', async () => { const { engine, dispatcher } = makeStack(ACTIVE_ORG); - const res = responseOf(await dispatcher.handleMetadata(`/views/${VIEW.name}`, ctx(ACTIVE_ORG), 'PUT', VIEW)); + const res = responseOf(await dispatcher.handleMetadata(`/views/${VIEW.name}`, ctx(ACTIVE_ORG), 'PUT', VIEW, PKG_QUERY)); expect(res.status).toBe(200); expect('organization_id' in metaRow(engine, 'view', VIEW.name)!).toBe(false); @@ -642,7 +659,7 @@ describe('#10503 · ADR-0131 D6 no spelling carries an organization through the // receipted 200, served by nothing. const viaPlural = makeStack(ACTIVE_ORG); const resPlural = responseOf( - await viaPlural.dispatcher.handleMetadata(`/${plural}/${item.name}`, ctx(ACTIVE_ORG), 'PUT', item), + await viaPlural.dispatcher.handleMetadata(`/${plural}/${item.name}`, ctx(ACTIVE_ORG), 'PUT', item, PKG_QUERY), ); expect(resPlural.status).toBe(200); const pluralRow = metaRow(viaPlural.engine, singular, item.name); @@ -654,7 +671,7 @@ describe('#10503 · ADR-0131 D6 no spelling carries an organization through the // must not have moved. const viaSingular = makeStack(ACTIVE_ORG); const resSingular = responseOf( - await viaSingular.dispatcher.handleMetadata(`/${singular}/${item.name}`, ctx(ACTIVE_ORG), 'PUT', item), + await viaSingular.dispatcher.handleMetadata(`/${singular}/${item.name}`, ctx(ACTIVE_ORG), 'PUT', item, PKG_QUERY), ); expect(resSingular.status).toBe(200); const singularRow = metaRow(viaSingular.engine, singular, item.name); @@ -670,10 +687,10 @@ describe('#10503 · ADR-0131 D6 no spelling carries an organization through the const { engine, dispatcher } = makeStack(ACTIVE_ORG); expect(responseOf( - await dispatcher.handleMetadata(`/${plural}/${item.name}`, ctx(ACTIVE_ORG), 'PUT', item), + await dispatcher.handleMetadata(`/${plural}/${item.name}`, ctx(ACTIVE_ORG), 'PUT', item, PKG_QUERY), ).status).toBe(200); expect(responseOf( - await dispatcher.handleMetadata(`/${singular}/${item.name}`, ctx(ACTIVE_ORG), 'PUT', item), + await dispatcher.handleMetadata(`/${singular}/${item.name}`, ctx(ACTIVE_ORG), 'PUT', item, PKG_QUERY), ).status).toBe(200); const rows = engine.metaRows().filter( @@ -689,7 +706,7 @@ describe('#10503 · ADR-0131 D6 no spelling carries an organization through the const { engine, dispatcher } = makeStack(undefined); expect(responseOf( - await dispatcher.handleMetadata(`/${plural}/${item.name}`, ctx(), 'PUT', item), + await dispatcher.handleMetadata(`/${plural}/${item.name}`, ctx(), 'PUT', item, PKG_QUERY), ).status).toBe(200); expect('organization_id' in metaRow(engine, singular, item.name)!).toBe(false); }); @@ -711,7 +728,7 @@ describe('#10503 · ADR-0131 D6 no spelling carries an organization through the fields: { subject: { type: 'text', label: 'Subject' } }, }; - const res = responseOf(await dispatcher.handleMetadata(`/objects/${OBJECT.name}`, ctx(ACTIVE_ORG), 'PUT', OBJECT)); + const res = responseOf(await dispatcher.handleMetadata(`/objects/${OBJECT.name}`, ctx(ACTIVE_ORG), 'PUT', OBJECT, PKG_QUERY)); expect(res.status).toBe(200); expect('organization_id' in metaRow(engine, 'object', OBJECT.name)!).toBe(false); diff --git a/packages/runtime/src/package-duplicate-adopt-org-scope.integration.test.ts b/packages/runtime/src/package-duplicate-adopt-org-scope.integration.test.ts index 0e45801a0db..3df286f8124 100644 --- a/packages/runtime/src/package-duplicate-adopt-org-scope.integration.test.ts +++ b/packages/runtime/src/package-duplicate-adopt-org-scope.integration.test.ts @@ -267,7 +267,7 @@ describe('#7819 tier 2 — duplicatePackage must copy the source’s env-wide ro }); describe('#7819 tier 2 — a package-less save writes an env-wide loose row', () => { - it('a package-less saveMetaItem still mints an env-wide orphan TODAY (why this is live, not legacy)', async () => { + it('a package-less saveMetaItem no longer mints an env-wide orphan: the create is refused 422 and nothing is stored', async () => { const { engine, protocol } = await boot(); // ADR-0070 D1 rejects a new loose row that names a READ-ONLY package @@ -276,16 +276,15 @@ describe('#7819 tier 2 — a package-less save writes an env-wide loose row', () // door (`moveIntoPackage`, #38150) reads, in exactly the scope an // org-scoped caller once could not see. This case is the reason the // measurement came back live instead of latent. - const res = await (protocol as any).saveMetaItem({ + // [#38174] a package-less create is refused (ADR-0070 D1) + const refused: any = await (protocol as any).saveMetaItem({ type: 'view', name: 'loose_view', item: viewBody('loose_view'), mode: 'publish', - }); - expect(res?.success ?? true).toBeTruthy(); + }).then(() => undefined, (e: unknown) => e); + expect({ code: refused?.code, status: refused?.status }).toEqual({ code: 'WRITABLE_PACKAGE_REQUIRED', status: 422 }); - expect((await rowsOf(engine)).map((r) => ({ name: r.name, org: r.org, pkg: r.pkg }))).toEqual([ - { name: 'loose_view', org: null, pkg: null }, - ]); + expect(await rowsOf(engine)).toEqual([]); }); }); diff --git a/packages/runtime/src/package-promote-runtime-owner-refusal.integration.test.ts b/packages/runtime/src/package-promote-runtime-owner-refusal.integration.test.ts index d2528cfc8a4..021e0a146a4 100644 --- a/packages/runtime/src/package-promote-runtime-owner-refusal.integration.test.ts +++ b/packages/runtime/src/package-promote-runtime-owner-refusal.integration.test.ts @@ -196,11 +196,11 @@ async function boot() { * refuses a draft of a code-packaged object today, so such a row is one * stored before the code package shipped the object. */ - async seedStoredDraft(packageId: string) { - const body = objectBody(packageId); + async seedStoredDraft(packageId: string | null) { + const body = objectBody(packageId ?? 'unbound'); const now = new Date().toISOString(); await engine.insert('sys_metadata', { - id: `seed_draft_${packageId}_${X}`, type: 'object', name: X, + id: `seed_draft_${packageId ?? 'unbound'}_${X}`, type: 'object', name: X, package_id: packageId, state: 'draft', metadata: JSON.stringify(body), checksum: hashSpec(body, 'object'), version: 1, created_at: now, updated_at: now, }, { context: { isSystem: true } } as any); @@ -379,7 +379,9 @@ describe('[#23630] ADR-0029 D9.9 at the promote doors — a draft promoted after it('CONTROL: publishMetaItem naming no package promotes a package-unbound draft INTO the owner\'s package', async () => { const h = await boot(); await h.install(P); - await h.saveDraft(undefined); + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the + // package-unbound draft is laid straight into the store. + await h.seedStoredDraft(null); expect((await h.saveActive(P)).success).toBe(true); expect(await h.draftBindings(), 'precondition: the unbound draft').toEqual([null]); diff --git a/packages/runtime/src/standalone-stack-hydrate-metadata.test.ts b/packages/runtime/src/standalone-stack-hydrate-metadata.test.ts index f03700b7dd0..5973f731ddf 100644 --- a/packages/runtime/src/standalone-stack-hydrate-metadata.test.ts +++ b/packages/runtime/src/standalone-stack-hydrate-metadata.test.ts @@ -75,6 +75,12 @@ async function boot(plugins: readonly unknown[]) { return kernel; } +/** [#38174] A package-less, env-wide row as the save door wrote one before ADR-0070 D1's create refusal. */ +const layLooseRow = (engine: ObjectQL, type: string, item: { name: string }) => engine.insert('sys_metadata', { + type, name: item.name, namespace: 'default', package_id: null, scope: 'platform', strategy: 'merge', + state: 'active', version: 1, metadata: JSON.stringify(item), +}, { context: { isSystem: true } } as never); + describe('[#20071] createStandaloneStack declares sys_metadata hydration instead of deducing it from the environment id', () => { const dirs: string[] = []; const kernels: any[] = []; @@ -137,18 +143,20 @@ describe('[#20071] createStandaloneStack declares sys_metadata hydration instead const first = await boot((await createStandaloneStack(stackConfig)).plugins); kernels.push(first); const protocol: any = first.getService('protocol'); - await protocol.saveMetaItem({ - type: 'object', - name: OBJECT, - item: { - name: OBJECT, - label: 'Widget', - sharingModel: 'private', - fields: { title: { type: 'text', label: 'Title' } }, - }, - }); - await protocol.saveMetaItem({ type: 'app', name: APP, item: { name: APP, label: 'Hydration Console' } }); const engine1 = first.getService('objectql'); + const objectItem = { + name: OBJECT, + label: 'Widget', + sharingModel: 'private', + fields: { title: { type: 'text', label: 'Title' } }, + }; + const appItem = { name: APP, label: 'Hydration Console' }; + // [#38174] A package-less CREATE is refused (ADR-0070 D1): each env-wide + // loose row is laid straight into the store, and its save runs in place. + await layLooseRow(engine1, 'object', objectItem); + await protocol.saveMetaItem({ type: 'object', name: OBJECT, item: objectItem }); + await layLooseRow(engine1, 'app', appItem); + await protocol.saveMetaItem({ type: 'app', name: APP, item: appItem }); // Harness health: both rows are persisted env-wide and active — exactly // the population `loadMetaFromDb` selects — so their absence from the // next boot's registry can only be the boot's doing. @@ -199,6 +207,8 @@ describe('[#20071] createStandaloneStack declares sys_metadata hydration instead const stackConfig = { projectRoot: dir, databaseUrl, skipSeedData: true, runPlatformMigrations: false } as const; const first = await boot((await createStandaloneStack(stackConfig)).plugins); kernels.push(first); + // [#38174] The env-wide loose row is laid straight into the store; its save runs in place. + await layLooseRow(first.getService('objectql'), 'app', { name: APP, label: 'Hydration Console' }); await (first.getService('protocol') as any).saveMetaItem({ type: 'app', name: APP, item: { name: APP, label: 'Hydration Console' } }); await first.shutdown(); kernels.splice(kernels.indexOf(first), 1); diff --git a/packages/runtime/src/standalone-stack-security-catalog-one-holder.test.ts b/packages/runtime/src/standalone-stack-security-catalog-one-holder.test.ts index 93ba4cfcd02..04d41a31d3f 100644 --- a/packages/runtime/src/standalone-stack-security-catalog-one-holder.test.ts +++ b/packages/runtime/src/standalone-stack-security-catalog-one-holder.test.ts @@ -180,8 +180,19 @@ describe('a package\'s security catalog name another holder holds refuses the bo const first = await boot((await artifactStack({ manifest: manifestOf('com.test.env-project'), packages: [{ manifest: base }] }, databaseUrl)).plugins); expect(first.refusal).toBeUndefined(); const protocol = first.kernel.getService('protocol'); - await protocol.saveMetaItem({ type: 'permission', name: 'env_held_set', item: { name: 'env_held_set', label: 'saved in the environment', objects: {} } }); - await protocol.saveMetaItem({ type: 'position', name: 'env_held_position', item: { name: 'env_held_position', label: 'saved in the environment' } }); + const heldSet = { name: 'env_held_set', label: 'saved in the environment', objects: {} }; + const heldPosition = { name: 'env_held_position', label: 'saved in the environment' }; + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the environment + // catalog's loose rows are laid straight into the store, and their saves run in place. + const engine = first.kernel.getService('objectql'); + for (const [type, item] of [['permission', heldSet], ['position', heldPosition]] as const) { + await engine.insert('sys_metadata', { + type, name: item.name, namespace: 'default', package_id: null, scope: 'platform', strategy: 'merge', + state: 'active', version: 1, metadata: JSON.stringify(item), + }, { context: { isSystem: true } }); + } + await protocol.saveMetaItem({ type: 'permission', name: 'env_held_set', item: heldSet }); + await protocol.saveMetaItem({ type: 'position', name: 'env_held_position', item: heldPosition }); await first.kernel.shutdown(); kernels.splice(kernels.indexOf(first.kernel), 1); diff --git a/packages/runtime/src/stored-metadata-body-boundary.pin.test.ts b/packages/runtime/src/stored-metadata-body-boundary.pin.test.ts index fa6e43d485d..04cc175224c 100644 --- a/packages/runtime/src/stored-metadata-body-boundary.pin.test.ts +++ b/packages/runtime/src/stored-metadata-body-boundary.pin.test.ts @@ -228,9 +228,16 @@ async function waitFor(predicate: () => Promise, ms = 15_000): Promise< return false; } +/** + * [#38174] The writable package the runtime-authored items are created in: a + * new item is saved into one (ADR-0070 D1), and the pin app's code package is a + * read-only base. It depends on that app, whose table the items bind. + */ +const AUTHORED_PKG = 'com.pin.boundary21520.authored'; + /** Save an `action` item through the metadata door, as the administrator: the platform's own family write. */ async function saveThroughMetadataDoor(name: string, label: string): Promise { - return as(adminToken, 'PUT', `/meta/action/${name}`, { + return as(adminToken, 'PUT', `/meta/action/${name}?package=${AUTHORED_PKG}`, { name, label, objectName: ORDINARY, @@ -257,6 +264,11 @@ beforeAll(async () => { await kernel.use(createDispatcherPlugin({})); await kernel.bootstrap(); + (await engine()).registry.installPackage( + { id: AUTHORED_PKG, name: 'Body boundary authored', version: '1.0.0', type: 'app', dependencies: { [PIN_APP.manifest.id]: '*' } }, + 'authored', + ); + httpServer = await kernel.getServiceAsync('http-server'); app = httpServer.getRawApp(); adminToken = await signIn(ADMIN); @@ -314,13 +326,13 @@ describe('[#21520] ① binding — a body hook targeting a family table is not b }); it('a hook authored at runtime through the metadata door is not bound to a family table; an ordinary one is', async () => { - const familyHook = await as(adminToken, 'PUT', '/meta/hook/boundary_authored_on_metadata', { + const familyHook = await as(adminToken, 'PUT', `/meta/hook/boundary_authored_on_metadata?package=${AUTHORED_PKG}`, { name: 'boundary_authored_on_metadata', object: 'sys_metadata', events: ['beforeInsert', 'beforeUpdate'], body: js(append('tags', 'authored-ran')), }); - const ordinaryHook = await as(adminToken, 'PUT', '/meta/hook/boundary_authored_ordinary', { + const ordinaryHook = await as(adminToken, 'PUT', `/meta/hook/boundary_authored_ordinary?package=${AUTHORED_PKG}`, { name: 'boundary_authored_ordinary', object: ORDINARY, events: ['beforeInsert'], diff --git a/packages/runtime/src/stored-metadata-reader-contexts.pin.test.ts b/packages/runtime/src/stored-metadata-reader-contexts.pin.test.ts index c10266a5ca8..2c092612cb4 100644 --- a/packages/runtime/src/stored-metadata-reader-contexts.pin.test.ts +++ b/packages/runtime/src/stored-metadata-reader-contexts.pin.test.ts @@ -502,6 +502,9 @@ async function warmUpFirstLoads(): Promise { // At module scope, never in a hook: vitest clocks a hook as it clocks a test. await warmUpFirstLoads(); +/** [#38174] The writable package the runtime-authored items are saved into. */ +const AUTHORED_PKG = 'com.pin.reader21454.authored'; + beforeAll(async () => { prevNodeEnv = process.env.NODE_ENV; process.env.NODE_ENV = 'development'; // the dev-admin seed, as `objectstack dev` / bootStack arm it @@ -514,8 +517,16 @@ beforeAll(async () => { adminToken = await signIn(ADMIN); memberToken = await signUpMember(); + // [#38174] A new item is saved into an installed, writable package (ADR-0070 D1): + // the pin app's code package is a read-only base, so the runtime-authored + // items go into this one, which depends on it (its `pin_note` binds them). + (await kernel.getServiceAsync('objectql')).registry.installPackage( + { id: AUTHORED_PKG, name: 'Reader pin authored', version: '1.0.0', type: 'app', dependencies: { 'com.pin.reader21454': '*' } }, + 'authored', + ); + // The stored credential, written by the production writer as the administrator. - const save = await as(adminToken, 'PUT', `/meta/datasource/${DS_NAME}`, { + const save = await as(adminToken, 'PUT', `/meta/datasource/${DS_NAME}?package=${AUTHORED_PKG}`, { name: DS_NAME, label: 'Pin datasource', driver: 'mongodb', @@ -663,7 +674,7 @@ describe('[#21594] ① a sandboxed body may not read the family: every read is r }); it('an action body authored at runtime through /meta: refused, for administrator and member', async () => { - const authored = await as(adminToken, 'PUT', '/meta/action/authored_reads_family', { + const authored = await as(adminToken, 'PUT', `/meta/action/authored_reads_family?package=${AUTHORED_PKG}`, { name: 'authored_reads_family', label: 'Authored read', objectName: 'pin_note', @@ -777,7 +788,7 @@ describe('[#21594] ① an action body is not handed a family row as its subject }); it('an action declared on a family table through the /meta door is refused once bound', async () => { - const authored = await as(adminToken, 'PUT', '/meta/action/authored_family_bound_reads_record', { + const authored = await as(adminToken, 'PUT', `/meta/action/authored_family_bound_reads_record?package=${AUTHORED_PKG}`, { name: 'authored_family_bound_reads_record', label: 'Authored family-bound body', objectName: 'sys_metadata', From d2baee52e8dbe1c25aa07c3fe0ece8ff39048dde Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 15:26:00 +0000 Subject: [PATCH 08/23] test(dogfood): migrate to name a package or seed the loose row; the package-less create refusal and controls on the showcase (#38174) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CasbvyQnz4st6s79P9 --- ...t-packageless-other-object.dogfood.test.ts | 17 +- ...write-operator-gate-single.dogfood.test.ts | 5 +- ...ormula-dimension-authoring.dogfood.test.ts | 10 +- .../dogfood/test/authz-conformance.matrix.ts | 2 +- ...on-authoring-doors-durable.dogfood.test.ts | 41 +++- ...mation-toggle-tenant-scope.dogfood.test.ts | 6 +- ...-name-one-holder-ai-family.dogfood.test.ts | 13 +- ...-one-holder-request-family.dogfood.test.ts | 19 ++ .../catalog-activation-door.dogfood.test.ts | 14 ++ ...ctor-failure-text-withheld.dogfood.test.ts | 7 +- ...tor-installer-oauth-client.dogfood.test.ts | 8 +- ...-door-credential-hardening.dogfood.test.ts | 14 +- ...or-entry-and-url-hardening.dogfood.test.ts | 16 +- ...or-meta-door-root-key-read.dogfood.test.ts | 18 +- ...r-undeclared-keys-withheld.dogfood.test.ts | 20 +- ...a-door-url-and-nested-keys.dogfood.test.ts | 42 ++-- ...shboard-designer-roundtrip.dogfood.test.ts | 10 +- ...ta-door-reaches-admin-door.dogfood.test.ts | 12 +- ...oor-url-credential-trimmed.dogfood.test.ts | 16 +- ...tasource-restore-code-wins.dogfood.test.ts | 5 +- ...e-restore-environment-rows.dogfood.test.ts | 8 +- .../test/delegation-of-duty.dogfood.test.ts | 5 +- ...federation-read-capability.dogfood.test.ts | 8 +- ...-code-datasource-namespace.dogfood.test.ts | 16 +- ...ort-walled-catalog-refusal.dogfood.test.ts | 5 +- ...validate-sees-runtime-save.dogfood.test.ts | 7 +- .../flow-credential-channel.dogfood.test.ts | 22 +- ...fig-values-at-registration.dogfood.test.ts | 88 +++++--- ...low-provenance-server-held.dogfood.test.ts | 41 +++- ...w-region-malformed-publish.dogfood.test.ts | 8 +- .../fls-own-field-mask-33828.dogfood.test.ts | 5 +- .../test/fls-superuser-vote.dogfood.test.ts | 5 +- ...p-undeclared-related-field.dogfood.test.ts | 11 +- ...grant-table-write-contract.dogfood.test.ts | 3 +- ...ge-source-studio-roundtrip.dogfood.test.ts | 30 ++- ...rce-unmounted-adapter-save.dogfood.test.ts | 10 +- .../managed-content-sealed.dogfood.test.ts | 16 +- ...l-field-evaluate-positions.dogfood.test.ts | 12 +- ...nvironment-authored-holder.dogfood.test.ts | 18 +- .../mcp-stdio-runtime-object-exposure.test.ts | 11 +- ...apps-and-everyone-baseline.dogfood.test.ts | 12 +- .../meta-door-code-datasource.dogfood.test.ts | 5 +- ...ect-unstored-field-removal.dogfood.test.ts | 19 +- ...w-audience-alternate-doors.dogfood.test.ts | 9 +- ...ect-designer-field-reorder.dogfood.test.ts | 17 +- ...mission-write-implies-read.dogfood.test.ts | 10 +- ...ged-flow-write-door-parity.dogfood.test.ts | 17 +- ...packageless-create-refused.dogfood.test.ts | 210 ++++++++++++++++++ ...-organization-write-guards.dogfood.test.ts | 8 +- ...adata-door-reaches-catalog.dogfood.test.ts | 10 +- .../permission-set-clone-door.dogfood.test.ts | 53 +++-- ...known-grant-object-refusal.dogfood.test.ts | 6 +- .../personal-view-row-scope.dogfood.test.ts | 8 +- ...e-binds-outside-sets-38149.dogfood.test.ts | 8 + .../print-service-named-page.dogfood.test.ts | 18 +- ...-currency-follow-save-door.dogfood.test.ts | 28 ++- ...p-undeclared-related-field.dogfood.test.ts | 6 +- ...ld-boot-environment-holder.dogfood.test.ts | 19 ++ ...ws-runtime-metadata-change.dogfood.test.ts | 19 +- ...aring-rule-org-less-caller.dogfood.test.ts | 6 +- ...owcase-fls-read-mask-strip.dogfood.test.ts | 8 +- ...wcase-mcp-aggregate-filter.dogfood.test.ts | 8 +- ...describe-object-field-mask.dogfood.test.ts | 8 +- ...wcase-scope-depth-fallback.dogfood.test.ts | 5 +- ...nector-package-ref-restart.dogfood.test.ts | 32 ++- ...ored-connector-package-ref.dogfood.test.ts | 31 ++- ...-expression-fill-at-change.dogfood.test.ts | 19 +- .../upsert-by-id-caller-read.dogfood.test.ts | 12 +- ...iner-cross-package-default.dogfood.test.ts | 12 +- .../test/wall-catalog-refusal.dogfood.test.ts | 16 +- ...ed-webhook-deployment-wide.dogfood.test.ts | 8 +- ...vironment-metadata-refusal.dogfood.test.ts | 64 ++++-- ...wall-package-doors-refusal.dogfood.test.ts | 8 + .../test/wall-package-refusal.dogfood.test.ts | 5 +- ...-door-credential-redaction.dogfood.test.ts | 10 +- 75 files changed, 1079 insertions(+), 279 deletions(-) create mode 100644 packages/qa/dogfood/test/packageless-create-refused.dogfood.test.ts diff --git a/packages/qa/dogfood/test/action-list-packageless-other-object.dogfood.test.ts b/packages/qa/dogfood/test/action-list-packageless-other-object.dogfood.test.ts index 46250c8b202..3aaf7664bf1 100644 --- a/packages/qa/dogfood/test/action-list-packageless-other-object.dogfood.test.ts +++ b/packages/qa/dogfood/test/action-list-packageless-other-object.dogfood.test.ts @@ -79,8 +79,23 @@ describe('[#33904] the action list agrees with the by-name read beside a package const name = order === 'the package\'s save first' ? 'qa_list_agree_pf' : 'qa_list_agree_ef'; const savePackage = () => put(`/meta/action/${name}?package=${PKG}`, action(name, 'package on task', 'showcase_task')); const saveEnvironment = () => put(`/meta/action/${name}`, action(name, 'environment on product', 'showcase_product')); + // [#38174] Saved first, the environment's item is a package-less CREATE, + // which no door makes any more (ADR-0070 D1): that order seeds the + // environment's row directly, as a legacy row, with the system context. + // Saved second, it is a package-less save of a name P holds, still open. + const seedEnvironment = async () => { + const ql = (await stack.kernel.getServiceAsync('objectql')) as unknown as { + insert(object: string, data: Record, options?: unknown): Promise; + }; + const now = new Date().toISOString(); + await ql.insert('sys_metadata', { + type: 'action', name, package_id: null, scope: 'platform', + state: 'active', version: 1, checksum: null, created_at: now, updated_at: now, + metadata: JSON.stringify(action(name, 'environment on product', 'showcase_product')), + }, { context: { isSystem: true, positions: [], permissions: [] } }); + }; if (order === 'the package\'s save first') { await savePackage(); await saveEnvironment(); } - else { await saveEnvironment(); await savePackage(); } + else { await seedEnvironment(); await savePackage(); } // [#33904, ADR-0150 D4] Two items, keyed by object: the bare read // serves the environment's own item (ruling 6942962369), the list names diff --git a/packages/qa/dogfood/test/activation-write-operator-gate-single.dogfood.test.ts b/packages/qa/dogfood/test/activation-write-operator-gate-single.dogfood.test.ts index b62b75339c0..c1853a51929 100644 --- a/packages/qa/dogfood/test/activation-write-operator-gate-single.dogfood.test.ts +++ b/packages/qa/dogfood/test/activation-write-operator-gate-single.dogfood.test.ts @@ -37,6 +37,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; const SYS = { isSystem: true } as const; const LEDGER = 'sys_metadata_activation'; @@ -96,7 +97,9 @@ describe('activation doors on the stock `single` posture: the authoring tier ans // The scratch set: `manage_metadata` and nothing else, authored at runtime // the way an administrator authors one (no stock showcase set grants it). - const saved = await stack.apiAs(admin, 'PUT', `/meta/permission/${SCRATCH_SET}`, { + // [#38174] A new item is created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + const pkg = await ensurePair(stack, admin, 'com.example.showcase'); + const saved = await stack.apiAs(admin, 'PUT', `/meta/permission/${SCRATCH_SET}?package=${pkg}`, { name: SCRATCH_SET, label: 'Activation gate meta author', objects: {}, systemPermissions: ['manage_metadata'], }); expect(saved.status, await saved.clone().text()).toBe(200); diff --git a/packages/qa/dogfood/test/analytics-formula-dimension-authoring.dogfood.test.ts b/packages/qa/dogfood/test/analytics-formula-dimension-authoring.dogfood.test.ts index 42be5e10f7b..e6e1f0448d2 100644 --- a/packages/qa/dogfood/test/analytics-formula-dimension-authoring.dogfood.test.ts +++ b/packages/qa/dogfood/test/analytics-formula-dimension-authoring.dogfood.test.ts @@ -20,6 +20,10 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.showcase.custom'; const OBJECT = 'showcase_project'; const SAVED = 'os30773_project_by_formula'; @@ -43,6 +47,8 @@ describe('dogfood: a dataset dimension over a formula field is refused at author beforeAll(async () => { stack = await bootShowcase(); token = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, token, 'com.example.showcase'); }, 180_000); afterAll(async () => { @@ -55,7 +61,7 @@ describe('dogfood: a dataset dimension over a formula field is refused at author } it('PUT /meta/dataset: the save is refused 422, naming dimension-virtual-field-refused at the dimension', async () => { - const res = await call('PUT', `/meta/dataset/${SAVED}`, dataset(SAVED, true)); + const res = await call('PUT', `/meta/dataset/${SAVED}?package=${PAIR_PKG}`, dataset(SAVED, true)); expect(res.status, JSON.stringify(res.body)).toBe(422); const text = JSON.stringify(res.body); expect(text).toContain('dimension-virtual-field-refused'); @@ -64,7 +70,7 @@ describe('dogfood: a dataset dimension over a formula field is refused at author }); it('CONTROL PUT /meta/dataset: the same dataset over a stored dimension saves', async () => { - const res = await call('PUT', `/meta/dataset/${SAVED_CONTROL}`, dataset(SAVED_CONTROL, false)); + const res = await call('PUT', `/meta/dataset/${SAVED_CONTROL}?package=${PAIR_PKG}`, dataset(SAVED_CONTROL, false)); expect(res.status, JSON.stringify(res.body)).toBe(200); }); diff --git a/packages/qa/dogfood/test/authz-conformance.matrix.ts b/packages/qa/dogfood/test/authz-conformance.matrix.ts index 4898df808b3..ee802185477 100644 --- a/packages/qa/dogfood/test/authz-conformance.matrix.ts +++ b/packages/qa/dogfood/test/authz-conformance.matrix.ts @@ -260,7 +260,7 @@ export const AUTHZ_CONFORMANCE: AuthzPrimitive[] = [ // #22773 — the one route the floor admits (ruling A on #22757): named in the // note's last sentences. ⛔ Ids stay in this comment, out of the row's strings. { id: 'anonymous-deny-automation', summary: 'anonymous-deny on the automation/flow surface (uniform anonymous posture, surface 3: refused 401 before dispatch, as `/data` and `/meta` are)', state: 'enforced', - enforcement: 'runtime/domains/automation.ts handleAutomationRequest — shouldDenyAnonymous DOMAIN-WIDE at the top, and deliberately BEFORE the isServiceServeable probe so the 401/501 difference cannot be used to fingerprint whether a deployment mounts automation; per-route capability predicates run after this floor — `manage_metadata` for the five gated flow writes (create `POST /` / update `PUT /:name` / deregister `DELETE /:name`, the definition writes on the metadata plane, plus enablement `POST /:name/toggle` since the 2026-08-23 ruling that enablement is an authoring write, which measured that the enabled bit is not a ROW and so reaches every organization on the deployment, plus the ADR-0126 §7.1 clone `POST /:name/clone`, which registers flow metadata at environment scope exactly as create does), all selected by the ONE `isFlowAuthoringWrite` predicate, fail-closed by construction (an absent executionContext, an absent `systemPermissions` or an empty one all refuse) and answering 403 `PERMISSION_DENIED`, with only engine `isSystem` bypassing; the run-state reads (the `sys_automation_run` read grant) and `resume` (keyed on the node the run is suspended on, fail-closed for a node that declares no resumeAuthority) carry their own separate per-route predicates, and the execution doors (trigger / execute) sit outside all of them — including `POST /trigger/:name` for a flow literally NAMED `toggle`, which the toggle arm deliberately excludes so a name cannot cost a member its run door', + enforcement: 'runtime/domains/automation.ts handleAutomationRequest — shouldDenyAnonymous DOMAIN-WIDE at the top, and deliberately BEFORE the isServiceServeable probe so the 401/501 difference cannot be used to fingerprint whether a deployment mounts automation; per-route capability predicates run after this floor — `manage_metadata` for the four gated flow writes (update `PUT /:name` / deregister `DELETE /:name`, the definition writes on the metadata plane — the create door `POST /` is retired (#38174) and unmounted, a new flow being created through `PUT /meta/flow/:name?package=` — plus enablement `POST /:name/toggle` since the 2026-08-23 ruling that enablement is an authoring write, which measured that the enabled bit is not a ROW and so reaches every organization on the deployment, plus the ADR-0126 §7.1 clone `POST /:name/clone`, which registers flow metadata exactly as a create does), all selected by the ONE `isFlowAuthoringWrite` predicate, fail-closed by construction (an absent executionContext, an absent `systemPermissions` or an empty one all refuse) and answering 403 `PERMISSION_DENIED`, with only engine `isSystem` bypassing; the run-state reads (the `sys_automation_run` read grant) and `resume` (keyed on the node the run is suspended on, fail-closed for a node that declares no resumeAuthority) carry their own separate per-route predicates, and the execution doors (trigger / execute) sit outside all of them — including `POST /trigger/:name` for a flow literally NAMED `toggle`, which the toggle arm deliberately excludes so a name cannot cost a member its run door', proof: 'showcase-anonymous-deny-surfaces.dogfood.test.ts', // [2026-08-31] Ledger granularity for the same DOMAIN-WIDE gate named // above — the property the note already relies on ("gating the DOMAIN diff --git a/packages/qa/dogfood/test/automation-authoring-doors-durable.dogfood.test.ts b/packages/qa/dogfood/test/automation-authoring-doors-durable.dogfood.test.ts index 2e1dbfdad16..2c94533b4bc 100644 --- a/packages/qa/dogfood/test/automation-authoring-doors-durable.dogfood.test.ts +++ b/packages/qa/dogfood/test/automation-authoring-doors-durable.dogfood.test.ts @@ -31,10 +31,19 @@ // - a flow created and then removed through the door stays removed after the // cold boot (the removal door keeps pace with the create door); // - a packaged flow's name is still refused as a locked base (the control). +// +// [#38174] `POST /automation`, the create door, is retired: a new flow is +// created through `PUT /meta/flow/NAME?package=PKG` (ADR-0070 D1), here into +// the showcase's writable `.custom` pair, and the update and removal doors +// under test act on it. The create cases pin that the retired door is not +// served, that a `PUT` of a new name is refused `WRITABLE_PACKAGE_REQUIRED` +// naming the `/meta` route, and that a create the store refuses registers +// nothing on the door that now creates. import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; import { ConnectorRestPlugin } from '@objectstack/connector-rest'; import { ConnectorOpenApiPlugin } from '@objectstack/connector-openapi'; import { ConnectorMcpPlugin } from '@objectstack/connector-mcp'; @@ -60,6 +69,9 @@ const REMOVED = 'dogfood_removed_flow_20862'; */ const UNSAVABLE = 'dogfood_unsavable_flow_20862'; +/** [#38174] The writable package new flows are created in: the showcase's paired customization package. */ +const PKG = 'com.example.showcase.custom'; + const UPDATED_LABEL = 'Updated through the automation door'; const definition = (name: string, label = `Dogfood ${name}`) => ({ @@ -132,6 +144,8 @@ describe('the /automation definition doors persist what they register (showcase, dbFile = join(dir, 'showcase.db'); stack = await boot(dbFile); token = await stack.signIn(); + // [#38174] The writable package new flows are created in. + await ensurePair(stack, token, 'com.example.showcase'); }, 180_000); afterAll(async () => { @@ -140,9 +154,18 @@ describe('the /automation definition doors persist what they register (showcase, if (dir) rmSync(dir, { recursive: true, force: true }); }); - it('a flow created through the automation door reads back on the metadata door', async () => { - const created = await call('POST', '/automation', definition(CREATED)); + it('a flow created through the metadata door is registered on the automation door and reads back on the metadata door', async () => { + // The retired create door is not served, and the update door does not create. + expect((await call('POST', '/automation', definition(CREATED))).status).toBe(404); + const refused = await call('PUT', `/automation/${CREATED}`, definition(CREATED)); + expect(refused.status, JSON.stringify(refused.json)).toBe(422); + expect(dispatcherCode(refused.json)).toBe('WRITABLE_PACKAGE_REQUIRED'); + expect((refused.json as DispatcherEnvelope).error?.message).toContain(`/api/v1/meta/flow/${CREATED}?package=`); + expect((await call('GET', `/automation/${CREATED}`)).status).toBe(404); + + const created = await call('PUT', `/meta/flow/${CREATED}?package=${PKG}`, definition(CREATED)); expect(created.status, JSON.stringify(created.json)).toBe(200); + expect(await engineLabel(CREATED)).toEqual({ status: 200, label: `Dogfood ${CREATED}` }); const served = await metaRead(CREATED); expect(served.status, JSON.stringify(served.doc)).toBe(200); @@ -150,7 +173,7 @@ describe('the /automation definition doors persist what they register (showcase, }); it('an update through the automation door to a /meta-stored flow reads back on the metadata door', async () => { - const stored = await call('PUT', `/meta/flow/${META_STORED}`, definition(META_STORED, 'Stored through /meta')); + const stored = await call('PUT', `/meta/flow/${META_STORED}?package=${PKG}`, definition(META_STORED, 'Stored through /meta')); expect(stored.status, JSON.stringify(stored.json)).toBe(200); const updated = await call('PUT', `/automation/${META_STORED}`, definition(META_STORED, UPDATED_LABEL)); @@ -161,10 +184,10 @@ describe('the /automation definition doors persist what they register (showcase, }); it('a create whose save the store refuses answers the store\'s refusal and leaves no engine registration', async () => { - const created = await call('POST', '/automation', gateRefused(UNSAVABLE)); + const created = await call('PUT', `/meta/flow/${UNSAVABLE}?package=${PKG}`, gateRefused(UNSAVABLE)); expect(created.status, JSON.stringify(created.json)).toBe(422); - expect(dispatcherCode(created.json)).toBe('INVALID_METADATA'); + expect((created.json as { code?: string }).code).toBe('INVALID_METADATA'); expect((await call('GET', `/automation/${UNSAVABLE}`)).status).toBe(404); }); @@ -177,8 +200,8 @@ describe('the /automation definition doors persist what they register (showcase, expect((await metaRead(META_STORED)).doc.label).toBe(UPDATED_LABEL); }); - it('a flow created and then removed through the automation door is gone from the metadata door too', async () => { - const created = await call('POST', '/automation', definition(REMOVED)); + it('a flow created through /meta and removed through the automation door is gone from the metadata door too', async () => { + const created = await call('PUT', `/meta/flow/${REMOVED}?package=${PKG}`, definition(REMOVED)); expect(created.status, JSON.stringify(created.json)).toBe(200); const removed = await call('DELETE', `/automation/${REMOVED}`); @@ -195,9 +218,9 @@ describe('the /automation definition doors persist what they register (showcase, expect(put.status, JSON.stringify(put.json)).toBe(403); expect(dispatcherCode(put.json)).toBe('NOT_OVERRIDABLE'); + // [#38174] The create door is retired: a create onto the name is not served. const post = await call('POST', '/automation', { ...before, label: 'Overwritten via create' }); - expect(post.status, JSON.stringify(post.json)).toBe(403); - expect(dispatcherCode(post.json)).toBe('NOT_OVERRIDABLE'); + expect(post.status, JSON.stringify(post.json)).toBe(404); expect(dataOf((await call('GET', `/automation/${SHIPPED}`)).json)).toEqual(before); }); diff --git a/packages/qa/dogfood/test/automation-toggle-tenant-scope.dogfood.test.ts b/packages/qa/dogfood/test/automation-toggle-tenant-scope.dogfood.test.ts index 1d4ac547b63..a8a67e0f101 100644 --- a/packages/qa/dogfood/test/automation-toggle-tenant-scope.dogfood.test.ts +++ b/packages/qa/dogfood/test/automation-toggle-tenant-scope.dogfood.test.ts @@ -212,8 +212,10 @@ describe('#10243 — POST /automation/:name/toggle demands `manage_metadata`', ( expect(meta.status).toBe(403); expect(((await meta.json()) as { error?: { code?: string } }).error?.code).toBe('FORBIDDEN'); - for (const [method, path] of [['POST', '/automation'], ['DELETE', `/automation/${FLOW}`]] as const) { - const body = method === 'POST' + // [#38174] `POST /automation` (the create door) is retired; the gated + // definition write a member could attempt is `PUT /automation/:name`. + for (const [method, path] of [['PUT', '/automation/probe_flow_10243'], ['DELETE', `/automation/${FLOW}`]] as const) { + const body = method === 'PUT' ? { name: 'probe_flow_10243', label: 'Probe', type: 'autolaunched', nodes: [], edges: [] } : undefined; const res = await stack.apiAs(tenantAToken, method, path, body); diff --git a/packages/qa/dogfood/test/bare-name-one-holder-ai-family.dogfood.test.ts b/packages/qa/dogfood/test/bare-name-one-holder-ai-family.dogfood.test.ts index c2c6040d2e7..a42e12641b9 100644 --- a/packages/qa/dogfood/test/bare-name-one-holder-ai-family.dogfood.test.ts +++ b/packages/qa/dogfood/test/bare-name-one-holder-ai-family.dogfood.test.ts @@ -403,9 +403,18 @@ describe('agent, skill and tool names held per namespace, on a booted showcase', const DOWN = 'qa_row_tool_down'; beforeAll(async () => { + // [#38174] No door creates a package-less row any more (ADR-0070 D1): + // the legacy row this pin judges is seeded directly, with the system context. + const ql = (await stack.kernel.getServiceAsync('objectql')) as unknown as { + insert(object: string, data: Record, options?: unknown): Promise; + }; + const now = new Date().toISOString(); for (const name of [UP, DOWN]) { - const saved = await stack.apiAs(admin, 'PUT', `/meta/tool/${name}`, tool('env', name)); - expect(saved.status, await saved.text()).toBeLessThan(300); + await ql.insert('sys_metadata', { + type: 'tool', name, package_id: null, scope: 'platform', + state: 'active', version: 1, checksum: null, created_at: now, updated_at: now, + metadata: JSON.stringify(tool('env', name)), + }, { context: { isSystem: true, positions: [], permissions: [] } }); } for (const [p, tools] of [['kappa', [UP]], ['lambda', [UP, DOWN]], ['iota', [DOWN]]] as const) { const { status, body } = await installLocal(inline(p, { tools: tools.map((n) => tool(p, n)) })); diff --git a/packages/qa/dogfood/test/bare-name-one-holder-request-family.dogfood.test.ts b/packages/qa/dogfood/test/bare-name-one-holder-request-family.dogfood.test.ts index 7171e832b57..aa6a5bdf66c 100644 --- a/packages/qa/dogfood/test/bare-name-one-holder-request-family.dogfood.test.ts +++ b/packages/qa/dogfood/test/bare-name-one-holder-request-family.dogfood.test.ts @@ -270,6 +270,19 @@ describe('one package holder per API, object-less action and function name, on a return { status: r.status, body: (await r.json()) as any, ran: takeRuns() }; }; + /** [#38174] A legacy package-less row, inserted as the store writes one, with the system context. */ + const seedLooseRow = async (type: string, name: string, body: unknown) => { + const ql = (await stack.kernel.getServiceAsync('objectql')) as unknown as { + insert(object: string, data: Record, options?: unknown): Promise; + }; + const now = new Date().toISOString(); + await ql.insert('sys_metadata', { + type, name, package_id: null, scope: 'platform', + state: 'active', version: 1, checksum: null, created_at: now, updated_at: now, + metadata: JSON.stringify(body), + }, { context: { isSystem: true, positions: [], permissions: [] } }); + }; + it('each package\'s script flow runs its OWN function of the name both hold (it ran the last registration)', async () => { for (const p of ['alpha', 'beta'] as const) { const { status, body, ran } = await trigger(`${p}_fn_flow`); @@ -278,6 +291,9 @@ describe('one package holder per API, object-less action and function name, on a }); it('narrowing — a flow with no package naming the two-holder function is 400 FLOW_FAILED carrying RESOURCE_CONFLICT naming both; neither runs', async () => { + // [#38174] A package-less flow is a legacy loose row (no door creates one, + // ADR-0070 D1): seeded directly, then saved in place, which stays open. + await seedLooseRow('flow', 'qa_env_fn_flow', fnFlow('qa_env_fn_flow', FN)); const put = await stack.apiAs(admin, 'PUT', '/meta/flow/qa_env_fn_flow', fnFlow('qa_env_fn_flow', FN)); expect(put.status, await put.clone().text()).toBeLessThan(300); const { status, body, ran } = await trigger('qa_env_fn_flow'); @@ -305,6 +321,9 @@ describe('one package holder per API, object-less action and function name, on a it('CONTROL — a one-holder function runs for its own package\'s flow and for a flow with no package, as before', async () => { const own = await trigger('alpha_alpha_fn_flow'); expect([own.status, own.body?.data?.success ?? own.body?.success, own.ran], JSON.stringify(own.body)).toEqual([200, true, ['alpha-only']]); + // [#38174] A package-less flow is a legacy loose row (no door creates one, + // ADR-0070 D1): seeded directly, then saved in place, which stays open. + await seedLooseRow('flow', 'qa_env_alpha_fn_flow', fnFlow('qa_env_alpha_fn_flow', ALPHA_FN)); const put = await stack.apiAs(admin, 'PUT', '/meta/flow/qa_env_alpha_fn_flow', fnFlow('qa_env_alpha_fn_flow', ALPHA_FN)); expect(put.status, await put.clone().text()).toBeLessThan(300); const env = await trigger('qa_env_alpha_fn_flow'); diff --git a/packages/qa/dogfood/test/catalog-activation-door.dogfood.test.ts b/packages/qa/dogfood/test/catalog-activation-door.dogfood.test.ts index 22c37c8c6ad..a2d78c1309a 100644 --- a/packages/qa/dogfood/test/catalog-activation-door.dogfood.test.ts +++ b/packages/qa/dogfood/test/catalog-activation-door.dogfood.test.ts @@ -195,6 +195,20 @@ describe('the catalog activation door, on a booted showcase', () => { // placeholder a reader could take for a package. The row is honoured all // the same, because the resolver keys it by type and name only. it('an environment-authored position and permission set switch off and back on, and the resolver honours both', async () => { + // [#38174] A package-less item is a legacy loose row (no door creates + // one, ADR-0070 D1): each is seeded directly, then saved in place + // through the door, which stays open. + const now = new Date().toISOString(); + for (const [type, name, body] of [ + ['permission', ENV_SET, { name: ENV_SET, label: 'Saved in the environment', objects: {} }], + ['position', ENV_POSITION, { name: ENV_POSITION, label: 'Saved in the environment', permissionSets: [ENV_SET] }], + ] as const) { + await ql.insert('sys_metadata', { + type, name, package_id: null, scope: 'platform', + state: 'active', version: 1, checksum: null, created_at: now, updated_at: now, + metadata: JSON.stringify(body), + }, { context: SYSTEM_CTX }); + } const savedSet = await stack.apiAs(token, 'PUT', `/meta/permission/${ENV_SET}`, { name: ENV_SET, label: 'Saved in the environment', objects: {}, }); diff --git a/packages/qa/dogfood/test/connector-failure-text-withheld.dogfood.test.ts b/packages/qa/dogfood/test/connector-failure-text-withheld.dogfood.test.ts index 3ab080121b8..b9fe97cdd93 100644 --- a/packages/qa/dogfood/test/connector-failure-text-withheld.dogfood.test.ts +++ b/packages/qa/dogfood/test/connector-failure-text-withheld.dogfood.test.ts @@ -19,6 +19,7 @@ import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; const SYSTEM = { isSystem: true, positions: [], permissions: [] }; @@ -100,7 +101,9 @@ describe("a connector's failure text carries no credential part the connector me // saved disabled and clean, then the system context writes the seeded // form over it, and a save of the served form (the stored URL carried // forward) enables it, so the instance materializes from the stored URL. - const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${SEEDED}`, instance(SEEDED, PLAIN_SPEC, { enabled: false })); + // [#38174] A new item is created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + const pkg = await ensurePair(stack, admin, 'com.example.showcase'); + const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${SEEDED}?package=${pkg}`, instance(SEEDED, PLAIN_SPEC, { enabled: false })); expect(put.status, await put.clone().text()).toBe(200); const [row] = await stored(SEEDED); await ql.update('sys_metadata', { id: row.id, metadata: JSON.stringify(instance(SEEDED, CREDENTIAL_SPEC)) }, { context: SYSTEM }); @@ -124,7 +127,7 @@ describe("a connector's failure text carries no credential part the connector me for (const spy of spies) spy.mockRestore(); } - const plain = await stack.apiAs(admin, 'PUT', `/meta/connector/${PLAIN}`, instance(PLAIN, PLAIN_SPEC)); + const plain = await stack.apiAs(admin, 'PUT', `/meta/connector/${PLAIN}?package=${pkg}`, instance(PLAIN, PLAIN_SPEC)); expect(plain.status, await plain.clone().text()).toBe(200); await waitDegraded(PLAIN); }, 180_000); diff --git a/packages/qa/dogfood/test/connector-installer-oauth-client.dogfood.test.ts b/packages/qa/dogfood/test/connector-installer-oauth-client.dogfood.test.ts index 87b3ca165e9..827b07c3920 100644 --- a/packages/qa/dogfood/test/connector-installer-oauth-client.dogfood.test.ts +++ b/packages/qa/dogfood/test/connector-installer-oauth-client.dogfood.test.ts @@ -29,6 +29,10 @@ import { createServer, type Server } from 'node:http'; import type { AddressInfo } from 'node:net'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.showcase.custom'; const SYSTEM = { isSystem: true, positions: [], permissions: [] }; @@ -99,11 +103,13 @@ describe("connector connection door: an `oauth2` instance that takes the install stack = await bootShowcase({}); ql = await stack.kernel.getServiceAsync('objectql'); admin = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, admin, 'com.example.showcase'); // The redirect URI is the deployment's fixed origin, read when a connect // is begun — never at boot, and never from the request (ADR-0143 D5). if (!savedOrigin.auth && !savedOrigin.base) process.env.OS_BASE_URL = 'https://dogfood.example.com'; - const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${NAME}`, { + const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${NAME}?package=${PAIR_PKG}`, { name: NAME, label: 'CIOC vendor', type: 'api', diff --git a/packages/qa/dogfood/test/connector-meta-door-credential-hardening.dogfood.test.ts b/packages/qa/dogfood/test/connector-meta-door-credential-hardening.dogfood.test.ts index 538826d4bf4..6e28f42fd77 100644 --- a/packages/qa/dogfood/test/connector-meta-door-credential-hardening.dogfood.test.ts +++ b/packages/qa/dogfood/test/connector-meta-door-credential-hardening.dogfood.test.ts @@ -25,6 +25,10 @@ import { createServer, type IncomingHttpHeaders, type Server } from 'node:http'; import type { AddressInfo } from 'node:net'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.showcase.custom'; const SYSTEM = { isSystem: true, positions: [], permissions: [] }; @@ -131,6 +135,8 @@ describe('connector metadata doors: inline credentials are refused on write and protocol = await stack.kernel.getServiceAsync('protocol'); automation = await stack.kernel.getServiceAsync('automation'); admin = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, admin, 'com.example.showcase'); member = await stack.signUp('cch-member@connector-credentials.test'); }, 180_000); @@ -149,7 +155,7 @@ describe('connector metadata doors: inline credentials are refused on write and ['none', { type: 'none', token: PLACEHOLDERS.inlineToken }, 'token'], ] as const)('%s: 422 INVALID_METADATA located at `auth`, naming the key, and nothing is stored', async (kind, auth, key) => { const name = refusedName(kind); - const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${name}`, instance(name, { auth })); + const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${name}?package=${PAIR_PKG}`, instance(name, { auth })); const json = (await res.json()) as any; expect(res.status, JSON.stringify(json).slice(0, 400)).toBe(422); expect(json.code, JSON.stringify(json).slice(0, 400)).toBe('INVALID_METADATA'); @@ -164,7 +170,7 @@ describe('connector metadata doors: inline credentials are refused on write and describe('CONTROL: a credentialRef-only instance saves and works', () => { it('saves, materializes ready, and dispatches with the reference resolved and its default headers sent', async () => { - const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${CONTROL}`, instance(CONTROL, { + const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${CONTROL}?package=${PAIR_PKG}`, instance(CONTROL, { providerConfig: { baseUrl: upstreamUrl, defaultHeaders: { 'X-Placeholder-Header': PLACEHOLDERS.defaultHeaderValue } }, })); expect(put.status, await put.clone().text()).toBe(200); @@ -183,7 +189,7 @@ describe('connector metadata doors: inline credentials are refused on write and expect(served.auth).toEqual({ type: 'bearer', credentialRef: CONTROL_REF }); const body = Object.fromEntries(Object.entries(served).filter(([k]) => !k.startsWith('_'))); - const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${CONTROL}`, { ...body, label: 'CCH control (edited)' }); + const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${CONTROL}?package=${PAIR_PKG}`, { ...body, label: 'CCH control (edited)' }); expect(put.status, await put.clone().text()).toBe(200); const [row] = await stored(CONTROL); expect(bodyOf(row).label).toBe('CCH control (edited)'); @@ -209,7 +215,7 @@ describe('connector metadata doors: inline credentials are refused on write and beforeAll(async () => { // A clean save makes the row; the system context then writes the body a // row stored before the write refusal can hold. - const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${STORED}`, instance(STORED, { + const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${STORED}?package=${PAIR_PKG}`, instance(STORED, { auth: { type: 'bearer', credentialRef: 'CCH_STORED_REF' }, })); expect(put.status, await put.clone().text()).toBe(200); diff --git a/packages/qa/dogfood/test/connector-meta-door-entry-and-url-hardening.dogfood.test.ts b/packages/qa/dogfood/test/connector-meta-door-entry-and-url-hardening.dogfood.test.ts index 7c918b0179b..292bb67e2ab 100644 --- a/packages/qa/dogfood/test/connector-meta-door-entry-and-url-hardening.dogfood.test.ts +++ b/packages/qa/dogfood/test/connector-meta-door-entry-and-url-hardening.dogfood.test.ts @@ -27,6 +27,10 @@ import { createServer, type Server } from 'node:http'; import type { AddressInfo } from 'node:net'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.showcase.custom'; const SYSTEM = { isSystem: true, positions: [], permissions: [] }; @@ -121,7 +125,7 @@ describe('connector metadata doors: undeclared entry keys refused; URL credentia /** A clean save makes the row; the system context then writes `body` over it. */ const seed = async (name: string, body: Record) => { - const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${name}`, instance(name)); + const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${name}?package=${PAIR_PKG}`, instance(name)); expect(put.status, await put.clone().text()).toBe(200); const [row] = await stored(name); await ql.update('sys_metadata', { id: row.id, metadata: JSON.stringify(body) }, { context: SYSTEM }); @@ -143,6 +147,8 @@ describe('connector metadata doors: undeclared entry keys refused; URL credentia ql = await stack.kernel.getServiceAsync('objectql'); automation = await stack.kernel.getServiceAsync('automation'); admin = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, admin, 'com.example.showcase'); member = await stack.signUp('ceu-member@connector-entry.test'); }, 180_000); @@ -159,7 +165,7 @@ describe('connector metadata doors: undeclared entry keys refused; URL credentia ['a nested container', 'ceu_refused_nested', { extraConfig: { secret: PLACEHOLDERS.nested } }, 'extraConfig', 'Unrecognized'], ['a misplaced provider setting', 'ceu_refused_provider', { baseUrl: 'http://127.0.0.1:9/v1' }, 'baseUrl', 'providerConfig'], ] as const)('%s: 422 INVALID_METADATA naming the key, and nothing is stored', async (_label, name, extra, key, prescription) => { - const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${name}`, { ...instance(name), ...extra }); + const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${name}?package=${PAIR_PKG}`, { ...instance(name), ...extra }); const json = (await res.json()) as any; expect(res.status, JSON.stringify(json).slice(0, 400)).toBe(422); expect(json.code, JSON.stringify(json).slice(0, 400)).toBe('INVALID_METADATA'); @@ -177,7 +183,7 @@ describe('connector metadata doors: undeclared entry keys refused; URL credentia describe('CONTROL: a declared-keys-only instance saves and works', () => { it('saves, materializes ready, and dispatches with the reference resolved', async () => { - const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${CONTROL}`, instance(CONTROL, { + const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${CONTROL}?package=${PAIR_PKG}`, instance(CONTROL, { providerConfig: { baseUrl: `${upstreamUrl}/v1` }, })); expect(put.status, await put.clone().text()).toBe(200); @@ -253,7 +259,7 @@ describe('connector metadata doors: undeclared entry keys refused; URL credentia // A row stored before the save door refused a credential part in a URL: // saved disabled, so nothing materializes before the seeded form is the // row, then the system context writes that form over it. - const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${CARRIED}`, instance(CARRIED, { enabled: false })); + const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${CARRIED}?package=${PAIR_PKG}`, instance(CARRIED, { enabled: false })); expect(put.status, await put.clone().text()).toBe(200); const [row] = await stored(CARRIED); await ql.update('sys_metadata', { @@ -267,7 +273,7 @@ describe('connector metadata doors: undeclared entry keys refused; URL credentia expect(holdsAPlaceholder(served)).toBe(false); const body = Object.fromEntries(Object.entries(served).filter(([k]) => !k.startsWith('_'))); - const resave = await stack.apiAs(admin, 'PUT', `/meta/connector/${CARRIED}`, { ...body, label: 'CEU carried (edited)' }); + const resave = await stack.apiAs(admin, 'PUT', `/meta/connector/${CARRIED}?package=${PAIR_PKG}`, { ...body, label: 'CEU carried (edited)' }); expect(resave.status, await resave.clone().text()).toBe(200); const atRest = bodyOf((await stored(CARRIED))[0]); expect(atRest.label).toBe('CEU carried (edited)'); diff --git a/packages/qa/dogfood/test/connector-meta-door-root-key-read.dogfood.test.ts b/packages/qa/dogfood/test/connector-meta-door-root-key-read.dogfood.test.ts index 87072910eda..754455ebcac 100644 --- a/packages/qa/dogfood/test/connector-meta-door-root-key-read.dogfood.test.ts +++ b/packages/qa/dogfood/test/connector-meta-door-root-key-read.dogfood.test.ts @@ -17,6 +17,10 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.showcase.custom'; const SYSTEM = { isSystem: true, positions: [], permissions: [] }; @@ -80,10 +84,12 @@ describe('connector metadata read doors: root keys the entry does not declare ar stack = await bootShowcase({}); ql = await stack.kernel.getServiceAsync('objectql'); admin = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, admin, 'com.example.showcase'); member = await stack.signUp('crk-member@connector-root-keys.test'); // A clean save makes the row; the system context then writes the legacy body over it. - const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${ROW}`, instance(ROW)); + const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${ROW}?package=${PAIR_PKG}`, instance(ROW)); expect(put.status, await put.clone().text()).toBe(200); const [row] = await stored(ROW); await ql.update('sys_metadata', { @@ -134,7 +140,7 @@ describe('connector metadata read doors: root keys the entry does not declare ar expectRootKeysAbsent(served, 'served'); const body = Object.fromEntries(Object.entries(served).filter(([k]) => !k.startsWith('_'))); - const resave = await stack.apiAs(admin, 'PUT', `/meta/connector/${ROW}`, { ...body, label: 'CRK root keys (edited)' }); + const resave = await stack.apiAs(admin, 'PUT', `/meta/connector/${ROW}?package=${PAIR_PKG}`, { ...body, label: 'CRK root keys (edited)' }); expect(resave.status, await resave.clone().text()).toBe(200); const atRest = bodyOf((await stored(ROW))[0]); @@ -162,7 +168,7 @@ describe('connector metadata read doors: root keys the entry does not declare ar }); it('a cleared undeclared root key is withheld so a plain read then save answers 200, not 422', async () => { - const put = await stack.apiAs(admin, 'PUT', `/meta/connector/crk_cleared`, instance('crk_cleared')); + const put = await stack.apiAs(admin, 'PUT', `/meta/connector/crk_cleared?package=${PAIR_PKG}`, instance('crk_cleared')); expect(put.status, await put.clone().text()).toBe(200); const [row] = await stored('crk_cleared'); await ql.update('sys_metadata', { @@ -176,12 +182,12 @@ describe('connector metadata read doors: root keys the entry does not declare ar expect(served).not.toHaveProperty('extra'); const body = Object.fromEntries(Object.entries(served).filter(([k]) => !k.startsWith('_'))); - const resave = await stack.apiAs(admin, 'PUT', `/meta/connector/crk_cleared`, { ...body, label: 'CRK cleared (edited)' }); + const resave = await stack.apiAs(admin, 'PUT', `/meta/connector/crk_cleared?package=${PAIR_PKG}`, { ...body, label: 'CRK cleared (edited)' }); expect(resave.status, await resave.clone().text()).toBe(200); }); it('a withheld dot-spelled root key and a dot-spelled providerConfig URL survive a save of the served form', async () => { - const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${DOTTED}`, instance(DOTTED)); + const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${DOTTED}?package=${PAIR_PKG}`, instance(DOTTED)); expect(put.status, await put.clone().text()).toBe(200); const [row] = await stored(DOTTED); const dottedUrl = `https://svc:${PLACEHOLDERS.dottedUrl}@api.vendor.example/v1`; @@ -200,7 +206,7 @@ describe('connector metadata read doors: root keys the entry does not declare ar expect(served.providerConfig).not.toHaveProperty('v1.url'); const body = Object.fromEntries(Object.entries(served).filter(([k]) => !k.startsWith('_'))); - const resave = await stack.apiAs(admin, 'PUT', `/meta/connector/${DOTTED}`, { ...body, label: 'CRK dotted (edited)' }); + const resave = await stack.apiAs(admin, 'PUT', `/meta/connector/${DOTTED}?package=${PAIR_PKG}`, { ...body, label: 'CRK dotted (edited)' }); expect(resave.status, await resave.clone().text()).toBe(200); const atRest = bodyOf((await stored(DOTTED))[0]); diff --git a/packages/qa/dogfood/test/connector-meta-door-undeclared-keys-withheld.dogfood.test.ts b/packages/qa/dogfood/test/connector-meta-door-undeclared-keys-withheld.dogfood.test.ts index f2cdd31d6b4..90d297b3599 100644 --- a/packages/qa/dogfood/test/connector-meta-door-undeclared-keys-withheld.dogfood.test.ts +++ b/packages/qa/dogfood/test/connector-meta-door-undeclared-keys-withheld.dogfood.test.ts @@ -26,6 +26,10 @@ import { createServer, type Server } from 'node:http'; import type { AddressInfo } from 'node:net'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.showcase.custom'; const SYSTEM = { isSystem: true, positions: [], permissions: [] }; @@ -140,11 +144,13 @@ describe('connector metadata doors: keys a connector does not declare are withhe ql = await stack.kernel.getServiceAsync('objectql'); automation = await stack.kernel.getServiceAsync('automation'); admin = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, admin, 'com.example.showcase'); member = await stack.signUp('cuk-member@connector-undeclared.test'); // A clean save makes the legacy row; the system context then writes the // undeclared top-level keys over it. - const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${LEGACY}`, instance(LEGACY)); + const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${LEGACY}?package=${PAIR_PKG}`, instance(LEGACY)); expect(put.status, await put.clone().text()).toBe(200); const [row] = await stored(LEGACY); await ql.update('sys_metadata', { @@ -159,7 +165,7 @@ describe('connector metadata doors: keys a connector does not declare are withhe // The nested rows: a clean save, then the system context writes the // undeclared nested key over it (the save door refuses it now). const seedOver = async (name: string, clean: Record, seeded: Record) => { - const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${name}`, clean); + const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${name}?package=${PAIR_PKG}`, clean); expect(res.status, await res.clone().text()).toBe(200); const [seedRow] = await stored(name); await ql.update('sys_metadata', { id: seedRow.id, metadata: JSON.stringify(seeded) }, { context: SYSTEM }); @@ -252,7 +258,7 @@ describe('connector metadata doors: keys a connector does not declare are withhe describe('CARRY-FORWARD: a save of the served form keeps the stored values', () => { it('the legacy row: the served form saves, and the row keeps its undeclared keys', async () => { const served = (await read(admin, LEGACY)).item; - const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${LEGACY}`, { ...authorable(served), label: 'CUK legacy (edited)' }); + const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${LEGACY}?package=${PAIR_PKG}`, { ...authorable(served), label: 'CUK legacy (edited)' }); expect(res.status, await res.clone().text()).toBe(200); const atRest = bodyOf((await stored(LEGACY))[0]); expect(atRest.label).toBe('CUK legacy (edited)'); @@ -265,7 +271,7 @@ describe('connector metadata doors: keys a connector does not declare are withhe const served = (await read(admin, DESCRIPTOR)).item; const body = authorable(served); body.actions = [...body.actions].reverse(); - const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${DESCRIPTOR}`, body); + const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${DESCRIPTOR}?package=${PAIR_PKG}`, body); expect(res.status, await res.clone().text()).toBe(200); const atRest = bodyOf((await stored(DESCRIPTOR))[0]); expect(atRest.actions).toEqual([ @@ -276,12 +282,12 @@ describe('connector metadata doors: keys a connector does not declare are withhe it('a `retryConfig` sent back as served replaces the stored one whole; one the author removes is removed', async () => { const served = authorable((await read(admin, RETRY)).item); - const replaced = await stack.apiAs(admin, 'PUT', `/meta/connector/${RETRY}`, { ...served, label: 'CUK retry (edited)' }); + const replaced = await stack.apiAs(admin, 'PUT', `/meta/connector/${RETRY}?package=${PAIR_PKG}`, { ...served, label: 'CUK retry (edited)' }); expect(replaced.status, await replaced.clone().text()).toBe(200); expect(bodyOf((await stored(RETRY))[0]).retryConfig).toEqual({ strategy: 'exponential_backoff', maxAttempts: 2 }); const { retryConfig: _removed, ...withoutRetry } = served; - const cleared = await stack.apiAs(admin, 'PUT', `/meta/connector/${RETRY}`, withoutRetry); + const cleared = await stack.apiAs(admin, 'PUT', `/meta/connector/${RETRY}?package=${PAIR_PKG}`, withoutRetry); expect(cleared.status, await cleared.clone().text()).toBe(200); expect(bodyOf((await stored(RETRY))[0])).not.toHaveProperty('retryConfig'); }); @@ -289,7 +295,7 @@ describe('connector metadata doors: keys a connector does not declare are withhe describe('CONTROL: a declared-keys-only instance saves and works', () => { it('saves, materializes ready, and dispatches with the reference resolved', async () => { - const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${CONTROL}`, instance(CONTROL)); + const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${CONTROL}?package=${PAIR_PKG}`, instance(CONTROL)); expect(put.status, await put.clone().text()).toBe(200); await waitReady(CONTROL); const handler = automation.resolveConnectorAction(CONTROL, 'request'); diff --git a/packages/qa/dogfood/test/connector-meta-door-url-and-nested-keys.dogfood.test.ts b/packages/qa/dogfood/test/connector-meta-door-url-and-nested-keys.dogfood.test.ts index 9a199548e49..928102f1657 100644 --- a/packages/qa/dogfood/test/connector-meta-door-url-and-nested-keys.dogfood.test.ts +++ b/packages/qa/dogfood/test/connector-meta-door-url-and-nested-keys.dogfood.test.ts @@ -45,6 +45,10 @@ import { createServer, type Server } from 'node:http'; import type { AddressInfo } from 'node:net'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.showcase.custom'; const SYSTEM = { isSystem: true, positions: [], permissions: [] }; @@ -144,7 +148,7 @@ describe('connector metadata doors: an authored connector keeps no credential in /** One refused save: the 422 envelope, located at `at`, echoing no credential. */ const expectRefused = async (name: string, body: Record, at: string) => { - const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${name}`, body); + const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${name}?package=${PAIR_PKG}`, body); const text = await res.text(); expect(res.status, text.slice(0, 300)).toBe(422); const json = JSON.parse(text); @@ -183,15 +187,17 @@ describe('connector metadata doors: an authored connector keeps no credential in ql = await stack.kernel.getServiceAsync('objectql'); automation = await stack.kernel.getServiceAsync('automation'); admin = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, admin, 'com.example.showcase'); member = await stack.signUp('cun-member@connector-url-nested.test'); - const existing = await stack.apiAs(admin, 'PUT', `/meta/connector/${EXISTING}`, instance(EXISTING)); + const existing = await stack.apiAs(admin, 'PUT', `/meta/connector/${EXISTING}?package=${PAIR_PKG}`, instance(EXISTING)); expect(existing.status, await existing.clone().text()).toBe(200); // Rows stored before the save door refused them: a clean save, then the // system context writes the credential parts / undeclared key over it. const seedOver = async (name: string, clean: Record, seeded: Record) => { - const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${name}`, clean); + const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${name}?package=${PAIR_PKG}`, clean); expect(res.status, await res.clone().text()).toBe(200); const [row] = await stored(name); await ql.update('sys_metadata', { id: row.id, metadata: JSON.stringify(seeded) }, { context: SYSTEM }); @@ -278,7 +284,7 @@ describe('connector metadata doors: an authored connector keeps no credential in describe('CONTROL: credential-free URLs and declared nested keys save and work', () => { it('an instance naming its secret with `credentialRef` saves, materializes ready, and dispatches with the reference resolved', async () => { - const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${CONTROL}`, instance(CONTROL, { + const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${CONTROL}?package=${PAIR_PKG}`, instance(CONTROL, { providerConfig: { baseUrl: `${upstreamUrl}/v1?region=eu&token=` }, retryConfig: { strategy: 'exponential_backoff', maxAttempts: 2 }, })); @@ -300,15 +306,15 @@ describe('connector metadata doors: an authored connector keeps no credential in providerConfig: { spec: inlineSpec('https://api.vendor.example.com/v1?region=eu') }, auth: { type: 'bearer', credentialRef: REF }, }; - const res = await stack.apiAs(admin, 'PUT', '/meta/connector/cun_inline_spec_clean', body); + const res = await stack.apiAs(admin, 'PUT', `/meta/connector/cun_inline_spec_clean?package=${PAIR_PKG}`, body); expect(res.status, await res.clone().text()).toBe(200); expect(bodyOf((await stored('cun_inline_spec_clean'))[0]).providerConfig).toEqual(body.providerConfig); }); it('a descriptor with declared action keys, and an oauth2 instance with credential-free endpoints, save', async () => { - const desc = await stack.apiAs(admin, 'PUT', `/meta/connector/${DESCRIPTOR}`, descriptor); + const desc = await stack.apiAs(admin, 'PUT', `/meta/connector/${DESCRIPTOR}?package=${PAIR_PKG}`, descriptor); expect(desc.status, await desc.clone().text()).toBe(200); - const oauth = await stack.apiAs(admin, 'PUT', '/meta/connector/cun_oauth_clean', oauth2('cun_oauth_clean')); + const oauth = await stack.apiAs(admin, 'PUT', `/meta/connector/cun_oauth_clean?package=${PAIR_PKG}`, oauth2('cun_oauth_clean')); expect(oauth.status, await oauth.clone().text()).toBe(200); expect(bodyOf((await stored(DESCRIPTOR))[0]).actions).toEqual(descriptor.actions); }); @@ -351,7 +357,7 @@ describe('connector metadata doors: an authored connector keeps no credential in describe('CARRY-FORWARD: the served form saves and keeps the stored values; an explicit edit is the author\'s word', () => { it('a save of the served oauth2 row succeeds and keeps each stored endpoint', async () => { const served = authorable((await read(admin, OAUTH_ROW)).item); - const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${OAUTH_ROW}`, { ...served, label: 'CUN oauth (edited)' }); + const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${OAUTH_ROW}?package=${PAIR_PKG}`, { ...served, label: 'CUN oauth (edited)' }); expect(res.status, await res.clone().text()).toBe(200); const atRest = bodyOf((await stored(OAUTH_ROW))[0]); expect(atRest.label).toBe('CUN oauth (edited)'); @@ -362,7 +368,7 @@ describe('connector metadata doors: an authored connector keeps no credential in it('an author\'s edit of a served URL is stored exactly as written', async () => { const served = authorable((await read(admin, OAUTH_ROW)).item); const edited = { ...served, auth: { ...served.auth, tokenUrl: 'https://auth.vendor.example.com/oauth2/token' } }; - const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${OAUTH_ROW}`, edited); + const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${OAUTH_ROW}?package=${PAIR_PKG}`, edited); expect(res.status, await res.clone().text()).toBe(200); const atRest = bodyOf((await stored(OAUTH_ROW))[0]); expect(atRest.auth.tokenUrl).toBe('https://auth.vendor.example.com/oauth2/token'); @@ -376,7 +382,7 @@ describe('connector metadata doors: an authored connector keeps no credential in .toEqual({ maxAttempts: 2, secret: PLACEHOLDERS.nested }); const served = authorable((await read(admin, RETRY_EMPTY)).item); expect(served.retryConfig).toEqual({ maxAttempts: 2 }); - const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${RETRY_EMPTY}`, { ...served, retryConfig: {} }); + const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${RETRY_EMPTY}?package=${PAIR_PKG}`, { ...served, retryConfig: {} }); const text = await res.text(); expect(res.status, text.slice(0, 300)).toBe(200); // The save names the key it did not carry forward. @@ -392,7 +398,7 @@ describe('connector metadata doors: an authored connector keeps no credential in it('a save of the served form replaces the stored `retryConfig` whole too', async () => { const served = authorable((await read(admin, RETRY_ROW)).item); - const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${RETRY_ROW}`, { ...served, label: 'CUN retry (edited)' }); + const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${RETRY_ROW}?package=${PAIR_PKG}`, { ...served, label: 'CUN retry (edited)' }); expect(res.status, await res.clone().text()).toBe(200); const atRest = bodyOf((await stored(RETRY_ROW))[0]); expect(atRest.label).toBe('CUN retry (edited)'); @@ -402,7 +408,7 @@ describe('connector metadata doors: an authored connector keeps no credential in it('CONTROL: a save that leaves `retryConfig` out removes it with its stored keys, as before', async () => { const { retryConfig: _removed, ...withoutRetry } = authorable((await read(admin, RETRY_OMIT)).item); - const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${RETRY_OMIT}`, withoutRetry); + const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${RETRY_OMIT}?package=${PAIR_PKG}`, withoutRetry); expect(res.status, await res.clone().text()).toBe(200); const atRest = bodyOf((await stored(RETRY_OMIT))[0]); expect(atRest).not.toHaveProperty('retryConfig'); @@ -412,7 +418,7 @@ describe('connector metadata doors: an authored connector keeps no credential in it('CONTROL: a `retryConfig` stored as a non-object is withheld whole and still carried forward by a save that leaves it out', async () => { const served = authorable((await read(admin, RETRY_MALFORMED)).item); expect(served).not.toHaveProperty('retryConfig'); - const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${RETRY_MALFORMED}`, { ...served, label: 'CUN retry malformed (edited)' }); + const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${RETRY_MALFORMED}?package=${PAIR_PKG}`, { ...served, label: 'CUN retry malformed (edited)' }); expect(res.status, await res.clone().text()).toBe(200); const atRest = bodyOf((await stored(RETRY_MALFORMED))[0]); expect(atRest.label).toBe('CUN retry malformed (edited)'); @@ -431,7 +437,7 @@ describe('connector metadata doors: an authored connector keeps no credential in beforeAll(async () => { // A row stored before the refusal: a clean save, then the system context // writes the credential parts over it. - const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${TRIM_ROW}`, oauth2(TRIM_ROW)); + const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${TRIM_ROW}?package=${PAIR_PKG}`, oauth2(TRIM_ROW)); expect(res.status, await res.clone().text()).toBe(200); const [row] = await stored(TRIM_ROW); const seeded = { @@ -468,7 +474,7 @@ describe('connector metadata doors: an authored connector keeps no credential in }); it('CONTROL: a credential-free URL behind a leading space, and a string that is not a URL holding none, save; the instance materializes ready and dispatches', async () => { - const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${TRIM_CONTROL}`, instance(TRIM_CONTROL, { + const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${TRIM_CONTROL}?package=${PAIR_PKG}`, instance(TRIM_CONTROL, { providerConfig: { baseUrl: ` ${upstreamUrl}/v1?region=eu`, note: 'sandbox ?region=eu&token=' }, })); expect(put.status, await put.clone().text()).toBe(200); @@ -484,7 +490,7 @@ describe('connector metadata doors: an authored connector keeps no credential in it('CONTROL: an ordinary query parameter with a tab inside its name saves and dispatches as a URL parser reads it; a scheme-relative URL with no userinfo saves', async () => { const name = 'cun_trim_tab_control'; - const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${name}`, instance(name, { + const put = await stack.apiAs(admin, 'PUT', `/meta/connector/${name}?package=${PAIR_PKG}`, instance(name, { providerConfig: { baseUrl: `${upstreamUrl}/v1?reg${TAB}ion=eu` }, })); expect(put.status, await put.clone().text()).toBe(200); @@ -497,7 +503,7 @@ describe('connector metadata doors: an authored connector keeps no credential in expect(received.length).toBe(before + 1); expect(received[received.length - 1]).toBe('/v1/probe?region=eu'); // Saved disabled: the pin is the door's answer, not a materialization. - const relative = await stack.apiAs(admin, 'PUT', '/meta/connector/cun_trim_relative_control', instance('cun_trim_relative_control', { + const relative = await stack.apiAs(admin, 'PUT', `/meta/connector/cun_trim_relative_control?package=${PAIR_PKG}`, instance('cun_trim_relative_control', { enabled: false, providerConfig: { baseUrl: '//api.vendor.example.com/v1' }, })); @@ -518,7 +524,7 @@ describe('connector metadata doors: an authored connector keeps no credential in it('CARRY-FORWARD: a save of the served form keeps each stored value', async () => { const served = authorable((await read(admin, TRIM_ROW)).item); - const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${TRIM_ROW}`, { ...served, label: 'CUN trim (edited)' }); + const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${TRIM_ROW}?package=${PAIR_PKG}`, { ...served, label: 'CUN trim (edited)' }); expect(res.status, await res.clone().text()).toBe(200); const atRest = bodyOf((await stored(TRIM_ROW))[0]); expect(atRest.label).toBe('CUN trim (edited)'); diff --git a/packages/qa/dogfood/test/dashboard-designer-roundtrip.dogfood.test.ts b/packages/qa/dogfood/test/dashboard-designer-roundtrip.dogfood.test.ts index 27abc51cf07..4ece0e7d720 100644 --- a/packages/qa/dogfood/test/dashboard-designer-roundtrip.dogfood.test.ts +++ b/packages/qa/dogfood/test/dashboard-designer-roundtrip.dogfood.test.ts @@ -19,6 +19,10 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.showcase.custom'; // Designer-shaped: each widget binds a dataset + dimensions/values but carries // NO `layout` — exactly what the Studio designer writes. `columns` is set, as @@ -44,6 +48,8 @@ describe('dogfood: a Studio-designer-shaped (layout-less) dashboard saves + publ beforeAll(async () => { stack = await bootShowcase(); token = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, token, 'com.example.showcase'); }, 90_000); afterAll(async () => { @@ -51,14 +57,14 @@ describe('dogfood: a Studio-designer-shaped (layout-less) dashboard saves + publ }); it('saves the layout-less draft (was 422 before DashboardWidget.layout became optional)', async () => { - const res = await stack.apiAs(token, 'PUT', `/meta/dashboard/${DASH}?mode=draft`, designerDashboard); + const res = await stack.apiAs(token, 'PUT', `/meta/dashboard/${DASH}?mode=draft&package=${PAIR_PKG}`, designerDashboard); // The regression: a widget with no `layout` made this 422 // ("widgets: Invalid type: expected object, received undefined"). expect(res.status).toBe(200); }); it('publishes the saved draft to live (Publish was disabled while the draft could not save)', async () => { - const res = await stack.apiAs(token, 'POST', `/meta/dashboard/${DASH}/publish`, {}); + const res = await stack.apiAs(token, 'POST', `/meta/dashboard/${DASH}/publish?package=${PAIR_PKG}`, {}); expect(res.status).toBe(200); }); diff --git a/packages/qa/dogfood/test/datasource-meta-door-reaches-admin-door.dogfood.test.ts b/packages/qa/dogfood/test/datasource-meta-door-reaches-admin-door.dogfood.test.ts index 2828230c38e..d92b67c762b 100644 --- a/packages/qa/dogfood/test/datasource-meta-door-reaches-admin-door.dogfood.test.ts +++ b/packages/qa/dogfood/test/datasource-meta-door-reaches-admin-door.dogfood.test.ts @@ -45,6 +45,10 @@ import { bootShowcase } from './showcase-boot.js'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.showcase.custom'; /** The showcase's code-defined datasource. */ const EXTERNAL = 'showcase_external'; @@ -96,6 +100,8 @@ describe('[#21923] the metadata door and the admin door agree on a runtime datas const boot = async () => { stack = await bootShowcase({ databaseFile: join(dir, 'showcase.db'), extraPlugins: [routes()] }); token = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, token, 'com.example.showcase'); }; const restart = async () => { await stack.stop(); @@ -163,9 +169,9 @@ describe('[#21923] the metadata door and the admin door agree on a runtime datas }); it('a datasource the metadata door creates is listed and editable through the admin door in the same boot, with a live pool', async () => { - const none = await call('PUT', `/meta/datasource/${META_NONE}`, sqliteBody(META_NONE, 'Meta None 21923')); + const none = await call('PUT', `/meta/datasource/${META_NONE}?package=${PAIR_PKG}`, sqliteBody(META_NONE, 'Meta None 21923')); expect(none.status, JSON.stringify(none.json)).toBe(200); - const code = await call('PUT', `/meta/datasource/${META_CODE}`, sqliteBody(META_CODE, 'Meta Code 21923', { origin: 'code' })); + const code = await call('PUT', `/meta/datasource/${META_CODE}?package=${PAIR_PKG}`, sqliteBody(META_CODE, 'Meta Code 21923', { origin: 'code' })); expect(code.status, JSON.stringify(code.json)).toBe(200); expect(await storedRows(META_NONE)).toHaveLength(1); // The stored body really asserts `origin: 'code'` — the record's own claim. @@ -218,7 +224,7 @@ describe('[#21923] the metadata door and the admin door agree on a runtime datas }, 180_000); it('the metadata door edits and removes an admin-edited datasource, and the admin door follows in the same boot', async () => { - const put = await call('PUT', `/meta/datasource/${META_NONE}`, { ...(await servedBody(META_NONE)), label: 'Meta None 21923 (meta edit)' }); + const put = await call('PUT', `/meta/datasource/${META_NONE}?package=${PAIR_PKG}`, { ...(await servedBody(META_NONE)), label: 'Meta None 21923 (meta edit)' }); expect(put.status, JSON.stringify(put.json)).toBe(200); expect(await adminEntry(META_NONE)).toMatchObject({ origin: 'runtime', label: 'Meta None 21923 (meta edit)' }); diff --git a/packages/qa/dogfood/test/datasource-meta-door-url-credential-trimmed.dogfood.test.ts b/packages/qa/dogfood/test/datasource-meta-door-url-credential-trimmed.dogfood.test.ts index 5f89ad93809..4c1a5682121 100644 --- a/packages/qa/dogfood/test/datasource-meta-door-url-credential-trimmed.dogfood.test.ts +++ b/packages/qa/dogfood/test/datasource-meta-door-url-credential-trimmed.dogfood.test.ts @@ -26,6 +26,9 @@ import { bootStack, type VerifyStack } from '@objectstack/verify'; import { defineStack } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.dogfood.ds-trim-38174'; + const fixture = defineStack({ manifest: { id: 'com.dogfood.datasource-url-credential-trimmed', namespace: 'duct', version: '0.0.0', type: 'app', @@ -74,15 +77,18 @@ describe('datasource metadata door: a driver config URL is judged after trimming beforeAll(async () => { stack = await bootStack(fixture); token = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1). + const created38174 = await stack.apiAs(token, 'POST', '/packages', { id: PAIR_PKG, name: 'Dogfood authoring', version: '1.0.0', type: 'app' }); + expect(created38174.status, await created38174.clone().text()).toBe(201); ql = await stack.kernel.getServiceAsync('objectql'); // A row stored before the refusal: a clean save, then the system context // writes the password over it. - const clean = await call('PUT', `/meta/datasource/${SEEDED}`, body(SEEDED, 'mysql', ' mysql://svc@db.internal:3306/app')); + const clean = await call('PUT', `/meta/datasource/${SEEDED}?package=${PAIR_PKG}`, body(SEEDED, 'mysql', ' mysql://svc@db.internal:3306/app')); expect(clean.status, clean.text).toBe(200); const [row] = await storedRows(SEEDED); const seeded = body(SEEDED, 'mysql', ` mysql://svc:${PLACEHOLDER}@db.internal:3306/app${LF}`); await ql.update('sys_metadata', { id: row!.id, metadata: JSON.stringify(seeded) }, { context: SYS }); - const cleanPg = await call('PUT', `/meta/datasource/${SEEDED_PG}`, body(SEEDED_PG, 'postgres', 'postgresql://svc@db.internal:5432/app')); + const cleanPg = await call('PUT', `/meta/datasource/${SEEDED_PG}?package=${PAIR_PKG}`, body(SEEDED_PG, 'postgres', 'postgresql://svc@db.internal:5432/app')); expect(cleanPg.status, cleanPg.text).toBe(200); const [pgRow] = await storedRows(SEEDED_PG); await ql.update('sys_metadata', { id: pgRow!.id, metadata: JSON.stringify(body(SEEDED_PG, 'postgres', storedPgUrl())) }, { context: SYS }); @@ -99,7 +105,7 @@ describe('datasource metadata door: a driver config URL is judged after trimming ['a mongo `config.url` between a leading space and a trailing newline', 'duct_w_mongo', 'mongodb', ` mongodb://svc:${PLACEHOLDER}@db.internal:27017/app${LF}`], ['a postgres `config.url` with a tab inside its scheme', 'duct_w_pg_scheme_tab', 'postgres', `postgre${TAB}sql://svc:${PLACEHOLDER}@db.internal:5432/app`], ])('%s', async (_label, name, driver, url) => { - const answer = await call('PUT', `/meta/datasource/${name}`, body(name, driver, url)); + const answer = await call('PUT', `/meta/datasource/${name}?package=${PAIR_PKG}`, body(name, driver, url)); expect(answer.status, answer.text.slice(0, 300)).toBe(422); expect(answer.json.code ?? answer.json.error?.code).toBe('INVALID_METADATA'); const issues: any[] = answer.json.issues ?? answer.json.error?.issues ?? []; @@ -112,7 +118,7 @@ describe('datasource metadata door: a driver config URL is judged after trimming it('WRITE: a postgres `config.url` whose `password` query parameter holds a tab inside its name is refused, and nothing is stored', async () => { const name = 'duct_w_pg_key_tab'; - const answer = await call('PUT', `/meta/datasource/${name}`, body(name, 'postgres', `postgresql://svc@db.internal:5432/app?pass${TAB}word=${PLACEHOLDER}`)); + const answer = await call('PUT', `/meta/datasource/${name}?package=${PAIR_PKG}`, body(name, 'postgres', `postgresql://svc@db.internal:5432/app?pass${TAB}word=${PLACEHOLDER}`)); expect(answer.status, answer.text.slice(0, 300)).toBe(422); expect(answer.json.code ?? answer.json.error?.code).toBe('INVALID_METADATA'); const issues: any[] = answer.json.issues ?? answer.json.error?.issues ?? []; @@ -129,7 +135,7 @@ describe('datasource metadata door: a driver config URL is judged after trimming ['a postgres bare username with a tab inside the scheme', 'duct_c_pg_scheme_tab', 'postgres', `postgre${TAB}sql://svc@db.internal:5432/app`], ['a postgres ordinary query parameter with a tab inside its name', 'duct_c_pg_key_tab', 'postgres', `postgresql://svc@db.internal:5432/app?connect${TAB}_timeout=10`], ])('%s', async (_label, name, driver, url) => { - const answer = await call('PUT', `/meta/datasource/${name}`, body(name, driver, url)); + const answer = await call('PUT', `/meta/datasource/${name}?package=${PAIR_PKG}`, body(name, driver, url)); expect(answer.status, answer.text.slice(0, 300)).toBe(200); expect((await storedBody(name)).config.url).toBe(url); }); diff --git a/packages/qa/dogfood/test/datasource-restore-code-wins.dogfood.test.ts b/packages/qa/dogfood/test/datasource-restore-code-wins.dogfood.test.ts index 2cbb9952651..99b9e1ed511 100644 --- a/packages/qa/dogfood/test/datasource-restore-code-wins.dogfood.test.ts +++ b/packages/qa/dogfood/test/datasource-restore-code-wins.dogfood.test.ts @@ -52,6 +52,7 @@ import showcaseStack, { onEnable } from '@objectstack/example-showcase'; import { registerDatasourceAdminRoutes } from '@objectstack/service-datasource'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -201,7 +202,9 @@ describe('[#21922 / #21944] a stored datasource row never displaces a code datas }); it('control: a runtime datasource still saves through the /meta door', async () => { - const saved = await call('PUT', `/meta/datasource/${META_RUNTIME}`, { + // [#38174] A new item is created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + const pkg = await ensurePair(stack, token, 'com.example.showcase'); + const saved = await call('PUT', `/meta/datasource/${META_RUNTIME}?package=${pkg}`, { name: META_RUNTIME, label: 'Meta Runtime 21944', driver: 'sqlite', config: { filename: join(dir, 'meta-rt.db') }, }); expect(saved.status, JSON.stringify(saved.json)).toBe(200); diff --git a/packages/qa/dogfood/test/datasource-restore-environment-rows.dogfood.test.ts b/packages/qa/dogfood/test/datasource-restore-environment-rows.dogfood.test.ts index 6f55e45caff..54900ddca05 100644 --- a/packages/qa/dogfood/test/datasource-restore-environment-rows.dogfood.test.ts +++ b/packages/qa/dogfood/test/datasource-restore-environment-rows.dogfood.test.ts @@ -21,6 +21,10 @@ import { bootShowcase } from './showcase-boot.js'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.showcase.custom'; /** A datasource name with no stored row, written through the doors below. */ const FRESH = 'dogfood_fresh_ds_22835'; @@ -51,6 +55,8 @@ describe('[#22835] the datasource-admin plugin reads environment rows only (show const boot = async () => { stack = await bootShowcase({ databaseFile: join(dir, 'showcase.db'), extraPlugins: [routes()] }); token = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, token, 'com.example.showcase'); }; const ql = () => stack.kernel.getService('objectql') as { find(object: string, query: unknown): Promise; @@ -140,7 +146,7 @@ describe('[#22835] the datasource-admin plugin reads environment rows only (show expect(await environmentRows(FRESH)).toHaveLength(0); // A `/meta` save under the name: the admin door serves the saved body. - const saved = await call('PUT', `/meta/datasource/${FRESH}`, { + const saved = await call('PUT', `/meta/datasource/${FRESH}?package=${PAIR_PKG}`, { name: FRESH, label: 'Meta save 22835', driver: 'sqlite', config: { filename: join(dir, 'meta.db') }, }); expect(saved.status, JSON.stringify(saved.json)).toBe(200); diff --git a/packages/qa/dogfood/test/delegation-of-duty.dogfood.test.ts b/packages/qa/dogfood/test/delegation-of-duty.dogfood.test.ts index f239c6e4986..e39f4115c3c 100644 --- a/packages/qa/dogfood/test/delegation-of-duty.dogfood.test.ts +++ b/packages/qa/dogfood/test/delegation-of-duty.dogfood.test.ts @@ -20,6 +20,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; import { PermissionSetSchema } from '@objectstack/spec/security'; import { resolveAuthzContext } from '@objectstack/core'; @@ -66,6 +67,8 @@ describe('delegation of duty (ADR-0091 D3) — end to end', () => { }), }); const adminToken = await stack.signIn(); + // [#38174] A new item is created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + const pkg = await ensurePair(stack, adminToken, 'com.example.showcase'); delegatorToken = await stack.signUp(DELEGATOR); await stack.signUp(DELEGATE); ql = await stack.kernel.getServiceAsync('objectql'); @@ -88,7 +91,7 @@ describe('delegation of duty (ADR-0091 D3) — end to end', () => { ['vacation_approver', 'Vacation Approver', true], ['locked_duty', 'Locked Duty', false], ] as const) { - const saved = await stack.apiAs(adminToken, 'PUT', `/meta/position/${name}`, { name, label, delegatable }); + const saved = await stack.apiAs(adminToken, 'PUT', `/meta/position/${name}?package=${pkg}`, { name, label, delegatable }); expect(saved.status, await saved.clone().text().catch(() => '')).toBe(200); } await ql.insert('sys_user_position', { id: 'hold_boss', user_id: delegatorId, position: 'vacation_approver', organization_id: orgId }, SYS); diff --git a/packages/qa/dogfood/test/external-federation-read-capability.dogfood.test.ts b/packages/qa/dogfood/test/external-federation-read-capability.dogfood.test.ts index b1e7525cda9..94b94c1668a 100644 --- a/packages/qa/dogfood/test/external-federation-read-capability.dogfood.test.ts +++ b/packages/qa/dogfood/test/external-federation-read-capability.dogfood.test.ts @@ -35,6 +35,10 @@ import { onEnable } from '@objectstack/example-showcase'; import { ExternalDatasourceServicePlugin } from '@objectstack/service-datasource'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.showcase.custom'; const SYS = { isSystem: true } as const; @@ -83,6 +87,8 @@ describe('seeing a datasource\'s remote structure needs the read capability on e await onEnable({ logger: { info() {}, warn() {} } } as never); stack = await bootShowcase({ extraPlugins: [new ExternalDatasourceServicePlugin()] }); admin = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, admin, 'com.example.showcase'); const ql: any = await stack.kernel.getServiceAsync('objectql'); // Authored at runtime, the way an administrator authors a set. @@ -90,7 +96,7 @@ describe('seeing a datasource\'s remote structure needs the read capability on e [WRITE_ONLY_SET, ['manage_metadata']], [BOTH_SET, ['manage_metadata', 'manage_platform_settings']], ] as const) { - const saved = await stack.apiAs(admin, 'PUT', `/meta/permission/${name}`, { + const saved = await stack.apiAs(admin, 'PUT', `/meta/permission/${name}?package=${PAIR_PKG}`, { name, label: name, objects: {}, systemPermissions: [...systemPermissions], }); expect(saved.status, await saved.clone().text()).toBe(200); diff --git a/packages/qa/dogfood/test/external-import-code-datasource-namespace.dogfood.test.ts b/packages/qa/dogfood/test/external-import-code-datasource-namespace.dogfood.test.ts index 5e3131fe3e4..fd91c2ef0eb 100644 --- a/packages/qa/dogfood/test/external-import-code-datasource-namespace.dogfood.test.ts +++ b/packages/qa/dogfood/test/external-import-code-datasource-namespace.dogfood.test.ts @@ -201,14 +201,26 @@ describe('an import over a code-defined datasource is held to its package\'s nam // An object imported before the placement changed: package-less, under the // base-namespace name, bound to the same remote table. It is not moved or // renamed, and importing the table again makes the new object beside it. - const legacy = await call('PUT', `/meta/object/${LEGACY}`, { + // [#38174] No door creates a package-less object any more (ADR-0070 D1): + // the legacy row is seeded directly, then saved in place, which stays open. + const legacyBody = { name: LEGACY, label: 'Legacy Customers', datasource: DATASOURCE, external: { remoteName: 'customers' }, fields: { name: { type: 'text', label: 'Name' } }, sharingModel: 'public_read', - }); + }; + const ql = (await stack.kernel.getServiceAsync('objectql')) as unknown as { + insert(object: string, data: Record, options?: unknown): Promise; + }; + const now = new Date().toISOString(); + await ql.insert('sys_metadata', { + type: 'object', name: LEGACY, package_id: null, scope: 'platform', + state: 'active', version: 1, checksum: null, created_at: now, updated_at: now, + metadata: JSON.stringify(legacyBody), + }, { context: { isSystem: true, positions: [], permissions: [] } }); + const legacy = await call('PUT', `/meta/object/${LEGACY}`, legacyBody); expect(legacy.status, JSON.stringify(legacy.json)).toBe(200); const imported = await call('POST', `${ext}/tables/customers/import`, {}); diff --git a/packages/qa/dogfood/test/external-import-walled-catalog-refusal.dogfood.test.ts b/packages/qa/dogfood/test/external-import-walled-catalog-refusal.dogfood.test.ts index b0423f48fa0..39591fdaec5 100644 --- a/packages/qa/dogfood/test/external-import-walled-catalog-refusal.dogfood.test.ts +++ b/packages/qa/dogfood/test/external-import-walled-catalog-refusal.dogfood.test.ts @@ -186,8 +186,9 @@ async function boot(posture: 'group' | 'single'): Promise { h.userA = String((await ql.findOne('sys_user', { where: { email }, context: SYS }))?.id); // The operator creates the customization package an import over this // datasource lands in, and authors the set A holds (inside org A under a wall). - await ensurePair(stack, operator, BASE); - const saved = await stack.apiAs(operator, 'PUT', `/meta/permission/${IMPORTER_SET}`, { + // [#38174] The set is created into that writable package (ADR-0070 D1). + const pair = await ensurePair(stack, operator, BASE); + const saved = await stack.apiAs(operator, 'PUT', `/meta/permission/${IMPORTER_SET}?package=${pair}`, { name: IMPORTER_SET, label: IMPORTER_SET, objects: {}, systemPermissions: [...IMPORTER_CAPABILITIES], }); expect(saved.status, await saved.clone().text()).toBe(200); diff --git a/packages/qa/dogfood/test/external-validate-sees-runtime-save.dogfood.test.ts b/packages/qa/dogfood/test/external-validate-sees-runtime-save.dogfood.test.ts index 3069012555f..a738eb55c72 100644 --- a/packages/qa/dogfood/test/external-validate-sees-runtime-save.dogfood.test.ts +++ b/packages/qa/dogfood/test/external-validate-sees-runtime-save.dogfood.test.ts @@ -37,6 +37,7 @@ import showcaseStack, { onEnable } from '@objectstack/example-showcase'; import { ExternalDatasourceServicePlugin } from '@objectstack/service-datasource'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -46,7 +47,8 @@ const DATASOURCE = 'showcase_external'; /** The two objects the showcase binds to it in code (`data/objects/external/`). */ const CODE_DEFINED = ['showcase_ext_customer', 'showcase_ext_order']; /** Saved at runtime through the metadata door, bound to the remote `customers` table. */ -const SAVED = 'dogfood_ext_cust_21842'; +// [#38174] Created into the showcase's writable `.custom` pair (ADR-0070 D1), so it carries the pair's prefix. +const SAVED = 'showcase_custom_dogfood_ext_cust_21842'; /** A column the saved object declares and the remote `customers` table does not have. */ const MISSING = 'loyalty_tier'; /** Imported at runtime from the remote `orders` table. */ @@ -113,7 +115,8 @@ describe('external validate lists a federated object saved at runtime, with no r }); it('lists an object saved through PUT /meta/object/:name with a real verdict, and still the code-defined ones', async () => { - const saved = await call('PUT', `/meta/object/${SAVED}`, { + const pair = await ensurePair(stack, token, 'com.example.showcase'); + const saved = await call('PUT', `/meta/object/${SAVED}?package=${pair}`, { name: SAVED, label: 'Dogfood External Customer', sharingModel: 'public_read_write', diff --git a/packages/qa/dogfood/test/flow-credential-channel.dogfood.test.ts b/packages/qa/dogfood/test/flow-credential-channel.dogfood.test.ts index 0bc08965e20..764acbcf107 100644 --- a/packages/qa/dogfood/test/flow-credential-channel.dogfood.test.ts +++ b/packages/qa/dogfood/test/flow-credential-channel.dogfood.test.ts @@ -49,6 +49,10 @@ import { stripReadDecorations } from '@objectstack/spec/kernel'; import { FlowCredentialChannel } from '@objectstack/service-automation'; import { ApiTrigger } from '@objectstack/trigger-api'; import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.crm.custom'; const FLOW = 'zz_channel_hook'; const LEGACY = 'zz_channel_legacy'; @@ -109,6 +113,8 @@ describe('[#20790] flow credentials live in the write-only channel, not the stor beforeAll(async () => { stack = await bootStack(crmStack as never, { automation: true }); token = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the CRM's `.custom` pair. + await ensurePair(stack, token, 'com.example.crm'); ql = await stack.kernel.getServiceAsync('objectql'); protocol = await stack.kernel.getServiceAsync('protocol'); automation = await stack.kernel.getServiceAsync('automation'); @@ -150,7 +156,7 @@ describe('[#20790] flow credentials live in the write-only channel, not the stor } it('1 — a credential saved through the metadata door is in no read surface; the channel holds it masked', async () => { - const put = await stack.apiAs(token, 'PUT', `/meta/flow/${FLOW}`, inbound(FLOW, { hook: HOOK_V1, sign: SIGN_V1 })); + const put = await stack.apiAs(token, 'PUT', `/meta/flow/${FLOW}?package=${PAIR_PKG}`, inbound(FLOW, { hook: HOOK_V1, sign: SIGN_V1 })); expect(put.status).toBe(200); const active = await stored(FLOW); @@ -194,7 +200,7 @@ describe('[#20790] flow credentials live in the write-only channel, not the stor expect(await post(FLOW, 'not-the-secret')).toBe(401); // The served (withheld) form saved back: the channel keeps the secret. - const republish = await stack.apiAs(token, 'PUT', `/meta/flow/${FLOW}`, inbound(FLOW, {}, 'Edited')); + const republish = await stack.apiAs(token, 'PUT', `/meta/flow/${FLOW}?package=${PAIR_PKG}`, inbound(FLOW, {}, 'Edited')); expect(republish.status).toBe(200); expect(hasAny(await stored(FLOW), ALL)).toBe(false); await arm(FLOW); @@ -202,7 +208,7 @@ describe('[#20790] flow credentials live in the write-only channel, not the stor }); it('3 — an explicit rotation replaces it, on the next post with no re-arm', async () => { - const rotate = await stack.apiAs(token, 'PUT', `/meta/flow/${FLOW}`, inbound(FLOW, { hook: HOOK_V2 }, 'Rotated')); + const rotate = await stack.apiAs(token, 'PUT', `/meta/flow/${FLOW}?package=${PAIR_PKG}`, inbound(FLOW, { hook: HOOK_V2 }, 'Rotated')); expect(rotate.status).toBe(200); expect(hasAny(await stored(FLOW), ALL)).toBe(false); expect(await post(FLOW, HOOK_V2)).toBe(202); @@ -210,7 +216,7 @@ describe('[#20790] flow credentials live in the write-only channel, not the stor }); it('4 — a draft save never rotates the live hook; publishing the draft promotes it', async () => { - const draft = await stack.apiAs(token, 'PUT', `/meta/flow/${FLOW}?mode=draft`, inbound(FLOW, { hook: HOOK_DRAFT }, 'Drafted')); + const draft = await stack.apiAs(token, 'PUT', `/meta/flow/${FLOW}?mode=draft&package=${PAIR_PKG}`, inbound(FLOW, { hook: HOOK_DRAFT }, 'Drafted')); expect(draft.status).toBe(200); expect(hasAny(await stored(FLOW), ALL)).toBe(false); // The live hook still verifies with the published secret. @@ -234,7 +240,7 @@ describe('[#20790] flow credentials live in the write-only channel, not the stor expect(flowChannel, 'the automation plugin registered the flow channel').toBeTruthy(); channels.delete('flow'); try { - const legacy = await stack.apiAs(token, 'PUT', `/meta/flow/${LEGACY}`, inbound(LEGACY, { hook: LEGACY_V1 })); + const legacy = await stack.apiAs(token, 'PUT', `/meta/flow/${LEGACY}?package=${PAIR_PKG}`, inbound(LEGACY, { hook: LEGACY_V1 })); expect(legacy.status).toBe(200); } finally { channels.set('flow', flowChannel); @@ -261,7 +267,7 @@ describe('[#20790] flow credentials live in the write-only channel, not the stor expect(await post(LEGACY, LEGACY_V1)).toBe(202); // Rotate, then roll back to version 1 — the version that held the old literal. - const rotate = await stack.apiAs(token, 'PUT', `/meta/flow/${LEGACY}`, inbound(LEGACY, { hook: LEGACY_V2 }, 'Rotated')); + const rotate = await stack.apiAs(token, 'PUT', `/meta/flow/${LEGACY}?package=${PAIR_PKG}`, inbound(LEGACY, { hook: LEGACY_V2 }, 'Rotated')); expect(rotate.status).toBe(200); const before = (await stored(LEGACY, 'sys_metadata_history')).length; const rollback = await stack.apiAs(token, 'POST', `/meta/flow/${LEGACY}/rollback`, { toVersion: 1 }); @@ -315,7 +321,7 @@ describe('[#20790] flow credentials live in the write-only channel, not the stor const provider = ql.cryptoProvider; ql.cryptoProvider = undefined; try { - const res = await stack.apiAs(token, 'PUT', '/meta/flow/zz_channel_noprov', inbound('zz_channel_noprov', { hook: NO_PROVIDER })); + const res = await stack.apiAs(token, 'PUT', `/meta/flow/zz_channel_noprov?package=${PAIR_PKG}`, inbound('zz_channel_noprov', { hook: NO_PROVIDER })); expect(res.status).toBe(503); const text = await res.text(); // The metadata door's error body names the code at its top level. @@ -334,7 +340,7 @@ describe('[#20790] flow credentials live in the write-only channel, not the stor expect(del.status).toBe(200); expect(await channelRows(FLOW)).toEqual([]); // Recreated in the withheld form: nothing is held, so the publish gate refuses it. - const again = await stack.apiAs(token, 'PUT', `/meta/flow/${FLOW}`, inbound(FLOW)); + const again = await stack.apiAs(token, 'PUT', `/meta/flow/${FLOW}?package=${PAIR_PKG}`, inbound(FLOW)); expect(again.status).toBe(422); expect(await channelRows(FLOW)).toEqual([]); }); diff --git a/packages/qa/dogfood/test/flow-node-config-values-at-registration.dogfood.test.ts b/packages/qa/dogfood/test/flow-node-config-values-at-registration.dogfood.test.ts index 24003683e83..3250e228101 100644 --- a/packages/qa/dogfood/test/flow-node-config-values-at-registration.dogfood.test.ts +++ b/packages/qa/dogfood/test/flow-node-config-values-at-registration.dogfood.test.ts @@ -2,8 +2,10 @@ // // A flow whose node config breaks the node's contract is refused where it // registers — through both registration doors an operator has: the package a -// stack ships (package load) and the admin write door (`POST /automation`) — -// and a flow refused at load is not left registered. +// stack ships (package load) and the admin write door (`POST /automation`, +// which #38174 retired: a new flow is now created through +// `PUT /meta/flow/NAME?package=PKG`, into a writable package) — and a flow +// refused at load is not left registered. // // ## What was broken // @@ -33,14 +35,15 @@ // - package load, a plugin node type whose executor registers after the boot // pull: an undeclared config key is refused by the `kernel:ready` bind, and // the flow is not left registered; its valid sibling is; -// - the admin door: both approval refusals answer `400 VALIDATION_FAILED` +// - the admin door: both approval refusals answer `422 INVALID_METADATA` // located at the config path, and nothing is registered under either name; // - the admin door, the control: a valid escalation registers; // - a flow with no `start` node, which can never run: the admin door answers -// `400 VALIDATION_FAILED` naming the missing node, and nothing registers; +// `422 INVALID_METADATA` naming the missing node, and nothing registers; // at package load the boot completes, refuses the flow and names it; // - a `notify` node naming a channel no plugin registers: the admin door -// answers `400 VALIDATION_FAILED` naming the node and the channel at its +// answers `422 INVALID_METADATA` (rule `flow-notify-channel-unregistered`) +// naming the node and the channel at its // config path and listing the channels the composition registers, and // nothing registers; the control, naming registered channels, registers. // @@ -77,6 +80,13 @@ const PACKAGED_NO_START = 'esc_value_packaged_no_start'; const DOOR_NO_START = 'esc_value_door_no_start'; const DOOR_UNKNOWN_CHANNEL = 'esc_value_door_unknown_channel'; const DOOR_KNOWN_CHANNELS = 'esc_value_door_known_channels'; +/** + * [#38174] The writable package the admin door creates flows in (a package-less + * create is refused, ADR-0070 D1). It declares the fixture package, whose + * object the gated flows trigger on. + */ +const DOOR_PACKAGE = 'com.dogfood.esc-value-door'; +const FIXTURE_PACKAGE = 'com.dogfood.escalation-values'; /** A flow run by hand whose one step is a `notify` node naming `channels`. */ function notifyFlow(name: string, channels: unknown) { @@ -205,7 +215,7 @@ function stampFlow(name: string, config: Record) { const fixtureStack = defineStack( { manifest: { - id: 'com.dogfood.escalation-values', + id: FIXTURE_PACKAGE, namespace: 'esc_value', version: '0.0.0', type: 'app', @@ -246,6 +256,14 @@ interface DispatcherEnvelope { }; } +/** [#38174] The `/meta` door's refusal: `{ error: , code, issues }`. */ +interface MetaRefusal { + error?: string; + code?: string; + issues?: Array<{ path?: string; rule?: string; message?: string; hint?: string }>; +} +const metaRefusal = (json: unknown) => json as MetaRefusal; + describe('a flow node config its contract refuses is refused at registration, and not left registered at load', () => { let stack: VerifyStack; let token: string; @@ -282,8 +300,15 @@ describe('a flow node config its contract refuses is refused at registration, an bootOutput = lines.join(''); } token = await stack.signIn(); + const pkg = await stack.apiAs(token, 'POST', '/packages', { + id: DOOR_PACKAGE, name: 'Escalation door', version: '0.0.0', type: 'app', dependencies: { [FIXTURE_PACKAGE]: '*' }, + }); + expect(pkg.status, await pkg.clone().text()).toBe(201); }, 120_000); + /** [#38174] The admin door: a new flow is created through `/meta`, into {@link DOOR_PACKAGE}. */ + const create = (name: string, body: unknown) => call('PUT', `/meta/flow/${name}?package=${DOOR_PACKAGE}`, body); + afterAll(async () => { await stack?.stop(); }); @@ -334,29 +359,30 @@ describe('a flow node config its contract refuses is refused at registration, an expect(sibling.status, JSON.stringify(sibling.json)).toBe(200); }); - it('the admin door: both approval refusals answer 400 VALIDATION_FAILED at the config path, and nothing registers', async () => { + it('the admin door: both approval refusals answer 422 INVALID_METADATA at the config path, and nothing registers', async () => { for (const [name, escalation, path] of [ [DOOR_SUB_HOUR, SUB_HOUR, SUB_HOUR_PATH], [DOOR_UNKNOWN_KEY, UNKNOWN_KEY, UNKNOWN_KEY_PATH], ] as const) { - const refused = await call('POST', '/automation', gatedFlow(name, escalation)); - expect(refused.status, JSON.stringify(refused.json)).toBe(400); - expect(refused.json.error?.code).toBe('VALIDATION_FAILED'); - const fields = refused.json.error?.details?.fields ?? []; - expect(fields.map((f) => f.field), JSON.stringify(refused.json)).toContain(path); + const refused = await create(name, gatedFlow(name, escalation)); + expect(refused.status, JSON.stringify(refused.json)).toBe(422); + const body = metaRefusal(refused.json); + expect(body.code).toBe('INVALID_METADATA'); + expect((body.issues ?? []).map((i) => i.path), JSON.stringify(refused.json)).toContain(path); const read = await call('GET', `/automation/${name}`); expect(read.status, JSON.stringify(read.json)).toBe(404); } }); - it('a flow with no start node: the admin door answers 400 VALIDATION_FAILED naming the missing node, and nothing registers', async () => { - const refused = await call('POST', '/automation', startlessFlow(DOOR_NO_START)); - expect(refused.status, JSON.stringify(refused.json)).toBe(400); - expect(refused.json.error?.code).toBe('VALIDATION_FAILED'); - expect(refused.json.error?.message).toMatch( - new RegExp(`^Flow '${DOOR_NO_START}' rejected: the flow's top-level \`nodes\` hold no \`start\` node`), - ); + it('a flow with no start node: the admin door answers 422 INVALID_METADATA naming the missing node, and nothing registers', async () => { + const refused = await create(DOOR_NO_START, startlessFlow(DOOR_NO_START)); + expect(refused.status, JSON.stringify(refused.json)).toBe(422); + const body = metaRefusal(refused.json); + expect(body.code).toBe('INVALID_METADATA'); + expect((body.issues ?? []).map((i) => i.rule)).toEqual(['flow-start-node-missing']); + expect(body.issues?.[0]?.message).toMatch(/^the flow's top-level `nodes` hold no `start` node/); + expect(body.error).toContain(`flow '${DOOR_NO_START}'`); const read = await call('GET', `/automation/${DOOR_NO_START}`); expect(read.status, JSON.stringify(read.json)).toBe(404); @@ -368,31 +394,31 @@ describe('a flow node config its contract refuses is refused at registration, an expect(bootLines(PACKAGED_NO_START, 'hold no `start` node').length, bootOutput.slice(-4000)).toBeGreaterThan(0); }); - it('a notify node naming a channel no plugin registers: the admin door answers 400 VALIDATION_FAILED naming it and the registered channels, and nothing registers', async () => { - const refused = await call('POST', '/automation', notifyFlow(DOOR_UNKNOWN_CHANNEL, ['inbox', 'emial'])); - expect(refused.status, JSON.stringify(refused.json)).toBe(400); - expect(refused.json.error?.code).toBe('VALIDATION_FAILED'); - const message = String(refused.json.error?.message); - expect(message).toMatch(new RegExp(`^Flow '${DOOR_UNKNOWN_CHANNEL}' rejected: 1 notify channel\\(s\\) no plugin registers:`)); - expect(message).toContain("node 'tell' (`notify`) names channel 'emial' at nodes.1.config.channels.1"); + it('a notify node naming a channel no plugin registers: the admin door answers 422 INVALID_METADATA naming it and the registered channels, and nothing registers', async () => { + const refused = await create(DOOR_UNKNOWN_CHANNEL, notifyFlow(DOOR_UNKNOWN_CHANNEL, ['inbox', 'emial'])); + expect(refused.status, JSON.stringify(refused.json)).toBe(422); + const body = metaRefusal(refused.json); + expect(body.code).toBe('INVALID_METADATA'); + const issues = body.issues ?? []; + expect(issues.map((i) => i.rule), JSON.stringify(refused.json)).toEqual(['flow-notify-channel-unregistered']); + expect(issues[0]?.path).toMatch(/(^|\.)nodes\.1\.config\.channels\.1$/); + expect(issues[0]?.message).toContain("node 'tell' (`notify`) names channel 'emial' at nodes.1.config.channels.1"); // The roster is the composition's own: the inbox, and the messaging providers. - expect(message).toMatch(/The channels this deployment registers: `inbox`, .*`email`/); - const fields = refused.json.error?.details?.fields ?? []; - expect(fields.map((f) => f.field)).toEqual(['nodes.1.config.channels.1']); + expect(issues[0]?.hint).toMatch(/Name a channel this deployment registers \((.*, )?email, .*inbox/); const read = await call('GET', `/automation/${DOOR_UNKNOWN_CHANNEL}`); expect(read.status, JSON.stringify(read.json)).toBe(404); }); it('a notify node naming registered channels, the control: the admin door registers it', async () => { - const created = await call('POST', '/automation', notifyFlow(DOOR_KNOWN_CHANNELS, ['inbox', 'email'])); + const created = await create(DOOR_KNOWN_CHANNELS, notifyFlow(DOOR_KNOWN_CHANNELS, ['inbox', 'email'])); expect(created.status, JSON.stringify(created.json)).toBe(200); const read = await call('GET', `/automation/${DOOR_KNOWN_CHANNELS}`); expect(read.status, JSON.stringify(read.json)).toBe(200); }); it('the admin door, the control: a valid escalation registers', async () => { - const created = await call('POST', '/automation', gatedFlow(DOOR_VALID, VALID)); + const created = await create(DOOR_VALID, gatedFlow(DOOR_VALID, VALID)); expect(created.status, JSON.stringify(created.json)).toBe(200); const read = await call('GET', `/automation/${DOOR_VALID}`); expect(read.status, JSON.stringify(read.json)).toBe(200); diff --git a/packages/qa/dogfood/test/flow-provenance-server-held.dogfood.test.ts b/packages/qa/dogfood/test/flow-provenance-server-held.dogfood.test.ts index 77a1a9030ee..1374bd238d1 100644 --- a/packages/qa/dogfood/test/flow-provenance-server-held.dogfood.test.ts +++ b/packages/qa/dogfood/test/flow-provenance-server-held.dogfood.test.ts @@ -33,10 +33,19 @@ // package, and nothing is written, served or registered. Its controls are // the cases above: a customer flow naming no package saves, one naming the // tenant's installed base saves, and a shipped flow is a locked base. +// +// [#38174] `POST /automation`, the create door, is retired, and a package-less +// create is refused on every door (ADR-0070 D1). The create door's case now +// pins that the retired door is not served and that the assertion is refused +// on the door that creates (`/meta`, into a writable package); the customer +// flows are created into the showcase's writable `.custom` pair; and the +// package-less customer flow the `/meta` round trip edits is a legacy loose +// row, seeded directly, whose in-place save stays open. import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; import { isCodeArtifactBody } from '@objectstack/metadata-core'; import { ConnectorRestPlugin } from '@objectstack/connector-rest'; import { ConnectorOpenApiPlugin } from '@objectstack/connector-openapi'; @@ -140,6 +149,8 @@ describe('a flow\'s package provenance is the server\'s fact at every door (show dbFile = join(dir, 'showcase.db'); stack = await boot(dbFile); token = await stack.signIn(); + // [#38174] The writable package new flows are created in. + await ensurePair(stack, token, 'com.example.showcase'); }, 180_000); afterAll(async () => { @@ -149,16 +160,19 @@ describe('a flow\'s package provenance is the server\'s fact at every door (show }); it('the create door refuses a definition asserting a package for a name no package ships, and registers nothing', async () => { - const created = await call('POST', '/automation', { ...definition(ASSERTED), ...ASSERTION }); + // [#38174] The retired create door is not served … + expect((await call('POST', '/automation', { ...definition(ASSERTED), ...ASSERTION })).status).toBe(404); + // … and the door that creates, naming a writable package, refuses the assertion. + const created = await call('PUT', `/meta/flow/${ASSERTED}?package=${PAIR_PACKAGE}`, { ...definition(ASSERTED), ...ASSERTION }); expect(created.status, JSON.stringify(created.json)).toBe(422); - expect(dispatcherCode(created.json)).toBe('INVALID_METADATA'); + expect(restCode(created.json)).toBe('INVALID_METADATA'); expect((await call('GET', `/automation/${ASSERTED}`)).status).toBe(404); expect(await ledgerRows(ASSERTED)).toEqual([]); }); it('the update door refuses the same assertion on a customer flow, and the flow is unchanged', async () => { - const created = await call('POST', '/automation', definition(CUSTOMER)); + const created = await call('PUT', `/meta/flow/${CUSTOMER}?package=${PAIR_PACKAGE}`, definition(CUSTOMER)); expect(created.status, JSON.stringify(created.json)).toBe(200); const before = dataOf((await call('GET', `/automation/${CUSTOMER}`)).json); @@ -171,7 +185,11 @@ describe('a flow\'s package provenance is the server\'s fact at every door (show it('a customer flow\'s own round trip through the automation door is accepted unchanged', async () => { const served = dataOf((await call('GET', `/automation/${CUSTOMER}`)).json)!; - expect(isCodeArtifactBody(served)).toBe(false); + // [#38174] MEASURED, as for META_BOUND below: created into a writable + // package, the served body surfaces the row's binding as a package + // stamp, which reads as code-shipped on its own — the edge the round + // trip must not break. + expect(isCodeArtifactBody(served)).toBe(true); const put = await call('PUT', `/automation/${CUSTOMER}`, served); @@ -206,8 +224,17 @@ describe('a flow\'s package provenance is the server\'s fact at every door (show }); it('a customer flow\'s own round trip through the metadata door is accepted', async () => { - const created = await call('PUT', `/meta/flow/${META_CUSTOMER}`, definition(META_CUSTOMER)); - expect(created.status, JSON.stringify(created.json)).toBe(200); + // [#38174] A package-less customer flow is a legacy loose row (no door + // creates one any more, ADR-0070 D1): seeded directly; its in-place save stays open. + const ql = (await stack.kernel.getServiceAsync('objectql')) as unknown as { + insert(object: string, data: Record, options?: unknown): Promise; + }; + const now = new Date().toISOString(); + await ql.insert('sys_metadata', { + type: 'flow', name: META_CUSTOMER, package_id: null, scope: 'platform', + state: 'active', version: 1, checksum: null, created_at: now, updated_at: now, + metadata: JSON.stringify(definition(META_CUSTOMER)), + }, { context: SYSTEM_CTX }); const served = await metaRead(META_CUSTOMER); expect(served.status).toBe(200); expect(isCodeArtifactBody(served.doc)).toBe(false); @@ -263,7 +290,7 @@ describe('a flow\'s package provenance is the server\'s fact at every door (show it('control: the metadata door keeps its old handling of the same assertion on another type', async () => { const name = 'dogfood_control_20761'; - const put = await call('PUT', `/meta/dashboard/${name}`, { + const put = await call('PUT', `/meta/dashboard/${name}?package=${PAIR_PACKAGE}`, { name, label: 'Control', widgets: [], diff --git a/packages/qa/dogfood/test/flow-region-malformed-publish.dogfood.test.ts b/packages/qa/dogfood/test/flow-region-malformed-publish.dogfood.test.ts index f7feba74de0..5a03d80c4a9 100644 --- a/packages/qa/dogfood/test/flow-region-malformed-publish.dogfood.test.ts +++ b/packages/qa/dogfood/test/flow-region-malformed-publish.dogfood.test.ts @@ -129,12 +129,14 @@ describe('dogfood: a flow with a malformed region is refused at publish, and its }, 30_000); it('the per-item publish and a live save refuse it too, before any write', async () => { - const drafted = await call('PUT', '/meta/flow/rgnprobe_item?mode=draft', closedLoopFlow('rgnprobe_item', 'i')); + // [#38174] A new item is created into a writable package (ADR-0070 D1), + // so each save reaches the region rule it pins. + const drafted = await call('PUT', `/meta/flow/rgnprobe_item?mode=draft&package=${PKG_BAD}`, closedLoopFlow('rgnprobe_item', 'i')); expect(drafted.status, JSON.stringify(drafted.json)).toBe(200); - expectRegionRefusal(await call('POST', '/meta/flow/rgnprobe_item/publish', {})); + expectRegionRefusal(await call('POST', `/meta/flow/rgnprobe_item/publish?package=${PKG_BAD}`, {})); await expectNoActiveRow('rgnprobe_item'); - expectRegionRefusal(await call('PUT', '/meta/flow/rgnprobe_live', closedLoopFlow('rgnprobe_live', 'v'))); + expectRegionRefusal(await call('PUT', `/meta/flow/rgnprobe_live?package=${PKG_BAD}`, closedLoopFlow('rgnprobe_live', 'v'))); await expectNoActiveRow('rgnprobe_live'); }, 30_000); diff --git a/packages/qa/dogfood/test/fls-own-field-mask-33828.dogfood.test.ts b/packages/qa/dogfood/test/fls-own-field-mask-33828.dogfood.test.ts index f2b51642e72..d6722438160 100644 --- a/packages/qa/dogfood/test/fls-own-field-mask-33828.dogfood.test.ts +++ b/packages/qa/dogfood/test/fls-own-field-mask-33828.dogfood.test.ts @@ -25,6 +25,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; import { showcaseAppDefaultSecurity } from './showcase-security.js'; import { catalogPermissionSet } from './catalog-permission-set.js'; @@ -59,6 +60,8 @@ describe('[ADR-0066 ⑧, v19 #36055] a set\'s own readable: false row binds its beforeAll(async () => { stack = await bootShowcase({ security: showcaseAppDefaultSecurity() }); const adminTok = await stack.signIn(); // the seeded platform admin first, so the sign-ups are plain members + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + const pkg = await ensurePair(stack, adminTok, 'com.example.showcase'); holderTok = await stack.signUp(HOLDER); bothTok = await stack.signUp(BOTH); unconvertedTok = await stack.signUp(UNCONVERTED); @@ -87,7 +90,7 @@ describe('[ADR-0066 ⑧, v19 #36055] a set\'s own readable: false row binds its }, ]; for (const body of sets) { - const authored = await stack.apiAs(adminTok, 'PUT', `/meta/permission/${body.name}`, body); + const authored = await stack.apiAs(adminTok, 'PUT', `/meta/permission/${body.name}?package=${pkg}`, body); expect(authored.status, `${body.name} authored: ${await authored.clone().text()}`).toBeLessThan(300); expect(await catalogPermissionSet(ql, body.name), `the catalog serves ${body.name}`).toBeTruthy(); } diff --git a/packages/qa/dogfood/test/fls-superuser-vote.dogfood.test.ts b/packages/qa/dogfood/test/fls-superuser-vote.dogfood.test.ts index 852d35671b3..ed670e6a2b2 100644 --- a/packages/qa/dogfood/test/fls-superuser-vote.dogfood.test.ts +++ b/packages/qa/dogfood/test/fls-superuser-vote.dogfood.test.ts @@ -30,6 +30,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; import { showcaseAppDefaultSecurity } from './showcase-security.js'; import { catalogPermissionSet } from './catalog-permission-set.js'; @@ -58,11 +59,13 @@ describe('[ruling 6573563853, v19 #36055] the admin\'s viewAllFields reads every beforeAll(async () => { stack = await bootShowcase({ security: showcaseAppDefaultSecurity() }); adminTok = await stack.signIn(); // the seeded platform admin first, so the sign-up is a plain member + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + const pkg = await ensurePair(stack, adminTok, 'com.example.showcase'); memberTok = await stack.signUp(MEMBER); ql = await stack.kernel.getServiceAsync('objectql'); // The card's app set, authored through the metadata door (ADR-0131 D3/D4). - const authored = await stack.apiAs(adminTok, 'PUT', `/meta/permission/${APP_SET}`, { + const authored = await stack.apiAs(adminTok, 'PUT', `/meta/permission/${APP_SET}?package=${pkg}`, { name: APP_SET, label: 'Scratch: app mask on business-unit fields', description: 'Test-authored (ruling 6573563853): object read, every field but name withheld.', diff --git a/packages/qa/dogfood/test/formula-hop-undeclared-related-field.dogfood.test.ts b/packages/qa/dogfood/test/formula-hop-undeclared-related-field.dogfood.test.ts index 756586b4700..c9925197ffc 100644 --- a/packages/qa/dogfood/test/formula-hop-undeclared-related-field.dogfood.test.ts +++ b/packages/qa/dogfood/test/formula-hop-undeclared-related-field.dogfood.test.ts @@ -19,6 +19,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { ensurePair } from './customization-pair.js'; import { defineStack } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; @@ -99,19 +100,23 @@ describe('[#24410] a formula reading a field its lookup target does not declare' }); it('the save door refuses the read, naming the field and the target object', async () => { - const saved = await call('PUT', '/meta/object/rhf_loan_saved', saveBody('rhf_loan_saved', UNDECLARED)); + // [#38174] A new object is created into a writable package (ADR-0070 D1): + // the fixture's `.custom` pair, whose namespace prefix (`rhf_custom_`) it carries. + const pair = await ensurePair(stack, token, 'com.dogfood.formula-hop-undeclared'); + const saved = await call('PUT', `/meta/object/rhf_custom_loan_saved?package=${pair}`, saveBody('rhf_custom_loan_saved', UNDECLARED)); expect(saved.status, JSON.stringify(saved.json)).toBe(422); expect(saved.json?.code, JSON.stringify(saved.json)).toBe('INVALID_METADATA'); const issues = (saved.json?.issues ?? []) as Row[]; // The existing `EXPRESSION_INVALID` rule, located at the key the author edits. expect(issues.map((i) => [i.rule, i.where]), JSON.stringify(saved.json)).toEqual([ - ['expression-invalid', "object 'rhf_loan_saved' · field 'summary' expression"], + ['expression-invalid', "object 'rhf_custom_loan_saved' · field 'summary' expression"], ]); expect(String(issues[0].message)).toMatch(/^unknown field `name` on `rhf_book`/); }); it('control: the same object reading a declared field of the target saves', async () => { - const saved = await call('PUT', '/meta/object/rhf_loan_ok', saveBody('rhf_loan_ok', 'record.book.title')); + const pair = await ensurePair(stack, token, 'com.dogfood.formula-hop-undeclared'); + const saved = await call('PUT', `/meta/object/rhf_custom_loan_ok?package=${pair}`, saveBody('rhf_custom_loan_ok', 'record.book.title')); expect(saved.status, JSON.stringify(saved.json)).toBe(200); }); diff --git a/packages/qa/dogfood/test/grant-table-write-contract.dogfood.test.ts b/packages/qa/dogfood/test/grant-table-write-contract.dogfood.test.ts index 804c57f3523..dd3eaeb89b4 100644 --- a/packages/qa/dogfood/test/grant-table-write-contract.dogfood.test.ts +++ b/packages/qa/dogfood/test/grant-table-write-contract.dogfood.test.ts @@ -259,7 +259,8 @@ describe('an agent ceiling set reaches no person through a position or a seed', }); it('control: a position naming a person set is saved, assigned, and its holder holds that set', async () => { - const saved = await stack.apiAs(admin, 'PUT', '/meta/position/person_set_position', { + // [#38174] A new item is created into a writable package (ADR-0070 D1). + const saved = await stack.apiAs(admin, 'PUT', `/meta/position/person_set_position?package=${PKG}`, { name: 'person_set_position', label: 'Person set', permissionSets: [SET], }); expect(saved.status, await saved.clone().text()).toBe(200); diff --git a/packages/qa/dogfood/test/knowledge-source-studio-roundtrip.dogfood.test.ts b/packages/qa/dogfood/test/knowledge-source-studio-roundtrip.dogfood.test.ts index 0b05644e5c7..c2939fca3e7 100644 --- a/packages/qa/dogfood/test/knowledge-source-studio-roundtrip.dogfood.test.ts +++ b/packages/qa/dogfood/test/knowledge-source-studio-roundtrip.dogfood.test.ts @@ -35,8 +35,18 @@ import { type VerifyStack } from '@objectstack/verify'; import { KnowledgeSourceSchema } from '@objectstack/spec/ai'; import { stripReadDecorations } from '@objectstack/spec/kernel'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.showcase.custom'; const SOURCE = 'ks_studio_open_tasks'; +/** + * [#38174] The id the knowledge service serves the source under: a packaged + * source is named `NS-NAME` (ADR-0150 addendum, `knowledge_source`), and the + * source is created in {@link PAIR_PKG}, whose namespace is `showcase_custom`. + */ +const SOURCE_ID = `showcase_custom-${SOURCE}`; /** A word no seeded task carries, so a hit on it is the record this file wrote. */ const MARKER = 'zephyrquartz'; @@ -85,6 +95,8 @@ describe('[ADR-0161 K4] a knowledge source authored through Studio\'s wire is se beforeAll(async () => { stack = await bootShowcase({ extraPlugins: [new MCPServerPlugin()] }); admin = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, admin, 'com.example.showcase'); const projects = await stack.apiAs(admin, 'GET', '/data/showcase_project?limit=1'); expect(projects.status, await projects.clone().text()).toBe(200); const project = rowsOf(await projects.json())[0]; @@ -108,13 +120,15 @@ describe('[ADR-0161 K4] a knowledge source authored through Studio\'s wire is se it('CONTROL: before the publish, search_knowledge lists no such source', async () => { const answer = await tool('search_knowledge', { query: MARKER }); expect(answer.isError, answer.text).toBe(false); - expect((answer.payload.sources as Array<{ id: string }>).map((s) => s.id)).not.toContain(SOURCE); + const ids = (answer.payload.sources as Array<{ id: string }>).map((s) => s.id); + expect(ids).not.toContain(SOURCE); + expect(ids).not.toContain(SOURCE_ID); }); it('Studio\'s Save — the draft PUT, then the item\'s publish — saves the source', async () => { - const draft = await stack.apiAs(admin, 'PUT', `/meta/knowledge_source/${SOURCE}?mode=draft`, FORM_BODY); + const draft = await stack.apiAs(admin, 'PUT', `/meta/knowledge_source/${SOURCE}?mode=draft&package=${PAIR_PKG}`, FORM_BODY); expect(draft.status, await draft.clone().text()).toBe(200); - const published = await stack.apiAs(admin, 'POST', `/meta/knowledge_source/${SOURCE}/publish`, {}); + const published = await stack.apiAs(admin, 'POST', `/meta/knowledge_source/${SOURCE}/publish?package=${PAIR_PKG}`, {}); expect(published.status, await published.clone().text()).toBe(200); }); @@ -131,10 +145,10 @@ describe('[ADR-0161 K4] a knowledge source authored through Studio\'s wire is se await new Promise((r) => setTimeout(r, 250)); } expect(hit, last?.text).toBeDefined(); - expect(hit).toMatchObject({ sourceId: SOURCE, record: { object: 'showcase_task', id: taskId } }); + expect(hit).toMatchObject({ sourceId: SOURCE_ID, record: { object: 'showcase_task', id: taskId } }); expect(String(hit.snippet)).toContain(MARKER); expect((last!.payload.sources as Array<{ id: string; label: string }>)).toContainEqual( - expect.objectContaining({ id: SOURCE, label: FORM_BODY.label }), + expect.objectContaining({ id: SOURCE_ID, label: FORM_BODY.label }), ); }); @@ -163,9 +177,9 @@ describe('[ADR-0161 K4] a knowledge source authored through Studio\'s wire is se label: 'Open tasks (edited in Studio)', source: { ...stored.source, content: ['notes', 'title'], split: { strategy: 'recursive', maxChars: 400, minChars: 100 } }, }; - const draft = await stack.apiAs(admin, 'PUT', `/meta/knowledge_source/${SOURCE}?mode=draft`, edited); + const draft = await stack.apiAs(admin, 'PUT', `/meta/knowledge_source/${SOURCE}?mode=draft&package=${PAIR_PKG}`, edited); expect(draft.status, await draft.clone().text()).toBe(200); - const published = await stack.apiAs(admin, 'POST', `/meta/knowledge_source/${SOURCE}/publish`, {}); + const published = await stack.apiAs(admin, 'POST', `/meta/knowledge_source/${SOURCE}/publish?package=${PAIR_PKG}`, {}); expect(published.status, await published.clone().text()).toBe(200); const after = await stack.apiAs(admin, 'GET', `/meta/knowledge_source/${SOURCE}`); @@ -186,7 +200,7 @@ describe('[ADR-0161 K4] a knowledge source authored through Studio\'s wire is se let listed = false; while (Date.now() < deadline) { last = await tool('search_knowledge', { query: MARKER, sourceIds: [SOURCE] }); - listed = !last.isError && (last.payload.sources as Array<{ id: string; label: string }>).some((s) => s.id === SOURCE && s.label === edited.label); + listed = !last.isError && (last.payload.sources as Array<{ id: string; label: string }>).some((s) => s.id === SOURCE_ID && s.label === edited.label); const hit = !last.isError && (last.payload.hits as any[]).some((h) => h.record?.id === taskId); if (listed && hit) break; await new Promise((r) => setTimeout(r, 250)); diff --git a/packages/qa/dogfood/test/knowledge-source-unmounted-adapter-save.dogfood.test.ts b/packages/qa/dogfood/test/knowledge-source-unmounted-adapter-save.dogfood.test.ts index 738cff5cf85..2c2280dbece 100644 --- a/packages/qa/dogfood/test/knowledge-source-unmounted-adapter-save.dogfood.test.ts +++ b/packages/qa/dogfood/test/knowledge-source-unmounted-adapter-save.dogfood.test.ts @@ -33,6 +33,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { MCPServerPlugin } from '@objectstack/mcp'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; const OPERATOR = { email: 'admin@objectos.ai', password: 'admin123' }; const AGENT_SCOPE = 'openid profile email offline_access metadata:write actions:execute'; @@ -102,8 +103,8 @@ describe('[ADR-0161 K4] a knowledge_source naming an adapter the deployment does let agent = ''; const priorOidc = process.env.OS_OIDC_PROVIDER_ENABLED; - const put = async (name: string, body: unknown) => { - const res = await stack.apiAs(admin, 'PUT', `/meta/knowledge_source/${name}`, body); + const put = async (name: string, body: unknown, pkg?: string) => { + const res = await stack.apiAs(admin, 'PUT', `/meta/knowledge_source/${name}${pkg ? `?package=${pkg}` : ''}`, body); const json: any = await res.json().catch(() => ({})); return { status: res.status, error: json?.error, json }; }; @@ -170,8 +171,11 @@ describe('[ADR-0161 K4] a knowledge_source naming an adapter the deployment does }); it('CONTROL: a source naming the mounted store, and one leaving `adapter` out, save at both doors', async () => { + // [#38174] A new item is created into a writable package (ADR-0070 D1): the + // showcase's `.custom` pair, whose closure holds the source's object. + const pair = await ensurePair(stack, admin, 'com.example.showcase'); for (const [name, adapter] of [['ks_named_store', 'memory'], ['ks_omitted_store', undefined]] as const) { - const saved = await put(name, sourceBody(name, adapter)); + const saved = await put(name, sourceBody(name, adapter), pair); expect(saved.status, JSON.stringify(saved.json)).toBe(200); const drafted = await saveDraft(`${name}_draft`, sourceBody(`${name}_draft`, adapter)); expect(drafted.isError, drafted.text).toBe(false); diff --git a/packages/qa/dogfood/test/managed-content-sealed.dogfood.test.ts b/packages/qa/dogfood/test/managed-content-sealed.dogfood.test.ts index 0724636b72d..5483090d753 100644 --- a/packages/qa/dogfood/test/managed-content-sealed.dogfood.test.ts +++ b/packages/qa/dogfood/test/managed-content-sealed.dogfood.test.ts @@ -25,8 +25,9 @@ // - a regime-O customization: a packaged VIEW is customized in its base's // `.custom` pair and the customization removed (#28576: the package-less // write onto it is closed); -// - a NEW flow, through `PUT /meta/flow/:name` and through `POST /automation` -// (the card's positive control: creating a new flow in Studio works); +// - a NEW flow, through `PUT /meta/flow/:name?package=` into the `.custom` +// pair (the card's positive control: creating a new flow in Studio works; +// the `POST /automation` create door is retired, #38174); // - the switch: `POST /automation/:name/toggle` turns the managed flow off and // on (this `single`-posture boot is inert to the operator wall, whose // walled-posture pins are `runtime/src/domains/activation-gate*.test.ts`); @@ -211,7 +212,7 @@ describe('[ADR-0131 D6] managed content is sealed — the hatch opens nothing a expect(del.text).toContain('reset to artifact default'); }); - it('control (the card\'s positive control): a NEW flow is created through /meta and through /automation', async () => { + it('control (the card\'s positive control): a NEW flow is created through /meta, in a writable package', async () => { const body = (name: string) => ({ name, label: 'Seal control', @@ -219,10 +220,15 @@ describe('[ADR-0131 D6] managed content is sealed — the hatch opens nothing a nodes: [{ id: 'start', type: 'start', label: 'Start' }, { id: 'end', type: 'end', label: 'End' }], edges: [{ id: 'e1', source: 'start', target: 'end' }], }); - const meta = await call('PUT', '/meta/flow/seal_control_meta', body('seal_control_meta')); + // [#38174] A new item is created in a writable package (ADR-0070 D1): + // the CRM's `.custom` pair. The `POST /automation` create door is + // retired, so the control there is that it is no longer served. + const pair = await call('POST', '/packages/com.example.crm/ensure-customization'); + expect([200, 201], pair.text).toContain(pair.status); + const meta = await call('PUT', '/meta/flow/seal_control_meta?package=com.example.crm.custom', body('seal_control_meta')); expect(meta.status, meta.text).toBe(200); const automation = await call('POST', '/automation', body('seal_control_automation')); - expect(automation.status, automation.text).toBe(200); + expect(automation.status, automation.text).toBe(404); expect((await served('flow', 'seal_control_meta')).name).toBe('seal_control_meta'); }); diff --git a/packages/qa/dogfood/test/mcp-internal-field-evaluate-positions.dogfood.test.ts b/packages/qa/dogfood/test/mcp-internal-field-evaluate-positions.dogfood.test.ts index 2b03ca23299..0a44560fe64 100644 --- a/packages/qa/dogfood/test/mcp-internal-field-evaluate-positions.dogfood.test.ts +++ b/packages/qa/dogfood/test/mcp-internal-field-evaluate-positions.dogfood.test.ts @@ -64,6 +64,8 @@ import { showcaseAppDefaultSecurity } from './showcase-security.js'; import { catalogPermissionSet } from './catalog-permission-set.js'; const OBJECT = 'mcpif_vault'; +/** [#38174] The writable package the fixture's object and set are created in. */ +const PKG = 'com.dogfood.mcpif'; const FLAGGED = 'pin'; const ORDINARY = 'tier'; const SYS = { context: { isSystem: true } } as const; @@ -291,13 +293,19 @@ describe('MCP data tools refuse an internal field in every evaluate position, as sessionTokens.admin = await stack.signIn(); sessionTokens.member = await stack.signUp(MEMBER_EMAIL); - const saved = await stack.apiAs(sessionTokens.admin, 'PUT', `/meta/object/${OBJECT}`, DEFINITION); + // [#38174] New items are created into a writable package (ADR-0070 D1), + // whose namespace is the object's prefix (`mcpif_`). + const pkg = await stack.apiAs(sessionTokens.admin, 'POST', '/packages', { + manifest: { id: PKG, name: 'MCP internal field', version: '1.0.0', type: 'app', namespace: 'mcpif' }, + }); + expect(pkg.status, await pkg.clone().text()).toBe(201); + const saved = await stack.apiAs(sessionTokens.admin, 'PUT', `/meta/object/${OBJECT}?package=${PKG}`, DEFINITION); expect(saved.status, `runtime object authored: ${await saved.clone().text()}`).toBe(200); const ql = await stack.kernel.getServiceAsync('objectql'); for (const row of ROWS) await ql.insert(OBJECT, row, SYS); // The member reads the object through one authored set and nothing else. - const authored = await stack.apiAs(sessionTokens.admin, 'PUT', `/meta/permission/${READER_SET}`, { + const authored = await stack.apiAs(sessionTokens.admin, 'PUT', `/meta/permission/${READER_SET}?package=${PKG}`, { name: READER_SET, label: 'Scratch: object read on the MCP internal-field fixture', objects: { [OBJECT]: { allowRead: true } }, diff --git a/packages/qa/dogfood/test/mcp-list-actions-environment-authored-holder.dogfood.test.ts b/packages/qa/dogfood/test/mcp-list-actions-environment-authored-holder.dogfood.test.ts index 08548000626..8d392005b4d 100644 --- a/packages/qa/dogfood/test/mcp-list-actions-environment-authored-holder.dogfood.test.ts +++ b/packages/qa/dogfood/test/mcp-list-actions-environment-authored-holder.dogfood.test.ts @@ -122,9 +122,21 @@ describe('[#33029] list_actions files an environment-authored action on a packag recordId = (Array.isArray(found) ? found : found?.records ?? [])[0]?.id; expect(recordId, 'the showcase seeds a task').toBeTruthy(); - const env = await stack.apiAs(admin, 'PUT', `/meta/action/${ENV_ACTION}`, authored(ENV_ACTION, 50)); + // [#38174] An environment-authored (package-less) action is a legacy loose + // row: no door creates one any more (ADR-0070 D1). Each is seeded directly, + // then saved in place through the door, which stays open. + const seedLoose = async (name: string, body: Record) => { + const now = new Date().toISOString(); + await ql.insert('sys_metadata', { + type: 'action', name, package_id: null, scope: 'platform', + state: 'active', version: 1, checksum: null, created_at: now, updated_at: now, + metadata: JSON.stringify(body), + }, { context: { isSystem: true, positions: [], permissions: [] } }); + return stack.apiAs(admin, 'PUT', `/meta/action/${name}`, body); + }; + const env = await seedLoose(ENV_ACTION, authored(ENV_ACTION, 50)); expect(env.status, await env.clone().text()).toBe(200); - const flow = await stack.apiAs(admin, 'PUT', `/meta/action/${ENV_FLOW_ACTION}`, { + const flow = await seedLoose(ENV_FLOW_ACTION, { name: ENV_FLOW_ACTION, label: ENV_FLOW_ACTION, objectName: OBJECT, type: 'flow', target: SHIPPED_FLOW, ai: ai('Recalculate the task estimate through the showcase flow'), }); @@ -138,7 +150,7 @@ describe('[#33029] list_actions files an environment-authored action on a packag expect(created.status, await created.clone().text()).toBe(201); const pkg = await stack.apiAs(admin, 'PUT', `/meta/action/${PKG_ACTION}?package=${QA_PACKAGE}`, authored(PKG_ACTION, 40)); expect(pkg.status, await pkg.clone().text()).toBe(200); - const shared = await stack.apiAs(admin, 'PUT', `/meta/action/${ENV_SHARED_FLOW_ACTION}`, { + const shared = await seedLoose(ENV_SHARED_FLOW_ACTION, { name: ENV_SHARED_FLOW_ACTION, label: ENV_SHARED_FLOW_ACTION, objectName: OBJECT, type: 'flow', target: SHARED_FLOW, ai: ai('Run the flow of the shared name'), }); diff --git a/packages/qa/dogfood/test/mcp-stdio-runtime-object-exposure.test.ts b/packages/qa/dogfood/test/mcp-stdio-runtime-object-exposure.test.ts index 5fca0ef8ce8..f5de0110917 100644 --- a/packages/qa/dogfood/test/mcp-stdio-runtime-object-exposure.test.ts +++ b/packages/qa/dogfood/test/mcp-stdio-runtime-object-exposure.test.ts @@ -134,6 +134,8 @@ function makeMemoryDriver(stores: Stores) { const GATED = 'qa_gated_gadget'; const OPEN = 'qa_open_gadget'; +/** [#38174] The writable package the runtime objects are created in (namespace `qa`). */ +const QA_PKG = 'com.qa.gadgets'; const SYSTEM = { context: { isSystem: true } } as never; /** A runtime object body; `enable` is the exposure under test. */ @@ -247,6 +249,13 @@ describe.each(SHAPES)('the MCP stdio door follows a runtime-authored object\'s c await kernel.use(new ObjectQLPlugin({ ql: engine, environmentId, hydrateMetadataFromDb: true })); } await kernel.bootstrap(); + // [#38174] A new item is created into a writable package (ADR-0070 D1): + // the package is installed the way Studio's "New package" does, once per store. + if (!(engine as any).registry?.getPackage?.(QA_PKG)) { + await (kernel.getService('protocol') as any).installPackage({ + manifest: { id: QA_PKG, name: 'QA gadgets', version: '0.0.0', type: 'app', namespace: 'qa' }, + }); + } // The faked seam, and only it: the key row the stdio principal resolves from, and its owner. const ql = new Proxy(engine as any, { @@ -319,7 +328,7 @@ describe.each(SHAPES)('the MCP stdio door follows a runtime-authored object\'s c } const save = (k: Booted, name: string, label: string, enable: Record) => - k.protocol.saveMetaItem({ type: 'object', name, item: objectBody(name, label, enable) }); + k.protocol.saveMetaItem({ type: 'object', name, item: objectBody(name, label, enable), packageId: QA_PKG }); /** The coded envelope a refused tool call carries. */ const refusal = (answer: ToolAnswer) => (answer.isError ? { code: answer.json?.error?.code, status: answer.json?.error?.status } : undefined); diff --git a/packages/qa/dogfood/test/me-apps-and-everyone-baseline.dogfood.test.ts b/packages/qa/dogfood/test/me-apps-and-everyone-baseline.dogfood.test.ts index 3013895be94..4aa69c79177 100644 --- a/packages/qa/dogfood/test/me-apps-and-everyone-baseline.dogfood.test.ts +++ b/packages/qa/dogfood/test/me-apps-and-everyone-baseline.dogfood.test.ts @@ -33,6 +33,10 @@ import { createSecurityCatalogReader } from '@objectstack/core'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; import { SecurityPlugin } from '@objectstack/plugin-security'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.showcase.custom'; const SYS = { isSystem: true } as const; @@ -59,6 +63,8 @@ describe('ADR-0090 D5 closures: /me/apps + anchor-bindable baseline', () => { // Nothing about the claim below changed; only who is saying it. stack = await bootShowcase({ security: new SecurityPlugin() }); adminTok = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, adminTok, 'com.example.showcase'); memberTok = await stack.signUp('baseline-member@verify.test'); ql = await stack.kernel.getServiceAsync('objectql'); }, 90_000); @@ -112,7 +118,7 @@ describe('ADR-0090 D5 closures: /me/apps + anchor-bindable baseline', () => { // Author the property: a set whose ONLY job is tabPermissions.hidden. // [ADR-0131 D3/D4] Authored through the metadata door, the security // catalog's write path: the definition it stores is what the resolver reads. - const hideSet = await stack.apiAs(adminTok, 'PUT', '/meta/permission/tab_probe_hide', { + const hideSet = await stack.apiAs(adminTok, 'PUT', `/meta/permission/tab_probe_hide?package=${PAIR_PKG}`, { name: 'tab_probe_hide', label: 'Tab probe — hide showcase', objects: {}, @@ -127,7 +133,7 @@ describe('ADR-0090 D5 closures: /me/apps + anchor-bindable baseline', () => { // Rank merge: hidden(0) loses to visible(3) from ANY other resolved set — // most-visible wins across the principal's sets, matching hono's tabRank. - const showSet = await stack.apiAs(adminTok, 'PUT', '/meta/permission/tab_probe_show', { + const showSet = await stack.apiAs(adminTok, 'PUT', `/meta/permission/tab_probe_show?package=${PAIR_PKG}`, { name: 'tab_probe_show', label: 'Tab probe — show showcase', objects: {}, @@ -172,7 +178,7 @@ describe('ADR-0090 D5 closures: /me/apps + anchor-bindable baseline', () => { // some wildcard happened to grant create. const memberUser = await ql.findOne('sys_user', { where: { email: 'baseline-member@verify.test' }, context: SYS }); expect(memberUser?.id, 'baseline member resolved').toBeTruthy(); - const inquirySet = await stack.apiAs(adminTok, 'PUT', '/meta/permission/baseline_inquiry_probe', { + const inquirySet = await stack.apiAs(adminTok, 'PUT', `/meta/permission/baseline_inquiry_probe?package=${PAIR_PKG}`, { name: 'baseline_inquiry_probe', label: 'Baseline probe — inquiry create, deliberately no delete', objects: { diff --git a/packages/qa/dogfood/test/meta-door-code-datasource.dogfood.test.ts b/packages/qa/dogfood/test/meta-door-code-datasource.dogfood.test.ts index 5ce45a6980b..244644a7c34 100644 --- a/packages/qa/dogfood/test/meta-door-code-datasource.dogfood.test.ts +++ b/packages/qa/dogfood/test/meta-door-code-datasource.dogfood.test.ts @@ -44,6 +44,7 @@ import showcaseStack, { onEnable } from '@objectstack/example-showcase'; import { registerDatasourceAdminRoutes } from '@objectstack/service-datasource'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -202,7 +203,9 @@ describe('[#21899] the metadata door answers a code-defined datasource as read-o const runtimeBody = (label: string) => ({ name: META_RUNTIME, label, driver: 'sqlite', config: { filename: join(dir, 'meta-rt.db') }, }); - const saved = await call('PUT', `/meta/datasource/${META_RUNTIME}`, runtimeBody('Meta Runtime 21899')); + // [#38174] A new item is created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + const pkg = await ensurePair(stack, token, 'com.example.showcase'); + const saved = await call('PUT', `/meta/datasource/${META_RUNTIME}?package=${pkg}`, runtimeBody('Meta Runtime 21899')); expect(saved.status, JSON.stringify(saved.json)).toBe(200); const updated = await call('PUT', `/meta/datasource/${META_RUNTIME}`, runtimeBody('Meta Runtime 21899 (edited)')); expect(updated.status, JSON.stringify(updated.json)).toBe(200); diff --git a/packages/qa/dogfood/test/meta-object-unstored-field-removal.dogfood.test.ts b/packages/qa/dogfood/test/meta-object-unstored-field-removal.dogfood.test.ts index cbeb36d2f17..594c3c53617 100644 --- a/packages/qa/dogfood/test/meta-object-unstored-field-removal.dogfood.test.ts +++ b/packages/qa/dogfood/test/meta-object-unstored-field-removal.dogfood.test.ts @@ -28,7 +28,13 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { bootStack, type VerifyStack } from '@objectstack/verify'; import { cel, defineStack } from '@objectstack/spec'; -const NAME = 'dfu_invoice'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PKG_38174 = 'com.dogfood.unstored-removal.custom'; + +// [#38174] Created into the fixture's `.custom` pair, so it carries that pair's prefix. +const NAME = 'dfu_custom_invoice'; const stackDef = defineStack({ manifest: { @@ -75,8 +81,11 @@ describe('dogfood: removing an unstored field through PUT /meta/object/:name', ( beforeAll(async () => { stack = await bootStack(stackDef); token = await stack.signIn(); + // [#38174] The object is created into a writable package (ADR-0070 D1): the + // fixture's `.custom` pair, whose namespace prefix (`dfu_custom_`) it carries. + await ensurePair(stack, token, 'com.dogfood.unstored-removal'); - const saved = await call('PUT', `/meta/object/${NAME}`, definition(FIELDS)); + const saved = await call('PUT', `/meta/object/${NAME}?package=${PKG_38174}`, definition(FIELDS)); expect(saved.status, JSON.stringify(saved.json)).toBe(200); const created = await call('POST', `/data/${NAME}`, { name: 'INV-1', notes: 'keep me', amount: 21 }); @@ -90,7 +99,7 @@ describe('dogfood: removing an unstored field through PUT /meta/object/:name', ( }); it('a stored `text` removal still answers 409 DESTRUCTIVE_CHANGE with today\'s finding (live control)', async () => { - const refused = await call('PUT', `/meta/object/${NAME}`, definition(without('notes'))); + const refused = await call('PUT', `/meta/object/${NAME}?package=${PKG_38174}`, definition(without('notes'))); expect(refused.status, JSON.stringify(refused.json)).toBe(409); expect(refused.json?.code, JSON.stringify(refused.json)).toBe('DESTRUCTIVE_CHANGE'); expect(refused.json?.issues).toEqual([{ @@ -103,14 +112,14 @@ describe('dogfood: removing an unstored field through PUT /meta/object/:name', ( }); it('an `autonumber` removal still answers 409: engine-computed, but stored in a column', async () => { - const refused = await call('PUT', `/meta/object/${NAME}`, definition(without('reference'))); + const refused = await call('PUT', `/meta/object/${NAME}?package=${PKG_38174}`, definition(without('reference'))); expect(refused.status, JSON.stringify(refused.json)).toBe(409); expect(refused.json?.code, JSON.stringify(refused.json)).toBe('DESTRUCTIVE_CHANGE'); expect(refused.json?.issues).toEqual([expect.objectContaining({ code: 'field_removed', field: 'reference' })]); }); it('a `formula` removal saves 200 without `force`, and the stored fields read back unchanged', async () => { - const saved = await call('PUT', `/meta/object/${NAME}`, definition(without('doubled'))); + const saved = await call('PUT', `/meta/object/${NAME}?package=${PKG_38174}`, definition(without('doubled'))); expect(saved.status, JSON.stringify(saved.json)).toBe(200); const meta = await call('GET', `/meta/object/${NAME}`); diff --git a/packages/qa/dogfood/test/meta-view-audience-alternate-doors.dogfood.test.ts b/packages/qa/dogfood/test/meta-view-audience-alternate-doors.dogfood.test.ts index d0bd3637ab2..257bb392b36 100644 --- a/packages/qa/dogfood/test/meta-view-audience-alternate-doors.dogfood.test.ts +++ b/packages/qa/dogfood/test/meta-view-audience-alternate-doors.dogfood.test.ts @@ -29,6 +29,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; const SYS = { isSystem: true } as const; const VIEW = 'showcase_task.qa_gated_view'; @@ -68,9 +69,11 @@ describe('a gated view on every alternate /meta door (#22639)', () => { stack = await bootShowcase(); admin = await stack.signIn(); ql = await stack.kernel.getServiceAsync('objectql'); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + const pkg = await ensurePair(stack, admin, 'com.example.showcase'); for (const [name, caps] of [[SETUP_SET, ['setup.access']], [STUDIO_SET, ['studio.access']]] as const) { - const saved = await stack.apiAs(admin, 'PUT', `/meta/permission/${name}`, { name, label: name, objects: {}, systemPermissions: [...caps] }); + const saved = await stack.apiAs(admin, 'PUT', `/meta/permission/${name}?package=${pkg}`, { name, label: name, objects: {}, systemPermissions: [...caps] }); expect(saved.status, await saved.clone().text()).toBe(200); } setupOnly = await grant('audience-setup@verify.test', SETUP_SET); @@ -80,9 +83,9 @@ describe('a gated view on every alternate /meta door (#22639)', () => { name: VIEW, object: 'showcase_task', viewKind: 'list', type: 'grid', label: 'QA gated view', columns: ['title'], requiredPermissions: [GATE], }; - const published = await stack.apiAs(admin, 'PUT', ITEM, body); + const published = await stack.apiAs(admin, 'PUT', `${ITEM}?package=${pkg}`, body); expect(published.status, await published.clone().text()).toBe(200); - const draft = await stack.apiAs(admin, 'PUT', `${ITEM}?mode=draft`, { ...body, label: 'QA gated view (draft)' }); + const draft = await stack.apiAs(admin, 'PUT', `${ITEM}?mode=draft&package=${pkg}`, { ...body, label: 'QA gated view (draft)' }); expect(draft.status, await draft.clone().text()).toBe(200); }, 120_000); diff --git a/packages/qa/dogfood/test/object-designer-field-reorder.dogfood.test.ts b/packages/qa/dogfood/test/object-designer-field-reorder.dogfood.test.ts index 2b9d26a922b..c27263f06fa 100644 --- a/packages/qa/dogfood/test/object-designer-field-reorder.dogfood.test.ts +++ b/packages/qa/dogfood/test/object-designer-field-reorder.dogfood.test.ts @@ -24,6 +24,9 @@ import { hashSpec } from '@objectstack/metadata-core'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +/** [#38174] The writable package this file's new items are created in. */ +const PKG_38174 = 'com.dogfood.fieldreorder'; + const OBJ = 'dogfood_field_reorder'; const SYSTEM_CTX = { isSystem: true }; @@ -63,6 +66,12 @@ describe('dogfood: an object designer field reorder publishes and reads back in beforeAll(async () => { stack = await bootShowcase(); token = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1), whose + // namespace is the objects' own prefix (`dogfood_`). + const pkg38174 = await stack.apiAs(token, 'POST', '/packages', { + manifest: { id: PKG_38174, name: 'Dogfood dogfood', version: '1.0.0', type: 'app', namespace: 'dogfood' }, + }); + expect(pkg38174.status, await pkg38174.clone().text()).toBe(201); ql = (await stack.kernel.getServiceAsync('objectql')) as unknown as Ql; }, 90_000); @@ -81,8 +90,8 @@ describe('dogfood: an object designer field reorder publishes and reads back in return Object.keys(body.item?.fields ?? {}).filter((k) => k in FIELDS); }; const saveDraft = (order: readonly string[]) => - stack.apiAs(token, 'PUT', `/meta/object/${OBJ}?mode=draft`, objectBody(order)); - const publish = () => stack.apiAs(token, 'POST', `/meta/object/${OBJ}/publish`, {}); + stack.apiAs(token, 'PUT', `/meta/object/${OBJ}?mode=draft&package=${PKG_38174}`, objectBody(order)); + const publish = () => stack.apiAs(token, 'POST', `/meta/object/${OBJ}/publish?package=${PKG_38174}`, {}); const activeRow = async (): Promise => { const rows = await ql.find('sys_metadata', { where: { type: 'object', name: OBJ, state: 'active' }, @@ -133,7 +142,7 @@ describe('dogfood: an object designer field reorder publishes and reads back in it('an identical save records no change and leaves the stamp as written', async () => { const before = await historyRows(); const stored = JSON.parse((await activeRow()).metadata) as Record; - const res = await stack.apiAs(token, 'PUT', `/meta/object/${OBJ}`, stored); + const res = await stack.apiAs(token, 'PUT', `/meta/object/${OBJ}?package=${PKG_38174}`, stored); expect(res.status).toBe(200); receipt = ((await res.json()) as { version: string }).version; expect(typeof receipt).toBe('string'); @@ -148,7 +157,7 @@ describe('dogfood: an object designer field reorder publishes and reads back in expect(hashSpec(sorted, 'object')).toBe(legacyStamp); const before = await historyRows(); - const res = await stack.api(`/meta/object/${OBJ}`, { + const res = await stack.api(`/meta/object/${OBJ}?package=${PKG_38174}`, { method: 'PUT', headers: { 'Content-Type': 'application/json', diff --git a/packages/qa/dogfood/test/object-permission-write-implies-read.dogfood.test.ts b/packages/qa/dogfood/test/object-permission-write-implies-read.dogfood.test.ts index fff100627bc..a7f79caeb77 100644 --- a/packages/qa/dogfood/test/object-permission-write-implies-read.dogfood.test.ts +++ b/packages/qa/dogfood/test/object-permission-write-implies-read.dogfood.test.ts @@ -25,6 +25,10 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.showcase.custom'; const SYS = { isSystem: true } as const; const PASS = 'Write-Implies-Read-0001'; @@ -80,6 +84,8 @@ describe('an object permission that edits or deletes a record also reads it (sto beforeAll(async () => { stack = await bootShowcase(); adminTok = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, adminTok, 'com.example.showcase'); ql = await stack.kernel.getServiceAsync('objectql'); writerTok = await storedSetPrincipal('qa_wir_stored_writer', { allowEdit: true, allowDelete: true }, 'wir-writer@verify.test'); readerWriterTok = await storedSetPrincipal( @@ -100,7 +106,7 @@ describe('an object permission that edits or deletes a record also reads it (sto for (const bit of ['allowEdit', 'allowDelete'] as const) { it(`the save door refuses ${bit} without read, at the bit's path, and stores nothing`, async () => { const name = `qa_wir_${bit.toLowerCase()}_unread`; - const saved = await call(adminTok, 'PUT', `/meta/permission/${name}`, { + const saved = await call(adminTok, 'PUT', `/meta/permission/${name}?package=${PAIR_PKG}`, { name, label: name, objects: { [OBJECT]: { [bit]: true } }, }); expect(saved.status, JSON.stringify(saved.body)).toBe(422); @@ -112,7 +118,7 @@ describe('an object permission that edits or deletes a record also reads it (sto it(`the save door accepts ${bit} beside allowRead: true`, async () => { const name = `qa_wir_${bit.toLowerCase()}_read`; - const saved = await call(adminTok, 'PUT', `/meta/permission/${name}`, { + const saved = await call(adminTok, 'PUT', `/meta/permission/${name}?package=${PAIR_PKG}`, { name, label: name, objects: { [OBJECT]: { allowRead: true, [bit]: true } }, }); expect(saved.status, JSON.stringify(saved.body)).toBe(200); diff --git a/packages/qa/dogfood/test/packaged-flow-write-door-parity.dogfood.test.ts b/packages/qa/dogfood/test/packaged-flow-write-door-parity.dogfood.test.ts index 6ae65381954..d6e44970a5b 100644 --- a/packages/qa/dogfood/test/packaged-flow-write-door-parity.dogfood.test.ts +++ b/packages/qa/dogfood/test/packaged-flow-write-door-parity.dogfood.test.ts @@ -25,8 +25,9 @@ // serves is byte-identical to the capture taken before any probe. // 3 `DELETE /automation/:name` is refused; the flow still serves. // 4 no residue: the engine's enabled/bound row for the flow is unchanged. -// A flow the customer authored through the same door is created, updated and -// removed as before — the lock is not a closed door. +// A flow the customer authored (created through `/meta` into a writable +// package, #38174) is updated and removed through the same door as before — +// the lock is not a closed door. // // Nothing is restored afterwards because nothing is mutated: a refused probe is // the whole assertion, and the byte-identical read-backs prove it. @@ -34,6 +35,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; // The showcase declares `connectors:` bound to these providers, and the // automation service refuses to start without their factories (ADR-0097) — // the same composition `packaged-activation-ledger-reach.dogfood.test.ts` boots. @@ -53,6 +55,8 @@ const SHOWCASE_DIR = fileURLToPath(new URL('../../../../examples/app-showcase/', const FLOW = 'showcase_urgent_task_alert'; /** A flow no package ships — created through the door under test, and removed by it. */ const CUSTOMER_FLOW = 'dogfood_customer_flow_20679'; +/** [#38174] The writable package it is created in: the showcase's paired customization package. */ +const CUSTOMER_PACKAGE = 'com.example.showcase.custom'; /** The ledgered locked-base family the metadata door answers with (ADR-0112). */ const LOCKED_BASE_CODES = ['NOT_OVERRIDABLE', 'ITEM_LOCKED']; @@ -157,7 +161,7 @@ describe('a packaged flow keeps its locked base at every write door (showcase)', expect(await statusRow()).toEqual(statusBefore); }); - it('a flow no package ships is still created, updated and removed through the same door', async () => { + it('a flow no package ships, created through /meta into a writable package, is still updated and removed through the same door', async () => { const definition = { name: CUSTOMER_FLOW, label: 'Customer Flow', @@ -169,7 +173,12 @@ describe('a packaged flow keeps its locked base at every write door (showcase)', edges: [{ id: 'e1', source: 'start', target: 'end' }], }; - const created = await call('POST', '/automation', definition); + // [#38174] The create door (`POST /automation`) is retired: a new flow is + // created through the metadata door, into a writable package (the + // showcase's paired customization package); the update and removal + // doors under test are unchanged. + expect(await ensurePair(stack, token, 'com.example.showcase')).toBe(CUSTOMER_PACKAGE); + const created = await call('PUT', `/meta/flow/${CUSTOMER_FLOW}?package=${CUSTOMER_PACKAGE}`, definition); expect(created.status, JSON.stringify(created.json)).toBe(200); const updated = await call('PUT', `/automation/${CUSTOMER_FLOW}`, { ...definition, label: 'Customer Flow (edited)' }); diff --git a/packages/qa/dogfood/test/packageless-create-refused.dogfood.test.ts b/packages/qa/dogfood/test/packageless-create-refused.dogfood.test.ts new file mode 100644 index 00000000000..b7170f61792 --- /dev/null +++ b/packages/qa/dogfood/test/packageless-create-refused.dogfood.test.ts @@ -0,0 +1,210 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#38174, ADR-0070 D1] A package-less CREATE is refused on every door, over the +// real showcase composition. +// +// The kernel save refuses a NEW item that names no package: +// `422 WRITABLE_PACKAGE_REQUIRED`, naming the writable packages, nothing stored. +// The `POST /automation` create door is retired (a new flow is created through +// `PUT /api/v1/meta/flow/NAME?package=PKG`), and `PUT /automation/NAME` of a new +// name answers the same refusal, sending the caller to that `/meta` route. A +// flow saved through `/meta` is also refused for a `notify` node naming a +// channel the messaging service does not know (`flow-notify-channel-unregistered`). +// +// The unit pins sit beside each module (`metadata-protocol`'s +// `protocol-packageless-create`, the runtime's automation domain). What they +// cannot answer is whether, on the stack an operator runs, every door reaches +// the kernel's refusal, and whether the controls still save. +// +// ## What each case pins +// +// (a) `PUT /meta/view/NEW` with no package → 422 WRITABLE_PACKAGE_REQUIRED +// naming a writable package; nothing is readable or stored afterwards; +// (b) the same with `?mode=draft`; +// (c) `POST /automation` is not served (404); `PUT /automation/NEW` → 422 +// WRITABLE_PACKAGE_REQUIRED whose message names +// `/api/v1/meta/flow/NEW?package=PKG`; nothing registers; +// (d) controls: the same view create with `?package=PKG` → 200; a +// `PUT /automation/EXISTING` of an existing flow still updates it; +// (e) a flow saved through `/meta/flow/NAME?package=PKG` with a `notify` node +// naming the unregistered channel `smss` is refused (422, rule +// `flow-notify-channel-unregistered`, the message naming the channel); the +// control naming `email` saves. +// +// 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'; +import { ensurePair } from './customization-pair.js'; +// The showcase declares `connectors:` bound to these providers, and the +// automation service refuses to start without their factories (ADR-0097) — +// the same composition `packaged-flow-write-door-parity.dogfood.test.ts` boots. +import { ConnectorRestPlugin } from '@objectstack/connector-rest'; +import { ConnectorOpenApiPlugin } from '@objectstack/connector-openapi'; +import { ConnectorMcpPlugin } from '@objectstack/connector-mcp'; +import { fileURLToPath } from 'node:url'; + +/** Package-relative connector refs resolve against the cwd — see the sibling boots. */ +const SHOWCASE_DIR = fileURLToPath(new URL('../../../../examples/app-showcase/', import.meta.url)); + +const SHOWCASE = 'com.example.showcase'; +const OBJECT = 'showcase_task'; +const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] }; + +const NEW_VIEW = `${OBJECT}.qa_pkgless_new_38174`; +const NEW_DRAFT_VIEW = `${OBJECT}.qa_pkgless_draft_38174`; +const PACKAGED_VIEW = `${OBJECT}.qa_pkgless_packaged_38174`; +const NEW_FLOW = 'qa_pkgless_new_flow_38174'; +const EXISTING_FLOW = 'qa_pkgless_existing_flow_38174'; +const SMSS_FLOW = 'qa_pkgless_smss_flow_38174'; +const EMAIL_FLOW = 'qa_pkgless_email_flow_38174'; + +const view = (name: string, label: string) => ({ + name, object: OBJECT, viewKind: 'list', label, config: { type: 'grid', columns: [{ field: 'title' }] }, +}); +const flow = (name: string, label = `QA ${name}`) => ({ + name, + label, + type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: {} }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'end' }], +}); +/** A flow run by hand whose one step is a `notify` node naming `channels`. */ +const notifyFlow = (name: string, channels: string[]) => ({ + name, + label: `Notify ${name}`, + type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: {} }, + { id: 'tell', type: 'notify', label: 'Tell', config: { recipients: 'role:admin', title: 'Hello', channels } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'tell' }, + { id: 'e2', source: 'tell', target: 'end' }, + ], +}); + +type Json = Record; + +describe('[#38174, ADR-0070 D1] a package-less create is refused on every door (showcase)', () => { + let stack: VerifyStack; + let token: string; + let prevCwd: string; + /** The writable package the controls create into: the showcase's `.custom` pair. */ + let pkg: string; + + const call = async (method: string, path: string, body?: unknown) => { + const res = await stack.apiAs(token, method, path, body); + const text = await res.text(); + let json: Json = {}; + try { json = JSON.parse(text) as Json; } catch { json = { raw: text }; } + /** The REST `/meta` envelope is `{ error: , code }`; the dispatcher's `{ error: { code, message } }`. */ + const code = (json.code ?? json.error?.code) as unknown; + const message = String(typeof json.error === 'string' ? json.error : json.error?.message ?? ''); + return { status: res.status, json, code, message, text }; + }; + const storedRows = async (type: string, name: string) => { + const ql = (await stack.kernel.getServiceAsync('objectql')) as unknown as { + find(object: string, options?: unknown): Promise; + }; + return ql.find('sys_metadata', { where: { type, name }, context: SYSTEM_CTX }); + }; + + beforeAll(async () => { + prevCwd = process.cwd(); + process.chdir(SHOWCASE_DIR); + stack = await bootShowcase({ + automation: true, + extraPlugins: [ + new ConnectorRestPlugin(), + new ConnectorOpenApiPlugin(), + new ConnectorMcpPlugin({ declarativeStdio: ['node'] }), + ], + }); + token = await stack.signIn(); + pkg = await ensurePair(stack, token, SHOWCASE); + }, 180_000); + + afterAll(async () => { + await stack?.stop(); + if (prevCwd) process.chdir(prevCwd); + }); + + it('(a) PUT /meta/view/NEW with no package → 422 WRITABLE_PACKAGE_REQUIRED naming a writable package; nothing is readable or stored', async () => { + const put = await call('PUT', `/meta/view/${NEW_VIEW}`, view(NEW_VIEW, 'Package-less')); + expect(put.status, put.text).toBe(422); + expect(put.code).toBe('WRITABLE_PACKAGE_REQUIRED'); + expect(put.message).toContain(`Cannot create view/${NEW_VIEW} with no package`); + expect(put.message).toMatch(/Writable packages here: .*\S/); + expect(put.message).toContain(pkg); + expect(put.message).toContain('Nothing was saved.'); + + expect((await call('GET', `/meta/view/${NEW_VIEW}`)).status).toBe(404); + expect(await storedRows('view', NEW_VIEW)).toEqual([]); + }); + + it('(b) the same create with ?mode=draft is refused alike, and no draft is stored', async () => { + const put = await call('PUT', `/meta/view/${NEW_DRAFT_VIEW}?mode=draft`, view(NEW_DRAFT_VIEW, 'Package-less draft')); + expect(put.status, put.text).toBe(422); + expect(put.code).toBe('WRITABLE_PACKAGE_REQUIRED'); + expect(put.message).toContain(`Cannot create view/${NEW_DRAFT_VIEW} with no package`); + expect(put.message).toContain(pkg); + + expect((await call('GET', `/meta/view/${NEW_DRAFT_VIEW}`)).status).toBe(404); + expect(await storedRows('view', NEW_DRAFT_VIEW)).toEqual([]); + }); + + it('(c) POST /automation is not served, and PUT /automation/NEW → 422 naming the /meta route; nothing registers', async () => { + const post = await call('POST', '/automation', flow(NEW_FLOW)); + expect(post.status, post.text).toBe(404); + + const put = await call('PUT', `/automation/${NEW_FLOW}`, flow(NEW_FLOW)); + expect(put.status, put.text).toBe(422); + expect(put.code).toBe('WRITABLE_PACKAGE_REQUIRED'); + expect(put.message).toContain(`/api/v1/meta/flow/${NEW_FLOW}?package=PKG`); + + expect((await call('GET', `/automation/${NEW_FLOW}`)).status).toBe(404); + expect((await call('GET', `/meta/flow/${NEW_FLOW}`)).status).toBe(404); + expect(await storedRows('flow', NEW_FLOW)).toEqual([]); + }); + + it('(d) control: the same view create naming a writable package saves', async () => { + const put = await call('PUT', `/meta/view/${PACKAGED_VIEW}?package=${pkg}`, view(PACKAGED_VIEW, 'In a package')); + expect(put.status, put.text).toBe(200); + const read = await call('GET', `/meta/view/${PACKAGED_VIEW}`); + expect(read.status, read.text).toBe(200); + expect((read.json.item ?? read.json.data?.item ?? read.json.data)?.label).toBe('In a package'); + }); + + it('(d) control: PUT /automation/EXISTING of an existing flow still updates it', async () => { + const created = await call('PUT', `/meta/flow/${EXISTING_FLOW}?package=${pkg}`, flow(EXISTING_FLOW, 'Before')); + expect(created.status, created.text).toBe(200); + expect((await call('GET', `/automation/${EXISTING_FLOW}`)).json.data?.label).toBe('Before'); + + const updated = await call('PUT', `/automation/${EXISTING_FLOW}`, flow(EXISTING_FLOW, 'After')); + expect(updated.status, updated.text).toBe(200); + expect((await call('GET', `/automation/${EXISTING_FLOW}`)).json.data?.label).toBe('After'); + }); + + it('(e) a /meta flow naming the unregistered notify channel `smss` is refused 422 flow-notify-channel-unregistered; nothing registers', async () => { + const put = await call('PUT', `/meta/flow/${SMSS_FLOW}?package=${pkg}`, notifyFlow(SMSS_FLOW, ['smss'])); + expect(put.status, put.text).toBe(422); + const issues = (put.json.issues ?? []) as Array<{ rule?: string; message?: string }>; + expect(issues.map((i) => i.rule), put.text).toEqual(['flow-notify-channel-unregistered']); + expect(issues[0]?.message).toContain("names channel 'smss'"); + + expect((await call('GET', `/automation/${SMSS_FLOW}`)).status).toBe(404); + expect(await storedRows('flow', SMSS_FLOW)).toEqual([]); + }); + + it('(e) control: the same flow naming the registered channel `email` saves and registers', async () => { + const put = await call('PUT', `/meta/flow/${EMAIL_FLOW}?package=${pkg}`, notifyFlow(EMAIL_FLOW, ['email'])); + expect(put.status, put.text).toBe(200); + expect((await call('GET', `/automation/${EMAIL_FLOW}`)).status).toBe(200); + }); +}); diff --git a/packages/qa/dogfood/test/parent-and-organization-write-guards.dogfood.test.ts b/packages/qa/dogfood/test/parent-and-organization-write-guards.dogfood.test.ts index a6b2f7ddb8b..a926e6c0434 100644 --- a/packages/qa/dogfood/test/parent-and-organization-write-guards.dogfood.test.ts +++ b/packages/qa/dogfood/test/parent-and-organization-write-guards.dogfood.test.ts @@ -38,6 +38,10 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; import { catalogPermissionSet } from './catalog-permission-set.js'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.showcase.custom'; const SYS = { isSystem: true } as const; const LINES = '/data/showcase_invoice_line'; @@ -97,11 +101,13 @@ describe('a detail write naming an unreadable header answers what a nonexistent beforeAll(async () => { stack = await bootShowcase(); admin = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, admin, 'com.example.showcase'); ql = await stack.kernel.getServiceAsync('objectql'); // A scratch set that writes tasks and selects no project: every member reads // projects through the stock baseline, so the set's row policy narrows it. - const saved = await stack.apiAs(admin, 'PUT', `/meta/permission/${TASK_WRITER}`, { + const saved = await stack.apiAs(admin, 'PUT', `/meta/permission/${TASK_WRITER}?package=${PAIR_PKG}`, { name: TASK_WRITER, label: 'QA task writer', systemPermissions: [], objects: { showcase_task: { allowRead: true, allowCreate: true, allowEdit: false, allowDelete: false } }, rowLevelSecurity: [{ diff --git a/packages/qa/dogfood/test/permission-metadata-door-reaches-catalog.dogfood.test.ts b/packages/qa/dogfood/test/permission-metadata-door-reaches-catalog.dogfood.test.ts index e7f2e4a9c4a..3de42bd6f07 100644 --- a/packages/qa/dogfood/test/permission-metadata-door-reaches-catalog.dogfood.test.ts +++ b/packages/qa/dogfood/test/permission-metadata-door-reaches-catalog.dogfood.test.ts @@ -19,6 +19,10 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; import { createSecurityCatalogReader } from '@objectstack/core'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.showcase.custom'; const SET = 'door_reach_auditor'; const SYS = { context: { isSystem: true } } as const; @@ -33,6 +37,8 @@ describe('a metadata-door permission save reaches the security catalog (ADR-0131 beforeAll(async () => { stack = await bootShowcase(); admin = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, admin, 'com.example.showcase'); await stack.signUp('door-reach@verify.test'); ql = await stack.kernel.getServiceAsync('objectql'); reader = createSecurityCatalogReader({ registry: ql.registry, metadata: stack.kernel.getService('metadata') }); @@ -54,7 +60,7 @@ describe('a metadata-door permission save reaches the security catalog (ADR-0131 }); it('a create: the catalog serves the saved body, and a grant naming it is accepted', async () => { - const saved = await stack.apiAs(admin, 'PUT', `/meta/permission/${SET}`, { + const saved = await stack.apiAs(admin, 'PUT', `/meta/permission/${SET}?package=${PAIR_PKG}`, { name: SET, label: 'Door v1', objects: { sys_user: { allowRead: true } }, }); expect(saved.status, await saved.clone().text()).toBe(200); @@ -67,7 +73,7 @@ describe('a metadata-door permission save reaches the security catalog (ADR-0131 }); it('an edit: the catalog serves the new body, not the one first saved', async () => { - const saved = await stack.apiAs(admin, 'PUT', `/meta/permission/${SET}`, { + const saved = await stack.apiAs(admin, 'PUT', `/meta/permission/${SET}?package=${PAIR_PKG}`, { name: SET, label: 'Door v2', objects: {}, }); expect(saved.status, await saved.clone().text()).toBe(200); diff --git a/packages/qa/dogfood/test/permission-set-clone-door.dogfood.test.ts b/packages/qa/dogfood/test/permission-set-clone-door.dogfood.test.ts index 255ae242b3a..523d0f10a2a 100644 --- a/packages/qa/dogfood/test/permission-set-clone-door.dogfood.test.ts +++ b/packages/qa/dogfood/test/permission-set-clone-door.dogfood.test.ts @@ -160,7 +160,7 @@ describe('the permission-set clone door, on a booted showcase', () => { // The copy is a real set: a holder resolves it. Distributed through a // position saved by name, so the leg needs no catalog row id. - const saved = await stack.apiAs(token, 'PUT', `/meta/position/${COPY_POSITION}`, { + const saved = await stack.apiAs(token, 'PUT', `/meta/position/${COPY_POSITION}?package=${SHOWCASE_PAIR}`, { name: COPY_POSITION, label: 'Holds the clone', permissionSets: [DEFAULT_COPY], }); expect(saved.status, await saved.clone().text()).toBe(200); @@ -229,39 +229,54 @@ describe('the permission-set clone door, on a booted showcase', () => { }); // [#29594, ruling record 6691217245] A kernel package has no paired - // customization package, so a platform set's copy is saved where an - // environment-authored set's copy is: environment-wide, the notice naming - // the kernel package and `package`. - it('a platform set (the lock-and-clone rule\'s commonest source) copies environment-wide: the kernel has no pair', async () => { + // customization package, so a platform set's copy has no package to land + // in by default. + // [#38174] a package-less create is refused (ADR-0070 D1) + it('a platform set (the lock-and-clone rule\'s commonest source) with no `package` is refused: the kernel has no pair, and nothing is stored', async () => { const reader = securityCatalogReaderOf(ql)!; const source = await reader.resolve('permission', 'member_default'); expect(source?.packageId, 'member_default is not packaged on this boot').toBeTruthy(); const res = await clone(token, 'member_default', { name: 'my_member_baseline', label: 'My Member Baseline' }); const text = await res.clone().text(); - expect(res.status, text).toBe(200); - const data = ((await res.json()) as any).data; - expect(data.package).toBeNull(); - expect(data.noticeCode).toBe('PERMISSION_SET_CLONE_ENVIRONMENT_WIDE_KERNEL_SOURCE'); - expect(data.notice).toContain(`kernel package '${source!.packageId}'`); - expect((await reader.resolve('permission', 'my_member_baseline'))?.packageId).toBeUndefined(); + expect(res.status, text).toBe(422); + const error = ((await res.json()) as any).error; + expect(error?.code).toBe('WRITABLE_PACKAGE_REQUIRED'); + expect(error?.message).toContain("Cannot clone permission set 'member_default' as 'my_member_baseline' with no package"); + expect(error?.message).toContain('Nothing was saved.'); + expect(await reader.resolve('permission', 'my_member_baseline')).toBeUndefined(); + const rows = await ql.find('sys_metadata', { where: { type: 'permission', name: 'my_member_baseline' }, context: SYSTEM_CTX }); + expect(rows).toEqual([]); expect((await stack.apiAs(token, 'GET', `/packages/${source!.packageId}.custom`)).status).toBe(404); }); - it('CONTROL — an environment-authored source still copies environment-wide, with no package', async () => { - const saved = await stack.apiAs(token, 'PUT', '/meta/permission/env_authored_source', { - name: 'env_authored_source', label: 'Env Authored', objects: { showcase_task: { allowRead: true } }, - }); + // [#38174] a package-less create is refused (ADR-0070 D1) + it('CONTROL — an environment-authored source with no `package` is refused alike, and copies into a named package', async () => { + // [#38174] The environment-authored (loose) source is seeded as the + // store writes it, then saved in place through the door. + const now = new Date().toISOString(); + const body = { name: 'env_authored_source', label: 'Env Authored', objects: { showcase_task: { allowRead: true } } }; + await ql.insert('sys_metadata', { + type: 'permission', name: 'env_authored_source', package_id: null, scope: 'platform', state: 'active', + version: 1, checksum: null, created_at: now, updated_at: now, metadata: JSON.stringify(body), + }, { context: SYSTEM_CTX }); + const saved = await stack.apiAs(token, 'PUT', '/meta/permission/env_authored_source', body); expect(saved.status, await saved.clone().text()).toBe(200); const source = await securityCatalogReaderOf(ql)!.resolve('permission', 'env_authored_source'); + expect(source?.name, 'the control source does not resolve').toBe('env_authored_source'); expect(source?.packageId, 'the control source is packaged').toBeUndefined(); const res = await clone(token, 'env_authored_source', { name: 'env_authored_copy', label: 'Env Authored Copy' }); - expect(res.status, await res.clone().text()).toBe(200); - expect(((await res.json()) as any).data.package).toBeNull(); - expect((await securityCatalogReaderOf(ql)!.resolve('permission', 'env_authored_copy'))?.packageId).toBeUndefined(); + expect(res.status, await res.clone().text()).toBe(422); + expect(((await res.json()) as any).error?.code).toBe('WRITABLE_PACKAGE_REQUIRED'); + expect(await securityCatalogReaderOf(ql)!.resolve('permission', 'env_authored_copy')).toBeUndefined(); const rows = await ql.find('sys_metadata', { where: { type: 'permission', name: 'env_authored_copy' }, context: SYSTEM_CTX }); - expect(rows.map((r) => r.package_id ?? null)).toEqual([null]); + expect(rows).toEqual([]); + + const landed = await clone(token, 'env_authored_source', { name: 'env_authored_copy', label: 'Env Authored Copy', package: SHOWCASE_PAIR }); + expect(landed.status, await landed.clone().text()).toBe(200); + expect(((await landed.json()) as any).data.package).toBe(SHOWCASE_PAIR); + expect((await securityCatalogReaderOf(ql)!.resolve('permission', 'env_authored_copy'))?.packageId).toBe(SHOWCASE_PAIR); }); it('a taken name is 409, an unknown source 404, a bad name 400', async () => { diff --git a/packages/qa/dogfood/test/permission-unknown-grant-object-refusal.dogfood.test.ts b/packages/qa/dogfood/test/permission-unknown-grant-object-refusal.dogfood.test.ts index 195230b434c..ef9783fcb7e 100644 --- a/packages/qa/dogfood/test/permission-unknown-grant-object-refusal.dogfood.test.ts +++ b/packages/qa/dogfood/test/permission-unknown-grant-object-refusal.dogfood.test.ts @@ -27,6 +27,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; const PKG = 'app.grantprobe28990'; /** The batch control's own package, so no other case's draft rides in its batch. */ @@ -102,7 +103,10 @@ describe('dogfood: a permission-set grant on an object that does not exist is re ["the `'*'` wildcard", '*'], ])('control: a live save granting on %s saves', async (_label, objectName) => { const name = `grantprobe_ok_${objectName === '*' ? 'wildcard' : objectName}`; - const saved = await call('PUT', `/meta/permission/${name}`, set(name, [objectName])); + // [#38174] A new item is created into a writable package (ADR-0070 D1): the + // showcase's `.custom` pair, whose closure holds the showcase object. + const pair = await ensurePair(stack, token, 'com.example.showcase'); + const saved = await call('PUT', `/meta/permission/${name}?package=${pair}`, set(name, [objectName])); expect(saved.status, JSON.stringify(saved.json)).toBe(200); }); diff --git a/packages/qa/dogfood/test/personal-view-row-scope.dogfood.test.ts b/packages/qa/dogfood/test/personal-view-row-scope.dogfood.test.ts index adaef8a4793..826b6a1bbc9 100644 --- a/packages/qa/dogfood/test/personal-view-row-scope.dogfood.test.ts +++ b/packages/qa/dogfood/test/personal-view-row-scope.dogfood.test.ts @@ -52,6 +52,10 @@ import { bootShowcase } from './showcase-boot.js'; import { showcaseAppDefaultSecurity } from './showcase-security.js'; import { catalogPermissionSet } from './catalog-permission-set.js'; import { hostedDispatcherDoor, type HostedDoorCall } from './hosted-dispatcher.testkit.js'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.showcase.custom'; const OBJ = 'sys_personal_view'; const TARGET = 'showcase_project'; @@ -104,6 +108,8 @@ describe('sys_personal_view over REST: a reader\'s own named list views (ruling beforeAll(async () => { stack = await bootShowcase({ security: showcaseAppDefaultSecurity() }); adminTok = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, adminTok, 'com.example.showcase'); aliceTok = await stack.signUp(ALICE); bobTok = await stack.signUp(BOB); carolTok = await stack.signUp(CAROL); @@ -117,7 +123,7 @@ describe('sys_personal_view over REST: a reader\'s own named list views (ruling // BOB is the predicate persona: a scratch set hides `showcase_project.budget` // from him, authored through the metadata door like // `showcase-fls-read-mask-strip.dogfood.test.ts`'s. - const authored = await stack.apiAs(adminTok, 'PUT', `/meta/permission/${SCRATCH_SET}`, { + const authored = await stack.apiAs(adminTok, 'PUT', `/meta/permission/${SCRATCH_SET}?package=${PAIR_PKG}`, { name: SCRATCH_SET, label: 'Scratch: FLS read deny on showcase_project.budget (personal views)', description: 'Test-authored: a field the predicate persona cannot read.', diff --git a/packages/qa/dogfood/test/position-in-package-binds-outside-sets-38149.dogfood.test.ts b/packages/qa/dogfood/test/position-in-package-binds-outside-sets-38149.dogfood.test.ts index 45c70e9c5d3..3c7d10f76bd 100644 --- a/packages/qa/dogfood/test/position-in-package-binds-outside-sets-38149.dogfood.test.ts +++ b/packages/qa/dogfood/test/position-in-package-binds-outside-sets-38149.dogfood.test.ts @@ -87,7 +87,15 @@ describe('a position created into a writable package binds sets from outside it' expect(live.status, `publish ${type}/${name}: ${live.text}`).toBe(200); }; /** The environment scope's create: a set written live, naming no package. */ + // [#38174] A loose (package-less) set is a legacy row: no door creates one any + // more (ADR-0070 D1). It is seeded directly, then saved in place, which stays open. const createLoose = async (name: string) => { + const now = new Date().toISOString(); + await ql.insert('sys_metadata', { + type: 'permission', name, package_id: null, scope: 'platform', + state: 'active', version: 1, checksum: null, created_at: now, updated_at: now, + metadata: JSON.stringify({ name, label: name, objects: {} }), + }, { context: { isSystem: true, positions: [], permissions: [] } }); const saved = await call('PUT', `/meta/permission/${name}`, { name, label: name, objects: {} }); expect(saved.status, `loose permission/${name}: ${saved.text}`).toBe(200); }; diff --git a/packages/qa/dogfood/test/print-service-named-page.dogfood.test.ts b/packages/qa/dogfood/test/print-service-named-page.dogfood.test.ts index a7f930e5fbb..b7bbd2d632d 100644 --- a/packages/qa/dogfood/test/print-service-named-page.dogfood.test.ts +++ b/packages/qa/dogfood/test/print-service-named-page.dogfood.test.ts @@ -32,6 +32,9 @@ import { PrintService, type PrintEngine } from '../../../services/service-print/ import type { IDataEngine } from '@objectstack/spec/contracts'; import { PROJECT_BRIEF_PAGE } from './print-named-page.fixture.js'; +/** [#38174] The writable package the brief page is created in. */ +const BRIEF_PACKAGE = 'com.dogfood.printbrief'; + const SYS = { isSystem: true } as const; const CONSOLE = 'http://127.0.0.1:1/_console'; const PDF = Buffer.from('%PDF-1.4\n% named print page dogfood\n%%EOF\n'); @@ -82,8 +85,19 @@ describe('a record printed on a print page that is not its object’s default re }); ql = stack.kernel.getService('objectql'); // The brief is added the way an author adds a page: through the metadata save door. - const protocol = await stack.kernel.getServiceAsync<{ saveMetaItem(r: Record): Promise }>('protocol'); - await protocol.saveMetaItem({ type: 'page', name: PROJECT_BRIEF_PAGE.name, item: PROJECT_BRIEF_PAGE }); + const protocol = await stack.kernel.getServiceAsync<{ + saveMetaItem(r: Record): Promise; + installPackage(r: Record): Promise; + }>('protocol'); + // [#38174] A new item is created into a writable package (ADR-0070 D1): one + // created as Studio's "New package" does, depending on the showcase whose object the page binds. + await protocol.installPackage({ + manifest: { + id: BRIEF_PACKAGE, name: 'Print brief', version: '0.1.0', type: 'app', namespace: 'printbrief', + dependencies: { 'com.example.showcase': '*' }, + }, + }); + await protocol.saveMetaItem({ type: 'page', name: PROJECT_BRIEF_PAGE.name, item: PROJECT_BRIEF_PAGE, packageId: BRIEF_PACKAGE }); const [seeded] = await ql.find('showcase_project', { limit: 1 }, { context: SYS }); project = String(seeded!.id); projectName = String(seeded!.name); diff --git a/packages/qa/dogfood/test/record-currency-follow-save-door.dogfood.test.ts b/packages/qa/dogfood/test/record-currency-follow-save-door.dogfood.test.ts index 9bb301d5475..254ca20c3bc 100644 --- a/packages/qa/dogfood/test/record-currency-follow-save-door.dogfood.test.ts +++ b/packages/qa/dogfood/test/record-currency-follow-save-door.dogfood.test.ts @@ -27,6 +27,10 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { bootStack, type VerifyStack } from '@objectstack/verify'; import { defineStack } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The fixture's writable `.custom` pair. */ +const PAIR = 'com.dogfood.record-currency-follow-save-door.custom'; const object = (name: string, fields: Record) => ObjectSchema.create({ name, label: name, pluralLabel: name, sharingModel: 'public_read_write', fields } as never); @@ -94,6 +98,8 @@ describe('the /meta save door asks the record-currency doors that read other obj beforeAll(async () => { stack = await bootStack(fixtureStack as unknown as Parameters[0]); token = await stack.signIn(); + // [#38174] The writable package new objects are created in (ADR-0070 D1). + await ensurePair(stack, token, 'com.dogfood.record-currency-follow-save-door'); ql = await stack.kernel.getServiceAsync('objectql'); }, 180_000); @@ -148,29 +154,31 @@ describe('the /meta save door asks the record-currency doors that read other obj }); it('CONTROL: a child following its parent\'s code field saves 200 and registers', async () => { - const saved = await call('PUT', '/meta/object/rcf_good_line', lineBody('rcf_good_line', 'invoice.currency_code')); + // [#38174] A new object is created into a writable package (ADR-0070 D1): + // the fixture's `.custom` pair, whose namespace prefix (`rcf_custom_`) it carries. + const saved = await call('PUT', `/meta/object/rcf_custom_good_line?package=${PAIR}`, lineBody('rcf_custom_good_line', 'invoice.currency_code')); expect(saved.status, JSON.stringify(saved.json)).toBe(200); - expect(ql.registry.getObject('rcf_good_line')).toBeDefined(); + expect(ql.registry.getObject('rcf_custom_good_line')).toBeDefined(); }); it('the per-item publish of a draft that follows no code is refused 422, and the published row and registered object stay as they were', async () => { - const name = 'rcf_pub_line'; + const name = 'rcf_custom_pub_line'; // [#38174] created into the fixture's `.custom` pair const followed = (json: any) => json?.item?.fields?.amount?.currencyConfig?.currencyField ?? json?.fields?.amount?.currencyConfig?.currencyField; // A published, registered child following the parent's code field. - expect((await call('PUT', `/meta/object/${name}`, lineBody(name, 'invoice.currency_code'))).status).toBe(200); + expect((await call('PUT', `/meta/object/${name}?package=${PAIR}`, lineBody(name, 'invoice.currency_code'))).status).toBe(200); const before = await call('GET', `/meta/object/${name}`); expect(followed(before.json), JSON.stringify(before.json).slice(0, 400)).toBe('invoice.currency_code'); // A draft repointing it at a field that holds no code saves (the re-point // is a destructive change, acknowledged with `force`): a draft is judged // at its publish. - const draft = await call('PUT', `/meta/object/${name}?mode=draft&force=true`, lineBody(name, 'invoice.title')); + const draft = await call('PUT', `/meta/object/${name}?mode=draft&force=true&package=${PAIR}`, lineBody(name, 'invoice.title')); expect(draft.status, JSON.stringify(draft.json)).toBe(200); - const published = await call('POST', `/meta/object/${name}/publish`, {}); + const published = await call('POST', `/meta/object/${name}/publish?package=${PAIR}`, {}); expect(published.status, JSON.stringify(published.json)).toBe(422); expect(codeOf(published.json)).toBe('INVALID_METADATA'); expect(messageOf(published.json)).toContain( - "Object 'rcf_pub_line' field 'amount' currencyConfig.currencyField: 'invoice.title' follows 'rcf_invoice.title', a 'text' field that does not hold an ISO 4217 code", + "Object 'rcf_custom_pub_line' field 'amount' currencyConfig.currencyField: 'invoice.title' follows 'rcf_invoice.title', a 'text' field that does not hold an ISO 4217 code", ); const after = await call('GET', `/meta/object/${name}`); expect(after.status).toBe(200); @@ -179,10 +187,10 @@ describe('the /meta save door asks the record-currency doors that read other obj }); it('the per-item publish of a NEW object\'s draft that follows no code is refused 422, and nothing is published or registered', async () => { - const name = 'rcf_pub_new_line'; - const draft = await call('PUT', `/meta/object/${name}?mode=draft`, lineBody(name, 'invoice.title')); + const name = 'rcf_custom_pub_new_line'; // [#38174] created into the fixture's `.custom` pair + const draft = await call('PUT', `/meta/object/${name}?mode=draft&package=${PAIR}`, lineBody(name, 'invoice.title')); expect(draft.status, JSON.stringify(draft.json)).toBe(200); - const published = await call('POST', `/meta/object/${name}/publish`, {}); + const published = await call('POST', `/meta/object/${name}/publish?package=${PAIR}`, {}); expect(published.status, JSON.stringify(published.json)).toBe(422); expect(codeOf(published.json)).toBe('INVALID_METADATA'); expect(messageOf(published.json)).toContain("'rcf_invoice.title', a 'text' field that does not hold an ISO 4217 code"); diff --git a/packages/qa/dogfood/test/rule-hop-undeclared-related-field.dogfood.test.ts b/packages/qa/dogfood/test/rule-hop-undeclared-related-field.dogfood.test.ts index 24de878f445..1941c91d47d 100644 --- a/packages/qa/dogfood/test/rule-hop-undeclared-related-field.dogfood.test.ts +++ b/packages/qa/dogfood/test/rule-hop-undeclared-related-field.dogfood.test.ts @@ -21,6 +21,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { ensurePair } from './customization-pair.js'; import { defineStack } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; @@ -110,7 +111,10 @@ describe('[#24468] a validation rule reading a field its lookup target does not }); it('control: the same object with only the rule reading a declared field saves', async () => { - const saved = await call('PUT', '/meta/object/rrh_order_ok', saveBody('rrh_order_ok', [validRule])); + // [#38174] A new object is created into a writable package (ADR-0070 D1): + // the fixture's `.custom` pair, whose namespace prefix (`rrh_custom_`) it carries. + const pair = await ensurePair(stack, token, 'com.dogfood.rule-hop-undeclared'); + const saved = await call('PUT', `/meta/object/rrh_custom_order_ok?package=${pair}`, saveBody('rrh_custom_order_ok', [validRule])); expect(saved.status, JSON.stringify(saved.json)).toBe(200); }); diff --git a/packages/qa/dogfood/test/security-catalog-cold-boot-environment-holder.dogfood.test.ts b/packages/qa/dogfood/test/security-catalog-cold-boot-environment-holder.dogfood.test.ts index 027138f69a1..ff43c366d25 100644 --- a/packages/qa/dogfood/test/security-catalog-cold-boot-environment-holder.dogfood.test.ts +++ b/packages/qa/dogfood/test/security-catalog-cold-boot-environment-holder.dogfood.test.ts @@ -60,6 +60,19 @@ import { ObjectSchema, Field } from '@objectstack/spec/data'; import { NAMESPACE_CONFLICT_CODE } from '@objectstack/objectql'; import { bootStack, type VerifyStack } from '@objectstack/verify'; +/** [#38174] A legacy package-less row, inserted as the store writes one, with the system context. */ +async function seedLoose(stack: VerifyStack, type: string, name: string, body: Record): Promise { + const ql = (await stack.kernel.getServiceAsync('objectql')) as unknown as { + insert(object: string, data: Record, options?: unknown): Promise; + }; + const now = new Date().toISOString(); + await ql.insert('sys_metadata', { + type, name, package_id: null, scope: 'platform', + state: 'active', version: 1, checksum: null, created_at: now, updated_at: now, + metadata: JSON.stringify(body), + }, { context: { isSystem: true, positions: [], permissions: [] } }); +} + const SYS = { context: { isSystem: true } } as const; const BOOT_TIMEOUT = 300_000; @@ -157,6 +170,10 @@ describe('ADR-0048 N.3: a package-held position or permission-set name the envir const db = databaseFile(); stack = await bootStack(baseApp, { databaseFile: db }); const token = await stack.signIn(); + // [#38174] The environment's names are legacy loose rows (no door creates one, + // ADR-0070 D1): seeded directly, then saved in place, which stays open. + await seedLoose(stack, 'permission', SET, { name: SET, label: 'Saved in the environment', objects: {} }); + await seedLoose(stack, 'position', POSITION, { name: POSITION, label: 'Saved in the environment' }); const savedSet = await stack.apiAs(token, 'PUT', `/meta/permission/${SET}`, { name: SET, label: 'Saved in the environment', objects: {} }); expect(savedSet.status, JSON.stringify(await savedSet.clone().json().catch(() => ({})))).toBe(200); const savedPosition = await stack.apiAs(token, 'PUT', `/meta/position/${POSITION}`, { name: POSITION, label: 'Saved in the environment' }); @@ -260,6 +277,8 @@ describe('ADR-0048 N.3: a package-held position or permission-set name the envir const db = databaseFile(); stack = await bootStack(baseApp, { databaseFile: db }); const token = await stack.signIn(); + // [#38174] A legacy loose row, seeded directly, then saved in place (see above). + await seedLoose(stack, 'permission', SET, { name: SET, label: 'Saved in the environment', objects: {} }); const saved = await stack.apiAs(token, 'PUT', `/meta/permission/${SET}`, { name: SET, label: 'Saved in the environment', objects: {} }); expect(saved.status).toBe(200); await stack.stop(); diff --git a/packages/qa/dogfood/test/security-verdict-follows-runtime-metadata-change.dogfood.test.ts b/packages/qa/dogfood/test/security-verdict-follows-runtime-metadata-change.dogfood.test.ts index 899e14e2263..b4f3074b0ef 100644 --- a/packages/qa/dogfood/test/security-verdict-follows-runtime-metadata-change.dogfood.test.ts +++ b/packages/qa/dogfood/test/security-verdict-follows-runtime-metadata-change.dogfood.test.ts @@ -40,6 +40,10 @@ import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; import { SecurityPlugin } from '@objectstack/plugin-security'; import { assertArmed, principalArmed } from './armed.js'; import { catalogPermissionSet } from './catalog-permission-set.js'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The probe's writable `.custom` pair, where its runtime objects are created. */ +const PAIR = 'com.example.verdictfollowsmeta.custom'; const UPDATE_FLOOR = "the platform's wildcard row-level update floor (`owner_only_writes`, positions ['org_member'])"; @@ -52,11 +56,13 @@ const UPDATE_FLOOR_DISARM = const CAP = 'vfm_gate_capability'; /** The five objects, one per case, each saved at runtime by the admin. */ -const OPENS = 'vfm_opens'; // A: private → public_read_write -const CLOSES = 'vfm_closes'; // B: public_read_write → public_read -const POSTURE = 'vfm_posture'; // C: access public → private -const GATED = 'vfm_gated'; // D: requiredPermissions added -const GROWS = 'vfm_grows'; // E: a field added after first use +// [#38174] Each object is created into the probe's writable `.custom` pair (ADR-0070 D1), +// so it carries that pair's namespace prefix (`vfm_custom_`). +const OPENS = 'vfm_custom_opens'; // A: private → public_read_write +const CLOSES = 'vfm_custom_closes'; // B: public_read_write → public_read +const POSTURE = 'vfm_custom_posture'; // C: access public → private +const GATED = 'vfm_custom_gated'; // D: requiredPermissions added +const GROWS = 'vfm_custom_grows'; // E: a field added after first use /** * Every member holds a wildcard CRUD grant and authors no row-level policy, so @@ -124,7 +130,7 @@ describe('[#26596, #26698] the authorization verdict follows a runtime metadata /** The admin saves through the metadata door and the door reports what it stored. */ const save = async (body: Record) => { - const res = await stack.apiAs(adminToken, 'PUT', `/meta/object/${body.name}`, body); + const res = await stack.apiAs(adminToken, 'PUT', `/meta/object/${body.name}?package=${PAIR}`, body); const out = await json(res); expect(res.status, `PUT /meta/object/${body.name}: ${JSON.stringify(out)}`).toBe(200); const read = await stack.apiAs(adminToken, 'GET', `/meta/object/${body.name}`); @@ -181,6 +187,7 @@ describe('[#26596, #26698] the authorization verdict follows a runtime metadata ]); // Each object's FIRST declaration, saved at runtime. + await ensurePair(stack, adminToken, 'com.example.verdictfollowsmeta'); await save(objectBody(OPENS, { sharingModel: 'private' })); await save(objectBody(CLOSES, { sharingModel: 'public_read_write' })); await save(objectBody(POSTURE, { sharingModel: 'public_read_write' })); diff --git a/packages/qa/dogfood/test/sharing-rule-org-less-caller.dogfood.test.ts b/packages/qa/dogfood/test/sharing-rule-org-less-caller.dogfood.test.ts index f179dfc31cd..4c383cfc535 100644 --- a/packages/qa/dogfood/test/sharing-rule-org-less-caller.dogfood.test.ts +++ b/packages/qa/dogfood/test/sharing-rule-org-less-caller.dogfood.test.ts @@ -70,6 +70,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; import { leaveOrganization } from './armed.js'; import { catalogPermissionSet } from './catalog-permission-set.js'; import { relaxTenantColumns } from './pre-18-tenant-column.testkit.js'; @@ -132,7 +133,7 @@ describe('#8158 — a manage_sharing holder with NO active organization cannot r beforeAll(async () => { stack = await bootShowcase(); - await stack.signIn(); // the first user: the bootstrap account + const adminTok = await stack.signIn(); // the first user: the bootstrap account ql = await stack.kernel.getServiceAsync('objectql'); // Two tenants — the anti-vacuity premise. @@ -147,10 +148,13 @@ describe('#8158 — a manage_sharing holder with NO active organization cannot r // precisely the caller who holds the org capability and no platform one. // Saved through the metadata door, the security catalog's one write path // (ADR-0131 D3): a grant names it, and the resolver reads it from there. + // [#38174] A new item is created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + const pair = await ensurePair(stack, adminTok, 'com.example.showcase'); const protocol = (await stack.kernel.getServiceAsync('protocol')) as any; await protocol.saveMetaItem({ type: 'permission', name: 'sharing_admin_8158', + packageId: pair, item: { name: 'sharing_admin_8158', label: 'Sharing Administrator (org-scoped)', objects: {}, systemPermissions: ['manage_sharing'] }, }); diff --git a/packages/qa/dogfood/test/showcase-fls-read-mask-strip.dogfood.test.ts b/packages/qa/dogfood/test/showcase-fls-read-mask-strip.dogfood.test.ts index 3f5dce51b47..2e0fe92ecdf 100644 --- a/packages/qa/dogfood/test/showcase-fls-read-mask-strip.dogfood.test.ts +++ b/packages/qa/dogfood/test/showcase-fls-read-mask-strip.dogfood.test.ts @@ -75,6 +75,10 @@ import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; import { showcaseAppDefaultSecurity } from './showcase-security.js'; import { catalogPermissionSet } from './catalog-permission-set.js'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.showcase.custom'; const SYS = { isSystem: true } as const; @@ -105,6 +109,8 @@ describe('showcase FLS read side: a readable:false field is STRIPPED, not masked beforeAll(async () => { stack = await bootShowcase({ security: showcaseAppDefaultSecurity() }); adminTok = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, adminTok, 'com.example.showcase'); memberTok = await stack.signUp(MEMBER); ql = await stack.kernel.getServiceAsync('objectql'); @@ -119,7 +125,7 @@ describe('showcase FLS read side: a readable:false field is STRIPPED, not masked // this set has no ledger row, so it is in effect. // [ADR-0131 D3/D4] Authored through the metadata door, the security // catalog's write path: the definition it stores is what the resolver reads. - const authored = await stack.apiAs(adminTok, 'PUT', `/meta/permission/${SCRATCH_SET}`, { + const authored = await stack.apiAs(adminTok, 'PUT', `/meta/permission/${SCRATCH_SET}?package=${PAIR_PKG}`, { name: SCRATCH_SET, label: 'Scratch: FLS read deny on showcase_project.budget', description: diff --git a/packages/qa/dogfood/test/showcase-mcp-aggregate-filter.dogfood.test.ts b/packages/qa/dogfood/test/showcase-mcp-aggregate-filter.dogfood.test.ts index b8e28ad184c..7e48ca0685b 100644 --- a/packages/qa/dogfood/test/showcase-mcp-aggregate-filter.dogfood.test.ts +++ b/packages/qa/dogfood/test/showcase-mcp-aggregate-filter.dogfood.test.ts @@ -39,6 +39,10 @@ import { MCPServerPlugin } from '@objectstack/mcp'; import { bootShowcase } from './showcase-boot.js'; import { showcaseAppDefaultSecurity } from './showcase-security.js'; import { catalogPermissionSet } from './catalog-permission-set.js'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.showcase.custom'; const SYS = { isSystem: true } as const; const OBJECT = 'showcase_project'; @@ -101,6 +105,8 @@ describe('showcase: MCP aggregate_records honours a per-aggregation filter as RE security: showcaseAppDefaultSecurity(), }); adminTok = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, adminTok, 'com.example.showcase'); memberTok = await stack.signUp(MEMBER); ql = await stack.kernel.getServiceAsync('objectql'); @@ -108,7 +114,7 @@ describe('showcase: MCP aggregate_records honours a per-aggregation filter as RE // baseline already grants read on `showcase_project`, so the set adds // nothing but the field deny. Object-qualified key (a bare `budget` key // enforces nothing). - const authored = await stack.apiAs(adminTok, 'PUT', `/meta/permission/${SCRATCH_SET}`, { + const authored = await stack.apiAs(adminTok, 'PUT', `/meta/permission/${SCRATCH_SET}?package=${PAIR_PKG}`, { name: SCRATCH_SET, label: 'Scratch: FLS read deny on showcase_project.budget (#28550)', objects: {}, diff --git a/packages/qa/dogfood/test/showcase-mcp-describe-object-field-mask.dogfood.test.ts b/packages/qa/dogfood/test/showcase-mcp-describe-object-field-mask.dogfood.test.ts index 41c399a6f8a..9c79963cc4a 100644 --- a/packages/qa/dogfood/test/showcase-mcp-describe-object-field-mask.dogfood.test.ts +++ b/packages/qa/dogfood/test/showcase-mcp-describe-object-field-mask.dogfood.test.ts @@ -37,6 +37,10 @@ import type { IDataEngine } from '@objectstack/spec/contracts'; import { bootShowcase } from './showcase-boot.js'; import { showcaseAppDefaultSecurity } from './showcase-security.js'; import { catalogPermissionSet } from './catalog-permission-set.js'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.showcase.custom'; const SYS = { isSystem: true } as const; const OBJECT = 'showcase_project'; @@ -172,7 +176,7 @@ describe('showcase: MCP describe_object answers the field-masked object schema t /** Author a scratch permission set through the metadata door and grant it to `email`. */ async function grantScratchSet(name: string, fields: Record, email: string) { - const authored = await stack.apiAs(tokens.admin!, 'PUT', `/meta/permission/${name}`, { + const authored = await stack.apiAs(tokens.admin!, 'PUT', `/meta/permission/${name}?package=${PAIR_PKG}`, { name, label: `Scratch: ${name}`, description: 'Test-authored: an object-schema field deny for the MCP describe_object parity pin.', @@ -204,6 +208,8 @@ describe('showcase: MCP describe_object answers the field-masked object schema t security: showcaseAppDefaultSecurity(), }); tokens.admin = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, tokens.admin, 'com.example.showcase'); tokens.member = await stack.signUp(MEMBER); tokens.peer = await stack.signUp(PEER); tokens.walled = await stack.signUp(WALLED); diff --git a/packages/qa/dogfood/test/showcase-scope-depth-fallback.dogfood.test.ts b/packages/qa/dogfood/test/showcase-scope-depth-fallback.dogfood.test.ts index 1ddfb16aaea..a543cb9fd59 100644 --- a/packages/qa/dogfood/test/showcase-scope-depth-fallback.dogfood.test.ts +++ b/packages/qa/dogfood/test/showcase-scope-depth-fallback.dogfood.test.ts @@ -21,6 +21,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; import { SecurityPlugin, appDefaultPermissionSetName } from '@objectstack/plugin-security'; const OBJ = '/data/showcase_private_note'; @@ -60,6 +61,8 @@ async function bootFallbackWorld(withResolver = true): Promise { }), }); const adminToken = await stack.signIn(); + // [#38174] A new item is created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + const pair = await ensurePair(stack, adminToken, 'com.example.showcase'); const tokens = {} as Record; for (const who of WHO) tokens[who] = await stack.signUp(`fb-${who}@verify.test`); @@ -93,7 +96,7 @@ async function bootFallbackWorld(withResolver = true): Promise { // catalog the named fallback resolves through (the SecurityPlugin's catalog // loader, ADR-0131 D3/D4; a `sys_permission_set` row is not read). // `readScope` rides inside `objects`. - const saveProfile = () => stack.apiAs(adminToken, 'PUT', `/meta/permission/${PROFILE_NAME}`, { + const saveProfile = () => stack.apiAs(adminToken, 'PUT', `/meta/permission/${PROFILE_NAME}?package=${pair}`, { name: PROFILE_NAME, label: DEFAULT_PROFILE_METADATA.label, objects: DEFAULT_PROFILE_METADATA.objects, diff --git a/packages/qa/dogfood/test/stored-connector-package-ref-restart.dogfood.test.ts b/packages/qa/dogfood/test/stored-connector-package-ref-restart.dogfood.test.ts index 8a79d25fd77..69170d7e92a 100644 --- a/packages/qa/dogfood/test/stored-connector-package-ref-restart.dogfood.test.ts +++ b/packages/qa/dogfood/test/stored-connector-package-ref-restart.dogfood.test.ts @@ -146,24 +146,42 @@ describe('dogfood: a stored connector entry refused its package-relative ref doe const first = await bootShowcase({ databaseFile }); try { const token = await first.signIn(); - saves[ENV_FILE] = await json(await first.apiAs(token, 'PUT', `/meta/connector/${ENV_FILE}`, openapi(ENV_FILE, FILE_REF))); - saves[ENV_CWD] = await json(await first.apiAs(token, 'PUT', `/meta/connector/${ENV_CWD}`, { + // [#38174] An environment-wide (package-less) entry is a legacy loose row: + // no door creates one any more (ADR-0070 D1). Each is seeded directly, then + // saved in place through the metadata door, which stays open. + const ql = (await first.kernel.getServiceAsync('objectql')) as unknown as { + insert(object: string, data: Record, options?: unknown): Promise; + }; + const seedLoose = async (name: string, body: Record) => { + const now = new Date().toISOString(); + await ql.insert('sys_metadata', { + type: 'connector', name, package_id: null, scope: 'platform', + state: 'active', version: 1, checksum: null, created_at: now, updated_at: now, + metadata: JSON.stringify(body), + }, { context: { isSystem: true, positions: [], permissions: [] } }); + }; + const envCwd = { name: ENV_CWD, label: 'Stored stdio', type: 'api', provider: 'mcp', providerConfig: { transport: { kind: 'stdio', command: 'node', args: ['./scripts/mcp-fixture.mjs'] } }, - })); + }; + const unknownProvider = { ...openapi(UNKNOWN_PROVIDER, DOCUMENT), provider: 'no_such_provider' }; + await seedLoose(ENV_FILE, openapi(ENV_FILE, FILE_REF)); + await seedLoose(ENV_CWD, envCwd); + await seedLoose(UNKNOWN_PROVIDER, unknownProvider); + await seedLoose(PLUGIN_NAME, openapi(PLUGIN_NAME, DOCUMENT)); + await seedLoose(INLINE, openapi(INLINE, DOCUMENT)); + saves[ENV_FILE] = await json(await first.apiAs(token, 'PUT', `/meta/connector/${ENV_FILE}`, openapi(ENV_FILE, FILE_REF))); + saves[ENV_CWD] = await json(await first.apiAs(token, 'PUT', `/meta/connector/${ENV_CWD}`, envCwd)); saves.package = await json(await first.apiAs(token, 'POST', '/packages', { id: AUTHORED_PACKAGE_ID, name: 'Stored connector restart', version: '1.0.0', type: 'app', })); saves[AUTHORED_FILE] = await json(await first.apiAs( token, 'PUT', `/meta/connector/${AUTHORED_FILE}?package=${AUTHORED_PACKAGE_ID}`, openapi(AUTHORED_FILE, FILE_REF), )); - saves[UNKNOWN_PROVIDER] = await json(await first.apiAs(token, 'PUT', `/meta/connector/${UNKNOWN_PROVIDER}`, { - ...openapi(UNKNOWN_PROVIDER, DOCUMENT), - provider: 'no_such_provider', - })); + saves[UNKNOWN_PROVIDER] = await json(await first.apiAs(token, 'PUT', `/meta/connector/${UNKNOWN_PROVIDER}`, unknownProvider)); saves[PLUGIN_NAME] = await json(await first.apiAs(token, 'PUT', `/meta/connector/${PLUGIN_NAME}`, openapi(PLUGIN_NAME, DOCUMENT))); saves[INLINE] = await json(await first.apiAs(token, 'PUT', `/meta/connector/${INLINE}`, openapi(INLINE, DOCUMENT))); before = await settle(first, token, [INLINE]); diff --git a/packages/qa/dogfood/test/stored-connector-package-ref.dogfood.test.ts b/packages/qa/dogfood/test/stored-connector-package-ref.dogfood.test.ts index c6abda55865..57dfbfa13fa 100644 --- a/packages/qa/dogfood/test/stored-connector-package-ref.dogfood.test.ts +++ b/packages/qa/dogfood/test/stored-connector-package-ref.dogfood.test.ts @@ -161,15 +161,32 @@ describe('dogfood: a stored connector entry\'s package-relative ref is refused, ql = await stack.kernel.getServiceAsync('objectql'); token = await stack.signIn(); + // [#38174] An environment-wide (package-less) entry is a legacy loose row: no + // door creates one any more (ADR-0070 D1). Each is seeded directly, then saved + // in place through the metadata door, which stays open. + const seedLoose = async (name: string, body: Record) => { + const now = new Date().toISOString(); + await ql.insert('sys_metadata', { + type: 'connector', name, package_id: null, scope: 'platform', + state: 'active', version: 1, checksum: null, created_at: now, updated_at: now, + metadata: JSON.stringify(body), + }, { context: SYSTEM }); + }; + const envCwd = { + name: ENV_CWD, + label: 'Stored stdio', + type: 'api', + provider: 'mcp', + providerConfig: { transport: { kind: 'stdio', command: 'node', args: ['./scripts/mcp-fixture.mjs'] } }, + }; + await seedLoose(ENV_FILE, openapi(ENV_FILE, FILE_REF)); + await seedLoose(ENV_CWD, envCwd); + await seedLoose(SELF_STAMPED, openapi(SELF_STAMPED, FILE_REF)); + await seedLoose(INLINE, openapi(INLINE, DOCUMENT)); + await seedLoose(BY_URL, openapi(BY_URL, documentUrl)); const captured = await captureOutput(async () => { saves[ENV_FILE] = await json(await stack.apiAs(token, 'PUT', `/meta/connector/${ENV_FILE}`, openapi(ENV_FILE, FILE_REF))); - saves[ENV_CWD] = await json(await stack.apiAs(token, 'PUT', `/meta/connector/${ENV_CWD}`, { - name: ENV_CWD, - label: 'Stored stdio', - type: 'api', - provider: 'mcp', - providerConfig: { transport: { kind: 'stdio', command: 'node', args: ['./scripts/mcp-fixture.mjs'] } }, - })); + saves[ENV_CWD] = await json(await stack.apiAs(token, 'PUT', `/meta/connector/${ENV_CWD}`, envCwd)); authoredPackage = await json(await stack.apiAs(token, 'POST', '/packages', { id: AUTHORED_PACKAGE_ID, name: 'Stored connector refs', version: '1.0.0', type: 'app', })); diff --git a/packages/qa/dogfood/test/stored-expression-fill-at-change.dogfood.test.ts b/packages/qa/dogfood/test/stored-expression-fill-at-change.dogfood.test.ts index b513b3146de..c2cd085863d 100644 --- a/packages/qa/dogfood/test/stored-expression-fill-at-change.dogfood.test.ts +++ b/packages/qa/dogfood/test/stored-expression-fill-at-change.dogfood.test.ts @@ -27,6 +27,10 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { bootStack, type VerifyStack } from '@objectstack/verify'; import { cel, defineStack } from '@objectstack/spec'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.dogfood.stored-expression-fill.custom'; const stackDef = defineStack({ manifest: { @@ -92,7 +96,7 @@ describe('dogfood: a formula turned into a stored number on a populated object i /** A live object whose `days` is a formula, holding the three requests. */ const populated = async (object: string) => { - const saved = await call('PUT', `/meta/object/${object}`, definition(object, FORMULA)); + const saved = await call('PUT', `/meta/object/${object}?package=${PAIR_PKG}`, definition(object, FORMULA)); expect(saved.status, JSON.stringify(saved.json)).toBe(200); for (const [start_day, end_day] of REQUESTS) { const created = await call('POST', `/data/${object}`, { title: `from ${start_day}`, start_day, end_day }); @@ -106,6 +110,9 @@ describe('dogfood: a formula turned into a stored number on a populated object i beforeAll(async () => { stack = await bootStack(stackDef); token = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the fixture's `.custom` pair, + // whose namespace prefix (`dfsx_custom_`) each object carries. + await ensurePair(stack, token, 'com.dogfood.stored-expression-fill'); }, 300_000); afterAll(async () => { @@ -113,14 +120,14 @@ describe('dogfood: a formula turned into a stored number on a populated object i }); it('PUT /meta/object: the save fills the rows, says how many, and the dataset sum reads 6', async () => { - const object = 'dfsx_leave'; + const object = 'dfsx_custom_leave'; await populated(object); // CONTROL: the formula reads each row's days, and there is no column to total. const read = await call('GET', `/data/${object}?limit=10`); expect(read.status, JSON.stringify(read.json)).toBe(200); expect((read.json?.records ?? []).map((r: any) => r.days).sort()).toEqual([1, 2, 3]); - const saved = await call('PUT', `/meta/object/${object}`, definition(object, STORED)); + const saved = await call('PUT', `/meta/object/${object}?package=${PAIR_PKG}`, definition(object, STORED)); expect(saved.status, JSON.stringify(saved.json)).toBe(200); const [notice] = filledNotice(saved.json); @@ -133,10 +140,10 @@ describe('dogfood: a formula turned into a stored number on a populated object i }); it('draft, then POST /meta/object/:name/publish: the publish fills the rows and the dataset sum reads 6', async () => { - const object = 'dfsx_leave_draft'; + const object = 'dfsx_custom_leave_draft'; await populated(object); - const draft = await call('PUT', `/meta/object/${object}?mode=draft`, definition(object, STORED)); + const draft = await call('PUT', `/meta/object/${object}?mode=draft&package=${PAIR_PKG}`, definition(object, STORED)); expect(draft.status, JSON.stringify(draft.json)).toBe(200); // A draft is not live: nothing is filled yet. expect(filledNotice(draft.json)).toEqual([]); @@ -145,7 +152,7 @@ describe('dogfood: a formula turned into a stored number on a populated object i expect(beforePublish.status, JSON.stringify(beforePublish.json)).toBe(400); expect(beforePublish.json?.code, JSON.stringify(beforePublish.json)).toBe('DATASET_INVALID'); - const published = await call('POST', `/meta/object/${object}/publish`, {}); + const published = await call('POST', `/meta/object/${object}/publish?package=${PAIR_PKG}`, {}); expect(published.status, JSON.stringify(published.json)).toBe(200); const [notice] = filledNotice(published.json); diff --git a/packages/qa/dogfood/test/upsert-by-id-caller-read.dogfood.test.ts b/packages/qa/dogfood/test/upsert-by-id-caller-read.dogfood.test.ts index 64abb8201e6..361d50564c8 100644 --- a/packages/qa/dogfood/test/upsert-by-id-caller-read.dogfood.test.ts +++ b/packages/qa/dogfood/test/upsert-by-id-caller-read.dogfood.test.ts @@ -59,6 +59,10 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.example.showcase.custom'; const SYS = { isSystem: true } as const; const PASS = 'Upsert-Read-Pass-0001'; @@ -166,12 +170,14 @@ describe('upsert by id: a row the caller cannot read answers as a create naming beforeAll(async () => { stack = await bootShowcase(); adminTok = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, adminTok, 'com.example.showcase'); ql = await stack.kernel.getServiceAsync('objectql'); memberTok = await stack.signUp(MEMBER, PASS); // A principal who may CREATE contacts and do nothing else with them: no // read, no edit. The member baseline grants nothing on the object. - const saved = await stack.apiAs(adminTok, 'PUT', `/meta/permission/${CREATE_ONLY}`, { + const saved = await stack.apiAs(adminTok, 'PUT', `/meta/permission/${CREATE_ONLY}?package=${PAIR_PKG}`, { name: CREATE_ONLY, label: 'QA create-only contacts', systemPermissions: [], objects: { showcase_contact: { allowRead: false, allowCreate: true, allowEdit: false, allowDelete: false } }, }); @@ -350,13 +356,15 @@ describe('upsert by id: a row behind the organization wall answers as a create n process.env.OS_AUTH_MEMBERSHIP_POLICY = 'invite-only'; stack = await bootShowcase({ multiTenant: true }); adminTok = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the showcase's `.custom` pair. + await ensurePair(stack, adminTok, 'com.example.showcase'); ql = await stack.kernel.getServiceAsync('objectql'); for (const [set, grant] of [ [RW, { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: false }], [CREATE, { allowRead: true, allowCreate: true, allowEdit: false, allowDelete: false }], ] as const) { - const saved = await stack.apiAs(adminTok, 'PUT', `/meta/permission/${set}`, { + const saved = await stack.apiAs(adminTok, 'PUT', `/meta/permission/${set}?package=${PAIR_PKG}`, { name: set, label: set, systemPermissions: [], objects: { [OBJECT]: grant }, }); expect(saved.status, await saved.clone().text()).toBe(200); diff --git a/packages/qa/dogfood/test/view-container-cross-package-default.dogfood.test.ts b/packages/qa/dogfood/test/view-container-cross-package-default.dogfood.test.ts index a8bb3925888..571a2c523a6 100644 --- a/packages/qa/dogfood/test/view-container-cross-package-default.dogfood.test.ts +++ b/packages/qa/dogfood/test/view-container-cross-package-default.dogfood.test.ts @@ -195,8 +195,18 @@ describe('dogfood: a bare-list container on another package\'s object leaves its }); it('step 8: the same with no package — a package-less container leaves the packaged default alone', async () => { + // [#38174] A package-less CREATE is refused (ADR-0070 D1), so the loose + // container is seeded as the store writes it, and the door's save runs in place. + const ql = (await stack.kernel.getServiceAsync('objectql')) as unknown as { + insert(object: string, data: Record, options?: unknown): Promise; + }; + const now = new Date().toISOString(); + await ql.insert('sys_metadata', { + type: 'view', name: 'os_qa_shadow_probe2', package_id: null, scope: 'platform', state: 'active', + version: 1, checksum: null, created_at: now, updated_at: now, metadata: JSON.stringify(probe('os_qa_shadow_probe2')), + }, { context: { isSystem: true, positions: [], permissions: [] } }); const saved = await stack.apiAs(token, 'PUT', '/meta/view/os_qa_shadow_probe2', probe('os_qa_shadow_probe2')); - expect(saved.status).toBe(200); + expect(saved.status, await saved.clone().text()).toBe(200); await expectDefaultUnchangedOnBothDoors(); const own = named(await objectDoor(), `${OBJECT}.os_qa_shadow_probe2`); diff --git a/packages/qa/dogfood/test/wall-catalog-refusal.dogfood.test.ts b/packages/qa/dogfood/test/wall-catalog-refusal.dogfood.test.ts index 704e92839cd..072541f28b4 100644 --- a/packages/qa/dogfood/test/wall-catalog-refusal.dogfood.test.ts +++ b/packages/qa/dogfood/test/wall-catalog-refusal.dogfood.test.ts @@ -42,6 +42,10 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import crmStack from '@objectstack/example-crm'; import { resolveUserAuthzGrants } from '@objectstack/core'; import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package new catalog items are created in. */ +const CRM_PAIR = 'com.example.crm.custom'; const SYS = { isSystem: true, positions: [], permissions: [] }; @@ -109,12 +113,14 @@ for (const posture of ['isolated', 'group'] as const) { // exist; // B's member holds the shared set in org B. const rbac = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }; + // [#38174] New catalog items are created into a writable package (ADR-0070 D1): the CRM's `.custom` pair. + await ensurePair(stack, operator, 'com.example.crm'); for (const body of [ { name: META_AUTHOR, label: 'Meta author', objects: {}, systemPermissions: ['manage_metadata'] }, { name: SHARED, label: 'Shared', objects: {}, systemPermissions: [] }, { name: RBAC_WRITER, label: 'Catalog table writer', systemPermissions: [], objects: { sys_user_permission_set: rbac, sys_user_position: rbac } }, ]) { - const saved = await stack.apiAs(operator, 'PUT', `/meta/permission/${body.name}`, body); + const saved = await stack.apiAs(operator, 'PUT', `/meta/permission/${body.name}?package=${CRM_PAIR}`, body); expect(saved.status, await saved.clone().text()).toBe(200); } for (const name of [META_AUTHOR, RBAC_WRITER]) { @@ -211,7 +217,7 @@ for (const posture of ['isolated', 'group'] as const) { }); it('CONTROL: the platform operator still saves the catalog', async () => { - const res = await stack.apiAs(operator, 'PUT', '/meta/position/w_operator_pos', { + const res = await stack.apiAs(operator, 'PUT', `/meta/position/w_operator_pos?package=${CRM_PAIR}`, { name: 'w_operator_pos', label: 'Operator position', permissionSets: [SHARED], }); expect(res.status, await res.clone().text()).toBe(200); @@ -230,7 +236,9 @@ describe('[ADR-0131 D3] single: a `manage_metadata` holder still authors the cat ql = (await stack.kernel.getServiceAsync('objectql')) as unknown as Engine; const operator = await stack.signIn(); author = await stack.signUp('w-single-author@wall.test'); - const saved = await stack.apiAs(operator, 'PUT', `/meta/permission/${META_AUTHOR}`, { + // [#38174] New catalog items are created into a writable package (ADR-0070 D1): the CRM's `.custom` pair. + await ensurePair(stack, operator, 'com.example.crm'); + const saved = await stack.apiAs(operator, 'PUT', `/meta/permission/${META_AUTHOR}?package=${CRM_PAIR}`, { name: META_AUTHOR, label: 'Meta author', objects: {}, systemPermissions: ['manage_metadata'], }); expect(saved.status, await saved.clone().text()).toBe(200); @@ -247,7 +255,7 @@ describe('[ADR-0131 D3] single: a `manage_metadata` holder still authors the cat expect(tenancy?.posture ?? 'single').toBe('single'); const session = (await (await stack.apiAs(author, 'GET', '/auth/get-session')).json()) as any; expect(session.user?.isPlatformAdmin).toBe(false); - const res = await stack.apiAs(author, 'PUT', '/meta/position/w_single_pos', { name: 'w_single_pos', label: 'Single position' }); + const res = await stack.apiAs(author, 'PUT', `/meta/position/w_single_pos?package=${CRM_PAIR}`, { name: 'w_single_pos', label: 'Single position' }); expect(res.status, await res.clone().text()).toBe(200); }); }); diff --git a/packages/qa/dogfood/test/wall-declared-webhook-deployment-wide.dogfood.test.ts b/packages/qa/dogfood/test/wall-declared-webhook-deployment-wide.dogfood.test.ts index 1db1728c5d7..84ae6fc481f 100644 --- a/packages/qa/dogfood/test/wall-declared-webhook-deployment-wide.dogfood.test.ts +++ b/packages/qa/dogfood/test/wall-declared-webhook-deployment-wide.dogfood.test.ts @@ -26,6 +26,10 @@ import { bootStack, type VerifyStack } from '@objectstack/verify'; import { MessagingServicePlugin } from '@objectstack/service-messaging'; import { WebhookOutboxPlugin } from '@objectstack/plugin-webhooks'; import { webhookFixtureStack } from './fixtures/webhook-materialization-fixture.js'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.dogfood.webhook-fixture.custom'; const SYS = { isSystem: true, positions: [], permissions: [] }; /** [ADR-0150 D5, #31699 PR 2] The fixture package's own slot: `declared:PKG/NAME`. */ @@ -91,6 +95,8 @@ for (const posture of ['isolated', 'group'] as const) { }); ql = await stack.kernel.getServiceAsync('objectql'); operator = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the fixture's `.custom` pair. + await ensurePair(stack, operator, 'com.dogfood.webhook-fixture'); tokA = await stack.signUp(`dw-a-${posture}@wall.test`); tokB = await stack.signUp(`dw-b-${posture}@wall.test`); for (const [tok, slug] of [[tokA, `dw-a-${posture}`], [tokB, `dw-b-${posture}`]] as const) { @@ -106,7 +112,7 @@ for (const posture of ['isolated', 'group'] as const) { // `manage_metadata`: the read below is judged by the wall, not refused by // object permission, and the activation door's `manage_metadata` gate // admits them, so only the walled posture rule can refuse them there. - const saved = await stack.apiAs(operator, 'PUT', `/meta/permission/${DELIVERY_READER}`, { + const saved = await stack.apiAs(operator, 'PUT', `/meta/permission/${DELIVERY_READER}?package=${PAIR_PKG}`, { name: DELIVERY_READER, label: 'Delivery reader', systemPermissions: ['manage_metadata'], objects: { sys_http_delivery: { allowRead: true } }, }); diff --git a/packages/qa/dogfood/test/wall-environment-metadata-refusal.dogfood.test.ts b/packages/qa/dogfood/test/wall-environment-metadata-refusal.dogfood.test.ts index 49952ef8164..4174670ff5f 100644 --- a/packages/qa/dogfood/test/wall-environment-metadata-refusal.dogfood.test.ts +++ b/packages/qa/dogfood/test/wall-environment-metadata-refusal.dogfood.test.ts @@ -84,6 +84,9 @@ function packageBody(id: string, version: string, objects: unknown[] = []) { const META_AUTHOR = 'em_meta_author'; const CATALOG_PKG = 'com.em.catalog'; +/** [#38174] `?package=` naming {@link CATALOG_PKG}: a new item is created into a writable package. */ +const IN_PKG = `package=${CATALOG_PKG}`; +// (An object created into it carries the package's namespace prefix, `catalog_`.) /** The package that ships `crm_lead` (`examples/app-crm/objectstack.config.ts`, `manifest.id`). */ const CRM_PKG = 'com.example.crm'; @@ -126,7 +129,11 @@ async function boot(posture: 'isolated' | 'group' | 'single'): Promise } } h.userA = String((await ql.find('sys_user', { where: { email: `em-a-${posture}@wall.test` }, limit: 1, context: SYS }))[0]?.id); - const created = await stack.apiAs(operator, 'POST', '/packages', { id: CATALOG_PKG, name: 'catalog', version: '1.0.0', type: 'app' }); + // [#38174] Every NEW item below is created into this writable package (a + // package-less create is refused, ADR-0070 D1). It declares the CRM package, + // whose `crm_lead` the views bind (#24563's closure rule). + const created = await stack.apiAs(operator, 'POST', '/packages', + { id: CATALOG_PKG, name: 'catalog', version: '1.0.0', type: 'app', dependencies: { [CRM_PKG]: '*' } }); expect(created.status, await created.clone().text()).toBe(201); const saved = await stack.apiAs(operator, 'PUT', `/meta/permission/${META_AUTHOR}?package=${CATALOG_PKG}`, set(META_AUTHOR, ['manage_metadata'])); expect(saved.status, await saved.clone().text()).toBe(200); @@ -199,30 +206,30 @@ for (const posture of ['isolated', 'group'] as const) { it("/meta save: A editing the operator's view is refused, and B reads the operator's label", async () => { const name = `crm_lead.em_${p}_opview`; - await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/view/${name}`, view(name, 'Operator'))); + await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/view/${name}?${IN_PKG}`, view(name, 'Operator'))); await refused(await h.stack.apiAs(h.tokA, 'PUT', `/meta/view/${name}`, view(name, 'Edited by A')), 'FORBIDDEN'); expect(await readAsB(h, 'view', name)).toEqual({ status: 200, label: 'Operator' }); }); it("/meta publish: A publishing the operator's pending draft is refused, and B reads the published version", async () => { const name = `crm_lead.em_${p}_pub`; - await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/view/${name}`, view(name, 'Published v1'))); - await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/view/${name}?mode=draft`, view(name, 'Operator draft'))); + await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/view/${name}?${IN_PKG}`, view(name, 'Published v1'))); + await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/view/${name}?${IN_PKG}&mode=draft`, view(name, 'Operator draft'))); await refused(await h.stack.apiAs(h.tokA, 'POST', `/meta/view/${name}/publish`, {}), 'FORBIDDEN'); expect(await readAsB(h, 'view', name)).toEqual({ status: 200, label: 'Published v1' }); }); it("/meta rollback: A rolling the operator's view back is refused, and B reads the current version", async () => { const name = `crm_lead.em_${p}_rb`; - await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/view/${name}`, view(name, 'Operator v1'))); - await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/view/${name}`, view(name, 'Operator v2'))); + await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/view/${name}?${IN_PKG}`, view(name, 'Operator v1'))); + await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/view/${name}?${IN_PKG}`, view(name, 'Operator v2'))); await refused(await h.stack.apiAs(h.tokA, 'POST', `/meta/view/${name}/rollback`, { toVersion: 1 }), 'FORBIDDEN'); expect(await readAsB(h, 'view', name)).toEqual({ status: 200, label: 'Operator v2' }); }); it("/meta reset: A resetting the operator's view is refused, and B still reads it", async () => { const name = `crm_lead.em_${p}_rs`; - await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/view/${name}`, view(name, 'Operator reset target'))); + await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/view/${name}?${IN_PKG}`, view(name, 'Operator reset target'))); await refused(await h.stack.apiAs(h.tokA, 'DELETE', `/meta/view/${name}`), 'FORBIDDEN'); expect(await readAsB(h, 'view', name)).toEqual({ status: 200, label: 'Operator reset target' }); }); @@ -255,7 +262,14 @@ for (const posture of ['isolated', 'group'] as const) { .map((c: { id: string }) => c.id); expect(commits.length).toBeGreaterThan(0); await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/view/${pv}?package=${pkg}&mode=draft`, view(pv, 'pending'))); - await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/view/crm_lead.em_${p}_orphan`, view(`crm_lead.em_${p}_orphan`, 'Orphan'))); + // [#38174] `move-in` needs a package-less (loose) row, which no door + // creates any more (ADR-0070 D1): it is seeded directly, as a legacy row. + const now = new Date().toISOString(); + await h.ql.insert('sys_metadata', { + type: 'view', name: `crm_lead.em_${p}_orphan`, package_id: null, scope: 'platform', + state: 'active', version: 1, checksum: null, created_at: now, updated_at: now, + metadata: JSON.stringify(view(`crm_lead.em_${p}_orphan`, 'Orphan')), + }, { context: SYS }); for (const [method, path, body] of [ ['POST', '/packages', { id: `com.em.${p}.a`, name: 'a', version: '1.0.0', type: 'app' }], @@ -296,8 +310,12 @@ for (const posture of ['isolated', 'group'] as const) { it("/automation: A's create, update, deregister and clone of a flow definition are refused 403 PERMISSION_DENIED", async () => { const name = `em_${p}_opflow`; - await ok(await h.stack.apiAs(h.operator, 'POST', '/automation', flow(name, 'Operator flow'))); - await refused(await h.stack.apiAs(h.tokA, 'POST', '/automation', flow(`em_${p}_aflow`, 'Flow by A')), 'PERMISSION_DENIED'); + // [#38174] The `POST /automation` create door is retired: a new flow is + // created through `/meta` into a package, and A's create through this + // domain is a `PUT` of a new name, still gated before anything else. + await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/flow/${name}?${IN_PKG}`, flow(name, 'Operator flow'))); + expect((await h.stack.apiAs(h.tokA, 'POST', '/automation', flow(`em_${p}_aflow`, 'Flow by A'))).status).toBe(404); + await refused(await h.stack.apiAs(h.tokA, 'PUT', `/automation/em_${p}_aflow`, flow(`em_${p}_aflow`, 'Flow by A')), 'PERMISSION_DENIED'); await refused(await h.stack.apiAs(h.tokA, 'PUT', `/automation/${name}`, flow(name, 'Edited by A')), 'PERMISSION_DENIED'); await refused(await h.stack.apiAs(h.tokA, 'POST', `/automation/${name}/clone`, { name: `em_${p}_aclone`, label: 'Clone by A' }), 'PERMISSION_DENIED'); await refused(await h.stack.apiAs(h.tokA, 'DELETE', `/automation/${name}`), 'PERMISSION_DENIED'); @@ -307,13 +325,13 @@ for (const posture of ['isolated', 'group'] as const) { }, 60_000); it('CONTROL: the platform operator writes at every one of these doors', async () => { - await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/object/em_${p}_opobj`, object(`em_${p}_opobj`, 'Operator object'))); - await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/flow/em_${p}_opmetaflow`, flow(`em_${p}_opmetaflow`, 'Operator flow'))); + await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/object/catalog_em_${p}_opobj?${IN_PKG}`, object(`catalog_em_${p}_opobj`, 'Operator object'))); + await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/flow/em_${p}_opmetaflow?${IN_PKG}`, flow(`em_${p}_opmetaflow`, 'Operator flow'))); const name = `crm_lead.em_${p}_opctl`; - await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/view/${name}`, view(name, 'v1'))); - await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/view/${name}`, view(name, 'v2'))); + await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/view/${name}?${IN_PKG}`, view(name, 'v1'))); + await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/view/${name}?${IN_PKG}`, view(name, 'v2'))); await ok(await h.stack.apiAs(h.operator, 'POST', `/meta/view/${name}/rollback`, { toVersion: 1 })); - await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/view/${name}?mode=draft`, view(name, 'draft'))); + await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/view/${name}?${IN_PKG}&mode=draft`, view(name, 'draft'))); await ok(await h.stack.apiAs(h.operator, 'POST', `/meta/view/${name}/publish`, {})); expect(await readAsB(h, 'view', name)).toEqual({ status: 200, label: 'draft' }); await ok(await h.stack.apiAs(h.operator, 'DELETE', `/meta/view/${name}`)); @@ -340,7 +358,10 @@ for (const posture of ['isolated', 'group'] as const) { expect(await readAsB(h, 'object', `em_${p}_opilobj`)).toEqual({ status: 200, label: 'v2' }); await ok(await h.stack.apiAs(h.operator, 'DELETE', `${INSTALL_LOCAL}/${il}`)); - await ok(await h.stack.apiAs(h.operator, 'POST', '/automation', flow(`em_${p}_opautoflow`, 'Operator automation'))); + // [#38174] The create door is retired: created through `/meta` into a + // package, then updated and deregistered through `/automation`. + await ok(await h.stack.apiAs(h.operator, 'PUT', `/meta/flow/em_${p}_opautoflow?${IN_PKG}`, flow(`em_${p}_opautoflow`, 'Operator automation'))); + await ok(await h.stack.apiAs(h.operator, 'PUT', `/automation/em_${p}_opautoflow`, flow(`em_${p}_opautoflow`, 'Operator automation v2'))); await ok(await h.stack.apiAs(h.operator, 'DELETE', `/automation/em_${p}_opautoflow`)); await ok(await h.stack.apiAs(h.operator, 'POST', '/meta/_migrate-stored', {})); }, 60_000); @@ -362,9 +383,9 @@ describe('[ADR-0131 D12 items 7–8 · D11] single (CONTROL): the refusal is ine const a = await resolveUserAuthzGrants(h.ql as never, h.userA, { tenantId: await sessionOrgOf(h) }); expect(a.systemPermissions).toContain('manage_metadata'); expect(a.posture).not.toBe('PLATFORM_ADMIN'); - await ok(await h.stack.apiAs(h.tokA, 'PUT', '/meta/object/em_sin_obj', object('em_sin_obj', 'Object by A'))); - await ok(await h.stack.apiAs(h.tokA, 'PUT', '/meta/view/crm_lead.em_sin_view', view('crm_lead.em_sin_view', 'View by A'))); - await ok(await h.stack.apiAs(h.tokA, 'PUT', '/meta/flow/em_sin_flow', flow('em_sin_flow', 'Flow by A'))); + await ok(await h.stack.apiAs(h.tokA, 'PUT', `/meta/object/catalog_em_sin_obj?${IN_PKG}`, object('catalog_em_sin_obj', 'Object by A'))); + await ok(await h.stack.apiAs(h.tokA, 'PUT', `/meta/view/crm_lead.em_sin_view?${IN_PKG}`, view('crm_lead.em_sin_view', 'View by A'))); + await ok(await h.stack.apiAs(h.tokA, 'PUT', `/meta/flow/em_sin_flow?${IN_PKG}`, flow('em_sin_flow', 'Flow by A'))); expect(await readAsB(h, 'view', 'crm_lead.em_sin_view')).toEqual({ status: 200, label: 'View by A' }); // As in the walled /packages case: the package declares the CRM package, and // the publish line reads the receipt. @@ -379,7 +400,10 @@ describe('[ADR-0131 D12 items 7–8 · D11] single (CONTROL): the refusal is ine await ok(await h.stack.apiAs(h.tokA, 'DELETE', '/packages/com.em.sin.a')); await ok(await h.stack.apiAs(h.tokA, 'POST', INSTALL_LOCAL, packageBody('com.em.sin.il', '1.0.0', [object('em_sin_ilobj', 'v1')]))); await ok(await h.stack.apiAs(h.tokA, 'DELETE', `${INSTALL_LOCAL}/com.em.sin.il`)); - await ok(await h.stack.apiAs(h.tokA, 'POST', '/automation', flow('em_sin_autoflow', 'Automation by A'))); + // [#38174] The create door is retired: created through `/meta` into a + // package, then updated through `/automation`. + await ok(await h.stack.apiAs(h.tokA, 'PUT', `/meta/flow/em_sin_autoflow?${IN_PKG}`, flow('em_sin_autoflow', 'Automation by A'))); + await ok(await h.stack.apiAs(h.tokA, 'PUT', '/automation/em_sin_autoflow', flow('em_sin_autoflow', 'Automation by A, v2'))); await ok(await h.stack.apiAs(h.tokA, 'POST', '/meta/_migrate-stored', {})); }, 60_000); }); diff --git a/packages/qa/dogfood/test/wall-package-doors-refusal.dogfood.test.ts b/packages/qa/dogfood/test/wall-package-doors-refusal.dogfood.test.ts index 1ab42bb42fc..efe100a265b 100644 --- a/packages/qa/dogfood/test/wall-package-doors-refusal.dogfood.test.ts +++ b/packages/qa/dogfood/test/wall-package-doors-refusal.dogfood.test.ts @@ -131,6 +131,14 @@ async function boot(posture: 'isolated' | 'group' | 'single'): Promise await ok(await call(stack, operator, 'POST', `/packages/${OP_PKG}/publish-drafts`, {})); h.c2 = (await commitIds(stack, operator, OP_PKG))[0]!; await ok(await call(stack, operator, 'PUT', `/meta/permission/${OP_SET}?package=${OP_PKG}&mode=draft`, set(OP_SET, ['manage_users', 'manage_metadata']))); + // [#38174] The orphan is a legacy loose row, which no door creates any more + // (ADR-0070 D1): seeded directly, then saved in place, which stays open. + const now = new Date().toISOString(); + await ql.insert('sys_metadata', { + type: 'permission', name: ENV_SET, package_id: null, scope: 'platform', + state: 'active', version: 1, checksum: null, created_at: now, updated_at: now, + metadata: JSON.stringify(set(ENV_SET, [])), + }, { context: SYS }); await ok(await call(stack, operator, 'PUT', `/meta/permission/${ENV_SET}`, set(ENV_SET, []))); const grant = (user: string, permissionSet: string, org: string | undefined) => diff --git a/packages/qa/dogfood/test/wall-package-refusal.dogfood.test.ts b/packages/qa/dogfood/test/wall-package-refusal.dogfood.test.ts index c90db0b6299..cbf9bf829e4 100644 --- a/packages/qa/dogfood/test/wall-package-refusal.dogfood.test.ts +++ b/packages/qa/dogfood/test/wall-package-refusal.dogfood.test.ts @@ -51,6 +51,7 @@ import { mkdtempSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { buildShapedArtifact } from './build-shaped-artifact.js'; +import { ensurePair } from './customization-pair.js'; const SYS = { isSystem: true, positions: [], permissions: [] }; const INSTALL_LOCAL = '/marketplace/install-local'; @@ -131,7 +132,9 @@ async function boot(posture: 'isolated' | 'group' | 'single'): Promise h.userA = await idOf(`w2-a-${posture}@wall.test`); h.userB = await idOf(`w2-b-${posture}@wall.test`); - const saved = await stack.apiAs(operator, 'PUT', `/meta/permission/${META_AUTHOR}`, set(META_AUTHOR, ['manage_metadata'])); + // [#38174] A new item is created into a writable package (ADR-0070 D1): the CRM's `.custom` pair. + const pair = await ensurePair(stack, operator, 'com.example.crm'); + const saved = await stack.apiAs(operator, 'PUT', `/meta/permission/${META_AUTHOR}?package=${pair}`, set(META_AUTHOR, ['manage_metadata'])); expect(saved.status, await saved.clone().text()).toBe(200); const installed = await stack.apiAs(operator, 'POST', INSTALL_LOCAL, packageBody(OP_PKG, '1.0.0', { permissions: [set(OP_SET, [])] })); expect(installed.status, await installed.clone().text()).toBe(200); diff --git a/packages/qa/dogfood/test/webhook-meta-door-credential-redaction.dogfood.test.ts b/packages/qa/dogfood/test/webhook-meta-door-credential-redaction.dogfood.test.ts index f103f152591..67eae9fc625 100644 --- a/packages/qa/dogfood/test/webhook-meta-door-credential-redaction.dogfood.test.ts +++ b/packages/qa/dogfood/test/webhook-meta-door-credential-redaction.dogfood.test.ts @@ -36,6 +36,10 @@ import { WebhookOutboxPlugin } from '@objectstack/plugin-webhooks'; import { defineStack } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; import { defineWebhook } from '@objectstack/spec/automation'; +import { ensurePair } from './customization-pair.js'; + +/** [#38174] The writable package this file's new items are created in. */ +const PAIR_PKG = 'com.dogfood.webhook-credential-redaction.custom'; const SYSTEM = { isSystem: true, positions: [], permissions: [] }; @@ -143,8 +147,10 @@ for (const composition of COMPOSITIONS) { ql = await stack.kernel.getServiceAsync('objectql'); protocol = await stack.kernel.getServiceAsync('protocol'); admin = await stack.signIn(); + // [#38174] New items are created into a writable package (ADR-0070 D1): the fixture's `.custom` pair. + await ensurePair(stack, admin, 'com.dogfood.webhook-credential-redaction'); member = await stack.signUp(`wcr-member-${composition.plugins().length}@redaction.test`); - const put = await stack.apiAs(admin, 'PUT', `/meta/webhook/${SAVED}`, savedBody()); + const put = await stack.apiAs(admin, 'PUT', `/meta/webhook/${SAVED}?package=${PAIR_PKG}`, savedBody()); expect(put.status, await put.clone().text()).toBe(200); }, 180_000); @@ -212,7 +218,7 @@ for (const composition of COMPOSITIONS) { expect(Object.keys(body)).not.toContain('secret'); expect(Object.keys(body)).not.toContain('headers'); - const put = await stack.apiAs(admin, 'PUT', `/meta/webhook/${SAVED}`, { ...body, label: 'WCR Saved (edited)' }); + const put = await stack.apiAs(admin, 'PUT', `/meta/webhook/${SAVED}?package=${PAIR_PKG}`, { ...body, label: 'WCR Saved (edited)' }); expect(put.status, await put.clone().text()).toBe(200); const [row] = await stored('sys_metadata', SAVED); From 05e408a07c806f4157ea31551aaf23f54fc84b46 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 15:29:02 +0000 Subject: [PATCH 09/23] chore(spec): api-surface baseline without the CreateFlow schemas (#38174) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CasbvyQnz4st6s79P9 --- packages/spec/api-surface/api.json | 6 ------ 1 file changed, 6 deletions(-) diff --git a/packages/spec/api-surface/api.json b/packages/spec/api-surface/api.json index b8bea962011..6716535d8f8 100644 --- a/packages/spec/api-surface/api.json +++ b/packages/spec/api-surface/api.json @@ -265,12 +265,6 @@ "CreateDataRequestSchema (const)", "CreateDataResponse (type)", "CreateDataResponseSchema (const)", - "CreateFlowRequest (type)", - "CreateFlowRequestParsed (type)", - "CreateFlowRequestSchema (const)", - "CreateFlowResponse (type)", - "CreateFlowResponseParsed (type)", - "CreateFlowResponseSchema (const)", "CreateImportJobRequest (type)", "CreateImportJobRequestParsed (type)", "CreateImportJobRequestSchema (const)", From 2111e52793f2767c2309dfe47be311c6f4836469 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 16:06:09 +0000 Subject: [PATCH 10/23] =?UTF-8?q?chore:=20gate=20fixes=20after=20merging?= =?UTF-8?q?=20main=20=E2=80=94=20regenerated=20spec=20artifacts,=20rule=20?= =?UTF-8?q?count=2090=20in=20CLI=20transcripts,=20route-ledger=20census,?= =?UTF-8?q?=20issue=20ids=20out=20of=20runtime=20strings,=20typed=20servic?= =?UTF-8?q?e=20lookup=20(#38174)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CasbvyQnz4st6s79P9 --- content/docs/deployment/cli.mdx | 2 +- content/docs/deployment/validating-metadata.mdx | 2 +- .../docs/getting-started/build-with-claude-code.mdx | 2 +- content/docs/references/index.mdx | 10 +++++----- content/docs/ui/react-pages.mdx | 2 +- packages/qa/dogfood/test/authz-conformance.matrix.ts | 2 +- .../src/domains/mcp-package-object-discovery.test.ts | 2 +- packages/runtime/src/route-ledger.ts | 4 ++-- packages/spec/api-surface/api.json | 3 +++ packages/spec/authorable-surface/api.json | 3 +++ packages/spec/declaration-map/api.json | 4 ---- packages/spec/export-origins/api.json | 3 +++ packages/spec/json-schema.manifest/api.json | 1 + 13 files changed, 23 insertions(+), 17 deletions(-) diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index f5d7faf1776..3085d3d7513 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -937,7 +937,7 @@ os compile --json # JSON output for CI pipelines → Normalizing stack definition... → Lowering inline handlers... → Validating protocol compliance... - → Running author-time rules (89)... + → Running author-time rules (90)... → Checking that every required capability has a provider installable in this edition... → Collecting package docs (ADR-0046)... 0 collected → Writing artifact... diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index 031f45f766f..1b281b1f51b 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -874,7 +874,7 @@ A clean run walks the registry and reports timing: Config: /path/to/support-desk/objectstack.config.ts Load time: 21ms → Validating against ObjectStack Protocol... - → Running author-time rules (89)... + → Running author-time rules (90)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/content/docs/getting-started/build-with-claude-code.mdx b/content/docs/getting-started/build-with-claude-code.mdx index 44ef844be8f..41e2456f9af 100644 --- a/content/docs/getting-started/build-with-claude-code.mdx +++ b/content/docs/getting-started/build-with-claude-code.mdx @@ -378,7 +378,7 @@ visible: 'status != "resolved"' ◆ Validate ──────────────────────────────────────── → Validating against ObjectStack Protocol... - → Running author-time rules (89)... + → Running author-time rules (90)... ✗ Author-time rules failed (1 issue) • stack · action 'resolve_ticket' visible: bare reference `status` — a diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 65aaa2ae17b..bfc3c2175b2 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1759 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1760 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -23,7 +23,7 @@ counts are sums of the rows they head. Regenerate with | Module | Pages | Schemas | Description | | :--- | ---: | ---: | :--- | | [AI Protocol](/docs/references/ai) | 18 | 108 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | -| [API Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/api) | 39 | 537 | REST contracts, endpoints, routing, realtime, batch, discovery. | +| [API Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/api) | 39 | 538 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | | [Data Protocol](/docs/references/data) | 35 | 198 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | | [Identity Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/identity) | 5 | 27 | Users and accounts, organizations, positions, SCIM provisioning. | @@ -36,7 +36,7 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 17 | 188 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **226** | **1759** | 14 protocol modules | +| **Total** | **226** | **1760** | 14 protocol modules | --- @@ -71,7 +71,7 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. ## API Protocol -**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **39 pages, 537 schemas** +**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **39 pages, 538 schemas** REST contracts, endpoints, routing, realtime, batch, discovery. @@ -102,7 +102,7 @@ REST contracts, endpoints, routing, realtime, batch, discovery. | [`package-api-assembled.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/package-api-assembled.md) | `AssembledInstalledPackage`, `GetInstalledPackageResponse`, `InstalledPackageAtEitherStage`, `ListInstalledPackagesResponse` | | [`package-lifecycle.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/package-lifecycle.md) | `DiscardPackageDraftsResponse`, `DuplicatePackageResponse`, `EnsureCustomizationPackageRequest`, `EnsureCustomizationPackageResponse`, `GetPackageCustomizationsRequest`, `GetPackageCustomizationsResponse`, `ImportUnmanagedPackageRequest`, `ImportUnmanagedPackageResponse`, `ListPackageCommitsResponse`, `MoveIntoPackageItem`, `MoveIntoPackageMovedItem`, `MoveIntoPackageRefusedItem`, `MoveIntoPackageRequest`, `MoveIntoPackageResponse`, `PackageExportBundle`, `PackageExportManifest`, `PackagePublishResult`, `RevertPackageCommitResponse`, `RollbackToPackageCommitResponse` | | [`plugin-rest-api.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/plugin-rest-api.md) | `ErrorHandlingConfig`, `OpenApiGenerationConfig`, `RequestValidationConfig`, `ResponseEnvelopeConfig`, `RestApiEndpoint`, `RestApiPluginConfig`, `RestApiRouteCategory`, `RestApiRouteRegistration`, `ValidationMode` | -| [`protocol.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/protocol.md) | `AiAgentCapabilities`, `AiAgentChatRequest`, `AiAgentSummary`, `AiAgentsResponse`, `AiChatRequest`, `AiChatResponse`, `AiCompleteRequest`, `AiConversation`, `AiConversationMessage`, `AiMessage`, `AiModelsResponse`, `AiPendingAction`, `AiPendingActionStatus`, `AiStreamChunk`, `ApproveAiPendingActionResponse`, `AuditMetaItemRequest`, `AuditMetaItemResponse`, `AutomationActionsResponse`, `AutomationTriggerRequest`, `AutomationTriggerResponse`, `BatchDataRequest`, `BatchDataResponse`, `BuildProbeReport`, `CheckPermissionRequest`, `CheckPermissionResponse`, `CloneDataResponse`, `CreateAiConversationRequest`, `CreateDataRequest`, `CreateDataResponse`, `CreateManyDataRequest`, `CreateManyDataResponse`, `DeleteDataRequest`, `DeleteDataResponse`, `DeleteManyDataRequest`, `DeleteManyDataResponse`, `DeleteMetaItemRequest`, `DeleteMetaItemResponse`, `DestructiveChangeIssue`, `DiffMetaItemRequest`, `DiffMetaItemResponse`, `DisablePackageRequest`, `DisablePackageResponse`, `EnablePackageRequest`, `EnablePackageResponse`, `FieldStillShownBy`, `FindDataRequest`, `FindDataResponse`, `FindReferencesToMetaResponse`, `FlowRegistration`, `FlowRegistrationRefusal`, `GetDataRequest`, `GetDataResponse`, `GetDiscoveryRequest`, `GetDiscoveryResponse`, `GetEffectivePermissionsRequest`, `GetEffectivePermissionsResponse`, `GetFieldLabelsRequest`, `GetFieldLabelsResponse`, `GetLocalesRequest`, `GetLocalesResponse`, `GetMetaDiagnosticsResponse`, `GetMetaItemCachedRequest`, `GetMetaItemCachedResponse`, `GetMetaItemLayeredRequest`, `GetMetaItemLayeredResponse`, `GetMetaItemRequest`, `GetMetaItemResponse`, `GetMetaItemsRequest`, `GetMetaItemsResponse`, `GetMetaTypesRequest`, `GetMetaTypesResponse`, `GetNotificationPreferencesRequest`, `GetNotificationPreferencesResponse`, `GetObjectPermissionsRequest`, `GetObjectPermissionsResponse`, `GetPackageRequest`, `GetPackageResponse`, `GetPresenceRequest`, `GetPresenceResponse`, `GetPublishedMetaItemResponse`, `GetRecordFieldAccessResponse`, `GetTranslationsRequest`, `GetTranslationsResponse`, `GetUiViewRequest`, `GetUiViewResponse`, `HistoryMetaItemRequest`, `HistoryMetaItemResponse`, `HttpFindQueryParams`, `InstallPackageRequest`, `InstallPackageResponse`, `ListAiConversationsRequest`, `ListAiConversationsResponse`, `ListAiPendingActionsRequest`, `ListAiPendingActionsResponse`, `ListDraftsResponse`, `ListNotificationsRequest`, `ListNotificationsResponse`, `ListPackagesRequest`, `ListPackagesResponse`, `MarkAllNotificationsReadRequest`, `MarkAllNotificationsReadResponse`, `MarkNotificationsReadRequest`, `MarkNotificationsReadResponse`, `MetadataAuthoringClient`, `MetadataAuthoringSurface`, `MetadataConflictError`, `Notification`, `NotificationPreferences`, `PublicFormSubmitResponse`, `PublishMetaItemRequest`, `PublishMetaItemResponse`, `PublishPackageDraftsRequest`, `PublishPackageDraftsResponse`, `RealtimeConnectRequest`, `RealtimeConnectResponse`, `RealtimeDisconnectRequest`, `RealtimeDisconnectResponse`, `RealtimeSubscribeRequest`, `RealtimeSubscribeResponse`, `RealtimeUnsubscribeRequest`, `RealtimeUnsubscribeResponse`, `RegisterDeviceRequest`, `RegisterDeviceResponse`, `RejectAiPendingActionResponse`, `RollbackMetaItemRequest`, `RollbackMetaItemResponse`, `RuntimeAuthoringIssue`, `RuntimeBuildIssue`, `SaveMetaItemRequest`, `SaveMetaItemResponse`, `SearchAllHit`, `SearchAllPageHit`, `SearchAllResponse`, `SeedAppliedIdList`, `SeedAppliedLanded`, `SetPresenceRequest`, `SetPresenceResponse`, `UninstallPackageRequest`, `UninstallPackageResponse`, `UnregisterDeviceRequest`, `UnregisterDeviceResponse`, `UpdateAiConversationRequest`, `UpdateDataRequest`, `UpdateDataResponse`, `UpdateManyDataRequest`, `UpdateManyDataResponse`, `UpdateNotificationPreferencesRequest`, `UpdateNotificationPreferencesResponse`, `ValidateDataIssue`, `ValidateDataRequest`, `ValidateDataResponse` | +| [`protocol.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/protocol.md) | `AiAgentCapabilities`, `AiAgentChatRequest`, `AiAgentSummary`, `AiAgentsResponse`, `AiChatRequest`, `AiChatResponse`, `AiCompleteRequest`, `AiConversation`, `AiConversationMessage`, `AiMessage`, `AiModelsResponse`, `AiPendingAction`, `AiPendingActionStatus`, `AiStreamChunk`, `ApproveAiPendingActionResponse`, `AuditMetaItemRequest`, `AuditMetaItemResponse`, `AutomationActionsResponse`, `AutomationTriggerRequest`, `AutomationTriggerResponse`, `BatchDataRequest`, `BatchDataResponse`, `BuildProbeReport`, `CheckPermissionRequest`, `CheckPermissionResponse`, `CloneDataResponse`, `CreateAiConversationRequest`, `CreateDataRequest`, `CreateDataResponse`, `CreateManyDataRequest`, `CreateManyDataResponse`, `DeleteDataRequest`, `DeleteDataResponse`, `DeleteManyDataRequest`, `DeleteManyDataResponse`, `DeleteMetaItemRequest`, `DeleteMetaItemResponse`, `DestructiveChangeIssue`, `DiffMetaItemRequest`, `DiffMetaItemResponse`, `DisablePackageRequest`, `DisablePackageResponse`, `EnablePackageRequest`, `EnablePackageResponse`, `FieldStillShownBy`, `FindDataRequest`, `FindDataResponse`, `FindReferencesToMetaResponse`, `FlowRegistration`, `FlowRegistrationAtRestFinding`, `FlowRegistrationRefusal`, `GetDataRequest`, `GetDataResponse`, `GetDiscoveryRequest`, `GetDiscoveryResponse`, `GetEffectivePermissionsRequest`, `GetEffectivePermissionsResponse`, `GetFieldLabelsRequest`, `GetFieldLabelsResponse`, `GetLocalesRequest`, `GetLocalesResponse`, `GetMetaDiagnosticsResponse`, `GetMetaItemCachedRequest`, `GetMetaItemCachedResponse`, `GetMetaItemLayeredRequest`, `GetMetaItemLayeredResponse`, `GetMetaItemRequest`, `GetMetaItemResponse`, `GetMetaItemsRequest`, `GetMetaItemsResponse`, `GetMetaTypesRequest`, `GetMetaTypesResponse`, `GetNotificationPreferencesRequest`, `GetNotificationPreferencesResponse`, `GetObjectPermissionsRequest`, `GetObjectPermissionsResponse`, `GetPackageRequest`, `GetPackageResponse`, `GetPresenceRequest`, `GetPresenceResponse`, `GetPublishedMetaItemResponse`, `GetRecordFieldAccessResponse`, `GetTranslationsRequest`, `GetTranslationsResponse`, `GetUiViewRequest`, `GetUiViewResponse`, `HistoryMetaItemRequest`, `HistoryMetaItemResponse`, `HttpFindQueryParams`, `InstallPackageRequest`, `InstallPackageResponse`, `ListAiConversationsRequest`, `ListAiConversationsResponse`, `ListAiPendingActionsRequest`, `ListAiPendingActionsResponse`, `ListDraftsResponse`, `ListNotificationsRequest`, `ListNotificationsResponse`, `ListPackagesRequest`, `ListPackagesResponse`, `MarkAllNotificationsReadRequest`, `MarkAllNotificationsReadResponse`, `MarkNotificationsReadRequest`, `MarkNotificationsReadResponse`, `MetadataAuthoringClient`, `MetadataAuthoringSurface`, `MetadataConflictError`, `Notification`, `NotificationPreferences`, `PublicFormSubmitResponse`, `PublishMetaItemRequest`, `PublishMetaItemResponse`, `PublishPackageDraftsRequest`, `PublishPackageDraftsResponse`, `RealtimeConnectRequest`, `RealtimeConnectResponse`, `RealtimeDisconnectRequest`, `RealtimeDisconnectResponse`, `RealtimeSubscribeRequest`, `RealtimeSubscribeResponse`, `RealtimeUnsubscribeRequest`, `RealtimeUnsubscribeResponse`, `RegisterDeviceRequest`, `RegisterDeviceResponse`, `RejectAiPendingActionResponse`, `RollbackMetaItemRequest`, `RollbackMetaItemResponse`, `RuntimeAuthoringIssue`, `RuntimeBuildIssue`, `SaveMetaItemRequest`, `SaveMetaItemResponse`, `SearchAllHit`, `SearchAllPageHit`, `SearchAllResponse`, `SeedAppliedIdList`, `SeedAppliedLanded`, `SetPresenceRequest`, `SetPresenceResponse`, `UninstallPackageRequest`, `UninstallPackageResponse`, `UnregisterDeviceRequest`, `UnregisterDeviceResponse`, `UpdateAiConversationRequest`, `UpdateDataRequest`, `UpdateDataResponse`, `UpdateManyDataRequest`, `UpdateManyDataResponse`, `UpdateNotificationPreferencesRequest`, `UpdateNotificationPreferencesResponse`, `ValidateDataIssue`, `ValidateDataRequest`, `ValidateDataResponse` | | [`push-delivery.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/push-delivery.md) | `PushDeliveryData`, `PushRoute` | | [`push-relay.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/push-relay.md) | `PushRelayDelivery`, `PushRelayError`, `PushRelayErrorResponse`, `PushRelayPayload`, `PushRelayPriority`, `PushRelayRequest`, `PushRelayResponse`, `PushRelayResult`, `PushRelayResultStatus` | | [`query-adapter.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/query-adapter.md) | `ODataQueryAdapter`, `OperatorMapping`, `QueryAdapterConfig`, `QueryAdapterTarget`, `RestQueryAdapter` | diff --git a/content/docs/ui/react-pages.mdx b/content/docs/ui/react-pages.mdx index 55339c58206..7142d727674 100644 --- a/content/docs/ui/react-pages.mdx +++ b/content/docs/ui/react-pages.mdx @@ -404,7 +404,7 @@ objectstack validate ──────────────────────────────────────── → Loading configuration... → Validating against ObjectStack Protocol... - → Running author-time rules (89)... + → Running author-time rules (90)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/packages/qa/dogfood/test/authz-conformance.matrix.ts b/packages/qa/dogfood/test/authz-conformance.matrix.ts index ee802185477..9720c5ae5b7 100644 --- a/packages/qa/dogfood/test/authz-conformance.matrix.ts +++ b/packages/qa/dogfood/test/authz-conformance.matrix.ts @@ -260,7 +260,7 @@ export const AUTHZ_CONFORMANCE: AuthzPrimitive[] = [ // #22773 — the one route the floor admits (ruling A on #22757): named in the // note's last sentences. ⛔ Ids stay in this comment, out of the row's strings. { id: 'anonymous-deny-automation', summary: 'anonymous-deny on the automation/flow surface (uniform anonymous posture, surface 3: refused 401 before dispatch, as `/data` and `/meta` are)', state: 'enforced', - enforcement: 'runtime/domains/automation.ts handleAutomationRequest — shouldDenyAnonymous DOMAIN-WIDE at the top, and deliberately BEFORE the isServiceServeable probe so the 401/501 difference cannot be used to fingerprint whether a deployment mounts automation; per-route capability predicates run after this floor — `manage_metadata` for the four gated flow writes (update `PUT /:name` / deregister `DELETE /:name`, the definition writes on the metadata plane — the create door `POST /` is retired (#38174) and unmounted, a new flow being created through `PUT /meta/flow/:name?package=` — plus enablement `POST /:name/toggle` since the 2026-08-23 ruling that enablement is an authoring write, which measured that the enabled bit is not a ROW and so reaches every organization on the deployment, plus the ADR-0126 §7.1 clone `POST /:name/clone`, which registers flow metadata exactly as a create does), all selected by the ONE `isFlowAuthoringWrite` predicate, fail-closed by construction (an absent executionContext, an absent `systemPermissions` or an empty one all refuse) and answering 403 `PERMISSION_DENIED`, with only engine `isSystem` bypassing; the run-state reads (the `sys_automation_run` read grant) and `resume` (keyed on the node the run is suspended on, fail-closed for a node that declares no resumeAuthority) carry their own separate per-route predicates, and the execution doors (trigger / execute) sit outside all of them — including `POST /trigger/:name` for a flow literally NAMED `toggle`, which the toggle arm deliberately excludes so a name cannot cost a member its run door', + enforcement: 'runtime/domains/automation.ts handleAutomationRequest — shouldDenyAnonymous DOMAIN-WIDE at the top, and deliberately BEFORE the isServiceServeable probe so the 401/501 difference cannot be used to fingerprint whether a deployment mounts automation; per-route capability predicates run after this floor — `manage_metadata` for the four gated flow writes (update `PUT /:name` / deregister `DELETE /:name`, the definition writes on the metadata plane — the create door `POST /` is retired and unmounted, a new flow being created through `PUT /meta/flow/:name?package=` — plus enablement `POST /:name/toggle` since the 2026-08-23 ruling that enablement is an authoring write, which measured that the enabled bit is not a ROW and so reaches every organization on the deployment, plus the ADR-0126 §7.1 clone `POST /:name/clone`, which registers flow metadata exactly as a create does), all selected by the ONE `isFlowAuthoringWrite` predicate, fail-closed by construction (an absent executionContext, an absent `systemPermissions` or an empty one all refuse) and answering 403 `PERMISSION_DENIED`, with only engine `isSystem` bypassing; the run-state reads (the `sys_automation_run` read grant) and `resume` (keyed on the node the run is suspended on, fail-closed for a node that declares no resumeAuthority) carry their own separate per-route predicates, and the execution doors (trigger / execute) sit outside all of them — including `POST /trigger/:name` for a flow literally NAMED `toggle`, which the toggle arm deliberately excludes so a name cannot cost a member its run door', proof: 'showcase-anonymous-deny-surfaces.dogfood.test.ts', // [2026-08-31] Ledger granularity for the same DOMAIN-WIDE gate named // above — the property the note already relies on ("gating the DOMAIN diff --git a/packages/runtime/src/domains/mcp-package-object-discovery.test.ts b/packages/runtime/src/domains/mcp-package-object-discovery.test.ts index bd8fe80aeaf..08dbe0e123b 100644 --- a/packages/runtime/src/domains/mcp-package-object-discovery.test.ts +++ b/packages/runtime/src/domains/mcp-package-object-discovery.test.ts @@ -846,7 +846,7 @@ async function saveAuthoredAction(kernel: ObjectKernel, boundTo?: string): Promi // [#38174] A package-less CREATE is refused (ADR-0070 D1): each // environment-authored loose row is laid straight into the store, and the // save door's package-less save of it runs in place. - const engine: any = kernel.getService('objectql'); + const engine = kernel.getService<{ insert(object: string, row: Record, options: { context: { isSystem: boolean } }): Promise }>('objectql'); const layLooseRow = (name: string, item: Record) => engine.insert('sys_metadata', { type: 'action', name, namespace: 'default', package_id: null, scope: 'platform', strategy: 'merge', state: 'active', version: 1, metadata: JSON.stringify(item), diff --git a/packages/runtime/src/route-ledger.ts b/packages/runtime/src/route-ledger.ts index 661a5fdb982..d3f83299b7f 100644 --- a/packages/runtime/src/route-ledger.ts +++ b/packages/runtime/src/route-ledger.ts @@ -301,7 +301,7 @@ export const NON_DISPATCH_MOUNT_PREFIXES = [ /** * The ledger. * - * CENSUS (generated): this list holds 158 rows. + * CENSUS (generated): this list holds 157 rows. * * ⛔ THAT NUMBER IS WRITTEN BY A TOOL — never by hand. * `pnpm check:route-ledger-census` counts the rows below and fails when the two @@ -669,7 +669,7 @@ export const ROUTE_LEDGER: readonly RouteLedgerEntry[] = [ { route: 'GET /automation/:name/runs', domain: '/automation', disposition: 'sdk', client: 'automation.listRuns' }, { route: 'GET /automation/:name', domain: '/automation', disposition: 'sdk', client: 'automation.get' }, { route: 'PUT /automation/:name', domain: '/automation', disposition: 'sdk', client: 'automation.update', - note: "authored metadata, so `manage_metadata` gates it: a flow definition lives on the metadata plane (ADR-0106), and this door asks the capability every other door onto that plane asks. Fail-closed by construction — an absent executionContext, an absent `systemPermissions` or an empty one all fall through to the refusal, 403 with code `PERMISSION_DENIED` (ADR-0112); only engine self-invocation (`isSystem`, never settable from the wire) bypasses. WHICH routes is one predicate, `isFlowAuthoringWrite` in `domains/automation.ts` — this row, DELETE `/:name` below and `POST /:name/toggle`, with the execution doors (trigger / execute / resume) deliberately outside it. Updates a flow that exists: a new name answers 422 `WRITABLE_PACKAGE_REQUIRED` naming `PUT /meta/flow/:name?package=` (#38174, the create door `POST /automation` retired). Pinned in `domains/automation-write-capability-gate.test.ts`" }, + note: "authored metadata, so `manage_metadata` gates it: a flow definition lives on the metadata plane (ADR-0106), and this door asks the capability every other door onto that plane asks. Fail-closed by construction — an absent executionContext, an absent `systemPermissions` or an empty one all fall through to the refusal, 403 with code `PERMISSION_DENIED` (ADR-0112); only engine self-invocation (`isSystem`, never settable from the wire) bypasses. WHICH routes is one predicate, `isFlowAuthoringWrite` in `domains/automation.ts` — this row, DELETE `/:name` below and `POST /:name/toggle`, with the execution doors (trigger / execute / resume) deliberately outside it. Updates a flow that exists: a new name answers 422 `WRITABLE_PACKAGE_REQUIRED` naming `PUT /meta/flow/:name?package=` (the create door `POST /automation` is retired). Pinned in `domains/automation-write-capability-gate.test.ts`" }, { route: 'DELETE /automation/:name', domain: '/automation', disposition: 'sdk', client: 'automation.delete', note: "authored metadata, so `manage_metadata` gates it — the same `isFlowAuthoringWrite` door as `PUT /automation/:name` below, and the destructive member of the family: before the gate a tenant org owner WITHOUT the capability deregistered a registered flow, 200, and flow metadata is registered at ENVIRONMENT scope so the write crossed the tenant wall. Fail-closed on an absent executionContext, an absent `systemPermissions` or an empty one, refusing 403 `PERMISSION_DENIED`, with only `isSystem` bypassing" }, // [#22773] The inbound hook's hosted door (segment 2 of ruling A on #22757). diff --git a/packages/spec/api-surface/api.json b/packages/spec/api-surface/api.json index 6716535d8f8..4bd6947db5a 100644 --- a/packages/spec/api-surface/api.json +++ b/packages/spec/api-surface/api.json @@ -494,6 +494,9 @@ "FlowInnerRefusalParsed (type)", "FlowInnerRefusalSchema (const)", "FlowRegistration (type)", + "FlowRegistrationAtRestFinding (type)", + "FlowRegistrationAtRestFindingParsed (type)", + "FlowRegistrationAtRestFindingSchema (const)", "FlowRegistrationRefusal (type)", "FlowRegistrationRefusalSchema (const)", "FlowRegistrationSchema (const)", diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index 0f134fdf555..d8e590d7a78 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -793,6 +793,9 @@ "api/FlowFailureDetails:summary", "api/FlowInnerRefusal:code", "api/FlowInnerRefusal:message", + "api/FlowRegistrationAtRestFinding:message", + "api/FlowRegistrationAtRestFinding:path", + "api/FlowRegistrationAtRestFinding:ruleId", "api/FlowRegistrationRefusal:code", "api/FlowRegistrationRefusal:message", "api/GeneratedApiDocumentation:generatedAt", diff --git a/packages/spec/declaration-map/api.json b/packages/spec/declaration-map/api.json index eb0ac45a9a4..c7e297133f3 100644 --- a/packages/spec/declaration-map/api.json +++ b/packages/spec/declaration-map/api.json @@ -204,10 +204,6 @@ "CreateDataRequestSchema": "api/CreateDataRequest", "CreateDataResponse": "api/CreateDataResponse", "CreateDataResponseSchema": "api/CreateDataResponse", - "CreateFlowRequest": "api/CreateFlowRequest", - "CreateFlowRequestSchema": "api/CreateFlowRequest", - "CreateFlowResponse": "api/CreateFlowResponse", - "CreateFlowResponseSchema": "api/CreateFlowResponse", "CreateImportJobRequest": "api/CreateImportJobRequest", "CreateImportJobRequestSchema": "api/CreateImportJobRequest", "CreateImportJobResponse": "api/CreateImportJobResponse", diff --git a/packages/spec/export-origins/api.json b/packages/spec/export-origins/api.json index af5c55eac0d..2ea7660f380 100644 --- a/packages/spec/export-origins/api.json +++ b/packages/spec/export-origins/api.json @@ -474,6 +474,9 @@ "FlowInnerRefusalParsed": "src/api/automation-api.zod.ts#FlowInnerRefusalParsed (type)", "FlowInnerRefusalSchema": "src/api/automation-api.zod.ts#FlowInnerRefusalSchema (const)", "FlowRegistration": "src/api/protocol.zod.ts#FlowRegistration (type)", + "FlowRegistrationAtRestFinding": "src/api/protocol.zod.ts#FlowRegistrationAtRestFinding (type)", + "FlowRegistrationAtRestFindingParsed": "src/api/protocol.zod.ts#FlowRegistrationAtRestFindingParsed (type)", + "FlowRegistrationAtRestFindingSchema": "src/api/protocol.zod.ts#FlowRegistrationAtRestFindingSchema (const)", "FlowRegistrationRefusal": "src/api/protocol.zod.ts#FlowRegistrationRefusal (type)", "FlowRegistrationRefusalSchema": "src/api/protocol.zod.ts#FlowRegistrationRefusalSchema (const)", "FlowRegistrationSchema": "src/api/protocol.zod.ts#FlowRegistrationSchema (const)", diff --git a/packages/spec/json-schema.manifest/api.json b/packages/spec/json-schema.manifest/api.json index bb2fb614c5f..ee706c29ed4 100644 --- a/packages/spec/json-schema.manifest/api.json +++ b/packages/spec/json-schema.manifest/api.json @@ -193,6 +193,7 @@ "api/FlowFailureDetails", "api/FlowInnerRefusal", "api/FlowRegistration", + "api/FlowRegistrationAtRestFinding", "api/FlowRegistrationRefusal", "api/GeneratedApiDocumentation", "api/GeneratedEndpoint", From f5a901e1acf1764b16d99011f9262d8d3cca3b7b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 16:16:43 +0000 Subject: [PATCH 11/23] =?UTF-8?q?fix:=20L2=20findings,=20first=20part=20?= =?UTF-8?q?=E2=80=94=20the=20package-less=20create=20judgment=20drops=20th?= =?UTF-8?q?e=20package-duplicate=20skip=20(F2);=20W5=20named=20at=20the=20?= =?UTF-8?q?call=20site?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CasbvyQnz4st6s79P9 --- .../38174-packageless-create-refused.md | 2 +- .../lint/src/validate-flow-notify-channels.ts | 12 +++++++++ .../src/protocol-packageless-create.ts | 5 ++-- .../metadata-protocol/src/protocol-save.ts | 6 +++-- .../meta-packageless-create-refused.test.ts | 27 ++++++++++++++++--- .../semantic/19.packageless-create-refused.ts | 27 ++++++++++++++----- 6 files changed, 63 insertions(+), 16 deletions(-) diff --git a/.changeset/38174-packageless-create-refused.md b/.changeset/38174-packageless-create-refused.md index b582150881a..5e4eb0d8fe9 100644 --- a/.changeset/38174-packageless-create-refused.md +++ b/.changeset/38174-packageless-create-refused.md @@ -5,7 +5,7 @@ '@objectstack/spec': minor '@objectstack/cli': minor '@objectstack/lint': minor -'@objectstack/plugin-sharing': minor +'@objectstack/plugin-sharing': patch --- feat(metadata-protocol)!: the kernel refuses a package-less create; `POST /api/v1/automation` is retired; a flow saved through `/meta` is refused for a `notify` channel no plugin registers diff --git a/packages/lint/src/validate-flow-notify-channels.ts b/packages/lint/src/validate-flow-notify-channels.ts index a47c6159db1..9da4efd844f 100644 --- a/packages/lint/src/validate-flow-notify-channels.ts +++ b/packages/lint/src/validate-flow-notify-channels.ts @@ -34,6 +34,18 @@ * is never refused for it. * * Every node is judged, at any region depth (`collectFlowGraphs`). + * + * ## The two doors share the predicate, not the judging mode (intended) + * + * The `/automation` door refuses every write of a flow naming an unregistered + * channel. The metadata door's runtime gate refuses only a finding the write + * ADDS (the gate's differential against the stored item): an in-place save of + * a flow already stored with the finding, from before this rule, still saves, + * so an existing flow is never locked by a rule it predates, and the run-time + * warning keeps naming the channel. A runtime package install meets the rule + * as any other metadata-door write does: a packaged flow naming a channel of a + * plugin the deployment lacks is refused there, which is the same failure the + * flow would otherwise hit at its first run. */ import { collectFlowGraphs, type FlowNodeParsed } from '@objectstack/spec/automation'; diff --git a/packages/metadata-protocol/src/protocol-packageless-create.ts b/packages/metadata-protocol/src/protocol-packageless-create.ts index 03209de9f3e..03f2420d7fc 100644 --- a/packages/metadata-protocol/src/protocol-packageless-create.ts +++ b/packages/metadata-protocol/src/protocol-packageless-create.ts @@ -48,7 +48,8 @@ * W13, platform registration (`MetadataManager.register(…, { origin: * 'platform' })`), writes the metadata service's own store and never reaches * this path. `package-duplicate` always names its target, so it never arrives - * here package-less. Ruling 7184753035 answered Q-a A and Q-b C: no type and + * here package-less; it has no skip of its own, and one that did arrive + * package-less would be refused like any other create. Ruling 7184753035 answered Q-a A and Q-b C: no type and * no case adds an exemption, and there is no flag or environment switch. * * Tests that need a loose row insert it directly through the engine with the @@ -85,7 +86,7 @@ export async function packagelessCreateRefusal( if (intent !== 'runtime-only') return undefined; if (request.packageId != null && request.packageId !== '') return undefined; if (request.source !== undefined) return undefined; - if (request.writeFace === 'external-import' || request.writeFace === 'package-duplicate') return undefined; + if (request.writeFace === 'external-import') return undefined; if (request.packagelessCreateProvenance === 'organization-ownership-ceremony') return undefined; const active = await host.packagelessAddress(singularType, request.name, member, 'active'); diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index 0dcf1c92965..6c6da603b3b 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -2165,8 +2165,10 @@ export class ProtocolSaveFacet { // package after its address resolved, of a name no package holds and // no loose row (active or draft) carries. In-place saves of an existing // loose row, a holder's customization (ADR-0150 D4), the kernel-item - // overlay (W3), the external import (W4) and the binding-preserving - // migrations (W12) keep their answers. See {@link packagelessCreateRefusal}. + // overlay (W3), the external import (W4), the binding-preserving + // migrations (W12) and the organization-ownership ceremony's + // conversions (W5, ruling 7380917604) keep their answers. See + // {@link packagelessCreateRefusal}. const createRefusal = await packagelessCreateRefusal( host, request, singularTypeForRepo, itemDiscriminator(singularTypeForRepo, request.item), intent, ); diff --git a/packages/runtime/src/meta-packageless-create-refused.test.ts b/packages/runtime/src/meta-packageless-create-refused.test.ts index df007ef2841..ee4af6237ca 100644 --- a/packages/runtime/src/meta-packageless-create-refused.test.ts +++ b/packages/runtime/src/meta-packageless-create-refused.test.ts @@ -17,9 +17,13 @@ * * The controls pin what the close does NOT reach: the same save naming a * package, an in-place save of a loose row that already exists, a package-less - * save of a name a package holds, and the server-stated exemptions (a - * binding-preserving migration's `source`, the external-datasource import's - * `writeFace`). + * save of a name a package holds, and the named exemptions: W3 the kernel-item + * overlay, W4 the external-datasource import's `writeFace`, W12 a + * binding-preserving migration's `source`, and W5 the organization-ownership + * ceremony's provenance. W13, platform registration + * (`MetadataManager.register(…, { origin: 'platform' })`), writes the metadata + * service's own store and never reaches the kernel save; it is pinned where it + * lives (`packages/metadata/src/metadata-manager-cluster.test.ts`). * * Ablation: dropping the `packagelessCreateRefusal` call from * `saveMetaItemUnaudited` (`protocol-save.ts`) turns every "refused" case RED @@ -196,7 +200,22 @@ describe('[#38174] controls — what the close does not reach', () => { expect((await rows('view', 'drafted_grid')).map((r) => r.package_id)).toEqual([PKG]); }); - it('a binding-preserving migration (server-stated `source`) is exempt', async () => { + it('W3, the kernel-item overlay: a package-less save of an item a code package ships is an overlay (intent `override-artifact`), never judged a create', async () => { + const { protocol } = await boot(); + // `task` ships in BASE_PKG's code and no sys_metadata row carries it, + // so with the intent check gone this save would read as a create. + const answer = await protocol.saveMetaItem({ type: 'object', name: 'task', item: { ...TASK, label: 'Task (customized)' } }) + .then(() => ({ code: 'SAVED' }), (error: { code?: string }) => ({ code: error?.code })); + expect(answer.code, JSON.stringify(answer)).not.toBe('WRITABLE_PACKAGE_REQUIRED'); + }); + + it('W4, the external-datasource import: the server-stated `writeFace: \'external-import\'` lands loose', async () => { + const { protocol, rows } = await boot(); + await protocol.saveMetaItem({ type: 'view', name: 'imported_grid', item: viewBody('imported_grid', 'A'), writeFace: 'external-import' }); + expect((await rows('view', 'imported_grid')).map((r) => r.package_id)).toEqual([null]); + }); + + it('W12, a binding-preserving migration (server-stated `source`) is exempt', async () => { const { protocol, rows } = await boot(); await protocol.saveMetaItem({ type: 'view', name: 'migrated_grid', item: viewBody('migrated_grid', 'A'), source: 'migrate-stored' }); expect((await rows('view', 'migrated_grid')).map((r) => r.package_id)).toEqual([null]); diff --git a/packages/spec/src/migrations/entries/semantic/19.packageless-create-refused.ts b/packages/spec/src/migrations/entries/semantic/19.packageless-create-refused.ts index 86ffa82b191..2fb9693adee 100644 --- a/packages/spec/src/migrations/entries/semantic/19.packageless-create-refused.ts +++ b/packages/spec/src/migrations/entries/semantic/19.packageless-create-refused.ts @@ -16,28 +16,41 @@ export const entry: SemanticMigration = { + '`200` storing a new package-less ("loose") row, and `POST /automation` creating a package-less ' + 'flow, TO `422 WRITABLE_PACKAGE_REQUIRED` naming the writable packages, nothing stored; ' + '`POST /automation` is unmounted and `PUT /api/v1/automation/{name}` of a new name answers `422 ' - + 'WRITABLE_PACKAGE_REQUIRED` naming the metadata door', + + 'WRITABLE_PACKAGE_REQUIRED` naming the metadata door. The permission-set clone door ' + + '(`POST /api/v1/security/permission-sets/{name}/clone`) with no `package` in its body is a ' + + 'package-less create too, and answers the same `422`. Separately, a flow saved through ' + + '`PUT /api/v1/meta/flow/{name}` whose `notify` node names a channel no plugin registers: FROM stored ' + + 'and armed, TO refused at the runtime publish gate (rule `flow-notify-channel-unregistered`) once the ' + + 'boot has settled, as the `/automation` door already refused it', replacement: 'name the package the new item belongs to: `?package=PKG` on the REST door, `--package PKG` on ' + '`os meta register`, `{ packageId }` on `client.meta.saveItem`, or choose a package in Studio. ' + 'Create a flow with `PUT /api/v1/meta/flow/{name}?package=PKG` (it registers and arms in the same ' + 'boot); a flow triggered on an object another package ships needs a package that declares that ' + 'package as a dependency. Existing package-less items save in place unchanged, and Studio\'s ' - + '"move into package" moves them', + + '"move into package" moves them. A permission-set clone names its landing package with `package` in ' + + 'the request body. A flow naming an unregistered `notify` channel: correct the channel name, or ' + + 'install the plugin that registers it', reason: 'ADR-0070 D1: a runtime create MUST resolve to a writable package, and the kernel write path is the ' + 'enforcement point of last resort. The save path judged only a NAMED package, so every door that ' + 'named none scattered new loose items with no container to version, publish, move or delete. ' + 'Studio now asks for a package before a create and loose items have a move door; this closes the ' - + 'kernel so no new loose item is made. Four writers keep a named exemption (ADR-0084 amendment ' - + '2026-11-26-org): the kernel-item overlay, the external-datasource import, the binding-preserving ' - + 'migrations and platform registration. The automation create door held no package, so it is ' - + 'retired rather than given one (Q-g C).', + + 'kernel so no new loose item is made. Five writers keep a named exemption: the kernel-item overlay, ' + + 'the external-datasource import, the binding-preserving migrations and platform registration ' + + '(ADR-0084 amendment 2026-11-26-org), and `os migrate organization-ownership --apply`\'s conversions ' + + 'of rows stored before the upgrade (ruling 7380917604), which land loose and are listed in its ' + + 'report with the move door. The automation create door held no package, so it is retired rather ' + + 'than given one (Q-g C). Both flow doors now ask one notify-channel predicate, so a flow the ' + + '`/automation` door refused is no longer stored through `/meta`.', acceptanceCriteria: 'A save naming no package of a new name answers 422 `WRITABLE_PACKAGE_REQUIRED` and stores nothing, ' + 'on `/meta` publish and draft and on `os meta register` (non-zero exit, the server\'s sentence ' + 'printed); `POST /api/v1/automation` is not served; `PUT /api/v1/automation/{new}` answers 422. ' + 'Verify UNAFFECTED: an in-place save, draft save, delete and per-item publish of an existing ' + 'package-less item; a package-less save of a name a package holds; `os migrate meta --stored`; the ' - + 'external-datasource import; platform registration at boot; `PUT /api/v1/automation/{existing}`.', + + 'external-datasource import; platform registration at boot; `os migrate organization-ownership ' + + '--apply` (its converted rows land loose and its report lists them); `PUT /api/v1/automation/{existing}`. ' + + 'A permission-set clone with no `package` answers 422; with one it lands there. A flow whose `notify` ' + + 'node names an unregistered channel is refused through `/meta` once the boot has settled.', }; From 13df4a6dcd85b118755e4e8e7c1180566d184e80 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 16:19:48 +0000 Subject: [PATCH 12/23] =?UTF-8?q?fix:=20L2=20findings=20=E2=80=94=20no=20p?= =?UTF-8?q?ackage-duplicate=20skip;=20migration=20entry=20and=20call-site?= =?UTF-8?q?=20comment=20name=20the=20fifth=20exemption=20and=20the=20notif?= =?UTF-8?q?y-channel=20narrowing;=20named=20W3/W4=20pins;=20notify=20rule?= =?UTF-8?q?=20states=20its=20judging=20mode;=20plugin-sharing=20patch?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CasbvyQnz4st6s79P9 --- .../38174-packageless-create-refused.md | 2 +- .../meta-packageless-create-refused.test.ts | 24 ++++++++++++------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/.changeset/38174-packageless-create-refused.md b/.changeset/38174-packageless-create-refused.md index 5e4eb0d8fe9..e3a20eeffac 100644 --- a/.changeset/38174-packageless-create-refused.md +++ b/.changeset/38174-packageless-create-refused.md @@ -12,7 +12,7 @@ feat(metadata-protocol)!: the kernel refuses a package-less create; `POST /api/v Clause-②: no (narrowing) Metadata-protocol: narrowed -Skills-docs: none — no skill teaches a package-less create, `POST /api/v1/automation` or `client.automation.create`; `skills/objectstack-platform/references/operations.md` lists `os meta register` as "create/update" and names no flag, which stays true (a create now names `--package`, and the refusal says so) +Skills-docs: follow-up owed — content/docs/permissions/permission-sets.mdx (the console's permission-set clone with no package; skills/** teach no package-less create, `POST /api/v1/automation` or `client.automation.create`) diff --git a/packages/runtime/src/meta-packageless-create-refused.test.ts b/packages/runtime/src/meta-packageless-create-refused.test.ts index ee4af6237ca..a73a4eb58f6 100644 --- a/packages/runtime/src/meta-packageless-create-refused.test.ts +++ b/packages/runtime/src/meta-packageless-create-refused.test.ts @@ -28,7 +28,10 @@ * Ablation: dropping the `packagelessCreateRefusal` call from * `saveMetaItemUnaudited` (`protocol-save.ts`) turns every "refused" case RED * (the save answers 200 and a loose row is stored) and leaves every control - * GREEN. + * GREEN. Each named exemption has its own: dropping the intent check turns W3 + * RED (the overlay is refused as a create), dropping the `external-import` + * line turns W4 RED, and dropping the provenance line turns W5's "saved loose + * with it" cases RED. */ // Pays the lint root's first load at collection, never inside a clocked case. @@ -130,7 +133,7 @@ async function boot() { }, { context: { isSystem: true } } as any); }; - return { protocol, put, rows, seedLooseRow }; + return { engine, protocol, put, rows, seedLooseRow }; } describe('[#38174] PUT /meta/:type/:name naming no package, of a new name, is refused', () => { @@ -200,13 +203,16 @@ describe('[#38174] controls — what the close does not reach', () => { expect((await rows('view', 'drafted_grid')).map((r) => r.package_id)).toEqual([PKG]); }); - it('W3, the kernel-item overlay: a package-less save of an item a code package ships is an overlay (intent `override-artifact`), never judged a create', async () => { - const { protocol } = await boot(); - // `task` ships in BASE_PKG's code and no sys_metadata row carries it, - // so with the intent check gone this save would read as a create. - const answer = await protocol.saveMetaItem({ type: 'object', name: 'task', item: { ...TASK, label: 'Task (customized)' } }) - .then(() => ({ code: 'SAVED' }), (error: { code?: string }) => ({ code: error?.code })); - expect(answer.code, JSON.stringify(answer)).not.toBe('WRITABLE_PACKAGE_REQUIRED'); + it('W3, the kernel-item overlay: a package-less save of a view a code package ships is an overlay (intent `override-artifact`), never judged a create', async () => { + const { engine, protocol, rows } = await boot(); + // The view ships in BASE_PKG's code (the registry), and no stored row + // carries it: the overlay is the only thing that makes this not a create. + const shipped = viewBody('shipped_grid', 'Shipped'); + (engine.registry as any).registerItem('view', clone(shipped), 'name', BASE_PKG); + const result = await protocol.saveMetaItem({ type: 'view', name: 'shipped_grid', item: { ...shipped, label: 'Customized' } }); + expect(result.success).toBe(true); + expect(result.message).toMatch(/customization overlay/); + expect((await rows('view', 'shipped_grid')).map((r) => r.package_id)).toEqual([null]); }); it('W4, the external-datasource import: the server-stated `writeFace: \'external-import\'` lands loose', async () => { From 90c84ed02034208b79c455dd392dcbf3d3a61a14 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 16:25:00 +0000 Subject: [PATCH 13/23] test: the duplicate face's server-face pins name their target package, as the door does Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CasbvyQnz4st6s79P9 --- .../src/protocol.save-door-lock-family.test.ts | 3 ++- .../src/protocol.save-door-protection.test.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/metadata-protocol/src/protocol.save-door-lock-family.test.ts b/packages/metadata-protocol/src/protocol.save-door-lock-family.test.ts index d98fa03cde0..c814a66a58c 100644 --- a/packages/metadata-protocol/src/protocol.save-door-lock-family.test.ts +++ b/packages/metadata-protocol/src/protocol.save-door-lock-family.test.ts @@ -358,7 +358,8 @@ for (const writeFace of AUTHOR_FACES) { describe('a lock a server face stamps still binds afterwards', () => { const faces = [ { face: "`source: 'migrate-stored'`", extra: { source: 'migrate-stored', force: true } }, - { face: "`writeFace: 'package-duplicate'`", extra: { writeFace: 'package-duplicate' } }, + // The duplicate door always names its target package. + { face: "`writeFace: 'package-duplicate'`", extra: { writeFace: 'package-duplicate', packageId: TEST_PKG } }, ] as const; for (const { face, extra } of faces) { diff --git a/packages/metadata-protocol/src/protocol.save-door-protection.test.ts b/packages/metadata-protocol/src/protocol.save-door-protection.test.ts index 24e090dba2d..bbc3f178023 100644 --- a/packages/metadata-protocol/src/protocol.save-door-protection.test.ts +++ b/packages/metadata-protocol/src/protocol.save-door-protection.test.ts @@ -264,7 +264,8 @@ describe('the server-stated rewrites strip the block instead — a row stored be const app = PROBES[0]; const rewrites = [ { face: '`source: \'migrate-stored\'` (the stored migration, the flow credential move)', extra: { source: 'migrate-stored', force: true } }, - { face: '`writeFace: \'package-duplicate\'`', extra: { writeFace: 'package-duplicate' } }, + // The duplicate door always names its target package. + { face: '`writeFace: \'package-duplicate\'`', extra: { writeFace: 'package-duplicate', packageId: TEST_PKG } }, ] as const; for (const rewrite of rewrites) { From ecacc0a5dcf335e1f3d41c6a11caec0386290e74 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 16:36:10 +0000 Subject: [PATCH 14/23] =?UTF-8?q?test:=20CI=20fixes=20=E2=80=94=20collecti?= =?UTF-8?q?on-time=20loads=20for=20the=20migrated=20suites,=20ledger=20hea?= =?UTF-8?q?der=20totals,=20package-naming=20saves=20in=20http-conformance,?= =?UTF-8?q?=20plugin-audit=20and=20the=20live=20Studio=20page=20specs,=20a?= =?UTF-8?q?=20seed=20helper's=20body=20type?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CasbvyQnz4st6s79P9 --- ...ed-legacy-organization.integration.test.ts | 11 ++++++++++ .../organization-ownership-apply.test.ts | 2 ++ ...tocol.active-save-namespace-prefix.test.ts | 2 ++ ...ol.cbp-master-not-writable-refusal.test.ts | 2 ++ ...tocol.code-defined-datasource-door.test.ts | 2 ++ .../src/protocol.credential-channel.test.ts | 2 ++ ...col.dashboard-dataset-publish-gate.test.ts | 2 ++ ...plicate-global-filter-name-refusal.test.ts | 2 ++ ...urce-credentials-ref-own-reference.test.ts | 2 ++ ...urce-credentials-ref-restore-doors.test.ts | 2 ++ ...l-binding-named-datasource-refusal.test.ts | 2 ++ ...binding-primary-datasource-refusal.test.ts | 2 ++ .../protocol.flow-org-override-closed.test.ts | 2 ++ .../src/protocol.item-name-every-door.test.ts | 2 ++ .../src/protocol.item-name-grammar.test.ts | 2 ++ .../src/protocol.lifecycle-audit-rows.test.ts | 2 ++ .../protocol.lock-gate-fail-closed.test.ts | 2 ++ .../protocol.named-base-every-type.test.ts | 2 ++ ...protocol.named-base-stored-binding.test.ts | 2 ++ ....permission-set-name-cross-package.test.ts | 2 ++ ...rotocol.platform-schedule-org-gate.test.ts | 2 ++ .../src/protocol.refusal-audit-rows.test.ts | 2 ++ .../src/protocol.save-door-protection.test.ts | 2 ++ .../src/protocol.save-receipt-wording.test.ts | 2 ++ ...ition-follows-metadata.integration.test.ts | 6 +++++- ...eta-save-preconditions.conformance.test.ts | 15 +++++++++++-- ...r-anonymous-floor.hono.integration.test.ts | 2 ++ .../automation-body-validation.test.ts | 2 ++ ...omation-flow-credential-projection.test.ts | 2 ++ .../automation-flow-save-actor.test.ts | 2 ++ .../automation-packaged-base-lock.test.ts | 2 ++ .../automation-put-post-error-parity.test.ts | 2 ++ .../automation-register-error-class.test.ts | 2 ++ .../automation-tenant-authored-write.test.ts | 2 ++ .../automation-toggle-deny-message.test.ts | 2 ++ ...automation-walled-definition-write.test.ts | 2 ++ .../automation-write-capability-gate.test.ts | 2 ++ .../domains/field-error-code-catalog.test.ts | 2 ++ .../domains/meta-app-package-id-key.test.ts | 2 ++ .../domains/meta-layers-draft-layer.test.ts | 2 ++ .../src/domains/meta-package-all-fold.test.ts | 2 ++ .../src/domains/meta-save-actor.test.ts | 2 ++ .../meta-save-preconditions-parity.test.ts | 2 ++ .../hook-handler-package-scope.pin.test.ts | 2 ++ .../src/meta-compound-arity-mint-door.test.ts | 2 ++ .../src/meta-field-overlay-lock.test.ts | 2 ++ .../meta-packageless-create-refused.test.ts | 2 ++ .../src/meta-sharing-rule-door.test.ts | 2 ++ ...-runtime-owner-refusal.integration.test.ts | 2 ++ .../standalone-stack-hydrate-metadata.test.ts | 2 +- .../spec/dropped-refinements.baseline.json | 4 ++-- .../live/studio-detail-save-at-once.spec.ts | 21 +++++++++++++++++-- ui/e2e/live/studio-editor.spec.ts | 21 +++++++++++++++++-- 53 files changed, 162 insertions(+), 10 deletions(-) diff --git a/packages/cli/src/commands/migrate/meta-stored-legacy-organization.integration.test.ts b/packages/cli/src/commands/migrate/meta-stored-legacy-organization.integration.test.ts index d7f3f98626d..a7b32c41086 100644 --- a/packages/cli/src/commands/migrate/meta-stored-legacy-organization.integration.test.ts +++ b/packages/cli/src/commands/migrate/meta-stored-legacy-organization.integration.test.ts @@ -43,6 +43,17 @@ import MigrateMeta from './meta.js'; import '@objectstack/runtime'; import '@objectstack/metadata-protocol'; import '@objectstack/platform-objects/plugin'; +import '@objectstack/service-datasource'; +import '@objectstack/driver-turso'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/cloud-connection'; +import '@objectstack/metadata'; +import '@objectstack/plugin-hono-server'; +import '@objectstack/service-automation'; +import '@objectstack/service-settings'; +import '@objectstack/service-storage'; const HERE = dirname(fileURLToPath(import.meta.url)); const CLI_ROOT = resolve(HERE, '..', '..', '..'); diff --git a/packages/cli/src/utils/organization-ownership-apply.test.ts b/packages/cli/src/utils/organization-ownership-apply.test.ts index b08c86ece98..694632ae641 100644 --- a/packages/cli/src/utils/organization-ownership-apply.test.ts +++ b/packages/cli/src/utils/organization-ownership-apply.test.ts @@ -64,6 +64,8 @@ import '@objectstack/platform-objects/plugin'; import '@objectstack/rest'; import '@objectstack/runtime'; import '@objectstack/service-datasource'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/spec/migrations'; let dir: string; let file: string; diff --git a/packages/metadata-protocol/src/protocol.active-save-namespace-prefix.test.ts b/packages/metadata-protocol/src/protocol.active-save-namespace-prefix.test.ts index d18050c7ec3..ae470a24828 100644 --- a/packages/metadata-protocol/src/protocol.active-save-namespace-prefix.test.ts +++ b/packages/metadata-protocol/src/protocol.active-save-namespace-prefix.test.ts @@ -7,6 +7,8 @@ import { describe, expect, it } from 'vitest'; // `@objectstack/objectql`: objectql DEPENDS ON this package. import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; /** * [#24547 · ADR-0129 D2] The package namespace-prefix rule holds at ALL THREE diff --git a/packages/metadata-protocol/src/protocol.cbp-master-not-writable-refusal.test.ts b/packages/metadata-protocol/src/protocol.cbp-master-not-writable-refusal.test.ts index 5ef47025635..9efaaa27dda 100644 --- a/packages/metadata-protocol/src/protocol.cbp-master-not-writable-refusal.test.ts +++ b/packages/metadata-protocol/src/protocol.cbp-master-not-writable-refusal.test.ts @@ -14,6 +14,8 @@ import { describe, expect, it } from 'vitest'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate, type EngineFindOneQueryInput } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; const TEST_PKG = 'test_pkg'; diff --git a/packages/metadata-protocol/src/protocol.code-defined-datasource-door.test.ts b/packages/metadata-protocol/src/protocol.code-defined-datasource-door.test.ts index 624c149bdf4..e164d9d6a9e 100644 --- a/packages/metadata-protocol/src/protocol.code-defined-datasource-door.test.ts +++ b/packages/metadata-protocol/src/protocol.code-defined-datasource-door.test.ts @@ -43,6 +43,8 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from './protocol.js'; import { SysMetadataRepository, resetEnvWritableMetadataTypes } from './sys-metadata-repository.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; /** The showcase's code-defined datasource and the package that declares it. */ const CODE_DS = 'showcase_external'; diff --git a/packages/metadata-protocol/src/protocol.credential-channel.test.ts b/packages/metadata-protocol/src/protocol.credential-channel.test.ts index 217275a154b..02137e2deff 100644 --- a/packages/metadata-protocol/src/protocol.credential-channel.test.ts +++ b/packages/metadata-protocol/src/protocol.credential-channel.test.ts @@ -32,6 +32,8 @@ import { import { registerMetadataTypeRedactor } from '@objectstack/spec/kernel'; import { ObjectStackProtocolImplementation, type MetadataCredentialChannel } from './protocol.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; const TEST_PKG = 'test_pkg'; const V1 = 'pin-protocol-secret-v1-3f1a'; diff --git a/packages/metadata-protocol/src/protocol.dashboard-dataset-publish-gate.test.ts b/packages/metadata-protocol/src/protocol.dashboard-dataset-publish-gate.test.ts index 8bb40c04555..6ed9b43f216 100644 --- a/packages/metadata-protocol/src/protocol.dashboard-dataset-publish-gate.test.ts +++ b/packages/metadata-protocol/src/protocol.dashboard-dataset-publish-gate.test.ts @@ -46,6 +46,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; // would close a dependency cycle turbo rejects outright (#5619). import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; // ───────────────────────────────────────────────────────────────────────────── // Fixtures — every one of them Zod-valid, so the refusal under test is the one diff --git a/packages/metadata-protocol/src/protocol.dashboard-duplicate-global-filter-name-refusal.test.ts b/packages/metadata-protocol/src/protocol.dashboard-duplicate-global-filter-name-refusal.test.ts index 8ef6d2326f8..04339173d22 100644 --- a/packages/metadata-protocol/src/protocol.dashboard-duplicate-global-filter-name-refusal.test.ts +++ b/packages/metadata-protocol/src/protocol.dashboard-duplicate-global-filter-name-refusal.test.ts @@ -15,6 +15,8 @@ import { describe, expect, it } from 'vitest'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate, type EngineFindOneQueryInput } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; const TEST_PKG = 'test_pkg'; diff --git a/packages/metadata-protocol/src/protocol.datasource-credentials-ref-own-reference.test.ts b/packages/metadata-protocol/src/protocol.datasource-credentials-ref-own-reference.test.ts index bbb37bd9f2a..212da097cf3 100644 --- a/packages/metadata-protocol/src/protocol.datasource-credentials-ref-own-reference.test.ts +++ b/packages/metadata-protocol/src/protocol.datasource-credentials-ref-own-reference.test.ts @@ -31,6 +31,8 @@ import { describe, expect, it } from 'vitest'; import { assertEngineFindOnePredicate, assertEngineUpdateDispatch, hashSpec } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from './protocol.js'; import type { MetadataWriteFace } from './protocol.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; interface Row { id: string; diff --git a/packages/metadata-protocol/src/protocol.datasource-credentials-ref-restore-doors.test.ts b/packages/metadata-protocol/src/protocol.datasource-credentials-ref-restore-doors.test.ts index 84713aa2ead..81e4ce558db 100644 --- a/packages/metadata-protocol/src/protocol.datasource-credentials-ref-restore-doors.test.ts +++ b/packages/metadata-protocol/src/protocol.datasource-credentials-ref-restore-doors.test.ts @@ -39,6 +39,8 @@ import { assertEngineFindOnePredicate, } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; interface Row { id: string; diff --git a/packages/metadata-protocol/src/protocol.external-binding-named-datasource-refusal.test.ts b/packages/metadata-protocol/src/protocol.external-binding-named-datasource-refusal.test.ts index 74878519bcb..163e2801135 100644 --- a/packages/metadata-protocol/src/protocol.external-binding-named-datasource-refusal.test.ts +++ b/packages/metadata-protocol/src/protocol.external-binding-named-datasource-refusal.test.ts @@ -37,6 +37,8 @@ import { describe, expect, it } from 'vitest'; // not `@objectstack/objectql`, which depends on this package. import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; interface Row { id: string; diff --git a/packages/metadata-protocol/src/protocol.external-binding-primary-datasource-refusal.test.ts b/packages/metadata-protocol/src/protocol.external-binding-primary-datasource-refusal.test.ts index cdbd4bc1735..d244d4ad8c8 100644 --- a/packages/metadata-protocol/src/protocol.external-binding-primary-datasource-refusal.test.ts +++ b/packages/metadata-protocol/src/protocol.external-binding-primary-datasource-refusal.test.ts @@ -22,6 +22,8 @@ import { describe, expect, it } from 'vitest'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate, type EngineFindOneQueryInput } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; /** The writable package the control saves name. */ const TEST_PKG = 'test_pkg'; diff --git a/packages/metadata-protocol/src/protocol.flow-org-override-closed.test.ts b/packages/metadata-protocol/src/protocol.flow-org-override-closed.test.ts index c6748431583..412bc08c3c9 100644 --- a/packages/metadata-protocol/src/protocol.flow-org-override-closed.test.ts +++ b/packages/metadata-protocol/src/protocol.flow-org-override-closed.test.ts @@ -86,6 +86,8 @@ import { describe, expect, it } from 'vitest'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; import { DEFAULT_METADATA_TYPE_REGISTRY } from '@objectstack/spec/kernel'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; interface Row { id: string; diff --git a/packages/metadata-protocol/src/protocol.item-name-every-door.test.ts b/packages/metadata-protocol/src/protocol.item-name-every-door.test.ts index 3d054182cd1..1196f7419a0 100644 --- a/packages/metadata-protocol/src/protocol.item-name-every-door.test.ts +++ b/packages/metadata-protocol/src/protocol.item-name-every-door.test.ts @@ -67,6 +67,8 @@ import { hashSpec, } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; /** * [#26708] The packages this file's saves name, installed: a save naming a diff --git a/packages/metadata-protocol/src/protocol.item-name-grammar.test.ts b/packages/metadata-protocol/src/protocol.item-name-grammar.test.ts index b6b53218453..a99e1ef7aa4 100644 --- a/packages/metadata-protocol/src/protocol.item-name-grammar.test.ts +++ b/packages/metadata-protocol/src/protocol.item-name-grammar.test.ts @@ -43,6 +43,8 @@ import { describe, expect, it } from 'vitest'; // below cannot accept a call ObjectQL itself refuses. import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; interface Row { id: string; diff --git a/packages/metadata-protocol/src/protocol.lifecycle-audit-rows.test.ts b/packages/metadata-protocol/src/protocol.lifecycle-audit-rows.test.ts index 274ed9c6889..7186a291cd2 100644 --- a/packages/metadata-protocol/src/protocol.lifecycle-audit-rows.test.ts +++ b/packages/metadata-protocol/src/protocol.lifecycle-audit-rows.test.ts @@ -94,6 +94,8 @@ import { describe, expect, it, vi } from 'vitest'; // rejects outright. import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; interface Row { id: string; diff --git a/packages/metadata-protocol/src/protocol.lock-gate-fail-closed.test.ts b/packages/metadata-protocol/src/protocol.lock-gate-fail-closed.test.ts index c6f36679aaf..96b13928819 100644 --- a/packages/metadata-protocol/src/protocol.lock-gate-fail-closed.test.ts +++ b/packages/metadata-protocol/src/protocol.lock-gate-fail-closed.test.ts @@ -89,6 +89,8 @@ import { describe, it, expect, vi } from 'vitest'; import { ErrorCode } from '@objectstack/spec/api'; import { ObjectStackProtocolImplementation } from './protocol.js'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; /** [#38174] An installed writable package: a save of a NEW item names one (ADR-0070 D1). */ const TEST_PKG = 'test_pkg'; diff --git a/packages/metadata-protocol/src/protocol.named-base-every-type.test.ts b/packages/metadata-protocol/src/protocol.named-base-every-type.test.ts index 54615573fba..bae00ccaf7a 100644 --- a/packages/metadata-protocol/src/protocol.named-base-every-type.test.ts +++ b/packages/metadata-protocol/src/protocol.named-base-every-type.test.ts @@ -7,6 +7,8 @@ import { describe, expect, it, vi } from 'vitest'; // `@objectstack/objectql`: objectql DEPENDS ON this package. import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; /** * [#26708, ADR-0070 D1] The named-base rule holds for EVERY type the `/meta` diff --git a/packages/metadata-protocol/src/protocol.named-base-stored-binding.test.ts b/packages/metadata-protocol/src/protocol.named-base-stored-binding.test.ts index 6fd7942c5d5..9536ee03f84 100644 --- a/packages/metadata-protocol/src/protocol.named-base-stored-binding.test.ts +++ b/packages/metadata-protocol/src/protocol.named-base-stored-binding.test.ts @@ -7,6 +7,8 @@ import { describe, expect, it, vi } from 'vitest'; // `@objectstack/objectql`: objectql DEPENDS ON this package. import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; /** * [#26921, #26708, ADR-0070 D1] The named-base rule reaches the two doors diff --git a/packages/metadata-protocol/src/protocol.permission-set-name-cross-package.test.ts b/packages/metadata-protocol/src/protocol.permission-set-name-cross-package.test.ts index 8121e2faee2..c4840ed5987 100644 --- a/packages/metadata-protocol/src/protocol.permission-set-name-cross-package.test.ts +++ b/packages/metadata-protocol/src/protocol.permission-set-name-cross-package.test.ts @@ -41,6 +41,8 @@ import { assertEngineFindOnePredicate, } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; /** The owners these cases publish into, installed (a save naming an uninstalled package is refused first). */ const OWNER_A = 'app.owner_a'; diff --git a/packages/metadata-protocol/src/protocol.platform-schedule-org-gate.test.ts b/packages/metadata-protocol/src/protocol.platform-schedule-org-gate.test.ts index fdd1c87eb87..c980257be85 100644 --- a/packages/metadata-protocol/src/protocol.platform-schedule-org-gate.test.ts +++ b/packages/metadata-protocol/src/protocol.platform-schedule-org-gate.test.ts @@ -60,6 +60,8 @@ import { PLATFORM_SCHEDULE_CREATE_RECORD_ORG_MISSING, findPlatformScheduleOrgGaps, } from './runtime-authoring-gate.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; // ───────────────────────────────────────────────────────────────────────────── // Fixtures — every one of them Zod-valid, so the refusal under test is the one diff --git a/packages/metadata-protocol/src/protocol.refusal-audit-rows.test.ts b/packages/metadata-protocol/src/protocol.refusal-audit-rows.test.ts index 77eec82e38a..8072b63b2eb 100644 --- a/packages/metadata-protocol/src/protocol.refusal-audit-rows.test.ts +++ b/packages/metadata-protocol/src/protocol.refusal-audit-rows.test.ts @@ -23,6 +23,8 @@ import { assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objec import { ObjectStackProtocolImplementation } from './protocol.js'; import { REFUSAL_AUDIT_CODES, refusalAuditEntry, withRefusalAudit } from './protocol-refusal-audit.js'; import { resetEnvWritableMetadataTypes } from './sys-metadata-repository.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; interface Row { id: string; diff --git a/packages/metadata-protocol/src/protocol.save-door-protection.test.ts b/packages/metadata-protocol/src/protocol.save-door-protection.test.ts index bbc3f178023..8a2569a5a46 100644 --- a/packages/metadata-protocol/src/protocol.save-door-protection.test.ts +++ b/packages/metadata-protocol/src/protocol.save-door-protection.test.ts @@ -44,6 +44,8 @@ import { applyProtection } from '@objectstack/spec/shared'; import { resolveThrownHttpError } from '@objectstack/types'; import { ObjectStackProtocolImplementation, overlaySchemaDeclaredKey } from './protocol.js'; import { resetEnvWritableMetadataTypes } from './sys-metadata-repository.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; type Row = Record; diff --git a/packages/metadata-protocol/src/protocol.save-receipt-wording.test.ts b/packages/metadata-protocol/src/protocol.save-receipt-wording.test.ts index ab30f0c0015..a7f3485a8be 100644 --- a/packages/metadata-protocol/src/protocol.save-receipt-wording.test.ts +++ b/packages/metadata-protocol/src/protocol.save-receipt-wording.test.ts @@ -50,6 +50,8 @@ import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFin import { DEFAULT_METADATA_TYPE_REGISTRY } from '@objectstack/spec/kernel'; import { ObjectStackProtocolImplementation } from './protocol.js'; import { resetEnvWritableMetadataTypes } from './sys-metadata-repository.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/lint'; interface Row { id: string; diff --git a/packages/plugins/plugin-audit/src/audit-writers.definition-follows-metadata.integration.test.ts b/packages/plugins/plugin-audit/src/audit-writers.definition-follows-metadata.integration.test.ts index 2f1ccb43c32..247ae472040 100644 --- a/packages/plugins/plugin-audit/src/audit-writers.definition-follows-metadata.integration.test.ts +++ b/packages/plugins/plugin-audit/src/audit-writers.definition-follows-metadata.integration.test.ts @@ -38,6 +38,8 @@ import { installDefaultOrganization } from './default-organization.testkit.js'; */ describe('audit writers answer from the current definition after a metadata-door change (#24565)', () => { const HARNESS_PACKAGE = 'com.objectstack.audit.test.definition-follows-metadata'; + /** The writable package the door's saves land in. */ + const AUTHORED_PACKAGE = 'com.objectstack.audit.test.authored'; const SYSTEM = { context: { isSystem: true } } satisfies DataEngineInsertOptions; let kernel: ObjectKernel; @@ -57,7 +59,8 @@ describe('audit writers answer from the current definition after a metadata-door }); const save = async (name: string, extra: Record = {}) => { - const result = await protocol.saveMetaItem({ type: 'object', name, item: objectBody(name, extra) }); + // A new item names a writable package (ADR-0070 D1). + const result = await protocol.saveMetaItem({ type: 'object', name, item: objectBody(name, extra), packageId: AUTHORED_PACKAGE }); expect(result?.success).toBe(true); }; @@ -95,6 +98,7 @@ describe('audit writers answer from the current definition after a metadata-door } as any, HARNESS_PACKAGE, ); + engine.registry.installPackage({ id: AUTHORED_PACKAGE, name: AUTHORED_PACKAGE, version: '1.0.0' } as any, 'authored'); await engine.syncSchemas(); // A real `single` install's Default Organization: the system writes below // derive it (ADR-0131 D9), as a fresh NOT NULL tenant column requires (D1). diff --git a/packages/qa/http-conformance/src/hono-meta-save-preconditions.conformance.test.ts b/packages/qa/http-conformance/src/hono-meta-save-preconditions.conformance.test.ts index 3dfedad130c..57c206e084d 100644 --- a/packages/qa/http-conformance/src/hono-meta-save-preconditions.conformance.test.ts +++ b/packages/qa/http-conformance/src/hono-meta-save-preconditions.conformance.test.ts @@ -93,6 +93,11 @@ afterEach(async () => { } }); +/** The writable package every save names. */ +const PKG = 'com.qa.conformance'; +/** The package the fixture's object ships in. */ +const BASE_PKG = 'com.qa.conformance_base'; + interface Answer { status: number; body: any } interface SaveOptions { headers?: Record; query?: Record } @@ -112,8 +117,14 @@ async function boot() { await kernel.bootstrap(); const ql = kernel.getService('objectql'); - ql.registerObject(TASK as any); + ql.registerObject(TASK as any, BASE_PKG); await ql.syncObjectSchema('task'); + // A new item names a writable package (ADR-0070 D1): the saves below land in it. + // The authored package depends on the one `task` ships in, so a view over + // `task` is inside its closure. + (ql as any).registry.installPackage( + { id: PKG, name: PKG, version: '1.0.0', dependencies: { [BASE_PKG]: '*' } }, 'authored', + ); vi.spyOn(HttpDispatcher.prototype as any, 'timedResolveExecutionContext') .mockImplementation(async () => clone(AUTHOR)); @@ -122,7 +133,7 @@ async function boot() { const send = async (method: 'PUT' | 'GET', name: string, { headers = {}, query = {} }: SaveOptions, body?: unknown): Promise => { const url = new URL(`http://localhost${PREFIX}/meta/view/${name}`); - for (const [k, v] of Object.entries(query)) url.searchParams.set(k, v); + for (const [k, v] of Object.entries(method === 'PUT' ? { package: PKG, ...query } : query)) url.searchParams.set(k, v); const res = await app.request(url.toString(), { method, headers: body === undefined ? headers : { 'content-type': 'application/json', ...headers }, diff --git a/packages/runtime/src/dispatcher-body-after-anonymous-floor.hono.integration.test.ts b/packages/runtime/src/dispatcher-body-after-anonymous-floor.hono.integration.test.ts index c61324bb5d8..10bcafd49b3 100644 --- a/packages/runtime/src/dispatcher-body-after-anonymous-floor.hono.integration.test.ts +++ b/packages/runtime/src/dispatcher-body-after-anonymous-floor.hono.integration.test.ts @@ -6,6 +6,8 @@ import { HonoServerPlugin } from '@objectstack/plugin-hono-server'; import type { IHttpServer } from '@objectstack/spec/contracts'; import { createDispatcherPlugin } from './dispatcher-plugin.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; /** * On the standalone server, an anonymous caller's answer does not depend on diff --git a/packages/runtime/src/domains/automation-body-validation.test.ts b/packages/runtime/src/domains/automation-body-validation.test.ts index c7b925ec318..388ecf950f7 100644 --- a/packages/runtime/src/domains/automation-body-validation.test.ts +++ b/packages/runtime/src/domains/automation-body-validation.test.ts @@ -25,6 +25,8 @@ import { describe, it, expect, vi } from 'vitest'; import { HttpDispatcher } from '../http-dispatcher.js'; import { validationFailureDetails } from '../validation-failure.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; function makeDispatcher() { const spies = { diff --git a/packages/runtime/src/domains/automation-flow-credential-projection.test.ts b/packages/runtime/src/domains/automation-flow-credential-projection.test.ts index 58f990edb22..c6723ed6cd0 100644 --- a/packages/runtime/src/domains/automation-flow-credential-projection.test.ts +++ b/packages/runtime/src/domains/automation-flow-credential-projection.test.ts @@ -26,6 +26,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { registerMetadataTypeRedactor } from '@objectstack/spec/kernel'; import { HttpDispatcher } from '../http-dispatcher.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; const SECRET = 'stored-hook-secret-20552'; const ROTATED = 'rotated-hook-secret-20552'; diff --git a/packages/runtime/src/domains/automation-flow-save-actor.test.ts b/packages/runtime/src/domains/automation-flow-save-actor.test.ts index 41ce51a43ae..ee46cdcce39 100644 --- a/packages/runtime/src/domains/automation-flow-save-actor.test.ts +++ b/packages/runtime/src/domains/automation-flow-save-actor.test.ts @@ -32,6 +32,8 @@ import { SysMetadata, SysMetadataHistoryObject, SysMetadataAuditObject } from '@ import { HttpDispatcher } from '../http-dispatcher.js'; import type { HttpProtocolContext } from '../http-dispatcher.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; /** `registry.registerObject` requires a package id (see the sibling real-stack tests). */ const TEST_PACKAGE_ID = 'objectstack-test'; diff --git a/packages/runtime/src/domains/automation-packaged-base-lock.test.ts b/packages/runtime/src/domains/automation-packaged-base-lock.test.ts index 9d85849f3bf..2f2ce897ed0 100644 --- a/packages/runtime/src/domains/automation-packaged-base-lock.test.ts +++ b/packages/runtime/src/domains/automation-packaged-base-lock.test.ts @@ -47,6 +47,8 @@ import { SchemaRegistry } from '@objectstack/objectql'; import { HttpDispatcher } from '../http-dispatcher.js'; import type { HttpProtocolContext } from '../http-dispatcher.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; /** A flow a code package ships — registered with a package id, as an artifact loader does. */ const PACKAGED = 'pkg_alert_flow'; diff --git a/packages/runtime/src/domains/automation-put-post-error-parity.test.ts b/packages/runtime/src/domains/automation-put-post-error-parity.test.ts index 438a6975e46..6e05789fea4 100644 --- a/packages/runtime/src/domains/automation-put-post-error-parity.test.ts +++ b/packages/runtime/src/domains/automation-put-post-error-parity.test.ts @@ -43,6 +43,8 @@ import { describe, it, expect } from 'vitest'; import { FlowSchema, validateControlFlow } from '@objectstack/spec/automation'; import { HttpDispatcher } from '../http-dispatcher.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; /** * [#21982] The node type the fake's #4277 walk judges: a PLUGIN type the spec diff --git a/packages/runtime/src/domains/automation-register-error-class.test.ts b/packages/runtime/src/domains/automation-register-error-class.test.ts index 63667cbabfd..6ff524b446c 100644 --- a/packages/runtime/src/domains/automation-register-error-class.test.ts +++ b/packages/runtime/src/domains/automation-register-error-class.test.ts @@ -72,6 +72,8 @@ import { describe, it, expect, vi } from 'vitest'; import { FlowSchema, validateControlFlow } from '@objectstack/spec/automation'; import { HttpDispatcher } from '../http-dispatcher.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; /** * [#21982] The node type the fake's #4277 walk judges: a PLUGIN type the spec diff --git a/packages/runtime/src/domains/automation-tenant-authored-write.test.ts b/packages/runtime/src/domains/automation-tenant-authored-write.test.ts index 171e89affe0..1003693d02e 100644 --- a/packages/runtime/src/domains/automation-tenant-authored-write.test.ts +++ b/packages/runtime/src/domains/automation-tenant-authored-write.test.ts @@ -40,6 +40,8 @@ import { FlowSchema } from '@objectstack/spec/automation'; import { HttpDispatcher } from '../http-dispatcher.js'; import { FLOW_CLONE_STATUS } from '../flow-clone.js'; import type { HttpProtocolContext } from '../http-dispatcher.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; const PACKAGED = 'pkg_alert_flow'; const PACKAGE_ID = 'com.example.pkg'; diff --git a/packages/runtime/src/domains/automation-toggle-deny-message.test.ts b/packages/runtime/src/domains/automation-toggle-deny-message.test.ts index 36670d612cf..8c6aeacbe2c 100644 --- a/packages/runtime/src/domains/automation-toggle-deny-message.test.ts +++ b/packages/runtime/src/domains/automation-toggle-deny-message.test.ts @@ -55,6 +55,8 @@ import { describe, it, expect, vi } from 'vitest'; import { HttpDispatcher } from '../http-dispatcher.js'; import type { HttpProtocolContext } from '../http-dispatcher.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; const FLOW = 'lead_auto_assignment'; const CAPABILITY = 'manage_metadata'; diff --git a/packages/runtime/src/domains/automation-walled-definition-write.test.ts b/packages/runtime/src/domains/automation-walled-definition-write.test.ts index 03322a357d2..7c7d088e378 100644 --- a/packages/runtime/src/domains/automation-walled-definition-write.test.ts +++ b/packages/runtime/src/domains/automation-walled-definition-write.test.ts @@ -17,6 +17,8 @@ import { describe, it, expect, vi } from 'vitest'; import { HttpDispatcher } from '../http-dispatcher.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; const FLOW = 'vendor_lead_router'; const DEFINITION = { diff --git a/packages/runtime/src/domains/automation-write-capability-gate.test.ts b/packages/runtime/src/domains/automation-write-capability-gate.test.ts index 9f776dc6ab0..e5911b1a3c7 100644 --- a/packages/runtime/src/domains/automation-write-capability-gate.test.ts +++ b/packages/runtime/src/domains/automation-write-capability-gate.test.ts @@ -71,6 +71,8 @@ import { describe, it, expect, vi } from 'vitest'; import { HttpDispatcher } from '../http-dispatcher.js'; import type { HttpProtocolContext } from '../http-dispatcher.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; const FLOW = 'lead_auto_assignment'; diff --git a/packages/runtime/src/domains/field-error-code-catalog.test.ts b/packages/runtime/src/domains/field-error-code-catalog.test.ts index 88dccbcb729..0c9345344d9 100644 --- a/packages/runtime/src/domains/field-error-code-catalog.test.ts +++ b/packages/runtime/src/domains/field-error-code-catalog.test.ts @@ -48,6 +48,8 @@ import { HttpDispatcher } from '../http-dispatcher.js'; import type { HttpProtocolContext } from '../http-dispatcher.js'; import { bindTestSecurityCatalog } from '../security/security-catalog.testkit.js'; import { VALIDATION_FAILED_STATUS, validationFailureDetails } from '../validation-failure.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; interface FieldRow { field?: unknown; diff --git a/packages/runtime/src/domains/meta-app-package-id-key.test.ts b/packages/runtime/src/domains/meta-app-package-id-key.test.ts index 811dafcf712..b235d615dc2 100644 --- a/packages/runtime/src/domains/meta-app-package-id-key.test.ts +++ b/packages/runtime/src/domains/meta-app-package-id-key.test.ts @@ -50,6 +50,8 @@ import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protoco import { SysMetadata, SysMetadataHistoryObject, SysMetadataAuditObject } from '@objectstack/platform-objects/metadata'; import { RestServer } from '@objectstack/rest'; import { HttpDispatcher } from '../http-dispatcher.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; const PREFIX = '/api/v1'; const META = `${PREFIX}/meta`; diff --git a/packages/runtime/src/domains/meta-layers-draft-layer.test.ts b/packages/runtime/src/domains/meta-layers-draft-layer.test.ts index 4a4fff28bb5..cc52dcd4716 100644 --- a/packages/runtime/src/domains/meta-layers-draft-layer.test.ts +++ b/packages/runtime/src/domains/meta-layers-draft-layer.test.ts @@ -40,6 +40,8 @@ import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protoco import { SysMetadata, SysMetadataHistoryObject, SysMetadataAuditObject } from '@objectstack/platform-objects/metadata'; import { RestServer } from '@objectstack/rest'; import { HttpDispatcher } from '../http-dispatcher.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; const PREFIX = '/api/v1'; const META = `${PREFIX}/meta`; diff --git a/packages/runtime/src/domains/meta-package-all-fold.test.ts b/packages/runtime/src/domains/meta-package-all-fold.test.ts index e47d7d7c38c..484836056aa 100644 --- a/packages/runtime/src/domains/meta-package-all-fold.test.ts +++ b/packages/runtime/src/domains/meta-package-all-fold.test.ts @@ -52,6 +52,8 @@ import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protoco import { SysMetadata, SysMetadataHistoryObject, SysMetadataAuditObject } from '@objectstack/platform-objects/metadata'; import { RestServer } from '@objectstack/rest'; import { HttpDispatcher } from '../http-dispatcher.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; const PREFIX = '/api/v1'; const META = `${PREFIX}/meta`; diff --git a/packages/runtime/src/domains/meta-save-actor.test.ts b/packages/runtime/src/domains/meta-save-actor.test.ts index e79a9e51193..5d4befee7be 100644 --- a/packages/runtime/src/domains/meta-save-actor.test.ts +++ b/packages/runtime/src/domains/meta-save-actor.test.ts @@ -37,6 +37,8 @@ import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protoco import { SysMetadata, SysMetadataHistoryObject, SysMetadataAuditObject } from '@objectstack/platform-objects/metadata'; import { RestServer } from '@objectstack/rest'; import { HttpDispatcher } from '../http-dispatcher.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; const PREFIX = '/api/v1'; const META = `${PREFIX}/meta`; diff --git a/packages/runtime/src/domains/meta-save-preconditions-parity.test.ts b/packages/runtime/src/domains/meta-save-preconditions-parity.test.ts index 45a2206f386..7769d7cb83b 100644 --- a/packages/runtime/src/domains/meta-save-preconditions-parity.test.ts +++ b/packages/runtime/src/domains/meta-save-preconditions-parity.test.ts @@ -56,6 +56,8 @@ import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protoco import { SysMetadata, SysMetadataHistoryObject, SysMetadataAuditObject } from '@objectstack/platform-objects/metadata'; import { RestServer } from '@objectstack/rest'; import { HttpDispatcher } from '../http-dispatcher.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; const PREFIX = '/api/v1'; const META = `${PREFIX}/meta`; diff --git a/packages/runtime/src/hook-handler-package-scope.pin.test.ts b/packages/runtime/src/hook-handler-package-scope.pin.test.ts index 0b90bb3a8d0..77dc287f617 100644 --- a/packages/runtime/src/hook-handler-package-scope.pin.test.ts +++ b/packages/runtime/src/hook-handler-package-scope.pin.test.ts @@ -64,6 +64,8 @@ import { AppPlugin } from './app-plugin.js'; import { DefaultDatasourcePlugin } from './default-datasource-plugin.js'; import { createDispatcherPlugin } from './dispatcher-plugin.js'; import { loadArtifactBundle } from './load-artifact-bundle.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; const BOOT_TIMEOUT = 180_000; const ORIGIN = 'http://localhost:3000'; diff --git a/packages/runtime/src/meta-compound-arity-mint-door.test.ts b/packages/runtime/src/meta-compound-arity-mint-door.test.ts index 13a237575ce..f264cafda88 100644 --- a/packages/runtime/src/meta-compound-arity-mint-door.test.ts +++ b/packages/runtime/src/meta-compound-arity-mint-door.test.ts @@ -50,6 +50,8 @@ import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFin import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; import { HttpDispatcher } from './http-dispatcher.js'; import type { HttpDispatcherResult } from './http-dispatcher.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; interface Row { id: string; [k: string]: unknown } diff --git a/packages/runtime/src/meta-field-overlay-lock.test.ts b/packages/runtime/src/meta-field-overlay-lock.test.ts index a8981ce257e..c5a5c420207 100644 --- a/packages/runtime/src/meta-field-overlay-lock.test.ts +++ b/packages/runtime/src/meta-field-overlay-lock.test.ts @@ -102,6 +102,8 @@ import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFin import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; import { HttpDispatcher } from './http-dispatcher.js'; import type { HttpDispatcherResult } from './http-dispatcher.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; // --------------------------------------------------------------------------- // Specimens diff --git a/packages/runtime/src/meta-packageless-create-refused.test.ts b/packages/runtime/src/meta-packageless-create-refused.test.ts index a73a4eb58f6..4e584bc8d6e 100644 --- a/packages/runtime/src/meta-packageless-create-refused.test.ts +++ b/packages/runtime/src/meta-packageless-create-refused.test.ts @@ -42,6 +42,8 @@ import { SqlDriver } from '@objectstack/driver-sql'; import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; import { SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject, hashSpec } from '@objectstack/metadata-core'; import { HttpDispatcher } from './http-dispatcher.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; const PREFIX = '/api/v1'; const META = `${PREFIX}/meta`; diff --git a/packages/runtime/src/meta-sharing-rule-door.test.ts b/packages/runtime/src/meta-sharing-rule-door.test.ts index e3e357dbbcf..1cf0c8c5409 100644 --- a/packages/runtime/src/meta-sharing-rule-door.test.ts +++ b/packages/runtime/src/meta-sharing-rule-door.test.ts @@ -36,6 +36,8 @@ import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFin import { ObjectStackProtocolImplementation, resetEnvWritableMetadataTypes } from '@objectstack/metadata-protocol'; import { HttpDispatcher } from './http-dispatcher.js'; import type { HttpDispatcherResult } from './http-dispatcher.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; const PKG = 'com.example.crm'; diff --git a/packages/runtime/src/package-promote-runtime-owner-refusal.integration.test.ts b/packages/runtime/src/package-promote-runtime-owner-refusal.integration.test.ts index 021e0a146a4..6c58058588a 100644 --- a/packages/runtime/src/package-promote-runtime-owner-refusal.integration.test.ts +++ b/packages/runtime/src/package-promote-runtime-owner-refusal.integration.test.ts @@ -75,6 +75,8 @@ import { } from '@objectstack/metadata-core'; import { PackageServicePlugin } from '@objectstack/service-package'; import { HttpDispatcher } from './http-dispatcher.js'; +// Pays these dist-resolved deps' first load at collection, never inside a clocked case. +import '@objectstack/metadata'; const P = 'com.probe.p'; const Q = 'com.probe.q'; diff --git a/packages/runtime/src/standalone-stack-hydrate-metadata.test.ts b/packages/runtime/src/standalone-stack-hydrate-metadata.test.ts index 5973f731ddf..31d1611bc77 100644 --- a/packages/runtime/src/standalone-stack-hydrate-metadata.test.ts +++ b/packages/runtime/src/standalone-stack-hydrate-metadata.test.ts @@ -76,7 +76,7 @@ async function boot(plugins: readonly unknown[]) { } /** [#38174] A package-less, env-wide row as the save door wrote one before ADR-0070 D1's create refusal. */ -const layLooseRow = (engine: ObjectQL, type: string, item: { name: string }) => engine.insert('sys_metadata', { +const layLooseRow = (engine: ObjectQL, type: string, item: { name: string; [key: string]: unknown }) => engine.insert('sys_metadata', { type, name: item.name, namespace: 'default', package_id: null, scope: 'platform', strategy: 'merge', state: 'active', version: 1, metadata: JSON.stringify(item), }, { context: { isSystem: true } } as never); diff --git a/packages/spec/dropped-refinements.baseline.json b/packages/spec/dropped-refinements.baseline.json index 193f4e778bb..cddf1da38bd 100644 --- a/packages/spec/dropped-refinements.baseline.json +++ b/packages/spec/dropped-refinements.baseline.json @@ -2,8 +2,8 @@ "description": "Shrink-only ledger of every PUBLISHED JSON Schema that is STILL WIDER than the Zod type it was generated from, because a rule written as `.refine()` reaches the runtime and not the file (#18670). `z.toJSONSchema()` has no arm for a `custom` check: a plain record, the same record with a `.refine()`, and the same record with an ABORTING `.refine()` all project byte-identically (measured on zod 4.4.3, the version packages/spec resolves). So a document one of these files ACCEPTS can still be refused at parse time, and an author -- or an AI -- validating against packages/spec/json-schema/** finds out a release later. Each `sites` path is a position under that schema at which a refinement is dropped; the same paths are written onto the artifact itself as `x-dropped-refinements`. Item 2 closed the first patterns: a refinement DECLARED through the closed list in src/shared/refinement-projection.ts is emitted into the published file, reads `projected` rather than `dropped`, and its row LEAVES this ledger in the same PR -- which is why the ledger shrinks and never grows on a repair. Every refinement outside that closed list stays here, and adding an arm to the list is a public-contract decision, not a refactor. Hand-edited on purpose and with no `gen:` script: a generator would let a new gap be admitted by running a command instead of by a decision, which is the silence this ledger exists to end. Adding, removing or moving a site fails packages/spec/scripts/build-schemas.ts until the line moves with it, and the failure prints the corrected entry in full. ⛔ Do not delete or weaken a refinement to shorten this file -- the runtime rule is correct; it is the projection that is silent, and the remedy is to teach the closed list a NAMED pattern, never to drop the rule.", "measured": { "zod": "4.4.3", - "publishedSchemasWithDroppedRefinements": 284, - "droppedRefinementSites": 1239, + "publishedSchemasWithDroppedRefinements": 282, + "droppedRefinementSites": 1231, "refinementSitesThatDidProject": 728, "refinementSitesWithNoJsonFormToCompare": 0 }, diff --git a/ui/e2e/live/studio-detail-save-at-once.spec.ts b/ui/e2e/live/studio-detail-save-at-once.spec.ts index b5c897c2151..c729e30c379 100644 --- a/ui/e2e/live/studio-detail-save-at-once.spec.ts +++ b/ui/e2e/live/studio-detail-save-at-once.spec.ts @@ -14,6 +14,21 @@ import { test, expect, type APIRequestContext, type Dialog } from '@playwright/t const API = process.env.LIVE_API_URL || 'http://localhost:3000'; const SHIPPED_PAGE = 'showcase_project_workspace'; +/** + * A new page names a writable package (objectstack ADR-0070 D1): each test + * authors one of its own, named from the page, and deletes it at the end. + */ +const packageOf = (name: string) => `com.e2e.${name.replace(/_/g, '')}`; + +async function authorPackage(request: APIRequestContext, name: string): Promise { + const pkgId = packageOf(name); + const res = await request.post(`${API}/api/v1/packages`, { + data: { manifest: { id: pkgId, name: `E2E ${name}`, version: '0.1.0', type: 'app' } }, + }); + expect(res.ok(), await res.text()).toBeTruthy(); + return pkgId; +} + async function authorEditablePage(request: APIRequestContext): Promise<{ name: string; firstRegionBlocks: number }> { const res = await request.get(`${API}/api/v1/meta/page/${SHIPPED_PAGE}`); expect(res.ok(), await res.text()).toBeTruthy(); @@ -21,7 +36,8 @@ async function authorEditablePage(request: APIRequestContext): Promise<{ name: s const body = Object.fromEntries(Object.entries(shipped).filter(([k]) => !k.startsWith('_'))); const firstRegionBlocks = ((body.regions as { components?: unknown[] }[])[0].components ?? []).length; const name = `e2e_save_at_once_${Date.now()}`; - const put = await request.put(`${API}/api/v1/meta/page/${name}`, { + const pkgId = await authorPackage(request, name); + const put = await request.put(`${API}/api/v1/meta/page/${name}?package=${pkgId}`, { data: { ...body, name, label: `E2E Save At Once ${name.slice(-6)}` }, }); expect(put.ok(), await put.text()).toBeTruthy(); @@ -99,6 +115,7 @@ test('Save makes the edit live at once, and an unsaved edit is guarded on × but expect(asked).toEqual([]); }); } finally { - await request.delete(`${API}/api/v1/meta/page/${name}`); + await request.delete(`${API}/api/v1/meta/page/${name}?package=${packageOf(name)}`); + await request.delete(`${API}/api/v1/packages/${packageOf(name)}`); } }); diff --git a/ui/e2e/live/studio-editor.spec.ts b/ui/e2e/live/studio-editor.spec.ts index 832afdeed62..0e7a9a210ea 100644 --- a/ui/e2e/live/studio-editor.spec.ts +++ b/ui/e2e/live/studio-editor.spec.ts @@ -27,6 +27,21 @@ import { test, expect, type APIRequestContext } from '@playwright/test'; const API = process.env.LIVE_API_URL || 'http://localhost:3000'; const SHIPPED_PAGE = 'showcase_project_workspace'; +/** + * A new page names a writable package (objectstack ADR-0070 D1): each test + * authors one of its own, named from the page, and deletes it at the end. + */ +const packageOf = (name: string) => `com.e2e.${name.replace(/_/g, '')}`; + +async function authorPackage(request: APIRequestContext, name: string): Promise { + const pkgId = packageOf(name); + const res = await request.post(`${API}/api/v1/packages`, { + data: { manifest: { id: pkgId, name: `E2E ${name}`, version: '0.1.0', type: 'app' } }, + }); + expect(res.ok(), await res.text()).toBeTruthy(); + return pkgId; +} + /** Author an editable copy of the shipped page; returns its name, how many regions it lays out and how many blocks its first region holds. */ async function authorEditablePage( request: APIRequestContext, @@ -41,7 +56,8 @@ async function authorEditablePage( const firstRegionBlocks = ((body.regions as { components?: unknown[] }[])[0].components ?? []).length; const name = `e2e_studio_editor_${Date.now()}`; - const put = await request.put(`${API}/api/v1/meta/page/${name}`, { + const pkgId = await authorPackage(request, name); + const put = await request.put(`${API}/api/v1/meta/page/${name}?package=${pkgId}`, { data: { ...body, name, label: `E2E Studio Editor ${name.slice(-6)}` }, }); expect(put.ok(), await put.text()).toBeTruthy(); @@ -49,7 +65,8 @@ async function authorEditablePage( } async function removePage(request: APIRequestContext, name: string) { - await request.delete(`${API}/api/v1/meta/page/${name}`); + await request.delete(`${API}/api/v1/meta/page/${name}?package=${packageOf(name)}`); + await request.delete(`${API}/api/v1/packages/${packageOf(name)}`); } test('the page editor loads with its config sections', async ({ page, request }) => { From a9a0cae02cf7b0bab23383456769e97371ccc60e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 16:55:18 +0000 Subject: [PATCH 15/23] test(verify): the metadata-door case saves into an authored package Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CasbvyQnz4st6s79P9 --- .../delete-behavior-referenceless-tree.test.ts | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/packages/verify/src/delete-behavior-referenceless-tree.test.ts b/packages/verify/src/delete-behavior-referenceless-tree.test.ts index 0c4770b5fd4..fbcb648c0ae 100644 --- a/packages/verify/src/delete-behavior-referenceless-tree.test.ts +++ b/packages/verify/src/delete-behavior-referenceless-tree.test.ts @@ -157,19 +157,24 @@ describe('[#23065] a referenceless tree field — delete behaviour at the public it('the metadata save door: an object saved with a referenceless tree clears the child too', async () => { // The save stores the authored body verbatim, so the registry receives the // field without the parse's output: the door the parse alone did not cover. - const saved = await stack.apiAs(token, 'PUT', '/meta/object/rtl_saved', { - name: 'rtl_saved', + // A new item names a writable package (ADR-0070 D1): an authored one, made here. + const pkg = await stack.apiAs(token, 'POST', '/packages', { + manifest: { id: 'com.example.rtl-authored', namespace: 'rtls', name: 'RTL Authored', version: '0.1.0', type: 'app' }, + }); + expect(pkg.ok, await pkg.clone().text()).toBe(true); + const saved = await stack.apiAs(token, 'PUT', '/meta/object/rtls_saved?package=com.example.rtl-authored', { + name: 'rtls_saved', label: 'Saved', sharingModel: 'public_read_write', fields: { title: { type: 'text', label: 'Title' }, parent: { type: 'tree', label: 'Parent' } }, }); expect(saved.status, await saved.clone().text()).toBe(200); - const p = await create('rtl_saved', { title: 'p' }); - const c = await create('rtl_saved', { title: 'c', parent: p }); + const p = await create('rtls_saved', { title: 'p' }); + const c = await create('rtls_saved', { title: 'c', parent: p }); - expect((await remove('rtl_saved', p)).status).toBe(200); - expect((await read('rtl_saved', c)).record?.parent).toBeNull(); + expect((await remove('rtls_saved', p)).status).toBe(200); + expect((await read('rtls_saved', c)).record?.parent).toBeNull(); }); it('os verify --delete-behaviors proves the referenceless fields through both doors', () => { From 7abd69a40d00db207949f5589efd623209e7f36c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 17:07:49 +0000 Subject: [PATCH 16/23] test: migrate plugin-security, service-automation and verify saves to name a package or seed the loose row Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CasbvyQnz4st6s79P9 --- .../src/catalog-reference-report.test.ts | 6 ++++ .../packaged-permission-set-lock-gate.test.ts | 12 +++++++ ...-env-kernel-registry-write-through.test.ts | 9 ++++- .../src/security-catalog-echo.test.ts | 18 ++++++++-- .../src/connector-definition-cluster.test.ts | 23 ++++++++----- .../src/connector-descriptor-audit.test.ts | 16 +++++---- ...w-metadata-save-arming.integration.test.ts | 34 +++++++++++++------ ...used-registration-read.integration.test.ts | 21 ++++++++---- .../flow-version-pinning.integration.test.ts | 8 +++++ 9 files changed, 113 insertions(+), 34 deletions(-) diff --git a/packages/plugins/plugin-security/src/catalog-reference-report.test.ts b/packages/plugins/plugin-security/src/catalog-reference-report.test.ts index 93eaa266144..769751df7c9 100644 --- a/packages/plugins/plugin-security/src/catalog-reference-report.test.ts +++ b/packages/plugins/plugin-security/src/catalog-reference-report.test.ts @@ -250,6 +250,12 @@ const findings = (report: CatalogReferenceReport) => describe('[ADR-0131 D4] the catalog reference report — references whose names resolve nowhere, per organization', () => { it('a deployment whose every reference resolves reports nothing: declared, packaged and environment-defined names', async () => { const b = await boot(); + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the environment's + // loose row is laid straight into the store, and its save runs in place. + await b.engine.insert('sys_metadata', { + type: 'position', name: 's3_env_lead', namespace: 'default', package_id: null, scope: 'platform', strategy: 'merge', + state: 'active', version: 1, metadata: JSON.stringify({ name: 's3_env_lead', label: 'Env lead' }), + }, { context: SYS } as any); await b.protocol.saveMetaItem({ type: 'position', name: 's3_env_lead', item: { name: 's3_env_lead', label: 'Env lead' } }); await insertRows(b, 'sys_user_position', [ { id: 'up_declared', user_id: 'usr_a', position: FIELD_LEAD.name, organization_id: ORG }, diff --git a/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.test.ts b/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.test.ts index cb7d1b68251..2789ee9cb7d 100644 --- a/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.test.ts +++ b/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.test.ts @@ -185,6 +185,12 @@ function boot(opts?: { listItemsThrows?: boolean }) { return { engine, protocol, wired }; } +/** A package-less permission-set row as it exists at rest, written straight into the store. */ +const layLooseSet = (engine: { insert(table: string, data: Record): Promise }, name: string) => + engine.insert('sys_metadata', { + type: 'permission', name, package_id: null, state: 'active', version: 1, metadata: JSON.stringify(body(name)), + }); + const metaRowsOf = (engine: { rows: Map }) => Array.from(engine.rows.values()).filter((r) => r.__table === 'sys_metadata'); @@ -262,6 +268,10 @@ describe('#11843 — the lock answers at the metadata door', () => { it('hatch OPEN: a package-less save to a NON-packaged name still lands, bound to no package', async () => { const { engine, protocol } = boot(); openHatch(); + // [#38174] A package-less CREATE is refused (ADR-0070 D1); the loose row + // is laid straight into the store, so this save is the in-place one the + // lock must not refuse. + await layLooseSet(engine, ORG_SET); const err = await save(protocol, { type: 'permission', name: ORG_SET, item: body(ORG_SET) }); @@ -278,6 +288,8 @@ describe('#11843 — the lock answers at the metadata door', () => { const { engine, protocol } = boot(); openHatch(); + // The shadow definition lives only in sys_metadata, laid there directly. + await layLooseSet(engine, SHADOW_SET); const err = await save(protocol, { type: 'permission', name: SHADOW_SET, item: body(SHADOW_SET) }); expect(err).toBeNull(); diff --git a/packages/plugins/plugin-security/src/permission-set-env-kernel-registry-write-through.test.ts b/packages/plugins/plugin-security/src/permission-set-env-kernel-registry-write-through.test.ts index 1542da99a9a..f44ff3e1c0d 100644 --- a/packages/plugins/plugin-security/src/permission-set-env-kernel-registry-write-through.test.ts +++ b/packages/plugins/plugin-security/src/permission-set-env-kernel-registry-write-through.test.ts @@ -280,8 +280,15 @@ describe('#23233 — controls: the owner is the binding, never invented', () => it('a set saved into no package stays unowned and records no suggestion', async () => { const { stores, engine, protocol, catalog } = await boot('host'); + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the loose row is + // laid straight into the store, and the door's package-less save runs in place. + const looseBody = { ...newDefaultSet(), name: 'org_member_default' }; + await engine.insert('sys_metadata', { + type: 'permission', name: 'org_member_default', namespace: 'default', package_id: null, scope: 'platform', + strategy: 'merge', state: 'active', version: 1, metadata: JSON.stringify(looseBody), + }, { context: { isSystem: true } } as never); expect(await protocol.saveMetaItem({ - type: 'permission', name: 'org_member_default', item: { ...newDefaultSet(), name: 'org_member_default' }, + type: 'permission', name: 'org_member_default', item: looseBody, })).toMatchObject({ success: true }); const resolved = await catalog.resolve('permission', 'org_member_default'); diff --git a/packages/plugins/plugin-security/src/security-catalog-echo.test.ts b/packages/plugins/plugin-security/src/security-catalog-echo.test.ts index e8bcc92b62c..fd5c92faa54 100644 --- a/packages/plugins/plugin-security/src/security-catalog-echo.test.ts +++ b/packages/plugins/plugin-security/src/security-catalog-echo.test.ts @@ -204,6 +204,17 @@ async function publishThroughPackageDoor(protocol: any, packageId: string, body: expect(published, JSON.stringify(published)).toMatchObject({ outcome: 'published', failed: [] }); } +/** + * [#38174] A package-less CREATE is refused (ADR-0070 D1): an environment's + * loose row is laid straight into the store, and the door's package-less save + * of it then runs in place. + */ +const layLoose = (engine: { insert(table: string, data: Record, opts?: unknown): Promise }, type: string, name: string, body: unknown) => + engine.insert('sys_metadata', { + type, name, namespace: 'default', package_id: null, scope: 'platform', strategy: 'merge', + state: 'active', version: 1, metadata: JSON.stringify(body), + }, { context: { isSystem: true } }); + const suggestionRows = (engine: ReturnType, set: string) => (engine.tables.sys_audience_binding_suggestion ?? []).filter((row) => row.permission_set_name === set); @@ -290,6 +301,7 @@ describe('#23233 — controls: the owner is carried, never invented', () => { it('a set saved with no package stays unowned — no binding, no owner, no suggestion (ADR-0086 D3)', async () => { const { engine, protocol, catalog } = boot(); + await layLoose(engine, 'permission', 'org_member_default', { ...runtimeDefault(), name: 'org_member_default' }); await protocol.saveMetaItem({ type: 'permission', name: 'org_member_default', item: { ...runtimeDefault(), name: 'org_member_default' } }); expect((await protocol.getMetaItem({ type: 'permission', name: 'org_member_default' })).item._packageId).toBeUndefined(); @@ -550,7 +562,8 @@ describe('positions are echoed too', () => { }); it('a position saved through the real environment protocol resolves in the catalog', async () => { - const { protocol, catalog } = boot(); + const { engine, protocol, catalog } = boot(); + await layLoose(engine, 'position', 'field_lead', position({ permissionSets: [CODE_SET] })); await protocol.saveMetaItem({ type: 'position', name: 'field_lead', item: position({ permissionSets: [CODE_SET] }) }); expect(await catalog.resolve('position', 'field_lead')).toMatchObject({ source: 'metadata', definition: { permissionSets: [CODE_SET] } }); }); @@ -839,7 +852,8 @@ describe('[#31698] one package\'s save never moves, drops or deletes another pac }); it('the doors name the package a set\'s row lands in: publish into a package, delete there, save naming none', async () => { - const { protocol } = boot(); + const { engine, protocol } = boot(); + await layLoose(engine, 'permission', 'org_member_default', { ...runtimeDefault(), name: 'org_member_default' }); const events: Array<{ state?: string; packageId?: unknown }> = []; protocol.registerMutationProjector('permission', async (evt: any) => { events.push({ state: evt.state, packageId: evt.packageId }); }); diff --git a/packages/services/service-automation/src/connector-definition-cluster.test.ts b/packages/services/service-automation/src/connector-definition-cluster.test.ts index cd1ca4096f4..f68434f404c 100644 --- a/packages/services/service-automation/src/connector-definition-cluster.test.ts +++ b/packages/services/service-automation/src/connector-definition-cluster.test.ts @@ -85,11 +85,14 @@ const plainFlow = (name: string) => ({ edges: [{ id: 'e1', source: 'start', target: 'end' }], }); +/** The writable package every save names (ADR-0070 D1), installed on each replica. */ +const PKG = 'com.qa.connector-cluster'; + /** The protocol surface this suite drives: the doors `PUT /meta/:type/:name`, `POST …/publish` and `DELETE` call. */ interface Protocol { - saveMetaItem(request: { type: string; name: string; item: unknown; mode?: 'draft' | 'publish' }): Promise; - publishMetaItem(request: { type: string; name: string }): Promise; - deleteMetaItem(request: { type: string; name: string }): Promise; + saveMetaItem(request: { type: string; name: string; item: unknown; mode?: 'draft' | 'publish'; packageId?: string }): Promise; + publishMetaItem(request: { type: string; name: string; packageId?: string }): Promise; + deleteMetaItem(request: { type: string; name: string; packageId?: string }): Promise; onMetadataMutation(listener: (evt: { type: string; name: string; state?: string }) => void): () => void; attachMetadataMutationPubSub(pubsub: IPubSub, nodeId: string): () => void; } @@ -187,6 +190,8 @@ async function replica(file: string, nodeId: string, bus: IPubSub, opts: { lane2 ql.registerDriver(driver as never, true); await ql.syncSchemas(); await installDefaultOrganization(ql); + (ql as unknown as { registry: { installPackage(m: unknown, kind: string): unknown } }) + .registry.installPackage({ id: PKG, name: PKG, version: '1.0.0' }, 'authored'); const protocol = kernel.getService('protocol'); const automation = kernel.getService('automation'); @@ -199,14 +204,14 @@ async function replica(file: string, nodeId: string, bus: IPubSub, opts: { lane2 /** The per-item publish door: a draft save, then `POST /api/v1/meta/connector/:name/publish`. */ const publish = async (item: unknown) => { - await protocol.saveMetaItem({ type: 'connector', name: NAME, item, mode: 'draft' }); - await protocol.publishMetaItem({ type: 'connector', name: NAME }); + await protocol.saveMetaItem({ type: 'connector', name: NAME, item, mode: 'draft', packageId: PKG }); + await protocol.publishMetaItem({ type: 'connector', name: NAME, packageId: PKG }); }; /** The direct door: `PUT /api/v1/meta/connector/:name`, saved active. */ - const save = (item: unknown) => protocol.saveMetaItem({ type: 'connector', name: NAME, item }); - const saveDraft = (item: unknown) => protocol.saveMetaItem({ type: 'connector', name: NAME, item, mode: 'draft' }); - const remove = () => protocol.deleteMetaItem({ type: 'connector', name: NAME }); - const saveFlow = (name: string) => protocol.saveMetaItem({ type: 'flow', name, item: plainFlow(name) }); + const save = (item: unknown) => protocol.saveMetaItem({ type: 'connector', name: NAME, item, packageId: PKG }); + const saveDraft = (item: unknown) => protocol.saveMetaItem({ type: 'connector', name: NAME, item, mode: 'draft', packageId: PKG }); + const remove = () => protocol.deleteMetaItem({ type: 'connector', name: NAME, packageId: PKG }); + const saveFlow = (name: string) => protocol.saveMetaItem({ type: 'flow', name, item: plainFlow(name), packageId: PKG }); const reload = () => hooks!.trigger('metadata:reloaded', { changed: [`connector/${NAME}`] }); const live = () => automation.getRegisteredConnectors().includes(NAME); /** Connector reconciles this replica ran — the run `metadata:reloaded` queues. */ diff --git a/packages/services/service-automation/src/connector-descriptor-audit.test.ts b/packages/services/service-automation/src/connector-descriptor-audit.test.ts index f48bea10528..86a76ca0f50 100644 --- a/packages/services/service-automation/src/connector-descriptor-audit.test.ts +++ b/packages/services/service-automation/src/connector-descriptor-audit.test.ts @@ -205,9 +205,11 @@ describe('[#33839] the audit on the metadata save door', () => { }); interface Protocol { - saveMetaItem(request: { type: string; name: string; item: unknown; mode?: 'draft' | 'publish' }): Promise; - publishMetaItem(request: { type: string; name: string }): Promise; + saveMetaItem(request: { type: string; name: string; item: unknown; mode?: 'draft' | 'publish'; packageId?: string }): Promise; + publishMetaItem(request: { type: string; name: string; packageId?: string }): Promise; } + /** The writable package each connector is saved into (ADR-0070 D1). */ + const PKG = 'com.qa.connector-descriptor-audit'; async function bootOverStore() { const dir = mkdtempSync(join(tmpdir(), 'os-33839-')); @@ -235,14 +237,16 @@ describe('[#33839] the audit on the metadata save door', () => { ql.registerDriver(driver as never, true); await ql.syncSchemas(); await installDefaultOrganization(ql); + (ql.registry as unknown as { installPackage(m: unknown, kind: string): unknown }) + .installPackage({ id: PKG, name: PKG, version: '1.0.0' }, 'authored'); const protocol = kernel.getService('protocol'); return { warnings: () => auditWarnings(warnSpy), - save: (name: string, item: unknown) => protocol.saveMetaItem({ type: 'connector', name, item }), - saveDraft: (name: string, item: unknown) => protocol.saveMetaItem({ type: 'connector', name, item, mode: 'draft' }), + save: (name: string, item: unknown) => protocol.saveMetaItem({ type: 'connector', name, item, packageId: PKG }), + saveDraft: (name: string, item: unknown) => protocol.saveMetaItem({ type: 'connector', name, item, mode: 'draft', packageId: PKG }), publish: async (name: string, item: unknown) => { - await protocol.saveMetaItem({ type: 'connector', name, item, mode: 'draft' }); - await protocol.publishMetaItem({ type: 'connector', name }); + await protocol.saveMetaItem({ type: 'connector', name, item, mode: 'draft', packageId: PKG }); + await protocol.publishMetaItem({ type: 'connector', name, packageId: PKG }); }, }; } diff --git a/packages/services/service-automation/src/flow-metadata-save-arming.integration.test.ts b/packages/services/service-automation/src/flow-metadata-save-arming.integration.test.ts index 945ab28bd1c..ebd85cce134 100644 --- a/packages/services/service-automation/src/flow-metadata-save-arming.integration.test.ts +++ b/packages/services/service-automation/src/flow-metadata-save-arming.integration.test.ts @@ -40,9 +40,9 @@ import { installDefaultOrganization } from './default-organization.testkit.js'; /** The saved surface these tests drive: `ObjectStackProtocolImplementation`'s write doors. */ interface MetadataWriteDoors { - saveMetaItem(request: { type: string; name: string; item: unknown; mode?: 'draft' | 'publish' }): Promise; - publishMetaItem(request: { type: string; name: string }): Promise; - deleteMetaItem(request: { type: string; name: string }): Promise; + saveMetaItem(request: { type: string; name: string; item: unknown; mode?: 'draft' | 'publish'; packageId?: string }): Promise; + publishMetaItem(request: { type: string; name: string; packageId?: string }): Promise; + deleteMetaItem(request: { type: string; name: string; packageId?: string }): Promise; } const TICKET = 'qa_ticket'; @@ -103,6 +103,9 @@ function objectqlRecordTrigger(ql: ObjectQL) { return { trigger, fired }; } +/** The writable package each new flow is saved into (ADR-0070 D1). */ +const PKG = 'com.qa.flow-save-arming'; + describe('a flow saved through the metadata API is armed on the running engine (#21725)', () => { let kernel: ObjectKernel; let ql: ObjectQL; @@ -137,13 +140,17 @@ describe('a flow saved through the metadata API is armed on the running engine ( // A real `single` install's Default Organization: the system writes below // derive it (ADR-0131 D9), as a fresh NOT NULL tenant column requires (D1). await installDefaultOrganization(ql); + // A new flow names a writable package (ADR-0070 D1); it depends on the + // package `ticket` ships in, so a flow on `ticket` is inside its closure. + (ql.registry as unknown as { installPackage(m: unknown, kind: string): unknown }) + .installPackage({ id: PKG, name: PKG, version: '1.0.0', dependencies: { 'qa-21725': '*' } }, 'authored'); const rec = objectqlRecordTrigger(ql); automation.registerTrigger(rec.trigger); fired = rec.fired; } - const saveActive = (name: string, item: unknown) => protocol.saveMetaItem({ type: 'flow', name, item }); + const saveActive = (name: string, item: unknown) => protocol.saveMetaItem({ type: 'flow', name, item, packageId: PKG }); const insertTicket = (title: string) => ql.insert(TICKET, { title }, { context: SYS } as never); const runtimeState = (name: string) => automation.getFlowRuntimeStates().find((s) => s.name === name); @@ -154,7 +161,7 @@ describe('a flow saved through the metadata API is armed on the running engine ( await boot(); const saved = await saveActive('qa_meta_flow', plainFlow('qa_meta_flow')); // The card's step 2, as the door answers it. - expect((saved as { message?: string }).message).toContain("Saved flow 'qa_meta_flow' (env-wide, state=active)"); + expect((saved as { message?: string }).message).toContain("Saved flow 'qa_meta_flow' (env-wide, package="); await vi.waitFor(async () => { expect(await automation.getFlow('qa_meta_flow'), 'GET /automation/:name reads this').not.toBeNull(); @@ -196,7 +203,7 @@ describe('a flow saved through the metadata API is armed on the running engine ( await saveActive('ticket_created', ticketCreatedFlow('ticket_created')); await vi.waitFor(() => expect(runtimeState('ticket_created')?.bound).toBe(true)); - await protocol.deleteMetaItem({ type: 'flow', name: 'ticket_created' }); + await protocol.deleteMetaItem({ type: 'flow', name: 'ticket_created', packageId: PKG }); await vi.waitFor(async () => { expect(await automation.getFlow('ticket_created'), 'GET /automation/:name answers 404 again').toBeNull(); }); @@ -207,7 +214,7 @@ describe('a flow saved through the metadata API is armed on the running engine ( it('a draft save arms nothing: the live row is unchanged', async () => { await boot(); const register = vi.spyOn(automation, 'registerFlow'); - await protocol.saveMetaItem({ type: 'flow', name: 'drafted', item: plainFlow('drafted'), mode: 'draft' }); + await protocol.saveMetaItem({ type: 'flow', name: 'drafted', item: plainFlow('drafted'), mode: 'draft', packageId: PKG }); await settleFlowSync(); expect(register.mock.calls.filter(([name]) => name === 'drafted')).toEqual([]); @@ -217,10 +224,10 @@ describe('a flow saved through the metadata API is armed on the running engine ( it('the per-item publish door (#10219) still arms the published flow exactly once', async () => { await boot(); const register = vi.spyOn(automation, 'registerFlow'); - await protocol.saveMetaItem({ type: 'flow', name: 'ticket_created', item: ticketCreatedFlow('ticket_created'), mode: 'draft' }); + await protocol.saveMetaItem({ type: 'flow', name: 'ticket_created', item: ticketCreatedFlow('ticket_created'), mode: 'draft', packageId: PKG }); // The door awaits its `metadata:reloaded` announce, which runs behind the // mutation sync the same publish raised — both are done when it answers. - await protocol.publishMetaItem({ type: 'flow', name: 'ticket_created' }); + await protocol.publishMetaItem({ type: 'flow', name: 'ticket_created', packageId: PKG }); expect(register.mock.calls.filter(([name]) => name === 'ticket_created')).toHaveLength(1); await insertTicket('after publish'); @@ -232,8 +239,15 @@ describe('a flow saved through the metadata API is armed on the running engine ( const register = vi.spyOn(automation, 'registerFlow'); // `registerAndSaveFlow`'s order (runtime `domains/automation.ts`): the // engine first, then the metadata door's own save. + // [#38174] That door now only updates a flow that exists (its create, + // `POST /automation`, is retired), and its save names no package: the + // existing loose row is laid straight into the store first. + await ql.insert('sys_metadata', { + type: 'flow', name: 'door_flow', namespace: 'default', package_id: null, scope: 'platform', strategy: 'merge', + state: 'active', version: 1, metadata: JSON.stringify(plainFlow('door_flow')), + }, { context: SYS } as never); automation.registerFlow('door_flow', plainFlow('door_flow')); - await saveActive('door_flow', plainFlow('door_flow')); + await protocol.saveMetaItem({ type: 'flow', name: 'door_flow', item: plainFlow('door_flow') }); await settleFlowSync(); expect(register.mock.calls.filter(([name]) => name === 'door_flow')).toHaveLength(1); diff --git a/packages/services/service-automation/src/flow-refused-registration-read.integration.test.ts b/packages/services/service-automation/src/flow-refused-registration-read.integration.test.ts index e4fcd867826..c599539529a 100644 --- a/packages/services/service-automation/src/flow-refused-registration-read.integration.test.ts +++ b/packages/services/service-automation/src/flow-refused-registration-read.integration.test.ts @@ -37,7 +37,7 @@ interface MetadataReadDoors { /** The default door's producer: REST's cached branch serves `data` and `registration` from it. */ getMetaItemCached(request: { type: string; name: string }): Promise; getMetaItems(request: { type: string }): Promise; - saveMetaItem(request: { type: string; name: string; item: unknown; mode?: 'draft' }): Promise; + saveMetaItem(request: { type: string; name: string; item: unknown; mode?: 'draft'; packageId?: string }): Promise; } const SYS = { isSystem: true } as const; @@ -109,6 +109,13 @@ function storedFlowsPlugin(driver: SqlDriver, flows: ReadonlyArray('objectql').registry as unknown as { installPackage(m: unknown, kind: string): unknown }) + .installPackage({ id: PKG, name: PKG, version: '1.0.0' }, 'authored'); +} + describe('a stored flow the engine refuses at boot is not served as running (#23316)', () => { let kernel: ObjectKernel; @@ -233,6 +240,7 @@ describe('a stored flow with no start node: refused at the bind, never at the bo const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); await kernel.use(storedFlowsPlugin(driver, [startless('no_start', 'active'), stampFlow('valid', { count: 2 })])); await kernel.bootstrap(); + installAuthoredPackage(kernel); return { protocol: kernel.getService('protocol'), automation: kernel.getService('automation'), @@ -259,13 +267,13 @@ describe('a stored flow with no start node: refused at the bind, never at the bo it('the metadata save door refuses a live start-less save, and keeps a start-less draft with the finding', async () => { const { protocol, automation } = await boot(); const refusal = await protocol - .saveMetaItem({ type: 'flow', name: 'draft_no_start', item: startless('draft_no_start', 'draft') }) + .saveMetaItem({ type: 'flow', name: 'draft_no_start', item: startless('draft_no_start', 'draft'), packageId: PKG }) .then(() => null, (e: unknown) => e as { code?: string; status?: number; issues?: Array<{ rule?: string }> }); expect({ code: refusal?.code, status: refusal?.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); expect((refusal?.issues ?? []).map((i) => i.rule)).toContain('flow-start-node-missing'); expect(await automation.getFlow('draft_no_start')).toBeNull(); - await protocol.saveMetaItem({ type: 'flow', name: 'draft_no_start', item: startless('draft_no_start', 'draft'), mode: 'draft' }); + await protocol.saveMetaItem({ type: 'flow', name: 'draft_no_start', item: startless('draft_no_start', 'draft'), mode: 'draft', packageId: PKG }); const read = await protocol.getMetaItem({ type: 'flow', name: 'draft_no_start', state: 'draft' }); const diagnostics = (read.item as { _diagnostics?: { valid: boolean; errors?: Array<{ code?: string }> } })._diagnostics; expect(diagnostics?.valid).toBe(false); @@ -328,6 +336,7 @@ describe('an after-save flow with a retried inline callout: refused at the bind stampFlow('valid', { count: 2 }), ])); await kernel.bootstrap(); + installAuthoredPackage(kernel); return { protocol: kernel.getService('protocol'), automation: kernel.getService('automation'), @@ -352,13 +361,13 @@ describe('an after-save flow with a retried inline callout: refused at the bind it('the metadata save door refuses a live save with 422 and the rule, and keeps a draft with the finding', async () => { const { protocol, automation } = await boot(); const refusal = await protocol - .saveMetaItem({ type: 'flow', name: 'new_sync', item: afterSaveSync('new_sync', 'active') }) + .saveMetaItem({ type: 'flow', name: 'new_sync', item: afterSaveSync('new_sync', 'active'), packageId: PKG }) .then(() => null, (e: unknown) => e as { code?: string; status?: number; issues?: Array<{ rule?: string }> }); expect({ code: refusal?.code, status: refusal?.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); expect((refusal?.issues ?? []).map((i) => i.rule)).toContain('flow-after-save-inline-retry'); expect(await automation.getFlow('new_sync')).toBeNull(); - await protocol.saveMetaItem({ type: 'flow', name: 'new_sync', item: afterSaveSync('new_sync', 'active'), mode: 'draft' }); + await protocol.saveMetaItem({ type: 'flow', name: 'new_sync', item: afterSaveSync('new_sync', 'active'), mode: 'draft', packageId: PKG }); const read = await protocol.getMetaItem({ type: 'flow', name: 'new_sync', state: 'draft' }); const diagnostics = (read.item as { _diagnostics?: { valid: boolean; errors?: Array<{ code?: string }> } })._diagnostics; expect(diagnostics?.valid).toBe(false); @@ -367,7 +376,7 @@ describe('an after-save flow with a retried inline callout: refused at the bind it('control: the same flow with `durable: true` saves and is armed', async () => { const { protocol, automation } = await boot(); - await protocol.saveMetaItem({ type: 'flow', name: 'durable_sync', item: afterSaveSync('durable_sync', 'active', { durable: true }) }); + await protocol.saveMetaItem({ type: 'flow', name: 'durable_sync', item: afterSaveSync('durable_sync', 'active', { durable: true }), packageId: PKG }); await vi.waitFor(async () => { expect(await automation.getFlow('durable_sync'), 'the mutation sync registered the durable row').not.toBeNull(); }); diff --git a/packages/services/service-automation/src/flow-version-pinning.integration.test.ts b/packages/services/service-automation/src/flow-version-pinning.integration.test.ts index fdc34f9daef..6138142171f 100644 --- a/packages/services/service-automation/src/flow-version-pinning.integration.test.ts +++ b/packages/services/service-automation/src/flow-version-pinning.integration.test.ts @@ -114,6 +114,14 @@ describe('a waiting run keeps its flow version across a restart (durable store, /** Save `item` active and wait until the engine armed it (the mutation signal is fire-and-forget). */ async function saveArmed(life: Awaited>, item: ReturnType) { + // [#38174] A package-less CREATE is refused (ADR-0070 D1): the flow's loose + // row is laid straight into the store once, and every save runs in place. + if (!(await life.ql.findOne('sys_metadata', { where: { type: 'flow', name: FLOW }, context: SYSTEM }))) { + await life.ql.insert('sys_metadata', { + type: 'flow', name: FLOW, namespace: 'default', package_id: null, scope: 'platform', strategy: 'merge', + state: 'active', version: 0, metadata: JSON.stringify({ ...item, version: 0 }), + }, { context: SYSTEM } as never); + } await life.protocol.saveMetaItem({ type: 'flow', name: FLOW, item }); await vi.waitFor(async () => { expect((await life.automation.getFlow(FLOW))?.version).toBe(item.version); From f7514c540711481b21c02bbf44fdf1389c10a60b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 17:35:27 +0000 Subject: [PATCH 17/23] test(verify): pay the automation service's first load at collection Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CasbvyQnz4st6s79P9 --- packages/verify/src/delete-behavior-referenceless-tree.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/verify/src/delete-behavior-referenceless-tree.test.ts b/packages/verify/src/delete-behavior-referenceless-tree.test.ts index fbcb648c0ae..d94027ca564 100644 --- a/packages/verify/src/delete-behavior-referenceless-tree.test.ts +++ b/packages/verify/src/delete-behavior-referenceless-tree.test.ts @@ -44,6 +44,8 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { defineStack } from '@objectstack/spec'; import { bootStack, type VerifyStack } from './harness.js'; +// Pays this dist-resolved dep's first load at collection, never inside a clocked case. +import '@objectstack/service-automation'; import { runDeleteBehaviorProofs, type DeleteBehaviorReport } from './delete-behavior.js'; // Booting the full in-process stack runs well past vitest's 5s default. From c913c4a14c27570774e82ae2efbd18e959187be1 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 19:19:54 +0000 Subject: [PATCH 18/23] feat(app-shell): clone dialog offers the writable packages when the copy has nowhere to land (#38174) F1 per Bill's ruling A (claim amendment 7389333883): the Console's "New similar" on a permission set no longer dead-ends on the kernel's package-less create refusal. A 422 WRITABLE_PACKAGE_REQUIRED from the clone door rejects as PermissionSetLandingRequired; the dialog shows the server's sentence with one button per writable package and re-sends the same source with the chosen package as the body's `package`. No new exemption. permission-sets.mdx now says a copy with nowhere to land is refused and names the Console pick, so Skills-docs reads "updated here". Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CasbvyQnz4st6s79P9 --- .../38174-packageless-create-refused.md | 2 +- content/docs/permissions/permission-sets.mdx | 20 +-- ui/.changeset/38174-clone-landing-pick.md | 10 ++ ...ssionSetCloneDialog.landing-38174.test.tsx | 138 ++++++++++++++++++ .../PermissionSetCloneDialog.tsx | 59 +++++++- .../metadata-admin/permission-set-clone.ts | 65 +++++++-- 6 files changed, 270 insertions(+), 24 deletions(-) create mode 100644 ui/.changeset/38174-clone-landing-pick.md create mode 100644 ui/packages/app-shell/src/views/metadata-admin/PermissionSetCloneDialog.landing-38174.test.tsx diff --git a/.changeset/38174-packageless-create-refused.md b/.changeset/38174-packageless-create-refused.md index e3a20eeffac..94d16ef4ef0 100644 --- a/.changeset/38174-packageless-create-refused.md +++ b/.changeset/38174-packageless-create-refused.md @@ -12,7 +12,7 @@ feat(metadata-protocol)!: the kernel refuses a package-less create; `POST /api/v Clause-②: no (narrowing) Metadata-protocol: narrowed -Skills-docs: follow-up owed — content/docs/permissions/permission-sets.mdx (the console's permission-set clone with no package; skills/** teach no package-less create, `POST /api/v1/automation` or `client.automation.create`) +Skills-docs: updated here — content/docs/permissions/permission-sets.mdx (a clone with no package to land in is refused, and the Console's "New similar" offers the writable packages; skills/** teach no package-less create, `POST /api/v1/automation` or `client.automation.create`) diff --git a/content/docs/permissions/permission-sets.mdx b/content/docs/permissions/permission-sets.mdx index 6ae22686c0c..bbf313b2df4 100644 --- a/content/docs/permissions/permission-sets.mdx +++ b/content/docs/permissions/permission-sets.mdx @@ -495,18 +495,20 @@ the source never reach the copy. package `.custom`, the package that holds everything you changed about X. The pair is created on the first copy, by the same ensure door as `POST /api/v1/packages/:id/ensure-customization` (its only creation path), - and reused after. A copy of a set the platform itself ships (a kernel - package of scope `system` or `cloud`, such as `member_default`) is saved - environment-wide, in no package: a kernel package has no paired - customization package in this version, and the notice says so - (`noticeCode` `PERMISSION_SET_CLONE_ENVIRONMENT_WIDE_KERNEL_SOURCE`). A copy of a set already in a writable package is - saved in that package, and a copy of a set authored in this system stays - environment-wide, in no package. With `package`, the copy is saved there: it + and reused after. A copy of a set already in a writable package is saved in + that package. A copy is a new set, and a new set is saved into a writable + package (ADR-0070), so a copy with nowhere to land is refused `422` + `WRITABLE_PACKAGE_REQUIRED`, nothing saved: a set the platform itself ships + (a kernel package of scope `system` or `cloud`, such as `member_default`, + which has no paired customization package in this version) or a set + authored in this system in no package. The refusal names the writable + packages here; name one with `package`. In the Console, "New similar" shows + that refusal with one button per package you can write, and the copy is + sent again into the one you choose. With `package`, the copy is saved there: it must be an installed, writable package (else `422` `WRITABLE_PACKAGE_REQUIRED`) whose declared dependencies reach the source's package and every object the set grants on (else `409` `RESOURCE_CONFLICT`). - The response's `package` names where the copy went (`null` for - environment-wide), and the copy is assigned by its bare name like any set. + The response's `package` names where the copy went, and the copy is assigned by its bare name like any set. - **The body is `{ name, label, package? }`, `name` and `label` required, and nothing else.** `name` is a new snake_case machine name: a name failing that rule answers `400`, and a name any permission set already uses (the source's own included) answers `409` diff --git a/ui/.changeset/38174-clone-landing-pick.md b/ui/.changeset/38174-clone-landing-pick.md new file mode 100644 index 00000000000..263eea7432e --- /dev/null +++ b/ui/.changeset/38174-clone-landing-pick.md @@ -0,0 +1,10 @@ +--- +'@object-ui/app-shell': patch +--- + +feat(app-shell): "New similar" on a permission set offers the writable packages when the copy has nowhere to land (objectstack#38174) + +The clone door now refuses a copy with no package to land in (`422 WRITABLE_PACKAGE_REQUIRED`, ADR-0070 D1): a set authored in no package, or a set a kernel package ships. The clone dialog shows that refusal in the server's words with one button per package the administrator can write (the package list's own `writable` verdict); choosing one sends the clone again with that package as the body's `package`. Nothing is chosen for the administrator, and with no writable package the server's sentence, which says to create one, stands alone. + +Clause-②: no +Metadata-protocol: none diff --git a/ui/packages/app-shell/src/views/metadata-admin/PermissionSetCloneDialog.landing-38174.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PermissionSetCloneDialog.landing-38174.test.tsx new file mode 100644 index 00000000000..6856e876481 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/PermissionSetCloneDialog.landing-38174.test.tsx @@ -0,0 +1,138 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38174 (ADR-0070 D1) — a copy with no package to land in. The + * clone door refuses it `422 WRITABLE_PACKAGE_REQUIRED`, nothing saved; the + * dialog shows that refusal as a pick of the packages the administrator can + * write. Pinned through the dialog: + * + * - CONTROL: an accepted clone sends no `package` in the body; + * - the refusal is the server's sentence with one button per writable + * package, and nothing is sent until one is chosen; + * - the choice sends the clone again, same source, with the chosen package + * as the body's `package`; + * - with no writable package the server's sentence stands alone; + * - a `422` of any other code is the server's sentence, with no pick. + */ +import * as React from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import type { WritablePackageIds } from './studioListSource'; + +const writable = vi.hoisted(() => ({ ids: [] as string[] })); + +vi.mock('./studioListSource', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + useWritablePackageIds: (enabled: boolean): WritablePackageIds => + enabled ? { status: 'read', ids: new Set(writable.ids) } : { status: 'off' }, + }; +}); + +import { PermissionSetCloneDialog } from './PermissionSetCloneDialog'; + +interface Call { + url: string; + body?: string; +} + +const REFUSAL = + "Cannot clone permission set 'sales_rep' as 'my_rep' with no package: the copy is a new item, and a new item is saved into a writable package (ADR-0070), but 'sales_rep' has no package the copy could land in. Name one with `package` in the request body. Nothing was saved. Writable packages here: com.acme.crm, com.acme.sales."; +const LANDING_REFUSED = { success: false, error: { code: 'WRITABLE_PACKAGE_REQUIRED', message: REFUSAL } }; +const CLONED = { success: true, data: { permissionSet: { name: 'my_rep' }, package: 'com.acme.sales', notice: 'Saved.' } }; + +function stubFetch(...answers: Array<{ status: number; body: unknown }>): Call[] { + const calls: Call[] = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string, init?: RequestInit) => { + calls.push({ url: String(url), body: init?.body as string | undefined }); + const answer = answers[Math.min(calls.length - 1, answers.length - 1)]; + return new Response(JSON.stringify(answer.body), { + status: answer.status, + headers: { 'Content-Type': 'application/json' }, + }); + }), + ); + return calls; +} + +beforeEach(() => { + writable.ids = ['com.acme.sales', 'com.acme.crm']; +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +function renderDialog(sourcePackage?: string) { + const onCloned = vi.fn(); + render( + {}} + onCloned={onCloned} + />, + ); + fireEvent.change(screen.getByLabelText('New machine name'), { target: { value: 'my_rep' } }); + fireEvent.change(screen.getByLabelText('New label'), { target: { value: 'My rep' } }); + return { onCloned, submit: () => fireEvent.click(screen.getByRole('button', { name: /Create copy/i })) }; +} + +const DOOR = '/api/v1/security/permission-sets/sales_rep/clone'; +const BODY = '{"name":"my_rep","label":"My rep"}'; + +describe('PermissionSetCloneDialog — a copy with no package to land in (objectstack#38174)', () => { + it('CONTROL: an accepted clone sends no package in the body', async () => { + const calls = stubFetch({ status: 200, body: CLONED }); + const { onCloned, submit } = renderDialog(); + submit(); + await waitFor(() => expect(onCloned).toHaveBeenCalledTimes(1)); + expect(calls).toEqual([{ url: DOOR, body: BODY }]); + expect(screen.queryByTestId('perm-clone-landing-pick')).toBeNull(); + }); + + it('shows the refusal with one button per writable package, sends nothing until one is chosen, then sends it with that package', async () => { + const calls = stubFetch({ status: 422, body: LANDING_REFUSED }, { status: 200, body: CLONED }); + const { onCloned, submit } = renderDialog('com.acme.base'); + submit(); + const pick = await screen.findByTestId('perm-clone-landing-pick'); + expect(pick.textContent).toContain(REFUSAL); + expect(screen.getByTestId('perm-clone-landing-com.acme.crm').textContent).toBe('Package com.acme.crm'); + expect(screen.getByTestId('perm-clone-landing-com.acme.sales').textContent).toBe('Package com.acme.sales'); + // ⛔ Nothing is chosen for the administrator: one request, no retry. + await new Promise((r) => setTimeout(r, 20)); + expect(calls).toHaveLength(1); + expect(onCloned).not.toHaveBeenCalled(); + + fireEvent.click(screen.getByTestId('perm-clone-landing-com.acme.sales')); + await waitFor(() => expect(onCloned).toHaveBeenCalledTimes(1)); + expect(onCloned.mock.calls[0][0]).toMatchObject({ name: 'my_rep', package: 'com.acme.sales' }); + expect(calls).toEqual([ + { url: `${DOOR}?package=com.acme.base`, body: BODY }, + { url: `${DOOR}?package=com.acme.base`, body: '{"name":"my_rep","label":"My rep","package":"com.acme.sales"}' }, + ]); + }); + + it("with no writable package the server's sentence stands alone", async () => { + writable.ids = []; + stubFetch({ status: 422, body: LANDING_REFUSED }); + const { submit } = renderDialog(); + submit(); + const pick = await screen.findByTestId('perm-clone-landing-pick'); + expect(pick.textContent).toBe(REFUSAL); + expect(pick.querySelectorAll('button')).toHaveLength(0); + }); + + it('a 422 of any other code is the server sentence alone, with no pick', async () => { + const said = 'The copy failed validation.'; + stubFetch({ status: 422, body: { success: false, error: { code: 'VALIDATION_ERROR', message: said } } }); + const { submit } = renderDialog(); + submit(); + expect((await screen.findByRole('alert')).textContent).toBe(said); + expect(screen.queryByTestId('perm-clone-landing-pick')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/PermissionSetCloneDialog.tsx b/ui/packages/app-shell/src/views/metadata-admin/PermissionSetCloneDialog.tsx index cbdd2d6a212..96786cf4a20 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PermissionSetCloneDialog.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PermissionSetCloneDialog.tsx @@ -12,6 +12,14 @@ * every holder, and the dialog shows that refusal as a pick * (`PermissionSetHolderPick.tsx`): choosing a holder sends the clone again * from that holder's set. ⛔ Nothing is chosen by order. + * + * objectstack#38174 (ADR-0070 D1) — a copy with no package to land in is + * refused `422 WRITABLE_PACKAGE_REQUIRED`. The dialog shows that refusal in + * the server's words with one button per package the administrator can write + * (the package list's own `writable` verdict), and choosing one sends the + * clone again with that package as the body's `package`. ⛔ Nothing is chosen + * for the administrator, and with no writable package the server's sentence + * (which says to create one) stands alone. */ import * as React from 'react'; @@ -28,13 +36,18 @@ import { Label, } from '@object-ui/components'; import { t as translate, tFormat } from './i18n.js'; -import { clonePermissionSet, type PermissionSetCloned } from './permission-set-clone.js'; +import { + clonePermissionSet, + PermissionSetLandingRequired, + type PermissionSetCloned, +} from './permission-set-clone.js'; import { candidatePackage, PermissionSetHolderConflict, type PermissionSetHolderCandidate, } from './permission-set-holder.js'; import { PermissionSetHolderPick } from './PermissionSetHolderPick.js'; +import { useWritablePackageIds } from './studioListSource.js'; export interface PermissionSetCloneDialogProps { /** Machine name of the set being copied. */ @@ -66,30 +79,44 @@ export function PermissionSetCloneDialog({ source, sourcePackage, locale, onClos const [refusal, setRefusal] = React.useState(null); /** A refusal naming the name's holders, shown as a pick in place of {@link refusal}. */ const [conflict, setConflict] = React.useState(null); + /** A refusal for want of a package to land in, shown with a pick of the writable packages. */ + const [landing, setLanding] = React.useState(null); + /** The source package the last request named, so a landing pick re-sends the same source. */ + const lastSource = React.useRef(sourcePackage); + const writable = useWritablePackageIds(landing !== null); const ready = name.trim() !== '' && label.trim() !== ''; - /** Send the clone of `fromPackage`'s set — none names the set by its name alone. */ - async function submit(fromPackage: string | undefined) { + /** + * Send the clone of `fromPackage`'s set — none names the set by its name + * alone — saved in `intoPackage` when one was picked. + */ + async function submit(fromPackage: string | undefined, intoPackage?: string) { if (!ready || busy) return; + lastSource.current = fromPackage; setBusy(true); setRefusal(null); setConflict(null); + setLanding(null); try { const cloned = await clonePermissionSet( source, { name: name.trim(), label: label.trim() }, (status) => tFormat('perm.clone.failedHttp', locale, { status }), fromPackage, + intoPackage, ); onCloned(cloned); } catch (err: unknown) { if (err instanceof PermissionSetHolderConflict) setConflict(err); + else if (err instanceof PermissionSetLandingRequired) setLanding(err); else setRefusal(err instanceof Error && err.message ? err.message : t('perm.clone.failed')); setBusy(false); } } const pick = (candidate: PermissionSetHolderCandidate) => void submit(candidatePackage(candidate)); + const land = (packageId: string) => void submit(lastSource.current, packageId); + const landingIds = writable.status === 'read' ? [...writable.ids].sort() : []; return ( !open && !busy && onClose()}> @@ -115,6 +142,7 @@ export function PermissionSetCloneDialog({ source, sourcePackage, locale, onClos setName(e.target.value); setRefusal(null); setConflict(null); + setLanding(null); }} /> @@ -128,6 +156,7 @@ export function PermissionSetCloneDialog({ source, sourcePackage, locale, onClos setLabel(e.target.value); setRefusal(null); setConflict(null); + setLanding(null); }} /> @@ -137,6 +166,30 @@ export function PermissionSetCloneDialog({ source, sourcePackage, locale, onClos

)} {conflict !== null && } + {landing !== null && ( +
+

+ {landing.message} +

+ {landingIds.length > 0 && ( +
+ {landingIds.map((id) => ( + + ))} +
+ )} +
+ )}