diff --git a/.changeset/35147-destructive-still-shown-by.md b/.changeset/35147-destructive-still-shown-by.md new file mode 100644 index 00000000000..ab278d2be64 --- /dev/null +++ b/.changeset/35147-destructive-still-shown-by.md @@ -0,0 +1,18 @@ +--- +'@objectstack/spec': minor +'@objectstack/metadata-protocol': patch +--- + +feat(metadata-protocol): a refused field removal or type change names the views, forms and dashboard cards that still show the field + +Clause-②: yes (widening: the DESTRUCTIVE_CHANGE answer gains stillShownBy; a new exported operator-fit table) +Metadata-protocol: added +Skills-docs: none — no skill in `skills/**` teaches the `409 DESTRUCTIVE_CHANGE` save refusal or its `issues[]`. The finding's own message now names the items, so a client relaying it says them without being taught. + +The `409 DESTRUCTIVE_CHANGE` refusal of an `object` save said what data the change loses. It now also says what breaks on screen. Each `field_removed` finding carries `stillShownBy`: the views, forms, datasets, dashboards, pages, flows, reports and objects that still reference the field, at the positions that name it, as the served listing presents each item (`config.columns[1]` on a view item, `columns[1]` on a flattened list overlay, `widgets[3]` through a dataset). Each `field_type_change` finding carries the view filter rules whose operator the new type no longer fits, for example a `contains` filter on a field changed to `number`: a view item's `config.filter`, a flattened overlay's `filter`, and the `userFilters.tabs[].filter` of either. The finding's message names the first five items and counts the rest, so a door that relays only the message says it too. The save edits none of them. + +- The answer rides the refusal's `issues[]`, which every door already relays verbatim: the REST `PUT /api/v1/meta/...` doors (`issues`), the runtime dispatcher (`details.issues`) and the MCP draft door (`error.issues`). No door changed. +- It is computed from the environment's served metadata, one listing per type, only when a finding needs it. No record and no draft is read. When it cannot be computed (a listing cannot be read, a judge throws or cannot be loaded) `stillShownBy` is absent ("not computed"), and the refusal still stands; `[]` means "computed, shown nowhere". +- A removal is judged by the checks `os validate` runs (`@objectstack/lint`'s reference-integrity suite, form-layout check and widget-binding check), with the field and without it. A position those checks do not read is not seen. The spec describe on `DestructiveChangeIssueSchema.stillShownBy` states exactly what is and is not seen. +- `@objectstack/spec/data` exports `filterOperatorFieldTypeFit(operator, field)` and its table `FILTER_OPERATOR_FIELD_TYPE_FIT`: the one place that judges which filter operator fits which field type. An operator is unfit only where a declared-type door refuses it. Today that is the text-operator door (a text operator over a type that can never store a string, `INVALID_FILTER` 400), referenced rather than re-listed. `dollarFilterOperatorOf(op)` lowers a view, alias or infix operator spelling to its `$` form; a `$` spelling is returned as written, and an unknown spelling answers `undefined`. +- `@objectstack/spec/api` declares the answer's shape: `DestructiveChangeIssueSchema` and `FieldStillShownBySchema`. diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index fb06941288d..d918b8a95f6 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -1,7 +1,7 @@ --- title: Protocol schema — API Protocol reference navTitle: Protocol -description: "Protocol schemas of the ObjectStack API Protocol: AiAgentCapabilities and 148 more — each property with its type, default and a TypeScript example." +description: "Protocol schemas of the ObjectStack API Protocol: AiAgentCapabilities and 150 more — each property with its type, default and a TypeScript example." --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -13,8 +13,8 @@ description: "Protocol schemas of the ObjectStack API Protocol: AiAgentCapabilit ## TypeScript Usage ```typescript -import { AiAgentCapabilitiesSchema, AiAgentChatRequestSchema, AiAgentSummarySchema, AiAgentsResponseSchema, AiChatRequestSchema, AiChatResponseSchema, AiCompleteRequestSchema, AiConversationSchema, AiConversationMessageSchema, AiMessageSchema, AiModelsResponseSchema, AiPendingActionSchema, AiPendingActionStatusSchema, AiStreamChunkSchema, ApproveAiPendingActionResponseSchema, AuditMetaItemRequestSchema, AuditMetaItemResponseSchema, AutomationActionsResponseSchema, AutomationTriggerRequestSchema, AutomationTriggerResponseSchema, BatchDataRequestSchema, BatchDataResponseSchema, BuildProbeReportSchema, CheckPermissionRequestSchema, CheckPermissionResponseSchema, CloneDataResponseSchema, CreateAiConversationRequestSchema, CreateDataRequestSchema, CreateDataResponseSchema, CreateManyDataRequestSchema, CreateManyDataResponseSchema, DeleteDataRequestSchema, DeleteDataResponseSchema, DeleteManyDataRequestSchema, DeleteManyDataResponseSchema, DeleteMetaItemRequestSchema, DeleteMetaItemResponseSchema, DiffMetaItemRequestSchema, DiffMetaItemResponseSchema, DisablePackageRequestSchema, DisablePackageResponseSchema, EnablePackageRequestSchema, EnablePackageResponseSchema, FindDataRequestSchema, FindDataResponseSchema, FindReferencesToMetaResponseSchema, FlowRegistrationSchema, FlowRegistrationRefusalSchema, GetDataRequestSchema, GetDataResponseSchema, GetDiscoveryRequestSchema, GetDiscoveryResponseSchema, GetEffectivePermissionsRequestSchema, GetEffectivePermissionsResponseSchema, GetFieldLabelsRequestSchema, GetFieldLabelsResponseSchema, GetLocalesRequestSchema, GetLocalesResponseSchema, GetMetaDiagnosticsResponseSchema, GetMetaItemCachedRequestSchema, GetMetaItemCachedResponseSchema, GetMetaItemLayeredRequestSchema, GetMetaItemLayeredResponseSchema, GetMetaItemRequestSchema, GetMetaItemResponseSchema, GetMetaItemsRequestSchema, GetMetaItemsResponseSchema, GetMetaTypesRequestSchema, GetMetaTypesResponseSchema, GetNotificationPreferencesRequestSchema, GetNotificationPreferencesResponseSchema, GetObjectPermissionsRequestSchema, GetObjectPermissionsResponseSchema, GetPackageRequestSchema, GetPackageResponseSchema, GetPresenceRequestSchema, GetPresenceResponseSchema, GetPublishedMetaItemResponseSchema, GetRecordFieldAccessResponseSchema, GetTranslationsRequestSchema, GetTranslationsResponseSchema, GetUiViewRequestSchema, GetUiViewResponseSchema, HistoryMetaItemRequestSchema, HistoryMetaItemResponseSchema, HttpFindQueryParamsSchema, InstallPackageRequestSchema, InstallPackageResponseSchema, ListAiConversationsRequestSchema, ListAiConversationsResponseSchema, ListAiPendingActionsRequestSchema, ListAiPendingActionsResponseSchema, ListDraftsResponseSchema, ListNotificationsRequestSchema, ListNotificationsResponseSchema, ListPackagesRequestSchema, ListPackagesResponseSchema, MarkAllNotificationsReadRequestSchema, MarkAllNotificationsReadResponseSchema, MarkNotificationsReadRequestSchema, MarkNotificationsReadResponseSchema, MetadataAuthoringClientSchema, MetadataAuthoringSurfaceSchema, MetadataConflictErrorSchema, NotificationSchema, NotificationPreferencesSchema, PublicFormSubmitResponseSchema, PublishMetaItemRequestSchema, PublishMetaItemResponseSchema, PublishPackageDraftsRequestSchema, PublishPackageDraftsResponseSchema, RealtimeConnectRequestSchema, RealtimeConnectResponseSchema, RealtimeDisconnectRequestSchema, RealtimeDisconnectResponseSchema, RealtimeSubscribeRequestSchema, RealtimeSubscribeResponseSchema, RealtimeUnsubscribeRequestSchema, RealtimeUnsubscribeResponseSchema, RegisterDeviceRequestSchema, RegisterDeviceResponseSchema, RejectAiPendingActionResponseSchema, RollbackMetaItemRequestSchema, RollbackMetaItemResponseSchema, RuntimeAuthoringIssueSchema, RuntimeBuildIssueSchema, SaveMetaItemRequestSchema, SaveMetaItemResponseSchema, SearchAllHitSchema, SearchAllPageHitSchema, SearchAllResponseSchema, SeedAppliedIdListSchema, SeedAppliedLandedSchema, SetPresenceRequestSchema, SetPresenceResponseSchema, UninstallPackageRequestSchema, UninstallPackageResponseSchema, UnregisterDeviceRequestSchema, UnregisterDeviceResponseSchema, UpdateAiConversationRequestSchema, UpdateDataRequestSchema, UpdateDataResponseSchema, UpdateManyDataRequestSchema, UpdateManyDataResponseSchema, UpdateNotificationPreferencesRequestSchema, UpdateNotificationPreferencesResponseSchema, ValidateDataIssueSchema, ValidateDataRequestSchema, ValidateDataResponseSchema } from '@objectstack/spec/api'; -import type { 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, DiffMetaItemRequest, DiffMetaItemResponse, DisablePackageRequest, DisablePackageResponse, EnablePackageRequest, EnablePackageResponse, 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, 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 } from '@objectstack/spec/api'; +import { AiAgentCapabilitiesSchema, AiAgentChatRequestSchema, AiAgentSummarySchema, AiAgentsResponseSchema, AiChatRequestSchema, AiChatResponseSchema, AiCompleteRequestSchema, AiConversationSchema, AiConversationMessageSchema, AiMessageSchema, AiModelsResponseSchema, AiPendingActionSchema, AiPendingActionStatusSchema, AiStreamChunkSchema, ApproveAiPendingActionResponseSchema, AuditMetaItemRequestSchema, AuditMetaItemResponseSchema, AutomationActionsResponseSchema, AutomationTriggerRequestSchema, AutomationTriggerResponseSchema, BatchDataRequestSchema, BatchDataResponseSchema, BuildProbeReportSchema, CheckPermissionRequestSchema, CheckPermissionResponseSchema, CloneDataResponseSchema, CreateAiConversationRequestSchema, CreateDataRequestSchema, CreateDataResponseSchema, CreateManyDataRequestSchema, CreateManyDataResponseSchema, DeleteDataRequestSchema, DeleteDataResponseSchema, DeleteManyDataRequestSchema, DeleteManyDataResponseSchema, DeleteMetaItemRequestSchema, DeleteMetaItemResponseSchema, DestructiveChangeIssueSchema, DiffMetaItemRequestSchema, DiffMetaItemResponseSchema, DisablePackageRequestSchema, DisablePackageResponseSchema, EnablePackageRequestSchema, EnablePackageResponseSchema, FieldStillShownBySchema, FindDataRequestSchema, FindDataResponseSchema, FindReferencesToMetaResponseSchema, FlowRegistrationSchema, FlowRegistrationRefusalSchema, GetDataRequestSchema, GetDataResponseSchema, GetDiscoveryRequestSchema, GetDiscoveryResponseSchema, GetEffectivePermissionsRequestSchema, GetEffectivePermissionsResponseSchema, GetFieldLabelsRequestSchema, GetFieldLabelsResponseSchema, GetLocalesRequestSchema, GetLocalesResponseSchema, GetMetaDiagnosticsResponseSchema, GetMetaItemCachedRequestSchema, GetMetaItemCachedResponseSchema, GetMetaItemLayeredRequestSchema, GetMetaItemLayeredResponseSchema, GetMetaItemRequestSchema, GetMetaItemResponseSchema, GetMetaItemsRequestSchema, GetMetaItemsResponseSchema, GetMetaTypesRequestSchema, GetMetaTypesResponseSchema, GetNotificationPreferencesRequestSchema, GetNotificationPreferencesResponseSchema, GetObjectPermissionsRequestSchema, GetObjectPermissionsResponseSchema, GetPackageRequestSchema, GetPackageResponseSchema, GetPresenceRequestSchema, GetPresenceResponseSchema, GetPublishedMetaItemResponseSchema, GetRecordFieldAccessResponseSchema, GetTranslationsRequestSchema, GetTranslationsResponseSchema, GetUiViewRequestSchema, GetUiViewResponseSchema, HistoryMetaItemRequestSchema, HistoryMetaItemResponseSchema, HttpFindQueryParamsSchema, InstallPackageRequestSchema, InstallPackageResponseSchema, ListAiConversationsRequestSchema, ListAiConversationsResponseSchema, ListAiPendingActionsRequestSchema, ListAiPendingActionsResponseSchema, ListDraftsResponseSchema, ListNotificationsRequestSchema, ListNotificationsResponseSchema, ListPackagesRequestSchema, ListPackagesResponseSchema, MarkAllNotificationsReadRequestSchema, MarkAllNotificationsReadResponseSchema, MarkNotificationsReadRequestSchema, MarkNotificationsReadResponseSchema, MetadataAuthoringClientSchema, MetadataAuthoringSurfaceSchema, MetadataConflictErrorSchema, NotificationSchema, NotificationPreferencesSchema, PublicFormSubmitResponseSchema, PublishMetaItemRequestSchema, PublishMetaItemResponseSchema, PublishPackageDraftsRequestSchema, PublishPackageDraftsResponseSchema, RealtimeConnectRequestSchema, RealtimeConnectResponseSchema, RealtimeDisconnectRequestSchema, RealtimeDisconnectResponseSchema, RealtimeSubscribeRequestSchema, RealtimeSubscribeResponseSchema, RealtimeUnsubscribeRequestSchema, RealtimeUnsubscribeResponseSchema, RegisterDeviceRequestSchema, RegisterDeviceResponseSchema, RejectAiPendingActionResponseSchema, RollbackMetaItemRequestSchema, RollbackMetaItemResponseSchema, RuntimeAuthoringIssueSchema, RuntimeBuildIssueSchema, SaveMetaItemRequestSchema, SaveMetaItemResponseSchema, SearchAllHitSchema, SearchAllPageHitSchema, SearchAllResponseSchema, SeedAppliedIdListSchema, SeedAppliedLandedSchema, SetPresenceRequestSchema, SetPresenceResponseSchema, UninstallPackageRequestSchema, UninstallPackageResponseSchema, UnregisterDeviceRequestSchema, UnregisterDeviceResponseSchema, UpdateAiConversationRequestSchema, UpdateDataRequestSchema, UpdateDataResponseSchema, UpdateManyDataRequestSchema, UpdateManyDataResponseSchema, UpdateNotificationPreferencesRequestSchema, UpdateNotificationPreferencesResponseSchema, ValidateDataIssueSchema, ValidateDataRequestSchema, ValidateDataResponseSchema } from '@objectstack/spec/api'; +import type { 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, 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 } from '@objectstack/spec/api'; // Validate data const result = AiAgentCapabilitiesSchema.parse(data); @@ -821,6 +821,30 @@ A write-path strip event: caller-supplied fields legally dropped from the payloa | **userMessage** | `string` | optional | The finding's user-facing sentence, composed by its producer in the request's locale (else the workspace default locale, else `en`) — the same field name and producer-marked meaning as `ApiErrorSchema.userMessage`. Present only when the producer authors a user sentence for this `rule`; absent, a consumer renders `message` as before. Consumers render it as received; `rule` stays the stable id and `message` / `hint` stay the developer-facing text. | +--- + +## DestructiveChangeIssue + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **code** | `string` | ✅ | What the save loses: `field_removed`, `field_type_change`, `field_required_no_default`, `currency_mode_to_record` or `currency_field_repointed`. | +| **field** | `string` | optional | The field the finding is about. | +| **message** | `string` | ✅ | The finding in prose. When `stillShownBy` names items, the prose ends by naming them too. | +| **stillShownBy** | `{ type: string; name: string; where: string[]; via?: string; … }[]` | optional | The metadata items that still show the field, computed from the environment's served metadata (one served listing per type: what the code packages register, with this environment's stored active rows folded over them; drafts are not read, and no record is read). On `field_removed` and `field_type_change` findings only; absent on every other code, and absent when it could not be computed: a listing could not be read, a judge threw or could not be loaded, or the retyped field's new definition carries no readable `type` (absent is "not computed", `[]` is "computed, none"). On `field_removed`: the `object`, `view`, `dataset`, `dashboard`, `page`, `flow` and `report` items in which the platform's reference-integrity suite, form-layout check and widget-binding check (`@objectstack/lint`, the judges `os validate` runs) find a reference that resolves with the field and dangles without it, the saved body taken as the save would write it; plus each dashboard widget bound to a dataset dimension or measure that dangles (`via`). A position those judges do not read is not seen, nor is an item of any other type (an app, an action, a permission set), nor code outside the metadata. On `field_type_change`: each filter rule of a served `view` item bound to the saved object that names the field by its bare name and whose operator does not fit the new type, judged by `filterOperatorFieldTypeFit` (an operator is unfit only where a declared-type door refuses it; a filter another door refuses, such as any filter on a field retyped to `formula`, is not named). The rules read are a view item's `config.filter` (the canonical served shape), a flattened list overlay's own `filter`, and the `userFilters.tabs[].filter` of either, rules inside an any-of group included. Filters elsewhere (datasets, dashboards, reports, flows), dotted paths, and comparands are not judged there. The save does not edit any listed item. | + +### Nested Shape: `DestructiveChangeIssue.stillShownBy[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | The metadata type of the item: `view` (a list view or a form), `dataset`, `dashboard`, `page`, `flow`, `report`, or `object` (another object, or the saved object's own body). | +| **name** | `string` | ✅ | The item's name, as the served list names it. One item can appear in more than one entry: a dashboard once directly and once per `via` dataset, a view once per unfit `operator`. | +| **where** | `string[]` | ✅ | Each position inside the item that names the field, as a path relative to the item as the served listing presents it: `config.columns[1]` or `config.sections[0].fields[2]` on a view item (the served listing never presents a `{ list, form, listViews }` container, only the view items it expands into), `columns[1]` on a flattened list overlay, `widgets[3]` on a dashboard. The literal `(root)` when the finding sits on the item itself. | +| **via** | `string` | optional | A dashboard widget shows the field through this dataset: it names a dimension or measure of the dataset, and that dimension or measure names the field. | +| **operator** | `string` | optional | On a `field_type_change` entry only: the filter operator, as the view rule spells it, that no longer fits the new type (`filterOperatorFieldTypeFit` answers `unfit`). | + + --- ## DiffMetaItemRequest @@ -965,6 +989,21 @@ Enable package response | **registeredNamespaces** | `string[]` | optional | Namespace prefixes registered by this package | +--- + +## FieldStillShownBy + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | The metadata type of the item: `view` (a list view or a form), `dataset`, `dashboard`, `page`, `flow`, `report`, or `object` (another object, or the saved object's own body). | +| **name** | `string` | ✅ | The item's name, as the served list names it. One item can appear in more than one entry: a dashboard once directly and once per `via` dataset, a view once per unfit `operator`. | +| **where** | `string[]` | ✅ | Each position inside the item that names the field, as a path relative to the item as the served listing presents it: `config.columns[1]` or `config.sections[0].fields[2]` on a view item (the served listing never presents a `{ list, form, listViews }` container, only the view items it expands into), `columns[1]` on a flattened list overlay, `widgets[3]` on a dashboard. The literal `(root)` when the finding sits on the item itself. | +| **via** | `string` | optional | A dashboard widget shows the field through this dataset: it names a dimension or measure of the dataset, and that dimension or measure names the field. | +| **operator** | `string` | optional | On a `field_type_change` entry only: the filter operator, as the view rule spells it, that no longer fits the new type (`filterOperatorFieldTypeFit` answers `unfit`). | + + --- ## FindDataRequest diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 22670b105c4..16f613b9912 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 — 1698 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1700 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) | 14 | 84 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | -| [API Protocol](/docs/references/api) | 37 | 519 | REST contracts, endpoints, routing, realtime, batch, discovery. | +| [API Protocol](/docs/references/api) | 37 | 521 | 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 | 188 | 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 | 297 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 16 | 180 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **219** | **1698** | 14 protocol modules | +| **Total** | **219** | **1700** | 14 protocol modules | --- @@ -65,7 +65,7 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. ## API Protocol -**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **37 pages, 519 schemas** +**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **37 pages, 521 schemas** REST contracts, endpoints, routing, realtime, batch, discovery. @@ -95,7 +95,7 @@ REST contracts, endpoints, routing, realtime, batch, discovery. | [`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`, `PackageExportBundle`, `PackageExportManifest`, `PackagePublishResult`, `ReassignOrphanedMetadataResponse`, `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`, `DiffMetaItemRequest`, `DiffMetaItemResponse`, `DisablePackageRequest`, `DisablePackageResponse`, `EnablePackageRequest`, `EnablePackageResponse`, `FindDataRequest`, `FindDataResponse`, `FindReferencesToMetaResponse`, `FlowRegistration`, `FlowRegistrationRefusal`, `GetDataRequest`, `GetDataResponse`, `GetDiscoveryRequest`, `GetDiscoveryResponse`, `GetEffectivePermissionsRequest`, `GetEffectivePermissionsResponse`, `GetFieldLabelsRequest`, `GetFieldLabelsResponse`, `GetLocalesRequest`, `GetLocalesResponse`, `GetMetaDiagnosticsResponse`, `GetMetaItemCachedRequest`, `GetMetaItemCachedResponse`, `GetMetaItemLayeredRequest`, `GetMetaItemLayeredResponse`, `GetMetaItemRequest`, `GetMetaItemResponse`, `GetMetaItemsRequest`, `GetMetaItemsResponse`, `GetMetaTypesRequest`, `GetMetaTypesResponse`, `GetNotificationPreferencesRequest`, `GetNotificationPreferencesResponse`, `GetObjectPermissionsRequest`, `GetObjectPermissionsResponse`, `GetPackageRequest`, `GetPackageResponse`, `GetPresenceRequest`, `GetPresenceResponse`, `GetPublishedMetaItemResponse`, `GetRecordFieldAccessResponse`, `GetTranslationsRequest`, `GetTranslationsResponse`, `GetUiViewRequest`, `GetUiViewResponse`, `HistoryMetaItemRequest`, `HistoryMetaItemResponse`, `HttpFindQueryParams`, `InstallPackageRequest`, `InstallPackageResponse`, `ListAiConversationsRequest`, `ListAiConversationsResponse`, `ListAiPendingActionsRequest`, `ListAiPendingActionsResponse`, `ListDraftsResponse`, `ListNotificationsRequest`, `ListNotificationsResponse`, `ListPackagesRequest`, `ListPackagesResponse`, `MarkAllNotificationsReadRequest`, `MarkAllNotificationsReadResponse`, `MarkNotificationsReadRequest`, `MarkNotificationsReadResponse`, `MetadataAuthoringClient`, `MetadataAuthoringSurface`, `MetadataConflictError`, `Notification`, `NotificationPreferences`, `PublicFormSubmitResponse`, `PublishMetaItemRequest`, `PublishMetaItemResponse`, `PublishPackageDraftsRequest`, `PublishPackageDraftsResponse`, `RealtimeConnectRequest`, `RealtimeConnectResponse`, `RealtimeDisconnectRequest`, `RealtimeDisconnectResponse`, `RealtimeSubscribeRequest`, `RealtimeSubscribeResponse`, `RealtimeUnsubscribeRequest`, `RealtimeUnsubscribeResponse`, `RegisterDeviceRequest`, `RegisterDeviceResponse`, `RejectAiPendingActionResponse`, `RollbackMetaItemRequest`, `RollbackMetaItemResponse`, `RuntimeAuthoringIssue`, `RuntimeBuildIssue`, `SaveMetaItemRequest`, `SaveMetaItemResponse`, `SearchAllHit`, `SearchAllPageHit`, `SearchAllResponse`, `SeedAppliedIdList`, `SeedAppliedLanded`, `SetPresenceRequest`, `SetPresenceResponse`, `UninstallPackageRequest`, `UninstallPackageResponse`, `UnregisterDeviceRequest`, `UnregisterDeviceResponse`, `UpdateAiConversationRequest`, `UpdateDataRequest`, `UpdateDataResponse`, `UpdateManyDataRequest`, `UpdateManyDataResponse`, `UpdateNotificationPreferencesRequest`, `UpdateNotificationPreferencesResponse`, `ValidateDataIssue`, `ValidateDataRequest`, `ValidateDataResponse` | +| [`protocol.zod.ts`](/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` | | [`push-relay.zod.ts`](/docs/references/api/push-relay) | `PushRelayDelivery`, `PushRelayError`, `PushRelayErrorResponse`, `PushRelayPayload`, `PushRelayPriority`, `PushRelayRequest`, `PushRelayResponse`, `PushRelayResult`, `PushRelayResultStatus` | | [`query-adapter.zod.ts`](/docs/references/api/query-adapter) | `ODataQueryAdapter`, `OperatorMapping`, `QueryAdapterConfig`, `QueryAdapterTarget`, `RestQueryAdapter` | 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 31269913097..d7957730d2b 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/` | 531 | +| `api/` | 533 | diff --git a/packages/metadata-protocol/src/destructive-still-shown-by.lint-entry.test.ts b/packages/metadata-protocol/src/destructive-still-shown-by.lint-entry.test.ts new file mode 100644 index 00000000000..a41742950cc --- /dev/null +++ b/packages/metadata-protocol/src/destructive-still-shown-by.lint-entry.test.ts @@ -0,0 +1,61 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The object save path reaches `@objectstack/lint` only through + * `@objectstack/lint/runtime`, never through the package ROOT (#4463; + * `packages/lint/src/runtime.ts`). `destructive-still-shown-by.ts` needs three + * judges only the root exports, so it loads the root lazily with a dynamic + * `import()`, as `build-probes.ts` does. + * + * Pinned over the STATIC import closure of `protocol-save.ts`: every module it + * reaches through a relative `import … from` / `export … from`, none of which + * may import the lint root as a value. A type-only import is erased and allowed; + * a dynamic `import('@objectstack/lint')` is the sanctioned shape. + */ + +import { describe, expect, it } from 'vitest'; +import { existsSync, readFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const SRC = dirname(fileURLToPath(import.meta.url)); + +/** A static value import or re-export of the lint ROOT (not `/runtime`, not `import type`). */ +const STATIC_LINT_ROOT = /^\s*(?:import|export)\s+(?!type\b)[^;]*?\bfrom\s+['"]@objectstack\/lint['"]/m; +/** Static relative imports and re-exports, the edges of the closure. */ +const RELATIVE_EDGE = /^\s*(?:import|export)\s+(?!type\b)[^;]*?\bfrom\s+['"](\.{1,2}\/[^'"]+)['"]/gm; + +function closureOf(entry: string): string[] { + const seen = new Set(); + const queue = [resolve(SRC, entry)]; + while (queue.length > 0) { + const file = queue.shift() as string; + if (seen.has(file)) continue; + seen.add(file); + const text = readFileSync(file, 'utf8'); + for (const m of text.matchAll(RELATIVE_EDGE)) { + const target = join(dirname(file), m[1].replace(/\.js$/, '.ts')); + if (existsSync(target)) queue.push(target); + } + } + return [...seen]; +} + +describe('the object save path does not statically import the lint root', () => { + it('no module in protocol-save.ts\'s static closure imports @objectstack/lint as a value', () => { + const closure = closureOf('protocol-save.ts'); + // Not vacuous: the walk reached the module that needs the judges. + expect(closure).toContain(join(SRC, 'destructive-still-shown-by.ts')); + const offenders = closure.filter((f) => STATIC_LINT_ROOT.test(readFileSync(f, 'utf8'))); + expect(offenders).toEqual([]); + }); + + it('the still-shown-by module loads the judges through a dynamic import of the root', () => { + const text = readFileSync(join(SRC, 'destructive-still-shown-by.ts'), 'utf8'); + expect(text).toMatch(/await import\(['"]@objectstack\/lint['"]\)/); + // The detector itself bites on the shape it forbids. + expect(STATIC_LINT_ROOT.test("import { validateFormLayout } from '@objectstack/lint';")).toBe(true); + expect(STATIC_LINT_ROOT.test("import type { X } from '@objectstack/lint';")).toBe(false); + expect(STATIC_LINT_ROOT.test("import { runRuntimeAuthoringRules } from '@objectstack/lint/runtime';")).toBe(false); + }); +}); diff --git a/packages/metadata-protocol/src/destructive-still-shown-by.ts b/packages/metadata-protocol/src/destructive-still-shown-by.ts new file mode 100644 index 00000000000..8c28b3550d8 --- /dev/null +++ b/packages/metadata-protocol/src/destructive-still-shown-by.ts @@ -0,0 +1,346 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * What still shows a field a refused `object` save would remove or retype: the + * `stillShownBy` of the `409 DESTRUCTIVE_CHANGE` findings + * (`DestructiveChangeIssueSchema` in `@objectstack/spec/api`, whose describe is + * the contract this module computes). + * + * "This change loses data" is half of what the person confirming needs; the + * other half is what breaks on screen: the list that shows the column, the form + * that edits it, the card that sums it. Each `field_removed` finding names those + * items, and each `field_type_change` finding names the list-view filters whose + * operator the new type no longer fits. The findings ride `err.issues`, which + * every door relays verbatim, so no door computes or reshapes anything. + * + * ## Ported from the hosted build door + * + * The semantics of the removal half are the hosted build door's + * (`field-shown-by.ts` in the hosted tree), adapted to this write face: the + * judge is the platform's own, asked twice. The stack is judged with the field + * and again without it, and every finding the second run adds is a place that + * still shows the field; a finding both runs share is a fact about the stack, + * not about this field, and is left out. No position table lives here, so a + * position the judges learn to read reaches this answer with no change here. + * One step is added on top, because no rule makes it: a dashboard widget shows a + * field THROUGH its dataset, so a widget bound to a dimension or measure the + * removal leaves dangling is named too, `via` that dataset. + * + * ## What it reads + * + * One served listing per metadata type (`getMetaItems`: the code packages' + * registered items with the environment's stored active rows folded over them), + * read together, and only when a finding needs it. No record is read, and no + * item is read on its own. A listing that cannot be read leaves `stillShownBy` + * absent — "not computed" — rather than an empty list that would read as + * "shown nowhere". + * + * The `view` listing serves view items (`viewKind` + `config`) and flattened + * list overlays, never an aggregated `{ list, form, listViews }` container: + * the served read filters every container out after expanding stored ones + * (`protocol-meta-list-reads.ts`, `isAggregatedViewContainer`). So the + * type-change half reads `config` and the item's own root, and nothing else. + * + * ## How it reaches the judges + * + * The three judges live only on `@objectstack/lint`'s ROOT entry, and this + * module sits on the object save path, which reaches lint through + * `@objectstack/lint/runtime` alone (#4463). So the root is loaded lazily, as + * `build-probes.ts` loads it: one dynamic `import()`, taken only when a + * `field_removed` finding needs the judges. A failed load leaves those findings + * without `stillShownBy` ("not computed"); the refusal itself is unchanged. + * `destructive-still-shown-by.lint-entry.test.ts` pins that no static import of + * the root lands on the save path. + */ + +import type { FieldStillShownBy } from '@objectstack/spec/api'; +import { filterOperatorFieldTypeFit } from '@objectstack/spec/data'; +import { isViewFilterOrGroup } from '@objectstack/spec/ui'; + +/** One destructive-change finding as `detectDestructiveObjectChanges` produces it. */ +export interface DestructiveFinding { + code: string; + field?: string; + message: string; + stillShownBy?: FieldStillShownBy[]; +} + +/** Lists the served items of one metadata type (singular). */ +export type ServedItemsLister = (type: string) => Promise; + +type AnyRec = Record; + +const isRecord = (v: unknown): v is AnyRec => !!v && typeof v === 'object' && !Array.isArray(v); +const str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined); + +/** The stack collections the judges read, with the metadata type each one lists. */ +const COLLECTIONS = [ + ['objects', 'object'], + ['views', 'view'], + ['datasets', 'dataset'], + ['dashboards', 'dashboard'], + ['pages', 'page'], + ['flows', 'flow'], + ['reports', 'report'], +] as const; + +type Collection = (typeof COLLECTIONS)[number][0]; +type Stack = Record; + +const TYPE_OF: Readonly> = Object.fromEntries(COLLECTIONS); +const PATH = new RegExp(`^(${COLLECTIONS.map(([c]) => c).join('|')})\\[(\\d+)\\]\\.?(.*)$`); + +/** How many items a finding's prose names before it says how many more. */ +const PROSE_CAP = 5; + +/** + * The findings, each `field_removed` and `field_type_change` one carrying the + * items that still show its field. Every other finding passes through as it + * came. `prev` is the stored body, `next` the body the save would write. + */ +export async function withStillShownBy( + objectName: string, + prev: unknown, + next: unknown, + issues: readonly DestructiveFinding[], + listServed: ServedItemsLister, +): Promise { + const removed = issues.filter((i) => i.code === 'field_removed' && i.field).map((i) => i.field as string); // adr0112-ok: D6 a field-addressed finding code of the refusal's issues[], not an error.code + const retyped = issues.filter((i) => i.code === 'field_type_change' && i.field).map((i) => i.field as string); // adr0112-ok: D6 a field-addressed finding code of the refusal's issues[], not an error.code + if (removed.length === 0 && retyped.length === 0) return [...issues]; + + // A type change needs the views alone; a removal needs every collection. + const wanted = removed.length > 0 ? COLLECTIONS : COLLECTIONS.filter(([c]) => c === 'views'); + let stack: Stack; + try { + const lists = await Promise.all(wanted.map(([, type]) => listServed(type))); + stack = { objects: [], views: [], datasets: [], dashboards: [], pages: [], flows: [], reports: [] }; + wanted.forEach(([collection], i) => { stack[collection] = lists[i] ?? []; }); + } catch (error) { + // Not computed, said once: the refusal itself stands unchanged. + console.warn( + `[Protocol] the destructive-change refusal of object '${objectName}' could not read the served ` + + `metadata it names still-shown items from: ${(error as { message?: string } | null)?.message ?? String(error)}. ` + + 'Its findings carry no `stillShownBy`.', + ); + return [...issues]; + } + + const judges = removed.length > 0 ? await loadJudges(objectName) : undefined; + const shownByRemoval = judges ? removalSurfaces(judges, stack, objectName, prev, next, removed) : undefined; + const nextFields = isRecord(next) && isRecord(next.fields) ? next.fields : {}; + return issues.map((issue) => { + if (!issue.field) return { ...issue }; + if (issue.code === 'field_removed') { // adr0112-ok: D6 a field-addressed finding code of the refusal's issues[], not an error.code + const shown = shownByRemoval?.get(issue.field); + if (!shown) return { ...issue }; + return withProse({ ...issue, stillShownBy: shown }, 'Still shown by'); + } + if (issue.code === 'field_type_change') { + const definition = nextFields[issue.field]; + if (!isRecord(definition) || typeof definition.type !== 'string') return { ...issue }; + const shown = unfitViewFilters(stack.views, objectName, issue.field, definition); + return withProse({ ...issue, stillShownBy: shown }, 'Still filtered by an operator its new type does not fit in'); + } + return { ...issue }; + }); +} + +/** The finding's prose, ending with the items it names when there are any. */ +function withProse(issue: DestructiveFinding, lead: string): DestructiveFinding { + const shown = issue.stillShownBy ?? []; + if (shown.length === 0) return issue; + const named = shown.slice(0, PROSE_CAP).map(phrase).join('; '); + const more = shown.length > PROSE_CAP ? ` (+${shown.length - PROSE_CAP} more)` : ''; + return { ...issue, message: `${issue.message} ${lead}: ${named}${more}; the save does not edit them.` }; +} + +function phrase(s: FieldStillShownBy): string { + const at = s.where.join(', '); + const via = s.via ? `, through dataset "${s.via}"` : ''; + const operator = s.operator ? `, operator '${s.operator}'` : ''; + return `${s.type} "${s.name}" (${at}${via}${operator})`; +} + +// ── field_removed: the platform's judges, asked with and without the field ── + +interface Finding { + rule: string; + path: string; +} + +type Judge = (stack: AnyRec) => readonly Finding[]; + +/** The three judges `os validate` runs, loaded lazily from lint's root entry; `undefined` when the load failed. */ +async function loadJudges(objectName: string): Promise { + try { + const lint = await import('@objectstack/lint'); + return [lint.validateReferenceIntegrity, lint.validateFormLayout, lint.validateWidgetBindings]; + } catch (error) { + console.warn( + `[Protocol] the destructive-change refusal of object '${objectName}' could not load the judges it names ` + + `still-shown items with: ${(error as { message?: string } | null)?.message ?? String(error)}. ` + + 'Its `field_removed` findings carry no `stillShownBy`.', + ); + return undefined; + } +} + +/** Every finding the judges answer for `stack`, or `undefined` when one threw. */ +function judge(judges: readonly Judge[], stack: AnyRec): Finding[] | undefined { + try { + return judges.flatMap((j) => [...j(stack)]); + } catch { + return undefined; + } +} + +const findingKey = (f: Finding): string => `${f.rule}@${f.path}`; + +/** + * For each removed field, the items whose references resolve with it and dangle + * without it. The saved object is judged as the save would write it (`next`), + * with every removed field's stored definition put back; each run then takes one + * field out again. `undefined` for a field when a judge could not run. + */ +function removalSurfaces( + judges: readonly Judge[], + stack: Stack, + objectName: string, + prev: unknown, + next: unknown, + removed: readonly string[], +): Map { + const answers = new Map(); + const prevFields = isRecord(prev) && isRecord(prev.fields) ? prev.fields : {}; + const nextBody = isRecord(next) ? next : {}; + const nextFields = isRecord(nextBody.fields) ? nextBody.fields : {}; + const restored: AnyRec = { ...nextFields }; + for (const field of removed) if (prevFields[field] !== undefined) restored[field] = prevFields[field]; + const withAll: AnyRec = { ...nextBody, name: str(nextBody.name) ?? objectName, fields: restored }; + + const others = stack.objects.filter((o) => !(isRecord(o) && o.name === objectName)); + const at = (objectBody: AnyRec): Stack => ({ ...stack, objects: [...others, objectBody] }); + const baselineStack = at(withAll); + const baseline = judge(judges, baselineStack); + if (!baseline) return answers; + const seen = new Set(baseline.map(findingKey)); + + for (const field of removed) { + const { [field]: _gone, ...rest } = restored; + const findings = judge(judges, at({ ...withAll, fields: rest })); + if (!findings) continue; + answers.set(field, surfacesOf(baselineStack, findings.filter((f) => !seen.has(findingKey(f))))); + } + return answers; +} + +/** The added findings, grouped by the item they sit in, plus the widgets that show the field through a dataset. */ +function surfacesOf(stack: Stack, added: readonly Finding[]): FieldStillShownBy[] { + const byItem = new Map(); + const add = (type: string, name: string, where: string, via?: string): void => { + const id = `${type}:${name}:${via ?? ''}`; + const entry = byItem.get(id) ?? { type, name, where: [], ...(via ? { via } : {}) }; + if (!entry.where.includes(where)) entry.where.push(where); + byItem.set(id, entry); + }; + // dataset name → the dimension and measure names the removal leaves dangling. + const datasetLosses = new Map>(); + for (const finding of added) { + const match = PATH.exec(finding.path); + if (!match) continue; + const [, collection, index, rest] = match; + const item = stack[collection as Collection][Number(index)]; + const name = isRecord(item) ? str(item.name) : undefined; + if (!isRecord(item) || !name) continue; + add(TYPE_OF[collection], name, rest.replace(/\.field$/, '') || '(root)'); + if (collection !== 'datasets') continue; + const member = /^(dimensions|measures)\[(\d+)\]/.exec(rest); + const declared = member ? (item[member[1]] as unknown[] | undefined)?.[Number(member[2])] : undefined; + const memberName = isRecord(declared) ? str(declared.name) : undefined; + if (!memberName) continue; + const lost = datasetLosses.get(name) ?? new Set(); + lost.add(memberName); + datasetLosses.set(name, lost); + } + for (const raw of stack.dashboards) { + if (!isRecord(raw) || !Array.isArray(raw.widgets)) continue; + const dashboard = str(raw.name); + if (!dashboard) continue; + raw.widgets.forEach((widget, i) => { + if (!isRecord(widget)) return; + const dataset = str(widget.dataset); + const lost = dataset ? datasetLosses.get(dataset) : undefined; + if (!dataset || !lost) return; + const selected = (['dimensions', 'values'] as const) + .flatMap((key) => (Array.isArray(widget[key]) ? (widget[key] as unknown[]) : [])) + .filter((n): n is string => typeof n === 'string'); + if (selected.some((n) => lost.has(n))) add('dashboard', dashboard, `widgets[${i}]`, dataset); + }); + } + return [...byItem.values()]; +} + +// ── field_type_change: the list-view filters whose operator stops fitting ── + +/** The object one view record binds: `objectName`, `object`, then `data.object`. */ +function boundObject(view: AnyRec): string | undefined { + return str(view.objectName) ?? str(view.object) ?? (isRecord(view.data) ? str(view.data.object) : undefined); +} + +/** + * Each filter rule of a served view item bound to `objectName` that names + * `field` by its bare name and whose operator does not fit `definition`'s type. + * The rules read: the item's own `filter` (a flattened list overlay), its + * `config.filter` (a view item, the canonical served shape), and the + * `userFilters.tabs[].filter` of either. A site binds the object it names, else + * the item's binding. + */ +function unfitViewFilters( + views: readonly unknown[], + objectName: string, + field: string, + definition: AnyRec, +): FieldStillShownBy[] { + const meta = { + type: definition.type as string, + ...(typeof definition.returnType === 'string' ? { returnType: definition.returnType } : {}), + }; + const shown: FieldStillShownBy[] = []; + for (const raw of views) { + if (!isRecord(raw)) continue; + const name = str(raw.name); + if (!name) continue; + const itemBinding = boundObject(raw); + const roots: Array<[string, AnyRec]> = [['', raw]]; + if (isRecord(raw.config)) roots.push(['config.', raw.config]); + const entries: Array<{ where: string; operator: string }> = []; + for (const [prefix, root] of roots) { + if ((boundObject(root) ?? itemBinding) !== objectName) continue; + const filters: Array<[string, unknown]> = [[`${prefix}filter`, root.filter]]; + const tabs = isRecord(root.userFilters) ? root.userFilters.tabs : undefined; + if (Array.isArray(tabs)) { + tabs.forEach((tab, k) => { + if (isRecord(tab)) filters.push([`${prefix}userFilters.tabs[${k}].filter`, tab.filter]); + }); + } + for (const [at, filter] of filters) { + if (!Array.isArray(filter)) continue; + filter.forEach((element, i) => { + const rules: Array<[string, unknown]> = isViewFilterOrGroup(element) && Array.isArray(element.or) + ? element.or.map((rule, j) => [`${at}[${i}].or[${j}]`, rule]) + : [[`${at}[${i}]`, element]]; + for (const [where, rule] of rules) { + if (!isRecord(rule) || rule.field !== field || typeof rule.operator !== 'string') continue; + if (filterOperatorFieldTypeFit(rule.operator, meta) === 'unfit') entries.push({ where, operator: rule.operator }); + } + }); + } + } + // One entry per operator, so each entry names the one operator its positions share. + const byOperator = new Map(); + for (const { where, operator } of entries) byOperator.set(operator, [...(byOperator.get(operator) ?? []), where]); + for (const [operator, where] of byOperator) shown.push({ type: 'view', name, where, operator }); + } + return shown; +} diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index d784f58894d..d5b5ad9a9a4 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -53,6 +53,7 @@ import { flowVerdictBody } from './protocol-flow-save-replay.js'; import { withParsedStoredActions } from './protocol-stored-action-parse.js'; import { datasourceCredentialsRefSaveRefusal } from './protocol-datasource-credentials-ref.js'; import { withNullMasterRowCounts } from './protocol-destructive-null-master.js'; +import { withStillShownBy } from './destructive-still-shown-by.js'; import { canonicalMetaType, canonicalizeMetaRequestType, resolveOverlaySchema } from './protocol-meta-type-schema.js'; import { permissionSetOwnerBindingRefusal, @@ -338,7 +339,7 @@ export class ProtocolSaveFacet { } /** [#28355] The body of {@link saveMetaItem} before its refusal audit; that method's docblock is the contract. */ - static async saveMetaItemUnaudited(host: Pick, request: SaveMetaItemRequest) { + static async saveMetaItemUnaudited(host: Pick, request: SaveMetaItemRequest) { // [ADR-0131 D6] FIRST, before every other gate and every read: an // organization-scoped write is refused for every type, draft or // publish. See {@link organizationScopedWriteRefusal}. @@ -1164,10 +1165,29 @@ export class ProtocolSaveFacet { // detail made required: its finding names how many stored rows // hold no master, since those stop serving everyone. One count // per such finding, none on any other save; see the module. - const issues = await withNullMasterRowCounts( + const counted = await withNullMasterRowCounts( detectDestructiveObjectChanges(prev, request.item), request.item, request.name, (field) => host.engine.count(request.name, { where: { [field]: { $null: true } }, context: { isSystem: true } }), ); + // A removed or retyped field names the items that still + // show it (`stillShownBy`), read from one served listing per + // type; it rides `issues`, which every door relays. + // Caught HERE: the enclosing `catch` reads any other throw as + // "skip the safety check", so a failure computing the names + // must leave them absent and the 409 standing. + let issues = counted; + try { + issues = await withStillShownBy( + request.name, prev, request.item, counted, + async (type) => (await host.getMetaItems({ type }))?.items ?? [], + ); + } catch (error) { + console.warn( + `[Protocol] object '${request.name}': naming the items that still show a removed or ` + + `retyped field failed (${(error as { message?: string } | null)?.message ?? String(error)}); ` + + 'the refusal carries no `stillShownBy`.', + ); + } if (issues.length > 0) { // [commit 809e61221] Deliberately NOT trimmed to a headline, and // this is a MEASURED verdict rather than an oversight — diff --git a/packages/metadata-protocol/src/protocol.destructive-gate-reachable-types.test.ts b/packages/metadata-protocol/src/protocol.destructive-gate-reachable-types.test.ts index 0dc5dab3268..2f396509288 100644 --- a/packages/metadata-protocol/src/protocol.destructive-gate-reachable-types.test.ts +++ b/packages/metadata-protocol/src/protocol.destructive-gate-reachable-types.test.ts @@ -83,6 +83,9 @@ import { assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objec // Reason 1 is a claim about the AUTHORABLE SHAPE of a `field` body, so it is // asserted against the schema itself rather than restated in prose here. import { FieldSchema } from '@objectstack/spec/data'; +// The refusal names still-shown items with lint's judges, loaded lazily: pay +// that first load during collection, never inside a clocked case. +import './lint-root-preload.testkit.js'; import { ObjectStackProtocolImplementation } from './protocol.js'; import { resetEnvWritableMetadataTypes } from './sys-metadata-repository.js'; @@ -554,6 +557,8 @@ describe('[#24411 §4] the destructive diff reads the field\'s own storage decla code: 'field_removed', field: 'notes', message: "Field 'notes' removed — existing data in this column will become inaccessible.", + // Computed, and nothing in this fixture shows the field. + stillShownBy: [], }]); expect(metadataWrites(writes)).toEqual([]); }); diff --git a/packages/metadata-protocol/src/protocol.destructive-still-shown-by.test.ts b/packages/metadata-protocol/src/protocol.destructive-still-shown-by.test.ts new file mode 100644 index 00000000000..7d274cf5eec --- /dev/null +++ b/packages/metadata-protocol/src/protocol.destructive-still-shown-by.test.ts @@ -0,0 +1,326 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The `409 DESTRUCTIVE_CHANGE` refusal names what still shows a removed field, + * and the list-view filters a type change leaves unfit (`stillShownBy` on the + * refusal's `issues[]`, `DestructiveChangeIssueSchema` in `@objectstack/spec/api`). + * + * Driven through the real producer, `saveMetaItem`, over a `sys_metadata` + * double (the harness `protocol.destructive-409-face-inventory.test.ts` uses). + * The findings ride `err.issues`, which every door relays verbatim; the + * relay itself is `resolveThrownHttpError`, the rule both HTTP doors read, and + * the MCP draft door saves with `mode: 'draft'` and `writeFace: 'meta-dispatch'`. + */ + +import { describe, expect, it, vi } from 'vitest'; +import { resolveThrownHttpError } from '@objectstack/types'; +import { assertEngineFindOnePredicate } from '@objectstack/metadata-core'; +import { DestructiveChangeIssueSchema } from '@objectstack/spec/api'; +import './lint-root-preload.testkit.js'; +import { ObjectStackProtocolImplementation } from './protocol.js'; + +interface Row { + id: string; + type: string; + name: string; + organization_id: string | null; + package_id: string | null; + state: string; + metadata: string; + checksum: string; + version?: number; +} + +const PKG = 'com.acme.crm'; + +const row = (type: string, name: string, body: Record): Row => ({ + id: `row_${type}_${name}`, + type, + name, + organization_id: null, + package_id: PKG, + state: 'active', + metadata: JSON.stringify(body), + checksum: 'sha256_35147_fixture', + version: 1, +}); + +const FIELDS = { + name: { name: 'name', type: 'text' }, + status: { name: 'status', type: 'text' }, + note: { name: 'note', type: 'text' }, +}; + +const leadObject = row('object', 'crm_lead', { name: 'crm_lead', label: 'Lead', fields: FIELDS }); + +/** + * A list view showing `status` as a column and filtering on it with a text + * operator, in the flattened list-overlay shape the `/meta/view` door stores. + */ +const leadList = row('view', 'crm_lead_open', { + name: 'crm_lead_open', + viewKind: 'list', + object: 'crm_lead', + type: 'grid', + data: { provider: 'object', object: 'crm_lead' }, + columns: ['name', 'status'], + filter: [{ field: 'status', operator: 'contains', value: 'op' }], +}); + +/** + * A view item in the shape the served `view` listing presents (`viewKind` + + * `config`): the listing never serves a `{ list, listViews }` container, only + * the items it expands into. Its `config` shows `status` as a column, filters + * on it, and carries a `userFilters` tab preset that filters on it too. + */ +const leadItem = row('view', 'crm_lead.pipeline', { + name: 'crm_lead.pipeline', + object: 'crm_lead', + viewKind: 'list', + config: { + type: 'grid', + columns: ['name', 'status'], + filter: [{ field: 'status', operator: 'contains', value: 'a' }], + userFilters: { + element: 'tabs', + tabs: [{ name: 'hot', label: 'Hot', filter: [{ field: 'status', operator: 'contains', value: 'h' }] }], + }, + }, +}); + +/** A dataset with a dimension on `status`, and a dashboard card bound to that dimension. */ +const leadDataset = row('dataset', 'lead_stats', { + name: 'lead_stats', + label: 'Lead stats', + object: 'crm_lead', + dimensions: [{ name: 'by_status', label: 'Status', field: 'status' }], + measures: [{ name: 'lead_count', label: 'Leads', aggregate: 'count' }], +}); +const leadDashboard = row('dashboard', 'lead_board', { + name: 'lead_board', + label: 'Lead board', + widgets: [ + { id: 'w_total', type: 'metric', dataset: 'lead_stats', values: ['lead_count'] }, + { id: 'w_status', type: 'bar', dataset: 'lead_stats', dimensions: ['by_status'], values: ['lead_count'] }, + ], +}); + +/** A form view editing `status`. */ +const leadForm = row('view', 'crm_lead_edit', { + name: 'crm_lead_edit', + object: 'crm_lead', + type: 'simple', + data: { provider: 'object', object: 'crm_lead' }, + sections: [{ label: 'Main', fields: ['name', 'status'] }], +}); + +const whereValueMatches = (actual: unknown, want: unknown): boolean => + want !== null && typeof want === 'object' && Array.isArray((want as { $in?: unknown }).$in) + ? (want as { $in: unknown[] }).$in.includes(actual) + : actual === want; + +function makeKernel(seed: Row[]) { + const rows = new Map(); + for (const r of seed) rows.set(r.id, r); + const match = (r: Row, where: Record): boolean => + Object.entries(where ?? {}).every(([k, v]) => { + if (k === '$or') return (v as Array>).some((c) => match(r, c)); + return v === null || v === undefined + ? (r as any)[k] === null || (r as any)[k] === undefined + : whereValueMatches((r as any)[k], v); + }); + const finds: string[] = []; + const engine: any = { + async find(table: string, o?: { where?: Record; limit?: number }) { + if (table !== 'sys_metadata') return []; + finds.push(String(o?.where?.type)); + const matched = Array.from(rows.values()).filter((r) => match(r, o?.where ?? {})); + return typeof o?.limit === 'number' ? matched.slice(0, o.limit) : matched; + }, + async findOne(table: string, o: { where: Record }) { + assertEngineFindOnePredicate(table, o); + if (table !== 'sys_metadata') return null; + for (const r of rows.values()) if (match(r, o?.where ?? {})) return r; + return null; + }, + async count() { + return 0; + }, + // No `insert` / `update` / `delete`: every case here is refused before + // anything is persisted. + registry: { + registerItem: () => {}, registerObject: () => {}, listItems: () => [], + getItem: () => undefined, getArtifactItem: () => undefined, + removeRuntimeShadow: () => false, removeOverlayEntry: () => {}, uninstallPackage: () => {}, + getPackage: (id: string) => (id === PKG ? { manifest: { id } } : undefined), + }, + }; + const protocol = new ObjectStackProtocolImplementation(engine, () => new Map()) as any; + return { protocol, finds }; +} + +async function refusal(seed: Row[], fields: Record, extra: Record = {}): Promise { + const { protocol } = makeKernel(seed); + return refusalOf(protocol, fields, extra); +} + +async function refusalOf(protocol: any, fields: Record, extra: Record = {}): Promise { + try { + await protocol.saveMetaItem({ type: 'object', name: 'crm_lead', item: { name: 'crm_lead', label: 'Lead', fields }, ...extra }); + } catch (e: any) { + return e; + } + throw new Error('expected saveMetaItem to refuse the destructive change'); +} + +const withoutStatus = { name: FIELDS.name, note: FIELDS.note }; + +describe('a refused field removal names the views and forms that still show the field', () => { + it('names the list view and the form on the field_removed finding', async () => { + const err = await refusal([leadObject, leadList, leadForm], withoutStatus); + expect(err.code).toBe('DESTRUCTIVE_CHANGE'); + expect(err.status).toBe(409); + const removed = err.issues.find((i: any) => i.code === 'field_removed' && i.field === 'status'); + expect(removed.stillShownBy).toEqual([ + { type: 'view', name: 'crm_lead_open', where: ['columns[1]', 'filter[0]'] }, + { type: 'view', name: 'crm_lead_edit', where: ['sections[0].fields[1]'] }, + ]); + // …and its prose names them too, so a face that carries only the message still says so. + expect(removed.message).toContain('view "crm_lead_open"'); + expect(removed.message).toContain('view "crm_lead_edit"'); + }); + + it('names nothing for a removed field no item shows (computed, empty)', async () => { + const err = await refusal([leadObject, leadList, leadForm], { name: FIELDS.name, status: FIELDS.status }); + const removed = err.issues.find((i: any) => i.code === 'field_removed' && i.field === 'note'); + expect(removed.stillShownBy).toEqual([]); + }); + + it('reaches the wire unchanged on the HTTP doors (the shared thrown-error rule)', async () => { + const err = await refusal([leadObject, leadList, leadForm], withoutStatus, { writeFace: 'meta-envelope' }); + const wire = resolveThrownHttpError(err, 500) as any; + expect(wire.status).toBe(409); + expect(wire.code).toBe('DESTRUCTIVE_CHANGE'); + const names = wire.details.issues + .flatMap((i: any) => i.stillShownBy ?? []) + .map((s: any) => s.name); + expect(names).toEqual(expect.arrayContaining(['crm_lead_open', 'crm_lead_edit'])); + }); + + it('names both on the MCP draft door\'s save (draft mode, meta-dispatch face)', async () => { + const err = await refusal([leadObject, leadList, leadForm], withoutStatus, { + mode: 'draft', surface: 'mcp', writeFace: 'meta-dispatch', packageId: PKG, + }); + expect(err.code).toBe('DESTRUCTIVE_CHANGE'); + const removed = err.issues.find((i: any) => i.code === 'field_removed' && i.field === 'status'); + expect(removed.stillShownBy.map((s: any) => s.name)).toEqual(expect.arrayContaining(['crm_lead_open', 'crm_lead_edit'])); + }); + + it('reads each type\'s served listing a fixed number of times, however many items it holds', async () => { + // The view listing is read (a positive count, so the bound cannot pass + // with no reads), and five more view items add no read at all. + const viewReads = async (seed: Row[]): Promise => { + const { protocol, finds } = makeKernel(seed); + await refusalOf(protocol, withoutStatus); + return finds.filter((t) => t === 'view').length; + }; + const extra = [1, 2, 3, 4, 5].map((n) => row('view', `crm_lead_extra_${n}`, { + name: `crm_lead_extra_${n}`, viewKind: 'list', object: 'crm_lead', type: 'grid', columns: ['status'], + })); + const one = await viewReads([leadObject, leadList]); + const six = await viewReads([leadObject, leadList, ...extra]); + expect(one).toBeGreaterThan(0); + expect(six).toBe(one); + }); + + it('names a served view item at its config positions', async () => { + const err = await refusal([leadObject, leadItem], withoutStatus); + const removed = err.issues.find((i: any) => i.code === 'field_removed' && i.field === 'status'); + expect(removed.stillShownBy).toEqual([ + { + type: 'view', + name: 'crm_lead.pipeline', + where: ['config.columns[1]', 'config.filter[0]', 'config.userFilters.tabs[0].filter[0]'], + }, + ]); + }); + + it('names a dashboard card that shows the field through a dataset (via)', async () => { + const err = await refusal([leadObject, leadDataset, leadDashboard], withoutStatus); + const removed = err.issues.find((i: any) => i.code === 'field_removed' && i.field === 'status'); + expect(removed.stillShownBy).toEqual([ + { type: 'dataset', name: 'lead_stats', where: ['dimensions[0]'] }, + { type: 'dashboard', name: 'lead_board', where: ['widgets[1]'], via: 'lead_stats' }, + ]); + expect(removed.message).toContain('through dataset "lead_stats"'); + }); + + it('leaves stillShownBy absent, not [], when a listing cannot be read, and still refuses', async () => { + // The served `dashboard` listing fails; every other listing answers. + const { protocol } = makeKernel([leadObject, leadList, leadForm]); + const served = protocol.getMetaItems.bind(protocol); + vi.spyOn(protocol, 'getMetaItems').mockImplementation(async (request: any) => { + if (request?.type === 'dashboard') throw new Error('fixture: the dashboard listing is unreadable'); + return served(request); + }); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const err = await refusalOf(protocol, withoutStatus).finally(() => warn.mockRestore()); + expect(err.code).toBe('DESTRUCTIVE_CHANGE'); + expect(err.status).toBe(409); + const removed = err.issues.find((i: any) => i.code === 'field_removed' && i.field === 'status'); + expect(removed).toBeDefined(); + expect('stillShownBy' in removed).toBe(false); + }); + + it('still refuses when naming the items throws, with stillShownBy absent', async () => { + // A listing answer that is not a list makes the namer throw past its + // own read guard; the save's call site must catch it rather than let + // the enclosing catch read it as "skip the safety check". + const { protocol } = makeKernel([leadObject, leadList, leadForm]); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(protocol, 'getMetaItems').mockResolvedValue({ type: 'view', items: 7 }); + try { + const err = await refusalOf(protocol, { ...FIELDS, status: { name: 'status', type: 'number' } }); + expect(err.code).toBe('DESTRUCTIVE_CHANGE'); + expect(err.status).toBe(409); + const retyped = err.issues.find((i: any) => i.code === 'field_type_change' && i.field === 'status'); + expect(retyped).toBeDefined(); + expect('stillShownBy' in retyped).toBe(false); + } finally { + warn.mockRestore(); + } + }); + + it('produces findings the declared wire shape parses (DestructiveChangeIssueSchema)', async () => { + const err = await refusal([leadObject, leadList, leadForm, leadDataset, leadDashboard], withoutStatus); + const removed = err.issues.find((i: any) => i.code === 'field_removed' && i.field === 'status'); + expect(removed.stillShownBy.length).toBeGreaterThan(0); + for (const issue of err.issues) { + const parsed = DestructiveChangeIssueSchema.safeParse(issue); + expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); + } + }); +}); + +describe('a refused type change names the list-view filters whose operator no longer fits', () => { + it('names the view filter whose text operator the new number type refuses', async () => { + const err = await refusal([leadObject, leadList, leadForm], { + ...FIELDS, status: { name: 'status', type: 'number' }, + }); + const retyped = err.issues.find((i: any) => i.code === 'field_type_change' && i.field === 'status'); + expect(retyped.stillShownBy).toEqual([ + { type: 'view', name: 'crm_lead_open', where: ['filter[0]'], operator: 'contains' }, + ]); + }); + + it('names a served view item\'s config filter and its userFilters tab filter', async () => { + const err = await refusal([leadObject, leadItem], { ...FIELDS, status: { name: 'status', type: 'number' } }); + const retyped = err.issues.find((i: any) => i.code === 'field_type_change' && i.field === 'status'); + expect(retyped.stillShownBy).toEqual([{ + type: 'view', + name: 'crm_lead.pipeline', + where: ['config.filter[0]', 'config.userFilters.tabs[0].filter[0]'], + operator: 'contains', + }]); + }); +}); diff --git a/packages/qa/dogfood/test/meta-object-unstored-field-removal.dogfood.test.ts b/packages/qa/dogfood/test/meta-object-unstored-field-removal.dogfood.test.ts index 5685c46f137..cbeb36d2f17 100644 --- a/packages/qa/dogfood/test/meta-object-unstored-field-removal.dogfood.test.ts +++ b/packages/qa/dogfood/test/meta-object-unstored-field-removal.dogfood.test.ts @@ -97,6 +97,8 @@ describe('dogfood: removing an unstored field through PUT /meta/object/:name', ( code: 'field_removed', field: 'notes', message: "Field 'notes' removed — existing data in this column will become inaccessible.", + // Computed from the served metadata: nothing shows this test's own field. + stillShownBy: [], }]); }); diff --git a/packages/rest/src/meta-destructive-still-shown-by-flat-issues.test.ts b/packages/rest/src/meta-destructive-still-shown-by-flat-issues.test.ts new file mode 100644 index 00000000000..28d8aaeda74 --- /dev/null +++ b/packages/rest/src/meta-destructive-still-shown-by-flat-issues.test.ts @@ -0,0 +1,125 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The REST `PUT /api/v1/meta/:type/:name` door answers a `409 + * DESTRUCTIVE_CHANGE` refusal in its flat dialect: `issues` sits at the top + * level of the body, beside `code` (`error-response.ts`). Each `field_removed` + * finding there carries `stillShownBy`, the items that still show the field + * (`DestructiveChangeIssueSchema` in `@objectstack/spec/api`). + * + * Driven end to end on the error leg: the REAL producer (`saveMetaItem` over a + * `sys_metadata` double) refuses, and the door's own writer + * (`handleRouteError`, the catch of the meta write routes) answers. The answer + * is non-empty: a list view shows the removed column. + */ + +import { describe, expect, it, vi } from 'vitest'; +import { assertEngineFindOnePredicate } from '@objectstack/metadata-core'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { handleRouteError } from './error-response.js'; + +interface Row { + id: string; + type: string; + name: string; + organization_id: string | null; + package_id: string | null; + state: string; + metadata: string; + checksum: string; + version: number; +} + +const PKG = 'com.acme.crm'; + +const row = (type: string, name: string, body: Record): Row => ({ + id: `row_${type}_${name}`, type, name, + organization_id: null, package_id: PKG, state: 'active', + metadata: JSON.stringify(body), checksum: 'sha256_35147_rest_fixture', version: 1, +}); + +const FIELDS = { + name: { name: 'name', type: 'text' }, + status: { name: 'status', type: 'text' }, +}; + +const SEED = [ + row('object', 'crm_lead', { name: 'crm_lead', label: 'Lead', fields: FIELDS }), + row('view', 'crm_lead_open', { + name: 'crm_lead_open', viewKind: 'list', object: 'crm_lead', type: 'grid', + data: { provider: 'object', object: 'crm_lead' }, columns: ['name', 'status'], + }), +]; + +const whereValueMatches = (actual: unknown, want: unknown): boolean => + want !== null && typeof want === 'object' && Array.isArray((want as { $in?: unknown }).$in) + ? (want as { $in: unknown[] }).$in.includes(actual) + : actual === want; + +function protocolOver(seed: Row[]) { + const rows = new Map(seed.map((r) => [r.id, r])); + const match = (r: Row, where: Record): boolean => + Object.entries(where ?? {}).every(([k, v]) => { + if (k === '$or') return (v as Array>).some((c) => match(r, c)); + return v === null || v === undefined + ? (r as any)[k] === null || (r as any)[k] === undefined + : whereValueMatches((r as any)[k], v); + }); + const engine: any = { + async find(table: string, o?: { where?: Record; limit?: number }) { + if (table !== 'sys_metadata') return []; + const matched = Array.from(rows.values()).filter((r) => match(r, o?.where ?? {})); + return typeof o?.limit === 'number' ? matched.slice(0, o.limit) : matched; + }, + async findOne(table: string, o: { where: Record }) { + assertEngineFindOnePredicate(table, o); + if (table !== 'sys_metadata') return null; + for (const r of rows.values()) if (match(r, o?.where ?? {})) return r; + return null; + }, + async count() { + return 0; + }, + // No `insert` / `update` / `delete`: the save is refused before anything is persisted. + registry: { + registerItem: () => {}, registerObject: () => {}, listItems: () => [], + getItem: () => undefined, getArtifactItem: () => undefined, + removeRuntimeShadow: () => false, removeOverlayEntry: () => {}, uninstallPackage: () => {}, + getPackage: (id: string) => (id === PKG ? { manifest: { id } } : undefined), + }, + }; + return new ObjectStackProtocolImplementation(engine, () => new Map()) as any; +} + +function mockRes() { + const res: any = { + statusCode: 200, + json: vi.fn(function (this: any, body: any) { this._body = body; return this; }), + status: vi.fn(function (this: any, code: number) { this.statusCode = code; return this; }), + send: vi.fn(), + header: vi.fn(), + }; + return res; +} + +describe('REST flat 409 DESTRUCTIVE_CHANGE body carries stillShownBy', () => { + it('names the list view that still shows a removed column, in the top-level issues', async () => { + const protocol = protocolOver(SEED); + let thrown: unknown; + try { + await protocol.saveMetaItem({ + type: 'object', name: 'crm_lead', writeFace: 'meta-envelope', + item: { name: 'crm_lead', label: 'Lead', fields: { name: FIELDS.name } }, + }); + } catch (e) { + thrown = e; + } + expect(thrown).toBeDefined(); + const res = mockRes(); + handleRouteError(res, thrown); + expect(res.statusCode).toBe(409); + expect(res._body.code).toBe('DESTRUCTIVE_CHANGE'); + const removed = res._body.issues.find((i: any) => i.code === 'field_removed' && i.field === 'status'); + expect(removed.stillShownBy).toEqual([{ type: 'view', name: 'crm_lead_open', where: ['columns[1]'] }]); + }); +}); diff --git a/packages/spec/api-surface/api.json b/packages/spec/api-surface/api.json index e8f57c64392..6d2c04ef346 100644 --- a/packages/spec/api-surface/api.json +++ b/packages/spec/api-surface/api.json @@ -342,6 +342,9 @@ "DeleteResponse (type)", "DeleteResponseParsed (type)", "DeleteResponseSchema (const)", + "DestructiveChangeIssue (type)", + "DestructiveChangeIssueParsed (type)", + "DestructiveChangeIssueSchema (const)", "DeviceRequestResponse (type)", "DeviceRequestResponseParsed (type)", "DeviceRequestResponseSchema (const)", @@ -452,6 +455,9 @@ "FieldMappingEntrySchema (const)", "FieldSortability (type)", "FieldSortabilitySchema (const)", + "FieldStillShownBy (type)", + "FieldStillShownByParsed (type)", + "FieldStillShownBySchema (const)", "FileDownloadUrlResponse (type)", "FileDownloadUrlResponseParsed (type)", "FileDownloadUrlResponseSchema (const)", diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 7478fdd78f4..324ab151298 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -306,6 +306,7 @@ "FILTER_LOGIC_CASES (const)", "FILTER_LOGIC_ROWS (const)", "FILTER_OPERATORS (const)", + "FILTER_OPERATOR_FIELD_TYPE_FIT (const)", "FILTER_STRING_STORED_COMPARAND_CASES (const)", "FILTER_STRING_STORED_COMPARAND_FIELDS (const)", "FILTER_STRING_STORED_COMPARAND_ROWS (const)", @@ -367,6 +368,9 @@ "FilterLogicCase (interface)", "FilterLogicRow (interface)", "FilterLoweringOptions (interface)", + "FilterOperatorFieldMeta (type)", + "FilterOperatorFieldTypeFit (type)", + "FilterOperatorFieldTypeFitRow (interface)", "FilterOperatorKey (type)", "FilterSubtreeProvenance (type)", "FilterTextCase (type)", @@ -960,6 +964,7 @@ "deriveRecordFlowSurface (function)", "deriveRecordSurface (function)", "discriminateDefaultValueShape (function)", + "dollarFilterOperatorOf (function)", "driverConfigJsonSchema (function)", "driverHasLocalDefault (function)", "driverSupportsTransactions (function)", @@ -970,6 +975,7 @@ "externalColumnMapTargets (function)", "fieldForm (const)", "fieldGroupBodyTableRefusal (function)", + "filterOperatorFieldTypeFit (function)", "filterSubtreeProvenanceOf (function)", "foldAsciiCase (function)", "foldQueryAliasSlots (function)", diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index eb18472890f..7859f267dd9 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -596,6 +596,10 @@ "api/DeleteResponse:id", "api/DeleteResponse:meta", "api/DeleteResponse:success", + "api/DestructiveChangeIssue:code", + "api/DestructiveChangeIssue:field", + "api/DestructiveChangeIssue:message", + "api/DestructiveChangeIssue:stillShownBy", "api/DeviceRequestResponse:code", "api/DeviceRequestResponse:expiresAt", "api/DeviceRequestResponse:interval [RETIRED]", @@ -766,6 +770,11 @@ "api/FieldSortability:caveat", "api/FieldSortability:reason", "api/FieldSortability:sortable", + "api/FieldStillShownBy:name", + "api/FieldStillShownBy:operator", + "api/FieldStillShownBy:type", + "api/FieldStillShownBy:via", + "api/FieldStillShownBy:where", "api/FileDownloadUrlResponse:data", "api/FileDownloadUrlResponse:error", "api/FileDownloadUrlResponse:meta", diff --git a/packages/spec/declaration-map/api.json b/packages/spec/declaration-map/api.json index b403cf17734..85c5d2b94de 100644 --- a/packages/spec/declaration-map/api.json +++ b/packages/spec/declaration-map/api.json @@ -261,6 +261,8 @@ "DeleteMetaItemResponseSchema": "api/DeleteMetaItemResponse", "DeleteResponse": "api/DeleteResponse", "DeleteResponseSchema": "api/DeleteResponse", + "DestructiveChangeIssue": "api/DestructiveChangeIssue", + "DestructiveChangeIssueSchema": "api/DestructiveChangeIssue", "DeviceRequestResponse": "api/DeviceRequestResponse", "DeviceRequestResponseSchema": "api/DeviceRequestResponse", "DeviceTokenResponse": "api/DeviceTokenResponse", @@ -330,6 +332,8 @@ "FieldMappingEntrySchema": "api/FieldMappingEntry", "FieldSortability": "api/FieldSortability", "FieldSortabilitySchema": "api/FieldSortability", + "FieldStillShownBy": "api/FieldStillShownBy", + "FieldStillShownBySchema": "api/FieldStillShownBy", "FileDownloadUrlResponse": "api/FileDownloadUrlResponse", "FileDownloadUrlResponseSchema": "api/FileDownloadUrlResponse", "FileTypeValidation": "api/FileTypeValidation", diff --git a/packages/spec/export-origins/api.json b/packages/spec/export-origins/api.json index 83837947df5..7663e6efaed 100644 --- a/packages/spec/export-origins/api.json +++ b/packages/spec/export-origins/api.json @@ -328,6 +328,9 @@ "DeleteResponse": "src/api/contract.zod.ts#DeleteResponse (type)", "DeleteResponseParsed": "src/api/contract.zod.ts#DeleteResponseParsed (type)", "DeleteResponseSchema": "src/api/contract.zod.ts#DeleteResponseSchema (const)", + "DestructiveChangeIssue": "src/api/protocol.zod.ts#DestructiveChangeIssue (type)", + "DestructiveChangeIssueParsed": "src/api/protocol.zod.ts#DestructiveChangeIssueParsed (type)", + "DestructiveChangeIssueSchema": "src/api/protocol.zod.ts#DestructiveChangeIssueSchema (const)", "DeviceRequestResponse": "src/api/auth-endpoints.zod.ts#DeviceRequestResponse (type)", "DeviceRequestResponseParsed": "src/api/auth-endpoints.zod.ts#DeviceRequestResponseParsed (type)", "DeviceRequestResponseSchema": "src/api/auth-endpoints.zod.ts#DeviceRequestResponseSchema (const)", @@ -432,6 +435,9 @@ "FieldMappingEntrySchema": "src/api/export.zod.ts#FieldMappingEntrySchema (const)", "FieldSortability": "src/api/sortability.zod.ts#FieldSortability (type)", "FieldSortabilitySchema": "src/api/sortability.zod.ts#FieldSortabilitySchema (const)", + "FieldStillShownBy": "src/api/protocol.zod.ts#FieldStillShownBy (type)", + "FieldStillShownByParsed": "src/api/protocol.zod.ts#FieldStillShownByParsed (type)", + "FieldStillShownBySchema": "src/api/protocol.zod.ts#FieldStillShownBySchema (const)", "FileDownloadUrlResponse": "src/api/storage.zod.ts#FileDownloadUrlResponse (type)", "FileDownloadUrlResponseParsed": "src/api/storage.zod.ts#FileDownloadUrlResponseParsed (type)", "FileDownloadUrlResponseSchema": "src/api/storage.zod.ts#FileDownloadUrlResponseSchema (const)", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index ff649d53cab..d47139f2136 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -301,6 +301,7 @@ "FILTER_LOGIC_CASES": "src/data/filter-logic-conformance.ts#FILTER_LOGIC_CASES (const)", "FILTER_LOGIC_ROWS": "src/data/filter-logic-conformance.ts#FILTER_LOGIC_ROWS (const)", "FILTER_OPERATORS": "src/data/filter.zod.ts#FILTER_OPERATORS (const)", + "FILTER_OPERATOR_FIELD_TYPE_FIT": "src/data/filter-operator-field-type-fit.ts#FILTER_OPERATOR_FIELD_TYPE_FIT (const)", "FILTER_STRING_STORED_COMPARAND_CASES": "src/data/filter-comparand-type-conformance.ts#FILTER_STRING_STORED_COMPARAND_CASES (const)", "FILTER_STRING_STORED_COMPARAND_FIELDS": "src/data/filter-comparand-type-conformance.ts#FILTER_STRING_STORED_COMPARAND_FIELDS (const)", "FILTER_STRING_STORED_COMPARAND_ROWS": "src/data/filter-comparand-type-conformance.ts#FILTER_STRING_STORED_COMPARAND_ROWS (const)", @@ -358,6 +359,9 @@ "FilterLogicCase": "src/data/filter-logic-conformance.ts#FilterLogicCase (interface)", "FilterLogicRow": "src/data/filter-logic-conformance.ts#FilterLogicRow (interface)", "FilterLoweringOptions": "src/data/filter-lowering.ts#FilterLoweringOptions (interface)", + "FilterOperatorFieldMeta": "src/data/filter-operator-field-type-fit.ts#FilterOperatorFieldMeta (type)", + "FilterOperatorFieldTypeFit": "src/data/filter-operator-field-type-fit.ts#FilterOperatorFieldTypeFit (type)", + "FilterOperatorFieldTypeFitRow": "src/data/filter-operator-field-type-fit.ts#FilterOperatorFieldTypeFitRow (interface)", "FilterOperatorKey": "src/data/filter.zod.ts#FilterOperatorKey (type)", "FilterSubtreeProvenance": "src/data/filter-subtree-provenance.ts#FilterSubtreeProvenance (type)", "FilterTextCase": "src/data/filter-text-conformance.ts#FilterTextCase (type)", @@ -946,6 +950,7 @@ "deriveRecordFlowSurface": "src/data/record-surface.ts#deriveRecordFlowSurface (function)", "deriveRecordSurface": "src/data/record-surface.ts#deriveRecordSurface (function)", "discriminateDefaultValueShape": "src/data/default-value-shape.ts#discriminateDefaultValueShape (function)", + "dollarFilterOperatorOf": "src/data/filter.zod.ts#dollarFilterOperatorOf (function)", "driverConfigJsonSchema": "src/data/driver/common.zod.ts#driverConfigJsonSchema (function)", "driverHasLocalDefault": "src/data/driver/config-registry.zod.ts#driverHasLocalDefault (function)", "driverSupportsTransactions": "src/data/driver.zod.ts#driverSupportsTransactions (function)", @@ -956,6 +961,7 @@ "externalColumnMapTargets": "src/data/injected-system-column-provenance.ts#externalColumnMapTargets (function)", "fieldForm": "src/data/field.form.ts#fieldForm (const)", "fieldGroupBodyTableRefusal": "src/data/related-list-body-table.ts#fieldGroupBodyTableRefusal (function)", + "filterOperatorFieldTypeFit": "src/data/filter-operator-field-type-fit.ts#filterOperatorFieldTypeFit (function)", "filterSubtreeProvenanceOf": "src/data/filter-subtree-provenance.ts#filterSubtreeProvenanceOf (function)", "foldAsciiCase": "src/data/filter.zod.ts#foldAsciiCase (function)", "foldQueryAliasSlots": "src/data/data-engine.zod.ts#foldQueryAliasSlots (function)", diff --git a/packages/spec/json-schema.manifest/api.json b/packages/spec/json-schema.manifest/api.json index c1cc71812dd..71466d7487f 100644 --- a/packages/spec/json-schema.manifest/api.json +++ b/packages/spec/json-schema.manifest/api.json @@ -137,6 +137,7 @@ "api/DeleteMetaItemRequest", "api/DeleteMetaItemResponse", "api/DeleteResponse", + "api/DestructiveChangeIssue", "api/DeviceRequestResponse", "api/DeviceTokenResponse", "api/DiffMetaItemRequest", @@ -179,6 +180,7 @@ "api/FieldErrorCode", "api/FieldMappingEntry", "api/FieldSortability", + "api/FieldStillShownBy", "api/FileDownloadUrlResponse", "api/FileTypeValidation", "api/FileUploadResponse", diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 5a777978dc7..af0c47b0b7e 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -1385,6 +1385,79 @@ export const SaveMetaItemResponseSchema = lazySchema(() => z.object({ message: z.string().optional(), })); +/** + * One metadata item that still shows (or, after a type change, still filters + * by) a field a refused `object` save would remove or retype — an entry of + * {@link DestructiveChangeIssueSchema}'s `stillShownBy`. + */ +export const FieldStillShownBySchema = lazySchema(() => z.object({ + type: z.string().describe( + 'The metadata type of the item: `view` (a list view or a form), `dataset`, `dashboard`, `page`, ' + + '`flow`, `report`, or `object` (another object, or the saved object\'s own body).', + ), + name: z.string().describe( + 'The item\'s name, as the served list names it. One item can appear in more than one entry: a ' + + 'dashboard once directly and once per `via` dataset, a view once per unfit `operator`.', + ), + where: z.array(z.string()).describe( + 'Each position inside the item that names the field, as a path relative to the item as the ' + + 'served listing presents it: `config.columns[1]` or `config.sections[0].fields[2]` on a view ' + + 'item (the served listing never presents a `{ list, form, listViews }` container, only the ' + + 'view items it expands into), `columns[1]` on a flattened list overlay, `widgets[3]` on a ' + + 'dashboard. The literal `(root)` when the finding sits on the item itself.', + ), + via: z.string().optional().describe( + 'A dashboard widget shows the field through this dataset: it names a dimension or measure of ' + + 'the dataset, and that dimension or measure names the field.', + ), + operator: z.string().optional().describe( + 'On a `field_type_change` entry only: the filter operator, as the view rule spells it, that ' + + 'no longer fits the new type (`filterOperatorFieldTypeFit` answers `unfit`).', + ), +})); + +/** + * One finding of the `409 DESTRUCTIVE_CHANGE` refusal of an `object` save (the + * save door's destructive-change diff): an entry of the refusal's `issues[]`, + * which every door relays verbatim beside the message — the REST `PUT` doors + * as a top-level `issues`, the runtime dispatcher as `details.issues`, the MCP + * draft door as `error.issues` on its refusal. + */ +export const DestructiveChangeIssueSchema = lazySchema(() => z.object({ + code: z.string().describe( + 'What the save loses: `field_removed`, `field_type_change`, `field_required_no_default`, ' + + '`currency_mode_to_record` or `currency_field_repointed`.', + ), + field: z.string().optional().describe('The field the finding is about.'), + message: z.string().describe( + 'The finding in prose. When `stillShownBy` names items, the prose ends by naming them too.', + ), + stillShownBy: z.array(FieldStillShownBySchema).optional().describe( + 'The metadata items that still show the field, computed from the environment\'s served ' + + 'metadata (one served listing per type: what the code packages register, with this ' + + 'environment\'s stored active rows folded over them; drafts are not read, and no record is read). ' + + 'On `field_removed` and `field_type_change` findings only; absent on every other code, and ' + + 'absent when it could not be computed: a listing could not be read, a judge threw or could not ' + + 'be loaded, or the retyped field\'s new definition carries no readable `type` (absent is "not ' + + 'computed", `[]` is "computed, none"). ' + + 'On `field_removed`: the `object`, `view`, `dataset`, `dashboard`, `page`, `flow` and `report` ' + + 'items in which the platform\'s reference-integrity suite, form-layout check and widget-binding ' + + 'check (`@objectstack/lint`, the judges `os validate` runs) find a reference that resolves with ' + + 'the field and dangles without it, the saved body taken as the save would write it; plus each ' + + 'dashboard widget bound to a dataset dimension or measure that dangles (`via`). A position ' + + 'those judges do not read is not seen, nor is an item of any other type (an app, an action, a ' + + 'permission set), nor code outside the metadata. On `field_type_change`: each filter rule of a ' + + 'served `view` item bound to the saved object that names the field by its bare name and whose ' + + 'operator does not fit the new type, judged by `filterOperatorFieldTypeFit` (an operator is ' + + 'unfit only where a declared-type door refuses it; a filter another door refuses, such as any ' + + 'filter on a field retyped to `formula`, is not named). The rules read are a view item\'s ' + + '`config.filter` (the canonical served shape), a flattened list overlay\'s own `filter`, and ' + + 'the `userFilters.tabs[].filter` of either, rules inside an any-of group included. Filters ' + + 'elsewhere (datasets, dashboards, reports, flows), dotted paths, and comparands are not judged ' + + 'there. The save does not edit any listed item.', + ), +})); + /** * Metadata Conflict — the 409 body of the `/meta/:type/:name` write doors * @@ -4774,6 +4847,12 @@ export type GetMetaItemLayeredResponse = z.input; export type SaveMetaItemRequest = z.input; export type SaveMetaItemResponse = z.input; +export type FieldStillShownBy = z.input; +export type DestructiveChangeIssue = z.input; +/** Post-parse shape of {@link FieldStillShownBy} (ADR-0122). */ +export type FieldStillShownByParsed = z.infer; +/** Post-parse shape of {@link DestructiveChangeIssue} (ADR-0122). */ +export type DestructiveChangeIssueParsed = z.infer; /** The 409 `METADATA_CONFLICT` body of the `/meta/:type/:name` write doors (#22114). */ export type MetadataConflictError = z.input; /** Post-parse shape of {@link MetadataConflictError} — defaults applied, transforms run (ADR-0122). */ diff --git a/packages/spec/src/data/filter-operator-field-type-fit.test.ts b/packages/spec/src/data/filter-operator-field-type-fit.test.ts new file mode 100644 index 00000000000..499f0f2a741 --- /dev/null +++ b/packages/spec/src/data/filter-operator-field-type-fit.test.ts @@ -0,0 +1,59 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { FieldType } from './field.zod'; +import { + FILTER_OPERATOR_FIELD_TYPE_FIT, + filterOperatorFieldTypeFit, +} from './filter-operator-field-type-fit'; +import { + TEXT_FILTER_OPERATORS, + textOperatorDoorVerdict, +} from './filter-text-operator-declared-type'; +import { VIEW_FILTER_OPERATORS } from '../ui/view.zod'; + +describe('filterOperatorFieldTypeFit — the one operator-by-field-type judgement', () => { + it('answers the text-operator door\'s verdict for every field type and every text operator', () => { + for (const type of FieldType.options) { + const door = textOperatorDoorVerdict({ type }); + const want = door === 'door-refusal' ? 'unfit' : door === 'deferred' ? 'unjudged' : 'fits'; + for (const op of TEXT_FILTER_OPERATORS) { + expect(filterOperatorFieldTypeFit(op, { type }), `${op} over ${type}`).toBe(want); + } + } + }); + + it('folds the view vocabulary and its aliases onto the same answer', () => { + expect(filterOperatorFieldTypeFit('contains', { type: 'number' })).toBe('unfit'); + expect(filterOperatorFieldTypeFit('not_contains', { type: 'date' })).toBe('unfit'); + expect(filterOperatorFieldTypeFit('notContains', { type: 'boolean' })).toBe('unfit'); + expect(filterOperatorFieldTypeFit('startsWith', { type: 'currency' })).toBe('unfit'); + expect(filterOperatorFieldTypeFit('contains', { type: 'text' })).toBe('fits'); + expect(filterOperatorFieldTypeFit('contains', { type: 'select' })).toBe('fits'); + }); + + it('calls an operator no door judges by type a fit, and an unknown spelling unjudged', () => { + expect(filterOperatorFieldTypeFit('greater_than', { type: 'boolean' })).toBe('fits'); + expect(filterOperatorFieldTypeFit('equals', { type: 'number' })).toBe('fits'); + expect(filterOperatorFieldTypeFit('$gt', { type: 'text' })).toBe('fits'); + expect(filterOperatorFieldTypeFit('resembles', { type: 'text' })).toBe('unjudged'); + expect(filterOperatorFieldTypeFit('$resembles', { type: 'text' })).toBe('unjudged'); + }); + + it('defers a formula whose return type it cannot read', () => { + expect(filterOperatorFieldTypeFit('contains', { type: 'formula' })).toBe('unjudged'); + expect(filterOperatorFieldTypeFit('contains', { type: 'formula', returnType: 'number' })).toBe('unfit'); + }); + + it('judges every canonical view operator (none falls outside the vocabulary)', () => { + for (const op of VIEW_FILTER_OPERATORS) { + expect(filterOperatorFieldTypeFit(op, { type: 'text' }), op).not.toBe('unjudged'); + } + }); + + it('holds one row per door, each naming operators the door itself exports', () => { + expect(FILTER_OPERATOR_FIELD_TYPE_FIT.map((r) => r.door)).toEqual(['filter-text-operator-declared-type']); + expect(FILTER_OPERATOR_FIELD_TYPE_FIT[0].operators).toBe(TEXT_FILTER_OPERATORS); + expect(Object.isFrozen(FILTER_OPERATOR_FIELD_TYPE_FIT)).toBe(true); + }); +}); diff --git a/packages/spec/src/data/filter-operator-field-type-fit.ts b/packages/spec/src/data/filter-operator-field-type-fit.ts new file mode 100644 index 00000000000..cf0bfbdc503 --- /dev/null +++ b/packages/spec/src/data/filter-operator-field-type-fit.ts @@ -0,0 +1,114 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Which filter operator FITS which declared field type: the one exported + * judgement every door asks, so no door keeps its own operator-by-type table. + * + * ## What "fits" means here, and why it is this narrow + * + * An operator does NOT fit a field type when a declared-type door of the + * platform REFUSES that operator over a field of that type. That is a fact the + * runtime enforces, so a caller that reports "this filter stops fitting" (the + * destructive-change answer's `stillShownBy` for a type change, a hosted build + * door's preview) reports a filter that will be refused, never a matter of + * taste. Every other pair fits: an ordering operator over a `boolean`, say, is + * answered by the engine, so it is not called unfit here. + * + * ## The rows are the doors, by reference + * + * {@link FILTER_OPERATOR_FIELD_TYPE_FIT} holds one row per declared-type door + * that judges an operator CLASS. Each row names its operators and its verdict + * by reference to the door's own exports — never a re-listing of field types. + * Today there is one door of that kind: the text-operator declared-type door + * (`filter-text-operator-declared-type.ts`, #15661), whose ruled verdict + * ({@link textOperatorDoorVerdict}) refuses a text operator over a type that can + * never store a string, with `INVALID_FILTER` / 400 at the engine's field-aware + * seam. A declared-type door added later that judges an operator class adds its + * row here, and every caller of {@link filterOperatorFieldTypeFit} sees it. + * + * The comparand doors (number, boolean, temporal, string-stored) judge the + * VALUE a filter compares with, not its operator, and are deliberately not + * rows: a type change that leaves a stored comparand unreadable is a different + * question from an operator that stops fitting. + * + * ## Not the filter builder's offer + * + * `@object-ui/components`' `operatorsForFieldType` decides which operators a + * dropdown DRAWS for a column. That is an offer, wider and narrower than this + * judgement in places (it draws no ordering operator over a `select`, which the + * engine still answers). This module judges what the runtime refuses. + */ + +import { dollarFilterOperatorOf, FILTER_OPERATORS } from './filter.zod'; +import { + TEXT_FILTER_OPERATORS, + textOperatorDoorVerdict, + type TextOperatorDoorFieldMeta, +} from './filter-text-operator-declared-type'; + +/** + * The judgement's three answers. + * + * - `fits` — no declared-type door refuses this operator over this field. + * - `unfit` — a declared-type door refuses it (the row's `refusal` says how). + * - `unjudged` — the operator spelling is outside the vocabulary, or the door + * that would judge it records no verdict for this field (a `formula` whose + * return type cannot be read). + */ +export type FilterOperatorFieldTypeFit = 'fits' | 'unfit' | 'unjudged'; + +/** The slice of a field definition the judgement reads. */ +export type FilterOperatorFieldMeta = TextOperatorDoorFieldMeta; + +/** One declared-type door that judges an operator class. */ +export interface FilterOperatorFieldTypeFitRow { + /** The door, named after the module that declares it. */ + readonly door: string; + /** The `$`-spelled operators the door judges — the door's own export. */ + readonly operators: readonly string[]; + /** The door's verdict for one field, folded onto this judgement's answers. */ + readonly verdict: (field: FilterOperatorFieldMeta) => FilterOperatorFieldTypeFit; + /** What the runtime answers an unfit filter with. */ + readonly refusal: string; +} + +/** + * The operator-by-field-type judgement: one row per declared-type door that + * judges an operator class. Read it through {@link filterOperatorFieldTypeFit}. + */ +export const FILTER_OPERATOR_FIELD_TYPE_FIT: readonly FilterOperatorFieldTypeFitRow[] = Object.freeze([ + Object.freeze({ + door: 'filter-text-operator-declared-type', + operators: TEXT_FILTER_OPERATORS, + verdict: (field: FilterOperatorFieldMeta): FilterOperatorFieldTypeFit => { + const verdict = textOperatorDoorVerdict(field); + return verdict === 'door-refusal' ? 'unfit' : verdict === 'deferred' ? 'unjudged' : 'fits'; + }, + refusal: 'INVALID_FILTER (400) at the engine\'s field-aware seam: a text operator over a field whose declared ' + + 'type can never store a string', + }), +]); + +/** Every `$` operator the judgement knows: the declared field operators and the text-operator door's set. */ +const KNOWN_DOLLAR_OPERATORS: ReadonlySet = new Set([ + ...FILTER_OPERATORS, + ...TEXT_FILTER_OPERATORS, +]); + +/** + * Does `operator` fit a field declared as `field`? `operator` is any spelling + * the filter vocabularies accept: a view rule's (`contains`, `not_contains`), + * an alias (`notContains`, `startsWith`), an infix one (`>`, `before`) or a `$` + * one (`$contains`). Pure: no I/O. + */ +export function filterOperatorFieldTypeFit( + operator: string, + field: FilterOperatorFieldMeta, +): FilterOperatorFieldTypeFit { + const dollar = dollarFilterOperatorOf(operator); + if (dollar === undefined || !KNOWN_DOLLAR_OPERATORS.has(dollar)) return 'unjudged'; + for (const row of FILTER_OPERATOR_FIELD_TYPE_FIT) { + if (row.operators.includes(dollar)) return row.verdict(field); + } + return 'fits'; +} diff --git a/packages/spec/src/data/filter.zod.ts b/packages/spec/src/data/filter.zod.ts index 6fab064a139..0c554a479dd 100644 --- a/packages/spec/src/data/filter.zod.ts +++ b/packages/spec/src/data/filter.zod.ts @@ -2830,6 +2830,28 @@ export function canonicalAstOperator(op: string): string { return CANONICAL_INFIX[dollar] ?? lower; } +/** + * The `$`-spelled field operator one operator spelling names, or `undefined` + * for a spelling outside the vocabulary. + * + * An infix or view spelling ({@link VALID_AST_OPERATORS}, case-insensitive: + * `contains`, `not_contains`, `notContains`, `>`, `before`, …) is lowered + * through {@link AST_OPERATOR_MAP}, the table {@link canonicalAstOperator} + * folds through. A `$` spelling is handed back as written: which `$` names a + * consumer accepts is that consumer's vocabulary, not this lowering's. + * + * The lowering erases a direction on two pairs, as every lowering here does: + * `is_null` and `is_not_null` both name `$null`, `is_empty` and `is_not_empty` + * both name `$empty`. A consumer that judges by operator CLASS (which operator + * a declared field type admits) reads this; one that needs the direction reads + * {@link canonicalAstOperator}. + */ +export function dollarFilterOperatorOf(op: string): string | undefined { + const spelled = String(op); + if (spelled.startsWith('$')) return spelled; + return astOperatorLowering(spelled.toLowerCase()); +} + /** * Detect whether a value is a valid Filter AST array structure. * diff --git a/packages/spec/src/data/index.ts b/packages/spec/src/data/index.ts index 79f1d73f44c..b32ed5b7492 100644 --- a/packages/spec/src/data/index.ts +++ b/packages/spec/src/data/index.ts @@ -100,6 +100,11 @@ export * from './filter-comparand-type-conformance'; // door it declares, like `filter-comparand-type`, not as a driver case-set: // drivers sit beneath this door and keep answering FILTER_TEXT_CASES' row. export * from './filter-text-operator-declared-type'; +// Which filter operator fits which declared field type: one row per +// declared-type door that judges an operator class (today the text-operator +// door above, by reference), read through `filterOperatorFieldTypeFit` by every +// door that reports a filter a type change leaves unfit. +export * from './filter-operator-field-type-fit'; // [#20311] The `$empty` expansion — the ruled per-type 「is empty」 table read // off a field DEFINITION (text-like, multi-value, null only) plus the // value-level predicate for the faces with no declaration. The operator is diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 14a85f7d948..f5700155408 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -911,6 +911,11 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/metadata-protocol/src/protocol.destructive-still-shown-by.test.ts", + "verb": "findOne", + "pinned": 1 + }, { "file": "packages/metadata-protocol/src/protocol.diagnostics-store-outage.test.ts", "verb": "findOne", @@ -4996,6 +5001,11 @@ "verb": "findOne", "pinned": 2 }, + { + "file": "packages/rest/src/meta-destructive-still-shown-by-flat-issues.test.ts", + "verb": "findOne", + "pinned": 1 + }, { "file": "packages/rest/src/meta-disabled-package-doors.test.ts", "verb": "delete",