diff --git a/.changeset/38174-packageless-create-refused.md b/.changeset/38174-packageless-create-refused.md
new file mode 100644
index 00000000000..182be92182d
--- /dev/null
+++ b/.changeset/38174-packageless-create-refused.md
@@ -0,0 +1,36 @@
+---
+'@objectstack/metadata-protocol': minor
+'@objectstack/runtime': minor
+'@objectstack/client': minor
+'@objectstack/spec': minor
+'@objectstack/cli': minor
+'@objectstack/lint': 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
+
+Clause-②: no (narrowing)
+Metadata-protocol: narrowed
+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`)
+
+
+
+**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 an item no package holds and no stored loose 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`). An `action` is keyed by its object (ADR-0150 D4): a package-less save of an action whose holders all bind other objects is the environment's new item and is refused the same way. In publish mode a package's draft of the name does not hold it, so a publish-mode save of a name only a package's draft carries is refused too.
+- **Not reached.** An in-place save, draft save, delete and per-item publish of an existing package-less item; a package-less save of an item a package holds (ADR-0150 D4: for an action, a holder at the body's object), and a draft-mode save of a name a package's draft holds (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.
+- **The clone door lands a kernel source's copy in a named package (widening).** `POST /api/v1/security/permission-sets/{name}/clone` with `package` naming a writable package, for a set a kernel package ships (`member_default`), was refused `409 RESOURCE_CONFLICT` because no such package declares a dependency on the kernel package; it now lands there (a kernel package is in every resolution closure, ADR-0150 D3), and the objects the set grants on are still judged against the target's closure.
+- **One notify-channel judge on both flow doors.** A flow written through the metadata save (`PUT /api/v1/meta/flow/{name}`, and every other caller of the runtime publish gate: a runtime package install, the MCP and AI doors) whose `notify` node names a channel no plugin registers was stored and armed (the `/automation` door refused it). The 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/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 66b450b8344..45265f99855 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
@@ -3007,7 +3010,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/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/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/content/docs/references/index.mdx b/content/docs/references/index.mdx
index 321c9083524..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 — 1762 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 | 540 | 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** | **1762** | 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, 540 schemas**
+**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **39 pages, 538 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/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/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/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/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/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/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..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, '..', '..', '..');
@@ -241,9 +252,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/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..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;
@@ -142,11 +144,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 +243,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 +1441,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 +1613,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/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/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/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/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/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.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/lint/src/validate-flow-notify-channels.ts b/packages/lint/src/validate-flow-notify-channels.ts
new file mode 100644
index 00000000000..9da4efd844f
--- /dev/null
+++ b/packages/lint/src/validate-flow-notify-channels.ts
@@ -0,0 +1,170 @@
+// 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`).
+ *
+ * ## 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';
+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-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-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-packageless-create.ts b/packages/metadata-protocol/src/protocol-packageless-create.ts
new file mode 100644
index 00000000000..db31f448627
--- /dev/null
+++ b/packages/metadata-protocol/src/protocol-packageless-create.ts
@@ -0,0 +1,175 @@
+// 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-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);
+ * - no package holds the ITEM: no active row of the name is bound to a
+ * package (a package-less save of an item a package holds customizes that
+ * holder, ADR-0150 D4, and keeps its answer). An `action` is keyed
+ * `(package, objectName, name)` (ADR-0150 D4, ruling 6902014292): when
+ * every holder binds the name to an object other than the one the body
+ * binds ({@link actionHeldOnlyOnOtherObjects}), no package holds this item,
+ * so the save would write the environment's own new item, and the holders
+ * on other objects do not make it a customization;
+ * - in DRAFT mode only, no draft row of it is bound to a package: the draft
+ * address binds a draft-mode save into that package (#23657), or refuses
+ * it 409 when two hold one. A publish-mode save is not bound by a draft
+ * (the publish-mode address reads active rows only), so a package's draft
+ * does not keep a publish-mode save of a new name from being a create.
+ *
+ * ## 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.
+ *
+ * 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
+ * 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
+ * system context (the fixture, not a fifth exemption).
+ */
+
+import type { ProtocolHost } from './protocol-host.js';
+import { actionHeldOnlyOnOtherObjects } from './sys-metadata-repository.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;
+ readonly packagelessCreateProvenance?: 'organization-ownership-ceremony';
+ /** The body, read for an `action`'s object (ADR-0150 D4's key). */
+ readonly item?: unknown;
+}
+
+/**
+ * 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',
+ mode: 'publish' | 'draft',
+): 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') return undefined;
+ if (request.packagelessCreateProvenance === 'organization-ownership-ceremony') return undefined;
+
+ const active = await host.packagelessAddress(singularType, request.name, member, 'active');
+ const drafts = await host.packagelessAddress(singularType, request.name, member, 'draft');
+ // A loose row of the name, active or draft, is saved in place.
+ if (active.unbound || drafts.unbound) return undefined;
+ // [ADR-0150 D4, ruling 6902014292] An action every holder binds to
+ // another object: no package holds THIS item, so neither the holders'
+ // active rows nor their drafts make the save a customization.
+ if (singularType === 'action' && active.candidates.length > 0
+ && actionHeldOnlyOnOtherObjects(singularType, request.item, await host.readItemActiveRows(singularType, request.name))) {
+ return packagelessCreateError(singularType, request.name, writablePackageIds(host));
+ }
+ // A holder's active row: the save customizes that holder (ADR-0150 D4).
+ if (active.candidates.length > 0) return undefined;
+ // A package's draft binds a DRAFT-mode save into that package (#23657),
+ // or refuses it 409 when two hold one. A publish-mode save is not bound
+ // by a draft, so it stays a create.
+ if (mode === 'draft' && drafts.candidates.length > 0) 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 54450446308..41868d9be9d 100644
--- a/packages/metadata-protocol/src/protocol-save.ts
+++ b/packages/metadata-protocol/src/protocol-save.ts
@@ -88,6 +88,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';
@@ -2159,6 +2160,21 @@ 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 an item no package holds
+ // (an action keyed at the body's object, ADR-0150 D4), that no loose
+ // row (active or draft) carries and, in draft mode, that no package's
+ // draft binds. In-place saves of an existing
+ // loose row, a holder's customization (ADR-0150 D4), the kernel-item
+ // 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, mode,
+ );
+ 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
@@ -2180,9 +2196,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
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..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
@@ -226,6 +228,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 +248,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..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,10 @@
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';
/** The engine surface the repository write path touches (as the container-issue-descent harness). */
function makeProtocol() {
@@ -36,7 +40,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 +74,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 +91,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..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,12 +43,19 @@ 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';
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 +205,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 +361,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 +406,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 +573,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..02137e2deff 100644
--- a/packages/metadata-protocol/src/protocol.credential-channel.test.ts
+++ b/packages/metadata-protocol/src/protocol.credential-channel.test.ts
@@ -32,7 +32,10 @@ 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';
const V2 = 'pin-protocol-secret-v2-b07c';
const DRAFT = 'pin-protocol-secret-draft-77e2';
@@ -95,7 +98,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 +184,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 +199,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 +215,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 +233,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 +253,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..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
@@ -118,6 +120,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 +222,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 +288,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 +302,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 +322,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 +336,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 +355,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 +424,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 +681,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..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,10 @@
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';
/** The engine surface the repository write path touches (as the container-issue-descent harness). */
function makeProtocol() {
@@ -37,7 +41,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 +76,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 +95,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..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;
@@ -56,6 +58,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 +106,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 +262,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..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;
@@ -83,6 +85,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 +187,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 +253,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 +274,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..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;
@@ -47,6 +49,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 +130,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 +194,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 +206,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 +216,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 +232,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 +244,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 +257,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 +267,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 +280,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 +292,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 +309,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 +364,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 +387,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 +398,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..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,11 @@
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';
/** The engine surface the repository write path touches (as the select-shorthand harness). */
function makeProtocol() {
@@ -46,7 +51,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 +103,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..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;
@@ -96,6 +98,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 +137,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 +271,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..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
@@ -64,8 +64,11 @@ import {
assertEngineDeleteDispatch,
assertEngineUpdateDispatch,
assertEngineFindOnePredicate,
+ 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
@@ -356,13 +359,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 +387,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 +450,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 +468,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 +485,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 +500,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 +677,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 +753,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 +766,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 +928,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 +976,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 +1015,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 +1031,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 +1042,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..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;
@@ -56,6 +58,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 +132,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 +170,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 +178,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 +186,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 +326,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..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;
@@ -152,6 +154,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 +259,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 +314,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 +335,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 +366,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 +393,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 +432,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 +474,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 +500,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..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,16 +89,25 @@ 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';
+/** [#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 +158,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 +183,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 +240,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 +367,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 +387,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..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`
@@ -190,8 +192,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 +226,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..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
@@ -272,6 +274,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 +302,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..c71dd519839 100644
--- a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts
+++ b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts
@@ -359,15 +359,52 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
name, label, type: 'url', target: `https://example.invalid/${label}`, ...(objectName ? { objectName } : {}),
});
const NAME = 'approve_p';
+ /**
+ * [#38174, ADR-0070 D1] The environment's own action is a NEW item at its
+ * key (ADR-0150 D4), so no door creates it package-less any more: it is a
+ * legacy loose row, laid as an older build left it, and each environment
+ * save below runs in place over it.
+ */
+ const layEnv = (seed: (row: Row) => void, objectName: string | undefined, state: 'active' | 'draft') => seed({
+ type: 'action', name: NAME, package_id: null, state,
+ metadata: JSON.stringify(action(NAME, 'env0', objectName)), checksum: 'sha-env0',
+ });
/** The stored rows of the action, by binding: `[package or null, objectName, label]`. */
const stored = (rows: Row[]) => rows
.map((r) => [r.package_id ?? null, JSON.parse(r.metadata).objectName ?? null, JSON.parse(r.metadata).label])
.sort((a, b) => String(a[0]).localeCompare(String(b[0])));
- it('FROM/TO: P holds the name on `invoice`; the save on `task` writes the environment\'s row, and P\'s row is untouched', async () => {
+ it('[#38174, contract review 7396202327 M2] TO: with no environment row stored, the save on `task` is the environment\'s NEW item, refused 422 WRITABLE_PACKAGE_REQUIRED; nothing is written', async () => {
+ const { protocol, rows, metadataWrites } = makeProtocol();
+ await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE });
+ const before = metadataWrites().length;
+
+ for (const mode of ['publish', 'draft'] as const) {
+ const err = resolveThrownHttpError(await refusalOf(() => protocol.saveMetaItem({
+ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), ...(mode === 'draft' ? { mode } : {}),
+ })));
+ expect([mode, err.status, err.code]).toEqual([mode, 422, 'WRITABLE_PACKAGE_REQUIRED']);
+ }
+ // An object-less body is its own key too.
+ const objectless = resolveThrownHttpError(await refusalOf(() => protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env') })));
+ expect([objectless.status, objectless.code]).toEqual([422, 'WRITABLE_PACKAGE_REQUIRED']);
+ expect(metadataWrites()).toHaveLength(before);
+ expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p']]);
+ expect(rows('action', NAME, 'draft')).toEqual([]);
+ });
+
+ it('[#38174] CONTROL: the save on `invoice`, the object P binds, is still P\'s customization, not a create', async () => {
const { protocol, rows } = makeProtocol();
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE });
+ await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'edited', 'invoice') });
+ expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'edited']]);
+ });
+ it('FROM/TO: P holds the name on `invoice`; the save on `task` writes the environment\'s row, and P\'s row is untouched', async () => {
+ const { protocol, rows, seedRow } = makeProtocol();
+ await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE });
+
+ layEnv(seedRow, 'task', 'active');
const saved = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') });
// FROM: `(env-wide, package=com.qa.lanebapp, …)` and ONE row, P's, on `task`.
@@ -376,8 +413,9 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
});
it('the read after the save: `?package=P` still answers P\'s item on `invoice`', async () => {
- const { protocol } = makeProtocol();
+ const { protocol, seedRow } = makeProtocol();
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE });
+ layEnv(seedRow, 'task', 'active');
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') });
// FROM: `['task', 'env']`, the environment's body under P. The bare
@@ -388,8 +426,9 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
});
it('a second package-less save on `task` edits the environment\'s row again; P\'s row is still untouched', async () => {
- const { protocol, rows } = makeProtocol();
+ const { protocol, rows, seedRow } = makeProtocol();
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE });
+ layEnv(seedRow, 'task', 'active');
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') });
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env2', 'task') });
@@ -398,9 +437,10 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
});
it('an object-less body is its own key too: the environment\'s row, P\'s row untouched', async () => {
- const { protocol, rows } = makeProtocol();
+ const { protocol, rows, seedRow } = makeProtocol();
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE });
+ layEnv(seedRow, undefined, 'active');
const saved = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env') });
expect(saved.message).not.toContain('package=');
@@ -408,10 +448,11 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
});
it('two packages holding the name on two other objects: the environment\'s row (FROM: 409 naming both)', async () => {
- const { protocol, rows } = makeProtocol();
+ const { protocol, rows, seedRow } = makeProtocol();
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE });
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'q', 'product'), packageId: OTHER_WRITABLE });
+ layEnv(seedRow, 'task', 'active');
const saved = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') });
expect(saved.success).toBe(true);
@@ -419,10 +460,11 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
});
it('a SOLE DISABLED holder on `invoice`: the save on `task` writes the environment\'s row (FROM: into the disabled package\'s row)', async () => {
- const { protocol, rows } = makeProtocol();
+ const { protocol, rows, seedRow } = makeProtocol();
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE });
protocol.engine.registry.isPackageDisabled = (id: string) => id === WRITABLE;
+ layEnv(seedRow, 'task', 'active');
const saved = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') });
expect(saved.message).not.toContain('package=');
@@ -434,6 +476,7 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
const GONE = 'com.qa.uninstalled';
seedRow({ type: 'action', name: NAME, package_id: GONE, metadata: JSON.stringify(action(NAME, 'gone', 'invoice')), checksum: 'sha-gone' });
+ layEnv(seedRow, 'task', 'active');
const saved = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') });
expect(saved.success).toBe(true);
@@ -455,9 +498,10 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
});
it('the DRAFT save on `task` writes the environment\'s draft (FROM: P\'s draft), and P\'s rows are untouched', async () => {
- const { protocol, rows } = makeProtocol();
+ const { protocol, rows, seedRow } = makeProtocol();
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE });
+ layEnv(seedRow, 'task', 'draft');
const drafted = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' });
// FROM: `(env-wide, package=com.qa.lanebapp, state=draft)`.
@@ -471,6 +515,7 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
const GONE = 'com.qa.uninstalled';
seedRow({ type: 'action', name: NAME, package_id: GONE, metadata: JSON.stringify(action(NAME, 'gone', 'invoice')), checksum: 'sha-gone' });
+ layEnv(seedRow, 'task', 'draft');
const drafted = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' });
expect(drafted.success).toBe(true);
@@ -479,8 +524,9 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
});
it('the per-item publish naming no package promotes that draft into the environment\'s row (FROM: over P\'s item on `invoice`)', async () => {
- const { protocol, rows } = makeProtocol();
+ const { protocol, rows, seedRow } = makeProtocol();
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE });
+ layEnv(seedRow, 'task', 'draft');
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' });
const published = await protocol.publishMetaItem({ type: 'action', name: NAME });
@@ -494,6 +540,7 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
const { protocol, rows, seedRow } = makeProtocol();
const GONE = 'com.qa.uninstalled';
seedRow({ type: 'action', name: NAME, package_id: GONE, metadata: JSON.stringify(action(NAME, 'gone', 'invoice')), checksum: 'sha-gone' });
+ layEnv(seedRow, 'task', 'draft');
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' });
await protocol.publishMetaItem({ type: 'action', name: NAME });
@@ -511,8 +558,9 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
}
it('the draft save writes the environment\'s draft', async () => {
- const { protocol, rows } = await twoHolders();
+ const { protocol, rows, seedRow } = await twoHolders();
+ layEnv(seedRow, 'task', 'draft');
const drafted = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' });
expect(drafted.message).toBe(`Saved action '${NAME}' (env-wide, state=draft) [seq=${drafted.seq}]`);
@@ -521,7 +569,8 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
});
it('the per-item publish naming no package promotes it into the environment\'s row', async () => {
- const { protocol, rows } = await twoHolders();
+ const { protocol, rows, seedRow } = await twoHolders();
+ layEnv(seedRow, 'task', 'draft');
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' });
const published = await protocol.publishMetaItem({ type: 'action', name: NAME });
@@ -532,7 +581,8 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
});
it('the draft discard naming no package removes it; both packages\' rows untouched', async () => {
- const { protocol, rows } = await twoHolders();
+ const { protocol, rows, seedRow } = await twoHolders();
+ layEnv(seedRow, 'task', 'draft');
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' });
const receipt = await protocol.deleteMetaItem({ type: 'action', name: NAME, state: 'draft' });
@@ -610,6 +660,7 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
it('the environment\'s draft on `task` stored beside P\'s customization row on `invoice`: the per-item publish naming no package is refused 409, and the row and the draft stay (FROM: promoted into P\'s row, moving P\'s action onto `task`; at the prior head of this change, that row rewritten onto `task`)', async () => {
const { protocol, rows, seedRow, metadataWrites } = makeProtocol();
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE });
+ layEnv(seedRow, 'task', 'draft');
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' });
seedRow({ type: 'action', name: NAME, package_id: null, metadata: JSON.stringify(action(NAME, 'custom', 'invoice')), checksum: 'sha-custom' });
const before = metadataWrites().length;
@@ -628,6 +679,7 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
it('the same, the per-item publish stating `packageId: null` in process: refused 409 the same way, and the row and the draft stay', async () => {
const { protocol, rows, seedRow, metadataWrites } = makeProtocol();
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE });
+ layEnv(seedRow, 'task', 'draft');
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' });
seedRow({ type: 'action', name: NAME, package_id: null, metadata: JSON.stringify(action(NAME, 'custom', 'invoice')), checksum: 'sha-custom' });
const before = metadataWrites().length;
@@ -643,8 +695,9 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
});
it('the environment\'s own row on `task`: a package-less save on `product` rewrites it onto `product` (one row per name, as for a name no package holds); P\'s row is untouched', async () => {
- const { protocol, rows } = makeProtocol();
+ const { protocol, rows, seedRow } = makeProtocol();
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE });
+ layEnv(seedRow, 'task', 'active');
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') });
const saved = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env2', 'product') });
@@ -654,8 +707,9 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
});
it('the environment\'s own draft on `task`: a package-less draft save on `product` rewrites it onto `product`; P\'s row is untouched', async () => {
- const { protocol, rows } = makeProtocol();
+ const { protocol, rows, seedRow } = makeProtocol();
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE });
+ layEnv(seedRow, 'task', 'draft');
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' });
const drafted = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env2', 'product'), mode: 'draft' });
@@ -671,6 +725,7 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
const fixture = makeProtocol();
await fixture.protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE });
await fixture.protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p-draft', 'invoice'), packageId: WRITABLE, mode: 'draft' });
+ layEnv(fixture.seedRow, 'task', 'draft');
await fixture.protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' });
expect(stored(fixture.rows('action', NAME, 'draft'))).toEqual([[WRITABLE, 'invoice', 'p-draft'], [null, 'task', 'env']]);
return fixture;
@@ -712,7 +767,7 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
// version (FROM: P's item and P's version, so the save carrying it was
// refused as a version conflict after the environment's row existed too).
it('[#33904] the version the read naming no package serves is P\'s item\'s until the environment\'s row exists (a save on `task` carrying it is refused), then the environment\'s, which a save on `task` carries as its parent', async () => {
- const { protocol, rows } = makeProtocol();
+ const { protocol, rows, seedRow } = makeProtocol();
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE });
const atPackage = await protocol.getMetaItem({ type: 'action', name: NAME, packageId: WRITABLE });
@@ -722,9 +777,13 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
const first = resolveThrownHttpError(await refusalOf(() => protocol.saveMetaItem({
type: 'action', name: NAME, item: action(NAME, 'env', 'task'), parentVersion: before.version,
})));
- expect([first.status, first.code]).toEqual([409, 'METADATA_CONFLICT']);
+ // [#38174] Before the environment's row exists the save on `task` is
+ // a package-less CREATE (ADR-0070 D1), refused before its version is
+ // judged (FROM: 409 METADATA_CONFLICT on the version it carried).
+ expect([first.status, first.code]).toEqual([422, 'WRITABLE_PACKAGE_REQUIRED']);
expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p']]);
+ layEnv(seedRow, 'task', 'active');
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') });
const after = await protocol.getMetaItem({ type: 'action', name: NAME });
expect([(after.item as any)?.objectName, (after.item as any)?.label]).toEqual(['task', 'env']);
@@ -742,10 +801,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(); seedEnv(); 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];
@@ -771,8 +833,9 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder
// names both, as the read and the delete naming no package already serve
// and remove the environment's (BASE: the list named P's item only).
it('[#33904] P\'s action OBJECT-LESS, the environment\'s on `task`: the list names both, the read naming no package serves the environment\'s, and the delete naming no package removes it', async () => {
- const { protocol, rows } = makeProtocol();
+ const { protocol, rows, seedRow } = makeProtocol();
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p'), packageId: WRITABLE });
+ layEnv(seedRow, 'task', 'active');
await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') });
expect(stored(rows('action', NAME))).toEqual([[WRITABLE, null, 'p'], [null, 'task', 'env']]);
const face = (item: any) => [item?.objectName ?? null, item?.label ?? null];
@@ -945,8 +1008,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 +1261,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 +1403,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 +1489,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 +1523,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 +1537,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 +1562,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 +1715,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 +1818,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 +1880,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 +1969,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 +2012,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 +2029,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 +2072,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 +2084,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 +2116,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 +2137,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 +2162,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 +2187,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 +2199,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 +2207,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..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';
@@ -269,6 +271,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 +369,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 +441,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 +574,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..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
@@ -322,6 +324,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 +403,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 +412,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 +479,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 +487,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 +533,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 +551,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 +580,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 +626,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..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;
@@ -48,6 +50,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 +124,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 +161,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..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
@@ -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({});
@@ -354,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) {
@@ -391,7 +396,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..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,10 +44,13 @@ 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;
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 +121,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 +198,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);
});
}
@@ -262,7 +266,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) {
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..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;
@@ -60,6 +62,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 +101,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 +205,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 +222,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 +238,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 +319,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.ts b/packages/metadata-protocol/src/protocol.ts
index d4cbff33033..8eb1e487635 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 {
@@ -1936,6 +1937,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,
};
@@ -2243,6 +2245,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/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/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/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