diff --git a/.changeset/38150-adopt-orphans-door-retired.md b/.changeset/38150-adopt-orphans-door-retired.md new file mode 100644 index 00000000000..242c39c6d84 --- /dev/null +++ b/.changeset/38150-adopt-orphans-door-retired.md @@ -0,0 +1,37 @@ +--- +'@objectstack/spec': major +'@objectstack/metadata-protocol': patch +'@objectstack/runtime': patch +'@objectstack/client': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(runtime)!: `POST /api/v1/packages/:id/adopt-orphans` is retired; loose items move by an explicit selection through `POST /api/v1/packages/:id/move-in` + +Clause-②: no (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING.** The all-at-once adoption of every loose (package-less) item into one package is gone, with every surface that reached it. It rebound rows with a bare storage update and asked none of the save door's questions, so it could adopt into a package nothing installed, adopt an object its target's namespace prefix refuses, and leave the runtime serving the old address until a restart (#37468). ADR-0084's amendment of 2026-11-26 replaces it with one door that moves a selection, each item through the save door: `POST /api/v1/packages/:id/move-in`, shipped in the same release. + +What is removed: + +- the route `POST /api/v1/packages/:id/adopt-orphans` (it answers `404` now), and its route-ledger row; +- the client method `packages.adoptOrphans(id)` of `@objectstack/client`; +- the protocol method `reassignOrphanedMetadata` of `@objectstack/metadata-protocol`'s `ObjectStackProtocolImplementation`; +- `ReassignOrphanedMetadataResponseSchema` and its `ReassignOrphanedMetadataResponse` / `ReassignOrphanedMetadataResponseParsed` types from `@objectstack/spec/api`, and the published JSON schema `api/ReassignOrphanedMetadataResponse.json`; +- the operation-message key `packages_orphan_adoption_unsupported` (four locales); +- in the console, the Packages page's "Adopt loose items" button and its dialog, and the matching item of Studio's 「⋯」 package menu, with the `engine.packages.detail.adopt*` keys of `@object-ui/i18n`'s studio namespace (`adoptOrphans`, `adopting`, `adoptTitle`, `adoptDescription`, `adoptedOne`, `adoptedOther`). The console's door to move loose items is the move-in confirm step of the next change in this release. + +How to move: + +| before | after | +|:--|:--| +| `POST /api/v1/packages/:id/adopt-orphans` | `POST /api/v1/packages/:id/move-in` with `{ "items": [{ "type": "flow", "name": "…" }, …] }` | +| `client.packages.adoptOrphans(id)` | `client.packages.moveIn(id, { items })` | +| `protocol.reassignOrphanedMetadata({ targetPackageId })` | `protocol.moveIntoPackage({ targetPackageId, items })` | +| `ReassignOrphanedMetadataResponseSchema` | `MoveIntoPackageResponseSchema` | + +The fix in one line: name the loose items to move; to move them all, list them and pass every one. The move is whole or nothing, and `dryRun: true` answers what it would do without writing. diff --git a/content/docs/api/metadata-api.mdx b/content/docs/api/metadata-api.mdx index 468823c93a3..34bff56cffe 100644 --- a/content/docs/api/metadata-api.mdx +++ b/content/docs/api/metadata-api.mdx @@ -174,7 +174,7 @@ Under a `group` or `isolated` tenancy posture every `/packages` write is the platform operator's (ADR-0131 D12 items 7–8, D11): install (`POST /packages`), the manifest `PATCH`, enable, disable, publish, `publish-drafts`, `discard-drafts`, `revert`, `rollback`, `commits/:commitId/revert`, `duplicate`, -`adopt-orphans` and this delete. Any other caller, a `manage_metadata` holder +`move-in` and this delete. Any other caller, a `manage_metadata` holder inside one organization included, is refused `403 PERMISSION_DENIED` naming the posture, before anything is read or written, whatever the package carries. Reads are unchanged. Under `single` every `manage_metadata` holder writes as diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 4fb987ecf85..91f3e088863 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -213,7 +213,7 @@ One of the largest consumers of the flag; | 54 | Package REST route capability gate bypassed | rest | Get: a marketplace publish over REST (`POST /packages/publish`, the one route the REST registrar mounts since #14503) without `manage_metadata`; the package read cohort (`studio.access` / `setup.access`) is enforced by the dispatcher `/packages` domain's own read gate, where the reads are served | `refusePackageRequest` | | 55 | Package domain capability gates bypassed | runtime | Get: package management and package-inventory reads without the capability; and a write to a package that holds a knowledge source (the twelve doors that write an existing package) without `manage_knowledge_sources` beside it (ADR-0161 K4); and, on the move-in door, a selected `datasource` or `knowledge_source` moved without the capability its `/meta` write asks (`manage_platform_settings`, `manage_knowledge_sources`) | `requireManageMetadata`, `requireReadCapability`, `refuseKnowledgeSourcePackageWrite`, `handlePackagesRequest` | | 56 | Activation write / authoring refusals do not fire | runtime | Get: activation artifacts writable and authorable without the activation-authoring capability | `refuseUngrantedActivationWrite`, `refuseUngrantedActivationAuthoring` | -| 55b | Walled environment-metadata refusal does not fire | metadata-core, rest, runtime | Get: under `isolated` / `group`, a write of the environment's metadata, of any type, at the `/meta` write doors (save, reset, publish, rollback) and `POST /meta/_migrate-stored` on both transports, at every `/packages` write door (create, the manifest `PATCH`, enable, disable, publish, `publish-drafts`, `discard-drafts`, `revert`, `rollback`, `commits/:commitId/revert`, `duplicate`, `adopt-orphans`, delete), at the `/automation` definition writes (create, update, delete, clone), at the permission-set clone door, at the import of a remote table as an object (the REST import route and the MCP `import_object` tool), at the open MCP server's draft save and discard (`save_metadata_draft`, `delete_metadata_draft`), and at the refresh of a federated datasource's cached catalog. Every other caller below the platform-operator rung is refused `403` there (ADR-0131 D3, D12 items 7–8, D11), because one organization's write would change what every organization resolves. The seeders, the package door and migrations write the environment's metadata this way. Under `single` the refusal is inert for every caller | `walledCatalogWriteVerdict`, `walledCatalogRefusal`, `refuseWalledCatalogPackageWrite`, `refuseWalledFlowDefinitionWrite`, `registerExternalDatasourceRoutes`, `federationService`, `openWriter` | +| 55b | Walled environment-metadata refusal does not fire | metadata-core, rest, runtime | Get: under `isolated` / `group`, a write of the environment's metadata, of any type, at the `/meta` write doors (save, reset, publish, rollback) and `POST /meta/_migrate-stored` on both transports, at every `/packages` write door (create, the manifest `PATCH`, enable, disable, publish, `publish-drafts`, `discard-drafts`, `revert`, `rollback`, `commits/:commitId/revert`, `duplicate`, `move-in`, delete), at the `/automation` definition writes (create, update, delete, clone), at the permission-set clone door, at the import of a remote table as an object (the REST import route and the MCP `import_object` tool), at the open MCP server's draft save and discard (`save_metadata_draft`, `delete_metadata_draft`), and at the refresh of a federated datasource's cached catalog. Every other caller below the platform-operator rung is refused `403` there (ADR-0131 D3, D12 items 7–8, D11), because one organization's write would change what every organization resolves. The seeders, the package door and migrations write the environment's metadata this way. Under `single` the refusal is inert for every caller | `walledCatalogWriteVerdict`, `walledCatalogRefusal`, `refuseWalledCatalogPackageWrite`, `refuseWalledFlowDefinitionWrite`, `registerExternalDatasourceRoutes`, `federationService`, `openWriter` | | 57 | Automation run-state read, flow-authoring write, the paused-run caller gate (screen read and resume), the two operator run-lifecycle writes, and the elevated self-triggered start, the AI-service-account elevated start and the start-record check at every door that starts a flow by name all pass | runtime | Get: run state, flow writes, a paused run's screen and its resume with no grant and without being the run's starter — and cancelling or restoring a suspension without the platform-operator rung. The screen read and the resume ask one predicate, so this is one bypass for both. The lifecycle bypass is the in-process owner's door: plugin-approvals' revise-window recall (ADR-0044) cancels on behalf of a decision it already authorized and recorded. And starting a flow declared `runAs: 'system'` whose type is self-triggered (`autolaunched`, `record_change`, `schedule`) through any door that starts a flow by name — the trigger route, an action of `type: 'flow'` (REST `/actions` and the MCP `run_action` bridge) and a declared endpoint of `type: 'flow'` — which every other caller, the guest principal included, is refused `403 PERMISSION_DENIED` (the maintainer's rulings, letters B and A) — and starting, through the same doors, a flow whose `requiredPermissions` the caller does not hold (ruling record 6377848497, letter A) — and starting, through the same doors, a flow declared `runAs: 'system'` as an AI service account (an agent acting for itself, with no `onBehalfOf`) where the action's `ai.exposed: true` opt-in is not in hand, which that account is refused `403 PERMISSION_DENIED` (ADR-0151 Non-goals, ruling record 6812617393, letter C; a trigger route and a declared endpoint carry no opt-in, so there it is always refused, and the refusal names the action door that admits it). And starting, through the same doors, a flow on a record key the caller's own scope does not deliver, which every other caller is refused with the action door's `404 RECORD_NOT_FOUND` before the run exists (and `400 VALIDATION_FAILED` for a key that is not one id, or for an elevated start that names no object). The three doors ask one check, so this is one bypass for all of them, and it is the in-process caller's, such as a job: inbound HTTP never carries the flag | `mayReadRunState`, `refuseUngrantedFlowWrite`, `isRunStarterOrRunStateReader`, `refuseUngrantedRunLifecycleWrite`, `flowStartRefusal`, `refuseUnreadableFlowStartRecords` | | 57b | Connector credential door's capability and posture gates pass | runtime | Get: listing, setting and clearing the environment's stored connector credentials (`/automation/connectors/credential-refs`) without `manage_metadata`, and under the `group` / `isolated` postures, where the door refuses every other caller `403 PERMISSION_DENIED` naming the posture, the platform operator included, because the store is environment-level. The bypass is the in-process caller's: inbound HTTP never carries the flag. Get nothing more about the value: no answer of this door carries it | `refuseUngrantedConnectorCredentialAccess`, `refuseWalledConnectorCredentialAccess` | | 57c | Connector connection door's capability gate passes | runtime | Get: reading, beginning, completing (the OAuth callback) and revoking an organization's connection of an `oauth2` `authorization_code` connector instance (`/automation/connectors/:name/connection`, `/automation/connectors/oauth/callback`, ADR-0143 D5) without `manage_metadata`. No posture refuses it: a connection belongs to its organization. The bypass is the in-process caller's: inbound HTTP never carries the flag. Get nothing more: no answer of this door carries a token, and the callback's `state` is still bound to the user and organization that began the connect | `refuseUngrantedConnectorConnectionAccess` | diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index fe293cc7d3a..8380057b106 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -225,7 +225,7 @@ and the MCP draft door: imply it. Over MCP it is the human's own grant that is read, never the agent's. The package doors ask it too: every write to an existing package that holds a knowledge source (enable, disable, publish, publish-drafts, - discard-drafts, the commit revert, rollback, revert, adopt-orphans, + discard-drafts, the commit revert, rollback, revert, move-in, duplicate, the manifest update and delete) needs the capability, and is refused `403` naming it otherwise. A package that holds none is written as before. Two doors are not asked. Installing a package is one: a packaged diff --git a/content/docs/references/api/package-lifecycle.mdx b/content/docs/references/api/package-lifecycle.mdx index 50c179d9379..48b3c9e80f9 100644 --- a/content/docs/references/api/package-lifecycle.mdx +++ b/content/docs/references/api/package-lifecycle.mdx @@ -50,8 +50,8 @@ authored after that retirement per the ruling's sequencing (3A). ## TypeScript Usage ```typescript -import { DiscardPackageDraftsResponseSchema, DuplicatePackageResponseSchema, EnsureCustomizationPackageRequestSchema, EnsureCustomizationPackageResponseSchema, GetPackageCustomizationsRequestSchema, GetPackageCustomizationsResponseSchema, ImportUnmanagedPackageRequestSchema, ImportUnmanagedPackageResponseSchema, ListPackageCommitsResponseSchema, MoveIntoPackageItemSchema, MoveIntoPackageMovedItemSchema, MoveIntoPackageRefusedItemSchema, MoveIntoPackageRequestSchema, MoveIntoPackageResponseSchema, PackageExportBundleSchema, PackageExportManifestSchema, PackagePublishResultSchema, ReassignOrphanedMetadataResponseSchema, RevertPackageCommitResponseSchema, RollbackToPackageCommitResponseSchema } from '@objectstack/spec/api'; -import type { DiscardPackageDraftsResponse, DuplicatePackageResponse, EnsureCustomizationPackageRequest, EnsureCustomizationPackageResponse, GetPackageCustomizationsRequest, GetPackageCustomizationsResponse, ImportUnmanagedPackageRequest, ImportUnmanagedPackageResponse, ListPackageCommitsResponse, MoveIntoPackageItem, MoveIntoPackageMovedItem, MoveIntoPackageRefusedItem, MoveIntoPackageRequest, MoveIntoPackageResponse, PackageExportBundle, PackageExportManifest, PackagePublishResult, ReassignOrphanedMetadataResponse, RevertPackageCommitResponse, RollbackToPackageCommitResponse } from '@objectstack/spec/api'; +import { DiscardPackageDraftsResponseSchema, DuplicatePackageResponseSchema, EnsureCustomizationPackageRequestSchema, EnsureCustomizationPackageResponseSchema, GetPackageCustomizationsRequestSchema, GetPackageCustomizationsResponseSchema, ImportUnmanagedPackageRequestSchema, ImportUnmanagedPackageResponseSchema, ListPackageCommitsResponseSchema, MoveIntoPackageItemSchema, MoveIntoPackageMovedItemSchema, MoveIntoPackageRefusedItemSchema, MoveIntoPackageRequestSchema, MoveIntoPackageResponseSchema, PackageExportBundleSchema, PackageExportManifestSchema, PackagePublishResultSchema, RevertPackageCommitResponseSchema, RollbackToPackageCommitResponseSchema } from '@objectstack/spec/api'; +import type { DiscardPackageDraftsResponse, DuplicatePackageResponse, EnsureCustomizationPackageRequest, EnsureCustomizationPackageResponse, GetPackageCustomizationsRequest, GetPackageCustomizationsResponse, ImportUnmanagedPackageRequest, ImportUnmanagedPackageResponse, ListPackageCommitsResponse, MoveIntoPackageItem, MoveIntoPackageMovedItem, MoveIntoPackageRefusedItem, MoveIntoPackageRequest, MoveIntoPackageResponse, PackageExportBundle, PackageExportManifest, PackagePublishResult, RevertPackageCommitResponse, RollbackToPackageCommitResponse } from '@objectstack/spec/api'; // Validate data const result = DiscardPackageDraftsResponseSchema.parse(data); @@ -513,27 +513,6 @@ Whole-deployment export, the answer of `GET /packages/export` (`os package expor | **message** | `string` | ✅ | Validation error message | ---- - -## ReassignOrphanedMetadataResponse - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **success** | `boolean` | ✅ | Whether the reassignment ran. | -| **reassignedCount** | `number` | ✅ | How many orphaned items were adopted. | -| **reassigned** | `{ type: string; name: string }[]` | ✅ | Every item that was adopted. | -| **targetPackageId** | `string` | ✅ | The package the items were adopted into. | - -### Nested Shape: `ReassignOrphanedMetadataResponse.reassigned[number]` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **type** | `string` | ✅ | Metadata type of the adopted item. | -| **name** | `string` | ✅ | Name of the adopted item. | - - --- ## RevertPackageCommitResponse diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 4a1e331afc0..1711f420b11 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 — 1744 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1743 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/. */} @@ -21,7 +21,7 @@ counts are sums of the rows they head. Regenerate with | Module | Pages | Schemas | Description | | :--- | ---: | ---: | :--- | | [AI Protocol](/docs/references/ai) | 18 | 104 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | -| [API Protocol](/docs/references/api) | 37 | 529 | REST contracts, endpoints, routing, realtime, batch, discovery. | +| [API Protocol](/docs/references/api) | 37 | 528 | 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 | 197 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | | [Identity Protocol](/docs/references/identity) | 5 | 27 | Users and accounts, organizations, positions, SCIM provisioning. | @@ -34,7 +34,7 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 17 | 186 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **224** | **1744** | 14 protocol modules | +| **Total** | **224** | **1743** | 14 protocol modules | --- @@ -69,7 +69,7 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. ## API Protocol -**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **37 pages, 529 schemas** +**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **37 pages, 528 schemas** REST contracts, endpoints, routing, realtime, batch, discovery. @@ -97,7 +97,7 @@ REST contracts, endpoints, routing, realtime, batch, discovery. | [`odata.zod.ts`](/docs/references/api/odata) | `ODataConfig`, `ODataError`, `ODataFilterFunction`, `ODataMetadata`, `ODataQuery`, `ODataResponse` | | [`package-api.zod.ts`](/docs/references/api/package-api) | `GetInstalledPackageRequest`, `ListInstalledPackagesRequest`, `PackageApiErrorCode`, `PackageInstallBody`, `PackageInstallManifest`, `PackageInstallRequest`, `PackageInstallResponse`, `PackagePathParams`, `PackageRollbackRequest`, `PackageUpgradeRequest`, `PackageUpgradeResponse`, `ResolveDependenciesRequest`, `ResolveDependenciesResponse`, `UninstallPackageApiRequest`, `UninstallPackageApiResponse`, `UploadArtifactRequest`, `UploadArtifactResponse` | | [`package-api-assembled.zod.ts`](/docs/references/api/package-api-assembled) | `AssembledInstalledPackage`, `GetInstalledPackageResponse`, `InstalledPackageAtEitherStage`, `ListInstalledPackagesResponse` | -| [`package-lifecycle.zod.ts`](/docs/references/api/package-lifecycle) | `DiscardPackageDraftsResponse`, `DuplicatePackageResponse`, `EnsureCustomizationPackageRequest`, `EnsureCustomizationPackageResponse`, `GetPackageCustomizationsRequest`, `GetPackageCustomizationsResponse`, `ImportUnmanagedPackageRequest`, `ImportUnmanagedPackageResponse`, `ListPackageCommitsResponse`, `MoveIntoPackageItem`, `MoveIntoPackageMovedItem`, `MoveIntoPackageRefusedItem`, `MoveIntoPackageRequest`, `MoveIntoPackageResponse`, `PackageExportBundle`, `PackageExportManifest`, `PackagePublishResult`, `ReassignOrphanedMetadataResponse`, `RevertPackageCommitResponse`, `RollbackToPackageCommitResponse` | +| [`package-lifecycle.zod.ts`](/docs/references/api/package-lifecycle) | `DiscardPackageDraftsResponse`, `DuplicatePackageResponse`, `EnsureCustomizationPackageRequest`, `EnsureCustomizationPackageResponse`, `GetPackageCustomizationsRequest`, `GetPackageCustomizationsResponse`, `ImportUnmanagedPackageRequest`, `ImportUnmanagedPackageResponse`, `ListPackageCommitsResponse`, `MoveIntoPackageItem`, `MoveIntoPackageMovedItem`, `MoveIntoPackageRefusedItem`, `MoveIntoPackageRequest`, `MoveIntoPackageResponse`, `PackageExportBundle`, `PackageExportManifest`, `PackagePublishResult`, `RevertPackageCommitResponse`, `RollbackToPackageCommitResponse` | | [`plugin-rest-api.zod.ts`](/docs/references/api/plugin-rest-api) | `ErrorHandlingConfig`, `OpenApiGenerationConfig`, `RequestValidationConfig`, `ResponseEnvelopeConfig`, `RestApiEndpoint`, `RestApiPluginConfig`, `RestApiRouteCategory`, `RestApiRouteRegistration`, `ValidationMode` | | [`protocol.zod.ts`](/docs/references/api/protocol) | `AiAgentCapabilities`, `AiAgentChatRequest`, `AiAgentSummary`, `AiAgentsResponse`, `AiChatRequest`, `AiChatResponse`, `AiCompleteRequest`, `AiConversation`, `AiConversationMessage`, `AiMessage`, `AiModelsResponse`, `AiPendingAction`, `AiPendingActionStatus`, `AiStreamChunk`, `ApproveAiPendingActionResponse`, `AuditMetaItemRequest`, `AuditMetaItemResponse`, `AutomationActionsResponse`, `AutomationTriggerRequest`, `AutomationTriggerResponse`, `BatchDataRequest`, `BatchDataResponse`, `BuildProbeReport`, `CheckPermissionRequest`, `CheckPermissionResponse`, `CloneDataResponse`, `CreateAiConversationRequest`, `CreateDataRequest`, `CreateDataResponse`, `CreateManyDataRequest`, `CreateManyDataResponse`, `DeleteDataRequest`, `DeleteDataResponse`, `DeleteManyDataRequest`, `DeleteManyDataResponse`, `DeleteMetaItemRequest`, `DeleteMetaItemResponse`, `DestructiveChangeIssue`, `DiffMetaItemRequest`, `DiffMetaItemResponse`, `DisablePackageRequest`, `DisablePackageResponse`, `EnablePackageRequest`, `EnablePackageResponse`, `FieldStillShownBy`, `FindDataRequest`, `FindDataResponse`, `FindReferencesToMetaResponse`, `FlowRegistration`, `FlowRegistrationRefusal`, `GetDataRequest`, `GetDataResponse`, `GetDiscoveryRequest`, `GetDiscoveryResponse`, `GetEffectivePermissionsRequest`, `GetEffectivePermissionsResponse`, `GetFieldLabelsRequest`, `GetFieldLabelsResponse`, `GetLocalesRequest`, `GetLocalesResponse`, `GetMetaDiagnosticsResponse`, `GetMetaItemCachedRequest`, `GetMetaItemCachedResponse`, `GetMetaItemLayeredRequest`, `GetMetaItemLayeredResponse`, `GetMetaItemRequest`, `GetMetaItemResponse`, `GetMetaItemsRequest`, `GetMetaItemsResponse`, `GetMetaTypesRequest`, `GetMetaTypesResponse`, `GetNotificationPreferencesRequest`, `GetNotificationPreferencesResponse`, `GetObjectPermissionsRequest`, `GetObjectPermissionsResponse`, `GetPackageRequest`, `GetPackageResponse`, `GetPresenceRequest`, `GetPresenceResponse`, `GetPublishedMetaItemResponse`, `GetRecordFieldAccessResponse`, `GetTranslationsRequest`, `GetTranslationsResponse`, `GetUiViewRequest`, `GetUiViewResponse`, `HistoryMetaItemRequest`, `HistoryMetaItemResponse`, `HttpFindQueryParams`, `InstallPackageRequest`, `InstallPackageResponse`, `ListAiConversationsRequest`, `ListAiConversationsResponse`, `ListAiPendingActionsRequest`, `ListAiPendingActionsResponse`, `ListDraftsResponse`, `ListNotificationsRequest`, `ListNotificationsResponse`, `ListPackagesRequest`, `ListPackagesResponse`, `MarkAllNotificationsReadRequest`, `MarkAllNotificationsReadResponse`, `MarkNotificationsReadRequest`, `MarkNotificationsReadResponse`, `MetadataAuthoringClient`, `MetadataAuthoringSurface`, `MetadataConflictError`, `Notification`, `NotificationPreferences`, `PublicFormSubmitResponse`, `PublishMetaItemRequest`, `PublishMetaItemResponse`, `PublishPackageDraftsRequest`, `PublishPackageDraftsResponse`, `RealtimeConnectRequest`, `RealtimeConnectResponse`, `RealtimeDisconnectRequest`, `RealtimeDisconnectResponse`, `RealtimeSubscribeRequest`, `RealtimeSubscribeResponse`, `RealtimeUnsubscribeRequest`, `RealtimeUnsubscribeResponse`, `RegisterDeviceRequest`, `RegisterDeviceResponse`, `RejectAiPendingActionResponse`, `RollbackMetaItemRequest`, `RollbackMetaItemResponse`, `RuntimeAuthoringIssue`, `RuntimeBuildIssue`, `SaveMetaItemRequest`, `SaveMetaItemResponse`, `SearchAllHit`, `SearchAllPageHit`, `SearchAllResponse`, `SeedAppliedIdList`, `SeedAppliedLanded`, `SetPresenceRequest`, `SetPresenceResponse`, `UninstallPackageRequest`, `UninstallPackageResponse`, `UnregisterDeviceRequest`, `UnregisterDeviceResponse`, `UpdateAiConversationRequest`, `UpdateDataRequest`, `UpdateDataResponse`, `UpdateManyDataRequest`, `UpdateManyDataResponse`, `UpdateNotificationPreferencesRequest`, `UpdateNotificationPreferencesResponse`, `ValidateDataIssue`, `ValidateDataRequest`, `ValidateDataResponse` | | [`push-delivery.zod.ts`](/docs/references/api/push-delivery) | `PushDeliveryData`, `PushRoute` | diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md index 9c83f7ff346..73004c45c5f 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `api/` | 545 | +| `api/` | 543 | diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 5af543c7be4..ec3704bda2f 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -135,7 +135,6 @@ import { RollbackToPackageCommitResponse, PackageExportManifest, PackageExportBundle, - ReassignOrphanedMetadataResponse, MoveIntoPackageRequest, MoveIntoPackageResponse, DuplicatePackageResponse, @@ -3437,8 +3436,8 @@ export class ObjectStackClient { /** * [#12038] The eight methods from here down — `publish`, `discardDrafts`, - * `listCommits`, `revertCommit`, `rollback`, `export`, `adoptOrphans`, - * `duplicate` — are BOUND under the recorded five-part ruling. The + * `listCommits`, `revertCommit`, `rollback`, `export`, `adoptOrphans` + * (retired since, #38150; `moveIn` replaced it), `duplicate` — were BOUND under the recorded five-part ruling. The * handlers' `(protocol as any)` casts erase types their producers declare * completely a few files away, so every one of these annotations is a * describe-only transcription of that producer shape, published in @@ -3619,16 +3618,6 @@ export class ObjectStackClient { return this.unwrapResponse(res); }, - /** ADR-0070 D5: bulk-rebind package-less (orphaned) metadata into this base. */ - adoptOrphans: async (id: string, opts?: { /** @deprecated Ignored: the server records the signed-in caller, never a name the request supplies. */ actor?: string }): Promise => { - const route = this.getRoute('packages'); - const res = await this.fetch(`${this.baseUrl}${route}/${encodeURIComponent(id)}/adopt-orphans`, { - method: 'POST', - body: JSON.stringify(opts ?? {}), - }); - return this.unwrapResponse(res); - }, - /** * Move a selection of loose (package-less) items into this package — one * item, several, or every loose item of a type, across types. Whole or diff --git a/packages/client/src/packages-lifecycle.test.ts b/packages/client/src/packages-lifecycle.test.ts index d1db62f710f..763d9e51661 100644 --- a/packages/client/src/packages-lifecycle.test.ts +++ b/packages/client/src/packages-lifecycle.test.ts @@ -42,7 +42,6 @@ describe('client.packages lifecycle (#3563 PR-4)', () => { ['publishDrafts', (c: ObjectStackClient) => c.packages.publishDrafts('p1'), 'POST', `${BASE}/p1/publish-drafts`, {}], ['discardDrafts', (c: ObjectStackClient) => c.packages.discardDrafts('p1', { actor: 'admin' }), 'POST', `${BASE}/p1/discard-drafts`, { actor: 'admin' }], ['revert', (c: ObjectStackClient) => c.packages.revert('p1'), 'POST', `${BASE}/p1/revert`, undefined], - ['adoptOrphans', (c: ObjectStackClient) => c.packages.adoptOrphans('p1'), 'POST', `${BASE}/p1/adopt-orphans`, {}], ['moveIn', (c: ObjectStackClient) => c.packages.moveIn('p1', { items: [{ type: 'flow', name: 'f' }], dryRun: true }), 'POST', `${BASE}/p1/move-in`, { items: [{ type: 'flow', name: 'f' }], dryRun: true }], ] as const)('%s hits its lifecycle route', async (_name, call, method, url, expectedBody) => { const { client, fetchMock } = createMockClient({ success: true, data: { ok: true } }); diff --git a/packages/client/src/return-type-precision.test.ts b/packages/client/src/return-type-precision.test.ts index 16bfbf5c260..661e6b11416 100644 --- a/packages/client/src/return-type-precision.test.ts +++ b/packages/client/src/return-type-precision.test.ts @@ -113,7 +113,6 @@ import type { RevertPackageCommitResponse, RollbackToPackageCommitResponse, PackageExportManifest, - ReassignOrphanedMetadataResponse, MoveIntoPackageResponse, DuplicatePackageResponse, EnsureCustomizationPackageResponse, @@ -448,7 +447,6 @@ export async function returnTypePrecisionPins12038(): Promise { expectTypeOf(await client.packages.revertCommit('com.acme.crm', 'cmt_1')).toEqualTypeOf(); expectTypeOf(await client.packages.rollback('com.acme.crm', 'cmt_1')).toEqualTypeOf(); expectTypeOf(await client.packages.export('com.acme.crm')).toEqualTypeOf(); - expectTypeOf(await client.packages.adoptOrphans('com.acme.crm')).toEqualTypeOf(); expectTypeOf(await client.packages.moveIn('com.acme.crm', { items: [{ type: 'flow', name: 'f' }] })).toEqualTypeOf(); expectTypeOf(await client.packages.duplicate('com.acme.crm', 'com.acme.copy')).toEqualTypeOf(); expectTypeOf(await client.packages.ensureCustomization('com.acme.crm')).toEqualTypeOf(); diff --git a/packages/client/src/unwrap-misfire.pin.test.ts b/packages/client/src/unwrap-misfire.pin.test.ts index 2cd59f213b2..68dcaf7fdb0 100644 --- a/packages/client/src/unwrap-misfire.pin.test.ts +++ b/packages/client/src/unwrap-misfire.pin.test.ts @@ -49,7 +49,7 @@ import { RollbackToPackageCommitResponseSchema, PackageExportManifestSchema, PackageExportBundleSchema, - ReassignOrphanedMetadataResponseSchema, + MoveIntoPackageResponseSchema, DuplicatePackageResponseSchema, } from '@objectstack/spec/api'; import { PLURAL_TO_SINGULAR } from '@objectstack/spec/shared'; @@ -75,7 +75,9 @@ const BOUND_PAYLOAD_SCHEMAS: ReadonlyArray = [ // [#28914] `packages.exportAll` — `{ packages }`, strict; each entry is the // export manifest above, so its open half is covered by the plural pin below. ['PackageExportBundleSchema', PackageExportBundleSchema], - ['ReassignOrphanedMetadataResponseSchema', ReassignOrphanedMetadataResponseSchema], + // [#38150] `packages.moveIn` — it replaced `adoptOrphans` (retired) and its + // `ReassignOrphanedMetadataResponseSchema` row. + ['MoveIntoPackageResponseSchema', MoveIntoPackageResponseSchema], ['DuplicatePackageResponseSchema', DuplicatePackageResponseSchema], ]; diff --git a/packages/metadata-protocol/src/protocol-extension-field-suffix.ts b/packages/metadata-protocol/src/protocol-extension-field-suffix.ts index 4502b428cd9..4e31768722e 100644 --- a/packages/metadata-protocol/src/protocol-extension-field-suffix.ts +++ b/packages/metadata-protocol/src/protocol-extension-field-suffix.ts @@ -18,9 +18,8 @@ * (`objectExtensionItemRefusal`, `protocol-object-extension-item.ts`); * - `duplicatePackage`, for every object the copy would write, judged against * the TARGET id before the copy mints anything; - * - `reassignOrphanedMetadata` (the adopt-orphans door), for every active - * `object` row the adoption would rebind, judged against the TARGET id - * before the first storage update; + * - `moveIntoPackage` (the move-in door) reaches it through the save door, + * which it runs for every item it moves; * - `os validate` (`@objectstack/cli`) and the marketplace install * (`@objectstack/cloud-connection`), for a whole package body, through * {@link judgeExtensionFieldSuffix}. diff --git a/packages/metadata-protocol/src/protocol-host.ts b/packages/metadata-protocol/src/protocol-host.ts index 17e58bcd1b8..03d3dee610c 100644 --- a/packages/metadata-protocol/src/protocol-host.ts +++ b/packages/metadata-protocol/src/protocol-host.ts @@ -217,7 +217,6 @@ export interface ProtocolHost { readonly registryAllowsOverlay: (typeof ObjectStackProtocolImplementation)['registryAllowsOverlay']; readonly registryMemberServedAt: ObjectStackProtocolImplementation['registryMemberServedAt']; readonly registryTakesStoredRows: ObjectStackProtocolImplementation['registryTakesStoredRows']; - readonly releaseAdoptedObjectOwner: ObjectStackProtocolImplementation['releaseAdoptedObjectOwner']; readonly reportPageRequiresAbsentAtLoad: ObjectStackProtocolImplementation['reportPageRequiresAbsentAtLoad']; readonly reportSealedOverlayRows: ObjectStackProtocolImplementation['reportSealedOverlayRows']; readonly resolveAppPackageIdKey: ObjectStackProtocolImplementation['resolveAppPackageIdKey']; diff --git a/packages/metadata-protocol/src/protocol-object-owner.ts b/packages/metadata-protocol/src/protocol-object-owner.ts index adf947f10e1..73927703d6f 100644 --- a/packages/metadata-protocol/src/protocol-object-owner.ts +++ b/packages/metadata-protocol/src/protocol-object-owner.ts @@ -4,9 +4,9 @@ * [#25467 cut 17] The object-owner verdicts of * `ObjectStackProtocolImplementation`: which contributor kind a stored object * row registers as against the registry's owner of that name - * (`classifyObjectContribution`), and handing an adopted object's name from the - * `'sys_metadata'` sentinel owner to its rebound row - * (`releaseAdoptedObjectOwner`), moved out of `protocol.ts` whole. + * (`classifyObjectContribution`), moved out of `protocol.ts` whole. (The cut + * also moved `releaseAdoptedObjectOwner`, which retired with the adopt-orphans + * door, #38150.) * * A MOVE, not a redesign. Each function below is the body of the * `ObjectStackProtocolImplementation` method of the same name as it stood, @@ -80,32 +80,3 @@ export function classifyObjectContribution( } return { kind: 'overlay', packageId: binding || 'sys_metadata' }; } - -/** The body of `ObjectStackProtocolImplementation#releaseAdoptedObjectOwner`; the method's docblock there is its contract. */ -export function releaseAdoptedObjectOwner( - this: Pick, - name: string, item: unknown, targetPackageId: string, -): boolean { - const registry: any = (this.engine as any)?.registry; - if (typeof registry?.registerObject !== 'function') return false; - if (!item || typeof item !== 'object' || typeof (item as { name?: unknown }).name !== 'string') return false; - const owner: { packageId?: unknown } | undefined = typeof registry.getObjectOwner === 'function' - ? registry.getObjectOwner(name) - : undefined; - if (owner === undefined) return true; - if (owner.packageId !== 'sys_metadata' || typeof registry.unregisterObject !== 'function') return false; - try { - registry.unregisterObject(name); - return true; - } catch (err: any) { - console.error( - `[Protocol] reassignOrphanedMetadata: object '${name}' was adopted into package ` - + `'${targetPackageId}' in sys_metadata, but the registry keeps its package-less definition ` - + `(owner 'sys_metadata') until the next restart: ${err?.message ?? err}. Until then the data ` - + `plane serves the pre-adoption definition, and a save of the object naming '${targetPackageId}' ` - + 'answers success without going live. Fix: restart the server; the boot registers the object ' - + `under '${targetPackageId}'.`, - ); - return false; - } -} diff --git a/packages/metadata-protocol/src/protocol-package-commits.ts b/packages/metadata-protocol/src/protocol-package-commits.ts index cee57dcab20..7335bebd7dc 100644 --- a/packages/metadata-protocol/src/protocol-package-commits.ts +++ b/packages/metadata-protocol/src/protocol-package-commits.ts @@ -1,10 +1,10 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * [#29985 codemod] The "Package revert, duplicate, import, orphans, commits, + * [#29985 codemod] The "Package revert, duplicate, import, commits, * revertCommit, rollback" facet of `ObjectStackProtocolImplementation`: the * bodies of `revertStoredPackage`, `duplicatePackage`, - * `importUnmanagedPackage`, `reassignOrphanedMetadata`, `listCommits`, + * `importUnmanagedPackage`, `listCommits`, * `readRevertableCommit`, `revertCommit`, `rollbackToPackageCommit`, * `rollbackMetaItem`, `rollbackMetaItemUnaudited` moved out of `protocol.ts` * whole (split by #29998 and #30687). @@ -34,7 +34,6 @@ import { packageScopedRowWhere } from './sys-metadata-repository.js'; import { overlayMemberWhere } from './migrations/overlay-index.js'; import type { SysMetadataRepository } from './sys-metadata-repository.js'; import { ConflictError, assertProtocolCompat } from '@objectstack/metadata-core'; -import { isPlatformRecordRow } from '@objectstack/metadata'; import { planUnmanagedImport, UNMANAGED_SEED_TYPE, @@ -71,7 +70,6 @@ import { canonicalizeMetaRequestType, overlaySchemaDeclaredKey, } from './protocol-meta-type-schema.js'; -import { permissionSetOwnerBindingRefusal } from './protocol-authoring-refusals.js'; import { zodIssuesToMetadataIssues } from './protocol-metadata-issues.js'; import { bundleMemberDiscriminator, @@ -919,202 +917,6 @@ export class ProtocolPackageCommitsFacet { }; } - /** The body of `ObjectStackProtocolImplementation#reassignOrphanedMetadata`; the method's docblock there is its contract. */ - static async reassignOrphanedMetadata(host: Pick, request: { - targetPackageId: string; - actor?: string; - }): Promise<{ - success: boolean; - reassignedCount: number; - reassigned: Array<{ type: string; name: string }>; - targetPackageId: string; - }> { - // [ADR-0131 D6] FIRST: an organization-scoped adoption is refused. - host.refuseOrganizationScopedWrite( - `Package '${request.targetPackageId}'`, request, - ); - // The ENVIRONMENT's orphans: ADR-0070 D5 makes the environment the unit - // ("bulk-assign legacy orphans to a default base named for the - // environment"), and since ADR-0131 D6 every new orphan is - // environment-wide (`saveMetaItem` writes `organization_id = NULL`). A - // legacy organization-scoped row is left as it is stored — rebinding - // it would be an organization-scoped write; the promotion ceremony - // (ADR-0131 C7) carries it to the environment layer, where a later - // adoption sees it. - const where: Record = {}; - // [#21911] The explicit system opt-in — see findServedOverlayRow. - const rows = (await host.findEnvironmentRows('sys_metadata', { where, context: { isSystem: true } })) as any[]; - const orphans = rows.filter( - (r) => (r?.package_id == null || r.package_id === '' || r.package_id === 'sys_metadata') - // [#23198] An overlay of an artifact item keeps its binding - // (ADR-0070); see the header. The type folds as the save's does. - && !host.isArtifactBacked(PLURAL_TO_SINGULAR[r.type] ?? r.type, String(r.name)) - // [#37604] …nor the platform's own record: the package-less row - // the platform registers at every boot is no orphan an author - // left behind, and rebound it would become the target's item, - // mark and all (`isPlatformRecordRow`, `@objectstack/metadata`, - // the one reader the restore refusal and the overlay census ask). - && !isPlatformRecordRow(r), - ); - - // [ADR-0029 D9.9, ADR-0086 D3, #28776] ⭐ THE OWNER JUDGES, in the save - // door's order (before the `__c` judge below), against the TARGET and - // before the first update: refused whole, each with its own envelope. - // The object arm skips the `'sys_metadata'` sentinel owner, the orphan's - // own registration this adoption hands over; see the header. - for (const row of orphans) { - if (row?.state !== 'active' || typeof row.name !== 'string') continue; - const type = canonicalMetaType(String(row.type)); - if (type === 'object') { - const layer = host.classifyObjectContribution(row.name, request.targetPackageId); - if (layer.kind === 'mismatch' && layer.ownerPackageId !== 'sys_metadata') { - throw host.overlayPackageMismatchError( - row.name, request.targetPackageId, layer.ownerPackageId, - ); - } - } else if (type === 'permission') { - let body: unknown; - try { - body = typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata; - } catch { - continue; - } - const ownerRefusal = permissionSetOwnerBindingRefusal( - type, body, row.name, request.targetPackageId, 'save', - ); - if (ownerRefusal) throw ownerRefusal; - } - } - - // [ADR-0146 D10, #28735] ⭐ THE `__c` RESERVATION, JUDGED AGAINST THE - // TARGET, before the first update below: each active object row this - // adoption rebinds becomes the target's own object. Refused whole, with - // the save door's judge and envelope; see the header. An unparseable - // row is left to the loop, as `duplicatePackage` leaves it. - { - const adoptedObjects: Record = {}; - for (const row of orphans) { - if (canonicalMetaType(String(row?.type)) !== 'object' || row.state !== 'active') continue; - if (typeof row.name !== 'string') continue; - let body: unknown; - try { - body = typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata; - } catch { - continue; - } - if (body && typeof body === 'object' && !Array.isArray(body)) { - adoptedObjects[row.name] = { ...(body as Record), name: row.name }; - } - } - const suffixRefusals = judgeExtensionFieldSuffix({ packageId: request.targetPackageId, objects: adoptedObjects }); - if (suffixRefusals.length > 0) throw extensionFieldSuffixRefusalError(suffixRefusals); - } - - const reassigned: Array<{ type: string; name: string }> = []; - // [#12981] The refusal channel this loop used to lack entirely. - // - // The catch below is the card's defining shape, and this method is the - // sharpest instance of it in the file: a refused `update` was dropped - // whole -- not logged, not rethrown, not carried on the response -- and - // the return then reported `success: reassigned.length > 0`. So an - // adoption where 99 of 100 orphans were refused answered - // `{success: true, reassignedCount: 1}`, byte-identical in shape to a - // healthy run with one orphan to move, and the 99 stayed orphans with - // nothing anywhere recording that they had been tried. Nothing retries - // them and no later boot reconstructs the attempt. - // - // A COUNTER plus one report AFTER the loop, deliberately, and not a - // `console.error` inside the catch: AGENTS.md -> "Degradation log - // levels" says an operator-facing degradation is stated ONCE, at the - // first occurrence, not once per failed write -- and a refused - // `sys_metadata` write is refused for every row, so the per-row - // spelling would print one line per orphan in the environment. This is - // the same shape #12923's shared refusal accumulator takes at the other - // repaired seams of this family. - let refusedCount = 0; - let firstRefusal = ''; - for (const row of orphans) { - try { - await host.engine.update( - 'sys_metadata', - { package_id: request.targetPackageId }, - { where: { id: row.id }, context: { isSystem: true } }, - ); - reassigned.push({ type: row.type, name: row.name }); - } catch (e: any) { - // Control flow is UNCHANGED: a row that cannot be rebound must - // not abort the adoption of the rows that can. Only the - // silence changes. - refusedCount += 1; - if (firstRefusal === '') firstRefusal = e?.message ?? String(e); - continue; - } - // [#23198] The registry follows the rebound row now, not at the - // next restart; see the header. [#23646] A view, and an object. - const type = canonicalMetaType(String(row.type)); - if (type !== 'view' && type !== 'object') continue; - // [#23646, #23690] Only an ACTIVE row reaches the registry: the - // boot registers no other ({@link loadMetaFromDb}), and a draft - // never reaches the runtime. An adopted draft is rebound in - // storage only. - if (row.state !== 'active') continue; - let rebound: { name: string; data: unknown }; - try { - // The row as the list read hydrates it, at its new binding. - [rebound] = host.storedOverlayEntries({ type }, [{ ...row, package_id: request.targetPackageId }]); - } catch (err: any) { - // Best-effort, as the write-through's own failure is: the row - // is rebound, and the next list read hydrates it. - console.warn(`[Protocol] registry write-through failed for ${type}/${row.name}: ${err?.message ?? err}`); - continue; - } - // [#23646] An object's one registry owner moves with its row. - if ( - type === 'object' - && !host.releaseAdoptedObjectOwner(rebound.name, rebound.data, request.targetPackageId) - ) { - continue; - } - await host.applyRegistryWriteThrough({ - type, - name: rebound.name, - item: rebound.data, - packageId: request.targetPackageId, - organizationId: null, - reboundFrom: { packageId: row.package_id ?? null }, - }); - } - if (refusedCount > 0) { - // `error` and not `warn`, by the one question AGENTS.md turns this - // on -- after the degradation the system still looks normal from - // the outside while something it claims to have persisted did not - // land. It is the same verdict, on the same sink, that - // `recordPackageCommit` in this file already reaches for the - // `sys_metadata_commit` write, and the inverse of the one - // `clientFacingRowFailureText` records for its `console.warn` - // (there the row reports `success: false` and the counters - // reconcile, so nothing was silently dropped; here neither holds). - console.error( - `[Protocol] reassignOrphanedMetadata: ${refusedCount} of ${orphans.length} orphaned ` - + `metadata row(s) were NOT rebound to package '${request.targetPackageId}' -- the ` - + `update was REFUSED. The call still answers reassignedCount=${reassigned.length}` - + `${reassigned.length > 0 ? ' with success: true' : ''}, so nothing looks broken, but ` - + 'those rows are STILL orphans: they keep `package_id` null or the `sys_metadata` ' - + 'sentinel, this environment has NOT converged on the package-first model (ADR-0070 ' - + 'D5 completes when an environment has no orphans), and nothing retries them. ' - + `First refusal: ${firstRefusal}. Fix: restore write access to \`sys_metadata\` for ` - + 'the system context and run the adoption again -- it is idempotent, rows already ' - + 'bound to a real package are left untouched.', - ); - } - return { - success: reassigned.length > 0, - reassignedCount: reassigned.length, - reassigned, - targetPackageId: request.targetPackageId, - }; - } - /** The body of `ObjectStackProtocolImplementation#listCommits`; the method's docblock there is its contract. */ static async listCommits(host: Pick, request: { packageId: string; diff --git a/packages/metadata-protocol/src/protocol-package-move-in.test.ts b/packages/metadata-protocol/src/protocol-package-move-in.test.ts index c2a9ac24508..b619deb8426 100644 --- a/packages/metadata-protocol/src/protocol-package-move-in.test.ts +++ b/packages/metadata-protocol/src/protocol-package-move-in.test.ts @@ -113,6 +113,39 @@ describe('the move door facet (#38150)', () => { expect(restoredF1.body).toMatchObject({ name: 'f1' }); }); + it('a row stored at any package-less spelling (null, \'\', the sys_metadata sentinel) is loose; a package\'s row is not', async () => { + // [ADR-0070 D5] The three spellings the retired adopt-orphans door rebound + // (#38150 PR-B1 removed its objectql pin with the door). + const { host } = stubHost([ + { ...flowRow('a'), package_id: null }, + { ...flowRow('b'), package_id: '' }, + { ...flowRow('c'), package_id: 'sys_metadata' }, + { ...flowRow('owned'), package_id: 'app.existing' }, + ]); + const loose = await move(host, [{ type: 'flow', name: 'a' }, { type: 'flow', name: 'b' }, { type: 'flow', name: 'c' }], true); + expect(loose.outcome).toBe('would_move'); + expect(loose.moved.map((m) => m.name)).toEqual(['a', 'b', 'c']); + const owned = await move(host, [{ type: 'flow', name: 'owned' }], true); + expect(owned.refused.map((r) => `${r.name}:${r.code}`)).toEqual(['owned:NOT_LOOSE']); + }); + + it('the platform\'s own record is not loose: refused NOT_LOOSE, and an author\'s row of a package-named body is', async () => { + // [#37604] A package-less row whose body carries the platform's mark is the + // record the platform registers at every boot (`isPlatformRecordRow`), not + // an item an author left behind. The retired adopt-orphans door pinned the + // same exclusion (#38150 PR-B1 removed its test with the door). + const platformRow = { ...flowRow('helper'), metadata: JSON.stringify({ name: 'helper', label: 'helper', _provenance: 'platform' }) }; + const { host } = stubHost([platformRow]); + const answer = await move(host, [{ type: 'flow', name: 'helper' }], true); + expect(answer.outcome).toBe('refused'); + expect(answer.refused.map((r) => `${r.name}:${r.code}`)).toEqual(['helper:NOT_LOOSE']); + + // Control: a body that names a package is no platform record, and moves. + const named = { ...flowRow('helper'), metadata: JSON.stringify({ name: 'helper', label: 'helper', _provenance: 'platform', _packageId: 'com.acme.crm' }) }; + const control = stubHost([named]); + expect((await move(control.host, [{ type: 'flow', name: 'helper' }], true)).outcome).toBe('would_move'); + }); + it('a refusal with no code of its own is MOVE_FAILED, its declared sentence quoted', async () => { const { host } = stubHost([flowRow('f1')]); host.saveMetaItem.mockRejectedValueOnce(refusal('The flow cannot be saved here.', 400)); diff --git a/packages/metadata-protocol/src/protocol-package-move-in.ts b/packages/metadata-protocol/src/protocol-package-move-in.ts index b56a70c58e5..2bf63818a16 100644 --- a/packages/metadata-protocol/src/protocol-package-move-in.ts +++ b/packages/metadata-protocol/src/protocol-package-move-in.ts @@ -11,7 +11,8 @@ * door moves them") and its ruling: a loose item stays where it is unless an * author moves it, and the move "runs each item through the save door's judges, * judging the selection as a set for the ADR-0150 D3 (a) cross-boundary rule". - * The old all-at-once adoption (`reassignOrphanedMetadata`) rebound rows with a + * The old all-at-once adoption (`reassignOrphanedMetadata`, retired by #38150's + * PR-B1) rebound rows with a * bare `engine.update` and asked none of the save door's questions, which let it * adopt into a package nothing installed, adopt an object its target's namespace * prefix refuses, and leave the runtime serving the old address until a restart. diff --git a/packages/metadata-protocol/src/protocol-registry-hydration.ts b/packages/metadata-protocol/src/protocol-registry-hydration.ts index efa63c12472..8421b125368 100644 --- a/packages/metadata-protocol/src/protocol-registry-hydration.ts +++ b/packages/metadata-protocol/src/protocol-registry-hydration.ts @@ -1355,7 +1355,7 @@ export class ProtocolRegistryHydrationFacet { * 2. Replace the record of the rows the write addresses with the names * registered in step 1. The old names come out of the record before any * heal runs, so a write that lands meanwhile reconciles against the new - * set. A rebind (an orphan adoption, {@link reassignOrphanedMetadata}) + * set. A rebind (the undo of a move into a package, `moveIntoPackage`) * addresses the row under both bindings: the record of the binding it * left is removed, and its names count as the row's old names. * 3. Heal each old name the new set lacks through the delete's per-name @@ -1507,9 +1507,9 @@ export class ProtocolRegistryHydrationFacet { * [#23198] Every caller awaits it: a republish of a view container heals * the members it dropped ({@link reconcileViewExpansions}) before the * write answers, so the reads that follow it serve the published set. - * The orphan adoption ({@link reassignOrphanedMetadata}) calls it for each - * view row it rebinds, with `reboundFrom`, and [#23646] for each object - * row, once {@link releaseAdoptedObjectOwner} has handed it the name. + * A move into a package that rolls back (`moveIntoPackage`) calls it for + * each item the transaction touched, with `reboundFrom`, so the registry + * serves the package-less address again. * * [#33851] What it answers: the registry's refusal of an object (the * object branch, #33005), and nothing else unless the caller asks @@ -2305,10 +2305,9 @@ export class ProtocolRegistryHydrationFacet { * ({@link applyObjectRegistryMutation}) meet the third state: the row * they register is stored, and each names every package's row. * - * ADR-0070 D5's `POST /api/v1/packages/:id/adopt-orphans` also hands an - * adopted object's registry owner to `Q` in the same request, but it - * rebinds EVERY package-less row of the environment, not only this - * object, so no prescription names it: each names the narrowest way out. + * `POST /api/v1/packages/:id/move-in` runs the first row's two steps for + * the items an author picks (#38150); each prescription here names the + * narrowest way out for one object. * * The code is D9.9's, not a new one: the ledger's meaning (a row bound to a * package that does not own the object) holds, and the caller's branch is diff --git a/packages/metadata-protocol/src/protocol.adopt-orphans-owner-judges.test.ts b/packages/metadata-protocol/src/protocol.adopt-orphans-owner-judges.test.ts deleted file mode 100644 index 30dc02ba219..00000000000 --- a/packages/metadata-protocol/src/protocol.adopt-orphans-owner-judges.test.ts +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * [ADR-0029 D9.9, ADR-0086 D3, #28776] The adopt-orphans door - * (`reassignOrphanedMetadata`, REST `POST /api/v1/packages/:id/adopt-orphans`) - * asks the save door's two owner judges, in the save door's order (before the - * `__c` judge #28735 added), against the TARGET package, before the first - * storage update, and refuses the adoption whole with each judge's envelope: - * - * - an active orphan `object` whose name ANOTHER package owns in the registry: - * `OBJECT_OVERLAY_PACKAGE_MISMATCH` / 422 (D9.9); - * - an active orphan `permission` set whose body `packageId` disagrees with the - * target: `VALIDATION_ERROR` / 400, `issues[0].path = 'packageId'` (D3). - * - * The D9.9 arm skips the `'sys_metadata'` sentinel owner: an orphan object is - * the sentinel's own registration, the owner the adoption hands over, so the - * judge asked unchanged would refuse EVERY object adoption (measured on a real - * CRM boot for #28776: `classifyObjectContribution` answers `mismatch` with the - * sentinel for a package-less object saved through the real door). The plain - * orphan below pins that. - * - * The namespace-prefix judge is not asked at this door (#28776's ruling), so - * nothing here pins it either way. - * - * The engine double stores rows and answers the registry's owner lookups from a - * table the test sets, the way `SchemaRegistry.getObjectOwner` answers them; the - * write-through to the registry after a rebind is spied out, since what is - * pinned is which rows the adoption moves. - */ - -import { afterEach, describe, expect, it, vi } from 'vitest'; -// [#5619] The producer's OWN write-verb dispatch decision, from -// `@objectstack/metadata-core` and NOT `@objectstack/objectql` (objectql -// depends on this package, so that import would close a cycle). -import { assertEngineFindOnePredicate, assertEngineUpdateDispatch } from '@objectstack/metadata-core'; -import { ObjectStackProtocolImplementation } from './protocol.js'; - -const TARGET = 'app.probe-target'; -const OTHER = 'app.probe-other'; - -interface Row { - id: string; - type: string; - name: string; - package_id: string | null; - organization_id: string | null; - state: string; - metadata: string; -} - -/** Rows stored package-less, and the registry's owner of each object name. */ -function makeProtocol(rows: Array>, owners: Record) { - const store = new Map(rows.map((r, i) => [`r_${i + 1}`, { - ...r, id: `r_${i + 1}`, package_id: null, organization_id: null, - }])); - const engine: any = { - async find(table: string, opts?: { where?: Record; limit?: number }) { - if (table !== 'sys_metadata') return []; - // The one shape the adoption reads: every environment row, no bound. - if (opts?.limit !== undefined || Object.keys(opts?.where ?? {}).length !== 0) { - throw new Error(`fake engine: unsupported read ${JSON.stringify(opts)}`); - } - return [...store.values()].map((r) => ({ ...r })); - }, - async findOne(table: string, opts: { where: Record }) { - assertEngineFindOnePredicate(table, opts); - return null; - }, - async update(_t: string, data: Record, opts: { where: Record }) { - assertEngineUpdateDispatch(data, opts); - const row = store.get(String(opts.where.id)); - if (!row) return { id: null }; - Object.assign(row, data); - return { id: row.id }; - }, - registry: { - getObjectOwner: (name: string) => (owners[name] ? { packageId: owners[name] } : undefined), - getArtifactItem: () => undefined, - getPackage: () => undefined, - registerObject: () => {}, - unregisterObject: () => true, - }, - }; - const protocol = new ObjectStackProtocolImplementation(engine, () => new Map(), undefined) as any; - const update = vi.spyOn(engine, 'update'); - const writeThrough = vi.spyOn(protocol, 'applyRegistryWriteThrough').mockResolvedValue(undefined); - const bindings = () => Object.fromEntries([...store.values()].map((r) => [`${r.type}/${r.name}`, r.package_id])); - return { protocol, update, writeThrough, bindings }; -} - -const object = (name: string, ...fields: string[]) => ({ - type: 'object', name, state: 'active', - metadata: JSON.stringify({ - name, label: name, sharingModel: 'private', - fields: Object.fromEntries(['title', ...fields].map((f) => [f, { type: 'text', label: f }])), - }), -}); -const permissionSet = (name: string, packageId?: string) => ({ - type: 'permission', name, state: 'active', - metadata: JSON.stringify({ name, label: name, objects: {}, ...(packageId !== undefined ? { packageId } : {}) }), -}); - -async function attempt(run: () => Promise): Promise<{ result: T | null; error: any }> { - try { - return { result: await run(), error: null }; - } catch (error) { - return { result: null, error }; - } -} - -afterEach(() => vi.restoreAllMocks()); - -describe('[ADR-0029 D9.9, #28776] the adopt door refuses an orphan object whose name another package owns', () => { - it('refused whole with OBJECT_OVERLAY_PACKAGE_MISMATCH / 422 naming the owner; no row moves, nothing is written through', async () => { - const h = makeProtocol([object('probe_clean'), object('probe_taken')], { probe_clean: 'sys_metadata', probe_taken: OTHER }); - - const { error } = await attempt(() => h.protocol.reassignOrphanedMetadata({ targetPackageId: TARGET })); - - expect(error).toBeInstanceOf(Error); - expect({ code: error.code, status: error.status }).toEqual({ code: 'OBJECT_OVERLAY_PACKAGE_MISMATCH', status: 422 }); - expect(error.message).toContain( - `Cannot layer object 'probe_taken': the overlay is bound to package '${TARGET}', but the object is owned by package '${OTHER}'.`, - ); - expect(h.update).not.toHaveBeenCalled(); - expect(h.writeThrough).not.toHaveBeenCalled(); - expect(h.bindings()).toEqual({ 'object/probe_clean': null, 'object/probe_taken': null }); - }); - - it('is asked before the `__c` judge, in the save door\'s order: a row both judges refuse answers the owner refusal', async () => { - const h = makeProtocol([object('probe_taken', 'x__c')], { probe_taken: OTHER }); - - const { error } = await attempt(() => h.protocol.reassignOrphanedMetadata({ targetPackageId: TARGET })); - - expect({ code: error?.code, status: error?.status }).toEqual({ code: 'OBJECT_OVERLAY_PACKAGE_MISMATCH', status: 422 }); - expect(h.bindings()).toEqual({ 'object/probe_taken': null }); - }); - - it('CONTROL (the sentinel pin): a plain orphan the registry owns under the `sys_metadata` sentinel is admitted and moves; so does one nobody owns', async () => { - const h = makeProtocol([object('probe_plain'), object('probe_unowned')], { probe_plain: 'sys_metadata' }); - - const res = await h.protocol.reassignOrphanedMetadata({ targetPackageId: TARGET }); - - expect(res).toMatchObject({ success: true, reassignedCount: 2, targetPackageId: TARGET }); - expect(h.bindings()).toEqual({ 'object/probe_plain': TARGET, 'object/probe_unowned': TARGET }); - }); - - it('CONTROL: an orphan object the target itself owns is admitted', async () => { - const h = makeProtocol([object('probe_mine')], { probe_mine: TARGET }); - - const res = await h.protocol.reassignOrphanedMetadata({ targetPackageId: TARGET }); - - expect(res.reassignedCount).toBe(1); - expect(h.bindings()).toEqual({ 'object/probe_mine': TARGET }); - }); -}); - -describe('[ADR-0086 D3, #28776] the adopt door refuses an orphan permission set whose body names another owner', () => { - it('refused whole with VALIDATION_ERROR / 400, `issues` at `packageId`; no row moves', async () => { - const h = makeProtocol([object('probe_clean'), permissionSet('probe_set', OTHER)], { probe_clean: 'sys_metadata' }); - - const { error } = await attempt(() => h.protocol.reassignOrphanedMetadata({ targetPackageId: TARGET })); - - expect(error).toBeInstanceOf(Error); - expect({ code: error.code, status: error.status }).toEqual({ code: 'VALIDATION_ERROR', status: 400 }); - expect(error.issues).toEqual([expect.objectContaining({ path: 'packageId', code: 'custom' })]); - expect(error.message).toContain(`Drop \`packageId\` from permission set 'probe_set'`); - expect(h.update).not.toHaveBeenCalled(); - expect(h.bindings()).toEqual({ 'object/probe_clean': null, 'permission/probe_set': null }); - }); - - it('CONTROL: a set whose body names the target, and one that names no owner, are admitted and move', async () => { - const h = makeProtocol([permissionSet('probe_named', TARGET), permissionSet('probe_bare')], {}); - - const res = await h.protocol.reassignOrphanedMetadata({ targetPackageId: TARGET }); - - expect(res.reassignedCount).toBe(2); - expect(h.bindings()).toEqual({ 'permission/probe_named': TARGET, 'permission/probe_bare': TARGET }); - }); -}); diff --git a/packages/metadata-protocol/src/protocol.adopt-orphans-platform-record.test.ts b/packages/metadata-protocol/src/protocol.adopt-orphans-platform-record.test.ts deleted file mode 100644 index 5d76871bfc9..00000000000 --- a/packages/metadata-protocol/src/protocol.adopt-orphans-platform-record.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * [#37604 item 2] `reassignOrphanedMetadata` (`POST /api/v1/packages/:id/adopt-orphans`) - * never rebinds the platform's own record: a package-less row whose body - * carries the platform's mark is the record the platform registers at every - * boot, not an orphan an author left behind. The one reader of that fact is - * `isPlatformRecordRow` (`@objectstack/metadata`), the reader the restore - * refusal and the overlay census ask. - * - * BASE (main 4e10d4bf): the adoption rebound that row to the target package, - * so the platform's record became the package's item, mark and all. - */ - -import { describe, expect, it } from 'vitest'; -import { assertEngineUpdateDispatch } from '@objectstack/metadata-core'; -import { ObjectStackProtocolImplementation } from './protocol.js'; -// Pay the source's dynamic `@objectstack/lint` load during collection, never inside a case. -import '@objectstack/lint'; - -type Row = { id: string; type: string; name: string; state: string; package_id: string | null; metadata: string }; - -/** `sys_metadata` alone, the empty filter the adoption reads with, the producer's own update dispatch. */ -function makeEngine(rows: Row[]) { - const store = new Map(rows.map((r) => [r.id, { ...r }])); - const engine = { - async find(table: string, opts?: { where?: Record; limit?: number }) { - if (table !== 'sys_metadata') return []; - if (opts?.limit !== undefined || Object.keys(opts?.where ?? {}).length !== 0) { - throw new Error(`fake engine: unsupported read ${JSON.stringify(opts)}`); - } - return [...store.values()]; - }, - async update(_table: string, data: Record, opts: { where: Record }) { - assertEngineUpdateDispatch(data, opts); - const row = store.get(String(opts.where.id)); - if (!row) return { id: null }; - Object.assign(row, data); - return { id: row.id }; - }, - }; - return { engine, store }; -} - -const skillRow = (id: string, name: string, body: Record, packageId: string | null = null): Row => ({ - id, type: 'skill', name, state: 'active', package_id: packageId, - metadata: JSON.stringify({ name, label: name, instructions: 'help', ...body }), -}); - -describe('[#37604] adopt-orphans leaves the platform\'s own record where the platform keeps it', () => { - it('the platform\'s package-less row is not rebound; the environment\'s own orphan beside it is (BASE: both rebound)', async () => { - const { engine, store } = makeEngine([ - skillRow('platform', 'helper', { _provenance: 'platform' }), - skillRow('orphan', 'notes', {}), - ]); - const protocol = new ObjectStackProtocolImplementation(engine as never); - - const res = await protocol.reassignOrphanedMetadata({ targetPackageId: 'app.base' }); - - expect(store.get('platform')!.package_id).toBeNull(); - expect(store.get('orphan')!.package_id).toBe('app.base'); - expect(res.reassigned).toEqual([{ type: 'skill', name: 'notes' }]); - expect(res.reassignedCount).toBe(1); - }); - - it('control: a package-less row whose body names a package is no platform record, and is adopted', async () => { - const { engine, store } = makeEngine([ - skillRow('named', 'helper', { _provenance: 'platform', _packageId: 'com.acme.crm' }), - ]); - const protocol = new ObjectStackProtocolImplementation(engine as never); - - const res = await protocol.reassignOrphanedMetadata({ targetPackageId: 'app.base' }); - - expect(store.get('named')!.package_id).toBe('app.base'); - expect(res.reassignedCount).toBe(1); - }); -}); 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 5a9c6f000fc..2412d80e23c 100644 --- a/packages/metadata-protocol/src/protocol.extension-field-suffix.test.ts +++ b/packages/metadata-protocol/src/protocol.extension-field-suffix.test.ts @@ -4,9 +4,11 @@ * [ADR-0146 D10, #28564] The `__c` extension-field reservation at every door * of this package — one judge (`protocol-extension-field-suffix.ts`), asked by * the save door, the restore doors, the draft promotion (`publishMetaItem` and - * the `publishPackageDrafts` batch that shares it), `duplicatePackage` and - * ([#28735]) `reassignOrphanedMetadata`, the adopt-orphans door; and - * `installPackage`, which its closed manifest already covers. + * the `publishPackageDrafts` batch that shares it), `duplicatePackage`; and + * `installPackage`, which its closed manifest already covers. (The + * adopt-orphans door [#28735] judged here too until it retired, #38150; the + * move door that replaced it runs the save door, pinned by + * `qa/dogfood/test/package-move-in.dogfood.test.ts`.) * * Maintainer, verbatim: 「扩展字段用 __c 后缀,只有 .custom 包能用。」 * @@ -604,56 +606,6 @@ describe('[ADR-0146 D10] duplicatePackage from a `.custom` pair into a plain id }); }); -// ═══════════════════════════════════════════════════════════════════════════ -// 4b. reassignOrphanedMetadata (the adopt-orphans door), judged against the target id -// ═══════════════════════════════════════════════════════════════════════════ - -describe('[ADR-0146 D10, #28735] the adopt-orphans door judges each object row it rebinds against the target', () => { - /** Package-less active objects through the real save door (not judged: no package), then the write-through spied. */ - async function orphans(h: Harness, ...bodies: Array>) { - for (const item of bodies) await h.protocol.saveMetaItem({ type: 'object', name: item.name, item }); - h.saveDoor.mockClear(); - return vi.spyOn(h.protocol, 'applyRegistryWriteThrough'); - } - - it('a package-less object with `x__c` adopted into a plain package is refused with case (a); nothing moves, nothing registers', async () => { - const h = makeProtocol(); - const writeThrough = await orphans(h, obj('probe_env', 'Env', 'x__c')); - const update = vi.spyOn(h.engine, 'update'); - - const { error } = await attempt(() => h.protocol.reassignOrphanedMetadata({ targetPackageId: BOUND })); - - expectReservedRefusal(error, 'x__c', 'probe_env', BOUND, 'objects.probe_env.fields.x__c'); - expect(update).not.toHaveBeenCalled(); - expect(writeThrough).not.toHaveBeenCalled(); - expect(storedObjects(h)).toEqual([{ row: 'probe_env', state: 'active', binding: null, fields: ['title', 'x__c'] }]); - }); - - it('a mixed adoption (one clean row, one `x__c` row) into a plain package is refused whole: the clean row does not move either', async () => { - const h = makeProtocol(); - const writeThrough = await orphans(h, obj('probe_clean', 'Clean'), obj('probe_env', 'Env', 'x__c')); - - const { error } = await attempt(() => h.protocol.reassignOrphanedMetadata({ targetPackageId: BOUND })); - - expectReservedRefusal(error, 'x__c', 'probe_env', BOUND, 'objects.probe_env.fields.x__c'); - expect(writeThrough).not.toHaveBeenCalled(); - expect(storedObjects(h).map((r) => [r.row, r.binding])).toEqual([['probe_clean', null], ['probe_env', null]]); - }); - - it('CONTROL: the same `x__c` row adopted into the base\'s `.custom` pair is admitted and moves; a clean row into the plain package too', async () => { - const pairH = makeProtocol(); - await orphans(pairH, obj('probe_env', 'Env', 'x__c')); - const res = await pairH.protocol.reassignOrphanedMetadata({ targetPackageId: PAIR }); - expect(res).toMatchObject({ success: true, reassignedCount: 1, targetPackageId: PAIR }); - expect(storedObjects(pairH)).toEqual([{ row: 'probe_env', state: 'active', binding: PAIR, fields: ['title', 'x__c'] }]); - - const plainH = makeProtocol(); - await orphans(plainH, obj('probe_clean', 'Clean', 'region')); - expect((await plainH.protocol.reassignOrphanedMetadata({ targetPackageId: BOUND })).reassignedCount).toBe(1); - expect(storedObjects(plainH)).toEqual([{ row: 'probe_clean', state: 'active', binding: BOUND, fields: ['title', 'region'] }]); - }); -}); - // ═══════════════════════════════════════════════════════════════════════════ // 5. installPackage — covered by its closed manifest // ═══════════════════════════════════════════════════════════════════════════ diff --git a/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts b/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts index d3ed3733835..82aa729b9d2 100644 --- a/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts +++ b/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts @@ -38,7 +38,8 @@ // The trace, measured on `origin/main` — all four routes fold at the producer // --------------------------------------------------------------------------- // `applyObjectRegistryMutation` has exactly ONE caller -// (`applyRegistryWriteThrough`), which has exactly TEN: +// (`applyRegistryWriteThrough`), which has exactly NINE (the orphan +// adoption's, `reassignOrphanedMetadata`, retired with its door, #38150): // // 1. `saveMetaItem` passes `singularTypeForRepo`, and the method // already ran `canonicalizeMetaRequestType`. @@ -60,30 +61,22 @@ // so this caller folds rather than trusting // the wire, even though every in-tree // publisher emits the already-folded singular. -// 6. `reassignOrphanedMetadata` (#23198) folds the STORED row type at the -// call site through `canonicalMetaType`, and -// writes through only a row that folds to -// `'view'` or [#23646] `'object'` — the latter -// once `releaseAdoptedObjectOwner` has handed -// the adopted row the name. A legacy row stored -// as `'objects'` therefore reaches -// `applyObjectRegistryMutation` as `'object'`. -// 7. `restoreArtifactRegistryView` (#23297) folds at the call site through +// 6. `restoreArtifactRegistryView` (#23297) folds at the call site through // `canonicalMetaType`, the key it also reads // the stored rows under, and registers a row // still stored after a delete (another // package's, or the package-less one), so the // registry keeps serving what the store serves. -// 8. `healOldShapeFormRowRemovals` (ADR-0159 D5) passes the literal +// 7. `healOldShapeFormRowRemovals` (ADR-0159 D5) passes the literal // `'view'`: it heals the old-shape `view` row a // `form` save, publish or delete re-saved, so no // stored spelling reaches it. -// 9. `restoreAfterRollback` (#38150) passes the item's type as the move-in +// 8. `restoreAfterRollback` (#38150) passes the item's type as the move-in // door folded it through `canonicalMetaType` // when it judged the selection: it puts each // moved item back at its package-less address // after a rolled-back move. -// 10. `undoLanded` (#38150) passes the same folded type: it writes back +// 9. `undoLanded` (#38150) passes the same folded type: it writes back // through each loose row a refused move put // back with no transaction to cover it. // @@ -561,29 +554,6 @@ describe('[#8862] every object registry write-through registers under the singul expect.objectContaining({ type: 'objects' }), ); }); - - // [#23646] The orphaned object used to be rebound in storage only, and - // this case pinned that (`registeredObjects` empty). It now pins the fold - // the adoption's object limb applies: a stored `objects` row registers - // under `object`, never under the plural it is stored as. - it('the orphan adoption writes a stored `views` row through as `view`, and a stored `objects` row as `object`', async () => { - // An unscoped kernel: the only one on which a view row is written through. - const h = makeStubEngine(); - const protocol = new ObjectStackProtocolImplementation(h.engine, () => new Map()) as any; - await seedRowVerbatim(protocol, { type: 'objects', name: 'ticket', body: objectBody('ticket'), state: 'active' }); - await seedRowVerbatim(protocol, { - type: 'views', name: 'ticket_grid', state: 'active', - body: { name: 'ticket_grid', label: 'Tickets', type: 'grid', data: { provider: 'object', object: 'ticket' } }, - }); - h.registeredItems.length = 0; - - const res = await protocol.reassignOrphanedMetadata({ targetPackageId: PKG }); - - expect(res.reassigned).toEqual([{ type: 'objects', name: 'ticket' }, { type: 'views', name: 'ticket_grid' }]); - expect(h.registeredItems).toEqual([{ type: 'object', name: 'ticket' }, { type: 'view', name: 'ticket_grid' }]); - expect(h.registeredItems).not.toContainEqual(expect.objectContaining({ type: 'objects' })); - expect(h.registeredObjects).toEqual(['ticket']); - }); }); // ═══════════════════════════════════════════════════════════════════════════ @@ -618,9 +588,9 @@ describe('[#8862] the `applyRegistryWriteThrough` caller set stays closed', () = const sources = [source, ...SPLIT_MODULES.map((file) => readFileSync(fileURLToPath(new URL(`./${file}`, import.meta.url)), 'utf8'))]; const sitesOf = (pattern: RegExp) => sources.flatMap((text) => text.match(pattern) ?? []); - it('has exactly ten call sites, all traced in this file’s header', () => { + it('has exactly nine call sites, all traced in this file’s header', () => { const callSites = sitesOf(/\b(?:this|host)\.applyRegistryWriteThrough\(/g); - expect(callSites).toHaveLength(10); + expect(callSites).toHaveLength(9); }); it('`applyObjectRegistryMutation` is reached only through the write-through', () => { 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 31669401113..9bdbdc611df 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 @@ -289,19 +289,26 @@ describe('platform-store calls carry the explicit system opt-in (#21911)', () => await expectSystemOptIn(calls, 'persistPackageCommitRow', () => protocol.persistPackageCommitRow({ id: 'c_1' })); }); - it('the package verbs: reassign orphans, duplicate, uninstall', async () => { + it('the package verbs: move loose items in (its judging read), duplicate, uninstall', async () => { const { engine, calls } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); await protocol.saveMetaItem({ type: 'view', name: 'orphan_grid', item: viewBody('orphan_grid'), mode: 'publish', }); + await protocol.saveMetaItem({ + type: 'view', name: 'pin_grid', item: viewBody('pin_grid'), packageId: 'app.pin', mode: 'publish', + }); - const reassignCalls = await expectSystemOptIn(calls, 'reassignOrphanedMetadata', async () => { - const res = await protocol.reassignOrphanedMetadata({ targetPackageId: 'app.pin' }); - expect(res.reassignedCount).toBe(1); + // [#38150] The adopt-orphans door retired; the move door's phase 0 reads + // the environment's rows with the same opt-in (a dry run writes nothing). + const moveCalls = await expectSystemOptIn(calls, 'moveIntoPackage', async () => { + await protocol.moveIntoPackage({ + targetPackageId: 'app.pin', items: [{ type: 'view', name: 'orphan_grid' }], dryRun: true, + }); }); - expect(reassignCalls.map((c) => c.verb)).toEqual(['find', 'update']); + expect(moveCalls.map((c) => c.verb)).toContain('find'); + expect(moveCalls.map((c) => c.verb)).not.toContain('update'); await expectSystemOptIn(calls, 'duplicatePackage', async () => { await protocol.duplicatePackage({ diff --git a/packages/metadata-protocol/src/protocol.reassign-orphans-durability.test.ts b/packages/metadata-protocol/src/protocol.reassign-orphans-durability.test.ts deleted file mode 100644 index 989556cabe5..00000000000 --- a/packages/metadata-protocol/src/protocol.reassign-orphans-durability.test.ts +++ /dev/null @@ -1,247 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * [#12981 batch 7] A refused orphan rebind in `reassignOrphanedMetadata` must - * not be silent. - * - * ADR-0070 D5's adoption loop walked every package-less `sys_metadata` row and - * rebound it to a target base. Its `catch` was bare: - * - * } catch { - * /* skip a row that fails to update; report only what moved *\/ - * } - * - * and the return line below it reports `success: reassigned.length > 0`. Put - * together, an adoption in which 99 of 100 orphans were REFUSED answered - * `{ success: true, reassignedCount: 1 }` — a response byte-identical in shape - * to a healthy run that had exactly one orphan to move. The 99 stayed orphans, - * nothing retried them, and no line anywhere recorded that they had been tried. - * That is the AGENTS.md durability shape exactly: the system keeps looking - * normal while something it claims to have persisted did not land. - * - * ## What this file pins, and what it deliberately does NOT - * - * ONLY the silence changes. The loop must still skip the refused row and adopt - * the rest — aborting the adoption over one unwritable row would strand the - * rows that CAN move — and the response shape is untouched, because adding a - * `failedCount` is a contract change this card does not carry. Both halves are - * asserted below rather than assumed. - * - * ## The level, stated so it can be argued with - * - * `console.error`, not `console.warn`, and not by default: `console.warn` is - * this file's overwhelming idiom (51 sites) and `clientFacingRowFailureText` - * records the discriminator in prose — it chose `warn` "deliberately — nothing - * claimed to be persisted was silently dropped (the row reports - * `success: false` and the counters reconcile)". Here NEITHER holds. The - * matching precedent is in this same file: `recordPackageCommit` already - * answers `console.error` for a refused `sys_metadata_commit` write under a - * publish that reports success. - * - * ## ONE line, not one per row - * - * AGENTS.md → "Degradation log levels" requires the report be stated once, at - * the first occurrence, not once per failed write — and a `sys_metadata` write - * that is refused is refused for every row, so the per-row spelling would print - * one line per orphan in the environment. The count is pinned, not just the - * presence. - * - * ⚠️ Two cases below are CONTROLS, not pins: they assert an ABSENCE against a - * seam that logged nothing at all before this repair, so they stay green in - * both directions by construction and are not evidence in an ablation. - */ - -import { describe, it, expect, vi, afterEach } from 'vitest'; -// [#5619] The producer's OWN write-verb dispatch decision, so this double -// cannot accept an `update` shape ObjectQL refuses. From -// `@objectstack/metadata-core` and NOT `@objectstack/objectql` — objectql -// depends on THIS package, so that import would close a cycle turbo rejects. -import { assertEngineUpdateDispatch } from '@objectstack/metadata-core'; -import { ObjectStackProtocolImplementation } from './protocol.js'; - -interface MetaRow { - id: string; - type: string; - name: string; - package_id: string | null; -} - -/** - * Engine double over `sys_metadata` with a per-id refusal injector on `update`. - * - * The injection is keyed by ROW ID rather than being a global switch, because - * the defect's dangerous case is the PARTIAL one: an adoption where some rows - * move and some do not is the run that answers `success: true` while leaving - * orphans behind. A double that could only fail everything could not express - * it. - */ -function makeEngine(rows: MetaRow[]) { - const store = new Map(rows.map((r) => [r.id, { ...r }])); - const refuse = new Set(); - let updateAttempts = 0; - - const engine = { - async find(table: string, opts?: { where?: Record; limit?: number }) { - if (table !== 'sys_metadata') return []; - // This double implements ONE `where` shape — the empty filter the - // producer passes (ADR-0131 D6/D7: every row is the environment's, - // so every orphan is adopted) — and NO bound, and REFUSES - // anything else rather than answering it silently. Paging belongs - // to tests that do not exist yet. A double looser than the engine - // it stands in for converts a green suite into no suite at all - // (#4434) — and the reason to refuse rather than approximate is - // that the approximation is invisible on the day the producer - // starts using the shape. - if (opts?.limit !== undefined) { - throw new Error('fake engine: unsupported `limit` — this double holds no bound'); - } - const where = opts?.where ?? {}; - const keys = Object.keys(where); - if (keys.length !== 0) { - throw new Error(`fake engine: unsupported where ${JSON.stringify(where)}`); - } - // The store IS the answer. - return [...store.values()]; - }, - async update(_table: string, data: Record, opts: { where: Record }) { - assertEngineUpdateDispatch(data, opts); - updateAttempts += 1; - const id = String(opts.where.id); - if (refuse.has(id)) throw new Error(`write refused for ${id}: permission denied on sys_metadata`); - const row = store.get(id); - if (!row) return { id: null }; - Object.assign(row, data); - return { id }; - }, - }; - - return { - engine, - store, - refuseIds: (...ids: string[]) => ids.forEach((i) => refuse.add(i)), - updateAttempts: () => updateAttempts, - }; -} - -const orphan = (id: string): MetaRow => ({ - id, - type: 'object', - name: `obj_${id}`, - package_id: null, -}); - -/** The one sentence fragment an operator greps for. */ -const HEADLINE = 'orphaned metadata row(s) were NOT rebound'; - -afterEach(() => { - vi.restoreAllMocks(); -}); - -function spyConsole() { - return { - error: vi.spyOn(console, 'error').mockImplementation(() => {}), - warn: vi.spyOn(console, 'warn').mockImplementation(() => {}), - }; -} - -describe('reassignOrphanedMetadata: a refused rebind is reported (#12981)', () => { - // ⚠️ CONTROL, not a pin. Before the repair this seam logged nothing at any - // level, so "a healthy adoption says nothing" was already true — it stays - // green in BOTH directions and is not ablation evidence. It is here so the - // pins below cannot pass on a seam that reports unconditionally. - it('CONTROL: an adoption in which every row rebinds reports nothing', async () => { - const spy = spyConsole(); - const stub = makeEngine([orphan('a'), orphan('b')]); - const protocol = new ObjectStackProtocolImplementation(stub.engine as never); - - const res = await protocol.reassignOrphanedMetadata({ targetPackageId: 'app.base' }); - - expect(res.reassignedCount).toBe(2); - expect(res.success).toBe(true); - expect(stub.updateAttempts()).toBe(2); - expect(spy.error).not.toHaveBeenCalled(); - expect(spy.warn).not.toHaveBeenCalled(); - }); - - it('reports a PARTIAL adoption — the run that still answers success: true', async () => { - const spy = spyConsole(); - const stub = makeEngine([orphan('a'), orphan('b'), orphan('c')]); - stub.refuseIds('b', 'c'); - const protocol = new ObjectStackProtocolImplementation(stub.engine as never); - - const res = await protocol.reassignOrphanedMetadata({ targetPackageId: 'app.base' }); - - // Proof the writes were really attempted and really threw — otherwise - // every assertion below is about an adoption that never reached the seam. - expect(stub.updateAttempts()).toBe(3); - expect(stub.store.get('b')!.package_id).toBeNull(); - expect(stub.store.get('c')!.package_id).toBeNull(); - - // ⛔ The response is UNCHANGED: this is the shape that reads healthy. - expect(res.success).toBe(true); - expect(res.reassignedCount).toBe(1); - expect(res.reassigned).toEqual([{ type: 'object', name: 'obj_a' }]); - - // …and it is no longer the only thing that happened. - expect(spy.error).toHaveBeenCalledTimes(1); - const line = String(spy.error.mock.calls[0][0]); - expect(line).toContain(HEADLINE); - expect(line).toContain('2 of 3'); - expect(line).toContain('app.base'); - // The consequence and the fix, which AGENTS.md requires of this level. - expect(line).toContain('STILL orphans'); - expect(line).toContain('Fix: restore write access'); - // The driver's own sentence, so the operator is not left guessing why. - expect(line).toContain('permission denied on sys_metadata'); - }); - - it('reports a TOTAL refusal, where the response already says success: false', async () => { - const spy = spyConsole(); - const stub = makeEngine([orphan('a'), orphan('b')]); - stub.refuseIds('a', 'b'); - const protocol = new ObjectStackProtocolImplementation(stub.engine as never); - - const res = await protocol.reassignOrphanedMetadata({ targetPackageId: 'app.base' }); - - expect(res.success).toBe(false); - expect(res.reassignedCount).toBe(0); - expect(spy.error).toHaveBeenCalledTimes(1); - expect(String(spy.error.mock.calls[0][0])).toContain('2 of 2'); - }); - - it('states the degradation ONCE, not once per refused row', async () => { - const spy = spyConsole(); - const ids = ['a', 'b', 'c', 'd', 'e', 'f']; - const stub = makeEngine(ids.map(orphan)); - stub.refuseIds(...ids); - const protocol = new ObjectStackProtocolImplementation(stub.engine as never); - - await protocol.reassignOrphanedMetadata({ targetPackageId: 'app.base' }); - - // Six refused writes, ONE operator-facing line — AGENTS.md's "say it - // once, at the first degradation, not once per failed write". - expect(stub.updateAttempts()).toBe(6); - expect(spy.error).toHaveBeenCalledTimes(1); - expect(String(spy.error.mock.calls[0][0])).toContain('6 of 6'); - }); - - // ⚠️ CONTROL, not a pin — an INVARIANCE assertion. The pre-repair code - // returns exactly this too, so it stays green in both directions. It is - // here because the repair would be wrong if it changed control flow. - it('CONTROL: a refused row does not abort the rows that can still move', async () => { - spyConsole(); - const stub = makeEngine([orphan('a'), orphan('b'), orphan('c')]); - stub.refuseIds('a'); - const protocol = new ObjectStackProtocolImplementation(stub.engine as never); - - const res = await protocol.reassignOrphanedMetadata({ targetPackageId: 'app.base' }); - - expect(res.reassignedCount).toBe(2); - expect(stub.store.get('b')!.package_id).toBe('app.base'); - expect(stub.store.get('c')!.package_id).toBe('app.base'); - // The response shape is untouched: no `failedCount` was added. - expect(Object.keys(res).sort()).toEqual( - ['reassigned', 'reassignedCount', 'success', 'targetPackageId'].sort(), - ); - }); -}); diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index a050b6f169d..ab454a202fb 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -316,11 +316,6 @@ import type { WrittenPackageScope, PackagelessWriteOperation, } from './protocol-packaged-base-refusal.js'; -// [ADR-0146 D10, #28564] The `__c` extension-field reservation's one judge. -import { - extensionFieldSuffixRefusalError, - judgeExtensionFieldSuffix, -} from './protocol-extension-field-suffix.js'; // [#25467 cut 14] The publish batch's seed apply and its own pending declarations. import { applySeedBodiesOnHost, collectBatchPendingDeclarations } from './protocol-publish-batch.js'; // [#25467 cut 15] The artifact registry's lookups: an item's artifact, the packages that ship a type, and the lock's artifact layer. @@ -330,7 +325,7 @@ import { // [#25467 cut 16] The stored-overlay row reads: a type's active rows, their parsed entries, the names with a row of their own, and one item's rows. import { namesWithOwnStoredRow, readActiveOverlayRows, readItemActiveRows, storedOverlayEntries } from './protocol-stored-overlay-reads.js'; // [#25467 cut 17] The object-owner verdicts: which contributor kind a stored object row registers as, and handing an adopted object's name to its rebound row. -import { classifyObjectContribution, releaseAdoptedObjectOwner } from './protocol-object-owner.js'; +import { classifyObjectContribution } from './protocol-object-owner.js'; // [#25467 cut 18] The flow save's retired-spelling replay verdict (#23903 ruling B′): does a save newly introduce a retired spelling no stored row carries. import { flowSaveReplaysRetired } from './protocol-flow-save-replay.js'; // [#25467 cut 19] A package write's validation scope: the written package and its declared dependency closure, from the registry. @@ -1354,7 +1349,6 @@ export class ObjectStackProtocolImplementation implements registryAllowsOverlay: (...a) => ObjectStackProtocolImplementation.registryAllowsOverlay(...a), registryMemberServedAt: (...a) => protocol.registryMemberServedAt(...a), registryTakesStoredRows: (...a) => protocol.registryTakesStoredRows(...a), - releaseAdoptedObjectOwner: (...a) => protocol.releaseAdoptedObjectOwner(...a), reportPageRequiresAbsentAtLoad: (...a) => protocol.reportPageRequiresAbsentAtLoad(...a), reportSealedOverlayRows: (...a) => protocol.reportSealedOverlayRows(...a), resolveAppPackageIdKey: (...a) => protocol.resolveAppPackageIdKey(...a), @@ -10581,168 +10575,10 @@ export class ObjectStackProtocolImplementation implements return rollBackUnmanagedImport.call(host, cause, context); } - /** - * ADR-0070 D5 — adopt orphaned (package-less) metadata into a base. The - * pre-package-first stopgaps left runtime-authored items with - * `package_id = null` (or the `sys_metadata` sentinel). This bulk-rebinds - * every such orphan to `targetPackageId` so the env converges on the - * package-first model and the "Local / Custom" migration scope can be - * retired. Owned rows (already bound to a real package) are left untouched. - * - * ## [#23198] An overlay of an artifact item is not an orphan - * - * ADR-0070's kernel section: "Overlays of artifact items (`intent = - * override-artifact`, `allowOrgOverride`) are **unchanged** — they keep - * their binding to the packaged item they customise." An orphan is a - * runtime-created item. So a package-less row for which - * {@link isArtifactBacked} holds — the predicate {@link saveMetaItem} sets - * `intent: 'override-artifact'` by — is not adopted, and it stays as - * stored. Adopted, a package-less overlay of a packaged view container - * expanded under its own name in the base, so the packaged view lost the - * customisation and two views were added beside it; an overlay of one - * packaged view was served twice under its name. Both took effect at the - * next restart, and the registry kept the old answer until then. - * - * Each view row it does rebind goes through the write-through, with the - * binding it left ({@link applyRegistryWriteThrough}, `reboundFrom`), so - * the registry follows the row at once: a view container's expansions are - * reconciled for the new binding, and the record of the old one moves - * with it ({@link reconcileViewExpansions}). - * - * ## [#23646] …and so does each object row it rebinds - * - * An object row used to be rebound in storage only. The registry kept the - * owner the package-less row had registered (the `'sys_metadata'` - * sentinel) and the pre-adoption definition until the next restart, and - * every save of the object naming the target package answered success - * without going live: the write-through's `own` claim under the target met - * the registry's single-owner rule (ADR-0029 D3) and landed in - * {@link applyObjectRegistryMutation}'s best-effort warn. Measured over - * `POST /api/v1/packages/:id/adopt-orphans` on a booted CRM example: the - * data plane refused the saved object's new field with `400 INVALID_FIELD`. - * So the sentinel's contribution leaves the registry first - * ({@link releaseAdoptedObjectOwner}), and the row registers at its new - * binding through the same write-through, in the same request; the next - * boot registers the same owner. Only an ACTIVE object row is registered, - * the rows the boot registers: an adopted draft is rebound in storage - * only, because a draft never reaches the runtime. Rows of other types are - * rebound in storage only, as before. - * - * ## [#23690] The active-only rule holds for a view too - * - * The view limb admitted a row by its type alone, so an adopted - * package-less DRAFT view was registered as live (its draft body, at the - * new binding) until the next boot dropped it again, against the - * write-through's own rule that a draft never leaks into the runtime - * (ADR-0048). One gate before both limbs now admits active rows only. - * - * ## [ADR-0146 D10, #28735] The `__c` reservation, judged against the target - * - * A package-unbound row is not judged by the reservation (it is the - * environment's own), so the save door admits an object carrying `x__c` - * into no package. Rebinding that row makes `x__c` a field the TARGET - * package declares on its own object, which case (a) refuses outside a - * `.custom` pair. So every active `object` row this adoption would rebind - * is judged against the target id with the save door's judge - * ({@link judgeExtensionFieldSuffix}) before the first storage update, and - * any refused field refuses the adoption whole, with the save door's - * envelope ({@link extensionFieldSuffixRefusalError}, `VALIDATION_ERROR` / - * 400, `issues[]` locating each field): no row moves and nothing is - * written through to the registry. An adopted draft is judged when it is - * promoted (the promotion asks the same judge against its binding). - * - * ## [ADR-0029 D9.9, ADR-0086 D3, #28776] …and the owner judges, first - * - * The save door asks two owner judges before the suffix judge, and so - * does this adoption, in the same order and with their own envelopes, - * before the first storage update: any refusal refuses the adoption whole. - * - * - An active `object` row whose name ANOTHER package owns in the - * registry ({@link classifyObjectContribution}'s `mismatch`) is refused - * with {@link overlayPackageMismatchError} - * (`OBJECT_OVERLAY_PACKAGE_MISMATCH` / 422). Adopted, it was rebound in - * storage while the registry kept the other owner - * ({@link releaseAdoptedObjectOwner} answers `false`): two rows for one - * object, the shape D9.9 exists to refuse. ⛔ Not the `'sys_metadata'` - * sentinel owner: an orphan object IS the sentinel's registration, the - * owner this adoption hands over, so asked unchanged the judge would - * refuse every object adoption. - * - An active `permission` row whose body `packageId` disagrees with the - * target is refused with {@link permissionSetOwnerBindingRefusal} - * (`VALIDATION_ERROR` / 400, the save door's words). - * - * The namespace-prefix judge is not asked here ({@link moveIntoPackage}, this door's replacement, asks it); a draft meets both owner judges when promoted. - * - * ## [#37604] The platform's own record is no orphan - * - * A package-less row whose body carries the platform's mark is the record - * the platform registers at every boot (`isPlatformRecordRow`, - * `@objectstack/metadata`), kept beside a package's item of the name in a - * slot of its own. It is left as it is stored, as an artifact-backed - * overlay is: rebound, it would become the target's item, mark and all. - */ - async reassignOrphanedMetadata(request: { - targetPackageId: string; - actor?: string; - }): Promise<{ - success: boolean; - reassignedCount: number; - reassigned: Array<{ type: string; name: string }>; - targetPackageId: string; - }> { - // [#29985 codemod] The body moved to `protocol-package-commits.ts`; it reaches this class through `protocol-host.ts`. - return ProtocolPackageCommitsFacet.reassignOrphanedMetadata(protocolHost(this), request); - } - async moveIntoPackage(request: MoveIntoPackageRequest) { return ProtocolPackageMoveInFacet.moveIntoPackage(protocolHost(this), request); } - /** - * [#23646, ADR-0070 D5] Hand an adopted object's registry name over to its - * rebound row: answers whether {@link reassignOrphanedMetadata} registers - * the row at its new binding through {@link applyRegistryWriteThrough}. - * - * An object has ONE owner per name in the registry (ADR-0029 D3), and a - * package-less row registers as its owner under the `'sys_metadata'` - * sentinel (the save's write-through and the boot's hydration both key a - * package-less row so). A registration at the new binding while that owner - * stands is a second package's `own` claim, which `registerObject` refuses. - * So the sentinel's contribution leaves first, through - * `SchemaRegistry.unregisterObject` — the verb - * {@link restoreArtifactRegistryView} already hands an object's name to a - * remaining row with — and the write-through then registers the row as a - * save of it does. Both run before the adoption answers, with no `await` - * between them, so no request sees the name unowned. No new registry verb - * exists for this, and none is needed. - * - * | the name's registered owner | answer | - * |:--|:--| - * | the sentinel (the adopted row's own registration) | unregistered; `true` | - * | none | `true`: the row registers as the next boot would register it | - * | another package's row | `false`: the adopted row never held the name; the registry keeps that owner, as before, and the next boot judges both rows | - * - * A code-shipped object is never adopted ({@link isArtifactBacked} filters - * it out first), so a packaged owner does not reach this table. - * - * `unregisterObject` refuses an object another package extends (its - * ADR-0029 guard). The registry then keeps the sentinel's owner and the - * pre-adoption definition until the next restart while storage says - * otherwise, which is why that refusal is logged at `error`, once per - * object, with the consequence and the remedy. - * - * `false` for a registry with no object half (a metadata-only double) and - * for a body with no name, which register nothing. - */ - private releaseAdoptedObjectOwner(name: string, item: unknown, targetPackageId: string): boolean { - // [#25467 cut 17] The body moved to `protocol-object-owner.ts` (see `ObjectOwnerHost`). - const readEngine = () => this.engine; - const host: ThisParameterType = { - get engine() { return readEngine(); }, - }; - return releaseAdoptedObjectOwner.call(host, name, item, targetPackageId); - } - // ───────────────────────────────────────────────────────────────────── // ADR-0067 — package-scoped commit history & rollback // ───────────────────────────────────────────────────────────────────── 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 5255d53cbb6..150d853d9ec 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 @@ -58,20 +58,17 @@ * name. `protocol.view-expansion-reconcile-call-sites.test.ts` pins that no * write reaches the registry around the reconcile. * - * ## [#23198] The orphan adoption + * ## [#23198] A rebind * - * `POST /packages/:id/adopt-orphans` (`reassignOrphanedMetadata`) rebound - * every package-less row into the base, the overlays of packaged items - * included, and touched no registry entry. Measured over the real - * `SchemaRegistry`: after a restart, an adopted overlay of the packaged - * container expanded under its own name in the base (the packaged - * `showcase_task.default` served again, `showcase_task.showcase_task` added), - * and an adopted overlay of one packaged view was listed twice under its name. - * ADR-0070 keeps an overlay of an artifact item bound to the item it - * customises, so the third block pins that the adoption leaves both overlays as - * they are, in the same process and after a restart (`boot` over the same - * rows, then `loadMetaFromDb`), and that a true orphan is adopted with the - * registry following its row at once, its record moved to the new binding. + * A write that moves a row to another binding (`reboundFrom`) moves the row's + * record of registered expansions with it. The orphan adoption + * (`POST /packages/:id/adopt-orphans`, `reassignOrphanedMetadata`) was the + * first caller; it retired with #38150, and the move door's undo after a + * rolled-back move (`moveIntoPackage`) rebinds the same way. The third block + * pins the record's move on the write-through itself. (The adoption's own + * cases — that it left an overlay of a packaged item where it was — went with + * the door: the move door refuses such an overlay `NOT_LOOSE`, pinned in + * `qa/dogfood/test/package-move-in.dogfood.test.ts`.) */ // Pays the lint root's first load at collection, never inside a clocked case. import './lint-root-preload.testkit.js'; @@ -652,104 +649,27 @@ describe('[#23198] after every write the registry holds the expansion set the st }); const BASE = 'app.home'; -/** What the adopted overlay of the container expanded to, under its own name in the base. */ -const OWN_NAME_VIEW = `${OBJ}.${OBJ}`; -const RT_DEFAULT = `${RT_OBJ}.default`; const RT_OPEN = `${RT_OBJ}.open`; const RT_CLOSED = `${RT_OBJ}.closed`; -/** The package binding of each active row stored under `name`. */ -const storedBindings = (rows: Map, name: string) => - [...rows.values()].filter((r) => r.name === name && r.state === 'active').map((r) => r.package_id ?? null); - -/** A restart: the package registered again, then the stored rows hydrated, over the rows the last process wrote. */ -async function restart(rows: Map) { - const next = boot({ rows }); - expect(await next.protocol.loadMetaFromDb()).toMatchObject({ errors: 0 }); - return next; -} - -/** The record list's View Config Save on one packaged view: read it, relabel it, save a draft, publish. */ -async function publishViewOverlay(protocol: ObjectStackProtocolImplementation, name: string, label: string) { - const read: any = await protocol.getMetaItem({ type: 'view', name }); - const view = stripInternal(read.item) as Record; - view.label = label; - if (view.config) view.config = { ...view.config, label }; - expect(await protocol.saveMetaItem({ type: 'view', name, item: view, mode: 'draft' })).toMatchObject({ success: true }); - expect(await protocol.publishMetaItem({ type: 'view', name })).toMatchObject({ success: true }); -} - -describe('[#23198] the orphan adoption rebinds runtime-created items only, and the registry follows the row at once', () => { - it('reading A: a package-less overlay of the packaged container is not adopted, and keeps serving its customisation', async () => { - const { protocol, rows } = boot(); - await publishContainerOverlay(protocol, xEdit('All Tasks (X)', true)); - - const adopted: any = await protocol.reassignOrphanedMetadata({ targetPackageId: BASE }); - - expect(adopted).toMatchObject({ success: false, reassignedCount: 0, reassigned: [] }); - expect(storedBindings(rows, OBJ)).toEqual([null]); - expect(await doors(protocol, DEFAULT_VIEW)).toEqual(servedOnEveryDoor('All Tasks (X)', 6)); - expect(await doors(protocol, OWN_NAME_VIEW)).toEqual(NOT_SERVED); - - const next = await restart(rows); - expect(await doors(next.protocol, DEFAULT_VIEW)).toEqual(servedOnEveryDoor('All Tasks (X)', 6)); - expect(await doors(next.protocol, OWN_NAME_VIEW)).toEqual(NOT_SERVED); - }); - - it("reading B: a package-less overlay of one packaged view (the record list's View Config Save) is not adopted, and is served once", async () => { - const { protocol, rows } = boot(); - await publishViewOverlay(protocol, IN_PROGRESS_VIEW, 'In Progress (X)'); - - const adopted: any = await protocol.reassignOrphanedMetadata({ targetPackageId: BASE }); - - expect(adopted).toMatchObject({ success: false, reassignedCount: 0, reassigned: [] }); - expect(storedBindings(rows, IN_PROGRESS_VIEW)).toEqual([null]); - expect(await doors(protocol, IN_PROGRESS_VIEW)).toEqual(servedOnEveryDoor('In Progress (X)', 2)); - - const next = await restart(rows); - expect(await doors(next.protocol, IN_PROGRESS_VIEW)).toEqual(servedOnEveryDoor('In Progress (X)', 2)); - }); - - it('control D: a true orphan beside them is adopted, and the registry serves it from the base before any read', async () => { - const { protocol, registry, rows } = boot(); - await publishContainerOverlay(protocol, xEdit('All Tasks (X)', true)); - expect(await protocol.saveMetaItem({ - type: 'view', name: RT_OBJ, item: rtContainer({ open: rtMember('Open') }), - })).toMatchObject({ success: true }); - expect(registry.bare('view', RT_OPEN)?._packageId).toBeUndefined(); - - const adopted: any = await protocol.reassignOrphanedMetadata({ targetPackageId: BASE }); - - expect(adopted).toMatchObject({ success: true, reassignedCount: 1, reassigned: [{ type: 'view', name: RT_OBJ }] }); - expect(storedBindings(rows, RT_OBJ)).toEqual([BASE]); - expect(storedBindings(rows, OBJ)).toEqual([null]); - // No read in between: the container and each view it expands to are the base's. - for (const name of [RT_OBJ, RT_DEFAULT, RT_OPEN]) { - expect(registry.bare('view', name)?._packageId, name).toBe(BASE); - } - expect(await doors(protocol, RT_OPEN, RT_OBJ)).toEqual(servedOnEveryDoor('Open', 1)); - expect(await doors(protocol, RT_DEFAULT, RT_OBJ)).toEqual(servedOnEveryDoor('All Tickets', 2)); - expect(await doors(protocol, DEFAULT_VIEW)).toEqual(servedOnEveryDoor('All Tasks (X)', 6)); - - // After a restart, the views it expands to are the base's too. (The - // boot hydrates the container's own body as stored, without the - // binding stamped on it, as it hydrates every bound row.) - const next = await restart(rows); - for (const name of [RT_DEFAULT, RT_OPEN]) { - expect(next.registry.bare('view', name)?._packageId, name).toBe(BASE); - } - expect(await doors(next.protocol, RT_OPEN, RT_OBJ)).toEqual(servedOnEveryDoor('Open', 1)); - expect(await doors(next.protocol, DEFAULT_VIEW)).toEqual(servedOnEveryDoor('All Tasks (X)', 6)); - }); - +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(); expect(await protocol.saveMetaItem({ type: 'view', name: RT_OBJ, item: rtContainer({ open: rtMember('Open'), closed: rtMember('Closed') }), })).toMatchObject({ success: true }); - await protocol.reassignOrphanedMetadata({ targetPackageId: BASE }); + // The rebind as a door makes it: the stored row moves to the base, and + // the write-through names the binding it left. + const loose = [...rows.values()].find((r) => r.type === 'view' && r.name === RT_OBJ)!; + rows.delete(keyOf(loose)); + const rebound: Row = { ...loose, package_id: BASE }; + rows.set(keyOf(rebound), rebound); + await (protocol as any).applyRegistryWriteThrough({ + type: 'view', name: RT_OBJ, item: JSON.parse(rebound.metadata), packageId: BASE, organizationId: null, + reboundFrom: { packageId: null }, + }); - // A package-less row of the adopted name (ADR-0048: two rows of one + // A package-less row of the rebound name (ADR-0048: two rows of one // name), with no members, and the write the door makes after storing it. const later = rtContainer({}); const row: Row = { @@ -762,7 +682,7 @@ describe('[#23198] the orphan adoption rebinds runtime-created items only, and t }); // The base row's members are still registered: the package-less - // record left with the adoption, so this write healed none of them. + // record left with the rebind, so this write healed none of them. expect(labelOf(registry.bare('view', RT_OPEN))).toBe('Open'); expect(labelOf(registry.bare('view', RT_CLOSED))).toBe('Closed'); expect(registry.bare('view', RT_OPEN)?._packageId).toBe(BASE); diff --git a/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts b/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts index 047dd05cba3..4b9177762a5 100644 --- a/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts +++ b/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts @@ -28,12 +28,10 @@ * call is pinned with its member in `protocol.register-item-call-sites.test.ts`, * where the expansion's registration sits in the reconcile. * - * Every write is routed; the census has no exception kind. The last one, the - * orphan adoption's rebinding (`reassignOrphanedMetadata`, - * `POST /packages/:id/adopt-orphans`), now writes each rebound view row - * through, with the binding it left, so the reconcile moves the row's record - * to its new binding at once. A new write with no route turns this red, and - * the only way to green it is to route that write. + * Every write is routed; the census has no exception kind. (The orphan + * adoption's rebinding, `reassignOrphanedMetadata`, was the last one routed; + * it retired with its door, #38150.) A new write with no route turns this + * red, and the only way to green it is to route that write. * * [#29985] The population is read from `protocol.ts` and every `protocol-*.ts` * module of the split: the codemod split moved member bodies out of the class @@ -170,7 +168,6 @@ const WRITES: ReadonlyArray<{ readonly member: string; readonly verb: string; re { member: 'rollbackMetaItemUnaudited', verb: 'repo.restoreVersion(', route: { sameMember: 'applyRegistryWriteThrough' } }, { member: 'deleteMetaItemUnaudited', verb: 'repo.delete(', route: { sameMember: 'restoreArtifactRegistryView' } }, { member: 'deleteMetaItemUnaudited', verb: 'this.engine.delete(\'sys_metadata\'', route: { sameMember: 'restoreArtifactRegistryView' } }, - { member: 'reassignOrphanedMetadata', verb: 'this.engine.update(\'sys_metadata\'', route: { sameMember: 'applyRegistryWriteThrough' } }, // [#30000] `os migrate packageless-overlays --apply`: the unbound row, once its pair's row reads back. { member: 'migratePackagelessOverlays', verb: 'repo.delete(', route: { sameMember: 'restoreArtifactRegistryView' } }, // [#32396] A refused package publish on a runtime that cannot roll back undoes its promotions: the diff --git a/packages/objectql/src/protocol-adopt-orphans-draft-view-registry.test.ts b/packages/objectql/src/protocol-adopt-orphans-draft-view-registry.test.ts deleted file mode 100644 index b5f559d8702..00000000000 --- a/packages/objectql/src/protocol-adopt-orphans-draft-view-registry.test.ts +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * #23690, ADR-0070 D5 / ADR-0048 — an orphan adoption never makes a DRAFT view - * live: an adopted draft view is rebound in storage only, as the boot treats it. - * - * ## The defect - * - * `reassignOrphanedMetadata` (the method `POST /api/v1/packages/:id/adopt-orphans` - * calls) sends each rebound view row through the registry write-through - * (#23198). The view limb admitted a row by its type alone, so a package-less - * draft view adopted into Q was registered as live (its draft body, stamped - * `_packageId` Q) until the next boot, which registers active rows only - * (`loadMetaFromDb`). `applyRegistryWriteThrough`'s own header: drafts "are a - * staging buffer and must never leak into the runtime". Measured on - * `origin/main` `4c21e57169` before the fix. - * - * ## The pins, on a real kernel (another kernel over the same store is a boot) - * - * - an adopted draft view: before and after the adoption the registry serves - * nothing for it, the stored row is Q's draft, and a boot afterwards agrees; - * - an adopted draft beside an adopted active row of the same view: the - * active body is served at Q, never the draft's; - * - CONTROL: an adopted active view is served at Q at once (#23198), and a - * boot afterwards agrees. - * - * The negative control (the gate removed, the draft pins red) is a one-off - * ablation recorded in the PR body, not a test. - */ - -import { randomUUID } from 'node:crypto'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { ObjectKernel } from '@objectstack/core'; -import { ObjectQL } from './engine.js'; -import { ObjectQLPlugin } from './plugin.js'; - -type Stores = Map>>; - -/** - * In-memory driver, copied from `protocol-adopt-orphans-object-registry.test.ts`; - * equality-only WHERE. `dropTable` records the tables a run drops, so a pin can - * say none was. - */ -function makeMemoryDriver(stores: Stores, drops: string[]) { - const storeFor = (obj: string) => { - let s = stores.get(obj); - if (!s) { s = new Map(); stores.set(obj, s); } - return s; - }; - // `$and` / `$or` are conjoined WITH their sibling keys, the way a real - // driver ANDs them. - const matchesWhere = (row: Record, where: any): boolean => { - if (!where || typeof where !== 'object') return true; - for (const [k, v] of Object.entries(where)) { - if (k === '$and' && Array.isArray(v)) { - if (!v.every((w: any) => matchesWhere(row, w))) return false; - continue; - } - if (k === '$or' && Array.isArray(v)) { - if (!v.some((w: any) => matchesWhere(row, w))) return false; - continue; - } - if (k.startsWith('$')) continue; - const rowVal = row[k]; - const expected = (v && typeof v === 'object' && '$eq' in (v as any)) ? (v as any).$eq : v; - const a = rowVal === undefined ? null : rowVal; - const b = expected === undefined ? null : expected; - if (a !== b) return false; - } - return true; - }; - const driver: any = { - name: 'memory', version: '0.0.0', supports: {} as any, - async connect() {}, async disconnect() {}, async checkHealth() { return true; }, - async execute() { return null; }, - async find(object: string, ast: any) { - const rows = Array.from(storeFor(object).values()).filter((r) => matchesWhere(r, ast?.where)); - // The caller's bound, after the filter, by presence (`check:objectql-double-limit`). - return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; - }, - async findOne(object: string, ast: any) { - for (const r of storeFor(object).values()) if (matchesWhere(r, ast?.where)) return r; - return null; - }, - async create(object: string, data: Record) { - const id = (data.id as string) ?? `r_${randomUUID()}`; - const row = { ...data, id }; - storeFor(object).set(id, row); - return row; - }, - async update(object: string, id: string, data: Record) { - const s = storeFor(object); - const cur = s.get(id); - if (!cur) throw new Error(`not found: ${object}/${id}`); - const updated = { ...cur, ...data, id }; - s.set(id, updated); - return updated; - }, - async upsert(object: string, data: Record) { - const id = data.id as string | undefined; - if (id && storeFor(object).has(id)) return this.update(object, id, data); - return this.create(object, data); - }, - async delete(object: string, id: string) { return storeFor(object).delete(id); }, - async count(object: string, ast: any) { return (await this.find(object, ast)).length; }, - async bulkCreate(object: string, rows: Record[]) { - return Promise.all(rows.map((r) => this.create(object, r))); - }, - async bulkUpdate() { return []; }, async bulkDelete() {}, - async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; }, - async commit() {}, async rollback() {}, - async dropTable(object: string) { drops.push(object); stores.delete(object); }, - }; - return driver; -} - -/** The data plane read, as the system reads it: typed, never erased (`check:query-options-erasure`). */ - -const Q = 'com.qa.q'; -const VIEW = 'qa_probe_gadget_grid'; - -/** A view body; `label` tells the rows apart. */ -const viewBody = (label: string) => ({ - name: VIEW, label, type: 'grid', data: { provider: 'object', object: 'qa_probe_gadget' }, -}); - -interface Booted { - kernel: ObjectKernel; - engine: ObjectQL; - protocol: any; -} - -describe('#23690 — an orphan adoption rebinds a draft view in storage only', () => { - const live: ObjectKernel[] = []; - afterEach(async () => { - vi.restoreAllMocks(); - while (live.length) { - const kernel = live.pop()!; - if (kernel.getState() === 'running') await kernel.shutdown(); - } - }); - - /** One boot over `stores`: a kernel, a fresh engine, and `loadMetaFromDb` run by the plugin's start. */ - async function boot(stores: Stores, drops: string[]): Promise { - // gracefulShutdown:false keeps process signal handlers out of vitest's fork workers (#4250). - const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); - live.push(kernel); - const engine = new ObjectQL(); - engine.registerDriver(makeMemoryDriver(stores, drops), true); - await kernel.use(new ObjectQLPlugin({ ql: engine })); - await kernel.bootstrap(); - return { kernel, engine, protocol: kernel.getService('protocol') }; - } - - /** A package-less view row, as a pre-package-first stopgap left it. */ - const insertOrphan = (k: Booted, state: 'active' | 'draft', label: string) => - k.engine.insert('sys_metadata', { - type: 'view', name: VIEW, state, package_id: null, metadata: JSON.stringify(viewBody(label)), - }, { context: { isSystem: true } } as any); - - /** The view's stored rows, as the driver holds them. */ - const storedRows = (stores: Stores) => - Array.from(stores.get('sys_metadata')?.values() ?? []) - .filter((r) => r.type === 'view' && r.name === VIEW) - .map((r) => ({ state: r.state, packageId: r.package_id ?? null })); - - /** What the registry serves for the view: nothing, or its label and package stamp. */ - const served = (k: Booted) => { - const view = k.engine.registry.getItem('view', VIEW) as { label?: string; _packageId?: string } | undefined; - return view === undefined ? undefined : { label: view.label, packageId: view._packageId }; - }; - - it('an adopted DRAFT view: the registry serves nothing before, after, and at the next boot', async () => { - const stores: Stores = new Map(); - const drops: string[] = []; - const k = await boot(stores, drops); - await insertOrphan(k, 'draft', 'Draft gadgets'); - expect(served(k)).toBeUndefined(); - const registerItem = vi.spyOn(k.engine.registry, 'registerItem'); - - const adopted = await k.protocol.reassignOrphanedMetadata({ targetPackageId: Q }); - - // The storage rebind and its answer are unchanged. - expect(adopted).toMatchObject({ success: true, reassignedCount: 1, reassigned: [{ type: 'view', name: VIEW }] }); - expect(storedRows(stores)).toEqual([{ state: 'draft', packageId: Q }]); - // Nothing of the draft reaches the registry. - expect(registerItem.mock.calls.filter(([type]) => type === 'view')).toEqual([]); - expect(served(k)).toBeUndefined(); - - // A boot afterwards agrees. - await k.kernel.shutdown(); - const k2 = await boot(stores, drops); - expect(served(k2)).toBeUndefined(); - expect(storedRows(stores)).toEqual([{ state: 'draft', packageId: Q }]); - expect(drops).toEqual([]); - }); - - it('an adopted draft beside an adopted active row of the same view: the active body is served at Q, never the draft', async () => { - const stores: Stores = new Map(); - const drops: string[] = []; - const k = await boot(stores, drops); - await insertOrphan(k, 'active', 'Published gadgets'); - await insertOrphan(k, 'draft', 'Draft gadgets'); - - const adopted = await k.protocol.reassignOrphanedMetadata({ targetPackageId: Q }); - - expect(adopted).toMatchObject({ success: true, reassignedCount: 2 }); - expect(storedRows(stores)).toEqual([{ state: 'active', packageId: Q }, { state: 'draft', packageId: Q }]); - expect(served(k)).toEqual({ label: 'Published gadgets', packageId: Q }); - - await k.kernel.shutdown(); - const k2 = await boot(stores, drops); - expect(served(k2)).toEqual({ label: 'Published gadgets', packageId: Q }); - }); - - it('CONTROL: an adopted ACTIVE view is served at Q at once (#23198), and a boot afterwards agrees', async () => { - const stores: Stores = new Map(); - const drops: string[] = []; - const k = await boot(stores, drops); - await insertOrphan(k, 'active', 'Published gadgets'); - - const adopted = await k.protocol.reassignOrphanedMetadata({ targetPackageId: Q }); - - expect(adopted).toMatchObject({ success: true, reassignedCount: 1, reassigned: [{ type: 'view', name: VIEW }] }); - expect(storedRows(stores)).toEqual([{ state: 'active', packageId: Q }]); - expect(served(k)).toEqual({ label: 'Published gadgets', packageId: Q }); - - await k.kernel.shutdown(); - const k2 = await boot(stores, drops); - expect(served(k2)).toEqual({ label: 'Published gadgets', packageId: Q }); - expect(drops).toEqual([]); - }); -}); diff --git a/packages/objectql/src/protocol-adopt-orphans-object-registry.test.ts b/packages/objectql/src/protocol-adopt-orphans-object-registry.test.ts deleted file mode 100644 index 80b4d26bcc8..00000000000 --- a/packages/objectql/src/protocol-adopt-orphans-object-registry.test.ts +++ /dev/null @@ -1,379 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * #23646, ADR-0070 D5 — an orphan adoption leaves the registry agreeing with - * storage for every object it adopts, in the same request, with no restart. - * - * ## The defect - * - * `reassignOrphanedMetadata` (the method `POST /api/v1/packages/:id/adopt-orphans` - * calls) rebinds each package-less `sys_metadata` row to the target package Q - * in storage. Its registry write-through followed view rows only, so an - * adopted runtime object kept the owner its package-less row registered (the - * `'sys_metadata'` sentinel) and its pre-adoption definition until the next - * boot. Meanwhile a save naming Q answered `200` and never went live: the - * write-through's `registerObject(…, Q, …, 'own')` met the registry's - * single-owner rule (ADR-0029 D3) and landed in a best-effort warn. Measured - * on `origin/main` `57994c311f` at protocol level and over the HTTP route on a - * booted CRM example. - * - * ## The fix the pins hold - * - * For each adopted object row, the orphan's own contribution leaves the - * registry (`SchemaRegistry.unregisterObject`, the verb the delete heal hands - * an object's name to a remaining row with) and the row registers at its new - * binding through the one write-through every save uses. The registry holds - * one owner per name throughout; no new registry verb exists. - * - * ## Why a real kernel, and three of them - * - * The disagreement is between the `sys_metadata` rows the driver holds and the - * `SchemaRegistry` the data plane dispatches on, and the boot half is - * `loadMetaFromDb`'s. `ObjectQLPlugin` binds the real protocol to the real - * engine and registry; another kernel over the same store is a boot. - * - * ## The pins - * - * - adopt, then read the owner and the served definition: Q at once, for an - * object saved in this process and for one hydrated at boot; - * - a save naming Q after the adoption goes live; - * - a boot after that agrees; - * - an adopted draft object row registers nothing, as the boot registers - * none; - * - an object another package extends keeps its old owner (the registry - * refuses to drop it), said once at `error`; - * - CONTROL: an adoption of non-object items leaves the object registry - * untouched, and the view write-through follows the view as before; - * - a package-less row of an object another package's row owns: the - * registry keeps that owner (#23646), and since #28776 the adoption is - * refused whole with the save door's D9.9 refusal - * (`OBJECT_OVERLAY_PACKAGE_MISMATCH` / 422), so storage no longer rebinds - * the row beside the owner's (this was a CONTROL pinning that rebind). - * - * The negative control (the object limb removed, these pins red) is a one-off - * ablation recorded in the PR body, not a test. - */ - -import { randomUUID } from 'node:crypto'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { ObjectKernel } from '@objectstack/core'; -import { ObjectQL, type EngineReadOptions } from './engine.js'; -import { ObjectQLPlugin } from './plugin.js'; - -type Stores = Map>>; - -/** - * In-memory driver, copied from `protocol-runtime-owner-overlay-refusal.test.ts`; - * equality-only WHERE. `dropTable` records the tables a run drops, so a pin can - * say none was. - */ -function makeMemoryDriver(stores: Stores, drops: string[]) { - const storeFor = (obj: string) => { - let s = stores.get(obj); - if (!s) { s = new Map(); stores.set(obj, s); } - return s; - }; - // `$and` / `$or` are conjoined WITH their sibling keys, the way a real - // driver ANDs them. - const matchesWhere = (row: Record, where: any): boolean => { - if (!where || typeof where !== 'object') return true; - for (const [k, v] of Object.entries(where)) { - if (k === '$and' && Array.isArray(v)) { - if (!v.every((w: any) => matchesWhere(row, w))) return false; - continue; - } - if (k === '$or' && Array.isArray(v)) { - if (!v.some((w: any) => matchesWhere(row, w))) return false; - continue; - } - if (k.startsWith('$')) continue; - const rowVal = row[k]; - const expected = (v && typeof v === 'object' && '$eq' in (v as any)) ? (v as any).$eq : v; - const a = rowVal === undefined ? null : rowVal; - const b = expected === undefined ? null : expected; - if (a !== b) return false; - } - return true; - }; - const driver: any = { - name: 'memory', version: '0.0.0', supports: {} as any, - async connect() {}, async disconnect() {}, async checkHealth() { return true; }, - async execute() { return null; }, - async find(object: string, ast: any) { - const rows = Array.from(storeFor(object).values()).filter((r) => matchesWhere(r, ast?.where)); - // The caller's bound, after the filter, by presence (`check:objectql-double-limit`). - return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; - }, - async findOne(object: string, ast: any) { - for (const r of storeFor(object).values()) if (matchesWhere(r, ast?.where)) return r; - return null; - }, - async create(object: string, data: Record) { - const id = (data.id as string) ?? `r_${randomUUID()}`; - const row = { ...data, id }; - storeFor(object).set(id, row); - return row; - }, - async update(object: string, id: string, data: Record) { - const s = storeFor(object); - const cur = s.get(id); - if (!cur) throw new Error(`not found: ${object}/${id}`); - const updated = { ...cur, ...data, id }; - s.set(id, updated); - return updated; - }, - async upsert(object: string, data: Record) { - const id = data.id as string | undefined; - if (id && storeFor(object).has(id)) return this.update(object, id, data); - return this.create(object, data); - }, - async delete(object: string, id: string) { return storeFor(object).delete(id); }, - async count(object: string, ast: any) { return (await this.find(object, ast)).length; }, - async bulkCreate(object: string, rows: Record[]) { - return Promise.all(rows.map((r) => this.create(object, r))); - }, - async bulkUpdate() { return []; }, async bulkDelete() {}, - async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; }, - async commit() {}, async rollback() {}, - async dropTable(object: string) { drops.push(object); stores.delete(object); }, - }; - return driver; -} - -/** The data plane read, as the system reads it: typed, never erased (`check:query-options-erasure`). */ -const SYSTEM_READ: EngineReadOptions = { context: { isSystem: true } }; - -const Q = 'com.qa.q'; -const R = 'com.qa.r'; -const NAME = 'qa_probe_gadget'; -const VIEW = 'qa_probe_gadget_grid'; -const SENTINEL = 'sys_metadata'; - -/** A runtime object body; `label` tells the writes apart, `extra` adds a field. */ -const gadgetBody = (label: string, extra?: string) => ({ - name: NAME, - label, - // [#8310] The runtime object door requires an authored OWD. - sharingModel: 'private', - fields: { - name: { name: 'name', type: 'text', label: 'Name' }, - ...(extra ? { [extra]: { name: extra, type: 'text', label: 'Extra' } } : {}), - }, -}); - -interface Booted { - kernel: ObjectKernel; - engine: ObjectQL; - protocol: any; -} - -describe('#23646 — an orphan adoption moves an adopted object\'s registry owner with its row', () => { - const live: ObjectKernel[] = []; - afterEach(async () => { - vi.restoreAllMocks(); - while (live.length) { - const kernel = live.pop()!; - if (kernel.getState() === 'running') await kernel.shutdown(); - } - }); - - /** One boot over `stores`: a kernel, a fresh engine, and `loadMetaFromDb` run by the plugin's start. */ - async function boot(stores: Stores, drops: string[]): Promise { - // `logger.level` is the real config key, and gracefulShutdown:false keeps - // process signal handlers out of vitest's fork workers (#4250). - const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); - live.push(kernel); - const engine = new ObjectQL(); - engine.registerDriver(makeMemoryDriver(stores, drops), true); - await kernel.use(new ObjectQLPlugin({ ql: engine })); - await kernel.bootstrap(); - // [#26708] The workspaces the saves below name are installed, as - // authored bases: a save naming a package no installed package has - // is refused before it is written. - for (const id of [Q, R]) engine.registry.installPackage({ id, name: id, version: '1.0.0' } as any, 'authored'); - return { kernel, engine, protocol: kernel.getService('protocol') }; - } - - /** The bindings of `name`'s stored rows of `type`, as the driver holds them. */ - const storedBindings = (stores: Stores, type = 'object', name = NAME) => - Array.from(stores.get('sys_metadata')?.values() ?? []) - .filter((r) => r.type === type && r.name === name) - .map((r) => r.package_id ?? null); - - const save = (k: Booted, packageId: string | undefined, label: string, extra?: string) => - k.protocol.saveMetaItem({ - type: 'object', name: NAME, ...(packageId ? { packageId } : {}), item: gadgetBody(label, extra), - }); - - /** - * The answers that must agree with storage: the registry's owner, the - * definition the data plane dispatches on (the registry's object, its label - * and its package stamp), the metadata read's served row, and the records. - */ - async function served(k: Booted) { - const read = await k.protocol.getMetaItem({ type: 'object', name: NAME }); - const records = await k.engine.find(NAME, {}, SYSTEM_READ); - const object = k.engine.registry.getObject(NAME) as { label?: string; _packageId?: string } | undefined; - return { - owner: k.engine.registry.getObjectOwner(NAME)?.packageId, - dataPlaneLabel: object?.label, - dataPlanePackage: object?._packageId, - metaReadLabel: (read?.item ?? read)?.label, - records: records.length, - }; - } - - /** The object saved naming no package, with two records in its table: the sentinel owns it. */ - async function seedPackagelessObject(stores: Stores, drops: string[]): Promise { - const k = await boot(stores, drops); - const res = await save(k, undefined, 'Gadget unbound'); - expect(res.success).toBe(true); - await k.engine.insert(NAME, { name: 'rec-1' }, { context: { isSystem: true } } as any); - await k.engine.insert(NAME, { name: 'rec-2' }, { context: { isSystem: true } } as any); - expect(storedBindings(stores)).toEqual([null]); - expect(k.engine.registry.getObjectOwner(NAME)?.packageId).toBe(SENTINEL); - return k; - } - - it.each([ - ['saved in this process', false], - ['hydrated at boot', true], - ])('an adopted object (%s): Q owns it at once, a save naming Q goes live, and a boot agrees', async (_how, reboot) => { - const stores: Stores = new Map(); - const drops: string[] = []; - let k = await seedPackagelessObject(stores, drops); - if (reboot) { - await k.kernel.shutdown(); - k = await boot(stores, drops); - expect(await served(k)).toMatchObject({ owner: SENTINEL, dataPlanePackage: SENTINEL }); - } - - const adopted = await k.protocol.reassignOrphanedMetadata({ targetPackageId: Q }); - - expect(adopted).toMatchObject({ success: true, reassignedCount: 1, reassigned: [{ type: 'object', name: NAME }] }); - expect(storedBindings(stores)).toEqual([Q]); - // The same request: the registry agrees with storage, with no restart. - expect(await served(k)).toEqual({ - owner: Q, dataPlaneLabel: 'Gadget unbound', dataPlanePackage: Q, metaReadLabel: 'Gadget unbound', records: 2, - }); - // One owner, and Q's package filter lists it (the sidebar's read). - expect(k.engine.registry.getObjectContributors(NAME).filter((c) => c.ownership === 'own')).toHaveLength(1); - expect(k.engine.registry.getAllObjects(Q).map((o) => o.name)).toContain(NAME); - - // A save naming Q goes live: its new field is on the data plane at once. - expect((await save(k, Q, 'Gadget Q', 'serial')).success).toBe(true); - expect(storedBindings(stores)).toEqual([Q]); - expect(await served(k)).toEqual({ - owner: Q, dataPlaneLabel: 'Gadget Q', dataPlanePackage: Q, metaReadLabel: 'Gadget Q', records: 2, - }); - await k.engine.insert(NAME, { name: 'rec-3', serial: 'S-3' }, { context: { isSystem: true } } as any); - - // A boot after that agrees. - await k.kernel.shutdown(); - const k2 = await boot(stores, drops); - expect(await served(k2)).toEqual({ - owner: Q, dataPlaneLabel: 'Gadget Q', dataPlanePackage: Q, metaReadLabel: 'Gadget Q', records: 3, - }); - expect(drops).toEqual([]); - }); - - it('an adopted DRAFT object row is rebound in storage only: a draft never reaches the registry', async () => { - const stores: Stores = new Map(); - const drops: string[] = []; - const k = await boot(stores, drops); - // A package-less draft, as a pre-package-first stopgap left it. - await k.engine.insert('sys_metadata', { - type: 'object', name: NAME, state: 'draft', package_id: null, - metadata: JSON.stringify(gadgetBody('Gadget draft')), - }, { context: { isSystem: true } } as any); - const registerObject = vi.spyOn(k.engine.registry, 'registerObject'); - const registerItem = vi.spyOn(k.engine.registry, 'registerItem'); - - const adopted = await k.protocol.reassignOrphanedMetadata({ targetPackageId: Q }); - - expect(adopted).toMatchObject({ reassignedCount: 1, reassigned: [{ type: 'object', name: NAME }] }); - expect(storedBindings(stores)).toEqual([Q]); - expect(registerObject).not.toHaveBeenCalled(); - expect(registerItem.mock.calls.filter(([type]) => type === 'object')).toEqual([]); - expect(k.engine.registry.getObject(NAME)).toBeUndefined(); - }); - - it('an object another package extends keeps its old owner, said once at `error` naming the object', async () => { - const stores: Stores = new Map(); - const drops: string[] = []; - const k = await seedPackagelessObject(stores, drops); - // A code package's extension of the runtime object: `unregisterObject`'s - // ADR-0029 guard refuses to drop an owner another package extends. - k.engine.registry.registerObject({ - name: NAME, fields: { ext_note: { name: 'ext_note', type: 'text', label: 'Note' } }, - } as any, R, undefined, 'extend'); - const error = vi.spyOn(console, 'error').mockImplementation(() => {}); - - const adopted = await k.protocol.reassignOrphanedMetadata({ targetPackageId: Q }); - - expect(adopted).toMatchObject({ success: true, reassignedCount: 1 }); - expect(storedBindings(stores)).toEqual([Q]); - expect(k.engine.registry.getObjectOwner(NAME)?.packageId).toBe(SENTINEL); - expect(k.engine.registry.getObjectContributors(NAME).map((c) => c.ownership).sort()).toEqual(['extend', 'own']); - const said = error.mock.calls.map(([line]) => String(line)).filter((line) => line.includes(`'${NAME}'`)); - expect(said).toHaveLength(1); - expect(said[0]).toContain(`'${Q}'`); - }); - - it('CONTROL: an adoption of non-object items leaves the object registry untouched, and the view follows as before', async () => { - const stores: Stores = new Map(); - const drops: string[] = []; - const k = await boot(stores, drops); - // A package-less view row, as a pre-package-first stopgap left it. - await k.engine.insert('sys_metadata', { - type: 'view', name: VIEW, state: 'active', package_id: null, - metadata: JSON.stringify({ - name: VIEW, label: 'Gadgets', type: 'grid', data: { provider: 'object', object: NAME }, - }), - }, { context: { isSystem: true } } as any); - const registerObject = vi.spyOn(k.engine.registry, 'registerObject'); - const unregisterObject = vi.spyOn(k.engine.registry, 'unregisterObject'); - - const adopted = await k.protocol.reassignOrphanedMetadata({ targetPackageId: Q }); - - expect(adopted).toMatchObject({ reassignedCount: 1, reassigned: [{ type: 'view', name: VIEW }] }); - expect(storedBindings(stores, 'view', VIEW)).toEqual([Q]); - expect(registerObject).not.toHaveBeenCalled(); - expect(unregisterObject).not.toHaveBeenCalled(); - // The view write-through (#23198), unchanged: the registry serves the - // view at its new binding. - expect((k.engine.registry.getItem('view', VIEW) as { _packageId?: string } | undefined)?._packageId).toBe(Q); - }); - - it('[#28776] a package-less row of an object another package\'s row owns: the adoption is refused whole (D9.9), nothing is rebound, and that owner stays', async () => { - const stores: Stores = new Map(); - const drops: string[] = []; - const k = await boot(stores, drops); - expect((await save(k, R, 'Gadget R')).success).toBe(true); - // Legacy residue beside R's row: a package-less row no door writes today. - await k.engine.insert('sys_metadata', { - type: 'object', name: NAME, state: 'active', package_id: null, - metadata: JSON.stringify(gadgetBody('Gadget residue')), - }, { context: { isSystem: true } } as any); - const registerObject = vi.spyOn(k.engine.registry, 'registerObject'); - const registerItem = vi.spyOn(k.engine.registry, 'registerItem'); - const unregisterObject = vi.spyOn(k.engine.registry, 'unregisterObject'); - - const refused = await k.protocol.reassignOrphanedMetadata({ targetPackageId: Q }).then( - () => undefined, (e: any) => e, - ); - - // The save door's D9.9 refusal, naming the target and the owner. - expect({ code: refused?.code, status: refused?.status }).toEqual({ code: 'OBJECT_OVERLAY_PACKAGE_MISMATCH', status: 422 }); - expect(String(refused?.message)).toContain(`owned by package '${R}'`); - // Nothing is rebound: the residue stays package-less beside R's row. - expect(storedBindings(stores).map((b) => b ?? 'none').sort()).toEqual([R, 'none'].sort()); - // [#23646] …and that owner stays: nothing reaches the registry, in either half. - expect(unregisterObject).not.toHaveBeenCalled(); - expect(registerObject).not.toHaveBeenCalled(); - expect(registerItem.mock.calls.filter(([type]) => type === 'object')).toEqual([]); - expect(k.engine.registry.getObjectOwner(NAME)?.packageId).toBe(R); - const object = k.engine.registry.getObject(NAME) as { label?: string; _packageId?: string } | undefined; - expect({ label: object?.label, pkg: object?._packageId }).toEqual({ label: 'Gadget R', pkg: R }); - }); -}); diff --git a/packages/objectql/src/protocol-package-lifecycle.test.ts b/packages/objectql/src/protocol-package-lifecycle.test.ts index 98f70c295cc..1e9c3edb263 100644 --- a/packages/objectql/src/protocol-package-lifecycle.test.ts +++ b/packages/objectql/src/protocol-package-lifecycle.test.ts @@ -183,33 +183,3 @@ describe('protocol.duplicatePackage (ADR-0070 D4)', () => { expect(calls.some((c: any) => /iojn_/.test(c.name))).toBe(false); // no un-renamed leftovers }); }); - -describe('protocol.reassignOrphanedMetadata (ADR-0070 D5)', () => { - it('rebinds package-less orphans (null / "" / sys_metadata) into the target base; leaves owned rows', async () => { - const rows = [ - { id: 'r1', type: 'object', name: 'loose_a', package_id: null }, - { id: 'r2', type: 'view', name: 'loose_v', package_id: 'sys_metadata' }, - { id: 'r3', type: 'object', name: 'blank', package_id: '' }, - { id: 'r4', type: 'object', name: 'owned', package_id: 'app.existing' }, - ]; - const update = vi.fn(async () => ({ id: 'x' })); - const engine = { find: vi.fn(async () => rows), update }; - const protocol = new ObjectStackProtocolImplementation(engine as never); - const res = await protocol.reassignOrphanedMetadata({ targetPackageId: 'app.home' }); - - expect(res).toMatchObject({ success: true, reassignedCount: 3, targetPackageId: 'app.home' }); - const movedIds = update.mock.calls.map((c: any) => c[2].where.id); - expect(movedIds).toEqual(['r1', 'r2', 'r3']); // the 3 orphans, not the owned r4 - // [#21911] The rebind carries the explicit system opt-in. - expect(update).toHaveBeenCalledWith('sys_metadata', { package_id: 'app.home' }, { where: { id: 'r1' }, context: { isSystem: true } }); - expect(res.reassigned.some((x) => x.name === 'owned')).toBe(false); - }); - - it('no orphans → reassignedCount 0, success false', async () => { - const engine = { find: vi.fn(async () => [{ id: 'r1', type: 'object', name: 'x', package_id: 'app.a' }]), update: vi.fn() }; - const protocol = new ObjectStackProtocolImplementation(engine as never); - const res = await protocol.reassignOrphanedMetadata({ targetPackageId: 'app.home' }); - expect(res).toMatchObject({ success: false, reassignedCount: 0 }); - expect((engine.update as any)).not.toHaveBeenCalled(); - }); -}); diff --git a/packages/objectql/src/protocol-packageless-overlay-migration.test.ts b/packages/objectql/src/protocol-packageless-overlay-migration.test.ts index 1012e3cc17d..a575fe4963b 100644 --- a/packages/objectql/src/protocol-packageless-overlay-migration.test.ts +++ b/packages/objectql/src/protocol-packageless-overlay-migration.test.ts @@ -803,16 +803,22 @@ describe('[#29392] the census and the move reach a row bound to the read-only ba }); }); -describe('[#28413] adopt-orphans leaves a shipped name to the ceremony', () => { - it('adopting into a writable package skips the shipped-name row and rebinds an environment one', async () => { +// [#38150] The adopt-orphans door retired; the move door that replaced it +// (`moveIntoPackage`) refuses the shipped-name row `NOT_LOOSE`, pinned on a +// booted stack in `qa/dogfood/test/package-move-in.dogfood.test.ts` ("a +// `.custom` pair item and a served overlay are not loose"). +describe('[#28413] the move door leaves a shipped name to the ceremony', () => { + it('a dry run into a writable package refuses the shipped-name row and would move an environment one', async () => { const { engine, protocol, rows } = await boot(); await (protocol as any).installPackage({ manifest: { id: WORKSPACE, name: 'workspace', version: '0.1.0', type: 'app' } }); await storeRow(engine, VIEW, 'showcase_task', UNBOUND_COLUMNS); await storeRow(engine, ENV_VIEW, 'showcase_task', UNBOUND_COLUMNS); - const result = await (protocol as any).reassignOrphanedMetadata({ targetPackageId: WORKSPACE }); - expect(result.reassigned).toEqual([{ type: 'view', name: ENV_VIEW }]); + const shipped = await (protocol as any).moveIntoPackage({ targetPackageId: WORKSPACE, items: [{ type: 'view', name: VIEW }], dryRun: true }); + expect(shipped.refused.map((r: any) => `${r.name}:${r.code}`)).toEqual([`${VIEW}:NOT_LOOSE`]); + const own = await (protocol as any).moveIntoPackage({ targetPackageId: WORKSPACE, items: [{ type: 'view', name: ENV_VIEW }], dryRun: true }); + expect(own.outcome).toBe('would_move'); expect(rows(VIEW)).toEqual([[null, 'active']]); - expect(rows(ENV_VIEW)).toEqual([[WORKSPACE, 'active']]); + expect(rows(ENV_VIEW)).toEqual([[null, 'active']]); }); }); diff --git a/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts b/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts index a7f923ec0c9..2fa9f271ab4 100644 --- a/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts +++ b/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts @@ -45,7 +45,8 @@ import { findPackageHeldSecurityCatalogNames, RESERVED_NAMESPACES, SecurityCatal type Stores = Map>>; /** - * In-memory driver, copied from `protocol-adopt-orphans-object-registry.test.ts`; + * In-memory driver, copied from `protocol-adopt-orphans-object-registry.test.ts` + * (retired with its door, #38150); * equality-only WHERE. */ function makeMemoryDriver(stores: Stores) { diff --git a/packages/objectql/src/protocol-sentinel-owner-package-save-refusal.test.ts b/packages/objectql/src/protocol-sentinel-owner-package-save-refusal.test.ts index 98419eaf607..67eb30d4618 100644 --- a/packages/objectql/src/protocol-sentinel-owner-package-save-refusal.test.ts +++ b/packages/objectql/src/protocol-sentinel-owner-package-save-refusal.test.ts @@ -21,11 +21,10 @@ * * Delete the package-less definition WITHOUT `dropStorage` (the delete door's * default), which keeps the table and its records, then save naming Q: Q's row - * becomes the owner at once and at every later boot. ADR-0070 D5's - * `adopt-orphans` door also hands an adopted object's registry owner to Q (its - * own pins, `protocol-adopt-orphans-object-registry.test.ts`, run beside these), - * but it rebinds EVERY package-less row of the environment, so the refusal - * names the narrower way out. + * becomes the owner at once and at every later boot. The move door + * (`POST /packages/:id/move-in`, #38150) runs exactly those two steps for the + * items an author picks; the all-at-once `adopt-orphans` door it replaced is + * retired. * * ## Why a real kernel, and two of them * diff --git a/packages/qa/dogfood/test/authz-conformance.matrix.ts b/packages/qa/dogfood/test/authz-conformance.matrix.ts index 3504c5dda6e..729c701ef03 100644 --- a/packages/qa/dogfood/test/authz-conformance.matrix.ts +++ b/packages/qa/dogfood/test/authz-conformance.matrix.ts @@ -278,7 +278,7 @@ export const AUTHZ_CONFORMANCE: AuthzPrimitive[] = [ // ONE handler body, `handlePackagesRequest`, so a single domain-wide gate there // covers them all. { id: 'anonymous-deny-packages', summary: 'anonymous-deny on the package-management surface', state: 'enforced', - enforcement: 'runtime/domains/packages.ts handlePackagesRequest — shouldDenyAnonymous DOMAIN-WIDE as the handler\'s FIRST statement, ahead of the ObjectQL registry probe so the 401-vs-503 difference cannot fingerprint whether the package service is mounted; per-route capability predicates run after this floor — `manage_metadata` for every state-changing route (install / enable / disable / publish / publish-drafts / discard-drafts / commit-revert / rollback / revert / adopt-orphans / duplicate / manifest-PATCH / DELETE), and the ADR-0106 D4 read set (`studio.access` / `setup.access`) for every read (list / detail / commits / export)', + enforcement: 'runtime/domains/packages.ts handlePackagesRequest — shouldDenyAnonymous DOMAIN-WIDE as the handler\'s FIRST statement, ahead of the ObjectQL registry probe so the 401-vs-503 difference cannot fingerprint whether the package service is mounted; per-route capability predicates run after this floor — `manage_metadata` for every state-changing route (install / enable / disable / publish / publish-drafts / discard-drafts / commit-revert / rollback / revert / move-in / duplicate / manifest-PATCH / DELETE), and the ADR-0106 D4 read set (`studio.access` / `setup.access`) for every read (list / detail / commits / export)', proof: 'showcase-anonymous-deny-surfaces.dogfood.test.ts', // [2026-08-31] The DISPATCHER domain only. ⛔ NOT the REST `packages` // family, which is a different registrar on a different server and stays diff --git a/packages/qa/dogfood/test/package-first-authoring.dogfood.test.ts b/packages/qa/dogfood/test/package-first-authoring.dogfood.test.ts index 6efdade0563..b20f951ff0b 100644 --- a/packages/qa/dogfood/test/package-first-authoring.dogfood.test.ts +++ b/packages/qa/dogfood/test/package-first-authoring.dogfood.test.ts @@ -9,14 +9,15 @@ // This is the contract the Studio + AI surfaces rely on. // // 2. The package is the lifecycle unit (D3/D4/D5) — a base is the unit you -// author into, discover by, edit, duplicate, delete (cascade), and adopt +// author into, discover by, edit, duplicate, delete (cascade), and move // loose items into. The full chain runs against the live protocol service: // create -> bind -> publish -> editable -> discoverable -> delete-cascade, -// plus the D4 "duplicate base" and D5 "adopt orphans" migration gestures. +// plus the D4 "duplicate base" and D5 migration gestures (D5 is the move +// door now, `moveIntoPackage`: the all-at-once adoption retired, #38150). // // Reverting D1 (the writable_package_required throw in saveMetaItem) turns the // first block red; regressing the package-lifecycle methods (deletePackage, -// duplicatePackage, reassignOrphanedMetadata) turns the rest red. That is the +// duplicatePackage, moveIntoPackage) turns the rest red. That is the // point of the gate — the manual dogfood in the ADR is now an automated proof. import { describe, it, expect, beforeAll, afterAll } from 'vitest'; @@ -24,7 +25,7 @@ import crmStack from '@objectstack/example-crm'; import { bootStack, type VerifyStack } from '@objectstack/verify'; // sys_metadata is the durable store every lifecycle method (deletePackage, -// duplicatePackage, reassignOrphanedMetadata) reads from — assertions against it +// duplicatePackage, moveIntoPackage) reads from — assertions against it // are deterministic, unlike registry merges. `name` is what each row keys on. async function ownedNames(ql: any, packageId: string): Promise { const rows = (await ql.find('sys_metadata', { where: { package_id: packageId }, context: { isSystem: true } })) as any[]; @@ -164,11 +165,11 @@ describe('dogfood: the package is the authoring & delete unit (ADR-0070 D3/D4)', }); }); -describe('dogfood: adopt orphaned metadata into a base (ADR-0070 D5 migration)', () => { +describe('dogfood: move loose metadata into a base (ADR-0070 D5 migration, the move door since #38150)', () => { let stack: VerifyStack; let protocol: any; let ql: any; - const BASE = 'app.dogfood_adopt'; + const BASE = 'app.dogfood-adopt'; const ORPHAN = 'dfa_legacy_orphan'; beforeAll(async () => { @@ -180,7 +181,10 @@ describe('dogfood: adopt orphaned metadata into a base (ADR-0070 D5 migration)', await stack?.stop?.(); }); - it('reassignOrphanedMetadata rebinds a legacy package-less row onto a base', async () => { + it('moveIntoPackage moves a legacy package-less row into a base', async () => { + await protocol.installPackage({ + manifest: { id: BASE, name: 'Dogfood move-in', version: '0.1.0', type: 'app', namespace: 'dfa' }, + }); // Simulate a pre-package-first stopgap leftover: a runtime-authored item with // package_id = null (the #2252 coerce-to-null / #1946 "Local / Custom" bucket). await ql.insert('sys_metadata', { @@ -193,11 +197,10 @@ describe('dogfood: adopt orphaned metadata into a base (ADR-0070 D5 migration)', // Precondition: it is NOT owned by the base yet. expect(await ownedNames(ql, BASE)).not.toContain(ORPHAN); - // MIGRATE — adopt every loose item in the env into the base. - const res = await protocol.reassignOrphanedMetadata({ targetPackageId: BASE }); - expect(res.success).toBe(true); - expect(res.reassignedCount).toBeGreaterThan(0); - expect(res.reassigned.map((r: any) => r.name)).toContain(ORPHAN); + // MIGRATE — move the loose item, named, into the base. + const res = await protocol.moveIntoPackage({ targetPackageId: BASE, items: [{ type: 'object', name: ORPHAN }] }); + expect(res.outcome, JSON.stringify(res.refused)).toBe('moved'); + expect(res.moved.map((r: any) => r.name)).toContain(ORPHAN); // Postcondition: the row is now owned by the base — no longer an orphan. expect(await ownedNames(ql, BASE)).toContain(ORPHAN); diff --git a/packages/qa/dogfood/test/package-move-in.dogfood.test.ts b/packages/qa/dogfood/test/package-move-in.dogfood.test.ts index 84eb89c9784..c7dcf2e0d8d 100644 --- a/packages/qa/dogfood/test/package-move-in.dogfood.test.ts +++ b/packages/qa/dogfood/test/package-move-in.dogfood.test.ts @@ -8,8 +8,9 @@ * * What this file pins, through THIS route on a booted CRM stack: * - * - #37468's three defects of the old `adopt-orphans` door, as regression - * tests on the new one: a move into an uninstalled package (A1), an object + * - #37468's three defects of the old `adopt-orphans` door (retired by + * #38150 PR-B1, which pins that it answers 404), as regression tests on the + * new one: a move into an uninstalled package (A1), an object * without the target's namespace prefix (A2), and a moved flow and dataset * readable at the package's address with no restart (A3). * - The ADR-0150 D3 (a) set rule: a report that reads a loose dataset is @@ -405,6 +406,12 @@ describe('dogfood: POST /packages/:id/move-in, the move door (#38150)', { timeou ]); }); + it('the retired all-at-once door is gone: POST …/adopt-orphans answers 404 and moves nothing (#38150 PR-B1)', async () => { + const res = await stack.apiAs(token, 'POST', `/packages/${encodeURIComponent(TARGET)}/adopt-orphans`, {}); + expect(res.status, await res.clone().text()).toBe(404); + expect(await stored('probe_dry_flow')).toEqual(['flow/probe_dry_flow@loose:active']); + }); + it('a body the schema refuses answers 400 and names the member', async () => { const r = await move(TARGET, { items: [] }); expect(r.status).toBe(400); diff --git a/packages/qa/dogfood/test/wall-environment-metadata-refusal.dogfood.test.ts b/packages/qa/dogfood/test/wall-environment-metadata-refusal.dogfood.test.ts index 3bfd0b1502f..49952ef8164 100644 --- a/packages/qa/dogfood/test/wall-environment-metadata-refusal.dogfood.test.ts +++ b/packages/qa/dogfood/test/wall-environment-metadata-refusal.dogfood.test.ts @@ -269,7 +269,7 @@ for (const posture of ['isolated', 'group'] as const) { ['POST', `/packages/${pkg}/rollback`, { commitId: commits[0] }], ['POST', `/packages/${pkg}/commits/${commits[0]}/revert`, {}], ['POST', `/packages/${pkg}/duplicate`, { targetPackageId: `com.em.${p}.dup` }], - ['POST', `/packages/${pkg}/adopt-orphans`, {}], + ['POST', `/packages/${pkg}/move-in`, { items: [{ type: 'view', name: `crm_lead.em_${p}_orphan` }] }], ['DELETE', `/packages/${pkg}`, undefined], ] as const) { await refused(await h.stack.apiAs(h.tokA, method, path, body), 'PERMISSION_DENIED'); diff --git a/packages/qa/dogfood/test/wall-package-doors-refusal.dogfood.test.ts b/packages/qa/dogfood/test/wall-package-doors-refusal.dogfood.test.ts index 6f7a7db5cee..1ab42bb42fc 100644 --- a/packages/qa/dogfood/test/wall-package-doors-refusal.dogfood.test.ts +++ b/packages/qa/dogfood/test/wall-package-doors-refusal.dogfood.test.ts @@ -17,14 +17,15 @@ // - `POST /packages/:id/revert` discarded the operator's pending draft // (`POST /packages/:id/discard-drafts` is the same discard, by a second door); // - `POST /packages/:id/adopt-orphans` moved the environment's catalog rows -// into A's package. +// into A's package. (That door is retired, #38150; its replacement, +// `POST /packages/:id/move-in`, is pinned here in its place.) // // Pinned here, under each walled posture: every one of those answers // `403 PERMISSION_DENIED`, nothing moves, and B's resolution stays. The commit // revert is judged by the commit's own items, whatever package the URL names. // [ADR-0131 D12 items 7–8] A catalog-free package is refused to A the same way // (ruling A on #23231 stops special-casing the catalog). CONTROLS: the platform -// operator runs every door on the catalog-carrying package, adopt-orphans +// operator runs every door on the catalog-carrying package, move-in // included. And under `single` (CONTROL): the same `manage_metadata` holder // runs every door on the operator's package as before. // @@ -120,8 +121,8 @@ async function boot(posture: 'isolated' | 'group' | 'single'): Promise const ok = async (res: Response, status = 200) => expect(res.status, await res.clone().text()).toBe(status); await ok(await call(stack, operator, 'POST', '/packages', { id: OP_PKG, name: 'w3 operator', version: '1.0.0', type: 'app' }), 201); - // META_AUTHOR lives in the operator's package, so the orphan adoption below - // reads ENV_SET alone as the environment's catalog orphan this file adds. + // META_AUTHOR lives in the operator's package, so ENV_SET alone is the + // environment's loose catalog row this file adds (the move-in cases below). await ok(await call(stack, operator, 'PUT', `/meta/permission/${META_AUTHOR}?package=${OP_PKG}`, set(META_AUTHOR, ['manage_metadata']))); await ok(await call(stack, operator, 'PUT', `/meta/permission/${OP_SET}?package=${OP_PKG}&mode=draft`, set(OP_SET, []))); await ok(await call(stack, operator, 'POST', `/packages/${OP_PKG}/publish-drafts`, {})); @@ -245,12 +246,12 @@ for (const posture of ['isolated', 'group'] as const) { expect(await rowsOf(h, { package_id: 'com.w3.dup' })).toHaveLength(0); }); - it('adopt-orphans: A adopting the environment\'s catalog orphans into another package is refused, and the orphan stays unbound', async () => { + it('move-in: A moving the environment\'s loose catalog row into another package is refused, and the row stays unbound', async () => { // [ADR-0131 D12 items 7–8] A can no longer create a package under a wall, - // so the adopting package is the operator's. + // so the target package is the operator's. const own = await call(h.stack, h.operator, 'POST', '/packages', { id: 'com.w3.a.adopt', name: 'adopt', version: '1.0.0', type: 'app' }); expect(own.status, await own.clone().text()).toBe(201); - await refused(await call(h.stack, h.tokA, 'POST', '/packages/com.w3.a.adopt/adopt-orphans', {})); + await refused(await call(h.stack, h.tokA, 'POST', '/packages/com.w3.a.adopt/move-in', { items: [{ type: 'permission', name: ENV_SET }] })); const env = await rowsOf(h, { type: 'permission', name: ENV_SET }); expect(env.map((r) => r.package_id ?? null)).not.toContain('com.w3.a.adopt'); }); @@ -297,7 +298,8 @@ for (const posture of ['isolated', 'group'] as const) { expect((await bGrants()).systemPermissions).not.toContain('manage_users'); const own = await call(h.stack, h.operator, 'POST', '/packages', { id: 'com.w3.op.oporphans', name: 'adopt', version: '1.0.0', type: 'app' }); expect(own.status, await own.clone().text()).toBe(201); - await ok(await call(h.stack, h.operator, 'POST', '/packages/com.w3.op.oporphans/adopt-orphans', {})); + // A dry run: the door is open to the operator, and the loose row stays loose for the cases after this one. + await ok(await call(h.stack, h.operator, 'POST', '/packages/com.w3.op.oporphans/move-in', { items: [{ type: 'permission', name: ENV_SET }], dryRun: true })); }); }); } @@ -326,6 +328,6 @@ describe('[ADR-0131 D3 · #15204 W3] single (CONTROL): the refusal is inert', () await ok(await call(h.stack, h.operator, 'PUT', `/meta/permission/${OP_SET}?package=${OP_PKG}&mode=draft`, set(OP_SET, ['manage_metadata']))); await ok(await call(h.stack, h.tokA, 'POST', `/packages/${OP_PKG}/discard-drafts`, {})); expect((await call(h.stack, h.tokA, 'POST', '/packages', { id: 'com.w3.a.adopt', name: 'adopt', version: '1.0.0', type: 'app' })).status).toBe(201); - await ok(await call(h.stack, h.tokA, 'POST', '/packages/com.w3.a.adopt/adopt-orphans', {})); + await ok(await call(h.stack, h.tokA, 'POST', '/packages/com.w3.a.adopt/move-in', { items: [{ type: 'permission', name: ENV_SET }], dryRun: true })); }); }); diff --git a/packages/runtime/src/dispatcher-plugin.ts b/packages/runtime/src/dispatcher-plugin.ts index 4f4e14fa45a..67b48b1f2a7 100644 --- a/packages/runtime/src/dispatcher-plugin.ts +++ b/packages/runtime/src/dispatcher-plugin.ts @@ -1711,10 +1711,9 @@ export function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plu // service): this promotes sys_metadata draft rows via the protocol. mountPackagesRoute('post', '/:id/publish-drafts', (req) => `/${req.params.id}/publish-drafts`); mountPackagesRoute('post', '/:id/revert', (req) => `/${req.params.id}/revert`); - // duplicate (ADR-0070 D4), adopt-orphans (D5), discard-drafts, and + // duplicate (ADR-0070 D4), discard-drafts, and // the ADR-0067 commit-history / rollback family. mountPackagesRoute('post', '/:id/duplicate', (req) => `/${req.params.id}/duplicate`); - mountPackagesRoute('post', '/:id/adopt-orphans', (req) => `/${req.params.id}/adopt-orphans`); // [ADR-0084 amendment 2026-11-26] Move a selection of loose items into the package. mountPackagesRoute('post', '/:id/move-in', (req) => `/${req.params.id}/move-in`); mountPackagesRoute('post', '/:id/discard-drafts', (req) => `/${req.params.id}/discard-drafts`); diff --git a/packages/runtime/src/domains/packages-adopt-orphans-readonly.test.ts b/packages/runtime/src/domains/packages-adopt-orphans-readonly.test.ts deleted file mode 100644 index 412d2b55a70..00000000000 --- a/packages/runtime/src/domains/packages-adopt-orphans-readonly.test.ts +++ /dev/null @@ -1,292 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * `POST /packages/:id/adopt-orphans` — the ADR-0070 D2 read-only rule at the - * orphan-adoption door (#24813). - * - * ## The defect - * - * The arm asked `requireManageMetadata` and the walled refusal, and then called - * `protocol.reassignOrphanedMetadata({ targetPackageId: id })`, which asks no - * writability question of its own: it rebinds every package-less - * `sys_metadata` row to whatever id it is handed. So a `manage_metadata` - * holder could bind the environment's loose items INTO a package the - * deployment ships — booted by code, installed from the marketplace, or a - * stored row whose manifest `scope` is `system` / `cloud` — and the door - * answered `200` with the rows it moved. Every other state-changing arm on the - * domain (install-overwrite, disable, publish, revert, the manifest PATCH and - * delete) refuses that same id `422 WRITABLE_PACKAGE_REQUIRED`. - * - * ## What is asserted, and why it is not the status alone - * - * The harm is the rebinding, so every refusal reads the rows back: the - * orphans the real producer minted (a package-less `saveMetaItem`, which still - * lands `package_id = NULL` today) are still package-less after the refusal, - * and the protocol's `reassignOrphanedMetadata` was never called. The store is - * REAL — better-sqlite3 `:memory:`, the real `sys_metadata*` objects, a real - * `ObjectStackProtocolImplementation` over a real `ObjectQL` — so the rows are - * the store's, not a double's. The code-booted and marketplace ids are booted - * through the engine's own `registerApp`; the two scope-only ids are installed - * the way `sys_packages` hydration installs a stored row (`source: - * 'authored'`, no booted manifest), so their refusal can only come from the - * scope signal. - * - * ## Order - * - * The gate sits where its siblings put it: after the capability gate and the - * walled refusal (both `403`, both still answer first on a read-only id), and - * before the protocol is resolved, so a read-only id answers `422` even on a - * deployment whose protocol cannot adopt (`501` for a writable id there). - * - * ## The gate is not an outage - * - * CONTROL: a writable package still adopts (`200`, and the rows really move), - * and an id nothing installed is writable by the predicate's own rule, so it - * still reaches the protocol, which binds the orphans to it exactly as before. - */ - -import { describe, it, expect, vi, afterEach } from 'vitest'; -import { ObjectQL } from '@objectstack/objectql'; -import { SqlDriver } from '@objectstack/driver-sql'; -import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; -import { SysMetadata, SysMetadataHistoryObject, SysMetadataAuditObject } from '@objectstack/platform-objects/metadata'; -import { HttpDispatcher } from '../http-dispatcher.js'; - -/** Booted by the deployment's code: `registerApp`, default source `'code'`. */ -const CODE_BOOTED = 'com.acme.codepkg'; -/** Installed from the marketplace: `registerApp(…, 'marketplace')`. */ -const MARKETPLACE = 'com.acme.marketpkg'; -/** A stored row whose manifest declares `scope: 'system'`; nothing booted it. */ -const SYSTEM_SCOPED = 'com.acme.systempkg'; -/** A stored row whose manifest declares `scope: 'cloud'`; nothing booted it. */ -const CLOUD_SCOPED = 'com.acme.cloudpkg'; -/** An org's own base. */ -const AUTHORED = 'com.acme.authoredpkg'; -/** An id nothing has installed. */ -const UNKNOWN = 'com.acme.nopkg'; -/** `registry.registerObject` requires a package id (see the sibling real-stack tests). */ -const TEST_PACKAGE_ID = 'objectstack-test'; - -/** The loose items the real producer leaves behind. */ -const ORPHANS = ['loose_grid', 'loose_board'] as const; - -const manifest = (id: string, extra: Record = {}) => ({ - id, - name: id, - version: '1.0.0', - type: 'app', - ...extra, -}); - -const TASK = { - name: 'task', - label: 'Task', - fields: { - id: { name: 'id', type: 'text' as const, primaryKey: true, label: 'ID' }, - name: { name: 'name', type: 'text' as const, label: 'Name' }, - }, -}; - -const view = (name: string) => ({ - name, - label: name, - object: 'task', - viewKind: 'list', - columns: [{ field: 'name', label: 'Name' }], -}); - -const silentLogger: any = { - debug() {}, info() {}, warn() {}, error() {}, trace() {}, fatal() {}, - child() { return silentLogger; }, -}; - -const liveEngines: ObjectQL[] = []; -afterEach(async () => { - while (liveEngines.length) { - try { await liveEngines.pop()?.destroy(); } catch { /* noop */ } - } -}); - -interface BootOptions { - /** Compose a protocol that cannot adopt (no `reassignOrphanedMetadata`). */ - protocolWithoutAdoption?: boolean; - /** Compose a `tenancy` service answering this posture. */ - posture?: 'isolated' | 'group'; -} - -/** The composed door over a real store, with the orphans already minted. */ -async function boot(options: BootOptions = {}) { - const engine = new ObjectQL({ logger: silentLogger }); - liveEngines.push(engine); - (engine.registry as unknown as { logLevel: string }).logLevel = 'silent'; - engine.registerDriver(new SqlDriver({ - client: 'better-sqlite3', - connection: { filename: ':memory:' }, - useNullAsDefault: true, - }), true); - await engine.init(); - engine.registry.registerObject(TASK as any, TEST_PACKAGE_ID); - engine.registry.registerObject(SysMetadata as any, TEST_PACKAGE_ID); - engine.registry.registerObject(SysMetadataHistoryObject as any, TEST_PACKAGE_ID); - engine.registry.registerObject(SysMetadataAuditObject as any, TEST_PACKAGE_ID); - await engine.syncSchemas(); - - engine.registerApp(manifest(CODE_BOOTED)); - engine.registerApp(manifest(MARKETPLACE), undefined, 'marketplace'); - engine.registry.installPackage(manifest(SYSTEM_SCOPED, { scope: 'system' }) as any, 'authored'); - engine.registry.installPackage(manifest(CLOUD_SCOPED, { scope: 'cloud' }) as any, 'authored'); - engine.registry.installPackage(manifest(AUTHORED, { scope: 'project' }) as any, 'authored'); - - const protocol = new ObjectStackProtocolImplementation(engine as any); - // The real producer of an orphan: a save naming no package. - for (const name of ORPHANS) { - await protocol.saveMetaItem({ type: 'view', name, item: view(name), mode: 'publish' }); - } - const adopt = vi.spyOn(protocol, 'reassignOrphanedMetadata'); - - const served = options.protocolWithoutAdoption - ? { saveMetaItem: protocol.saveMetaItem.bind(protocol) } - : protocol; - const services: Record = { protocol: served, objectql: engine }; - if (options.posture) services.tenancy = { posture: options.posture }; - const get = (name: string) => services[name] ?? null; - const kernel: any = { context: { getService: get }, getService: get, getServiceAsync: async (n: string) => get(n) }; - const dispatcher = new HttpDispatcher(kernel); - - /** Each loose item's binding, read off the store. */ - const bindings = async (): Promise> => { - const rows = (await engine.find('sys_metadata', { where: { type: 'view' } })) as any[]; - return Object.fromEntries( - rows.filter((r) => (ORPHANS as readonly string[]).includes(r.name)).map((r) => [r.name, r.package_id ?? null]), - ); - }; - - return { engine, dispatcher, adopt, bindings }; -} - -type Caller = Record; -/** Holds `manage_metadata`; the operator rung, so no wall refuses it. */ -const ADMIN: Caller = { userId: 'u_pkg_admin', systemPermissions: ['manage_metadata', 'studio.access'], posture: 'PLATFORM_ADMIN' }; -/** Signed in, without `manage_metadata`. */ -const NO_CAPABILITY: Caller = { userId: 'u_reader', systemPermissions: ['studio.access'] }; -/** An organization's `manage_metadata` holder below the operator rung. */ -const TENANT_AUTHOR: Caller = { userId: 'u_tenant', tenantId: 'org_a', systemPermissions: ['manage_metadata'], posture: 'TENANT_ADMIN' }; - -type Door = Awaited>; -const adoptInto = async (d: Door, id: string, caller: Caller = ADMIN) => { - const r = await d.dispatcher.handlePackages( - `/${encodeURIComponent(id)}/adopt-orphans`, 'POST', {}, {}, - { request: {}, environmentId: 'pkg-adopt-orphans-readonly-test', executionContext: caller } as any, - ); - expect(r.handled).toBe(true); - return { status: r.response?.status, body: r.response?.body as any }; -}; - -const UNBOUND = Object.fromEntries(ORPHANS.map((n) => [n, null])); -const boundTo = (id: string) => Object.fromEntries(ORPHANS.map((n) => [n, id])); - -// ══════════════════════════════════════════════════════════════════════════════ -// 1. REFUSED: adopting into a read-only package binds nothing -// ══════════════════════════════════════════════════════════════════════════════ - -const READ_ONLY: Array<{ label: string; id: string; booted: boolean }> = [ - { label: 'code-booted (registerApp)', id: CODE_BOOTED, booted: true }, - { label: 'marketplace-installed (registerApp, marketplace)', id: MARKETPLACE, booted: true }, - { label: 'system-scoped stored row (scope signal only)', id: SYSTEM_SCOPED, booted: false }, - { label: 'cloud-scoped stored row (scope signal only)', id: CLOUD_SCOPED, booted: false }, -]; - -describe('POST /packages/:id/adopt-orphans on a read-only package is refused', () => { - for (const pkg of READ_ONLY) { - it(`422s the ${pkg.label} package and binds nothing`, async () => { - const d = await boot(); - expect(await d.bindings(), 'precondition: the producer left orphans').toEqual(UNBOUND); - expect((d.engine as unknown as { manifests: Map }).manifests.has(pkg.id), - 'precondition: the boot signal').toBe(pkg.booted); - - const r = await adoptInto(d, pkg.id); - - expect(r.status).toBe(422); - expect(r.body?.success).toBe(false); - expect(r.body?.error?.code).toBe('WRITABLE_PACKAGE_REQUIRED'); - expect(r.body?.error?.httpStatus).toBe(422); - expect(r.body?.error?.details?.packageId).toBe(pkg.id); - expect(r.body?.error?.details?.docs).toBe('docs/adr/0070-package-first-authoring.md'); - // Nothing was rebound: the protocol was never asked, and the rows say so. - expect(d.adopt).not.toHaveBeenCalled(); - expect(await d.bindings()).toEqual(UNBOUND); - }, 30_000); - } -}); - -// ══════════════════════════════════════════════════════════════════════════════ -// 2. ORDER: which refusal answers when more than one applies to a read-only id -// ══════════════════════════════════════════════════════════════════════════════ - -describe('POST /packages/:id/adopt-orphans — the gate\'s place among the refusals', () => { - it('a caller without manage_metadata is refused 403 by the capability gate first', async () => { - const d = await boot(); - - const r = await adoptInto(d, CODE_BOOTED, NO_CAPABILITY); - - expect(r.status).toBe(403); - expect(r.body?.error?.code).not.toBe('WRITABLE_PACKAGE_REQUIRED'); - expect(String(r.body?.error?.message)).toContain('manage_metadata'); - expect(d.adopt).not.toHaveBeenCalled(); - expect(await d.bindings()).toEqual(UNBOUND); - }, 30_000); - - it('under a wall, a tenant holder is refused 403 PERMISSION_DENIED by the walled refusal first', async () => { - const d = await boot({ posture: 'isolated' }); - - const r = await adoptInto(d, CODE_BOOTED, TENANT_AUTHOR); - - expect(r.status).toBe(403); - expect(r.body?.error?.code).toBe('PERMISSION_DENIED'); - expect(String(r.body?.error?.message)).toContain('tenancy posture'); - expect(d.adopt).not.toHaveBeenCalled(); - expect(await d.bindings()).toEqual(UNBOUND); - }, 30_000); - - it('the gate precedes the protocol: a read-only id answers 422 where a writable id answers 501', async () => { - const d = await boot({ protocolWithoutAdoption: true }); - - const readOnly = await adoptInto(d, CODE_BOOTED); - expect(readOnly.status).toBe(422); - expect(readOnly.body?.error?.code).toBe('WRITABLE_PACKAGE_REQUIRED'); - - const writable = await adoptInto(d, AUTHORED); - expect(writable.status).toBe(501); - expect(writable.body?.error?.code).not.toBe('WRITABLE_PACKAGE_REQUIRED'); - expect(await d.bindings()).toEqual(UNBOUND); - }, 30_000); -}); - -// ══════════════════════════════════════════════════════════════════════════════ -// 3. CONTROL: the gate is not an outage -// ══════════════════════════════════════════════════════════════════════════════ - -describe('POST /packages/:id/adopt-orphans still adopts into what an org owns', () => { - it('a writable package adopts: 200, and every orphan is really bound to it', async () => { - const d = await boot(); - - const r = await adoptInto(d, AUTHORED); - - expect(r.status).toBe(200); - expect(r.body?.data).toMatchObject({ success: true, reassignedCount: ORPHANS.length, targetPackageId: AUTHORED }); - expect(d.adopt).toHaveBeenCalledTimes(1); - expect(await d.bindings()).toEqual(boundTo(AUTHORED)); - }, 30_000); - - it('an id nothing installed is writable by the predicate\'s own rule, so it still reaches the protocol, as before', async () => { - const d = await boot(); - expect(d.engine.registry.getPackage(UNKNOWN), 'precondition: nothing installed it').toBeUndefined(); - - const r = await adoptInto(d, UNKNOWN); - - expect(r.status).toBe(200); - expect(r.body?.error?.code).toBeUndefined(); - expect(d.adopt).toHaveBeenCalledTimes(1); - expect(await d.bindings()).toEqual(boundTo(UNKNOWN)); - }, 30_000); -}); diff --git a/packages/runtime/src/domains/packages-capability-gate.test.ts b/packages/runtime/src/domains/packages-capability-gate.test.ts index 84be52025bc..917b6b200d3 100644 --- a/packages/runtime/src/domains/packages-capability-gate.test.ts +++ b/packages/runtime/src/domains/packages-capability-gate.test.ts @@ -93,7 +93,7 @@ function fullProtocol() { listCommits: vi.fn().mockResolvedValue([{ id: 'c1' }]), revertCommit: vi.fn().mockResolvedValue({ success: true }), rollbackToPackageCommit: vi.fn().mockResolvedValue({ success: true }), - reassignOrphanedMetadata: vi.fn().mockResolvedValue({ reassigned: 0 }), + moveIntoPackage: vi.fn().mockResolvedValue({ outcome: 'moved', targetPackageId: 'pkg-a', moved: [], refused: [] }), duplicatePackage: vi.fn().mockResolvedValue({ package: { id: 'pkg-b' } }), ensureCustomizationPackage: vi.fn().mockResolvedValue({ basePackageId: 'pkg-a', packageId: 'pkg-a.custom', namespace: 'pkg_custom', dependencyRange: '^1', created: true, writable: true }), updatePackage: vi.fn().mockResolvedValue({ package: { manifest: { id: 'com.example.pkg-a' } } }), @@ -176,7 +176,8 @@ const WRITE_ROUTES: WriteCase[] = [ { name: 'POST /:id/discard-drafts', path: '/pkg-a/discard-drafts', method: 'POST', target: (p) => p.discardPackageDrafts }, { name: 'POST /:id/commits/:c/revert', path: '/pkg-a/commits/c1/revert', method: 'POST', target: (p) => p.revertCommit }, { name: 'POST /:id/rollback', path: '/pkg-a/rollback', method: 'POST', body: { commitId: 'c1' }, target: (p) => p.rollbackToPackageCommit }, - { name: 'POST /:id/adopt-orphans', path: '/pkg-a/adopt-orphans', method: 'POST', target: (p) => p.reassignOrphanedMetadata }, + // [#38150] The move door replaced `adopt-orphans` (retired); same gate. + { name: 'POST /:id/move-in', path: '/pkg-a/move-in', method: 'POST', body: { items: [{ type: 'flow', name: 'f1' }] }, target: (p) => p.moveIntoPackage }, { name: 'POST /:id/duplicate', path: '/pkg-a/duplicate', method: 'POST', body: { targetPackageId: 'pkg-b' }, target: (p) => p.duplicatePackage }, { name: 'POST /:id/ensure-customization', path: '/pkg-a/ensure-customization', method: 'POST', target: (p) => p.ensureCustomizationPackage }, { name: 'PATCH /:id (manifest)', path: '/pkg-a', method: 'PATCH', body: { name: 'renamed' }, target: (p) => p.updatePackage }, diff --git a/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts b/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts index 13358bc9f71..bfed2ac7c4b 100644 --- a/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts +++ b/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts @@ -54,7 +54,7 @@ function make(holding: Holding = {}, knowledge?: unknown) { discardPackageDrafts: vi.fn().mockResolvedValue({ success: true, discardedCount: 2 }), revertCommit: vi.fn().mockResolvedValue({ success: true }), rollbackToPackageCommit: vi.fn().mockResolvedValue({ success: true }), - reassignOrphanedMetadata: vi.fn().mockResolvedValue({ reassigned: 0 }), + moveIntoPackage: vi.fn().mockResolvedValue({ outcome: 'moved', targetPackageId: 'pkg-a', moved: [], refused: [] }), duplicatePackage: vi.fn().mockResolvedValue({ package: { id: 'pkg-b' } }), ensureCustomizationPackage: vi.fn().mockResolvedValue({ basePackageId: 'pkg-a', packageId: 'pkg-a.custom', namespace: 'pkg_custom', dependencyRange: '^1', created: true, writable: true }), updatePackage: vi.fn().mockResolvedValue({ package: { manifest: { id: 'com.example.pkg-a' } } }), @@ -121,7 +121,8 @@ const DOORS: Door[] = [ { name: 'POST /:id/commits/:c/revert', path: '/pkg-a/commits/c1/revert', method: 'POST', target: (s) => s.protocol.revertCommit }, { name: 'POST /:id/rollback', path: '/pkg-a/rollback', method: 'POST', body: { commitId: 'c1' }, target: (s) => s.protocol.rollbackToPackageCommit }, { name: 'POST /:id/revert', path: '/pkg-a/revert', method: 'POST', target: (s) => s.protocol.revertStoredPackage }, - { name: 'POST /:id/adopt-orphans', path: '/pkg-a/adopt-orphans', method: 'POST', target: (s) => s.protocol.reassignOrphanedMetadata }, + // [#38150] The move door replaced `adopt-orphans` (retired); same guard one. + { name: 'POST /:id/move-in', path: '/pkg-a/move-in', method: 'POST', body: { items: [{ type: 'flow', name: 'f1' }] }, target: (s) => s.protocol.moveIntoPackage }, { name: 'POST /:id/duplicate', path: '/pkg-a/duplicate', method: 'POST', body: { targetPackageId: 'pkg-b' }, target: (s) => s.protocol.duplicatePackage }, { name: 'PATCH /:id (manifest)', path: '/pkg-a', method: 'PATCH', body: { name: 'renamed' }, target: (s) => s.protocol.updatePackage }, { name: 'DELETE /:id', path: '/pkg-a', method: 'DELETE', tenantId: 'org_a', target: (s) => s.protocol.deletePackage }, diff --git a/packages/runtime/src/domains/packages-protocol-handle-typing.test.ts b/packages/runtime/src/domains/packages-protocol-handle-typing.test.ts index bd498c6d8f2..b9ce8a71b08 100644 --- a/packages/runtime/src/domains/packages-protocol-handle-typing.test.ts +++ b/packages/runtime/src/domains/packages-protocol-handle-typing.test.ts @@ -171,6 +171,9 @@ describe('#13598 · 1 · the compile-time pins are type-level only', () => { }); }); +/** The move door parses its body before it probes the protocol, so it is driven with a body it admits. */ +const MOVE_IN_BODY = { items: [{ type: 'flow', name: 'f1' }] }; + describe('#13598 · 2 · a PARTIAL protocol host is still answered, never crashed', () => { const cases: Array<[string, string, string, string]> = [ ['publish-drafts', '/crm/publish-drafts', 'POST', 'Draft publishing not supported'], @@ -178,15 +181,15 @@ describe('#13598 · 2 · a PARTIAL protocol host is still answered, never crashe ['commits', '/crm/commits', 'GET', 'Commit history not supported'], ['commit revert', '/crm/commits/c1/revert', 'POST', 'Commit revert not supported'], ['rollback', '/crm/rollback', 'POST', 'Commit rollback not supported'], - ['adopt-orphans', '/crm/adopt-orphans', 'POST', 'Orphan adoption not supported'], + // [#38150] `adopt-orphans` retired; the move door that replaced it probes the same way. + ['move-in', '/crm/move-in', 'POST', 'Moving loose items into a package is not supported'], ['duplicate', '/crm/duplicate', 'POST', 'Package duplication not supported'], ]; for (const [label, path, method, message] of cases) { it(`${label} answers 501 from the capability probe`, async () => { - const result = await partialProtocolDoor().handlePackages( - path, method, { commitId: 'c1', targetPackageId: 'crm_copy' }, {}, PKG_ADMIN(), - ); + const body = path.endsWith('/move-in') ? MOVE_IN_BODY : { commitId: 'c1', targetPackageId: 'crm_copy' }; + const result = await partialProtocolDoor().handlePackages(path, method, body, {}, PKG_ADMIN()); expect(result.response?.status).toBe(501); expect(JSON.stringify(result.response?.body)).toContain(message); }); @@ -217,14 +220,15 @@ describe('[#37811] each probe 501 follows the request\'s language', () => { ['/crm/commits', 'GET', 'packages_commit_history_unsupported'], ['/crm/commits/c1/revert', 'POST', 'packages_commit_revert_unsupported'], ['/crm/rollback', 'POST', 'packages_commit_rollback_unsupported'], - ['/crm/adopt-orphans', 'POST', 'packages_orphan_adoption_unsupported'], + ['/crm/move-in', 'POST', 'packages_move_in_unsupported'], ['/crm/duplicate', 'POST', 'packages_duplication_unsupported'], ['/crm/ensure-customization', 'POST', 'packages_customization_ensure_unsupported'], ]; for (const [path, method, key] of cases) { it(key, async () => { for (const [locale, extra] of LANGS_37811) { - const body = path.endsWith('/ensure-customization') ? undefined : { commitId: 'c1', targetPackageId: 'crm_copy' }; + const body = path.endsWith('/ensure-customization') ? undefined + : path.endsWith('/move-in') ? MOVE_IN_BODY : { commitId: 'c1', targetPackageId: 'crm_copy' }; const result = await partialProtocolDoor().handlePackages(path, method, body, {}, { ...PKG_ADMIN(), ...extra }); expect(result.response?.status).toBe(501); expect(result.response?.body?.error?.message).toBe(sentence37811(locale, key)); diff --git a/packages/runtime/src/domains/packages-readonly-remedy-pair-route.test.ts b/packages/runtime/src/domains/packages-readonly-remedy-pair-route.test.ts index f81ff2d1126..49b9bb8ea8d 100644 --- a/packages/runtime/src/domains/packages-readonly-remedy-pair-route.test.ts +++ b/packages/runtime/src/domains/packages-readonly-remedy-pair-route.test.ts @@ -39,6 +39,8 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { SchemaRegistry } from '@objectstack/objectql'; import { HttpDispatcher } from '../http-dispatcher.js'; +// Pay the source's dynamic `@objectstack/metadata` load during collection, never inside a clocked case. +import '@objectstack/metadata'; /** A code-booted package (registered into `engine.manifests`), as the showcase is. */ const CODE_LOADED = 'com.acme.helpdesk'; @@ -95,7 +97,8 @@ const WRITABLE_DOORS: Array<{ verb: string; call: (d: HttpDispatcher, id: string { verb: 'disable', call: (d, id) => d.handlePackages(`/${id}/disable`, 'PATCH', {}, {}, admin()) }, { verb: 'publish', call: (d, id) => d.handlePackages(`/${id}/publish`, 'POST', {}, {}, admin()) }, { verb: 'revert', call: (d, id) => d.handlePackages(`/${id}/revert`, 'POST', {}, {}, admin()) }, - { verb: 'adopt items into', call: (d, id) => d.handlePackages(`/${id}/adopt-orphans`, 'POST', {}, {}, admin()) }, + // [#38150] The move door replaced `adopt-orphans` (retired). + { verb: 'move items into', call: (d, id) => d.handlePackages(`/${id}/move-in`, 'POST', { items: [{ type: 'flow', name: 'f1' }] }, {}, admin()) }, { verb: 'edit', call: (d, id) => d.handlePackages(`/${id}`, 'PATCH', { name: 'Renamed' }, {}, admin()) }, { verb: 'overwrite', diff --git a/packages/runtime/src/domains/packages-vetted-org-source.test.ts b/packages/runtime/src/domains/packages-vetted-org-source.test.ts index 2de803904b9..0fcf66d457e 100644 --- a/packages/runtime/src/domains/packages-vetted-org-source.test.ts +++ b/packages/runtime/src/domains/packages-vetted-org-source.test.ts @@ -71,6 +71,8 @@ import type { IHttpServer } from '@objectstack/spec/contracts'; import { HttpDispatcher } from '../http-dispatcher.js'; import { createDispatcherPlugin } from '../dispatcher-plugin.js'; import { bindCatalogFromTables } from '../security/security-catalog.testkit.js'; +// Pay the source's dynamic `@objectstack/metadata` load during collection, never inside a clocked case. +import '@objectstack/metadata'; const PREFIX = '/api/v1'; const PKG = 'com.acme.crm'; @@ -152,9 +154,11 @@ function protocolDouble() { takeCommit(record('rollbackToPackageCommit', req), req.commitId); return { success: true }; }, - reassignOrphanedMetadata: async (req: any) => { - const reassigned = record('reassignOrphanedMetadata', req).orphans.splice(0); - return { success: true, reassignedCount: reassigned.length, reassigned }; + // [#38150] The move door replaced `adopt-orphans` (retired): it moves the + // selection out of the partition the request reaches. + moveIntoPackage: async (req: any) => { + const moved = record('moveIntoPackage', req).orphans.splice(0); + return { outcome: 'moved', targetPackageId: req.targetPackageId, moved: moved.map((name) => ({ type: 'flow', name })), refused: [] }; }, duplicatePackage: async (req: any) => ({ success: true, copied: [...record('duplicatePackage', req).rows] }), deletePackage: async (req: any) => { @@ -371,7 +375,7 @@ const DOORS: Door[] = [ { name: 'GET /packages/:id/commits', method: 'GET', path: `/packages/${PKG}/commits`, verb: 'listCommits' }, { name: 'POST /packages/:id/commits/:commitId/revert', method: 'POST', path: `/packages/${PKG}/commits/cmt_alpha/revert`, body: {}, verb: 'revertCommit' }, { name: 'POST /packages/:id/rollback', method: 'POST', path: `/packages/${PKG}/rollback`, body: { commitId: 'cmt_alpha' }, verb: 'rollbackToPackageCommit' }, - { name: 'POST /packages/:id/adopt-orphans', method: 'POST', path: `/packages/${PKG}/adopt-orphans`, body: {}, verb: 'reassignOrphanedMetadata' }, + { name: 'POST /packages/:id/move-in', method: 'POST', path: `/packages/${PKG}/move-in`, body: { items: [{ type: 'flow', name: 'shared_orphan' }] }, verb: 'moveIntoPackage' }, { name: 'POST /packages/:id/duplicate', method: 'POST', path: `/packages/${PKG}/duplicate`, body: { targetPackageId: 'com.acme.crm_copy' }, verb: 'duplicatePackage' }, { name: 'DELETE /packages/:id', method: 'DELETE', path: `/packages/${PKG}`, verb: 'deletePackage' }, { name: 'GET /packages/:id/export', method: 'GET', path: `/packages/${PKG}/export`, verb: 'getMetaItems' }, diff --git a/packages/runtime/src/domains/packages-walled-write-refusal.test.ts b/packages/runtime/src/domains/packages-walled-write-refusal.test.ts index 3f1e39ce12b..7660c8db1d8 100644 --- a/packages/runtime/src/domains/packages-walled-write-refusal.test.ts +++ b/packages/runtime/src/domains/packages-walled-write-refusal.test.ts @@ -18,6 +18,8 @@ import { describe, it, expect, vi } from 'vitest'; import { HttpDispatcher } from '../http-dispatcher.js'; +// Pay the source's dynamic `@objectstack/metadata` load during collection, never inside a clocked case. +import '@objectstack/metadata'; const PKG = 'com.example.pkg-a'; @@ -28,7 +30,7 @@ function boot(posture: 'single' | 'isolated' | 'group' | null) { listCommits: vi.fn().mockResolvedValue([{ id: 'c1' }]), revertCommit: vi.fn().mockResolvedValue({ success: true }), rollbackToPackageCommit: vi.fn().mockResolvedValue({ success: true }), - reassignOrphanedMetadata: vi.fn().mockResolvedValue({ reassigned: 0 }), + moveIntoPackage: vi.fn().mockResolvedValue({ outcome: 'moved', targetPackageId: PKG, moved: [], refused: [] }), duplicatePackage: vi.fn().mockResolvedValue({ package: { id: 'com.example.pkg-b' } }), ensureCustomizationPackage: vi.fn().mockResolvedValue({ basePackageId: PKG, packageId: `${PKG}.custom`, namespace: 'pkg_custom', dependencyRange: '^1', created: true, writable: true }), updatePackage: vi.fn().mockResolvedValue({ package: { manifest: { id: PKG } } }), @@ -73,7 +75,8 @@ const DOORS: Array<{ method: string; path: string; body?: unknown; action: strin { method: 'POST', path: `/${PKG}/commits/c1/revert`, body: {}, action: 'Reverting commit "c1"' }, { method: 'POST', path: `/${PKG}/rollback`, body: { commitId: 'c1' }, action: `Rolling back package "${PKG}"` }, { method: 'POST', path: `/${PKG}/revert`, body: {}, action: `Reverting package "${PKG}"` }, - { method: 'POST', path: `/${PKG}/adopt-orphans`, body: {}, action: `Adopting orphaned metadata into package "${PKG}"` }, + // [#38150] The move door replaced `adopt-orphans` (retired). + { method: 'POST', path: `/${PKG}/move-in`, body: { items: [{ type: 'flow', name: 'f1' }] }, action: `Moving loose metadata into package "${PKG}"` }, { method: 'POST', path: `/${PKG}/duplicate`, body: { targetPackageId: 'com.example.pkg-b' }, action: `Duplicating package "${PKG}"` }, { method: 'POST', path: `/${PKG}/ensure-customization`, action: `Ensuring the customization package of "${PKG}"` }, { method: 'DELETE', path: `/${PKG}`, action: `Deleting package "${PKG}"` }, diff --git a/packages/runtime/src/domains/packages-write-actor-session.test.ts b/packages/runtime/src/domains/packages-write-actor-session.test.ts index f2a62008e35..b2911b92077 100644 --- a/packages/runtime/src/domains/packages-write-actor-session.test.ts +++ b/packages/runtime/src/domains/packages-write-actor-session.test.ts @@ -54,7 +54,6 @@ function boot(caller: Record) { discardPackageDrafts: vi.fn(async (_r: any) => ({ success: true, discardedCount: 1, failedCount: 0, discarded: [], failed: [] })), revertCommit: vi.fn(async (_r: any) => ({ success: true })), rollbackToPackageCommit: vi.fn(async (_r: any) => ({ success: true, revertedCommits: [], failed: [] })), - reassignOrphanedMetadata: vi.fn(async (r: any) => ({ success: true, reassignedCount: 0, reassigned: [], targetPackageId: r.targetPackageId })), duplicatePackage: vi.fn(async (r: any) => ({ success: true, copiedCount: 0, failedCount: 0, targetPackageId: r.targetPackageId, copied: [], failed: [] })), // [#31023] Its outcome names the runtime's disable-record cleanup, so the // door leaves the record to the verb and writes no state file here. @@ -86,7 +85,9 @@ const DOORS: Door[] = [ { door: 'POST /packages/:id/discard-drafts', path: `/packages/${PKG}/discard-drafts`, body: {}, act: 'discardPackageDrafts' }, { door: 'POST /packages/:id/commits/:c/revert', path: `/packages/${PKG}/commits/c_1/revert`, body: {}, act: 'revertCommit' }, { door: 'POST /packages/:id/rollback', path: `/packages/${PKG}/rollback`, body: { commitId: 'c_1' }, act: 'rollbackToPackageCommit' }, - { door: 'POST /packages/:id/adopt-orphans', path: `/packages/${PKG}/adopt-orphans`, body: {}, act: 'reassignOrphanedMetadata' }, + // [#38150] `adopt-orphans` retired. The move door that replaced it records the + // session user too, and its strict body refuses an `actor` key outright (400), + // so it has no spoof case to run here. { door: 'POST /packages/:id/duplicate', path: `/packages/${PKG}/duplicate`, body: { targetPackageId: 'com.acme.copy' }, act: 'duplicatePackage' }, ]; diff --git a/packages/runtime/src/domains/packages-write-doors-closed-query.test.ts b/packages/runtime/src/domains/packages-write-doors-closed-query.test.ts index 0fa45362680..851bdc7c6aa 100644 --- a/packages/runtime/src/domains/packages-write-doors-closed-query.test.ts +++ b/packages/runtime/src/domains/packages-write-doors-closed-query.test.ts @@ -14,7 +14,7 @@ * |---|---| * | `DELETE /packages/:id?keepdata=true` (or `?keep_data=true`) | `200`; `deletePackage` received the package id alone, so the protocol dropped the object tables the caller asked to keep | * | `POST /packages?overwrite_existing=true` | the name ignored, the install ran as if it were absent | - * | `PATCH`, `enable`, `disable`, `publish`, `revert`, `rollback`, `commits/:c/revert`, `adopt-orphans`, `duplicate` with any name | `200`; the act performed, the name ignored | + * | `PATCH`, `enable`, `disable`, `publish`, `revert`, `rollback`, `commits/:c/revert`, `adopt-orphans` (retired since, #38150; `move-in` took its place and closes its query the same way), `duplicate` with any name | `200`; the act performed, the name ignored | * * Both halves per door (AGENTS.md route rule 5): a REFUSAL pin — status, * code, the shared sentence over the door's declared set, and the act never @@ -59,7 +59,7 @@ function boot(caller: Record = AUTHOR) { revertStoredPackage: vi.fn(async () => ({ stored: true })), rollbackToPackageCommit: vi.fn(async () => ({ success: true })), revertCommit: vi.fn(async () => ({ success: true })), - reassignOrphanedMetadata: vi.fn(async () => ({ success: true, adoptedCount: 0 })), + moveIntoPackage: vi.fn(async (r: any) => ({ outcome: 'moved', targetPackageId: r.targetPackageId, moved: [], refused: [] })), duplicatePackage: vi.fn(async (r: any) => ({ success: true, copiedCount: 0, failedCount: 0, targetPackageId: r.targetPackageId, copied: [], failed: [] })), ensureCustomizationPackage: vi.fn(async (r: any) => ({ basePackageId: r.basePackageId, packageId: `${r.basePackageId}.custom`, namespace: 'app_custom', dependencyRange: '^1', created: true, writable: true })), }; @@ -70,7 +70,7 @@ function boot(caller: Record = AUTHOR) { revertStoredPackage: acts.revertStoredPackage, rollbackToPackageCommit: acts.rollbackToPackageCommit, revertCommit: acts.revertCommit, - reassignOrphanedMetadata: acts.reassignOrphanedMetadata, + moveIntoPackage: acts.moveIntoPackage, duplicatePackage: acts.duplicatePackage, ensureCustomizationPackage: acts.ensureCustomizationPackage, }; @@ -124,7 +124,7 @@ const DOORS: Door[] = [ { door: 'POST /packages/:id/revert', method: 'POST', path: `/packages/${PKG}/revert`, body: {}, declared: [], act: 'revertStoredPackage', okStatus: 200 }, { door: 'POST /packages/:id/rollback', method: 'POST', path: `/packages/${PKG}/rollback`, body: { commitId: 'c_1' }, declared: [], act: 'rollbackToPackageCommit', okStatus: 200 }, { door: 'POST /packages/:id/commits/:c/revert', method: 'POST', path: `/packages/${PKG}/commits/c_1/revert`, body: {}, declared: [], act: 'revertCommit', okStatus: 200 }, - { door: 'POST /packages/:id/adopt-orphans', method: 'POST', path: `/packages/${PKG}/adopt-orphans`, body: {}, declared: [], act: 'reassignOrphanedMetadata', okStatus: 200 }, + { door: 'POST /packages/:id/move-in', method: 'POST', path: `/packages/${PKG}/move-in`, body: { items: [{ type: 'flow', name: 'f1' }] }, declared: [], act: 'moveIntoPackage', okStatus: 200 }, { door: 'POST /packages/:id/duplicate', method: 'POST', path: `/packages/${PKG}/duplicate`, body: { targetPackageId: 'com.acme.copy' }, declared: [], act: 'duplicatePackage', okStatus: 200 }, { door: 'POST /packages/:id/ensure-customization', method: 'POST', path: `/packages/${PKG}/ensure-customization`, body: {}, declared: [], act: 'ensureCustomizationPackage', okStatus: 201 }, ]; diff --git a/packages/runtime/src/domains/packages.ts b/packages/runtime/src/domains/packages.ts index 63584b7a206..e39fb7e7cc3 100644 --- a/packages/runtime/src/domains/packages.ts +++ b/packages/runtime/src/domains/packages.ts @@ -4,7 +4,7 @@ * `/packages` domain — extracted dispatcher body (ADR-0076 D11 step ③, * PR-5). Package management: list/install/enable/disable, ADR-0033 draft * publish/discard, ADR-0067 commit history & rollback, ADR-0070 export / - * orphan adoption / duplicate, and delete. Since D11 step ② (#3142) the + * the move of loose items / duplicate, and delete. Since D11 step ② (#3142) the * whole family flows through `dispatch()` (single pipeline), which this * extraction preserves — only the body's home changes. */ @@ -299,7 +299,6 @@ export type PackagesDomainProtocol = listCommits?(request: any): Promise; revertCommit?(request: any): Promise; rollbackToPackageCommit?(request: any): Promise; - reassignOrphanedMetadata?(request: any): Promise; moveIntoPackage?(request: { targetPackageId: string; items: ReadonlyArray<{ type: string; name: string; member?: string }>; dryRun?: boolean; actor?: string }): Promise; duplicatePackage?(request: any): Promise; updatePackage?(request: any): Promise; @@ -342,7 +341,7 @@ export function createPackagesDomain(deps: DomainHandlerDeps): DomainRoute { * * Every state-changing package route — install, enable/disable, publish, * publish-drafts, discard-drafts, the ADR-0067 commit revert / rollback / - * revert family, adopt-orphans, duplicate, manifest PATCH and DELETE — demands + * revert family, move-in, duplicate, manifest PATCH and DELETE — demands * the same `manage_metadata` capability the sibling `/meta` writes carry: * #6603 gated the REST `PUT /meta/:type/:name` and #7019 its dispatcher * transport, and `POST /meta/_migrate-stored` gates on the same key. Promoting @@ -447,7 +446,7 @@ type KnowledgeSourcePackageReach = 'drafts' | 'items' | 'history'; * The package doors act on many items at once: publish-drafts makes every * pending draft live, discard-drafts and revert drop them, the commit revert * and the rollback rewrite items from the timeline, duplicate copies a - * package's items into a new one, adopt-orphans binds items to it, and enable, + * package's items into a new one, move-in binds loose items to it, and enable, * disable and delete decide whether its items are served at all. Where one of * those items is a knowledge source the verb does to it what a `/meta` write * would. So the rule is stated on the package and is the same at every door @@ -689,7 +688,7 @@ async function refuseDuplicatedKnowledgeSources( * doors, so attribution cannot drift from authorization. [#28414] Every * package door that stamps history or a commit reads it: `publish-drafts` * (and its app re-save), `discard-drafts`, `commits/:commitId/revert`, - * `rollback`, `adopt-orphans` and `duplicate`, and [#31023] the package + * `rollback`, `move-in` and `duplicate`, and [#31023] the package * `DELETE`, whose verb credits each metadata delete. A body `actor` is ignored, not * refused, so a client still sending one keeps working and is recorded as * itself. No caller acts on behalf of another identity through these doors @@ -849,7 +848,8 @@ function requireCommitTrailReadCapability(deps: DomainHandlerDeps, context: Http * `isolated` and `group`: an organization's `manage_metadata` holder (rung * `TENANT_ADMIN`) answered `2xx` at all thirteen write doors — create, the * manifest `PATCH`, enable, disable, publish, publish-drafts, discard-drafts, - * revert, rollback, `commits/:commitId/revert`, duplicate, adopt-orphans and + * revert, rollback, `commits/:commitId/revert`, duplicate, adopt-orphans + * (since retired; `move-in` took its place and asks the same refusal) and * delete — on packages carrying no catalog item, and another organization's * member read each change (`wall-environment-metadata-refusal.dogfood.test.ts`). * W2 and W3 had refused these doors only when the items a verb acted on @@ -2398,7 +2398,7 @@ const PACKAGE_DELETE_QUERY_PARAMS: readonly string[] = Object.freeze(['keepData' * [#26713 · #26857] The closed query set of every other package write door — * `PATCH /packages/:id`, `…/enable`, `…/disable`, `POST …/publish`, * `…/publish-drafts`, `…/discard-drafts`, `…/revert`, `…/rollback`, - * `…/commits/:commitId/revert`, `…/adopt-orphans` and `…/duplicate`. + * `…/commits/:commitId/revert`, `…/move-in` and `…/duplicate`. * **Measured**: EMPTY. Each reads the path, the session and the body (an * `actor`, a `commitId`, a target id, a manifest patch); none reads a query * parameter, and neither does any helper they call. @@ -4031,48 +4031,6 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin } } - // POST /packages/:id/adopt-orphans → bulk-rebind package-less (legacy - // null / 'sys_metadata') metadata INTO this base (ADR-0070 D5 migration; - // lets the env retire the "Local / Custom" scope once it has no orphans). - if (parts.length === 2 && parts[1] === 'adopt-orphans' && m === 'POST') { - const denied = requireManageMetadata(deps, _context); if (denied) return denied; - const id = decodeURIComponent(parts[0]); - // [ADR-0131 D12 items 7–8] Under a wall, the platform operator's. - const walled = await refuseWalledCatalogPackageWrite(deps, _context, `Adopting orphaned metadata into package "${id}"`); - if (walled) return walled; - // [ADR-0161 K4, guard one] A package that holds a knowledge source - // asks `manage_knowledge_sources` too. - const sourceGate = await refuseKnowledgeSourcePackageWrite(deps, _context, { - packageId: id, action: `Adopting orphaned metadata into package "${id}"`, reach: ['drafts', 'items'], - }); - if (sourceGate) return sourceGate; - const queryRefused = refusePackageWriteDoorQuery(deps, query, PACKAGE_WRITE_NO_QUERY_PARAMS); if (queryRefused) return queryRefused; - // [#24813] ADR-0070 D2: a package the deployment ships is not a - // base, so nothing is adopted into it. `reassignOrphanedMetadata` - // asks no writability question and rebinds every package-less row - // to whatever id it is handed, so this door refuses with the answer - // install-overwrite, disable, publish, revert, the manifest PATCH - // and delete give. Asked BEFORE the protocol is resolved, so a - // read-only id answers 422 whether or not this deployment can - // adopt. An id nothing installed is writable by the predicate's own - // rule, so it still reaches the protocol. - const readOnly = requireWritablePackage(deps, qlService, id, 'adopt items into'); if (readOnly) return readOnly; - const protocol = await resolveProtocol(deps, _context); - if (!protocol || typeof protocol.reassignOrphanedMetadata !== 'function') { - return catalogNotImplemented(deps, _context, 'packages_orphan_adoption_unsupported'); - } - try { - const actor = resolvePackageWriteActor(_context); - const result = await protocol.reassignOrphanedMetadata({ - targetPackageId: id, - ...(actor !== undefined ? { actor } : {}), - }); - return { handled: true, response: deps.success(result) }; - } catch (e: any) { - return { handled: true, response: deps.errorFromThrown(e, 500) }; - } - } - // POST /packages/:id/move-in → move a SELECTION of loose items into // this package (ADR-0084 amendment of 2026-11-26, "Loose items stay // where they are, and one door moves them"). Body diff --git a/packages/runtime/src/package-duplicate-adopt-org-scope.integration.test.ts b/packages/runtime/src/package-duplicate-adopt-org-scope.integration.test.ts index dd4e5c824e1..9c7f7cafb7f 100644 --- a/packages/runtime/src/package-duplicate-adopt-org-scope.integration.test.ts +++ b/packages/runtime/src/package-duplicate-adopt-org-scope.integration.test.ts @@ -4,6 +4,14 @@ // `protocol.reassignOrphanedMetadata` each scanned `sys_metadata` with a strict // `organization_id` equality, so an org-scoped caller could not see any row // recorded env-wide (`organization_id IS NULL`). +// +// [#38150] `reassignOrphanedMetadata` (the adopt-orphans door) is retired; its +// half of this suite went with it. The move door that replaced it +// (`moveIntoPackage`) reads the environment's rows through the same +// `findEnvironmentRows` and is pinned on a booted stack by +// `qa/dogfood/test/package-move-in.dogfood.test.ts`. What stays below is the +// duplicate half, and the measurement that a package-less save writes an +// env-wide loose row. import { describe, it, expect, afterEach } from 'vitest'; import { mkdtempSync, rmSync } from 'node:fs'; @@ -257,16 +265,15 @@ describe('#7819 tier 2 — duplicatePackage must copy the source’s env-wide ro }); }); -describe('#7819 tier 2 — reassignOrphanedMetadata must see env-wide orphans', () => { +describe('#7819 tier 2 — a package-less save writes an env-wide loose row', () => { it('a package-less saveMetaItem still mints an env-wide orphan TODAY (why this is live, not legacy)', async () => { const { engine, protocol } = await boot(); - // The docstring on `reassignOrphanedMetadata` describes orphans as a - // pre-package-first residue, and ADR-0070 D1 does reject a new orphan that - // names a READ-ONLY package (`WRITABLE_PACKAGE_REQUIRED`). But naming no - // package at all is still accepted, and lands both columns NULL — so the - // population this method exists to find is still being produced, in exactly - // the scope an org-scoped caller could not see. This case is the reason the + // ADR-0070 D1 rejects a new loose row that names a READ-ONLY package + // (`WRITABLE_PACKAGE_REQUIRED`). But naming no package at all is still + // accepted, and lands both columns NULL — the loose population the move + // door (`moveIntoPackage`, #38150) reads, in exactly the scope an + // org-scoped caller once could not see. This case is the reason the // measurement came back live instead of latent. const res = await (protocol as any).saveMetaItem({ type: 'view', @@ -280,21 +287,4 @@ describe('#7819 tier 2 — reassignOrphanedMetadata must see env-wide orphans', { name: 'loose_view', org: null, pkg: null }, ]); }); - - it('leaves OWNED rows alone — an env-wide row bound to a real package is not an orphan', async () => { - const { engine, protocol } = await boot(); - const p = protocol as any; - // Env-wide, so the widened scan now RETURNS it; it must still be filtered - // out by the orphan test rather than adopted. Widening the scan must not - // widen what counts as an orphan. - await publish(p, { type: 'view', name: 'iojn_env', packageId: SRC }); - await p.saveMetaItem({ type: 'view', name: 'orph_env', item: viewBody('orph_env'), mode: 'publish' }); - - const res = await p.reassignOrphanedMetadata({ - targetPackageId: DST, - }); - - expect(res.reassigned.map((r: any) => r.name)).toEqual(['orph_env']); - expect((await rowsOf(engine)).find((r) => r.name === 'iojn_env')?.pkg).toBe(SRC); - }); }); diff --git a/packages/runtime/src/route-ledger.ts b/packages/runtime/src/route-ledger.ts index b79b800457c..4d0a072a8e6 100644 --- a/packages/runtime/src/route-ledger.ts +++ b/packages/runtime/src/route-ledger.ts @@ -301,7 +301,7 @@ export const NON_DISPATCH_MOUNT_PREFIXES = [ /** * The ledger. * - * CENSUS (generated): this list holds 158 rows. + * CENSUS (generated): this list holds 157 rows. * * ⛔ THAT NUMBER IS WRITTEN BY A TOOL — never by hand. * `pnpm check:route-ledger-census` counts the rows below and fails when the two @@ -587,9 +587,6 @@ export const ROUTE_LEDGER: readonly RouteLedgerEntry[] = [ { route: 'GET /packages/:id/customizations', domain: '/packages', disposition: 'sdk', client: 'packages.customizations', responseSchema: 'GetPackageCustomizationsResponseSchema', note: 'Enveloped — the named schema is the `data`. A new route whose declaration is its contract, not a transcription: for an installed base, its `.custom` pair\'s served overrides (the served-override predicate the effective read asks, never re-derived), the fields, validations and indexes the pair\'s object extensions add to objects the base owns, each whole arrangement those extensions write (`fieldGroups`, `relatedLists`, `actionLayout`: one entry per object and key, named, never copied), the base\'s `active: false` activation-ledger rows, and every field and flow another package contributes to the base\'s objects, each entry naming its package, with each list\'s length. Same read gate and 404 wording as `GET /packages/:id`; closed query set (none), declared with the path id in `GetPackageCustomizationsRequestSchema` (no `requestSchema` here: that field names a JSON body, and a GET reads none); a `.custom` id refused 400 `VALIDATION_ERROR` naming its base; no pair answers empty lists and never creates one. Pinned in `domains/packages-customizations.test.ts`, which drives THIS handler over the real protocol and parses the payload through the response schema' }, - { route: 'POST /packages/:id/adopt-orphans', domain: '/packages', disposition: 'sdk', client: 'packages.adoptOrphans', - responseSchema: 'ReassignOrphanedMetadataResponseSchema', - note: 'Enveloped — the named schema is the `data`: `reassignOrphanedMetadata`\'s declared return, transcribed describe-only. Conformance: spec `api/package-lifecycle.test.ts`' }, // [ADR-0084 amendment of 2026-11-26] The move door: a selection of loose items into one package. { route: 'POST /packages/:id/move-in', domain: '/packages', disposition: 'sdk', client: 'packages.moveIn', requestSchema: 'MoveIntoPackageRequestSchema', diff --git a/packages/spec/api-surface/api.json b/packages/spec/api-surface/api.json index fdaf4764e36..8a960d9db4e 100644 --- a/packages/spec/api-surface/api.json +++ b/packages/spec/api-surface/api.json @@ -1001,9 +1001,6 @@ "RealtimeUnsubscribeRequestSchema (const)", "RealtimeUnsubscribeResponse (type)", "RealtimeUnsubscribeResponseSchema (const)", - "ReassignOrphanedMetadataResponse (type)", - "ReassignOrphanedMetadataResponseParsed (type)", - "ReassignOrphanedMetadataResponseSchema (const)", "RecordData (type)", "RecordDataSchema (const)", "RecordPageActivityRequest (type)", diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index e5d83765bc4..9e8e5e2f5ca 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -1635,10 +1635,6 @@ "api/RealtimeSubscribeResponse:subscriptionId", "api/RealtimeUnsubscribeRequest:subscriptionId", "api/RealtimeUnsubscribeResponse:success", - "api/ReassignOrphanedMetadataResponse:reassigned", - "api/ReassignOrphanedMetadataResponse:reassignedCount", - "api/ReassignOrphanedMetadataResponse:success", - "api/ReassignOrphanedMetadataResponse:targetPackageId", "api/RecordPageActivityRequest:top", "api/RecordPageApprovals:lock", "api/RecordPageApprovals:requests", diff --git a/packages/spec/declaration-map/api.json b/packages/spec/declaration-map/api.json index 1222e449d62..d590a2b762d 100644 --- a/packages/spec/declaration-map/api.json +++ b/packages/spec/declaration-map/api.json @@ -741,8 +741,6 @@ "RealtimeUnsubscribeRequestSchema": "api/RealtimeUnsubscribeRequest", "RealtimeUnsubscribeResponse": "api/RealtimeUnsubscribeResponse", "RealtimeUnsubscribeResponseSchema": "api/RealtimeUnsubscribeResponse", - "ReassignOrphanedMetadataResponse": "api/ReassignOrphanedMetadataResponse", - "ReassignOrphanedMetadataResponseSchema": "api/ReassignOrphanedMetadataResponse", "RecordData": "api/RecordData", "RecordDataSchema": "api/RecordData", "RecordPageActivityRequest": "api/RecordPageActivityRequest", diff --git a/packages/spec/export-origins/api.json b/packages/spec/export-origins/api.json index f2af4b6adb4..d218e9d6b2d 100644 --- a/packages/spec/export-origins/api.json +++ b/packages/spec/export-origins/api.json @@ -970,9 +970,6 @@ "RealtimeUnsubscribeRequestSchema": "src/api/protocol.zod.ts#RealtimeUnsubscribeRequestSchema (const)", "RealtimeUnsubscribeResponse": "src/api/protocol.zod.ts#RealtimeUnsubscribeResponse (type)", "RealtimeUnsubscribeResponseSchema": "src/api/protocol.zod.ts#RealtimeUnsubscribeResponseSchema (const)", - "ReassignOrphanedMetadataResponse": "src/api/package-lifecycle.zod.ts#ReassignOrphanedMetadataResponse (type)", - "ReassignOrphanedMetadataResponseParsed": "src/api/package-lifecycle.zod.ts#ReassignOrphanedMetadataResponseParsed (type)", - "ReassignOrphanedMetadataResponseSchema": "src/api/package-lifecycle.zod.ts#ReassignOrphanedMetadataResponseSchema (const)", "RecordData": "src/api/contract.zod.ts#RecordData (type)", "RecordDataSchema": "src/api/contract.zod.ts#RecordDataSchema (const)", "RecordPageActivityRequest": "src/api/record-page.zod.ts#RecordPageActivityRequest (type)", diff --git a/packages/spec/json-schema.manifest/api.json b/packages/spec/json-schema.manifest/api.json index 86863253141..b381d11e884 100644 --- a/packages/spec/json-schema.manifest/api.json +++ b/packages/spec/json-schema.manifest/api.json @@ -399,7 +399,6 @@ "api/RealtimeSubscribeResponse", "api/RealtimeUnsubscribeRequest", "api/RealtimeUnsubscribeResponse", - "api/ReassignOrphanedMetadataResponse", "api/RecordData", "api/RecordPageActivityRequest", "api/RecordPageApprovals", diff --git a/packages/spec/src/api/package-lifecycle.test.ts b/packages/spec/src/api/package-lifecycle.test.ts index 3d6ce2d39e0..db771211ce6 100644 --- a/packages/spec/src/api/package-lifecycle.test.ts +++ b/packages/spec/src/api/package-lifecycle.test.ts @@ -17,7 +17,6 @@ import { RollbackToPackageCommitResponseSchema, PackageExportManifestSchema, PackageExportBundleSchema, - ReassignOrphanedMetadataResponseSchema, MoveIntoPackageRequestSchema, MoveIntoPackageResponseSchema, DuplicatePackageResponseSchema, @@ -406,30 +405,6 @@ describe('PackageExportBundleSchema declares the whole-deployment export as comp }); }); -describe('ReassignOrphanedMetadataResponseSchema declares the adopt-orphans body', () => { - /** A verbatim-shaped capture of a real `reassignOrphanedMetadata` return. */ - const realResponse = { - success: true, - reassignedCount: 2, - reassigned: [ - { type: 'view', name: 'orphan_view' }, - { type: 'flow', name: 'orphan_flow' }, - ], - targetPackageId: 'com.example.crm', - }; - - it('parses the real adoption report and PRESERVES every member', () => { - const result = ReassignOrphanedMetadataResponseSchema.safeParse(realResponse); - expect(result.success).toBe(true); - if (result.success) expect(result.data).toEqual(realResponse); - }); - - it('the honest-empty report parses — no orphans to adopt is a declared, legal body', () => { - const empty = { success: true, reassignedCount: 0, reassigned: [], targetPackageId: 'com.example.crm' }; - expect(ReassignOrphanedMetadataResponseSchema.safeParse(empty).success).toBe(true); - }); -}); - describe('MoveIntoPackageRequestSchema declares the move door\'s body (#38150)', () => { it('takes a selection of one or more items, each with an optional member, and an optional dryRun', () => { const body = { diff --git a/packages/spec/src/api/package-lifecycle.zod.ts b/packages/spec/src/api/package-lifecycle.zod.ts index 6f0df3b5791..3442ffb07b9 100644 --- a/packages/spec/src/api/package-lifecycle.zod.ts +++ b/packages/spec/src/api/package-lifecycle.zod.ts @@ -360,23 +360,6 @@ export const PackageExportBundleSchema = lazySchema(() => z.object({ + 'assembled fails the whole read, naming it.', )); -/** - * `POST /packages/:id/adopt-orphans` — bulk-rebind package-less (orphaned) - * metadata into this base (ADR-0070 D5); the client method is - * `packages.adoptOrphans`. - * - * Transcribed from `reassignOrphanedMetadata`'s declared return. - */ -export const ReassignOrphanedMetadataResponseSchema = lazySchema(() => z.object({ - success: z.boolean().describe('Whether the reassignment ran.'), - reassignedCount: z.number().describe('How many orphaned items were adopted.'), - reassigned: z.array(z.object({ - type: z.string().describe('Metadata type of the adopted item.'), - name: z.string().describe('Name of the adopted item.'), - })).describe('Every item that was adopted.'), - targetPackageId: z.string().describe('The package the items were adopted into.'), -})); - /** * One item a move names: the item's metadata type and name, and for a bundled * type (an email template's locale) the one member. See @@ -877,9 +860,6 @@ export type PackageExportManifestParsed = z.infer; /** Post-parse shape of {@link PackageExportBundle} — defaults applied, transforms run (ADR-0122). */ export type PackageExportBundleParsed = z.infer; -export type ReassignOrphanedMetadataResponse = z.input; -/** Post-parse shape of {@link ReassignOrphanedMetadataResponse} — defaults applied, transforms run (ADR-0122). */ -export type ReassignOrphanedMetadataResponseParsed = z.infer; export type MoveIntoPackageItem = z.input; /** Post-parse shape of {@link MoveIntoPackageItem} — defaults applied, transforms run (ADR-0122). */ export type MoveIntoPackageItemParsed = z.infer; diff --git a/packages/spec/src/migrations/entries/retired-defs/19.api__ReassignOrphanedMetadataResponse.ts b/packages/spec/src/migrations/entries/retired-defs/19.api__ReassignOrphanedMetadataResponse.ts new file mode 100644 index 00000000000..241563822af --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-defs/19.api__ReassignOrphanedMetadataResponse.ts @@ -0,0 +1,10 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// #38150 (ADR-0084 amendment of 2026-11-26, "Loose items stay where they are, +// and one door moves them"): `POST /packages/:id/adopt-orphans` and the +// client's `packages.adoptOrphans` are retired, so the response def they +// answered with leaves with them. The move door, `POST /packages/:id/move-in` +// (`MoveIntoPackageResponse`, `packages.moveIn`), moves an explicit selection +// in its place. A response shape, never authored metadata: nothing stored +// carries it, so no stored body needs a conversion. +export const entry = 'api/ReassignOrphanedMetadataResponse'; diff --git a/packages/spec/src/migrations/entries/semantic/19.packages-adopt-orphans-door-retired.ts b/packages/spec/src/migrations/entries/semantic/19.packages-adopt-orphans-door-retired.ts new file mode 100644 index 00000000000..e5ed28613ed --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.packages-adopt-orphans-door-retired.ts @@ -0,0 +1,31 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// #38150 (ADR-0084 amendment of 2026-11-26, "Loose items stay where they are, +// and one door moves them") — a runtime-door retirement with no authorable +// key: the all-at-once adoption of every loose item is gone, and the move door +// takes an explicit selection in its place. Registered because a caller that +// ran the old door is answered 404 now, and must be told where the move went. +export const entry: SemanticMigration = { + id: 'packages-adopt-orphans-door-retired', + surface: + 'POST /api/v1/packages/:id/adopt-orphans on the runtime dispatcher, the client\'s ' + + '`packages.adoptOrphans(id)`, the protocol\'s `reassignOrphanedMetadata`, and the ' + + '`ReassignOrphanedMetadataResponseSchema` response def of `@objectstack/spec/api`', + replacement: + 'POST /api/v1/packages/:id/move-in with `{ items: [{ type, name, member? }], dryRun? }` ' + + '(`client.packages.moveIn(id, { items })`, `moveIntoPackage`, `MoveIntoPackageResponseSchema`): ' + + 'name the loose items to move. To move every loose item, list them (the loose rows are the ' + + 'package-less ones) and pass them all; each is judged by the save door, and the move is whole or nothing', + reason: + 'ADR-0084\'s amendment of 2026-11-26: a loose item stays where it is unless an author moves it. ' + + 'The old door rebound every package-less row of the environment with a bare storage update and ' + + 'asked none of the save door\'s questions, so it could adopt into a package nothing installed, ' + + 'adopt an object its target\'s namespace prefix refuses, and leave the runtime serving the old ' + + 'address until a restart.', + acceptanceCriteria: + 'On a booted stack, POST /api/v1/packages//adopt-orphans answers ' + + '404 and every loose row stays loose; POST /api/v1/packages//move-in naming a loose flow ' + + 'moves it into the package, read at the package\'s address with no restart.', +}; diff --git a/packages/spec/src/system/operation-message.test.ts b/packages/spec/src/system/operation-message.test.ts index 5b66896d3a9..71d861938f2 100644 --- a/packages/spec/src/system/operation-message.test.ts +++ b/packages/spec/src/system/operation-message.test.ts @@ -794,9 +794,10 @@ describe('operation message catalog — the domain modules\' 501 sentences (#378 /^(auth_service_unavailable|i18n_service_unavailable|mcp_server_unavailable|meta_|packages_|automation_(connector|flow|resume|run|screen)|action_activation_|catalog_activation_|permission_set_clone_|security_audience_|share_links_)/.test(key), ); - // [#38150] +1: `packages_move_in_unsupported`, the move-in door's 501. - it('names the thirty-eight keys (thirty-two sentences, six activation nouns)', () => { - expect(KEYS).toHaveLength(38); + // [#38150] `packages_move_in_unsupported` (the move-in door's 501) in, + // `packages_orphan_adoption_unsupported` (the retired adopt-orphans door's) out. + it('names the thirty-seven keys (thirty-one sentences, six activation nouns)', () => { + expect(KEYS).toHaveLength(37); }); it.each(KEYS)('%s: every locale translates it and keeps the English placeholders', (key) => { diff --git a/packages/spec/src/system/operation-message.ts b/packages/spec/src/system/operation-message.ts index b7b02697e04..b8f3a5ed690 100644 --- a/packages/spec/src/system/operation-message.ts +++ b/packages/spec/src/system/operation-message.ts @@ -526,7 +526,6 @@ export const BUILTIN_OPERATION_MESSAGES: Record> packages_commit_history_unsupported: 'Commit history not supported', packages_commit_revert_unsupported: 'Commit revert not supported', packages_commit_rollback_unsupported: 'Commit rollback not supported', - packages_orphan_adoption_unsupported: 'Orphan adoption not supported', packages_move_in_unsupported: 'Moving loose items into a package is not supported', packages_duplication_unsupported: 'Package duplication not supported', packages_customization_ensure_unsupported: 'Customization package ensure not supported', @@ -651,7 +650,6 @@ export const BUILTIN_OPERATION_MESSAGES: Record> packages_commit_history_unsupported: '不支持查看提交历史。', packages_commit_revert_unsupported: '不支持撤销提交。', packages_commit_rollback_unsupported: '不支持回滚到某次提交。', - packages_orphan_adoption_unsupported: '不支持认领孤立的元数据。', packages_move_in_unsupported: '不支持把散落项移入软件包。', packages_duplication_unsupported: '不支持复制软件包。', packages_customization_ensure_unsupported: '不支持确保定制包存在。', @@ -790,7 +788,6 @@ export const BUILTIN_OPERATION_MESSAGES: Record> packages_commit_history_unsupported: 'コミット履歴はサポートされていません。', packages_commit_revert_unsupported: 'コミットの取り消しはサポートされていません。', packages_commit_rollback_unsupported: 'コミットへのロールバックはサポートされていません。', - packages_orphan_adoption_unsupported: '孤立したメタデータの引き取りはサポートされていません。', packages_move_in_unsupported: '未所属のメタデータをパッケージへ移動する操作はサポートされていません。', packages_duplication_unsupported: 'パッケージの複製はサポートされていません。', packages_customization_ensure_unsupported: 'カスタマイズパッケージの確保はサポートされていません。', @@ -945,7 +942,6 @@ export const BUILTIN_OPERATION_MESSAGES: Record> packages_commit_history_unsupported: 'No se admite el historial de confirmaciones.', packages_commit_revert_unsupported: 'No se admite revertir una confirmación.', packages_commit_rollback_unsupported: 'No se admite restaurar una confirmación anterior.', - packages_orphan_adoption_unsupported: 'No se admite adoptar metadatos huérfanos.', packages_move_in_unsupported: 'No se admite mover metadatos sueltos a un paquete.', packages_duplication_unsupported: 'No se admite duplicar paquetes.', packages_customization_ensure_unsupported: 'No se admite asegurar el paquete de personalización.', diff --git a/scripts/check-engine-double-contract.mjs b/scripts/check-engine-double-contract.mjs index 6bad367f25e..47cb7f7d1ec 100644 --- a/scripts/check-engine-double-contract.mjs +++ b/scripts/check-engine-double-contract.mjs @@ -1848,8 +1848,9 @@ function censusReport() { // property of one (`request.id`, `params.id`). An id read off a row this // function just fetched (`row.id`, `existing.id`) cannot name a missing // record -- it came from one. This conjunct removes 29 sites, and it is -// the one that keeps `reassignOrphanedMetadata` and `rebuildApproverIndex` -// out: both answer a receipt, both write by an id they just read. +// the one that keeps `rebuildApproverIndex` (and, until it retired with +// #38150, `reassignOrphanedMetadata`) out: it answers a receipt and writes +// by an id it just read. // // 3. and ANSWERS A RECEIPT 4 sites // returns an object literal carrying `success` / `record` / `deleted` / @@ -4476,8 +4477,8 @@ ${body} s.length === 1 && s[0].refusal === null); // Conjunct 2: an id read off a row this function already fetched cannot name - // a missing record. `reassignOrphanedMetadata` and `rebuildApproverIndex` are - // this shape and must stay out — they answer receipts and probe nothing. + // a missing record. `rebuildApproverIndex` is this shape and must stay out — + // it answers a receipt and probes nothing. const rowIdBody = ` const row = await this.engine.findOne(request.object, {}); await this.engine.update(request.object, request.data, { where: { id: row.id } }); diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 1ef3abcf564..583fdde9e22 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -436,16 +436,6 @@ "verb": "update", "pinned": 1 }, - { - "file": "packages/metadata-protocol/src/protocol.adopt-orphans-owner-judges.test.ts", - "verb": "findOne", - "pinned": 1 - }, - { - "file": "packages/metadata-protocol/src/protocol.adopt-orphans-owner-judges.test.ts", - "verb": "update", - "pinned": 1 - }, { "file": "packages/metadata-protocol/src/protocol.adr0005-org-override-rollback.test.ts", "verb": "delete", diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.adoptLooseItems-13339.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.adoptLooseItems-13339.test.tsx deleted file mode 100644 index 8f273cd1c69..00000000000 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.adoptLooseItems-13339.test.tsx +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#13339 — the package sheet's *Adopt loose items*, and the sheet's - * one message line. - * - * Before: *Adopt loose items* asked with the browser's native - * `window.confirm`, then said "Loose items adopted into this base." whatever - * moved, so an adoption that found nothing read as one that did. And the - * message line kept the previous action's answer: a Revert refusal still - * stood under the Duplicate form opened after it. - * - * After, pinned here through the real `PackageDetailSheet`: - * - Adopt asks in an in-app dialog, never `window.confirm`; its Cancel sends - * nothing, and its confirm sends one `POST …/adopt-orphans`. - * - The answer reports the server's own `reassignedCount` - * (`ReassignOrphanedMetadataResponse`), 0 included, and a 0 (whose own - * `success` is false) is reported as a count, not as a failure. - * - Starting any action on the sheet clears the previous action's message, - * including the actions that first open a dialog or a form. - * - * Every request is recorded by the fetch stub, so "sends nothing" is read off - * the wire, not off the UI. - */ - -import * as React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; - -import { PackageDetailSheet, type InstalledPackageRow } from './PackagesPage'; -// Loaded at import so their first load is not paid inside a test's clocked window. -import '@objectstack/formula'; -import '@objectstack/lint'; - -const PKG_ID = 'com.acme.crm'; -const PKG_NAME = 'Acme CRM'; -const PKG: InstalledPackageRow = { - manifest: { id: PKG_ID, name: PKG_NAME, version: '1.0.0', type: 'app' }, - enabled: true, - status: 'installed', - source: 'authored', - writable: true, - // A writable base is disableable too (objectstack#28318): the sheet offers - // Disable from this verdict alone. - disableable: true, -}; -const DRAFTS = [ - { type: 'object', name: 'acme_lead' }, - { type: 'view', name: 'acme_lead_list' }, -]; -const REVERT_REFUSAL = 'Nothing to revert on this package'; - -type Call = { url: string; method: string }; -let calls: Call[]; -/** What `POST /adopt-orphans` answers; a test may replace it. */ -let adoptAnswer: unknown; -let confirmSpy: ReturnType; -let savedConfirm: PropertyDescriptor | undefined; - -function respond(body: unknown, status = 200) { - const text = JSON.stringify(body); - return { - ok: status >= 200 && status < 300, - status, - headers: new Headers(), - text: async () => text, - json: async () => JSON.parse(text), - } as unknown as Response; -} - -/** The adopt door's answer: the envelope around `ReassignOrphanedMetadataResponse`. */ -function adopted(items: Array<{ type: string; name: string }>) { - return { - success: true, - data: { - // The producer's own verdict: true exactly when something moved. - success: items.length > 0, - reassignedCount: items.length, - reassigned: items, - targetPackageId: PKG_ID, - }, - }; -} - -beforeEach(() => { - calls = []; - adoptAnswer = adopted([ - { type: 'object', name: 'loose_a' }, - { type: 'view', name: 'loose_b' }, - { type: 'flow', name: 'loose_c' }, - ]); - vi.stubGlobal( - 'fetch', - vi.fn(async (input: string, init: RequestInit = {}) => { - const method = (init.method ?? 'GET').toUpperCase(); - calls.push({ url: input, method }); - if (input.startsWith('/api/v1/meta/_drafts')) { - return respond({ success: true, data: { drafts: DRAFTS } }); - } - if (input.endsWith('/adopt-orphans')) return respond(adoptAnswer); - if (input.endsWith('/revert')) { - return respond({ success: false, error: { code: 'NOTHING_TO_REVERT', message: REVERT_REFUSAL } }, 409); - } - return respond({ success: true, data: {} }); - }), - ); - // happy-dom implements no `confirm`; a spy observes (and answers OK to) a - // native call, so a regression would send the POST and still be caught. - savedConfirm = Object.getOwnPropertyDescriptor(window, 'confirm'); - confirmSpy = vi.fn(() => true); - Object.defineProperty(window, 'confirm', { configurable: true, writable: true, value: confirmSpy }); -}); - -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); - if (savedConfirm) Object.defineProperty(window, 'confirm', savedConfirm); - else delete (window as unknown as Record).confirm; -}); - -function renderSheet() { - const onChanged = vi.fn(); - render( - - - , - ); - return { onChanged }; -} - -const adoptPosts = () => calls.filter((c) => c.method === 'POST' && c.url.endsWith('/adopt-orphans')); - -/** Let any handler the click scheduled run before reading the wire. */ -async function settle() { - await act(async () => { - await new Promise((r) => setTimeout(r, 0)); - }); -} - -async function openAdoptDialog() { - fireEvent.click(await screen.findByRole('button', { name: 'Adopt loose items' })); - return screen.findByTestId('pkg-detail-adopt-dialog'); -} - -async function adoptAndConfirm() { - const dialog = await openAdoptDialog(); - fireEvent.click(within(dialog).getByTestId('pkg-detail-adopt-confirm')); - await settle(); -} - -describe('PackageDetailSheet — Adopt loose items asks in-app (objectui#13339)', () => { - it('opens an in-app dialog naming the package, never window.confirm, and sends nothing yet', async () => { - renderSheet(); - const dialog = await openAdoptDialog(); - expect(within(dialog).getByText(`Adopt loose items into "${PKG_NAME}"?`)).toBeInTheDocument(); - await settle(); - expect(confirmSpy).not.toHaveBeenCalled(); - expect(adoptPosts()).toEqual([]); - }); - - it('its Cancel sends no request and reports nothing', async () => { - const { onChanged } = renderSheet(); - const dialog = await openAdoptDialog(); - fireEvent.click(within(dialog).getByTestId('pkg-detail-adopt-cancel')); - await waitFor(() => expect(screen.queryByTestId('pkg-detail-adopt-dialog')).toBeNull()); - await settle(); - expect(adoptPosts()).toEqual([]); - expect(onChanged).not.toHaveBeenCalled(); - expect(screen.queryByText(/adopted into this base/)).toBeNull(); - }); - - it('its confirm sends one POST and closes the dialog', async () => { - const { onChanged } = renderSheet(); - await adoptAndConfirm(); - expect(adoptPosts()).toHaveLength(1); - expect(adoptPosts()[0].url).toBe(`/api/v1/packages/${encodeURIComponent(PKG_ID)}/adopt-orphans`); - await waitFor(() => expect(screen.queryByTestId('pkg-detail-adopt-dialog')).toBeNull()); - expect(onChanged).toHaveBeenCalledTimes(1); - expect(confirmSpy).not.toHaveBeenCalled(); - }); -}); - -describe('PackageDetailSheet — Adopt reports the server count (objectui#13339)', () => { - it('reports the answer’s reassignedCount', async () => { - renderSheet(); - await adoptAndConfirm(); - expect(await screen.findByText('3 items adopted into this base.')).toBeInTheDocument(); - }); - - it('reports 0 when nothing moved: a count, not "adopted" and not a failure', async () => { - adoptAnswer = adopted([]); - renderSheet(); - await adoptAndConfirm(); - expect(await screen.findByText('0 items adopted into this base.')).toBeInTheDocument(); - expect(screen.queryByText('Loose items adopted into this base.')).toBeNull(); - }); - - it('says "1 item" for one', async () => { - adoptAnswer = adopted([{ type: 'object', name: 'loose_a' }]); - renderSheet(); - await adoptAndConfirm(); - expect(await screen.findByText('1 item adopted into this base.')).toBeInTheDocument(); - }); -}); - -describe('PackageDetailSheet — starting an action clears the previous message (objectui#13339)', () => { - async function showRevertRefusal() { - fireEvent.click(await screen.findByRole('button', { name: 'Revert' })); - expect(await screen.findByText(REVERT_REFUSAL, { exact: false })).toBeInTheDocument(); - } - - // Each opens a dialog or a form before anything runs: the press that opens - // it is where the action starts. - it.each([ - ['Duplicate'], - ['Delete package'], - ['Disable'], - ['Adopt loose items'], - [`Discard changes (${DRAFTS.length})`], - ['View info'], - ['Edit'], - ])('a Revert refusal is gone once %s is pressed', async (label) => { - renderSheet(); - await showRevertRefusal(); - fireEvent.click(await screen.findByRole('button', { name: label })); - await settle(); - expect(screen.queryByText(REVERT_REFUSAL, { exact: false })).toBeNull(); - }); - - it('an Adopt count is gone once Duplicate is pressed', async () => { - renderSheet(); - await adoptAndConfirm(); - expect(await screen.findByText('3 items adopted into this base.')).toBeInTheDocument(); - fireEvent.click(await screen.findByRole('button', { name: 'Duplicate' })); - await settle(); - expect(screen.queryByText('3 items adopted into this base.')).toBeNull(); - expect(screen.getByTestId('pkg-detail-dup-form')).toBeInTheDocument(); - }); -}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.installedAppsUpdates-34722.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.installedAppsUpdates-34722.test.tsx index f770ea46cde..7faf987016f 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.installedAppsUpdates-34722.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.installedAppsUpdates-34722.test.tsx @@ -656,7 +656,6 @@ describe('Setup → Packages: the administration face (objectstack#36834)', () = 'engine.packages.detail.revert', 'engine.packages.detail.export', 'engine.packages.detail.duplicate', - 'engine.packages.detail.adoptOrphans', ]; it('the detail sheet offers View info, Disable and Delete, and links an authored package to Studio', async () => { diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.moduleDisable-28118.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.moduleDisable-28118.test.tsx index 0d7f13204e7..fa0f4911311 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.moduleDisable-28118.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.moduleDisable-28118.test.tsx @@ -50,7 +50,7 @@ const ZH = await loadStudioCatalogue('zh'); const label = (key: string) => t(`engine.packages.detail.${key}`, 'en'); /** The write actions a writable base offers besides Disable. */ -const OTHER_WRITES = ['edit', 'publish', 'revert', 'duplicate', 'adoptOrphans', 'deletePackage']; +const OTHER_WRITES = ['edit', 'publish', 'revert', 'duplicate', 'deletePackage']; const MODULE_ID = 'com.acme.suite.orders'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.readOnlyActions-13157.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.readOnlyActions-13157.test.tsx index 17d6c303515..03d76eda282 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.readOnlyActions-13157.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.readOnlyActions-13157.test.tsx @@ -13,8 +13,7 @@ * * Pinned here through the real `PackageDetailSheet`: * (a) a read-only package (`writable: false`, whatever its scope) offers - * none of Edit, Publish, Revert, Disable, Duplicate, Adopt loose items or - * Delete app; the reads (View info, Export) stay; + * none of Edit, Publish, Revert, Disable, Duplicate or Delete app; the reads (View info, Export) stay; * (b) CONTROL: a writable package offers every one of them, as before; * (c) Duplicate is one of the refused writes: the server answers a read-only * source `422 DUPLICATE_SOURCE_NOT_A_BASE` (its source must be a @@ -31,11 +30,13 @@ import { MemoryRouter } from 'react-router-dom'; import { PackageDetailSheet, type InstalledPackageRow } from './PackagesPage'; import { t } from './i18n'; +// Pay the source's dynamic `@objectstack/lint` load during collection, never inside a clocked case. +import '@objectstack/lint'; const label = (key: string) => t(`engine.packages.detail.${key}`, 'en'); /** Every write action the sheet offers on a writable package. */ -const WRITES = ['edit', 'publish', 'revert', 'disable', 'duplicate', 'adoptOrphans', 'deletePackage']; +const WRITES = ['edit', 'publish', 'revert', 'disable', 'duplicate', 'deletePackage']; /** The read actions, offered on every package. */ const READS = ['viewInfo', 'export']; diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx index 6f52037de24..a778d237397 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx @@ -24,11 +24,10 @@ * Source filter, and in the detail sheet only enable / disable and delete * (with its keep-data choice); New Package lands in Studio on the new * package, and Import sits beside it (objectstack#37139). Publish, revert, - * discard drafts, adopt loose items and manifest edit stay on the - * development surface. + * discard drafts and manifest edit stay on the development surface. * * objectstack#37139 — the development face's whole-package actions (Edit, - * Export, Duplicate, Revert, Adopt loose items) are shared with Studio's 「⋯」 + * Export, Duplicate, Revert) are shared with Studio's 「⋯」 * package menu through `packageActions.tsx`. */ @@ -48,7 +47,6 @@ import { AlertTriangle, Trash2, Copy, - Inbox, Pencil, Eye, MoreHorizontal, @@ -101,12 +99,9 @@ import { useMetadataClient } from './useMetadata.js'; import { newAppStep } from '../studio-design/newAppDoor.js'; import { PackageFormDialog } from './PackageFormDialog.js'; import { - AdoptLooseItemsDialog, DuplicatePackageForm, EditPackageDialog, PACKAGES_API, - adoptLooseItems, - adoptedText, exportPackageFile, packagesApiJson, revertPackage, @@ -685,8 +680,8 @@ export function PackageDetailSheet({ * objectstack#36834 — which face of the Packages page opened the sheet. The * `admin` face (Setup → Packages) offers the administration actions only: * View info, Disable / Enable and Delete, plus "Open in Studio" on an - * authored package. Edit, Publish, Revert, Export, Duplicate, Adopt loose - * items and the pending changes' Publish / Discard stay on the development + * authored package. Edit, Publish, Revert, Export, Duplicate and the + * pending changes' Publish / Discard stay on the development * face. On the administration face a read-only base also draws what this * deployment changed on it (objectstack#36908). */ @@ -726,9 +721,7 @@ export function PackageDetailSheet({ // objectui#11784 — the confirmations this sheet asks are in-app, never // `window.confirm` / `window.prompt`: those are blocked or auto-answered in // an embedded frame, and the old delete chained two confirms where the - // second one's Cancel still deleted. objectui#13339 — Adopt loose items is - // the fourth. - const [adoptOpen, setAdoptOpen] = React.useState(false); + // second one's Cancel still deleted. const [deleteOpen, setDeleteOpen] = React.useState(false); // Disable takes a package's metadata out of service for every user, so it // is confirmed first; Enable restores and runs at once. @@ -751,7 +744,6 @@ export function PackageDetailSheet({ React.useEffect(() => { setMsg(null); setBusy(null); - setAdoptOpen(false); setDeleteOpen(false); setDiscardOpen(false); setDupOpen(false); @@ -825,8 +817,7 @@ export function PackageDetailSheet({ // `true` is never writable). On a read-only package the server refuses // Edit, Publish, Revert and Delete (`WRITABLE_PACKAGE_REQUIRED`) and // Duplicate (`DUPLICATE_SOURCE_NOT_A_BASE`: its source must be a writable - // base); Adopt orphans would bind loose items into a package the org cannot - // author. So none of them is offered there. The reads stay. Disable has its + // base). So none of them is offered there. The reads stay. Disable has its // own served verdict, `disableable`, below. const writable = pkg.writable === true; // objectstack#28118 — Disable is offered from the disable door's own served @@ -847,7 +838,7 @@ export function PackageDetailSheet({ // objectui#13339 — the sheet's one message line answers the action the // author started LAST. An action that runs straight away clears it as it - // starts (`run`, and the delete / duplicate / adopt calls); one that first + // starts (`run`, and the delete / duplicate calls); one that first // opens a dialog or a form clears it here, at the press that opens it, so // a previous action's answer (a Revert refusal, say) never stands under // the next action's form as if it were that action's. @@ -1105,31 +1096,6 @@ export function PackageDetailSheet({ } }; - // ADR-0070 D5 — adopt every package-less (loose) item in this env INTO this - // base. The *Adopt loose items* button opens an in-app confirmation - // (objectui#13339); only its confirm runs this, and its Cancel sends nothing. - // - // The answer reports the server's own count, `reassignedCount` - // (`ReassignOrphanedMetadataResponse`), 0 included: the sheet used to say - // "Loose items adopted" whatever moved, so an adoption that found nothing - // read as one that did. The answer's own `success` is false exactly when - // nothing moved (`reassigned.length > 0`); on this door that is a count of - // 0, not a failure, so the count is what the author is told. - const adoptOrphans = async () => { - setAdoptOpen(false); - setBusy('adopt'); - setMsg(null); - try { - const count = await adoptLooseItems(id); - setMsg({ kind: 'ok', text: adoptedText(count, locale) }); - onChanged(); - } catch (e: any) { - setMsg({ kind: 'err', text: e?.message ?? 'Adopt failed' }); - } finally { - setBusy(null); - } - }; - const toggleEnable = () => run( 'toggle', @@ -1360,12 +1326,6 @@ export function PackageDetailSheet({ {busy === 'duplicate' ? t('engine.packages.detail.duplicating', locale) : t('engine.packages.detail.duplicate', locale)} )} - {authoring && writable && ( - - )} {writable && (