diff --git a/content/docs/references/ui/view.mdx b/content/docs/references/ui/view.mdx index daa45afc79b..a24a4a0a575 100644 --- a/content/docs/references/ui/view.mdx +++ b/content/docs/references/ui/view.mdx @@ -24,7 +24,7 @@ failure direction below is discoverable from the key being written: |:---|:---|:---|:---| | standalone **ViewItem record** | a nested `config` | `ViewItemNameSchema` — `QUALIFIED_ITEM_NAME_PATTERN`, dot REQUIRED | **rejected**, located at `["name"]` | | flattened runtime **overlay** | an inline view config; no `config`, no container slot | `z.string().optional()` — no grammar at all | accepted | -| `defineView` **container** | a container slot (`list` / `form` / `listViews` / `formViews`) | `z.string().optional()` on `ViewSchema` — no grammar at all | accepted, and normally IS flat | +| `defineView` **container** | a container slot (`list` / `listViews`; a body that names the retired `form` / `formViews` is read as a container too, and refused with their prescription) | `z.string().optional()` on `ViewSchema` — no grammar at all | accepted, and normally IS flat | The two permissive rows are deliberate, not gaps left to tighten later: @@ -2114,9 +2114,9 @@ Tab configuration for multi-tab view interface | **label** | `string \| Record` | optional | Human-readable label shown in metadata lists. | | **object** | `string` | optional | Object this container binds to — how a stack-level `views: [...]` entry says which object its views belong to; read by `getViewsByObject()` / `GET /meta/view?object=`. | | **list** | `{ name?: string; label?: string \| Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }` | optional | | -| **form** | `{ type?: Enum<'simple' \| 'tabbed' \| 'wizard'>; layout?: Enum<'vertical' \| 'horizontal'>; columns?: integer; title?: string; … }` | optional | | +| **form** | `never` | optional | [REMOVED] `view.form` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7) — a form is its own metadata type, and a `view` holds lists only. Move the form to the stack's `forms:` as a `form` item named `OBJECT.form` (`defineForm({ name, object, sections, … })`, the body at the top level and bound with `object`); a record's New and Edit dialogs lay out by the object's `fieldGroups` and read no form, so a create or edit form that nothing else opens is deleted, not moved. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **listViews** | `Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }>` | optional | Additional named list views (views mode — dropdown userFilters allowed, no tabs; ADR-0047) | -| **formViews** | `Record; layout?: Enum<'vertical' \| 'horizontal'>; columns?: integer; title?: string; … }>` | optional | Additional named form views | +| **formViews** | `never` | optional | [REMOVED] `view.formViews` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7) — a form is its own metadata type, and a `view` holds lists only. Move each entry to the stack's `forms:` as a `form` item named `OBJECT.KEY` (`defineForm({ name, object, sections, … })`, the body at the top level and bound with `object`); the name stays the one it is served under, so a `type: 'form'` action and a public link keep reaching it. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **protection** | `{ lock: Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>; reason: string; docsUrl?: string }` | optional | Package author protection block — lock policy for this view. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | @@ -2178,34 +2178,6 @@ Tab configuration for multi-tab view interface | **aria** | `{ ariaLabel?: string \| Record; ariaDescribedBy?: string; role?: string }` | optional | ARIA accessibility attributes for the list view | | **userFilters** | `{ element?: Enum<'dropdown' \| 'toggle'>; fields?: object[] }` | optional | | -### Nested Shape: `View.form` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **type** | `Enum<'simple' \| 'tabbed' \| 'wizard'>` | optional (default: `"simple"`) | Form layout: 'simple' (stacked sections, the default), 'tabbed' (one tab per section) or 'wizard' (one gated step per section). Where the form opens is the caller's choice, not the form's | -| **layout** | `Enum<'vertical' \| 'horizontal'>` | optional | Field layout direction — 'vertical' (the renderer default) or 'horizontal'. Multi-column is not a layout value: set `columns` | -| **columns** | `integer` | optional | Number of columns for the form body | -| **title** | `string` | optional | Form title | -| **description** | `string` | optional | Form description | -| **defaultTab** | `string` | optional | Initially active tab (tabbed forms) | -| **tabPosition** | `Enum<'top' \| 'bottom' \| 'left' \| 'right'>` | optional | Tab strip position (tabbed forms) | -| **allowSkip** | `boolean` | optional | Wizard step-gate opt-out: allow entering a later step without submitting the one before it. Navigation freedom, NOT a validation exemption — the final submit still re-validates every step and returns to the first failing one. Default (absent/false): steps unlock in array order as each prior step submits validly. UI admission only, never authorization. | -| **showStepIndicator** | `boolean` | optional | Show the wizard step indicator (renderer default: shown). Step progress (completed/current/upcoming/invalid) is derived from the step gate — this boolean is the only authorable progress surface. | -| **splitDirection** | `never` | optional | [REMOVED] `view.form.splitDirection` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it set the pane orientation of a split form, and the split form renderer retired in the same release, so no form draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitSize** | `never` | optional | [REMOVED] `view.form.splitSize` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it sized the primary pane of a `type: 'split'` form, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitResizable** | `never` | optional | [REMOVED] `view.form.splitResizable` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it made the panes of a `type: 'split'` form resizable, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerSide** | `never` | optional | [REMOVED] `view.form.drawerSide` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it. Delete the key: an object's list opens a record in its drawer from the hover icon, and the React `ObjectForm` block keeps its own `drawerSide` prop for the drawer it opens with `formType='drawer'`. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerWidth** | `never` | optional | [REMOVED] `view.form.drawerWidth` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it, and a pixel width cannot be chosen without knowing the client viewport. Delete the key: a list's record drawer takes its starting width from the `navigation.size` bucket, and the React `ObjectForm` block keeps its own `drawerWidth` prop for the drawer it opens. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **modalSize** | `never` | optional | [REMOVED] `view.form.modalSize` was removed in @objectstack/spec 19.0.0 (ADR-0049) — no form view opens in a dialog, so nothing reads it from a form view. Delete the key: the console's New and Edit dialogs lay a record out by the object's `fieldGroups` and choose their own size, a form opened by name gets a page of its own, and the React `ObjectForm` block keeps its own `modalSize` prop for the modal it opens with `formType='modal'`. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **data** | `{ provider: 'object'; object: string } \| { provider: 'value'; items: any[] } \| { provider: 'schema'; schemaId: string; schema?: Record }` | optional | Data source configuration (defaults to "object" provider) | -| **sections** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | | -| **groups** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | [LEGACY ALIAS → `sections`] Accepted for back-compat and folded onto `sections` at parse; `sections` wins when both are present. Prefer `sections`. | -| **subforms** | `{ childObject: string; relationshipField?: string; columns?: object[]; amountField?: string; … }[]` | optional | Inline master-detail child collections | -| **sharing** | `{ enabled?: boolean; publicLink?: string; password?: string; allowedDomains?: string[]; … }` | optional | Public sharing configuration for this form | -| **submitBehavior** | `{ kind: 'thank-you'; title?: string; message?: string } \| { kind: 'redirect'; url: string; delayMs?: integer } \| { kind: 'continue' } \| { kind: 'next-record' }` | optional | Post-submit behavior. On the `redirect` arm, `url` is relative-only and interpolates only declared record fields as `{{record.field_name}}`, URL-escaped. | -| **buttons** | `{ submit?: object; cancel?: object }` | optional | Form action-button visibility & labels; folded onto the flat renderer props by ObjectUI ObjectForm. | -| **defaults** | `Record` | optional | Initial field values for create-mode forms (folded into ObjectUI ObjectForm initial values;). | - ### Nested Shape: `View.listViews[string]` | Property | Type | Required | Description | @@ -2258,34 +2230,6 @@ Tab configuration for multi-tab view interface | **aria** | `{ ariaLabel?: string \| Record; ariaDescribedBy?: string; role?: string }` | optional | ARIA accessibility attributes for the list view | | **userFilters** | `{ element?: Enum<'dropdown' \| 'toggle'>; fields?: object[] }` | optional | | -### Nested Shape: `View.formViews[string]` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **type** | `Enum<'simple' \| 'tabbed' \| 'wizard'>` | optional (default: `"simple"`) | Form layout: 'simple' (stacked sections, the default), 'tabbed' (one tab per section) or 'wizard' (one gated step per section). Where the form opens is the caller's choice, not the form's | -| **layout** | `Enum<'vertical' \| 'horizontal'>` | optional | Field layout direction — 'vertical' (the renderer default) or 'horizontal'. Multi-column is not a layout value: set `columns` | -| **columns** | `integer` | optional | Number of columns for the form body | -| **title** | `string` | optional | Form title | -| **description** | `string` | optional | Form description | -| **defaultTab** | `string` | optional | Initially active tab (tabbed forms) | -| **tabPosition** | `Enum<'top' \| 'bottom' \| 'left' \| 'right'>` | optional | Tab strip position (tabbed forms) | -| **allowSkip** | `boolean` | optional | Wizard step-gate opt-out: allow entering a later step without submitting the one before it. Navigation freedom, NOT a validation exemption — the final submit still re-validates every step and returns to the first failing one. Default (absent/false): steps unlock in array order as each prior step submits validly. UI admission only, never authorization. | -| **showStepIndicator** | `boolean` | optional | Show the wizard step indicator (renderer default: shown). Step progress (completed/current/upcoming/invalid) is derived from the step gate — this boolean is the only authorable progress surface. | -| **splitDirection** | `never` | optional | [REMOVED] `view.form.splitDirection` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it set the pane orientation of a split form, and the split form renderer retired in the same release, so no form draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitSize** | `never` | optional | [REMOVED] `view.form.splitSize` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it sized the primary pane of a `type: 'split'` form, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitResizable** | `never` | optional | [REMOVED] `view.form.splitResizable` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it made the panes of a `type: 'split'` form resizable, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerSide** | `never` | optional | [REMOVED] `view.form.drawerSide` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it. Delete the key: an object's list opens a record in its drawer from the hover icon, and the React `ObjectForm` block keeps its own `drawerSide` prop for the drawer it opens with `formType='drawer'`. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerWidth** | `never` | optional | [REMOVED] `view.form.drawerWidth` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it, and a pixel width cannot be chosen without knowing the client viewport. Delete the key: a list's record drawer takes its starting width from the `navigation.size` bucket, and the React `ObjectForm` block keeps its own `drawerWidth` prop for the drawer it opens. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **modalSize** | `never` | optional | [REMOVED] `view.form.modalSize` was removed in @objectstack/spec 19.0.0 (ADR-0049) — no form view opens in a dialog, so nothing reads it from a form view. Delete the key: the console's New and Edit dialogs lay a record out by the object's `fieldGroups` and choose their own size, a form opened by name gets a page of its own, and the React `ObjectForm` block keeps its own `modalSize` prop for the modal it opens with `formType='modal'`. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **data** | `{ provider: 'object'; object: string } \| { provider: 'value'; items: any[] } \| { provider: 'schema'; schemaId: string; schema?: Record }` | optional | Data source configuration (defaults to "object" provider) | -| **sections** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | | -| **groups** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | [LEGACY ALIAS → `sections`] Accepted for back-compat and folded onto `sections` at parse; `sections` wins when both are present. Prefer `sections`. | -| **subforms** | `{ childObject: string; relationshipField?: string; columns?: object[]; amountField?: string; … }[]` | optional | Inline master-detail child collections | -| **sharing** | `{ enabled?: boolean; publicLink?: string; password?: string; allowedDomains?: string[]; … }` | optional | Public sharing configuration for this form | -| **submitBehavior** | `{ kind: 'thank-you'; title?: string; message?: string } \| { kind: 'redirect'; url: string; delayMs?: integer } \| { kind: 'continue' } \| { kind: 'next-record' }` | optional | Post-submit behavior. On the `redirect` arm, `url` is relative-only and interpolates only declared record fields as `{{record.field_name}}`, URL-escaped. | -| **buttons** | `{ submit?: object; cancel?: object }` | optional | Form action-button visibility & labels; folded onto the flat renderer props by ObjectUI ObjectForm. | -| **defaults** | `Record` | optional | Initial field values for create-mode forms (folded into ObjectUI ObjectForm initial values;). | - ### Nested Shape: `View.protection` | Property | Type | Required | Description | @@ -2503,7 +2447,7 @@ This schema accepts one of the following structures: | **_lockDocsUrl** | `string` | optional | Optional documentation link surfaced next to _lockReason. | | **overrides** | `{ package: string; basedOn: string }` | optional | Override declaration (ADR-0146 D2): `{ package, basedOn }` — this item of "``.custom" replaces the base package's same-named item whole. `basedOn` is recorded and never gates; a base's upgrade plan reads it only as advice. | -### Nested Shape: `ViewItem[viewKind='list'].config` +### Nested Shape: `ViewItem.config` | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | @@ -2555,7 +2499,7 @@ This schema accepts one of the following structures: | **emptyState** | `{ title?: string \| Record; message?: string \| Record; icon?: string; link?: object }` | optional | Empty state configuration when no records found | | **aria** | `{ ariaLabel?: string \| Record; ariaDescribedBy?: string; role?: string }` | optional | ARIA accessibility attributes for the list view | -### Nested Shape: `ViewItem[viewKind='list'].protection` +### Nested Shape: `ViewItem.protection` | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | @@ -2563,78 +2507,7 @@ This schema accepts one of the following structures: | **reason** | `string` | ✅ | User-visible reason shown when the lock blocks an action. | | **docsUrl** | `string` | optional | Optional URL the Studio banner links to for more context. | -### Nested Shape: `ViewItem[viewKind='list'].overrides` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **package** | `string` | ✅ | The base package id whose same-named item this item replaces whole (e.g. "com.acme.crm"). Only an item of the base's paired "``.custom" package declares an override. | -| **basedOn** | `string` | ✅ | Recorded, never a gate: the base package's `manifest.version` this override was taken from (e.g. "3.2.0"), not a history version of the item. Nothing is refused, merged or rebased on it; it tells a person re-basing the override where it started. One reader, as advice: a base's upgrade plan lists an override whose `basedOn` is not the installed base version as stale, beside each override whose base item the upgrade changes (ADR-0146 D2, as amended). | - ---- - -#### Option 2 - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **viewKind** | `'form'` | ✅ | | -| **config** | `{ type?: Enum<'simple' \| 'tabbed' \| 'wizard'>; layout?: Enum<'vertical' \| 'horizontal'>; columns?: integer; title?: string; … }` | ✅ | Form view configuration. | -| **name** | `string` | ✅ | Globally-unique view id, `.`. | -| **object** | `string` | ✅ | Bound object name — the foreign key used to aggregate views. | -| **label** | `string \| Record` | optional | Display label (supports i18n). | -| **isDefault** | `boolean` | optional | Whether this is the object's default view in the switcher. | -| **order** | `integer` | optional | Sort order within the object's view switcher / left rail. | -| **scope** | `Enum<'package' \| 'shared'>` | optional | Identity layer (defaults to `package` for source-loaded views). | -| **owner** | `never` | optional | [REMOVED] `view.owner` was removed in @objectstack/spec 17.5.0 (ADR-0049 enforce-or-remove) — it named the user a `personal` view item belonged to, and nothing ever read it: the view switcher (`GET /meta/view?object=`) serves every item bound to the object without looking at `owner`, so a view marked as one user's was listed for every user who can read the object. Delete the key. Nothing restricts a view item to one user — personal named views are a user-owned record, not a view item (ADR-0017) — so a view item is visible to everyone who can read its object. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **hidden** | `never` | optional | [REMOVED] `view.hidden` was removed in @objectstack/spec 17.5.0 (ADR-0049 enforce-or-remove) — it promised to hide a view item from the switcher, and nothing ever read it: `GET /meta/view?object=` and the console's view switcher list every item bound to the object, `hidden: true` included. Delete the key; to take a view out of the switcher, delete the view item itself (or stop shipping it from source). Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **protection** | `{ lock: Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>; reason: string; docsUrl?: string }` | optional | Package author protection block — lock policy for this view. | -| **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | -| **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | -| **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | -| **_provenance** | `Enum<'package' \| 'org' \| 'env-forced' \| 'platform'>` | optional | Origin of the item (package \| org \| env-forced \| platform). | -| **_packageId** | `string` | optional | Owning package machine id. | -| **_packageVersion** | `string` | optional | Owning package version. | -| **_lockDocsUrl** | `string` | optional | Optional documentation link surfaced next to _lockReason. | -| **overrides** | `{ package: string; basedOn: string }` | optional | Override declaration (ADR-0146 D2): `{ package, basedOn }` — this item of "``.custom" replaces the base package's same-named item whole. `basedOn` is recorded and never gates; a base's upgrade plan reads it only as advice. | - -### Nested Shape: `ViewItem[viewKind='form'].config` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **type** | `Enum<'simple' \| 'tabbed' \| 'wizard'>` | optional (default: `"simple"`) | Form layout: 'simple' (stacked sections, the default), 'tabbed' (one tab per section) or 'wizard' (one gated step per section). Where the form opens is the caller's choice, not the form's | -| **layout** | `Enum<'vertical' \| 'horizontal'>` | optional | Field layout direction — 'vertical' (the renderer default) or 'horizontal'. Multi-column is not a layout value: set `columns` | -| **columns** | `integer` | optional | Number of columns for the form body | -| **title** | `string` | optional | Form title | -| **description** | `string` | optional | Form description | -| **defaultTab** | `string` | optional | Initially active tab (tabbed forms) | -| **tabPosition** | `Enum<'top' \| 'bottom' \| 'left' \| 'right'>` | optional | Tab strip position (tabbed forms) | -| **allowSkip** | `boolean` | optional | Wizard step-gate opt-out: allow entering a later step without submitting the one before it. Navigation freedom, NOT a validation exemption — the final submit still re-validates every step and returns to the first failing one. Default (absent/false): steps unlock in array order as each prior step submits validly. UI admission only, never authorization. | -| **showStepIndicator** | `boolean` | optional | Show the wizard step indicator (renderer default: shown). Step progress (completed/current/upcoming/invalid) is derived from the step gate — this boolean is the only authorable progress surface. | -| **splitDirection** | `never` | optional | [REMOVED] `view.form.splitDirection` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it set the pane orientation of a split form, and the split form renderer retired in the same release, so no form draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitSize** | `never` | optional | [REMOVED] `view.form.splitSize` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it sized the primary pane of a `type: 'split'` form, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitResizable** | `never` | optional | [REMOVED] `view.form.splitResizable` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it made the panes of a `type: 'split'` form resizable, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerSide** | `never` | optional | [REMOVED] `view.form.drawerSide` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it. Delete the key: an object's list opens a record in its drawer from the hover icon, and the React `ObjectForm` block keeps its own `drawerSide` prop for the drawer it opens with `formType='drawer'`. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerWidth** | `never` | optional | [REMOVED] `view.form.drawerWidth` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it, and a pixel width cannot be chosen without knowing the client viewport. Delete the key: a list's record drawer takes its starting width from the `navigation.size` bucket, and the React `ObjectForm` block keeps its own `drawerWidth` prop for the drawer it opens. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **modalSize** | `never` | optional | [REMOVED] `view.form.modalSize` was removed in @objectstack/spec 19.0.0 (ADR-0049) — no form view opens in a dialog, so nothing reads it from a form view. Delete the key: the console's New and Edit dialogs lay a record out by the object's `fieldGroups` and choose their own size, a form opened by name gets a page of its own, and the React `ObjectForm` block keeps its own `modalSize` prop for the modal it opens with `formType='modal'`. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **data** | `{ provider: 'object'; object: string } \| { provider: 'value'; items: any[] } \| { provider: 'schema'; schemaId: string; schema?: Record }` | optional | Data source configuration (defaults to "object" provider) | -| **sections** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | | -| **groups** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | [LEGACY ALIAS → `sections`] Accepted for back-compat and folded onto `sections` at parse; `sections` wins when both are present. Prefer `sections`. | -| **subforms** | `{ childObject: string; relationshipField?: string; columns?: object[]; amountField?: string; … }[]` | optional | Inline master-detail child collections | -| **sharing** | `{ enabled?: boolean; publicLink?: string; password?: string; allowedDomains?: string[]; … }` | optional | Public sharing configuration for this form | -| **submitBehavior** | `{ kind: 'thank-you'; title?: string; message?: string } \| { kind: 'redirect'; url: string; delayMs?: integer } \| { kind: 'continue' } \| { kind: 'next-record' }` | optional | Post-submit behavior. On the `redirect` arm, `url` is relative-only and interpolates only declared record fields as `{{record.field_name}}`, URL-escaped. | -| **buttons** | `{ submit?: object; cancel?: object }` | optional | Form action-button visibility & labels; folded onto the flat renderer props by ObjectUI ObjectForm. | -| **defaults** | `Record` | optional | Initial field values for create-mode forms (folded into ObjectUI ObjectForm initial values;). | - -### Nested Shape: `ViewItem[viewKind='form'].protection` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | ✅ | Lock policy — none \| no-overlay \| no-delete \| full. | -| **reason** | `string` | ✅ | User-visible reason shown when the lock blocks an action. | -| **docsUrl** | `string` | optional | Optional URL the Studio banner links to for more context. | - -### Nested Shape: `ViewItem[viewKind='form'].overrides` +### Nested Shape: `ViewItem.overrides` | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | @@ -2692,7 +2565,7 @@ This schema accepts one of the following structures: | **columnState** | `never` | optional | [REMOVED] `view.columnState` was removed in @objectstack/spec 19.0.0 (ADR-0049 enforce-or-remove) — it held one column order and set of widths on a shared view row; nothing writes it any more, and a stored layout is no longer applied, so every reader sees the view's own column order and widths. The console keeps column widths in each reader's browser and saves a column order into the view itself. Delete the key. To ship a column order, list `columns` in that order (or set `fieldOrder`); to ship a width, set `width` on the column. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **options** | `never` | optional | Refused: a view item record carries no top-level `options` bag. Its per-kind blocks live under `config` (`config.kanban`, `config.timeline`, …); the legacy `options.KIND` bag belongs to the flattened list overlay only. | -### Nested Shape: `ViewItemWire[viewKind='list'].config` +### Nested Shape: `ViewItemWire.config` | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | @@ -2744,83 +2617,7 @@ This schema accepts one of the following structures: | **emptyState** | `{ title?: string \| Record; message?: string \| Record; icon?: string; link?: object }` | optional | Empty state configuration when no records found | | **aria** | `{ ariaLabel?: string \| Record; ariaDescribedBy?: string; role?: string }` | optional | ARIA accessibility attributes for the list view | -### Nested Shape: `ViewItemWire[viewKind='list'].protection` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | ✅ | Lock policy — none \| no-overlay \| no-delete \| full. | -| **reason** | `string` | ✅ | User-visible reason shown when the lock blocks an action. | -| **docsUrl** | `string` | optional | Optional URL the Studio banner links to for more context. | - -### Nested Shape: `ViewItemWire[viewKind='list'].overrides` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **package** | `string` | ✅ | The base package id whose same-named item this item replaces whole (e.g. "com.acme.crm"). Only an item of the base's paired "``.custom" package declares an override. | -| **basedOn** | `string` | ✅ | Recorded, never a gate: the base package's `manifest.version` this override was taken from (e.g. "3.2.0"), not a history version of the item. Nothing is refused, merged or rebased on it; it tells a person re-basing the override where it started. One reader, as advice: a base's upgrade plan lists an override whose `basedOn` is not the installed base version as stale, beside each override whose base item the upgrade changes (ADR-0146 D2, as amended). | - ---- - -#### Option 2 - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **viewKind** | `'form'` | ✅ | | -| **config** | `{ type?: Enum<'simple' \| 'tabbed' \| 'wizard'>; layout?: Enum<'vertical' \| 'horizontal'>; columns?: integer; title?: string; … }` | ✅ | Form view configuration. | -| **name** | `string` | ✅ | Globally-unique view id, `.`. | -| **object** | `string` | ✅ | Bound object name — the foreign key used to aggregate views. | -| **label** | `string \| Record` | optional | Display label (supports i18n). | -| **isDefault** | `boolean` | optional | Whether this is the object's default view in the switcher. | -| **order** | `integer` | optional | Sort order within the object's view switcher / left rail. | -| **scope** | `Enum<'package' \| 'shared'>` | optional | Identity layer (defaults to `package` for source-loaded views). | -| **owner** | `never` | optional | [REMOVED] `view.owner` was removed in @objectstack/spec 17.5.0 (ADR-0049 enforce-or-remove) — it named the user a `personal` view item belonged to, and nothing ever read it: the view switcher (`GET /meta/view?object=`) serves every item bound to the object without looking at `owner`, so a view marked as one user's was listed for every user who can read the object. Delete the key. Nothing restricts a view item to one user — personal named views are a user-owned record, not a view item (ADR-0017) — so a view item is visible to everyone who can read its object. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **hidden** | `never` | optional | [REMOVED] `view.hidden` was removed in @objectstack/spec 17.5.0 (ADR-0049 enforce-or-remove) — it promised to hide a view item from the switcher, and nothing ever read it: `GET /meta/view?object=` and the console's view switcher list every item bound to the object, `hidden: true` included. Delete the key; to take a view out of the switcher, delete the view item itself (or stop shipping it from source). Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **protection** | `{ lock: Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>; reason: string; docsUrl?: string }` | optional | Package author protection block — lock policy for this view. | -| **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | -| **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | -| **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | -| **_provenance** | `Enum<'package' \| 'org' \| 'env-forced' \| 'platform'>` | optional | Origin of the item (package \| org \| env-forced \| platform). | -| **_packageId** | `string` | optional | Owning package machine id. | -| **_packageVersion** | `string` | optional | Owning package version. | -| **_lockDocsUrl** | `string` | optional | Optional documentation link surfaced next to _lockReason. | -| **overrides** | `{ package: string; basedOn: string }` | optional | Override declaration (ADR-0146 D2): `{ package, basedOn }` — this item of "``.custom" replaces the base package's same-named item whole. `basedOn` is recorded and never gates; a base's upgrade plan reads it only as advice. | -| **isPinned** | `boolean` | optional | Console round-trip: the view is pinned in the object's view switcher. Written by the console's pin toggle through the `view` metadata API and read back to draw the pinned group. Stored on the view's row, which has no per-user scope. Not authored. | -| **sortOrder** | `integer` | optional | Console round-trip: the view's position among the object's saved views in the switcher, 0-based and counted over saved views only (a code-defined view carries none). Written by the console's drag-reorder and read back to order the tabs. Not authored: `order` is the authored default position. | -| **visibility** | `Enum<'private' \| 'team' \| 'organization' \| 'public'>` | optional | Console round-trip: the group the switcher files this view's tab under (private, team, organization or public). Display grouping only, NOT access control: nothing restricts who can list or open the view by this value. No console control sets it; the console carries a stored value forward when it re-saves the row. Not authored. | -| **columnState** | `never` | optional | [REMOVED] `view.columnState` was removed in @objectstack/spec 19.0.0 (ADR-0049 enforce-or-remove) — it held one column order and set of widths on a shared view row; nothing writes it any more, and a stored layout is no longer applied, so every reader sees the view's own column order and widths. The console keeps column widths in each reader's browser and saves a column order into the view itself. Delete the key. To ship a column order, list `columns` in that order (or set `fieldOrder`); to ship a width, set `width` on the column. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **options** | `never` | optional | Refused: a view item record carries no top-level `options` bag. Its per-kind blocks live under `config` (`config.kanban`, `config.timeline`, …); the legacy `options.KIND` bag belongs to the flattened list overlay only. | - -### Nested Shape: `ViewItemWire[viewKind='form'].config` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **type** | `Enum<'simple' \| 'tabbed' \| 'wizard'>` | optional (default: `"simple"`) | Form layout: 'simple' (stacked sections, the default), 'tabbed' (one tab per section) or 'wizard' (one gated step per section). Where the form opens is the caller's choice, not the form's | -| **layout** | `Enum<'vertical' \| 'horizontal'>` | optional | Field layout direction — 'vertical' (the renderer default) or 'horizontal'. Multi-column is not a layout value: set `columns` | -| **columns** | `integer` | optional | Number of columns for the form body | -| **title** | `string` | optional | Form title | -| **description** | `string` | optional | Form description | -| **defaultTab** | `string` | optional | Initially active tab (tabbed forms) | -| **tabPosition** | `Enum<'top' \| 'bottom' \| 'left' \| 'right'>` | optional | Tab strip position (tabbed forms) | -| **allowSkip** | `boolean` | optional | Wizard step-gate opt-out: allow entering a later step without submitting the one before it. Navigation freedom, NOT a validation exemption — the final submit still re-validates every step and returns to the first failing one. Default (absent/false): steps unlock in array order as each prior step submits validly. UI admission only, never authorization. | -| **showStepIndicator** | `boolean` | optional | Show the wizard step indicator (renderer default: shown). Step progress (completed/current/upcoming/invalid) is derived from the step gate — this boolean is the only authorable progress surface. | -| **splitDirection** | `never` | optional | [REMOVED] `view.form.splitDirection` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it set the pane orientation of a split form, and the split form renderer retired in the same release, so no form draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitSize** | `never` | optional | [REMOVED] `view.form.splitSize` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it sized the primary pane of a `type: 'split'` form, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitResizable** | `never` | optional | [REMOVED] `view.form.splitResizable` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it made the panes of a `type: 'split'` form resizable, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerSide** | `never` | optional | [REMOVED] `view.form.drawerSide` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it. Delete the key: an object's list opens a record in its drawer from the hover icon, and the React `ObjectForm` block keeps its own `drawerSide` prop for the drawer it opens with `formType='drawer'`. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerWidth** | `never` | optional | [REMOVED] `view.form.drawerWidth` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it, and a pixel width cannot be chosen without knowing the client viewport. Delete the key: a list's record drawer takes its starting width from the `navigation.size` bucket, and the React `ObjectForm` block keeps its own `drawerWidth` prop for the drawer it opens. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **modalSize** | `never` | optional | [REMOVED] `view.form.modalSize` was removed in @objectstack/spec 19.0.0 (ADR-0049) — no form view opens in a dialog, so nothing reads it from a form view. Delete the key: the console's New and Edit dialogs lay a record out by the object's `fieldGroups` and choose their own size, a form opened by name gets a page of its own, and the React `ObjectForm` block keeps its own `modalSize` prop for the modal it opens with `formType='modal'`. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **data** | `{ provider: 'object'; object: string } \| { provider: 'value'; items: any[] } \| { provider: 'schema'; schemaId: string; schema?: Record }` | optional | Data source configuration (defaults to "object" provider) | -| **sections** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | | -| **groups** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | [LEGACY ALIAS → `sections`] Accepted for back-compat and folded onto `sections` at parse; `sections` wins when both are present. Prefer `sections`. | -| **subforms** | `{ childObject: string; relationshipField?: string; columns?: object[]; amountField?: string; … }[]` | optional | Inline master-detail child collections | -| **sharing** | `{ enabled?: boolean; publicLink?: string; password?: string; allowedDomains?: string[]; … }` | optional | Public sharing configuration for this form | -| **submitBehavior** | `{ kind: 'thank-you'; title?: string; message?: string } \| { kind: 'redirect'; url: string; delayMs?: integer } \| { kind: 'continue' } \| { kind: 'next-record' }` | optional | Post-submit behavior. On the `redirect` arm, `url` is relative-only and interpolates only declared record fields as `{{record.field_name}}`, URL-escaped. | -| **buttons** | `{ submit?: object; cancel?: object }` | optional | Form action-button visibility & labels; folded onto the flat renderer props by ObjectUI ObjectForm. | -| **defaults** | `Record` | optional | Initial field values for create-mode forms (folded into ObjectUI ObjectForm initial values;). | - -### Nested Shape: `ViewItemWire[viewKind='form'].protection` +### Nested Shape: `ViewItemWire.protection` | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | @@ -2828,7 +2625,7 @@ This schema accepts one of the following structures: | **reason** | `string` | ✅ | User-visible reason shown when the lock blocks an action. | | **docsUrl** | `string` | optional | Optional URL the Studio banner links to for more context. | -### Nested Shape: `ViewItemWire[viewKind='form'].overrides` +### Nested Shape: `ViewItemWire.overrides` | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | @@ -2842,12 +2639,11 @@ This schema accepts one of the following structures: ## ViewKind -Whether `config` is a ListView (list family) or a FormView. +The family of the view: a list (`form` was retired in protocol 19 — a form is a `form` item). ### Allowed Values * `list` -* `form` --- diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ui.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ui.md index ea7e630c5a5..7a111d9752e 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ui.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ui.md @@ -21,7 +21,7 @@ The `strict` column is the one the campaign schedules against; it counts both th | Dir | Sites | strict | passthrough | catchall | strip | |---|---|---|---|---|---| -| `ui/` | 233 | 223 | 6 | 0 | 4 | +| `ui/` | 231 | 221 | 6 | 0 | 4 | ## `ui/` — sites @@ -45,9 +45,9 @@ classify and is not listed (it becomes reportable the day it grows its first sit | `report.zod.ts` | 4 | | `responsive.zod.ts` | 1 | | `sharing.zod.ts` | 1 | -| `view.zod.ts` | 67 | +| `view.zod.ts` | 65 | | `widget.zod.ts` | 1 | -| **total** | **233** | +| **total** | **231** | ## `ui/` — open @@ -55,15 +55,15 @@ Per file, how many of its sites still silently discard unknown keys. The `Class` column that decides the bucket split is hand-written in the ledger; the arithmetic over it is here. -**4 strip of 233**, in 4 file(s). +**4 strip of 231**, in 4 file(s). | File | Strip | Sites | |---|---|---| | `action-params.zod.ts` | 1 | 1 | | `app.zod.ts` | 1 | 20 | -| `view.zod.ts` | 1 | 67 | +| `view.zod.ts` | 1 | 65 | | `widget.zod.ts` | 1 | 1 | -| **total** | **4** | **233** | +| **total** | **4** | **231** | | Bucket | Sites | |---|---| diff --git a/packages/cli/src/commands/migrate/apply.organization-ownership-birth.integration.test.ts b/packages/cli/src/commands/migrate/apply.organization-ownership-birth.integration.test.ts index eff0000f26f..bd71e843c79 100644 --- a/packages/cli/src/commands/migrate/apply.organization-ownership-birth.integration.test.ts +++ b/packages/cli/src/commands/migrate/apply.organization-ownership-birth.integration.test.ts @@ -33,8 +33,17 @@ import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import Database from 'better-sqlite3'; -import { ORGANIZATION_OWNERSHIP_MIGRATION_ID, ORGANIZATION_OWNERSHIP_SHAPE_GENERATION } from '@objectstack/spec/system'; -import { assertOrganizationOwnershipMigrated, isOrganizationOwnershipBootRefusal } from '@objectstack/runtime'; +import { + FORM_TYPE_SWITCH_MIGRATION_ID, + ORGANIZATION_OWNERSHIP_MIGRATION_ID, + ORGANIZATION_OWNERSHIP_SHAPE_GENERATION, +} from '@objectstack/spec/system'; +import { + assertFormTypeSwitched, + assertOrganizationOwnershipMigrated, + isFormTypeSwitchBootRefusal, + isOrganizationOwnershipBootRefusal, +} from '@objectstack/runtime'; import { isExitSignal } from '../../utils/format.js'; import { bootSchemaStack } from '../../utils/schema-migrate.js'; import MigrateApply from './apply.js'; @@ -42,6 +51,14 @@ import MigrateApply from './apply.js'; // Pay the first transform of the dist-resolved workspace deps the command // reaches through dynamic `import()`s at MODULE LOAD, not inside a case. import '@objectstack/objectql'; +import '@objectstack/service-datasource'; +import '@objectstack/driver-turso'; +import '@objectstack/driver-sql'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/platform-objects/system'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; +import '@objectstack/metadata-protocol'; const HERE = dirname(fileURLToPath(import.meta.url)); const CLI_ROOT = resolve(HERE, '..', '..', '..'); @@ -119,7 +136,10 @@ const markerRows = (file: string): Array> => * the data stack alone registers no `sys_migration`, and the guard is inert * there — it would admit every file. Case (b)'s refusal is the control. */ -async function guardVerdict(file: string): Promise { +async function guardVerdict( + file: string, + judge: (engine: never) => Promise = (engine) => assertOrganizationOwnershipMigrated(engine), +): Promise { const stack = await bootSchemaStack({ jsonOutput: false, databaseUrl: `file:${file}`, @@ -131,7 +151,7 @@ async function guardVerdict(file: string): Promise { }); try { const engine = (stack.kernel as { getService: (name: string) => unknown }).getService('objectql'); - await assertOrganizationOwnershipMigrated(engine as never); + await judge(engine as never); } finally { await stack.shutdown(); } @@ -239,3 +259,47 @@ describe('os migrate apply writes the organization-ownership birth marker on a d expect(markerRows(file)).toEqual(before); }, CASE_TIMEOUT_MS); }); + +/** + * [ADR-0159 D7; ruling record 7308112533] The same flush writes the + * protocol-19 switch's BIRTH MARKER, on the same counts: a database `os + * migrate apply` created from empty stores no form, so its switch is recorded + * at birth and the served boot's guard (`assertFormTypeSwitched`, read as + * above on a boot that creates nothing) admits it. A database the apply did + * not create gets none, though the flush creates a table in it, and the guard + * still refuses it, naming the switch command. + */ +describe('os migrate apply writes the protocol-19 switch birth marker on a database it created from empty', () => { + const switchRows = (file: string): Array> => + withDb(file, (db) => db.prepare('SELECT * FROM sys_migration WHERE id = ?').all(FORM_TYPE_SWITCH_MIGRATION_ID) as Array>); + const switchVerdict = (file: string) => guardVerdict(file, (engine) => assertFormTypeSwitched(engine)); + + it('an empty file: one verified birth row naming protocol 19, no ceremony claimed, and the guard admits it', async () => { + expect(freshApply.exitCode, JSON.stringify(freshApply.payload).slice(0, 400)).toBe(0); + const rows = switchRows(freshDb); + expect(rows).toHaveLength(1); + expect(rows[0].verified_at).not.toBeNull(); + expect(rows[0].applied_at).toBeNull(); + expect(Number(rows[0].blocking)).toBe(0); + expect(JSON.parse(String(rows[0].details)).birth).toMatchObject({ protocol: 19 }); + + await expect(switchVerdict(freshDb)).resolves.toBeUndefined(); + }, CASE_TIMEOUT_MS); + + it('a database the apply did not create: no birth marker, though the flush creates a table, and the guard refuses it', async () => { + const file = copyOfFresh((db) => { + db.prepare('DELETE FROM sys_migration WHERE id = ?').run(FORM_TYPE_SWITCH_MIGRATION_ID); + db.exec(`DROP TABLE ${DROPPED_TABLE}`); + }); + + const { payload, exitCode } = await runJson(applyArgv(file)); + expect(exitCode, JSON.stringify(payload).slice(0, 400)).toBe(0); + expect(payload.created).toEqual([expect.objectContaining({ table: DROPPED_TABLE, kind: 'create_table' })]); + + expect(switchRows(file)).toEqual([]); + const refusal = await switchVerdict(file).then(() => null, (error: unknown) => error); + expect(isFormTypeSwitchBootRefusal(refusal), String(refusal)).toBe(true); + expect((refusal as { reason?: string }).reason).toBe('absent'); + expect((refusal as Error).message).toContain("'os migrate protocol --to 19 --apply --yes'"); + }, CASE_TIMEOUT_MS); +}); diff --git a/packages/cli/src/commands/migrate/protocol.integration.test.ts b/packages/cli/src/commands/migrate/protocol.integration.test.ts index c5b67cfcf66..9f4553cf2a4 100644 --- a/packages/cli/src/commands/migrate/protocol.integration.test.ts +++ b/packages/cli/src/commands/migrate/protocol.integration.test.ts @@ -8,8 +8,9 @@ * ## The fixture * * A compiled artifact (`dist/objectstack.json`) whose package ships an object - * and a linked public form in an old shape (`formViews.contact`), over a - * database an older release left behind with, bound to no package: + * and a linked public form as a `form` item (the only shape a protocol-19 + * artifact loads: the stack is refused at boot with `view.formViews` in it), + * over a database an older release left behind with, bound to no package: * * - a `viewKind: 'form'` row of the package's form that switches it off * (moves into the package's pair as a declared override); @@ -20,6 +21,14 @@ * preview writes nothing; `--apply` over a held deployment writes nothing * either (no row, no pair, no marker); `--apply` over a deployment that can * switch moves the row and records the verified `sys_migration` marker. + * + * ## The marker is what the served boot reads + * + * `os serve`'s protocol-19 guard (`assertFormTypeSwitched`, + * `@objectstack/runtime`) is asked here on a boot that creates nothing, so its + * verdict is the marker's alone: it refuses the database before the switch, + * still refuses it after a held `--apply`, and admits it once the command has + * recorded the switch. */ import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest'; @@ -28,6 +37,7 @@ import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { SqlDriver } from '@objectstack/driver-sql'; +import { assertFormTypeSwitched, isFormTypeSwitchBootRefusal } from '@objectstack/runtime'; import { isExitSignal } from '../../utils/format.js'; import { bootSchemaStack } from '../../utils/schema-migrate.js'; import MigrateProtocol from './protocol.js'; @@ -56,12 +66,17 @@ const FORM = `${OBJECT}.contact`; const BROKEN = `${OBJECT}.broken`; const CREATE = `${OBJECT}.create`; const SLUG = 'contact-m37111'; -const formBody = (enabled: boolean) => ({ +/** A form's own content: what a `form` item carries at its top level. */ +const formContent = (enabled: boolean) => ({ type: 'simple', sections: [{ fields: ['name'] }], - data: { provider: 'object', object: OBJECT }, sharing: { publicLink: `/forms/${SLUG}`, enabled, allowAnonymous: true }, }); +/** The same content as an older release stored it, under a `viewKind: 'form'` row's `config`. */ +const formBody = (enabled: boolean) => ({ + ...formContent(enabled), + data: { provider: 'object', object: OBJECT }, +}); const ARTIFACT = { manifest: { id: PKG, name: 'm37111', version: '2.3.0', type: 'app', namespace: 'm37111' }, objects: [{ @@ -70,7 +85,8 @@ const ARTIFACT = { sharingModel: 'private', fields: { name: { name: 'name', label: 'Name', type: 'text' } }, }], - views: [{ object: OBJECT, list: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } }, formViews: { contact: formBody(true) } }], + views: [{ object: OBJECT, list: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } } }], + forms: [{ name: FORM, object: OBJECT, label: 'Contact us', ...formContent(true) }], }; interface SeedRow { type: string; name: string; state: string; body: Record; packageId?: string } @@ -218,6 +234,29 @@ async function switchMarker(dbFile: string): Promise { } } +/** + * The served boot's verdict on `dbFile`, as `os serve`'s guard reaches it, from + * a boot that holds its DDL back: it creates nothing, so the guard cannot read + * the store as created from empty and decides on the marker alone. `null` when + * the database would be served, the refusal when it would not. + */ +async function guardRefusal(dbFile: string): Promise { + const stack = await bootSchemaStack({ + jsonOutput: false, + databaseUrl: `file:${dbFile}`, + deferSchemaDdl: true, + readOnlyProbe: true, + composeHostStack: true, + projectRoot: dir, + }); + try { + const engine = (stack.kernel as { getService: (name: string) => unknown }).getService('objectql'); + return await assertFormTypeSwitched(engine as never).then(() => null, (error: unknown) => error); + } finally { + await stack.shutdown(); + } +} + describe('os migrate protocol --to 19', () => { it('previews by default: lists the move, says it can switch, writes nothing, exits 0', async () => { const db = caseDb(templateDb); @@ -250,10 +289,17 @@ describe('os migrate protocol --to 19', () => { expect(applied.payload.refusal).toContain('Nothing was written'); expect(await storeSnapshot(db)).toBe(before); expect(await switchMarker(db)).toBeUndefined(); + // A held switch records nothing, so the served boot still refuses this database. + const refusal = await guardRefusal(db); + expect(isFormTypeSwitchBootRefusal(refusal), String(refusal)).toBe(true); }, CASE_TIMEOUT_MS); it('--apply on a deployment that can switch moves the row, checks again, and records the verified switch marker', async () => { const db = caseDb(templateDb); + // Before the switch the served boot refuses this database, naming this command. + const before = await guardRefusal(db); + expect(isFormTypeSwitchBootRefusal(before), String(before)).toBe(true); + expect((before as Error).message).toContain("'os migrate protocol --to 19 --apply --yes'"); const { payload, exitCode } = await runJson(['--to', '19', '--apply', '--yes', '--database-url', `file:${db}`, '--json']); expect(payload.error, JSON.stringify(payload).slice(0, 600)).toBeUndefined(); expect(exitCode).toBe(0); @@ -270,7 +316,11 @@ describe('os migrate protocol --to 19', () => { const marker = await switchMarker(db); expect(marker?.verified_at).toBeTruthy(); expect(marker?.blocking).toBe(0); + // The ceremony ran here: the record says so. + expect(marker?.applied_at).toBeTruthy(); expect(JSON.parse(marker.details).ceremony.removed[0].form).toBe(CREATE); + // The record is what the served boot reads: it admits the database now. + expect(await guardRefusal(db)).toBeNull(); // A second run finds nothing to move, and re-verifies. const again = await runJson(['--to', '19', '--apply', '--yes', '--database-url', `file:${db}`, '--json']); expect(again.exitCode).toBe(0); @@ -278,6 +328,24 @@ describe('os migrate protocol --to 19', () => { expect(again.payload.ceremony.removed).toEqual([]); }, CASE_TIMEOUT_MS); + it('a database with no sys_metadata table stores no form: --apply records the switch on the census alone, and claims no ceremony', async () => { + // A file that does not exist yet: no table at all, the marker's included. + const db = join(dir, 'cases', 'no-tables.db'); + mkdirSync(dirname(db), { recursive: true }); + const { payload, exitCode } = await runJson(['--to', '19', '--apply', '--yes', '--database-url', `file:${db}`, '--json']); + expect(payload.error, JSON.stringify(payload).slice(0, 600)).toBeUndefined(); + expect(exitCode).toBe(0); + expect(payload).toMatchObject({ switched: true, canSwitch: true }); + expect(payload.counts).toMatchObject({ keep: 0, move: 0, remove: 0, hold: 0 }); + expect(payload.ceremony).toMatchObject({ written: [], removed: [], rowsChanged: [] }); + const marker = await switchMarker(db); + expect(marker?.verified_at).toBeTruthy(); + expect(marker?.blocking).toBe(0); + // `applied_at` says the ceremony ran, and here it was never asked. + expect(marker?.applied_at).toBeNull(); + expect(await guardRefusal(db)).toBeNull(); + }, CASE_TIMEOUT_MS); + it('refuses a major it does not switch to', async () => { const db = caseDb(emptyDb); const { exitCode } = await runJson(['--to', '18', '--database-url', `file:${db}`, '--json']); diff --git a/packages/cli/src/commands/migrate/protocol.ts b/packages/cli/src/commands/migrate/protocol.ts index 215c4fd4dc7..135e51f7da6 100644 --- a/packages/cli/src/commands/migrate/protocol.ts +++ b/packages/cli/src/commands/migrate/protocol.ts @@ -103,8 +103,22 @@ async function confirm(question: string): Promise { * * ⛔ No write precedes the switch verdict: a held precheck writes no form row, * no pair and no marker; a database whose driver cannot roll back a - * transaction is refused before the ceremony is asked. The marker is the - * switch's record; no boot reads it in this release. + * transaction is refused before the ceremony is asked. + * + * The marker is the switch's record, and the served boot reads it: `os serve` + * refuses to start on a database without it and names this command + * (`FormTypeSwitchBootGuardPlugin`, `@objectstack/runtime`). A database a + * protocol-19 boot created from empty carries it from birth, so a new project + * never runs this command. + * + * ## A database with no `sys_metadata` table + * + * It stores no metadata row, so no form in any shape: there is no ceremony to + * run. Step 1 is skipped, the census of steps 2 and 3 is the empty one, and + * the marker is recorded verified with `applied_at` left unset, because this + * run moved nothing. Where the marker's own table is not there either, the + * run performs the DDL its boot held back before it writes the row: the one + * DDL this command ever performs, and only after the verdict. * * ## The refusal * @@ -208,7 +222,9 @@ export default class MigrateProtocol extends Command { composeHostStack: true, composeAuthGatedSecurity: true, serveFlags: { dev: flags.dev === true, ...(flags.preset ? { preset: flags.preset } : {}) }, - // The switch writes metadata rows and one `sys_migration` row, never DDL. + // The boot holds its DDL back: the switch writes metadata rows and one + // `sys_migration` row. Its only DDL is the flush below, after the + // verdict, on a database that has no table for that row yet. deferSchemaDdl: true, ...(apply ? {} : { readOnlyProbe: true }), }); @@ -369,7 +385,9 @@ export default class MigrateProtocol extends Command { passed: true, blocking: 0, advisory: 0, - applied: true, + // `applied_at` says the ceremony ran. With no `sys_metadata` table it + // was never asked: the row is the census's verdict alone. + applied: !noMetadataTable, details: { protocol: to, counts: after.precheck.counts, ceremony: ceremonyJson(result) }, }); if (typeof flagEngine.invalidateDataMigrationFlags === 'function') flagEngine.invalidateDataMigrationFlags(); diff --git a/packages/cli/src/commands/serve-form-type-switch-refusal.integration.test.ts b/packages/cli/src/commands/serve-form-type-switch-refusal.integration.test.ts new file mode 100644 index 00000000000..7324d376ded --- /dev/null +++ b/packages/cli/src/commands/serve-form-type-switch-refusal.integration.test.ts @@ -0,0 +1,267 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { spawn, spawnSync, type ChildProcessByStdio } from 'node:child_process'; +import { copyFileSync, existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import type { Readable } from 'node:stream'; +import { fileURLToPath } from 'node:url'; +import Database from 'better-sqlite3'; +import { FORM_TYPE_SWITCH_MIGRATION_ID } from '@objectstack/spec/system'; + +/** + * [ADR-0159 D7] A real `os serve` boot serves a database only once the + * protocol-19 switch is recorded on it. + * + * The guard's own decisions are pinned on a real kernel in + * `@objectstack/runtime` (`form-type-switch-boot-guard.kernel.test.ts`), and + * the upgrade sequence on the showcase in + * `form-type-switch-boot-refusal.dogfood.test.ts`. Both compose the guard + * themselves. What is pinned HERE is the wiring only `serve.ts` owns, on the + * shipped entrypoint in production posture, one boot per shape: + * + * 1. a database this boot creates is served, and carries the switch record + * from birth (`details.birth`); + * 2. the same database with that record gone, which is how a database an + * earlier release created reads, is refused: the process exits non-zero + * before its ready banner and names `os migrate protocol --to 19`, + * without printing the auth secret it ran with; + * 3. a stack plugin registered under the guard's own name does not take its + * place (a later registration under one name replaces the earlier one): + * the boot is refused, naming the plugin name. Shapes 1 and 2 are its + * control: the same stack with that plugin under a name of its own; + * 4. the named command, through the same binary, records the switch, and the + * next boot is served. + * + * ## Why `bin/run.js` with `NODE_ENV` unset + * + * Production posture, which `bin/run-dev.js` cannot reach; `NODE_ENV` unset is + * also what makes oclif resolve the command from `dist/`, so this file needs a + * built CLI (CI declares it: `@objectstack/cli#test` dependsOn `build`). + * `src/` cannot import `test/helpers/serve-process.ts`, so the few helpers it + * needs are local, as in `serve-no-server-banner.integration.test.ts`. + */ + +const HERE = dirname(fileURLToPath(import.meta.url)); +/** `bin/run.js` — the SHIPPED entrypoint. See the header for why this one. */ +const CLI = resolve(HERE, '../../bin/run.js'); +/** What one build emits for every command; its absence means "never built". */ +const BUILT_SERVE = resolve(HERE, '../../dist/commands/serve.js'); + +/** The complete banner — keyed on its LAST line, so the whole block is on the stream. */ +const READY_BANNER_TAIL = /Press Ctrl\+C to stop/; + +const AUTH_SECRET = 'os-37112-auth-secret-not-a-real-credential'; +const SECRET_KEY = '0e2e'.repeat(16); +const GUARD_NAME = 'com.objectstack.form-type-switch-boot-guard'; + +const OBJECT = `{ name: 'fx_task', label: 'Task', pluralLabel: 'Tasks', fields: { title: { type: 'text', label: 'Title' } } }`; +const MANIFEST = `{ id: 'com.example.fx37112', namespace: 'fx', version: '1.0.0', type: 'app', name: 'Fx' }`; +/** An instantiated plugin, which is what makes this a HOST config. */ +const hostPlugin = (name: string) => `{ name: '${name}', version: '1.0.0', init: async () => {}, start: async () => {} }`; + +/** What `spawn(…, { stdio: ['ignore', 'pipe', 'pipe'] })` returns — no `stdin`. */ +type BootChild = ChildProcessByStdio; + +const children: BootChild[] = []; +let root: string; +/** One object and a host plugin under a name of its own. */ +let plainDir: string; +/** The same, the host plugin registered under the guard's name. */ +let impostorDir: string; + +/** The root of an installed dependency of this package, found through `node_modules`. */ +function packageRoot(specifier: string): string { + let dir = dirname(createRequire(import.meta.url).resolve(specifier)); + while (!existsSync(join(dir, 'package.json'))) { + if (dirname(dir) === dir) throw new Error(`${specifier} resolved to no package root`); + dir = dirname(dir); + } + return dir; +} + +function writeFixture(dir: string, pluginName: string): void { + mkdirSync(join(dir, 'node_modules', '@objectstack'), { recursive: true }); + writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'fx-37112', private: true, type: 'module' })); + writeFileSync( + join(dir, 'objectstack.config.ts'), + `import { defineStack } from '@objectstack/spec';\n` + + `export default defineStack({ manifest: ${MANIFEST}, objects: [${OBJECT}], plugins: [${hostPlugin(pluginName)}] });\n`, + ); + symlinkSync(packageRoot('@objectstack/spec'), join(dir, 'node_modules', '@objectstack', 'spec'), 'dir'); +} + +/** + * This process's environment for a child, minus the vitest worker family and + * every input that would point the boot at another store. An `undefined` + * entry unsets a variable. + */ +function childEnv(cwd: string, database: string): Record { + const env: Record = {}; + for (const [key, value] of Object.entries(process.env)) { + if (key === 'TEST' || key === 'VITEST' || key.startsWith('VITEST_') || key === 'NODE_PATH') continue; + env[key] = value; + } + return { + ...env, + NO_COLOR: '1', + OS_LOG_LEVEL: '', + OS_DISABLE_CONSOLE: '1', + OS_CLOUD_URL: 'off', + OS_HOME: join(cwd, '.os-home'), + OS_SECRET_KEY: SECRET_KEY, + OS_DATABASE_URL: `file:${database}`, + DATABASE_URL: undefined, + OS_DATABASE_DRIVER: undefined, + OS_AUTH_SECRET: AUTH_SECRET, + OS_TENANCY_POSTURE: undefined, + OS_MULTI_ORG_ENABLED: undefined, + OS_AUTH_URL: undefined, + BETTER_AUTH_URL: undefined, + OS_BASE_URL: undefined, + // Truly unset: production posture, and oclif resolves the command from `dist/`. + NODE_ENV: undefined, + }; +} + +interface Outcome { + /** True when the complete ready banner printed (the child was then stopped). */ + served: boolean; + /** The exit code of a child that exited before its banner; null when it was served. */ + code: number | null; + output: string; +} + +/** + * Spawn `os serve --no-server` over `database` and resolve on whichever comes + * first: the complete ready banner (the child is then stopped and awaited, so + * the file is closed before the caller reads it) or the child's own exit. + */ +function serve(cwd: string, database: string): Promise { + const child = spawn(process.execPath, [CLI, 'serve', 'objectstack.config.ts', '--no-server'], { + cwd, + stdio: ['ignore', 'pipe', 'pipe'], + env: childEnv(cwd, database), + }) as BootChild; + children.push(child); + + let output = ''; + return new Promise((done, fail) => { + let served = false; + const timer = setTimeout(() => { + child.kill('SIGKILL'); + fail(new Error(`serve neither printed its complete banner nor exited\n--- output ---\n${output}`)); + }, 150_000); + const onData = (d: unknown) => { + output += String(d); + if (!served && READY_BANNER_TAIL.test(output)) { + served = true; + child.kill('SIGTERM'); + } + }; + child.stdout.on('data', onData); + child.stderr.on('data', onData); + child.on('exit', (code) => { + clearTimeout(timer); + done({ served, code: served ? null : code, output }); + }); + }); +} + +interface MarkerRow { verified_at: unknown; applied_at: unknown; blocking: unknown; details: unknown } + +/** The switch record of `database`, read on a connection of our own; undefined when there is none. */ +function switchMarker(database: string): MarkerRow | undefined { + const db = new Database(database, { readonly: true }); + try { + return db.prepare('SELECT verified_at, applied_at, blocking, details FROM sys_migration WHERE id = ?') + .get(FORM_TYPE_SWITCH_MIGRATION_ID) as MarkerRow | undefined; + } finally { + db.close(); + } +} + +let born: string; +let unswitched: string; + +beforeAll(() => { + if (!existsSync(BUILT_SERVE)) { + throw new Error( + `packages/cli is not built: ${BUILT_SERVE} does not exist. This file spawns bin/run.js with NODE_ENV unset, ` + + 'which resolves the command from dist/. Run: pnpm exec turbo run build --filter=@objectstack/cli', + ); + } + root = mkdtempSync(join(tmpdir(), 'os-serve-form-type-switch-')); + plainDir = join(root, 'plain'); + writeFixture(plainDir, 'com.example.fx37112.host-plugin'); + impostorDir = join(root, 'impostor'); + writeFixture(impostorDir, GUARD_NAME); + born = join(root, 'born.db'); + unswitched = join(root, 'unswitched.db'); +}); + +afterAll(() => { + for (const child of children) { + try { child.kill('SIGTERM'); } catch { /* already gone */ } + } + if (root) rmSync(root, { recursive: true, force: true }); +}); + +describe('os serve — a database is served only once the protocol-19 switch is recorded on it (ADR-0159 D7)', () => { + it('1. a database this boot creates is served, and carries the switch record from birth', async () => { + const outcome = await serve(plainDir, born); + expect(outcome.served, `not served\n--- output ---\n${outcome.output}`).toBe(true); + const marker = switchMarker(born); + expect(marker?.verified_at, 'the birth marker is a verified record').toBeTruthy(); + expect(Number(marker?.blocking)).toBe(0); + expect(marker?.applied_at ?? null, 'no ceremony ran, and the record claims none').toBeNull(); + expect(JSON.parse(String(marker?.details)).birth.protocol).toBe(19); + }, 240_000); + + it('2. the same database with no switch record is refused before the banner, naming the command and no credential', async () => { + // Every table of the served database, and no switch record: how a + // database an earlier release created reads to this boot. + copyFileSync(born, unswitched); + const db = new Database(unswitched); + try { + expect(db.prepare('DELETE FROM sys_migration WHERE id = ?').run(FORM_TYPE_SWITCH_MIGRATION_ID).changes).toBe(1); + } finally { + db.close(); + } + + const outcome = await serve(plainDir, unswitched); + const seen = `\n--- output ---\n${outcome.output}`; + expect(outcome.served, `an unswitched database was served${seen}`).toBe(false); + expect(outcome.code, `the refused boot exited 0${seen}`).not.toBe(0); + expect(outcome.output, `the refusal does not name the command${seen}`).toContain('os migrate protocol --to 19'); + expect(outcome.output, seen).toContain('--apply --yes'); + expect(outcome.output, `the refusal printed the auth secret${seen}`).not.toContain(AUTH_SECRET); + expect(switchMarker(unswitched), 'a refused boot records nothing').toBeUndefined(); + }, 240_000); + + it('3. a stack plugin under the guard\'s name does not take its place: the boot is refused, naming that name', async () => { + const database = join(root, 'impostor.db'); + copyFileSync(unswitched, database); + const outcome = await serve(impostorDir, database); + const seen = `\n--- output ---\n${outcome.output}`; + expect(outcome.served, `the database was served behind a plugin that took the guard's name${seen}`).toBe(false); + expect(outcome.code, `the refused boot exited 0${seen}`).not.toBe(0); + expect(outcome.output, `the refusal does not name the plugin name${seen}`).toContain(`'${GUARD_NAME}'`); + expect(switchMarker(database), 'a refused boot records nothing').toBeUndefined(); + }, 240_000); + + it('4. the named command records the switch through the same binary, and the next boot is served', async () => { + const database = join(root, 'switched.db'); + copyFileSync(unswitched, database); + const run = spawnSync(process.execPath, [CLI, 'migrate', 'protocol', '--to', '19', '--apply', '--yes'], { + cwd: plainDir, encoding: 'utf8', timeout: 200_000, env: childEnv(plainDir, database) as NodeJS.ProcessEnv, + }); + expect(run.status, `${run.stdout}\n${run.stderr}`).toBe(0); + expect(switchMarker(database)?.verified_at, 'the command verified its record').toBeTruthy(); + + const outcome = await serve(plainDir, database); + expect(outcome.served, `not served after the switch\n--- output ---\n${outcome.output}`).toBe(true); + }, 480_000); +}); diff --git a/packages/cli/src/commands/serve.ts b/packages/cli/src/commands/serve.ts index 93e7c7aa40c..45cc2582518 100644 --- a/packages/cli/src/commands/serve.ts +++ b/packages/cli/src/commands/serve.ts @@ -4496,6 +4496,32 @@ export default class Serve extends Command { trackPlugin('OrganizationOwnershipBootGuard'); } + // 5c-quater. [ADR-0159 D7; ruling record 7303149461] The protocol-19 + // boot refusal, beside the ownership one and judged after it: it + // refuses to start a database whose switch (`os migrate protocol --to + // 19`) is not recorded, naming the command, and writes the switch + // record as a birth marker on a store this boot creates from empty + // (ruling record 7308112533). Composed HERE, ahead of the auth family + // and the stack's own plugins, on served kernels only: + // ⛔ never in `createStandaloneStack`, which the switch command's own + // boot shares. ⛔ Always this command's own instance, and nothing skips + // it: a stack plugin that carries its name would replace it, and is + // refused before `runtime.start()` below. + const { FormTypeSwitchBootGuardPlugin, assertFormTypeSwitchGuardNotReplaced } = await import('@objectstack/runtime'); + // The refusal names the command as this boot was started (`--dev`, + // `--preset`, the database and the connection its parent's flags chose), + // so run verbatim it switches the database that was refused. + const switchDatabase = readCeremonyDatabaseChannel(process.env); + const formTypeSwitchGuard = new FormTypeSwitchBootGuardPlugin({ + dev: isDev, + ...(flags.preset ? { preset: flags.preset } : {}), + authSecretFile: readAuthSecretFileChannel(process.env), + ...(switchDatabase ? { databaseUrl: switchDatabase } : {}), + ...readCeremonyConnectionChannel(process.env), + }); + await kernel.use(formTypeSwitchGuard); + trackPlugin('FormTypeSwitchBootGuard'); + // The ONE secret crypto provider, built below (`createHostCryptoProvider`, // after the stack's plugins are checked) and declared here, because the // AuditPlugin of 5d is composed before it exists and reads it when its @@ -6073,6 +6099,10 @@ export default class Serve extends Command { // refused by the kernel itself when it happens. refuseTwoCryptoProviderPlugins([...stackMountedPlugins, ...resolverMounted]); + // [ADR-0159 D7] The protocol-19 boot guard stays this command's own + // instance: see `assertFormTypeSwitchGuardNotReplaced`. + assertFormTypeSwitchGuardNotReplaced(formTypeSwitchGuard, [...stackMountedPlugins, ...resolverMounted]); + // Boot the runtime await runtime.start(); @@ -6511,17 +6541,23 @@ export default class Serve extends Command { // so the kernel hands it on as the `cause` of its own start-failure // error: the refusal is looked for down the chain, and its own text is // what this boot prints. - const { isOrganizationOwnershipBootRefusal } = await import('@objectstack/runtime'); + // + // [ADR-0159 D7] The protocol-19 guard refuses the same way, and its own + // text is printed the same way. It has no development exception: a + // development database an earlier release created runs the command once. + const { isOrganizationOwnershipBootRefusal, isFormTypeSwitchBootRefusal } = await import('@objectstack/runtime'); let ownershipRefusal: { tables: readonly string[]; message: string } | undefined; - for (let cause: unknown = error, depth = 0; !ownershipRefusal && cause && typeof cause === 'object' && depth < 8; depth++) { + let switchRefusal: { message: string } | undefined; + for (let cause: unknown = error, depth = 0; !ownershipRefusal && !switchRefusal && cause && typeof cause === 'object' && depth < 8; depth++) { if (isOrganizationOwnershipBootRefusal(cause)) ownershipRefusal = cause; + else if (isFormTypeSwitchBootRefusal(cause)) switchRefusal = cause; cause = (cause as { cause?: unknown }).cause; } if (ownershipRefusal && isDev && typeof process.send === 'function') { const sent = await announceOrganizationOwnershipRequired([...ownershipRefusal.tables]); if (sent) this.exit(1); } - printError(ownershipRefusal?.message || error.message || String(error)); + printError(ownershipRefusal?.message || switchRefusal?.message || error.message || String(error)); // A boot that died is when its warnings matter most, and the banner that // would normally carry them never printed (#4012). const diagnostics = collectBootDiagnostics(); diff --git a/packages/cli/src/utils/schema-migrate.birth-after-flush.test.ts b/packages/cli/src/utils/schema-migrate.birth-after-flush.test.ts index f5cc3154c1b..155c561b7c6 100644 --- a/packages/cli/src/utils/schema-migrate.birth-after-flush.test.ts +++ b/packages/cli/src/utils/schema-migrate.birth-after-flush.test.ts @@ -14,8 +14,19 @@ */ import { describe, expect, it, vi } from 'vitest'; -import { ORGANIZATION_OWNERSHIP_MIGRATION_ID } from '@objectstack/spec/system'; -import { recordBirthOfFlushedStore } from './schema-migrate.js'; +import { FORM_TYPE_SWITCH_MIGRATION_ID, ORGANIZATION_OWNERSHIP_MIGRATION_ID } from '@objectstack/spec/system'; +import { formTypeSwitchBirthFailure, recordBirthOfFlushedStore } from './schema-migrate.js'; + +// Pay the first transform of the dist-resolved workspace deps `schema-migrate` +// reaches through dynamic `import()`s at MODULE LOAD, never inside a case's +// clocked window (`scripts/check-test-source-alias.mjs`). +import '@objectstack/runtime'; +import '@objectstack/service-datasource'; +import '@objectstack/driver-turso'; +import '@objectstack/driver-sql'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; /** The ceremony's two steps, as the boot refusal prescribes them. */ const CEREMONY_STEPS = [ @@ -57,3 +68,34 @@ describe('recordBirthOfFlushedStore — the birth half after a deferred flush', expect(recordBirth).not.toHaveBeenCalled(); }); }); + +/** + * [ADR-0159 D7] The protocol-19 switch's birth half goes through the same + * seam with its own failure sentence: the row it could not write, the cause, + * and the command that records the switch on such a database. The decision + * itself, on a real database, is `apply.organization-ownership-birth.integration.test.ts`'s. + */ +describe('recordBirthOfFlushedStore, the protocol-19 switch birth half after a deferred flush', () => { + it('a switch birth marker that cannot be written fails the flush, naming the row, the cause and the command', async () => { + const cause = new Error('SQLITE_READONLY: attempt to write a readonly database'); + const recordBirth = vi.fn(async () => { throw cause; }); + const failure = await recordBirthOfFlushedStore(kernelWith(engine), recordBirth, undefined, formTypeSwitchBirthFailure).then( + () => null, + (error: unknown) => error as Error, + ); + expect(failure).toBeInstanceOf(Error); + expect(failure!.cause).toBe(cause); + expect(failure!.message).toContain(FORM_TYPE_SWITCH_MIGRATION_ID); + expect(failure!.message).toContain(cause.message); + expect(failure!.message).toContain('os migrate protocol --to 19 --apply --yes'); + // Its own sentence, not the ownership ceremony's. + for (const step of CEREMONY_STEPS) expect(failure!.message).not.toContain(step); + }); + + it('resolves when the birth half does, handing it the engine and the logger', async () => { + const logger = { info: vi.fn() }; + const recordBirth = vi.fn(async () => null); + await expect(recordBirthOfFlushedStore(kernelWith(engine), recordBirth, logger, formTypeSwitchBirthFailure)).resolves.toBeUndefined(); + expect(recordBirth).toHaveBeenCalledWith(engine, logger); + }); +}); diff --git a/packages/cli/src/utils/schema-migrate.ts b/packages/cli/src/utils/schema-migrate.ts index a8ef1b0ec73..534cc5a9a7d 100644 --- a/packages/cli/src/utils/schema-migrate.ts +++ b/packages/cli/src/utils/schema-migrate.ts @@ -56,7 +56,7 @@ import type { PendingSchemaWork, } from '@objectstack/driver-sql'; import type { IObjectQLEngine } from '@objectstack/spec/contracts'; -import { ORGANIZATION_OWNERSHIP_MIGRATION_ID, StorageNameMapping } from '@objectstack/spec/system'; +import { FORM_TYPE_SWITCH_MIGRATION_ID, ORGANIZATION_OWNERSHIP_MIGRATION_ID, StorageNameMapping } from '@objectstack/spec/system'; import { isDevelopmentBoot, isFederatedObject } from '@objectstack/core'; import { doctorNodeEnv, @@ -648,13 +648,21 @@ type BirthLogger = Parameters[1]; * first `os serve` would refuse this database, and the command must not end * reporting success. The ceremony certifies such a database. * + * [ADR-0159 D7; ruling record 7308112533] The protocol-19 switch has the same + * birth half (`recordFormTypeSwitchBirth`), run through here on the same + * counts with its own failure sentence ({@link formTypeSwitchBirthFailure}): + * a store this flush created from empty holds no stored form, so its switch + * record is written as a birth marker and its first `os serve` is not refused. + * * Exported for its unit pin (`schema-migrate.birth-after-flush.test.ts`), which * holds the failed-write refusal without booting a kernel. */ -export async function recordBirthOfFlushedStore( +export async function recordBirthOfFlushedStore( kernel: { getService?: (name: string) => unknown }, - recordBirth: RecordOrganizationOwnershipBirth, + recordBirth: (engine: E, logger?: BirthLogger) => Promise, logger: BirthLogger | undefined, + /** What the thrown failure says, given the write's own message. The organization-ownership sentence when unset. */ + describeFailure: (cause: string) => string = organizationOwnershipBirthFailure, ): Promise { let engine: unknown; try { @@ -664,20 +672,38 @@ export async function recordBirthOfFlushedStore( } if (!engine || typeof (engine as { getDriverForObject?: unknown }).getDriverForObject !== 'function') return; try { - await recordBirth(engine as Parameters[0], logger); + await recordBirth(engine as E, logger); } catch (error) { - throw new Error( - `This run created the database from empty, and its organization-ownership birth marker (sys_migration ` + - `'${ORGANIZATION_OWNERSHIP_MIGRATION_ID}') could not be written ` + - `(${error instanceof Error ? error.message : String(error)}). Without it the first 'os serve' takes this ` + - `database for one an earlier release created and refuses it. Fix the write, then run 'os migrate ` + - `organization-ownership --out PLAN' and 'os migrate organization-ownership --apply --plan-file PLAN ` + - `--backup-taken', which certifies it.`, - { cause: error }, - ); + throw new Error(describeFailure(error instanceof Error ? error.message : String(error)), { cause: error }); } } +/** The failure of the organization-ownership birth half after a flush: what was not written, and the ceremony that certifies the database. */ +function organizationOwnershipBirthFailure(cause: string): string { + return ( + `This run created the database from empty, and its organization-ownership birth marker (sys_migration ` + + `'${ORGANIZATION_OWNERSHIP_MIGRATION_ID}') could not be written ` + + `(${cause}). Without it the first 'os serve' takes this ` + + `database for one an earlier release created and refuses it. Fix the write, then run 'os migrate ` + + `organization-ownership --out PLAN' and 'os migrate organization-ownership --apply --plan-file PLAN ` + + `--backup-taken', which certifies it.` + ); +} + +/** + * [ADR-0159 D7] The failure of the protocol-19 birth half after a flush: what + * was not written, and the command that records the switch on such a database. + * Exported for the same unit pin. + */ +export function formTypeSwitchBirthFailure(cause: string): string { + return ( + `This run created the database from empty, and its protocol 19 birth marker (sys_migration ` + + `'${FORM_TYPE_SWITCH_MIGRATION_ID}') could not be written (${cause}). Without it the first 'os serve' takes ` + + `this database for one an earlier release created and refuses it. Fix the write, then run 'os migrate protocol ` + + `--to 19 --apply --yes', which records the switch.` + ); +} + /** * [#23816] The engine's DEFAULT driver — the primary datasource's — read * through the accessors the engine makes public, or `null` when the engine @@ -1298,8 +1324,9 @@ export async function bootSchemaStack( const projectRoot = opts.projectRoot ?? process.cwd(); const envLoad = loadProjectEnvFiles(projectRoot, { dev: opts.serveFlags?.dev === true }); - const { createStandaloneStack, Runtime, resolveStandaloneDatabase, recordOrganizationOwnershipBirth } = - await import('@objectstack/runtime'); + const { + createStandaloneStack, Runtime, resolveStandaloneDatabase, recordOrganizationOwnershipBirth, recordFormTypeSwitchBirth, + } = await import('@objectstack/runtime'); // The inputs the database is resolved from — by `createStandaloneStack` // below, the occupancy probe before it, and the telemetry sibling's key. @@ -1692,6 +1719,8 @@ export async function bootSchemaStack( // [ADR-0131 D10] The birth half the deferred boot could not run: only a // deferred boot holds DDL back, so only it can have created the store here. if (deferral) await recordBirthOfFlushedStore(kernel, recordOrganizationOwnershipBirth, deferral.logger); + // [ADR-0159 D7] …and the protocol-19 switch's, on the same counts. + if (deferral) await recordBirthOfFlushedStore(kernel, recordFormTypeSwitchBirth, deferral.logger, formTypeSwitchBirthFailure); return sortPendingSchemaWork(performed); }, composition, diff --git a/packages/metadata-core/src/anonymous-form-intake.test.ts b/packages/metadata-core/src/anonymous-form-intake.test.ts index 99f7d986f04..dd5bdbe4ca4 100644 --- a/packages/metadata-core/src/anonymous-form-intake.test.ts +++ b/packages/metadata-core/src/anonymous-form-intake.test.ts @@ -170,14 +170,21 @@ describe('where the reason is located, and the reason itself', () => { .toEqual(['form.sharing', 'formViews.contact.sharing', 'config.sharing']); }); - it('anonymousFormObjectName: the form\'s own data.object first, then the view\'s', () => { + it('anonymousFormObjectName: the form\'s own data.object first, then the body\'s form and object', () => { const view = { object: 'v_obj', list: { data: { object: 'list_obj' } } }; expect(anonymousFormObjectName(view, { data: { object: 'form_obj' } })).toBe('form_obj'); - expect(anonymousFormObjectName(view, {})).toBe('list_obj'); + expect(anonymousFormObjectName({ ...view, form: { data: { object: 'slot_obj' } } }, {})).toBe('slot_obj'); expect(anonymousFormObjectName({ object: 'v_obj' }, {})).toBe('v_obj'); expect(anonymousFormObjectName(undefined, undefined)).toBeUndefined(); }); + // [ADR-0159 D7] Since @objectstack/spec 19 a form reads no binding off a list. + it('anonymousFormObjectName: a list beside the form lends it no object', () => { + const view = { object: 'v_obj', list: { data: { object: 'list_obj' } } }; + expect(anonymousFormObjectName(view, {})).toBe('v_obj'); + expect(anonymousFormObjectName({ list: { data: { object: 'list_obj' } } }, {})).toBeUndefined(); + }); + it('the message names the slug, the object, the column and the posture, and ends with the remedy', () => { const u = { object: 'inquiry', posture: 'isolated' as const, tenantField: 'organization_id' }; const message = anonymousFormIntakeUnavailableMessage('contact-us', u); diff --git a/packages/metadata-protocol/src/protocol-form-reads.ts b/packages/metadata-protocol/src/protocol-form-reads.ts index 816cf86d0ec..809a42f9a1b 100644 --- a/packages/metadata-protocol/src/protocol-form-reads.ts +++ b/packages/metadata-protocol/src/protocol-form-reads.ts @@ -44,7 +44,7 @@ import { AsyncLocalStorage } from 'node:async_hooks'; import { pairsOf, type InstalledManifestLookup } from '@objectstack/metadata-core'; -import { PROJECTED_FORM_SOURCE_KEY, isAggregatedViewContainer, projectViewForms, type UnreadableFormBody } from '@objectstack/spec/ui'; +import { PROJECTED_FORM_SOURCE_KEY, isAggregatedViewContainer, isServedViewItem, projectViewForms, type UnreadableFormBody } from '@objectstack/spec/ui'; import { installedManifestsOfEngine } from './installed-manifests.js'; import type { ProtocolHost } from './protocol-host.js'; import { holdsServedOverlayCandidate, servedOverlayRowCandidates } from './protocol-overlay-merge.js'; @@ -369,17 +369,50 @@ function projectedServed(item: Record, packageId: string | unde } /** - * [ADR-0159 D5] The effective `form` list ({@link FormReadHost}): the generic - * `form` list, the projection of the served `view` list, and the cross-type - * resolution at each address whose package authors the form as a `form` item. - * See the module header for the three readings and how they combine. + * [ADR-0159 D7] Which reading of the stored old shapes a `form` read takes. + * + * - `'major-19'`, every read that serves or executes a form: the projection + * serves no content. A stored old-shape row is never a served item, and + * where the served-row order picks one at a package's address nothing of + * that name is served from the package while it stands (rule 11's kept + * replacement check, "After the major"). + * - `'before-the-switch'`, the stored-form census alone (`listStoredForms`, + * ADR-0159 D7-c): what the read served before the switch, the projected + * items included, so that the ceremony moves exactly the forms served today. + */ +export type StoredShapeReading = 'major-19' | 'before-the-switch'; + +/** + * [ADR-0159 D7] The by-name `view` answer a `view` read serves: a list, or no + * `item`, which both transports answer `404`: the answer of a name the served + * `view` list does not hold (`servedViewList`, `protocol-meta-list-reads.ts`). + * A stored old-shape form row at the name is not rewritten and not refused: it + * is left out of this served answer alone, and every reader of stored forms + * reads it raw ({@link storedViewRowHoldings}, `getViewItemsWithStoredForms`, + * the layered read). A new envelope: the answer it came from may be a cached + * one and is never mutated. + */ +export function servedViewItemAnswer(answer: T): T { + const item = (answer as { item?: unknown } | null | undefined)?.item; + if (item === undefined || item === null || isServedViewItem(item)) return answer; + const { item: _item, ...rest } = answer as Record; + return rest as T; +} + +/** + * [ADR-0159 D5, D7] The effective `form` list ({@link FormReadHost}): the + * generic `form` list, the projection of the served `view` list, and the + * cross-type resolution at each address whose package authors the form as a + * `form` item. See the module header for the three readings and how they + * combine, and {@link StoredShapeReading} for what the projection serves. */ export async function readEffectiveForms( host: FormReadHost, request: { type: string; packageId?: string; names?: readonly string[]; previewDrafts?: boolean }, audience: 'served' | 'execution', + reading: StoredShapeReading = 'major-19', ): Promise { - return (await readEffectiveFormList(host, request, audience)).items; + return (await readEffectiveFormList(host, request, audience, reading)).items; } /** @@ -411,9 +444,12 @@ export async function readEffectiveFormList( host: FormReadHost, request: { type: string; packageId?: string; names?: readonly string[]; previewDrafts?: boolean }, audience: 'served' | 'execution', + reading: StoredShapeReading = 'major-19', ): Promise<{ type: string; items: unknown[] } & Record> { // Every reading below reads through one request scope: each stored row set once. host = formRequestScope(host); + // [ADR-0159 D7] Whether a projected item is served (the census's reading only). + const servesProjection = reading === 'before-the-switch'; const { packageId: scope, names, ...rest } = request; const unscoped = { ...rest, type: 'form', ...(names !== undefined ? { names } : {}) }; const genericList = await host.readFlattenedMetaItems(unscoped, audience) as { items: unknown[] } & Record; @@ -506,8 +542,10 @@ export async function readEffectiveFormList( put(key, item); continue; } - // A stored `view` row is the served row at this address. - if (served.holding.kind === 'form') put(key, projectedServed(served.holding.item, pkg)); + // A stored `view` row is the served row at this address. [ADR-0159 D7] + // Since protocol 19 it serves no content: nothing of the name is served + // from the package while it stands (rule 11's kept replacement check). + if (servesProjection && served.holding.kind === 'form') put(key, projectedServed(served.holding.item, pkg)); // …else the closed reading: nothing is served for the name from the package. } // A package that authors the form but has no item in the generic list (its @@ -541,7 +579,8 @@ export async function readEffectiveFormList( continue; } } - put(key, item); + // [ADR-0159 D7] Since protocol 19 a projected item is not served. + if (servesProjection) put(key, item); } // …and a package-less `form` row that stood in at no such address is // listed as its own item, as the generic list serves it. diff --git a/packages/metadata-protocol/src/protocol-meta-list-reads.ts b/packages/metadata-protocol/src/protocol-meta-list-reads.ts index be949c2bad8..a04d38f1984 100644 --- a/packages/metadata-protocol/src/protocol-meta-list-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-list-reads.ts @@ -20,7 +20,7 @@ import { ITEM_KEY_DISCRIMINATORS, isTenantAuthored, packageDependencyClosure, pairsOf } from '@objectstack/metadata-core'; import { PLURAL_TO_SINGULAR, SINGULAR_TO_PLURAL } from '@objectstack/spec/shared'; -import { isAggregatedViewContainer } from '@objectstack/spec/ui'; +import { isAggregatedViewContainer, isServedViewItem } from '@objectstack/spec/ui'; import { type ItemAddress, type ItemLock, @@ -96,7 +96,33 @@ export async function getMetaItems(host: FormReadHost, request: { type: string; // generic read where the list names no package (`readEffectiveFormList`). if (canonical.type === 'form') return effectiveFormList(host, canonical, 'served'); // Inside a form request's reading (`readInFormRequest`), through its scope. - return inFormRequestScope(host).readFlattenedMetaItems(canonical, 'served'); + const answer = await inFormRequestScope(host).readFlattenedMetaItems(canonical, 'served'); + // [ADR-0159 D7] A `view` read serves lists only. + return canonical.type === 'view' ? servedViewList(answer) : answer; +} + +/** + * [ADR-0159 D7] The `view` list a `view` read serves: lists only. A stored + * old-shape row is not rewritten and not refused (constraint: the stored seam + * stays on STORED_ROWS_NOT_REWRITTEN): its form items are left out of the + * served answer, and every reader of stored forms reads them raw + * ({@link getViewItemsWithStoredForms}, the stored-row reads of + * `protocol-form-reads.ts`). A new envelope; the scoped read it came from is + * shared by the request's other readings and is never mutated. + */ +function servedViewList(answer: T): T { + const items = answer.items.filter(isServedViewItem); + return items.length === answer.items.length ? answer : { ...answer, items }; +} + +/** + * The body of `ObjectStackProtocolImplementation#getViewItemsWithStoredForms`; + * the method's docblock there is its contract. + */ +export async function getViewItemsWithStoredForms(host: FormReadHost, request: { type?: string; packageId?: string; previewDrafts?: boolean }) { + // Inside a form request's reading (`readInFormRequest`), through its scope: + // the same read the served `view` list filters. + return inFormRequestScope(host).readFlattenedMetaItems({ ...request, type: 'view' }, 'served'); } /** The body of `ObjectStackProtocolImplementation#getMetaItemsForExecution`; the method's docblock there is its contract. */ diff --git a/packages/metadata-protocol/src/protocol-stored-form-migration.ts b/packages/metadata-protocol/src/protocol-stored-form-migration.ts index c3a6509f9b9..b76bf8d0d2f 100644 --- a/packages/metadata-protocol/src/protocol-stored-form-migration.ts +++ b/packages/metadata-protocol/src/protocol-stored-form-migration.ts @@ -1757,10 +1757,11 @@ function collectFormActionTargets(value: unknown, out: Set, depth = 0): export async function listStoredForms(host: StoredFormCensusHost): Promise { const places = await storedFormPlaces(host); const installed = installedManifestsOfEngine(host.engine); - // The forms the read serves today, by package and name: the list the doors read. + // The forms the read serves today, by package and name: the list the doors + // read before the switch, the projected items included (ADR-0159 D7). const servedNow = new Set(); const servedNames = new Set(); - for (const item of await readEffectiveForms(host, { type: 'form' }, 'served')) { + for (const item of await readEffectiveForms(host, { type: 'form' }, 'served', 'before-the-switch')) { const { name, _packageId: packageId } = (item ?? {}) as { name?: unknown; _packageId?: unknown }; if (typeof name !== 'string') continue; servedNames.add(name); diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 79f0302b0a8..a3891c9110a 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -1,7 +1,7 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. import { formTypeWriteRefusal } from './protocol-form-writes.js'; -import { readInFormRequest, readUnreadableFormBodies } from './protocol-form-reads.js'; +import { readInFormRequest, readUnreadableFormBodies, servedViewItemAnswer } from './protocol-form-reads.js'; import type { DataProtocol, FlowRegistration, @@ -588,6 +588,7 @@ import { getMetaItems, getMetaItemsForExecution, getMetaItemsPerPackage, + getViewItemsWithStoredForms, readFlattenedMetaItems, } from './protocol-meta-list-reads.js'; // [#25467 E2 cut 1b] The metadata item reads and the layered reads. @@ -3530,6 +3531,23 @@ export class ObjectStackProtocolImplementation implements return getMetaItemsPerPackage(protocolHost(this), request); } + /** + * [ADR-0159 D7] The `view` list {@link getMetaItems} serves, WITH the form + * items of the stored old-shape rows it leaves out: a `view` read serves + * lists only since protocol 19, and a stored old-shape row is neither + * rewritten nor dropped by a read. A server-only extension, kept for one + * reader: **the anonymous form doors' withdrawal judgement** + * (`form-routes.ts` in `@objectstack/rest`), which reads every body the + * doors honoured (ADR-0159 D6 rule 10, the kept reader) and is never judged + * against a narrower layer than this one. + * + * ⛔ Never call this from a door that serves a caller a document: every + * such door serves {@link getMetaItems}. + */ + async getViewItemsWithStoredForms(request: { packageId?: string; previewDrafts?: boolean } = {}) { + return getViewItemsWithStoredForms(protocolHost(this), request); + } + /** Contract: {@link readUnreadableFormBodies} [ADR-0159 D6 rule 7]; a server-only extension the anonymous form doors feature-detect. */ async getUnreadableFormBodies(): Promise { return readUnreadableFormBodies(protocolHost(this)); @@ -4143,7 +4161,9 @@ export class ObjectStackProtocolImplementation implements userTextLocales?: readonly string[], }) { // [#25467 E1] The body moved to `protocol-meta-item-reads.ts`; it reaches this class through `protocol-host.ts`. - return getMetaItem(protocolHost(this), request); + const answer = await getMetaItem(protocolHost(this), request); + // [ADR-0159 D7] A `view` read serves lists only, in every state it serves. + return (PLURAL_TO_SINGULAR[request.type] ?? request.type) === 'view' ? servedViewItemAnswer(answer) : answer; } /** diff --git a/packages/metadata-protocol/src/protocol.ui-view-response-conformance.test.ts b/packages/metadata-protocol/src/protocol.ui-view-response-conformance.test.ts index 5faf80579d6..cc808b69747 100644 --- a/packages/metadata-protocol/src/protocol.ui-view-response-conformance.test.ts +++ b/packages/metadata-protocol/src/protocol.ui-view-response-conformance.test.ts @@ -26,8 +26,21 @@ // version of this test that can fail when the producer drifts. import { describe, it, expect } from 'vitest'; -import { GetUiViewResponseSchema } from '@objectstack/spec/api'; +import { z } from 'zod'; +import { GetUiViewResponseSchema, type GetUiViewFormScaffold } from '@objectstack/spec/api'; +import { FormViewSchema } from '@objectstack/spec/ui'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// The protocol reaches `@objectstack/lint` only through a dynamic import; paid +// here at module scope so the first load lands during collection, not inside a +// clocked window (`pnpm check:test-source-alias`). +import '@objectstack/lint'; + +/** + * [ADR-0159 D7] The `type: 'form'` answer, `GetUiViewFormScaffold`: a view + * holds lists only since @objectstack/spec 19, so the form scaffold is not a + * `ViewSchema` and is parsed here against the form body schema it carries. + */ +const FormScaffoldSchema = z.strictObject({ object: z.string(), form: FormViewSchema }); const SCHEMA = { name: 'account', @@ -65,13 +78,41 @@ describe('[#5948] getUiView emits a body that satisfies its own declared schema' expect(parsed.success).toBe(true); }); - it('form branch parses GREEN against GetUiViewResponseSchema', async () => { + it('form branch parses GREEN as the form scaffold: `{ object, form }`, its `form` a form body', async () => { const p = protocolFor(); const body = await p.getUiView({ object: 'account', type: 'form' }); - const parsed = GetUiViewResponseSchema.safeParse(body); + const parsed = FormScaffoldSchema.safeParse(body); expect(explain(parsed)).toBe('GREEN'); expect(parsed.success).toBe(true); + // …and it is not a view: `ViewSchema.form` is retired in protocol 19. + expect(GetUiViewResponseSchema.safeParse(body).success).toBe(false); + }); + + it('the form answer is byte-equal to the protocol-18 answer', async () => { + const p = protocolFor(); + const body = await p.getUiView({ object: 'account', type: 'form' }); + const field = (name: string, label: unknown, type: string, required?: boolean, colSpan = 1) => ({ + field: name, label, required, readonly: undefined, type, colSpan, span: 'auto', + }); + const expected: GetUiViewFormScaffold = { + object: 'account', + form: { + type: 'simple', + sections: [{ + label: 'General Information', + columns: 2, + collapsible: false, + collapsed: false, + fields: [ + field('name', 'Name', 'text', true), + field('status', 'Status', 'text'), + field('notes', 'Notes', 'textarea', undefined, 2), + ] as any, + }], + }, + }; + expect(JSON.stringify(body)).toBe(JSON.stringify(expected)); }); // The three keys this issue removed, pinned by name. The GREEN assertions diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index 4ee052f5e49..a5d53fe321c 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -698,8 +698,18 @@ export class AuthPlugin implements Plugin { * Organization, and on a kernel that composes the guard (`os serve`) a * database the guard refuses must be left as the guard found it, so the * organization is created only once the guard has judged. + * + * `com.objectstack.form-type-switch-boot-guard` — the protocol-19 boot guard + * (`@objectstack/runtime`'s `FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME`, spelled + * here for the same reason; ADR-0159 D7), order-if-present and for the same + * property: a database that guard refuses is left as it found it, so nothing + * `start()` writes is written before its verdict. */ - optionalDependencies = ['com.objectstack.service.settings', 'com.objectstack.organization-ownership-boot-guard']; + optionalDependencies = [ + 'com.objectstack.service.settings', + 'com.objectstack.organization-ownership-boot-guard', + 'com.objectstack.form-type-switch-boot-guard', + ]; private options: AuthPluginOptions; diff --git a/packages/plugins/plugin-auth/src/form-type-switch-guard-ordering.pin.test.ts b/packages/plugins/plugin-auth/src/form-type-switch-guard-ordering.pin.test.ts new file mode 100644 index 00000000000..dc57a657ab5 --- /dev/null +++ b/packages/plugins/plugin-auth/src/form-type-switch-guard-ordering.pin.test.ts @@ -0,0 +1,88 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Nothing the auth family writes at start is written before the protocol-19 + * boot guard has judged the database (ADR-0159 D7) — declared, not incidental. + * + * `AuthPlugin.start()` and `IdentityObjectsPlugin.start()` write identity rows + * (the Default Organization under `single`, ADR-0131 D3). The guard + * (`@objectstack/runtime`'s `FormTypeSwitchBootGuardPlugin`) judges in its own + * `start()`, and a database it refuses must be left as it found it, so both + * plugins name it in `optionalDependencies`, beside the v18 guard + * (`default-organization-guard-ordering.pin.test.ts`). This file proves the + * declaration is what moves the order: a hostile registry (the writer used + * BEFORE the guard) still starts the guard first, and the same registry with + * the declaration removed does not. The real guard on a real kernel is + * `runtime/src/form-type-switch-boot-guard.kernel.test.ts`. + * + * The guard is a NAME-ONLY stub carrying the real guard's own order-if-present + * edges: this package does not depend on the runtime, and + * `resolvePluginOrder` reads only the `OrderablePlugin` surface. + */ + +import { describe, expect, it } from 'vitest'; +import { resolvePluginOrder } from '@objectstack/core'; +import type { OrderablePlugin } from '@objectstack/core'; +import { AuthPlugin } from './auth-plugin.js'; +import { IdentityObjectsPlugin } from './identity-objects-plugin.js'; + +// Pay the first transform of the dist-resolved dependency `auth-plugin`'s +// reach loads through a dynamic `import()` at MODULE LOAD, never inside a +// case's clocked window (`scripts/check-test-source-alias.mjs`). +import '@objectstack/core/egress'; + +const GUARD_PLUGIN = 'com.objectstack.form-type-switch-boot-guard'; +const OWNERSHIP_GUARD_PLUGIN = 'com.objectstack.organization-ownership-boot-guard'; +const ENGINE_PLUGIN = 'com.objectstack.engine.objectql'; + +const writers: Array<[string, () => OrderablePlugin]> = [ + ['AuthPlugin', () => new AuthPlugin({ secret: 'test-secret-at-least-32-chars-long!!' }) as unknown as OrderablePlugin], + ['IdentityObjectsPlugin', () => new IdentityObjectsPlugin() as unknown as OrderablePlugin], +]; + +/** The guard as the resolver sees it: its name and its own order-if-present edges. */ +const guardStub = (): OrderablePlugin => ({ + name: GUARD_PLUGIN, + optionalDependencies: [ENGINE_PLUGIN, 'com.objectstack.platform-objects', OWNERSHIP_GUARD_PLUGIN], +}); + +const orderOf = (...plugins: OrderablePlugin[]): string[] => + resolvePluginOrder(new Map(plugins.map((p) => [p.name, p]))).map((p) => p.name); + +describe.each(writers)('%s writes its identity rows only after the protocol-19 boot guard has judged', (_label, make) => { + it('declares the guard as an OPTIONAL dependency', () => { + const writer = make(); + expect(writer.optionalDependencies ?? []).toContain(GUARD_PLUGIN); + expect(writer.dependencies ?? []).not.toContain(GUARD_PLUGIN); + }); + + it('⭐ the declaration moves the order: used BEFORE the guard, it still starts after it', () => { + const writer = make(); + const ordered = orderOf({ name: ENGINE_PLUGIN }, writer, guardStub()); + expect(ordered.indexOf(GUARD_PLUGIN)).toBeLessThan(ordered.indexOf(writer.name)); + }); + + it('…and the declaration is what does it: forget it and the writer starts first', () => { + const writer = make(); + writer.optionalDependencies = (writer.optionalDependencies ?? []).filter((d) => d !== GUARD_PLUGIN); + const ordered = orderOf({ name: ENGINE_PLUGIN }, writer, guardStub()); + expect(ordered.indexOf(writer.name)).toBeLessThan(ordered.indexOf(GUARD_PLUGIN)); + }); + + it('beside the v18 guard: used before both, it starts after both, the older guard judging first', () => { + const writer = make(); + const ordered = orderOf( + { name: ENGINE_PLUGIN }, + writer, + guardStub(), + { name: OWNERSHIP_GUARD_PLUGIN, optionalDependencies: [ENGINE_PLUGIN] }, + ); + expect(ordered.indexOf(OWNERSHIP_GUARD_PLUGIN)).toBeLessThan(ordered.indexOf(GUARD_PLUGIN)); + expect(ordered.indexOf(GUARD_PLUGIN)).toBeLessThan(ordered.indexOf(writer.name)); + }); + + it('order-if-present: a kernel that composes no guard resolves as before', () => { + const writer = make(); + expect(orderOf({ name: ENGINE_PLUGIN }, writer)).toContain(writer.name); + }); +}); diff --git a/packages/plugins/plugin-auth/src/identity-objects-plugin.ts b/packages/plugins/plugin-auth/src/identity-objects-plugin.ts index 164e60460fb..0c7d4dcb144 100644 --- a/packages/plugins/plugin-auth/src/identity-objects-plugin.ts +++ b/packages/plugins/plugin-auth/src/identity-objects-plugin.ts @@ -94,9 +94,15 @@ export class IdentityObjectsPlugin implements Plugin { * `auth` service is registered by the time `init()` asks, and the pair is * refused there. And the v18 boot guard's (ADR-0131 D10 item 5; see * `AuthPlugin.optionalDependencies`): `start()` creates the Default - * Organization only once the guard has judged the database. + * Organization only once the guard has judged the database. And the + * protocol-19 boot guard's (ADR-0159 D7), for the same property: nothing + * `start()` writes is written before that guard's verdict. */ - optionalDependencies: string[] = ['com.objectstack.auth', 'com.objectstack.organization-ownership-boot-guard']; + optionalDependencies: string[] = [ + 'com.objectstack.auth', + 'com.objectstack.organization-ownership-boot-guard', + 'com.objectstack.form-type-switch-boot-guard', + ]; requiresServices: string[] = ['manifest']; private readonly options: IdentityObjectsPluginOptions; diff --git a/packages/qa/dogfood/test/form-type-switch-boot-refusal.dogfood.test.ts b/packages/qa/dogfood/test/form-type-switch-boot-refusal.dogfood.test.ts new file mode 100644 index 00000000000..17a8d423b83 --- /dev/null +++ b/packages/qa/dogfood/test/form-type-switch-boot-refusal.dogfood.test.ts @@ -0,0 +1,143 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [ADR-0159 D7] A runtime on protocol major 19 serves a database only once the +// protocol-19 switch is recorded on it, and the refusal is the way through, +// never a dead end. +// +// Measured here end to end, on the showcase composition over SQLite files: +// +// 1. a database an earlier boot left behind, with no switch record, is +// refused, naming the command. It stores no form in an old shape at all: +// the command still has to run once, because only its census can say so; +// 2. `os migrate protocol --to 19` previews and writes nothing; with +// `--apply --yes` it records the switch — through the real CLI binary, +// with the arguments, working directory and environment an operator's run +// has, and with no boot in between; +// 3. the next boot is served; +// 4. a database this boot creates from empty needs no command: the boot +// records the switch itself as a birth marker, and the boot after it reads +// that record like any other. +// +// The guard is composed here as `os serve` composes it: its own plugin, judged +// in its own `start()`. A boot without it (`bootShowcase` composes none of its +// own) is how step 1's database comes to exist with no record. + +import { spawnSync } from 'node:child_process'; +import { copyFileSync, mkdtempSync, rmSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { DatabaseSync } from 'node:sqlite'; +import { afterAll, describe, expect, it } from 'vitest'; +import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; +import { FormTypeSwitchBootGuardPlugin, isFormTypeSwitchBootRefusal } from '@objectstack/runtime'; +import { FORM_TYPE_SWITCH_MIGRATION_ID } from '@objectstack/spec/system'; +import { bootShowcase } from './showcase-boot.js'; + +const SHOWCASE_DIR = fileURLToPath(new URL('../../../../examples/app-showcase/', import.meta.url)); +const CLI_ROOT = dirname(createRequire(import.meta.url).resolve('@objectstack/cli/package.json')); +const CLI_BIN = join(CLI_ROOT, 'bin', 'run.js'); + +interface MarkerRow { verified_at: unknown; applied_at: unknown; blocking: unknown; details: unknown } + +/** The switch record of `file`, read on a connection of our own; undefined when there is none. */ +function switchMarker(file: string): MarkerRow | undefined { + const db = new DatabaseSync(file); + try { + return db.prepare('SELECT verified_at, applied_at, blocking, details FROM sys_migration WHERE id = ?') + .get(FORM_TYPE_SWITCH_MIGRATION_ID) as MarkerRow | undefined; + } finally { + db.close(); + } +} + +/** The guard's refusal down a failed boot's `cause` chain (the kernel reports a failed `start()` as its own error). */ +function refusalIn(error: unknown): unknown { + for (let e = error, depth = 0; !!e && typeof e === 'object' && depth < 8; e = (e as { cause?: unknown }).cause, depth++) { + if (isFormTypeSwitchBootRefusal(e)) return e; + } + return undefined; +} + +/** A boot of the showcase over `file`; with `guard`, the switch guard composed as `os serve` composes it. The failure, or null. */ +async function boot(file: string, guard: boolean): Promise { + try { + const stack = await bootShowcase({ + databaseFile: file, + security: new SecurityPlugin({ defaultPermissionSets: [...securityDefaultPermissionSets] }), + extraPlugins: guard ? [new FormTypeSwitchBootGuardPlugin()] : [], + }); + await stack.stop(); + return null; + } catch (error) { + return error; + } +} + +/** `os migrate protocol --to 19` over `file`, through the real binary, run from the showcase's directory. */ +const protocolCommand = (file: string, args: string[]) => spawnSync(process.execPath, [ + CLI_BIN, 'migrate', 'protocol', '--to', '19', '--database-url', `file:${file}`, ...args, +], { cwd: SHOWCASE_DIR, encoding: 'utf8', timeout: 300_000, env: { ...process.env, NO_COLOR: '1' } }); + +describe('[ADR-0159 D7] a database with no protocol-19 switch record is refused, and the named command is the way through', () => { + const dir = mkdtempSync(join(tmpdir(), 'dogfood-form-type-switch-')); + const file = join(dir, 'showcase.db'); + /** + * The command's output, copied the moment the switch is recorded. An + * operator's refused `os serve` process has exited before the command runs; + * the refused boot here lives on in this process with its SQLite driver + * never torn down (bootstrap failed before any handle came back), so the + * next boot reads the copied bytes, which is the operator's sequence. + */ + const switched = join(dir, 'showcase.switched.db'); + let refusal: unknown; + + afterAll(() => { + rmSync(dir, { recursive: true, force: true }); + }); + + it('1. a database an earlier boot left with no switch record is refused, naming the command', async () => { + expect(await boot(file, false), 'the boot that leaves the database behind').toBeNull(); + expect(switchMarker(file), 'a boot without the guard records no switch').toBeUndefined(); + + refusal = refusalIn(await boot(file, true)); + expect(refusal, 'the boot was refused for the missing switch record').toBeDefined(); + expect((refusal as { reason?: string }).reason).toBe('absent'); + expect(String((refusal as Error).message)).toContain("'os migrate protocol --to 19 --apply --yes'"); + expect(switchMarker(file), 'a refused boot records nothing').toBeUndefined(); + }, 480_000); + + it('2. the command previews without writing, then records the switch with no boot in between', () => { + expect(refusal).toBeDefined(); + const preview = protocolCommand(file, []); + expect(preview.status, `${preview.stdout}\n${preview.stderr}`).toBe(0); + expect(switchMarker(file), 'the preview records nothing').toBeUndefined(); + + const run = protocolCommand(file, ['--apply', '--yes']); + expect(run.status, `${run.stdout}\n${run.stderr}`).toBe(0); + const marker = switchMarker(file); + expect(marker?.verified_at, 'the command verified its record').toBeTruthy(); + expect(Number(marker?.blocking)).toBe(0); + copyFileSync(file, switched); + }, 640_000); + + it('3. the next boot is served', async () => { + expect(await boot(switched, true)).toBeNull(); + }, 240_000); + + it('4. a database the boot creates from empty records the switch itself, and the boot after it is served', async () => { + const born = join(dir, 'born.db'); + expect(await boot(born, true)).toBeNull(); + const marker = switchMarker(born); + expect(marker?.verified_at, 'the birth marker is a verified record').toBeTruthy(); + expect(Number(marker?.blocking)).toBe(0); + // No ceremony ran: the record says how the database came to be, not that forms were moved. + expect(marker?.applied_at ?? null).toBeNull(); + const details = typeof marker?.details === 'string' ? JSON.parse(marker.details) : marker?.details; + expect(details?.birth?.protocol).toBe(19); + + expect(await boot(born, true)).toBeNull(); + expect(switchMarker(born)?.details, 'the second boot reads the record and leaves it as it is').toEqual(marker?.details); + }, 480_000); +}); diff --git a/packages/qa/dogfood/test/guest-grants-channel.dogfood.test.ts b/packages/qa/dogfood/test/guest-grants-channel.dogfood.test.ts index f99f65fe497..dbf834ea387 100644 --- a/packages/qa/dogfood/test/guest-grants-channel.dogfood.test.ts +++ b/packages/qa/dogfood/test/guest-grants-channel.dogfood.test.ts @@ -38,7 +38,7 @@ import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; import { bootStack, type VerifyStack } from '@objectstack/verify'; import { MetadataPlugin } from '@objectstack/metadata'; -import { defineStack, defineView } from '@objectstack/spec'; +import { defineForm, defineStack, defineView } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; import { definePermissionSet } from '@objectstack/spec/security'; import type { ApiEndpoint } from '@objectstack/spec/api'; @@ -157,14 +157,14 @@ const endpoints: ApiEndpoint[] = [ const intakeData = { provider: 'object' as const, object: OBJ.intake }; const IntakeViews = defineView({ list: { label: 'Intake', type: 'grid', data: intakeData, columns: [{ field: 'name' }] }, - formViews: { - intake: { - type: 'simple', - data: intakeData, - sections: [{ name: 'intake', label: 'Intake', columns: 1, fields: [{ field: 'name', required: true }] }], - sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${FORM_SLUG}` }, - }, - }, +}); +/** The public form, a `form` item (ADR-0159): `OBJECT.KEY`, bound by `object`. */ +const IntakeForm = defineForm({ + name: `${OBJ.intake}.intake`, + object: OBJ.intake, + type: 'simple', + sections: [{ name: 'intake', label: 'Intake', columns: 1, fields: [{ field: 'name', required: true }] }], + sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${FORM_SLUG}` }, }); const fixtureStack = defineStack({ @@ -178,6 +178,7 @@ const fixtureStack = defineStack({ }, objects, views: [IntakeViews], + forms: [IntakeForm], permissions: [GuestReader, FoldSet, EveryoneReader], apis: endpoints, } as any); diff --git a/packages/qa/dogfood/test/guest-owner-stamp.dogfood.test.ts b/packages/qa/dogfood/test/guest-owner-stamp.dogfood.test.ts index 9e2f1caaefb..3822d2d7002 100644 --- a/packages/qa/dogfood/test/guest-owner-stamp.dogfood.test.ts +++ b/packages/qa/dogfood/test/guest-owner-stamp.dogfood.test.ts @@ -36,7 +36,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { bootStack, type VerifyStack } from '@objectstack/verify'; import { MetadataPlugin } from '@objectstack/metadata'; import { RecordChangeTriggerPlugin } from '@objectstack/trigger-record-change'; -import { defineStack, defineView, defineFlow } from '@objectstack/spec'; +import { defineForm, defineStack, defineView, defineFlow } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; import { definePermissionSet, describeAnchorForbiddenBits } from '@objectstack/spec/security'; import { SystemUserId } from '@objectstack/spec/system'; @@ -134,14 +134,14 @@ const create = (key: 'lead' | 'hooked' | 'flowed'): ApiEndpoint => ({ const intakeData = { provider: 'object' as const, object: OBJ.intake }; const IntakeViews = defineView({ list: { label: 'Intake', type: 'grid', data: intakeData, columns: [{ field: 'name' }] }, - formViews: { - intake: { - type: 'simple', - data: intakeData, - sections: [{ name: 'intake', label: 'Intake', columns: 1, fields: [{ field: 'name', required: true }] }], - sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${FORM_SLUG}` }, - }, - }, +}); +/** The public form, a `form` item (ADR-0159): `OBJECT.KEY`, bound by `object`. */ +const IntakeForm = defineForm({ + name: `${OBJ.intake}.intake`, + object: OBJ.intake, + type: 'simple', + sections: [{ name: 'intake', label: 'Intake', columns: 1, fields: [{ field: 'name', required: true }] }], + sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${FORM_SLUG}` }, }); const fixtureStack = defineStack({ @@ -157,6 +157,7 @@ const fixtureStack = defineStack({ requires: ['automation', 'triggers'], objects: [object(OBJ.lead), object(OBJ.hooked), object(OBJ.flowed), object(OBJ.intake)], views: [IntakeViews], + forms: [IntakeForm], flows: [AssignFlow], permissions: [GuestWriter, GuestWriterTransfer], apis: [create('lead'), create('hooked'), create('flowed')], diff --git a/packages/qa/dogfood/test/public-form-read-back-masking.dogfood.test.ts b/packages/qa/dogfood/test/public-form-read-back-masking.dogfood.test.ts index 848214ec532..db1c5cc3b56 100644 --- a/packages/qa/dogfood/test/public-form-read-back-masking.dogfood.test.ts +++ b/packages/qa/dogfood/test/public-form-read-back-masking.dogfood.test.ts @@ -33,7 +33,7 @@ import { describe, it, expect } from 'vitest'; import { bootStack } from '@objectstack/verify'; -import { defineStack, defineView } from '@objectstack/spec'; +import { defineForm, defineStack, defineView } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; import { definePermissionSet } from '@objectstack/spec/security'; @@ -62,21 +62,21 @@ const PfmaskTicket = ObjectSchema.create({ const data = { provider: 'object' as const, object: TICKET }; const PfmaskTicketViews = defineView({ list: { label: 'Tickets', type: 'grid', data, columns: [{ field: 'subject' }] }, - formViews: { - intake: { - type: 'simple', - data, - sections: [ - { - name: 'intake', - label: 'Intake', - columns: 1, - fields: [{ field: 'subject', required: true }, { field: 'pfmask_code' }], - }, - ], - sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${SLUG}` }, +}); +/** The public form, a `form` item (ADR-0159): `OBJECT.KEY`, bound by `object`. */ +const PfmaskTicketIntakeForm = defineForm({ + name: `${TICKET}.intake`, + object: TICKET, + type: 'simple', + sections: [ + { + name: 'intake', + label: 'Intake', + columns: 1, + fields: [{ field: 'subject', required: true }, { field: 'pfmask_code' }], }, - }, + ], + sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${SLUG}` }, }); /** The guest set the form-submit route's grant context names, declared by the stack. */ @@ -99,12 +99,14 @@ const noGuestSetStack = defineStack({ manifest: manifest('no-guest-set', 'One object with two masked fields behind an anonymous form; no guest set.'), objects: [PfmaskTicket], views: [PfmaskTicketViews], + forms: [PfmaskTicketIntakeForm], }); const guestSetStack = defineStack({ manifest: manifest('guest-set', 'One object with two masked fields behind an anonymous form, and a guest set.'), objects: [PfmaskTicket], views: [PfmaskTicketViews], + forms: [PfmaskTicketIntakeForm], permissions: [PfmaskGuestSet], }); diff --git a/packages/qa/dogfood/test/public-form-submit-answer.dogfood.test.ts b/packages/qa/dogfood/test/public-form-submit-answer.dogfood.test.ts index 5050d847a3a..34d903bc248 100644 --- a/packages/qa/dogfood/test/public-form-submit-answer.dogfood.test.ts +++ b/packages/qa/dogfood/test/public-form-submit-answer.dogfood.test.ts @@ -33,7 +33,7 @@ import { describe, it, expect } from 'vitest'; import { bootStack } from '@objectstack/verify'; -import { defineStack, defineView } from '@objectstack/spec'; +import { defineForm, defineStack, defineView } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; import { definePermissionSet } from '@objectstack/spec/security'; @@ -77,21 +77,21 @@ const PfansRequest = ObjectSchema.create({ const data = { provider: 'object' as const, object: REQUEST }; const PfansRequestViews = defineView({ list: { label: 'Requests', type: 'grid', data, columns: [{ field: 'subject' }] }, - formViews: { - intake: { - type: 'simple', - data, - sections: [ - { - name: 'intake', - label: 'Intake', - columns: 1, - fields: [{ field: 'subject', required: true }, { field: 'email' }], - }, - ], - sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${SLUG}` }, +}); +/** The public form, a `form` item (ADR-0159): `OBJECT.KEY`, bound by `object`. */ +const PfansRequestIntakeForm = defineForm({ + name: `${REQUEST}.intake`, + object: REQUEST, + type: 'simple', + sections: [ + { + name: 'intake', + label: 'Intake', + columns: 1, + fields: [{ field: 'subject', required: true }, { field: 'email' }], }, - }, + ], + sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${SLUG}` }, }); /** Look the submitted email up among existing contacts, elevated, and stamp the match. */ @@ -135,6 +135,7 @@ const noGuestSetStack = defineStack({ manifest: manifest('no-guest-set', 'An anonymous form whose elevated hook stamps a match from existing records; no guest set.'), objects: [PfansContact, PfansRequest], views: [PfansRequestViews], + forms: [PfansRequestIntakeForm], hooks: [matchExistingHook], } as any); @@ -142,6 +143,7 @@ const guestSetStack = defineStack({ manifest: manifest('guest-set', 'An anonymous form whose elevated hook stamps a match from existing records, and a guest set.'), objects: [PfansContact, PfansRequest], views: [PfansRequestViews], + forms: [PfansRequestIntakeForm], hooks: [matchExistingHook], permissions: [PfansGuestSet], } as any); diff --git a/packages/qa/dogfood/test/public-form-withdrawal-walled.dogfood.test.ts b/packages/qa/dogfood/test/public-form-withdrawal-walled.dogfood.test.ts index 03de40e5cef..a199d251026 100644 --- a/packages/qa/dogfood/test/public-form-withdrawal-walled.dogfood.test.ts +++ b/packages/qa/dogfood/test/public-form-withdrawal-walled.dogfood.test.ts @@ -29,13 +29,13 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { bootStack, type VerifyStack } from '@objectstack/verify'; import { declaredOverride, ensurePair, inPair } from './customization-pair.js'; -import { defineStack, defineView } from '@objectstack/spec'; +import { defineForm, defineStack, defineView } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; const LEAD = 'walled_lead'; const SLUG = 'walled-lead-intake'; -const VIEW = `/meta/view/${LEAD}.intake`; +const FORM = `/meta/form/${LEAD}.intake`; const BASE = 'com.dogfood.walled-public-form'; const WalledLead = ObjectSchema.create({ @@ -52,14 +52,14 @@ const WalledLead = ObjectSchema.create({ const data = { provider: 'object' as const, object: LEAD }; const WalledLeadViews = defineView({ list: { label: 'Leads', type: 'grid', data, columns: [{ field: 'name' }] }, - formViews: { - intake: { - type: 'simple', - data, - sections: [{ name: 'intake', label: 'Intake', columns: 1, fields: [{ field: 'name', required: true }] }], - sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${SLUG}` }, - }, - }, +}); +/** The public form, a `form` item (ADR-0159): `OBJECT.KEY`, bound by `object`, the body at its root. */ +const WalledLeadIntakeForm = defineForm({ + name: `${LEAD}.intake`, + object: LEAD, + type: 'simple', + sections: [{ name: 'intake', label: 'Intake', columns: 1, fields: [{ field: 'name', required: true }] }], + sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${SLUG}` }, }); const walledFormStack = defineStack({ @@ -73,6 +73,7 @@ const walledFormStack = defineStack({ }, objects: [WalledLead], views: [WalledLeadViews], + forms: [WalledLeadIntakeForm], }); const SYS = { isSystem: true } as const; @@ -114,20 +115,20 @@ describe('walled posture: withdrawing a public form from anonymous intake', () = /** PUT the form at the admin's current session scope. */ const put = async (body: Record) => { - const res = await stack.apiAs(admin, 'PUT', inPair(VIEW, BASE), declaredOverride(body, BASE, '0.0.0')); + const res = await stack.apiAs(admin, 'PUT', inPair(FORM, BASE), declaredOverride(body, BASE, '0.0.0')); const json = (await res.json()) as Record; return { status: res.status, json }; }; const withAnonymous = (allowAnonymous: boolean): Record => { const body = structuredClone(published); - body.config.sharing.allowAnonymous = allowAnonymous; + body.sharing.allowAnonymous = allowAnonymous; return body; }; /** The effective form as the admin's current scope reads it. */ const read = async (): Promise> => { - const res = await stack.apiAs(admin, 'GET', VIEW); + const res = await stack.apiAs(admin, 'GET', FORM); expect(res.status).toBe(200); const json = (await res.json()) as { item?: Record }; return (json.item ?? json) as Record; @@ -144,7 +145,7 @@ describe('walled posture: withdrawing a public form from anonymous intake', () = const item = await read(); // The editor's PUT body: the effective item without its read decorations. published = Object.fromEntries(Object.entries(item).filter(([k]) => !k.startsWith('_'))); - expect(published.config?.sharing?.allowAnonymous).toBe(true); + expect(published.sharing?.allowAnonymous).toBe(true); const created = await stack.apiAs(admin, 'POST', '/auth/organization/create', { name: 'Walled Tenant', slug: 'walled-tenant-form', @@ -221,7 +222,7 @@ describe('walled posture: withdrawing a public form from anonymous intake', () = it('withdrawn through `sharing.enabled: false` alone, by an org-active admin and env-wide: both doors 404 and nothing lands', async () => { const withEnabled = (enabled: boolean): Record => { const body = withAnonymous(true); - body.config.sharing.enabled = enabled; + body.sharing.enabled = enabled; return body; }; // [ADR-0131 D6] An org-active admin's withdrawal is environment-wide too. diff --git a/packages/rest/src/form-routes.ts b/packages/rest/src/form-routes.ts index c2268c420f6..b62bf7a0c1c 100644 --- a/packages/rest/src/form-routes.ts +++ b/packages/rest/src/form-routes.ts @@ -68,20 +68,16 @@ */ import { - anonymousFormIntakeCandidates, anonymousFormIntakePosture, anonymousFormIntakeUnavailability, - anonymousFormObjectName, } from '@objectstack/metadata-core'; import { isEmptyForRequired, isMissing } from '@objectstack/core'; import type { CreateDataRequest, GetMetaItemsRequest, PublicFormSubmitResponse } from '@objectstack/spec/api'; import { PUBLIC_FORM_SERVER_MANAGED_FIELDS } from '@objectstack/spec/security'; import { renderValidationMessage } from '@objectstack/spec/system'; import { - PROJECTED_FORM_SOURCE_KEY, formIntakeLayer, openFormAt, - projectViewForms, thankYouRecordFieldNames, type FormIntakeLayer, type UnreadableFormBody, @@ -215,12 +211,10 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo // dependent package's same-named row, the base's form the override // removed — is not offered: that narrows intake, the direction a layer // may take. - // [ADR-0159 D6] Since card ②, over BOTH types. The candidates are the - // open forms of the effective `form` read — authored `form` items and the - // projection of the old shapes (a container's `form`, a `formViews` - // entry, a `viewKind: 'form'` item), resolved over both types, so a - // stored row that closes an address by replacing its base's body keeps - // closing it. The withdrawal layer is the effective lists AND the + // [ADR-0159 D6, D7] Over BOTH types. The candidates are the open forms of + // the effective `form` read, resolved over both types, so a stored row + // that closes an address by replacing its base's body keeps closing it + // (rule 11). The withdrawal layer is the effective lists AND the // per-package layers of both `form` and `view`, the old shapes passed // through the projection first (`formIntakeLayer`): narrowing only, in // both directions. Identity is the served name and, inside one name, the @@ -229,38 +223,19 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo // different form. A stored body the projection cannot read closes the // links it names (rule 7, `getUnreadableFormBodies`). // - // A projected form whose served `view` item the effective `view` list - // still serves is answered through that item exactly as before (the same - // `form` object, the same label and translation), so an old-shape form - // answers byte-equal on the resolve door. + // [ADR-0159 D7] Since protocol 19 the candidates are `form` items only: + // the projection serves no content, so no candidate is answered through a + // `view` item. The stored old-shape bodies are read for the withdrawal + // layer alone (rule 10, the kept reader). const findPublicForm = ( forms: any[], - views: any[], layer: FormIntakeLayer, slug: string, - ): { view: any; form: any; object: string; formItem: any } | null => { + ): { form: any; object: string; formItem: any } | null => { const open = openFormAt(forms ?? [], layer, slug); if (!open) return null; const item = open.form; - if (item?.[PROJECTED_FORM_SOURCE_KEY] === 'view') { - const pkg = item?._packageId ?? undefined; - for (const view of views ?? []) { - if (!view || typeof view !== 'object') continue; - // The served item of that name, or (from a protocol that hands - // the doors a container) the container whose projection it is. - if (view.name !== item.name && !projectViewForms(view).forms.some((f) => f.name === item.name)) continue; - if ((view._packageId ?? undefined) !== pkg) continue; - const c = anonymousFormIntakeCandidates(view).find((candidate) => candidate.slug === slug); - if (!c) continue; - const objectName = anonymousFormObjectName(view, c.form); - if (objectName !== open.object) continue; - return { view, form: c.form, object: objectName, formItem: item }; - } - } - // An authored `form` item, or a projected one the `view` list does - // not serve at its address (a stored `view` row over a base that left - // the type): served as the form body, without its item envelope. - return { view: undefined, form: formBodyOf(item), object: open.object, formItem: item }; + return { form: formBodyOf(item), object: open.object, formItem: item }; }; // [ADR-0131 D6, C7] WHICH metadata an anonymous form request reads: @@ -292,7 +267,7 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo environmentId: string | undefined, req: any, slug: string, - ): Promise<{ view: any; form: any; object: string; formItem: any } | null> => { + ): Promise<{ form: any; object: string; formItem: any } | null> => { const p = await this.resolveProtocol(environmentId, req); if (typeof (p as any).getMetaItems !== 'function') return null; const tenancy = await this.resolveAnonymousFormTenancy(environmentId, req); @@ -314,8 +289,16 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo const inOneReading = (read: () => Promise): Promise => (typeof (p as any).readFormRequest === 'function' ? (p as any).readFormRequest(read) : read()); - const { forms, views, layer } = await inOneReading(async () => { - const views = listOf(await p.getMetaItems(viewsRequest)); + const { forms, layer } = await inOneReading(async () => { + // [ADR-0159 D7, D6 rule 10] The withdrawal layer reads every + // stored body the doors honoured, the form items of a stored + // old-shape row included, which the served `view` list leaves out + // since protocol 19 (`getViewItemsWithStoredForms`, a server-only + // extension, feature-detected). A protocol without it serves the + // whole `view` list on its own read. + const views = listOf(typeof (p as any).getViewItemsWithStoredForms === 'function' + ? await (p as any).getViewItemsWithStoredForms(viewsRequest) + : await p.getMetaItems(viewsRequest)); // [ADR-0159 D5, D6 rules 1 and 3] The candidates are the effective // `form` read, which projects the old shapes itself: ONE read, and no // second candidate source inside the door. A protocol that serves no @@ -338,9 +321,9 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo views: [...views, ...(await perPackage(viewsRequest))], unreadable, }); - return { forms, views, layer }; + return { forms, layer }; }); - const match = findPublicForm(forms, views, layer, slug); + const match = findPublicForm(forms, layer, slug); if (!match) return null; // [#21476] A form that cannot take intake on this posture is not // offered: `null` here IS the withdrawn form's answer on both @@ -407,12 +390,12 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo // sections' `label` / `description` localized beside the // schema's field labels (see the translation block). let servedForm: any = match.form; - // The top-level `label`, served from the TRANSLATED view - // when the view authors one (see the translation block). A - // view that authors none keeps the route's own reading, so + // The top-level `label`, served from the TRANSLATED form + // when the form authors one (see the translation block). A + // form that authors none keeps the route's own reading, so // the console's `label ?? form.title ?? objectSchema.label` // still reaches the form's (translated) title. - let servedLabel: any = match.view !== undefined ? (match.view?.label ?? match.form?.label) : match.formItem?.label; + let servedLabel: any = match.formItem?.label; try { const p = await this.resolveProtocol(environmentId, req); if (typeof (p as any).getMetaItems === 'function') { @@ -470,7 +453,7 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo // rank sits above it: an object is extended, // never replaced (ADR-0146 D10), so it never // answers `servedOverrideBaseOf` and this call - // passes no `pairBundle` (the view call below does). + // passes no `pairBundle` (the form call below does). const patchBundles = await patchTranslationBundlesOf(p, 'object', objectSchema?.name); objectSchema = translateMetadataDocument('object', objectSchema, bundle, { ...this.translateOptionsFor(i18n, locale), @@ -479,69 +462,28 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo }); // [#23497] The section headings. An anonymous // visitor cannot load the bundle client-side (the - // `/i18n` domain answers it 401), so a section's - // `objects.OBJECT._sections.NAME` copy reaches it - // here or not at all. ONE call into the spec's view - // translator, which owns every rule: the key is the - // section's `name` (a nameless section is returned - // as authored), a missing key keeps the authored - // text, only authored copy is translated, and an - // explicit override beats the catalog against the - // packaged view, handed over exactly as the object - // call above hands its own base. ⛔ No walk of - // `_sections` and no locale chain here. - // - // The protocol's view list serves view ITEMS only - // (a container is dropped and served as the - // `viewKind: 'form'` items it expands to), so the - // matched form is the item's `config`, the address - // `translateView` translates sections at. A form - // matched in any other slot is served as matched, - // never swapped for the item's `config`. It runs - // BEFORE the strip below and returns each section's - // `fields` untouched, so it cannot re-introduce a - // stripped field. The same call translates the - // form's `title` (`objects.OBJECT._views.VIEW.title`, - // at `config.title`), so the served form carries it. - // - // The top-level `label` is taken from the translated - // view only when the view AUTHORS one: the translator - // falls back to the view's machine name, which must - // never shadow the form's title in the console's - // `label ?? form.title ?? objectSchema.label`. + // `/i18n` domain answers it 401), so the form's copy + // reaches it here or not at all. ONE call into the + // spec's form translator, which owns every rule: + // `forms.NAME` first, `objects.OBJECT._sections` as + // a section's object-level default, a missing key + // keeps the authored text, and an explicit override + // beats the catalog against the packaged form. It + // runs BEFORE the strip below and returns each + // section's `fields` untouched, so it cannot + // re-introduce a stripped field. // - // A form view a `.custom` pair overrides (ADR-0146 - // D2) is also handed the pair's own translations, - // the first rank of a string the override changed - // (ruling record 6631250894): the same - // `pairTranslationBundleOf` question the `/meta/view` - // reads ask, of the view as the protocol served it - // (its envelope names the base). `undefined` keeps - // the override's own text, as before. - if (match.view !== undefined) { - const pairBundle = await pairTranslationBundleOf(p, 'view', match.view); - const view = translateMetadataDocument('view', match.view, bundle, { - ...this.translateOptionsFor(i18n, locale), - packagedBase: this.packagedObjectBase(p, 'view', match.view?.name), - ...(pairBundle !== undefined ? { pairBundle: pairBundle as any } : {}), - }); - if (match.form === match.view?.config) servedForm = view?.config; - if (match.view?.label !== undefined && view?.label !== undefined) { - servedLabel = view.label; - } - } else { - // [ADR-0159 D8] A `form` item: `forms.NAME` first, - // its old-shape `_views` tails as the fallback. - const pairBundle = await pairTranslationBundleOf(p, 'form', match.formItem); - const form = translateMetadataDocument('form', match.formItem, bundle, { - ...this.translateOptionsFor(i18n, locale), - packagedBase: this.packagedObjectBase(p, 'form', match.formItem?.name), - ...(pairBundle !== undefined ? { pairBundle: pairBundle as any } : {}), - }); - servedForm = formBodyOf(form); - if (match.formItem?.label !== undefined && form?.label !== undefined) { - servedLabel = form.label; - } + // [ADR-0159 D8] A `form` item, translated from `forms.NAME`; + // the `.custom` pair's own strings rank first (ADR-0146 D2). + const pairBundle = await pairTranslationBundleOf(p, 'form', match.formItem); + const form = translateMetadataDocument('form', match.formItem, bundle, { + ...this.translateOptionsFor(i18n, locale), + packagedBase: this.packagedObjectBase(p, 'form', match.formItem?.name), + ...(pairBundle !== undefined ? { pairBundle: pairBundle as any } : {}), + }); + servedForm = formBodyOf(form); + if (match.formItem?.label !== undefined && form?.label !== undefined) { + servedLabel = form.label; } } } catch (e: any) { diff --git a/packages/rest/src/stored-forms-major19-kept-reader.test.ts b/packages/rest/src/stored-forms-major19-kept-reader.test.ts new file mode 100644 index 00000000000..e787e45912f --- /dev/null +++ b/packages/rest/src/stored-forms-major19-kept-reader.test.ts @@ -0,0 +1,365 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0159 D5, D6 rules 10 and 11, D7; card ⑤b #37112] What both public form + * doors answer on a major-19 build for a stored row of the old shapes. + * + * Since @objectstack/spec 19 a `view` holds lists only: no door admits + * `view.form`, `view.formViews` or `viewKind: 'form'`, and no read serves form + * content from a `view` row. A deployment upgraded from 18 may still store + * such rows. They are read, never refused and never rewritten by a read, and + * these pins hold what `GET /api/v1/forms/:slug` and + * `POST /api/v1/forms/:slug/submit` answer at the address of a package's open + * `form` item while one stands: + * + * - a stored old-shape body whose form is switched off (the link kept); + * - a stored old-shape row of the form's name whose form names no link; + * - a stored row of the form's name that carries no form at all (a list), + * in each binding ADR-0159 D5 bounds the reading to. + * + * Every row is seeded as the store holds it at rest (the save door refuses the + * shapes; the last describe pins that refusal), and every pin reads status, + * `code` and the record count on both doors. The harness is the one of + * `stored-forms-switch-37112.test.ts`: the real protocol on a real `ObjectQL` + * engine and SQL store. + * + * Ablations (each run, rebuilt and restored; recorded in the PR): + * - describe 1: `oldShapeFormWithdrawals` answers no withdrawal; + * - describe 2: `readEffectiveFormList` serves the package's source item + * under a stored `view` row that holds a form; + * - describe 3: the same read serves it under a stored `view` row that holds + * no form. + */ +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { + ObjectStackProtocolImplementation, + resetEnvWritableMetadataTypes, +} from '@objectstack/metadata-protocol'; +import { + SysMetadataAuditObject, + SysMetadataCommitObject, + SysMetadataHistoryObject, + SysMetadataObject, + hashSpec, +} from '@objectstack/metadata-core'; +import { RestServer } from './rest-server'; + +const BASE = 'com.example.forms19'; +const PAIR = `${BASE}.custom`; +const DEPENDENT = 'com.default.acme-forms19'; +const OBJECT = 'fkr_inquiry'; +const NAME = `${OBJECT}.contact`; +const SLUG = 'contact-19'; + +const overrides = { overrides: { package: BASE, basedOn: '1.0.0' } }; +const sharing = (open: boolean) => ({ enabled: true, allowAnonymous: open, publicLink: `/forms/${SLUG}` }); +const body = (open: boolean | null) => ({ + type: 'simple', + sections: [{ fields: ['name', 'email'] }], + ...(open === null ? {} : { sharing: sharing(open) }), +}); +/** The major-19 shape: a `form` item, bound with `object`. */ +const formItem = (open: boolean | null, extra: Record = {}) => ({ + name: NAME, object: OBJECT, label: 'Contact us', ...body(open), ...extra, +}); +/** A stored old-shape item row: `viewKind: 'form'`, the body under `config`. */ +const oldShapeItem = (open: boolean | null, extra: Record = {}) => ({ + name: NAME, object: OBJECT, viewKind: 'form', label: 'Contact us', + config: { ...body(open), data: { provider: 'object', object: OBJECT } }, + ...extra, +}); +/** A stored old-shape container row: the form under `formViews.contact`, served as {@link NAME}. */ +const oldShapeContainer = (open: boolean | null) => ({ + name: OBJECT, object: OBJECT, + formViews: { contact: { ...body(open), data: { provider: 'object', object: OBJECT } } }, +}); +const listConfig = { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } }; +/** A stored list item of the form's name. */ +const LIST = { name: NAME, object: OBJECT, viewKind: 'list', label: 'A list', config: listConfig }; +/** A stored package-less container whose bare `list` expands to `OBJECT.CONTAINER`: a list at the form's name. */ +const LIST_CONTAINER = { name: 'contact', object: OBJECT, list: listConfig }; + +const INQUIRY = { + name: OBJECT, + label: 'Inquiry', + fields: { + name: { name: 'name', type: 'text' as const, label: 'Name' }, + email: { name: 'email', type: 'text' as const, label: 'Email' }, + }, +}; + +function mockServer() { + const noop = () => {}; + return { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; +} + +function makeRes() { + const res: any = { + header: () => res, + setHeader: () => res, + send: (b: unknown) => { res._json = b; return res; }, + write: () => true, + end: () => res, + status: (code: number) => { res._status = code; return res; }, + json: (b: unknown) => { res._json = b; return res; }, + }; + return res; +} + +interface Answer { status: number; body: any } + +const engines: ObjectQL[] = []; + +/** A deployment whose read-only package {@link BASE} ships the form OPEN, as a `form` item. */ +async function boot(ships: { forms?: unknown[] } = { forms: [formItem(true)] }) { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any); + const engine = new ObjectQL(); + engines.push(engine); + engine.registerDriver(driver, true); + await engine.init(); + for (const o of [SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) { + engine.registry.registerObject(o as any, 'test-package'); + } + engine.registerApp({ + id: BASE, name: 'forms19', version: '1.0.0', namespace: 'fkr', objects: [INQUIRY], + ...(ships.forms ? { forms: ships.forms } : {}), + } as any); + await engine.syncSchemas(); + const protocol: any = new ObjectStackProtocolImplementation(engine as any, () => new Map()); + const rest = new RestServer(mockServer() as any, protocol, { api: { requireAuth: false } } as any); + rest.registerRoutes(); + const route = (method: string, path: string) => rest.getRoutes().find((r: any) => r.method === method && r.path === path)!; + const resolve = route('GET', '/api/v1/forms/:slug'); + const submit = route('POST', '/api/v1/forms/:slug/submit'); + const get = async (): Promise => { + const res = makeRes(); + await resolve.handler({ params: { slug: SLUG }, query: {}, headers: {} } as any, res); + return { status: res._status ?? 200, body: res._json }; + }; + const post = async (): Promise => { + const res = makeRes(); + await submit.handler({ params: { slug: SLUG }, body: { name: 'Ada', email: 'ada@example.test' }, headers: {} } as any, res); + return { status: res._status ?? 200, body: res._json }; + }; + const records = async () => ((await engine.find(OBJECT, {}, { context: { isSystem: true } })) as unknown[]).length; + const install = async (id: string) => protocol.installPackage({ + manifest: { id, name: id.split('.').join('-'), version: '0.1.0', type: 'app', namespace: id === PAIR ? 'fkr_custom' : 'fkr_acme', dependencies: { [BASE]: '^1' } }, + }); + /** A stored row as it exists at rest, written past every door. */ + const seedRow = async (type: string, name: string, packageId: string | null, item: Record) => { + const now = new Date().toISOString(); + await engine.insert('sys_metadata', { + id: `seed_${type}_${name}_${packageId ?? 'unbound'}`, type, name, + package_id: packageId, state: 'active', metadata: JSON.stringify(item), checksum: hashSpec(item, type), + version: 1, created_at: now, updated_at: now, + }, { context: { isSystem: true } }); + }; + /** The forms of {@link NAME} the effective `form` list serves: `[package, open]` each. */ + const servedForms = async () => ((await protocol.getMetaItems({ type: 'form' })).items as any[]) + .filter((f) => f?.name === NAME) + .map((f) => [f._packageId ?? null, f.sharing?.allowAnonymous ?? null]); + /** Every stored row, as the store holds it. */ + const rows = async () => JSON.stringify(((await engine.find('sys_metadata', {}, { context: { isSystem: true } })) as any[]) + .map((r) => [r.type, r.name, r.package_id ?? null, r.state, typeof r.metadata === 'string' ? r.metadata : JSON.stringify(r.metadata), r.checksum]) + .sort((a, c) => JSON.stringify(a).localeCompare(JSON.stringify(c)))); + return { engine, protocol, get, post, records, install, seedRow, servedForms, rows }; +} + +type Booted = Awaited>; + +/** Both doors' answers — status and `code` — and the record count the pair left behind. */ +async function doors(b: Booted) { + const before = await b.records(); + const get = await b.get(); + const post = await b.post(); + const wrote = (await b.records()) - before; + return { get: [get.status, get.body?.code ?? null], post: [post.status, post.body?.code ?? null], wrote }; +} + +const CLOSED = { get: [404, 'FORM_NOT_FOUND'], post: [404, 'FORM_NOT_FOUND'], wrote: 0 }; +/** + * The package's form as it answers with no stored row over it: served, and the + * submit reaches the object's own rules. This harness composes no tenancy + * service, so the insert is refused for its `organization_id`; a closed + * address answers 404 before any of that is read. + */ +const OPEN = { get: [200, null], post: [400, 'VALIDATION_FAILED'], wrote: 0 }; + +/** The binding a stored row is seeded in, and the package it needs installed first. */ +const BINDINGS = [ + { binding: 'the package\'s declared override', packageId: PAIR, extra: overrides }, + { binding: 'the read-only package itself', packageId: BASE, extra: {} }, + { binding: 'no package', packageId: null, extra: {} }, +] as const; + +describe('#37112 a stored old-shape row on a major-19 build, at a package\'s open `form` item', () => { + const savedWritable = process.env.OS_METADATA_WRITABLE; + beforeAll(() => { delete process.env.OS_METADATA_WRITABLE; }); + beforeEach(() => { + ObjectStackProtocolImplementation.resetEnvWritableCache(); + resetEnvWritableMetadataTypes(); + }); + afterAll(async () => { + if (savedWritable === undefined) delete process.env.OS_METADATA_WRITABLE; + else process.env.OS_METADATA_WRITABLE = savedWritable; + ObjectStackProtocolImplementation.resetEnvWritableCache(); + resetEnvWritableMetadataTypes(); + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + + it('the premise: with no stored row over it, the package\'s `form` item is served and its submit reaches the object', async () => { + const b = await boot(); + expect(await b.servedForms()).toEqual([[BASE, true]]); + expect(await doors(b)).toEqual(OPEN); + }); + + describe('a stored old-shape body that switches the form off answers 404 at its link', () => { + it('an item row of the name in a dependent package: the `form` list still serves the package\'s open item, and both doors answer 404', async () => { + const b = await boot(); + await b.install(DEPENDENT); + await b.seedRow('view', NAME, DEPENDENT, oldShapeItem(false)); + const stored = await b.rows(); + // The effective `form` list serves the package's open item alone: the + // stored body is the only thing that closes the address. + expect(await b.servedForms()).toEqual([[BASE, true]]); + expect(await doors(b)).toEqual(CLOSED); + // A read rewrites nothing. + expect(await b.rows()).toBe(stored); + }); + + it('an item row beside an open stored `form` row of the name, both in the package\'s declared override: the `form` row is served, and both doors answer 404', async () => { + const b = await boot(); + await b.install(PAIR); + await b.seedRow('form', NAME, PAIR, formItem(true, overrides)); + expect(await doors(b)).toEqual(OPEN); + await b.seedRow('view', NAME, PAIR, oldShapeItem(false, overrides)); + const stored = await b.rows(); + // The stored `form` row is the served row of the address, open: the + // stored old-shape body is the only thing that closes it. + expect((await b.servedForms()).map(([, open]) => open)).toEqual([true]); + expect(await doors(b)).toEqual(CLOSED); + expect(await b.rows()).toBe(stored); + }); + + it('an item row beside an open stored `form` row of the name, both in no package: the `form` row is served, and both doors answer 404', async () => { + const b = await boot({}); + await b.seedRow('form', NAME, null, formItem(true)); + expect(await doors(b)).toEqual(OPEN); + await b.seedRow('view', NAME, null, oldShapeItem(false)); + expect(await b.servedForms()).toEqual([[null, true]]); + expect(await doors(b)).toEqual(CLOSED); + }); + + it('a container row bound to the package whose `formViews` entry of the name is switched off: both doors answer 404', async () => { + const b = await boot(); + expect(await doors(b)).toEqual(OPEN); + await b.seedRow('view', OBJECT, BASE, oldShapeContainer(false)); + const stored = await b.rows(); + expect(await doors(b)).toEqual(CLOSED); + expect(await b.rows()).toBe(stored); + }); + + it.each(BINDINGS)('an item row of the name in $binding: both doors answer 404', async ({ packageId, extra }) => { + const b = await boot(); + if (packageId === PAIR) await b.install(PAIR); + await b.seedRow('view', NAME, packageId, oldShapeItem(false, extra)); + expect(await doors(b)).toEqual(CLOSED); + }); + }); + + describe('a stored old-shape row of the name whose form names no link answers 404 at the package\'s link', () => { + it.each(BINDINGS)('in $binding: nothing of the name is served, and both doors answer 404', async ({ packageId, extra }) => { + const b = await boot(); + if (packageId === PAIR) await b.install(PAIR); + expect(await doors(b)).toEqual(OPEN); + await b.seedRow('view', NAME, packageId, oldShapeItem(null, extra)); + const stored = await b.rows(); + expect(await b.servedForms()).toEqual([]); + expect(await doors(b)).toEqual(CLOSED); + expect(await b.rows()).toBe(stored); + }); + }); + + describe('a stored row of the name that carries no form answers 404 at the package\'s link', () => { + it.each(BINDINGS)('a list item in $binding: nothing of the name is served, and both doors answer 404', async ({ packageId, extra }) => { + const b = await boot(); + if (packageId === PAIR) await b.install(PAIR); + expect(await doors(b)).toEqual(OPEN); + await b.seedRow('view', NAME, packageId, { ...LIST, ...extra }); + expect(await b.servedForms()).toEqual([]); + expect(await doors(b)).toEqual(CLOSED); + }); + + it('a package-less container whose expansion writes a list at the name: both doors answer 404', async () => { + const b = await boot(); + expect(await doors(b)).toEqual(OPEN); + await b.seedRow('view', LIST_CONTAINER.name, null, LIST_CONTAINER); + expect(await b.servedForms()).toEqual([]); + expect(await doors(b)).toEqual(CLOSED); + }); + }); + + describe('the served `view` reads hold lists only, and the stored row stays as stored', () => { + it('a stored old-shape item row is in no `view` list and answers no item by name; a stored list of another name is served by both', async () => { + const OTHER = `${OBJECT}.all`; + const b = await boot(); + await b.seedRow('view', NAME, null, oldShapeItem(false)); + await b.seedRow('view', OTHER, null, { ...LIST, name: OTHER }); + const stored = await b.rows(); + const listed = ((await b.protocol.getMetaItems({ type: 'view' })).items as any[]).map((v) => v?.name); + expect(listed).toContain(OTHER); + expect(listed).not.toContain(NAME); + expect((await b.protocol.getMetaItem({ type: 'view', name: OTHER })).item?.name).toBe(OTHER); + expect((await b.protocol.getMetaItem({ type: 'view', name: NAME })).item).toBeUndefined(); + // …and the row is still there, byte-equal, and still closes the form. + expect(await b.rows()).toBe(stored); + expect(await doors(b)).toEqual(CLOSED); + }); + }); +}); + +describe('#37112 the save door refuses the three old shapes with their prescription', () => { + afterAll(async () => { + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + + const refusal = async (item: Record, name: string) => { + const b = await boot(); + await b.install(DEPENDENT); + const stored = await b.rows(); + const err: any = await b.protocol.saveMetaItem({ type: 'view', name, item, mode: 'draft', packageId: DEPENDENT }).then( + () => undefined, + (e: unknown) => e, + ); + return { + code: err?.code, + status: err?.status, + paths: ((err?.issues ?? []) as any[]).map((i) => (Array.isArray(i.path) ? i.path.join('.') : String(i.path ?? ''))), + messages: ((err?.issues ?? []) as any[]).map((i) => String(i.message)), + wrote: (await b.rows()) !== stored, + }; + }; + + it('`view.form`: 422 INVALID_METADATA located at `form`, and no row is written', async () => { + const r = await refusal({ name: OBJECT, object: OBJECT, list: listConfig, form: { ...body(true), data: { provider: 'object', object: OBJECT } } }, OBJECT); + expect([r.code, r.status, r.wrote]).toEqual(['INVALID_METADATA', 422, false]); + expect(r.paths).toContain('form'); + expect(r.messages.find((m) => m.startsWith('`view.form` was removed in @objectstack/spec 19.0.0'))).toBeDefined(); + }); + + it('`view.formViews`: 422 INVALID_METADATA located at `formViews`, and no row is written', async () => { + const r = await refusal({ ...oldShapeContainer(true), list: listConfig }, OBJECT); + expect([r.code, r.status, r.wrote]).toEqual(['INVALID_METADATA', 422, false]); + expect(r.paths).toContain('formViews'); + expect(r.messages.find((m) => m.startsWith('`view.formViews` was removed in @objectstack/spec 19.0.0'))).toBeDefined(); + }); + + it('`viewKind: \'form\'`: 422 INVALID_METADATA located at `viewKind`, and no row is written', async () => { + const r = await refusal(oldShapeItem(true), NAME); + expect([r.code, r.status, r.wrote]).toEqual(['INVALID_METADATA', 422, false]); + expect(r.paths).toContain('viewKind'); + expect(r.messages.find((m) => m.startsWith("`view.viewKind: 'form'` was removed in @objectstack/spec 19.0.0"))).toBeDefined(); + }); +}); diff --git a/packages/rest/src/stored-forms-switch-37112.test.ts b/packages/rest/src/stored-forms-switch-37112.test.ts index 5775f4f3122..108e1295078 100644 --- a/packages/rest/src/stored-forms-switch-37112.test.ts +++ b/packages/rest/src/stored-forms-switch-37112.test.ts @@ -222,7 +222,7 @@ describe('#37112 the protocol-19 switch through both doors', () => { // Ablation: count an unreadable body as nothing to move → the switch is // recorded over a row whose links are closed only by its unreadability. it('a stored body the projection cannot read', async () => { - const b = await boot({ views: [container(true)] }); + const b = await boot({ forms: [formItem(true)] }); await b.seedRow('view', NAME, BASE, { name: NAME, object: OBJECT, viewKind: 'form', config: 'not-a-form', sharing: sharing(false) }); const rows = await allRows(b); const before = await doors(b); @@ -240,7 +240,7 @@ describe('#37112 the protocol-19 switch through both doors', () => { describe('a kind the rulings do not count does not stop the switch', () => { // Ablation: count a draft as a hold → the switch is refused. it('an old-shape draft row: neither moved nor deleted, and the switch is recorded', async () => { - const b = await boot({ views: [container(true)] }); + const b = await boot({ forms: [formItem(true)] }); await b.seedRow('view', NAME, BASE, viewItem(false), 'draft'); const before = await doors(b); expect(before.get[0]).toBe(200); @@ -255,8 +255,8 @@ describe('#37112 the protocol-19 switch through both doors', () => { describe('a deployment that can switch is switched, and both doors answer as before', () => { // Ablation: skip the ceremony and record the switch → the re-run census // still plans the move, and the verdict is false. - it('⛔ a stored withdrawal over a base\'s open old-shape form moves, and the form stays closed', async () => { - const b = await boot({ views: [container(true)] }); + it('⛔ a stored withdrawal over a base\'s open form moves, and the form stays closed', async () => { + const b = await boot({ forms: [formItem(true)] }); await b.seedRow('view', NAME, BASE, viewItem(false)); const before = await doors(b); // The "before" reading: the stored switch-off closes the base's form. @@ -270,7 +270,7 @@ describe('#37112 the protocol-19 switch through both doors', () => { }); it('an internal record form is removed, and nothing a door answers changes', async () => { - const b = await boot({ views: [container(true)] }); + const b = await boot({ forms: [formItem(true)] }); await b.seedRow('view', DFORM, BASE, { name: DFORM, object: OBJECT, viewKind: 'form', isDefault: true, config: { ...body(null), data: { provider: 'object', object: OBJECT } } }); const before = await doors(b); expect(before.get[0]).toBe(200); @@ -282,7 +282,7 @@ describe('#37112 the protocol-19 switch through both doors', () => { }); it('a second run finds nothing to move: the switch is idempotent', async () => { - const b = await boot({ views: [container(true)] }); + const b = await boot({ forms: [formItem(true)] }); await b.seedRow('view', NAME, BASE, viewItem(false)); expect((await runSwitch(b)).switched).toBe(true); const rows = await allRows(b); @@ -292,4 +292,27 @@ describe('#37112 the protocol-19 switch through both doors', () => { expect(await allRows(b)).toBe(rows); }); }); + + // [ADR-0159 D6 rules 10 and 11, D7] A stored old-shape container is a stored + // old-shape row like any other: its form members are read wherever a stored + // form is read, before the switch and after it. + describe('a stored container\'s form members are read as stored forms', () => { + it('⛔ a switched-off form member of a stored container keeps the base\'s open `form` item closed on both doors', async () => { + const b = await boot({ forms: [formItem(true)] }); + expect((await doors(b)).get[0]).toBe(200); + await b.seedRow('view', OBJECT, BASE, { name: OBJECT, ...container(false) }); + expect(await doors(b)).toEqual(CLOSED); + }); + + it('the census counts an open form member of a package-less stored container, and the switch moves it', async () => { + const MEMBER = `${OBJECT}.intake.contact`; + const b = await boot({}); + await b.seedRow('view', 'intake', null, { name: 'intake', ...container(true) }); + const run = await runSwitch(b); + expect(run.before.forms.filter((f) => f.form === MEMBER).map((f) => f.outcome)).toEqual(['move']); + expect(run.before.precheck.counts.move).toBe(1); + expect(run.switched).toBe(true); + expect(run.after?.forms.filter((f) => f.form === MEMBER).map((f) => f.outcome)).toEqual(['keep']); + }); + }); }); diff --git a/packages/runtime/src/app-plugin.ts b/packages/runtime/src/app-plugin.ts index cbd94e44fb0..fd861a3b8f3 100644 --- a/packages/runtime/src/app-plugin.ts +++ b/packages/runtime/src/app-plugin.ts @@ -193,6 +193,11 @@ export class AppPlugin implements Plugin { * plugin's `start()`, which loads the inline seed, runs only after the guard * has judged. Order-if-present: every other kernel is unchanged. * + * The protocol-19 boot guard (ADR-0159 D7; the guard module's + * `FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME`, a literal for the same + * reason): it judges after the ownership guard, and the inline seed loads + * only once both have judged. Order-if-present. + * * The host's package-state store (`PACKAGE_STATE_STORE_PLUGIN_NAME`, * `./package-state-host-store.ts`, spelled as a literal for the same * reason): `init()` seeds the registry's disabled set from it, so it must @@ -202,6 +207,7 @@ export class AppPlugin implements Plugin { optionalDependencies = [ 'com.objectstack.engine.objectql', 'com.objectstack.organization-ownership-boot-guard', + 'com.objectstack.form-type-switch-boot-guard', 'com.objectstack.auth', 'com.objectstack.auth.identity-objects', 'com.objectstack.package-state-store', diff --git a/packages/runtime/src/form-type-switch-boot-guard.kernel.test.ts b/packages/runtime/src/form-type-switch-boot-guard.kernel.test.ts new file mode 100644 index 00000000000..2bffcd6d53e --- /dev/null +++ b/packages/runtime/src/form-type-switch-boot-guard.kernel.test.ts @@ -0,0 +1,414 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0159 D7; ruling records 7303149461 and 7308112533] The protocol-19 boot + * refusal and its birth half on a REAL kernel: the guard's throw must stop + * `bootstrap()`, and "created from empty" must be the driver's own + * observation, which no hand-called plugin can show. + * + * The composition is `os serve`'s data spine: a driver, ObjectQL, the platform + * objects, plus the guard. Each case prepares the store before the boot, the + * way an earlier release or the switch command left it: + * + * 1. a database an earlier release created (its tables there, no switch + * record) is refused, naming the command, and the kernel never runs; + * 2. the same database with the switch recorded boots; + * 3. a database created from empty boots, the guard writing the birth marker + * (`details.birth`), and boots again on that marker; + * 4. a store with any table already there is not born here: refused; + * 5. a record that is not verified is refused; + * 6. a refused boot loads no seed: `AppPlugin`, `use()`d ahead of the guard + * (the hostile slot), starts only after it judged; + * 7. the birth half alone (what every CLI data and schema boot composes) + * writes the marker on a store it created and never refuses; + * 8. beside the organization-ownership guard: a database that owes both acts + * hears of the older one first, and a fresh store carries both markers; + * 9. the guard is not SQL-only: an in-memory store born here boots, one + * restored with rows is refused; + * 10. a composition that stores metadata and registers no ledger is refused; + * 11. a plugin that takes the guard's name replaces it on the kernel, which is + * why the host refuses that composition before it starts. + */ + +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { DatabaseSync } from 'node:sqlite'; +import { afterEach, describe, expect, it } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { InMemoryDriver } from '@objectstack/driver-memory'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ObjectQLPlugin } from '@objectstack/objectql'; +import { PlatformObjectsPlugin } from '@objectstack/platform-objects/plugin'; +import { FORM_TYPE_SWITCH_MIGRATION_ID } from '@objectstack/spec/system'; +import { createIdentityObjectsPlugin } from '@objectstack/plugin-auth'; +// The real plugin chain loads `@objectstack/metadata` lazily (AppPlugin); paid +// here, at collection, so no case's clocked window pays the first load. +import '@objectstack/metadata'; +import { AppPlugin } from './app-plugin.js'; +import { DriverPlugin } from './driver-plugin.js'; +import { + assertFormTypeSwitchGuardNotReplaced, + FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME, + FORM_TYPE_SWITCH_BOOT_REFUSAL_CODE, + FORM_TYPE_SWITCH_BOOT_REFUSAL_NAME, + FORM_TYPE_SWITCH_PROTOCOL_MAJOR, + FormTypeSwitchBirthMarkerPlugin, + FormTypeSwitchBootGuardPlugin, + formTypeSwitchRefusalMessage, + isFormTypeSwitchBootRefusal, + type FormTypeSwitchBootRefusal, +} from './form-type-switch-boot-guard.js'; +import { + isOrganizationOwnershipBootRefusal, + OrganizationOwnershipBootGuardPlugin, +} from './organization-ownership-boot-guard.js'; + +const dirs: string[] = []; +const kernels: ObjectKernel[] = []; +const MARKER = FORM_TYPE_SWITCH_MIGRATION_ID; +const COMMAND = `os migrate protocol --to ${FORM_TYPE_SWITCH_PROTOCOL_MAJOR}`; + +/** + * The refusal a failed boot carries. The guard refuses from its `start()`, and + * the kernel reports a failed `start()` as its own error with the plugin's as + * the `cause`: the shape a host that composes the guard reads. + */ +function refusalIn(error: unknown): FormTypeSwitchBootRefusal | undefined { + for (let e = error, depth = 0; !!e && typeof e === 'object' && depth < 8; e = (e as { cause?: unknown }).cause, depth++) { + if (isFormTypeSwitchBootRefusal(e)) return e; + } + return undefined; +} + +function databaseFile(): string { + const dir = mkdtempSync(join(tmpdir(), 'os-form-switch-guard-')); + dirs.push(dir); + return join(dir, 'data.db'); +} + +function sql>(file: string, statement: string): T[] { + const db = new DatabaseSync(file); + try { + return db.prepare(statement).all() as T[]; + } finally { + db.close(); + } +} + +interface MarkerRow { verified_at: string | null; applied_at: string | null; blocking: number; details: string | null } +const markerRows = (file: string): MarkerRow[] => + sql(file, `SELECT verified_at, applied_at, blocking, details FROM sys_migration WHERE id = '${MARKER}'`); + +/** The switch's record as `os migrate protocol --to 19 --apply` writes it; `verifiedAt: null` is a run that did not verify. */ +function recordSwitch(file: string, verifiedAt: string | null): void { + const db = new DatabaseSync(file); + try { + db.prepare('INSERT INTO sys_migration (id, last_run_at, verified_at, applied_at, blocking, details) VALUES (?, ?, ?, ?, ?, ?)') + .run(MARKER, '2026-12-01T00:00:00.000Z', verifiedAt, '2026-12-01T00:00:00.000Z', 0, JSON.stringify({ protocol: 19 })); + } finally { + db.close(); + } +} + +/** An app whose inline seed writes two rows. */ +const seededApp = () => new AppPlugin({ + id: 'com.test.switch_seed', + name: 'switch_seed', + version: '1.0.0', + type: 'app', + objects: [{ name: 'switch_event', label: 'Event', fields: { subject: { name: 'subject', type: 'text', label: 'Subject' } } }], + data: [{ object: 'switch_event', mode: 'upsert', externalId: 'subject', records: [{ subject: 'one' }, { subject: 'two' }] }], +}); + +interface BootOptions { + /** What judges the store: `os serve`'s guard, the CLI boots' birth half, or nothing (an earlier release). */ + guard?: 'serve' | 'birth' | 'none'; + /** + * The seeding app and the identity objects its seed rows are stamped with, + * `use()`d first, so only the app's declared ordering holds its seed back. + */ + seed?: boolean; + /** The organization-ownership guard too, `use()`d after this one, so only the declared ordering judges it first. */ + ownership?: boolean; + /** Leave the platform objects out: a composition with no `sys_migration` ledger. */ + noLedger?: boolean; + /** Plugins `use()`d last, as a stack's own `plugins` are. */ + late?: unknown[]; + driver?: unknown; +} + +async function boot(file: string | null, opts: BootOptions = {}): Promise<{ kernel: ObjectKernel; error: unknown }> { + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); + kernels.push(kernel); + if (opts.seed) { + await kernel.use(seededApp()); + await kernel.use(createIdentityObjectsPlugin() as never); + } + await kernel.use(new DriverPlugin((opts.driver ?? new SqlDriver({ + client: 'better-sqlite3', + connection: { filename: file as string }, + useNullAsDefault: true, + })) as never)); + await kernel.use(new ObjectQLPlugin()); + const guard = opts.guard ?? 'serve'; + if (guard === 'serve') await kernel.use(new FormTypeSwitchBootGuardPlugin()); + if (guard === 'birth') await kernel.use(new FormTypeSwitchBirthMarkerPlugin()); + if (opts.ownership) await kernel.use(new OrganizationOwnershipBootGuardPlugin()); + if (!opts.noLedger) await kernel.use(new PlatformObjectsPlugin() as never); + for (const plugin of opts.late ?? []) await kernel.use(plugin as never); + try { + await kernel.bootstrap(); + return { kernel, error: null }; + } catch (error) { + return { kernel, error }; + } +} + +/** + * A database an earlier release created: this composition booted over it with + * no guard and no birth half, so every table is there and no switch record is. + */ +async function earlierReleaseDatabase(): Promise { + const file = databaseFile(); + const { kernel, error } = await boot(file, { guard: 'none' }); + expect(error).toBeNull(); + await kernel.shutdown(); + expect(markerRows(file)).toEqual([]); + return file; +} + +afterEach(async () => { + for (const kernel of kernels.splice(0)) { + if (kernel.getState() === 'running') await kernel.shutdown(); + } + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +describe('the protocol-19 boot refusal on a real kernel (ADR-0159 D7)', () => { + it('a database an earlier release created stops the boot with the refusal, naming the command, before the kernel runs', async () => { + const file = await earlierReleaseDatabase(); + const { kernel, error } = await boot(file); + const refusal = refusalIn(error); + expect(refusal?.name, String(error)).toBe(FORM_TYPE_SWITCH_BOOT_REFUSAL_NAME); + // The registered machine code, by value: what a host discriminates the refusal by. + expect(refusal?.code).toBe('FORM_TYPE_SWITCH_REQUIRED'); + expect(FORM_TYPE_SWITCH_BOOT_REFUSAL_CODE).toBe('FORM_TYPE_SWITCH_REQUIRED'); + expect(refusal?.reason).toBe('absent'); + expect(refusal?.message).toContain(`'${COMMAND}'`); + expect(refusal?.message).toContain(`'${COMMAND} --apply --yes'`); + // Refused in `start()`: the kernel's start-failure error carries it as its cause. + expect((error as Error).cause).toBe(refusal); + expect(kernel.getState()).not.toBe('running'); + // A refusal records nothing: the store is still one the command has not run on. + expect(markerRows(file)).toEqual([]); + }); + + it('the same database, its switch recorded and verified, boots', async () => { + const file = await earlierReleaseDatabase(); + recordSwitch(file, '2026-12-01T00:00:01.000Z'); + const { kernel, error } = await boot(file); + expect(error).toBeNull(); + expect(kernel.getState()).toBe('running'); + }); + + it('a record that is not verified is refused', async () => { + const file = await earlierReleaseDatabase(); + recordSwitch(file, null); + const { kernel, error } = await boot(file); + expect(refusalIn(error)?.reason, String(error)).toBe('unverified'); + expect(kernel.getState()).not.toBe('running'); + }); + + it('a database created from empty boots, the guard writing the birth marker; the next boot reads it and boots', async () => { + const file = databaseFile(); + const { kernel, error } = await boot(file); + expect(error).toBeNull(); + expect(kernel.getState()).toBe('running'); + const [row, ...rest] = markerRows(file); + expect(rest).toEqual([]); + expect(row?.verified_at).toBeTruthy(); + expect(row?.applied_at).toBeNull(); + expect(Number(row?.blocking)).toBe(0); + const details = JSON.parse(String(row!.details)) as { birth?: Record }; + expect(details.birth).toMatchObject({ protocol: FORM_TYPE_SWITCH_PROTOCOL_MAJOR, createdAt: row!.verified_at }); + expect(typeof details.birth?.platformVersion).toBe('string'); + await kernel.shutdown(); + // The same store, found this time: the marker carries it, and is not written again. + expect((await boot(file)).error).toBeNull(); + expect(markerRows(file)).toEqual([row]); + }); + + it('a store with one table already there was not created from empty: refused, and no birth marker is written', async () => { + const file = databaseFile(); + const db = new DatabaseSync(file); + // Any table of the composition that an earlier boot left: here the journal's. + db.exec('CREATE TABLE sys_migration_journal (id TEXT PRIMARY KEY)'); + db.close(); + const { kernel, error } = await boot(file); + expect(refusalIn(error)?.reason, String(error)).toBe('absent'); + expect(kernel.getState()).not.toBe('running'); + expect(markerRows(file)).toEqual([]); + }); +}); + +describe('a refused boot loads no seed (the guard judges before AppPlugin starts)', () => { + it('AppPlugin, use()d ahead of the guard: its own declaration holds the inline seed back', async () => { + const file = await earlierReleaseDatabase(); + const { kernel, error } = await boot(file, { seed: true }); + expect(refusalIn(error)?.reason, String(error)).toBe('absent'); + expect(kernel.getState()).not.toBe('running'); + // The engine's schema sync ran before the refusal; the seed did not. + expect(sql(file, 'SELECT id FROM switch_event')).toEqual([]); + }); + + it('control: the same composition over a fresh file loads the seed', async () => { + const file = databaseFile(); + const { kernel, error } = await boot(file, { seed: true }); + expect(error).toBeNull(); + expect(kernel.getState()).toBe('running'); + expect(sql<{ subject: string }>(file, 'SELECT subject FROM switch_event ORDER BY subject').map((r) => r.subject)).toEqual(['one', 'two']); + }); + + it('AppPlugin names the guard in its optionalDependencies, by the guard\'s own name', () => { + expect(new FormTypeSwitchBootGuardPlugin().name).toBe(FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME); + expect(new AppPlugin({}).optionalDependencies).toContain(FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME); + }); +}); + +describe('the birth half alone, as every CLI data and schema boot composes it', () => { + it('writes the birth marker on a store this boot created from empty', async () => { + const file = databaseFile(); + const { kernel, error } = await boot(file, { guard: 'birth' }); + expect(error).toBeNull(); + expect(kernel.getState()).toBe('running'); + const [row] = markerRows(file); + expect(row?.verified_at).toBeTruthy(); + expect(JSON.parse(String(row!.details)).birth).toMatchObject({ protocol: FORM_TYPE_SWITCH_PROTOCOL_MAJOR }); + await kernel.shutdown(); + // The served boot that follows a CLI-created store reads that marker. + expect((await boot(file)).error).toBeNull(); + }); + + it('never refuses and never marks a store it found: an earlier release\'s database boots and stays unrecorded', async () => { + const file = await earlierReleaseDatabase(); + const { kernel, error } = await boot(file, { guard: 'birth' }); + expect(error).toBeNull(); + expect(kernel.getState()).toBe('running'); + expect(markerRows(file)).toEqual([]); + }); +}); + +describe('beside the organization-ownership guard, as os serve composes both', () => { + it('a fresh store carries both birth markers and boots', async () => { + const file = databaseFile(); + const { kernel, error } = await boot(file, { ownership: true }); + expect(error).toBeNull(); + expect(kernel.getState()).toBe('running'); + expect(sql<{ id: string }>(file, 'SELECT id FROM sys_migration ORDER BY id').map((r) => r.id)) + .toEqual(expect.arrayContaining(['adr-0131-organization-ownership', MARKER])); + }); + + it('a database that owes both acts hears of the older one first', async () => { + const file = await earlierReleaseDatabase(); + const { error } = await boot(file, { ownership: true }); + expect(refusalIn(error)).toBeUndefined(); + expect(isOrganizationOwnershipBootRefusal((error as Error).cause), String(error)).toBe(true); + }); +}); + +describe('not limited to SQL stores: a stored form is a sys_metadata row on whatever driver persists it', () => { + it('an in-memory store born at this boot boots, its birth marker written', async () => { + const { kernel, error } = await boot(null, { driver: new InMemoryDriver() }); + expect(error).toBeNull(); + expect(kernel.getState()).toBe('running'); + const engine = kernel.getService<{ findOne: (o: string, q: unknown) => Promise<{ verified_at?: unknown; details?: unknown } | null> }>('objectql'); + const row = await engine.findOne('sys_migration', { where: { id: MARKER }, context: { isSystem: true } }); + expect(row?.verified_at).toBeTruthy(); + }); + + it('an in-memory store restored with rows was not created here: refused', async () => { + const driver = new InMemoryDriver({ initialData: { sys_migration_journal: [{ id: 'j1' }] } }); + const { kernel, error } = await boot(null, { driver }); + expect(refusalIn(error)?.reason, String(error)).toBe('absent'); + expect(kernel.getState()).not.toBe('running'); + }); +}); + +describe('what the guard can and cannot judge', () => { + it('a composition that stores metadata and registers no ledger has no switch record to read: refused', async () => { + const file = databaseFile(); + const { kernel, error } = await boot(file, { noLedger: true }); + expect(refusalIn(error)?.reason, String(error)).toBe('no-ledger'); + expect(kernel.getState()).not.toBe('running'); + }); + + it('a kernel with no engine has no database to judge: the guard and the birth half do nothing', async () => { + const noEngine = { getService: () => { throw new Error('service objectql is not registered'); } } as never; + await expect(new FormTypeSwitchBootGuardPlugin().start(noEngine)).resolves.toBeUndefined(); + await expect(new FormTypeSwitchBirthMarkerPlugin().start(noEngine)).resolves.toBeUndefined(); + }); +}); + +describe('the guard is the host\'s own: no plugin replaces it', () => { + /** A stack plugin that carries the guard's name and judges nothing. */ + const impostor = () => ({ name: FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME, version: '9.9.9', init: async () => {}, start: async () => {} }); + + it('control: on the kernel, a later plugin under the guard\'s name replaces it, and an unswitched database boots', async () => { + const file = await earlierReleaseDatabase(); + const { kernel, error } = await boot(file, { late: [impostor()] }); + expect(error).toBeNull(); + expect(kernel.getState()).toBe('running'); + }); + + it('so the host refuses a composition that carries the name on another plugin, before it starts', () => { + const guard = new FormTypeSwitchBootGuardPlugin(); + const refused = (() => { + try { + assertFormTypeSwitchGuardNotReplaced(guard, [{ name: 'com.example.other' }, impostor()]); + return undefined; + } catch (error) { + return error; + } + })(); + expect(isFormTypeSwitchBootRefusal(refused)).toBe(true); + expect((refused as FormTypeSwitchBootRefusal).reason).toBe('guard-replaced'); + }); + + it('the guard itself, and plugins under other names, pass', () => { + const guard = new FormTypeSwitchBootGuardPlugin(); + expect(() => assertFormTypeSwitchGuardNotReplaced(guard, [guard, { name: 'com.example.other' }, null, 'a-specifier'])).not.toThrow(); + }); +}); + +describe('the refusal names the command as the refused boot was started', () => { + it('a development boot names it with --dev, a preset boot with its preset', () => { + expect(formTypeSwitchRefusalMessage('absent', { dev: true })).toContain(`'${COMMAND} --dev'`); + expect(formTypeSwitchRefusalMessage('absent', { preset: 'minimal' })).toContain(`'${COMMAND} --preset minimal --apply --yes'`); + }); + + it('a database the command would not find by default is named, so the command switches the database that was refused', () => { + const message = formTypeSwitchRefusalMessage('absent', { databaseUrl: 'file:/srv/app/data.db' }); + expect(message).toContain(`'${COMMAND} --database-url file:/srv/app/data.db'`); + }); + + it('a credential is never printed: the URL, the auth token and the auth secret are read from the shell', () => { + const message = formTypeSwitchRefusalMessage('absent', { + databaseUrl: 'postgres://app:s3cret@db.internal/app', + databaseDriver: 'postgres', + databaseAuthTokenFromFlag: true, + authSecretFile: '/srv/app/home/auth-secret', + }); + expect(message).not.toContain('s3cret'); + expect(message).toContain('--database-url "${OS_DATABASE_URL:?'); + expect(message).toContain('OS_DATABASE_DRIVER=postgres '); + expect(message).toContain('OS_DATABASE_AUTH_TOKEN="${OS_DATABASE_AUTH_TOKEN:?'); + expect(message).toContain('OS_AUTH_SECRET="$(cat /srv/app/home/auth-secret)" '); + }); + + it('every refusing state names the command', () => { + for (const state of ['absent', 'unverified', 'unreadable', 'no-ledger'] as const) { + expect(formTypeSwitchRefusalMessage(state), state).toContain(`'${COMMAND} --apply --yes'`); + } + }); +}); diff --git a/packages/runtime/src/form-type-switch-boot-guard.ts b/packages/runtime/src/form-type-switch-boot-guard.ts new file mode 100644 index 00000000000..0b81c9f0609 --- /dev/null +++ b/packages/runtime/src/form-type-switch-boot-guard.ts @@ -0,0 +1,611 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { Plugin, PluginContext } from '@objectstack/core'; +import { + isDataMigrationFlagVerified, + DATA_MIGRATION_FLAG_OBJECT, + FORM_TYPE_SWITCH_MIGRATION_ID, + type DataMigrationFlag, +} from '@objectstack/spec/system'; +import { resolveRuntimeVersion } from './runtime-version.js'; + +/** + * FormTypeSwitchBootGuardPlugin — the protocol-19 boot refusal (ADR-0159 D7; + * ruling record 7303149461) and its birth half (ruling record 7308112533). + * + * On protocol 19 `view` holds lists only, and a form is a `form` item. A + * database an earlier release left may still store forms in an old shape: a + * view container's form, a `formViews` entry, a `viewKind: 'form'` item. The + * act that moves them, `os migrate protocol --to 19 --apply`, is an + * operator's: it previews, moves all or nothing, checks again, and only then + * records the switch. It is never a boot step. So a served boot refuses to + * start until the switch is recorded, and says which command to run. + * + * ## What is refused + * + * The guard reads the switch's `sys_migration` row + * ({@link FORM_TYPE_SWITCH_MIGRATION_ID}) and decides on one question, the + * spec's own (`isDataMigrationFlagVerified`): is it there and verified. It + * never compares versions and never reads a stored form: counting what is left + * to move is the command's census, not a boot's. + * + * 1. A VERIFIED row boots: the command's record, or the birth marker below. + * 2. No row, on a datastore this boot observed being CREATED FROM EMPTY: the + * guard writes the BIRTH MARKER (verified, `details.birth` = + * {@link FormTypeSwitchBirthMarker}) exactly once and boots. A store with + * no prior data holds no stored form, so no switch is owed. The observation + * is the stores' own schema-sync counts, the one that holds the ledger and + * the one that holds `sys_metadata` (the same store on every composition + * this repository builds), never the sum over every driver. + * 3. No row on any other store, which is every database an earlier release + * created: refused until the command has run on it. A database with no + * stored form runs it once too: it finds nothing to move and records the + * switch, and the refusal says so. + * 4. A row that is not verified, or one that could not be read, is refused. + * 5. A composition that serves `sys_metadata` from a store and registers no + * ledger to read the switch from is refused: where the stored forms are + * and the record is not, there is nothing to boot on. + * + * - A read that fails is refused, never passed: "I could not check" is not + * "the switch is recorded". + * - A birth marker that cannot be written refuses the boot: a store left + * without one would be taken, at its next boot, for a database an earlier + * release created. + * - ⛔ No way round: no `OS_ALLOW_*` / `OS_SKIP_*` variable, no flag and no + * config key skips the check (ruling record 7303149461). + * + * ## When it judges: in `start()` + * + * Ordered after the engine (whose `start()` connects the drivers and runs the + * schema sync the "created from empty" observation is read off), the platform + * objects (`sys_migration`) and the organization-ownership guard, so a + * database that owes both acts is told the older one first. `AppPlugin`, + * whose `start()` loads the inline seed, and `@objectstack/plugin-auth`'s + * `AuthPlugin` and `IdentityObjectsPlugin`, whose `start()` writes identity + * rows, name this guard in their `optionalDependencies` + * ({@link FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME}). A `start()` + * that throws stops the kernel before the next plugin starts; the kernel + * hands the refusal on as the `cause` of its own start-failure error, so a + * host that inspects the boot error asks {@link isFormTypeSwitchBootRefusal} + * of each `cause` down the chain. + * + * ## Where it runs, and where it must not + * + * Composed by `os serve` (and so `os dev` and `os start`) only. ⛔ Never in + * `createStandaloneStack`'s own list: every CLI data and schema boot shares + * that builder, `os migrate protocol`'s own boot among them, and a guard there + * would refuse the one command that clears it. That builder composes the birth + * half alone ({@link FormTypeSwitchBirthMarkerPlugin}), which writes the + * marker on a store it created from empty and never refuses. + * + * Unlike the organization-ownership guard this one is not limited to SQL + * stores: a stored form is a `sys_metadata` row on whatever driver persists + * it. A composition with no engine, or one where no store serves either + * `sys_migration` or `sys_metadata`, has nothing to judge and the guard is + * inert there. + */ + +/** + * The machine code a host discriminates this refusal by, across module + * instances. Registered in `@objectstack/spec`'s error-code ledger under this + * package; the refusal is thrown at boot, before any socket opens, so no + * request ever carries it. + */ +export const FORM_TYPE_SWITCH_BOOT_REFUSAL_CODE = 'FORM_TYPE_SWITCH_REQUIRED' as const; + +/** The `name` every refusal carries: what a log line and a stack trace show. */ +export const FORM_TYPE_SWITCH_BOOT_REFUSAL_NAME = 'FormTypeSwitchBootRefusal' as const; + +/** + * The guard's kernel plugin name: a plugin that writes rows in its `start()` + * names it in `optionalDependencies`, so on a kernel that composes the guard it + * starts only once the guard has judged the database (ADR-0116 ordering). + * Each writer spells the name as a string literal (`check:init-service-contract` + * reads `optionalDependencies` as literals only), and the guard's tests pin the + * declaration against this constant. + */ +export const FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME = 'com.objectstack.form-type-switch-boot-guard' as const; + +/** The birth-marker plugin's kernel name. */ +export const FORM_TYPE_SWITCH_BIRTH_MARKER_PLUGIN_NAME = 'com.objectstack.form-type-switch-birth-marker' as const; + +/** The protocol major whose switch this guard reads, and the one a birth marker names. */ +export const FORM_TYPE_SWITCH_PROTOCOL_MAJOR = 19 as const; + +/** The object whose rows hold every stored form: where an old shape would be. */ +const METADATA_OBJECT = 'sys_metadata'; + +/** + * What the guard writes into `details.birth` of the + * {@link FORM_TYPE_SWITCH_MIGRATION_ID} row on a datastore created from empty. + * Provenance only: the guard decides on the row being verified, never on + * these fields. + */ +export interface FormTypeSwitchBirthMarker { + /** The protocol major the store was born on. */ + protocol: number; + /** The exact platform version that created the store (never compared). */ + platformVersion: string; + /** When the boot observed the store created from empty (ISO 8601). */ + createdAt: string; +} + +/** How the boot that runs the guard was started: what the refusal's command must match. */ +export interface FormTypeSwitchBootGuardOptions { + /** A development boot (`os dev` / `os serve --dev`): the named command carries `--dev`, as the command's own flag asks. */ + dev?: boolean; + /** The tier preset this boot was given (`os serve --preset`): the named command carries it, so it composes the same stack. */ + preset?: string; + /** + * The file this production boot read its auth secret from because the + * operator set none (`os start`'s `/auth-secret`). The command + * composes the deployment as this server does only with that secret, and the + * operator's shell does not hold it, so on a boot that is not a development + * boot the named commands export it from this file. + */ + authSecretFile?: string; + /** + * The database this boot serves, when the command run bare in the + * operator's shell would reach another one (`os start -d`, a `--home` home, + * `os dev -d`). The named commands then carry `--database-url`, so run + * verbatim they switch the database that was refused. A URL that carries a + * credential is not printed: the commands read it from `OS_DATABASE_URL` and + * stop if it is unset. + */ + databaseUrl?: string; + /** The driver `--database-driver` chose for this boot: set in front of the named commands as `OS_DATABASE_DRIVER`. */ + databaseDriver?: string; + /** + * Whether this boot's database auth token came from `--database-auth-token`. + * The value never reaches the guard: the named commands read + * `OS_DATABASE_AUTH_TOKEN` from the operator's shell and stop when it is + * unset, so the token is never printed. + */ + databaseAuthTokenFromFlag?: boolean; +} + +/** What the guard read of the switch's `sys_migration` row, when that reading refuses the boot. */ +export type FormTypeSwitchMarkerState = 'absent' | 'unverified' | 'unreadable' | 'no-ledger'; + +/** + * Why a boot was refused: what the guard read of the marker + * ({@link FormTypeSwitchMarkerState}), `birth-unwritten` when the store was + * created from empty and its birth marker could not be written, or + * `guard-replaced` when another plugin took the guard's name + * ({@link assertFormTypeSwitchGuardNotReplaced}). + */ +export type FormTypeSwitchRefusalReason = FormTypeSwitchMarkerState | 'birth-unwritten' | 'guard-replaced'; + +export class FormTypeSwitchBootRefusal extends Error { + readonly code = FORM_TYPE_SWITCH_BOOT_REFUSAL_CODE; + override readonly name = FORM_TYPE_SWITCH_BOOT_REFUSAL_NAME; + constructor( + message: string, + /** Why the boot was refused. */ + readonly reason: FormTypeSwitchRefusalReason, + ) { + super(message); + } +} + +/** Structural, not `instanceof`: a host may hold two module instances. */ +export function isFormTypeSwitchBootRefusal(error: unknown): error is FormTypeSwitchBootRefusal { + return !!error && typeof error === 'object' && (error as { code?: unknown }).code === FORM_TYPE_SWITCH_BOOT_REFUSAL_CODE; +} + +/** + * What a shell running a printed command without `OS_DATABASE_URL` says, and + * stops at, when the boot's database URL carries a credential. + */ +export const FORM_TYPE_SWITCH_CREDENTIAL_URL_UNSET = + 'export OS_DATABASE_URL as the database URL this server was started with'; + +/** What a shell says, and stops at, when the boot's auth token came from a flag and the variable is unset. */ +const AUTH_TOKEN_UNSET = 'export OS_DATABASE_AUTH_TOKEN as the database auth token this server was started with'; + +/** + * A value as one POSIX shell word: bare when it holds only characters no shell + * reads specially, otherwise double-quoted with the four characters a double + * quote still interprets escaped. + */ +function shellWord(value: string): string { + if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(value)) return value; + return '"' + value.replace(/[\\"$\x60]/g, (c) => '\\' + c) + '"'; +} + +/** + * Whether a database URL holds a secret: a password in its user-info, or a + * query parameter whose name says token, password, secret or key. A value that + * does not parse as a URL is treated as holding one: a refusal never guesses a + * credential away. + */ +function carriesCredential(url: string): boolean { + if (/^file:/i.test(url)) return false; + let parsed: URL; + try { + parsed = new URL(url); + } catch { + return true; + } + if (parsed.password !== '') return true; + return [...parsed.searchParams.keys()].some((key) => /token|password|passwd|secret|key/i.test(key)); +} + +/** + * The switch command the refusal names, spelled for the boot that refused, so + * that run verbatim it composes the same deployment over the same database: + * `--dev` and `--preset` as the boot had them, `--database-url` when the + * command's own default would reach another database (by reference when the + * URL carries a credential), and in front of it the variables the command + * reads a driver, an auth token or a file-held auth secret from. + */ +function switchCommand(opts: FormTypeSwitchBootGuardOptions): string { + let front = ''; + if (opts.databaseDriver) front += `OS_DATABASE_DRIVER=${shellWord(opts.databaseDriver)} `; + if (opts.databaseAuthTokenFromFlag) front += `OS_DATABASE_AUTH_TOKEN="\${OS_DATABASE_AUTH_TOKEN:?${AUTH_TOKEN_UNSET}}" `; + if (!opts.dev && opts.authSecretFile) front += `OS_AUTH_SECRET="$(cat ${shellWord(opts.authSecretFile)})" `; + let flags = ''; + if (opts.dev) flags += ' --dev'; + if (opts.preset) flags += ` --preset ${shellWord(opts.preset)}`; + if (opts.databaseUrl) { + flags += carriesCredential(opts.databaseUrl) + ? ` --database-url "\${OS_DATABASE_URL:?${FORM_TYPE_SWITCH_CREDENTIAL_URL_UNSET}}"` + : ` --database-url ${shellWord(opts.databaseUrl)}`; + } + return `${front}os migrate protocol --to ${FORM_TYPE_SWITCH_PROTOCOL_MAJOR}${flags}`; +} + +/** Why a named command reads a value from the shell instead of printing it. */ +function referenceNotes(opts: FormTypeSwitchBootGuardOptions): string { + let notes = ''; + if (!opts.dev && opts.authSecretFile) { + notes += ` Both commands export the auth secret this server read from ${opts.authSecretFile}, so they compose the ` + + 'deployment as this server does.'; + } + if (opts.databaseUrl && carriesCredential(opts.databaseUrl)) { + notes += ' The database URL this server was started with carries a credential, so it is not printed: export it as ' + + 'OS_DATABASE_URL in the shell that runs both commands, which read it from there and stop if it is unset.'; + } + if (opts.databaseAuthTokenFromFlag) { + notes += ' The database auth token this server was started with (--database-auth-token) is not printed: export it ' + + 'as OS_DATABASE_AUTH_TOKEN in the shell that runs both commands, which read it from there and stop if it is unset.'; + } + return notes; +} + +/** + * The refusal text: what was found, that the server refuses to start, and the + * command, first as its preview and then as the run that switches. + */ +export function formTypeSwitchRefusalMessage( + marker: FormTypeSwitchMarkerState, + opts: FormTypeSwitchBootGuardOptions = {}, +): string { + const command = switchCommand(opts); + const major = FORM_TYPE_SWITCH_PROTOCOL_MAJOR; + const run = + `Run '${command}' to see what the switch does with every stored form in an old shape, take a backup, then run ` + + `'${command} --apply --yes', and start again.${referenceNotes(opts)}`; + if (marker === 'absent') { + return ( + `This database has not been switched to protocol ${major}: it carries no switch record (sys_migration ` + + `'${FORM_TYPE_SWITCH_MIGRATION_ID}'), so an earlier release created it. On protocol ${major} a view holds lists ` + + 'only and a form is a form item, and the switch is what moves the forms this database stores in an old shape. ' + + `The server refuses to start rather than serve it unswitched. ${run} A database that stores no form runs the ` + + 'command once too: it finds nothing to move and records the switch.' + ); + } + if (marker === 'unreadable') { + return ( + `The protocol ${major} switch record (sys_migration '${FORM_TYPE_SWITCH_MIGRATION_ID}') of this database could ` + + 'not be read, and an unread answer is never taken for a switched database. The server refuses to start. Fix the ' + + `read, or run the switch: ${run}` + ); + } + if (marker === 'no-ledger') { + return ( + `This composition stores metadata (sys_metadata) and registers no ${DATA_MIGRATION_FLAG_OBJECT} ledger to read ` + + `the protocol ${major} switch record from, so the server cannot tell whether this database was switched and ` + + 'refuses to start. Compose the platform objects plugin (@objectstack/platform-objects), which os serve mounts ' + + `by default, then start again; on a database an earlier release created: ${run}` + ); + } + return ( + `The protocol ${major} switch has not finished on this database: its record (sys_migration ` + + `'${FORM_TYPE_SWITCH_MIGRATION_ID}') is not verified. The server refuses to start rather than serve it ` + + `unswitched. ${run}` + ); +} + +interface GuardDriver { + getSchemaSyncStats?: () => { created: number; existing: number } | undefined; +} + +interface GuardEngine { + getDriverForObject?: (object: string) => unknown; + findOne?: (object: string, query: Record) => Promise; + insert?: (object: string, data: Record, options?: Record) => Promise; + getObject?: (name: string) => unknown; + wasDatastoreCreatedFromEmpty?: () => boolean; + invalidateDataMigrationFlags?: () => void; +} + +/** What the guard read of the switch's `sys_migration` row. */ +type MarkerReading = + /** No store serves the ledger or `sys_metadata` on this composition: nothing to judge. */ + | { state: 'inert' } + | { state: 'no-ledger' } + | { state: 'absent' } + | { state: 'unreadable' } + | { state: 'unverified' } + | { state: 'verified' }; + +/** The driver that serves `object` when the composition registers it, or `undefined`. */ +function storeOf(engine: GuardEngine, object: string): GuardDriver | undefined { + if (typeof engine.getDriverForObject !== 'function') return undefined; + try { + if (typeof engine.getObject === 'function' && !engine.getObject(object)) return undefined; + return (engine.getDriverForObject(object) as GuardDriver | undefined) ?? undefined; + } catch { + return undefined; + } +} + +/** + * The switch's row. `inert` when no store serves the ledger and none serves + * `sys_metadata` either (`os serve` with no database), or the engine offers no + * read. `no-ledger` when a store serves `sys_metadata` and none serves the + * ledger. `unreadable` only when a store serves the ledger and its read threw. + */ +async function readMarker(engine: GuardEngine): Promise { + if (typeof engine.findOne !== 'function') return { state: 'inert' }; + if (!storeOf(engine, DATA_MIGRATION_FLAG_OBJECT)) { + return storeOf(engine, METADATA_OBJECT) ? { state: 'no-ledger' } : { state: 'inert' }; + } + try { + const row = (await engine.findOne(DATA_MIGRATION_FLAG_OBJECT, { + where: { id: FORM_TYPE_SWITCH_MIGRATION_ID }, + context: { isSystem: true }, + })) as DataMigrationFlag | null; + if (!row) return { state: 'absent' }; + const flag = { ...row, blocking: Number((row as { blocking?: unknown }).blocking) } as DataMigrationFlag; + return isDataMigrationFlagVerified(flag) ? { state: 'verified' } : { state: 'unverified' }; + } catch { + return { state: 'unreadable' }; + } +} + +/** + * Did THIS boot observe the store being created from empty? Judged on the + * store that holds the ledger and on the one that holds `sys_metadata` (one + * driver wherever they share a datasource): each one's own schema-sync counts + * (`getSchemaSyncStats`) must say every table it synced it created, and none + * it found. A driver that cannot report answers through the engine's + * all-driver reading, and "cannot say" is no. + */ +function storesCreatedFromEmpty(engine: GuardEngine): boolean { + const stores = new Set(); + for (const object of [DATA_MIGRATION_FLAG_OBJECT, METADATA_OBJECT]) { + const store = storeOf(engine, object); + if (store) stores.add(store); + } + if (stores.size === 0) return false; + for (const store of stores) { + let stats: { created: number; existing: number } | undefined; + try { + stats = store.getSchemaSyncStats?.(); + } catch { + return false; + } + if (stats) { + if ((Number(stats.existing) || 0) !== 0 || !((Number(stats.created) || 0) > 0)) return false; + continue; + } + try { + if (engine.wasDatastoreCreatedFromEmpty?.() !== true) return false; + } catch { + return false; + } + } + return true; +} + +/** + * Write the birth marker: the switch's row, verified, with `details.birth` + * naming the protocol major the store was created on. Only where no row exists. + */ +async function writeBirthMarker(engine: GuardEngine, now: Date): Promise { + if (typeof engine.insert !== 'function') throw new Error('the engine offers no insert'); + const at = now.toISOString(); + const birth: FormTypeSwitchBirthMarker = { + protocol: FORM_TYPE_SWITCH_PROTOCOL_MAJOR, + platformVersion: resolveRuntimeVersion(), + createdAt: at, + }; + await engine.insert( + DATA_MIGRATION_FLAG_OBJECT, + { + id: FORM_TYPE_SWITCH_MIGRATION_ID, + last_run_at: at, + verified_at: at, + applied_at: null, + blocking: 0, + advisory: 0, + details: JSON.stringify({ birth }), + created_at: at, + updated_at: at, + }, + { context: { isSystem: true } }, + ); + engine.invalidateDataMigrationFlags?.(); + return birth; +} + +function birthLine(birth: FormTypeSwitchBirthMarker): string { + return ( + `[form-type-switch] a datastore created from empty: birth marker written (protocol ${birth.protocol}, ` + + `platform ${birth.platformVersion}).` + ); +} + +/** + * Write the birth marker when, and only when, this boot created the store + * from empty and no switch row is there. The marker written, or `null` when + * none was owed. Throws when the write fails. + */ +export async function recordFormTypeSwitchBirth( + engine: GuardEngine, + logger?: { info?: (msg: string) => void }, + now: () => Date = () => new Date(), +): Promise { + if (!storesCreatedFromEmpty(engine)) return null; + if ((await readMarker(engine)).state !== 'absent') return null; + const birth = await writeBirthMarker(engine, now()); + logger?.info?.(birthLine(birth)); + return birth; +} + +/** + * The check itself, for the plugin and for a host that composes its own boot: + * resolves when the database may be served (writing the birth marker on a + * store created from empty), throws {@link FormTypeSwitchBootRefusal} when it + * may not. + */ +export async function assertFormTypeSwitched( + engine: GuardEngine, + logger?: { info?: (msg: string) => void }, + opts: FormTypeSwitchBootGuardOptions & { now?: () => Date } = {}, +): Promise { + const marker = await readMarker(engine); + if (marker.state === 'inert' || marker.state === 'verified') return; + if (marker.state === 'absent' && storesCreatedFromEmpty(engine)) { + let birth: FormTypeSwitchBirthMarker; + try { + birth = await writeBirthMarker(engine, (opts.now ?? (() => new Date()))()); + } catch (error) { + throw new FormTypeSwitchBootRefusal( + `The server refuses to start: this datastore was created from empty, and its protocol ` + + `${FORM_TYPE_SWITCH_PROTOCOL_MAJOR} birth marker (sys_migration '${FORM_TYPE_SWITCH_MIGRATION_ID}') could ` + + `not be written (${error instanceof Error ? error.message : String(error)}). Without it the next boot would ` + + `take this store for a database an earlier release created. Fix the write and start again, or run ` + + `'${switchCommand(opts)} --apply --yes'.`, + 'birth-unwritten', + ); + } + logger?.info?.(birthLine(birth)); + return; + } + throw new FormTypeSwitchBootRefusal(formTypeSwitchRefusalMessage(marker.state, opts), marker.state); +} + +/** + * Refuse a composition in which another plugin carries the guard's name. + * + * Duplicate registration by name is last-one-wins on the kernel, by declared + * contract: a plugin mounted after the guard under its name replaces it, the + * guard never starts, and the boot goes unjudged. That would be a config key + * that boots an unswitched database anyway, which the ruling excludes (record + * 7303149461), so the host that composes the guard hands the plugins it + * mounted from the stack here before any of them initializes. Throws + * {@link FormTypeSwitchBootRefusal} (`guard-replaced`). + */ +export function assertFormTypeSwitchGuardNotReplaced(guard: unknown, composed: Iterable): void { + for (const plugin of composed) { + if (plugin === guard) continue; + if ((plugin as { name?: unknown } | null | undefined)?.name !== FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME) continue; + throw new FormTypeSwitchBootRefusal( + `Refusing to boot: a plugin of this stack is named '${FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME}', the name of the ` + + `server's own protocol ${FORM_TYPE_SWITCH_PROTOCOL_MAJOR} boot guard, and a later registration under one name ` + + 'replaces the earlier one. The guard is not replaceable: remove that plugin from the stack, or give it a ' + + 'name of its own.', + 'guard-replaced', + ); + } +} + +export class FormTypeSwitchBootGuardPlugin implements Plugin { + readonly name = FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME; + readonly type = 'standard'; + readonly version = '1.0.0'; + readonly dependencies: string[] = []; + /** + * Started after the engine (its `start()` connects the drivers and runs the + * schema sync), after the platform objects, which register `sys_migration`, + * and after the organization-ownership guard: a database that owes both acts + * hears of the older one first, and a store created from empty has that + * guard's birth marker before this one's. Order-if-present: the guard still + * loads (inert) on a kernel with no engine. + */ + readonly optionalDependencies: string[] = [ + 'com.objectstack.engine.objectql', + 'com.objectstack.platform-objects', + 'com.objectstack.organization-ownership-boot-guard', + ]; + + constructor(private readonly options: FormTypeSwitchBootGuardOptions = {}) {} + + async init(_ctx: PluginContext): Promise {} + + /** [ADR-0159 D7] Judges here, not at `kernel:ready`: a `start()` that throws stops the boot before the next plugin starts. */ + async start(ctx: PluginContext): Promise { + let engine: GuardEngine | undefined; + try { + engine = (ctx as any).getService?.('objectql'); + } catch { + return; // no engine: no database to judge + } + if (!engine || typeof engine.getDriverForObject !== 'function') return; + await assertFormTypeSwitched(engine, (ctx as any)?.logger, this.options); + } +} + +/** + * [Ruling record 7308112533] The birth half alone, for a boot that composes no + * guard: every CLI data and schema boot (`createStandaloneStack`), which can + * be the boot that creates a fresh install's store (`os migrate apply`, + * `os seed` before the first `os serve`). It writes the birth marker under + * exactly the guard's conditions and never refuses: judging the database stays + * the served boot's. Without it, the first `os serve` of an install whose + * store a CLI boot created would find no marker on a store it did not create, + * and refuse a fresh install. + * + * A boot that holds its DDL back (`deferSchemaDdl`) or skips schema sync + * reports nothing created, so the plugin writes nothing there: the switch + * command's own boots never trip it. A deferred boot that then creates the + * tables calls {@link recordFormTypeSwitchBirth} itself once they exist (the + * CLI's `flushSchemaDdl`), judged on the same counts. + */ +export class FormTypeSwitchBirthMarkerPlugin implements Plugin { + readonly name = FORM_TYPE_SWITCH_BIRTH_MARKER_PLUGIN_NAME; + readonly type = 'standard'; + readonly version = '1.0.0'; + readonly dependencies: string[] = []; + /** As the guard: after the engine's schema sync and the ledger's registration. */ + readonly optionalDependencies: string[] = ['com.objectstack.engine.objectql', 'com.objectstack.platform-objects']; + + async init(_ctx: PluginContext): Promise {} + + async start(ctx: PluginContext): Promise { + let engine: GuardEngine | undefined; + try { + engine = (ctx as any).getService?.('objectql'); + } catch { + return; + } + if (!engine || typeof engine.getDriverForObject !== 'function') return; + const logger = (ctx as any)?.logger as { info?: (msg: string) => void; error?: (msg: string) => void } | undefined; + try { + await recordFormTypeSwitchBirth(engine, logger); + } catch (error) { + // Durability: the store keeps looking healthy, and its first served boot + // will refuse it as one an earlier release created. + logger?.error?.( + `[form-type-switch] this store was created from empty and its birth marker (sys_migration ` + + `'${FORM_TYPE_SWITCH_MIGRATION_ID}') could not be written ` + + `(${error instanceof Error ? error.message : String(error)}): the first 'os serve' will refuse it as a ` + + `database an earlier release created. Fix the write and run this command again, or run 'os migrate ` + + `protocol --to ${FORM_TYPE_SWITCH_PROTOCOL_MAJOR} --apply --yes' on it.`, + ); + } + } +} diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts index 482c5f515b6..fc8099dc0b7 100644 --- a/packages/runtime/src/index.ts +++ b/packages/runtime/src/index.ts @@ -159,6 +159,29 @@ export { organizationOwnershipRefusalMessage, } from './organization-ownership-boot-guard.js'; export type { OrganizationOwnershipBootGuardOptions, OrganizationOwnershipMarkerState } from './organization-ownership-boot-guard.js'; +// [ADR-0159 D7] The protocol-19 boot refusal `os serve` composes, and the birth +// half every CLI data and schema boot composes beside it. +export { + FormTypeSwitchBootGuardPlugin, + FormTypeSwitchBirthMarkerPlugin, + FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME, + FORM_TYPE_SWITCH_BIRTH_MARKER_PLUGIN_NAME, + FORM_TYPE_SWITCH_PROTOCOL_MAJOR, + recordFormTypeSwitchBirth, + FormTypeSwitchBootRefusal, + FORM_TYPE_SWITCH_BOOT_REFUSAL_CODE, + FORM_TYPE_SWITCH_BOOT_REFUSAL_NAME, + assertFormTypeSwitched, + assertFormTypeSwitchGuardNotReplaced, + isFormTypeSwitchBootRefusal, + formTypeSwitchRefusalMessage, +} from './form-type-switch-boot-guard.js'; +export type { + FormTypeSwitchBirthMarker, + FormTypeSwitchBootGuardOptions, + FormTypeSwitchMarkerState, + FormTypeSwitchRefusalReason, +} from './form-type-switch-boot-guard.js'; export { DefaultDatasourcePlugin } from './default-datasource-plugin.js'; export type { DefaultDatasourceDefinition, DefaultDatasourcePluginOptions } from './default-datasource-plugin.js'; export { AppPlugin, collectBundleHooks, collectBundleFunctions, collectBundleFunctionEntries, collectBundleActions } from './app-plugin.js'; diff --git a/packages/runtime/src/standalone-stack.ts b/packages/runtime/src/standalone-stack.ts index d810dea2a51..44e92ac9cc4 100644 --- a/packages/runtime/src/standalone-stack.ts +++ b/packages/runtime/src/standalone-stack.ts @@ -81,6 +81,7 @@ import { makeDirectorySync } from './make-directory.js'; import { loadTursoDriverFactory } from './turso-driver-factory.js'; import { devAutoMigrateConfig } from './dev-auto-migrate.js'; import { OrganizationOwnershipBirthMarkerPlugin } from './organization-ownership-boot-guard.js'; +import { FormTypeSwitchBirthMarkerPlugin } from './form-type-switch-boot-guard.js'; import { namesRetiredMemoryEngine, resolveProjectDatabaseUrl, @@ -1178,6 +1179,13 @@ export async function createStandaloneStack(config?: StandaloneStackConfig): Pro // by its first `os serve`. It never refuses — the served boot's guard // judges (⛔ the guard itself stays out of this list). new OrganizationOwnershipBirthMarkerPlugin(), + // [ADR-0159 D7; ruling record 7308112533] The same for the protocol-19 + // switch: a store this boot creates from empty holds no stored form, + // so its switch record is written here as a birth marker and the + // first `os serve` does not refuse a fresh install. It never refuses + // (⛔ the guard itself stays out of this list: `os migrate protocol`'s + // own boot shares it). + new FormTypeSwitchBirthMarkerPlugin(), ]; if (artifactBundle) { plugins.push(new AppPlugin(artifactBundle, undefined, { diff --git a/packages/spec/api-surface/api.json b/packages/spec/api-surface/api.json index 8a960d9db4e..01b200262bc 100644 --- a/packages/spec/api-surface/api.json +++ b/packages/spec/api-surface/api.json @@ -591,6 +591,7 @@ "GetTranslationsRequestSchema (const)", "GetTranslationsResponse (type)", "GetTranslationsResponseSchema (const)", + "GetUiViewFormScaffold (type)", "GetUiViewRequest (type)", "GetUiViewRequestSchema (const)", "GetUiViewResponse (type)", diff --git a/packages/spec/api-surface/root.json b/packages/spec/api-surface/root.json index 5ae86b2dc59..60b7a48b013 100644 --- a/packages/spec/api-surface/root.json +++ b/packages/spec/api-surface/root.json @@ -177,6 +177,7 @@ "defineViewItem (function)", "defineWebhook (function)", "deriveViewContainerObject (function)", + "expandServedViewContainer (function)", "expandViewContainer (function)", "expandViewContainerWithDiagnostics (function)", "expression (function)", @@ -188,6 +189,7 @@ "hasStackProvenance (function)", "isAggregatedViewContainer (function)", "isKnownPlatformCapability (function)", + "isServedViewItem (function)", "isViewContainerShaped (function)", "lintUnknownAuthoringKeys (function)", "lintUnknownKeysAgainstSchema (function)", diff --git a/packages/spec/api-surface/ui.json b/packages/spec/api-surface/ui.json index a3b73edd4fe..2b859dfd0e2 100644 --- a/packages/spec/api-surface/ui.json +++ b/packages/spec/api-surface/ui.json @@ -477,6 +477,7 @@ "SelectionConfig (type)", "SelectionConfigParsed (type)", "SelectionConfigSchema (const)", + "ServedViewItem (type)", "SharingConfig (type)", "SharingConfigParsed (type)", "SharingConfigSchema (const)", @@ -610,6 +611,7 @@ "deriveColumnSummary (function)", "deriveViewContainerObject (function)", "diagnoseViewMetadata (function)", + "expandServedViewContainer (function)", "expandViewContainer (function)", "expandViewContainerWithDiagnostics (function)", "expressionBindableTextKeysFor (function)", @@ -622,6 +624,7 @@ "isExpressionBindableTextKey (function)", "isKnownComponentType (function)", "isRecordContextBlockType (function)", + "isServedViewItem (function)", "isViewContainerShaped (function)", "isViewFilterOrGroup (function)", "listViewGroupKeyPredicate (function)", diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index 0cb48136c0d..457c3995a61 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -991,8 +991,8 @@ "api/GetUiViewResponse:_packageId", "api/GetUiViewResponse:_packageVersion", "api/GetUiViewResponse:_provenance", - "api/GetUiViewResponse:form", - "api/GetUiViewResponse:formViews", + "api/GetUiViewResponse:form [RETIRED]", + "api/GetUiViewResponse:formViews [RETIRED]", "api/GetUiViewResponse:label", "api/GetUiViewResponse:list", "api/GetUiViewResponse:listViews", diff --git a/packages/spec/authorable-surface/ui.json b/packages/spec/authorable-surface/ui.json index 30b0daf0c68..ffc4faa8c3b 100644 --- a/packages/spec/authorable-surface/ui.json +++ b/packages/spec/authorable-surface/ui.json @@ -1436,8 +1436,8 @@ "ui/View:_packageId", "ui/View:_packageVersion", "ui/View:_provenance", - "ui/View:form", - "ui/View:formViews", + "ui/View:form [RETIRED]", + "ui/View:formViews [RETIRED]", "ui/View:label", "ui/View:list", "ui/View:listViews", diff --git a/packages/spec/docs/references/api/automation-api.md b/packages/spec/docs/references/api/automation-api.md index 143fe482586..5ab357e2ee9 100644 --- a/packages/spec/docs/references/api/automation-api.md +++ b/packages/spec/docs/references/api/automation-api.md @@ -419,7 +419,7 @@ const result = AutomationApiErrorCode.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +385 more>` | ✅ | The inner refusal's code in its WIRE spelling - the ADR-0112 member a record save of the same write answers in `error.code` (e.g. `UNIQUE_VIOLATION`); the closed set `ApiErrorSchema.code` parses against | +| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +386 more>` | ✅ | The inner refusal's code in its WIRE spelling - the ADR-0112 member a record save of the same write answers in `error.code` (e.g. `UNIQUE_VIOLATION`); the closed set `ApiErrorSchema.code` parses against | | **message** | `string` | ✅ | The inner refusal's own diagnostic text, verbatim, without the node and operation prefixes the run's failure text adds | ### Allowed Values: `FlowInnerRefusal.code` @@ -612,6 +612,7 @@ const result = AutomationApiErrorCode.parse(data); * `FORM_ADDRESS_TAKEN` * `FORM_NOT_FOUND` * `FORM_RESOLVE_FAILED` +* `FORM_TYPE_SWITCH_REQUIRED` * `HOOK_ABORTED` * `HOOK_UNSCOPED_DATA_ACCESS` * `IMPORT_JOB_CREATE_FAILED` diff --git a/packages/spec/docs/references/api/contract.md b/packages/spec/docs/references/api/contract.md index ac280168ff1..82ea52bb12d 100644 --- a/packages/spec/docs/references/api/contract.md +++ b/packages/spec/docs/references/api/contract.md @@ -22,7 +22,7 @@ const result = ApiErrorSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +385 more>` | ✅ | Error code (e.g. VALIDATION_ERROR; StandardErrorCode ∪ the ledger the serving side registers — ERROR_CODE_LEDGER for framework packages) | +| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +386 more>` | ✅ | Error code (e.g. VALIDATION_ERROR; StandardErrorCode ∪ the ledger the serving side registers — ERROR_CODE_LEDGER for framework packages) | | **declaredCode** | `string` | optional | The producer-declared code, verbatim, when it is not a member of the closed `code` vocabulary — the open, author-authored channel (app-specific spellings; ADR-0112) | | **message** | `string` | ✅ | Readable error message | | **userMessage** | `string` | optional | Producer-marked user-facing refusal text, verbatim, in the request's locale: platform-composed text falls back to the workspace default locale, then `en`; an app-authored refusal falls back to its declared wording. Present exactly when the producer opted in at throw time; consumers render it to end users as received and keep their generic substitution for anything unmarked. Status-agnostic; never replaces `message`. | @@ -222,6 +222,7 @@ const result = ApiErrorSchema.parse(data); * `FORM_ADDRESS_TAKEN` * `FORM_NOT_FOUND` * `FORM_RESOLVE_FAILED` +* `FORM_TYPE_SWITCH_REQUIRED` * `HOOK_ABORTED` * `HOOK_UNSCOPED_DATA_ACCESS` * `IMPORT_JOB_CREATE_FAILED` diff --git a/packages/spec/docs/references/api/error-code-ledger.md b/packages/spec/docs/references/api/error-code-ledger.md index 2a7ae6b030c..2335a1050a8 100644 --- a/packages/spec/docs/references/api/error-code-ledger.md +++ b/packages/spec/docs/references/api/error-code-ledger.md @@ -389,6 +389,7 @@ const result = ErrorCode.parse(data); * `FORM_ADDRESS_TAKEN` * `FORM_NOT_FOUND` * `FORM_RESOLVE_FAILED` +* `FORM_TYPE_SWITCH_REQUIRED` * `HOOK_ABORTED` * `HOOK_UNSCOPED_DATA_ACCESS` * `IMPORT_JOB_CREATE_FAILED` diff --git a/packages/spec/docs/references/api/protocol.md b/packages/spec/docs/references/api/protocol.md index 5e818e11a89..2ad2339e726 100644 --- a/packages/spec/docs/references/api/protocol.md +++ b/packages/spec/docs/references/api/protocol.md @@ -5,8 +5,8 @@ > This reference is split into 3 files, each small enough for GitHub to show as a document. - Part 1: [AiAgentCapabilities](#aiagentcapabilities), [AiAgentChatRequest](#aiagentchatrequest), [AiAgentSummary](#aiagentsummary), [AiAgentsResponse](#aiagentsresponse), [AiChatRequest](#aichatrequest), [AiChatResponse](#aichatresponse), [AiCompleteRequest](#aicompleterequest), [AiConversation](#aiconversation), [AiConversationMessage](#aiconversationmessage), [AiMessage](#aimessage), [AiModelsResponse](#aimodelsresponse), [AiPendingAction](#aipendingaction), [AiPendingActionStatus](#aipendingactionstatus), [AiStreamChunk](#aistreamchunk), [ApproveAiPendingActionResponse](#approveaipendingactionresponse), [AuditMetaItemRequest](#auditmetaitemrequest), [AuditMetaItemResponse](#auditmetaitemresponse), [AutomationActionsResponse](#automationactionsresponse), [AutomationTriggerRequest](#automationtriggerrequest), [AutomationTriggerResponse](#automationtriggerresponse), [BatchDataRequest](#batchdatarequest), [BatchDataResponse](#batchdataresponse), [BuildProbeReport](#buildprobereport), [CheckPermissionRequest](#checkpermissionrequest), [CheckPermissionResponse](#checkpermissionresponse), [CloneDataResponse](#clonedataresponse), [CreateAiConversationRequest](#createaiconversationrequest), [CreateDataRequest](#createdatarequest), [CreateDataResponse](#createdataresponse), [CreateManyDataRequest](#createmanydatarequest), [CreateManyDataResponse](#createmanydataresponse), [DeleteDataRequest](#deletedatarequest), [DeleteDataResponse](#deletedataresponse), [DeleteManyDataRequest](#deletemanydatarequest), [DeleteManyDataResponse](#deletemanydataresponse), [DeleteMetaItemRequest](#deletemetaitemrequest), [DeleteMetaItemResponse](#deletemetaitemresponse), [DestructiveChangeIssue](#destructivechangeissue), [DiffMetaItemRequest](#diffmetaitemrequest), [DiffMetaItemResponse](#diffmetaitemresponse), [DisablePackageRequest](#disablepackagerequest), [DisablePackageResponse](#disablepackageresponse), [EnablePackageRequest](#enablepackagerequest), [EnablePackageResponse](#enablepackageresponse), [FieldStillShownBy](#fieldstillshownby), [FindDataRequest](#finddatarequest), [FindDataResponse](#finddataresponse), [FindReferencesToMetaResponse](#findreferencestometaresponse), [FlowRegistration](#flowregistration), [FlowRegistrationRefusal](#flowregistrationrefusal), [GetDataRequest](#getdatarequest), [GetDataResponse](#getdataresponse), [GetDiscoveryRequest](#getdiscoveryrequest), [GetDiscoveryResponse](#getdiscoveryresponse), [GetEffectivePermissionsRequest](#geteffectivepermissionsrequest), [GetEffectivePermissionsResponse](#geteffectivepermissionsresponse), [GetFieldLabelsRequest](#getfieldlabelsrequest), [GetFieldLabelsResponse](#getfieldlabelsresponse), [GetLocalesRequest](#getlocalesrequest), [GetLocalesResponse](#getlocalesresponse), [GetMetaDiagnosticsResponse](#getmetadiagnosticsresponse), [GetMetaItemCachedRequest](#getmetaitemcachedrequest), [GetMetaItemCachedResponse](#getmetaitemcachedresponse), [GetMetaItemLayeredRequest](#getmetaitemlayeredrequest), [GetMetaItemLayeredResponse](#getmetaitemlayeredresponse), [GetMetaItemRequest](#getmetaitemrequest) -- Part 2: [GetMetaItemResponse](protocol.part-2.md#getmetaitemresponse), [GetMetaItemsRequest](protocol.part-2.md#getmetaitemsrequest), [GetMetaItemsResponse](protocol.part-2.md#getmetaitemsresponse), [GetMetaTypesRequest](protocol.part-2.md#getmetatypesrequest), [GetMetaTypesResponse](protocol.part-2.md#getmetatypesresponse), [GetNotificationPreferencesRequest](protocol.part-2.md#getnotificationpreferencesrequest), [GetNotificationPreferencesResponse](protocol.part-2.md#getnotificationpreferencesresponse), [GetObjectPermissionsRequest](protocol.part-2.md#getobjectpermissionsrequest), [GetObjectPermissionsResponse](protocol.part-2.md#getobjectpermissionsresponse), [GetPackageRequest](protocol.part-2.md#getpackagerequest), [GetPackageResponse](protocol.part-2.md#getpackageresponse), [GetPresenceRequest](protocol.part-2.md#getpresencerequest), [GetPresenceResponse](protocol.part-2.md#getpresenceresponse), [GetPublishedMetaItemResponse](protocol.part-2.md#getpublishedmetaitemresponse), [GetRecordFieldAccessResponse](protocol.part-2.md#getrecordfieldaccessresponse), [GetTranslationsRequest](protocol.part-2.md#gettranslationsrequest), [GetTranslationsResponse](protocol.part-2.md#gettranslationsresponse), [GetUiViewRequest](protocol.part-2.md#getuiviewrequest), [GetUiViewResponse](protocol.part-2.md#getuiviewresponse), [HistoryMetaItemRequest](protocol.part-2.md#historymetaitemrequest), [HistoryMetaItemResponse](protocol.part-2.md#historymetaitemresponse), [HttpFindQueryParams](protocol.part-2.md#httpfindqueryparams), [InstallPackageRequest](protocol.part-2.md#installpackagerequest), [InstallPackageResponse](protocol.part-2.md#installpackageresponse), [ListAiConversationsRequest](protocol.part-2.md#listaiconversationsrequest), [ListAiConversationsResponse](protocol.part-2.md#listaiconversationsresponse), [ListAiPendingActionsRequest](protocol.part-2.md#listaipendingactionsrequest), [ListAiPendingActionsResponse](protocol.part-2.md#listaipendingactionsresponse), [ListDraftsResponse](protocol.part-2.md#listdraftsresponse), [ListNotificationsRequest](protocol.part-2.md#listnotificationsrequest), [ListNotificationsResponse](protocol.part-2.md#listnotificationsresponse), [ListPackagesRequest](protocol.part-2.md#listpackagesrequest), [ListPackagesResponse](protocol.part-2.md#listpackagesresponse), [MarkAllNotificationsReadRequest](protocol.part-2.md#markallnotificationsreadrequest), [MarkAllNotificationsReadResponse](protocol.part-2.md#markallnotificationsreadresponse), [MarkNotificationsReadRequest](protocol.part-2.md#marknotificationsreadrequest), [MarkNotificationsReadResponse](protocol.part-2.md#marknotificationsreadresponse), [MetadataAuthoringClient](protocol.part-2.md#metadataauthoringclient), [MetadataAuthoringSurface](protocol.part-2.md#metadataauthoringsurface), [MetadataConflictError](protocol.part-2.md#metadataconflicterror), [Notification](protocol.part-2.md#notification), [NotificationPreferences](protocol.part-2.md#notificationpreferences), [PublicFormSubmitResponse](protocol.part-2.md#publicformsubmitresponse), [PublishMetaItemRequest](protocol.part-2.md#publishmetaitemrequest), [PublishMetaItemResponse](protocol.part-2.md#publishmetaitemresponse), [PublishPackageDraftsRequest](protocol.part-2.md#publishpackagedraftsrequest) -- Part 3: [PublishPackageDraftsResponse](protocol.part-3.md#publishpackagedraftsresponse), [RealtimeConnectRequest](protocol.part-3.md#realtimeconnectrequest), [RealtimeConnectResponse](protocol.part-3.md#realtimeconnectresponse), [RealtimeDisconnectRequest](protocol.part-3.md#realtimedisconnectrequest), [RealtimeDisconnectResponse](protocol.part-3.md#realtimedisconnectresponse), [RealtimeSubscribeRequest](protocol.part-3.md#realtimesubscriberequest), [RealtimeSubscribeResponse](protocol.part-3.md#realtimesubscriberesponse), [RealtimeUnsubscribeRequest](protocol.part-3.md#realtimeunsubscriberequest), [RealtimeUnsubscribeResponse](protocol.part-3.md#realtimeunsubscriberesponse), [RegisterDeviceRequest](protocol.part-3.md#registerdevicerequest), [RegisterDeviceResponse](protocol.part-3.md#registerdeviceresponse), [RejectAiPendingActionResponse](protocol.part-3.md#rejectaipendingactionresponse), [RollbackMetaItemRequest](protocol.part-3.md#rollbackmetaitemrequest), [RollbackMetaItemResponse](protocol.part-3.md#rollbackmetaitemresponse), [RuntimeAuthoringIssue](protocol.part-3.md#runtimeauthoringissue), [RuntimeBuildIssue](protocol.part-3.md#runtimebuildissue), [SaveMetaItemRequest](protocol.part-3.md#savemetaitemrequest), [SaveMetaItemResponse](protocol.part-3.md#savemetaitemresponse), [SearchAllHit](protocol.part-3.md#searchallhit), [SearchAllPageHit](protocol.part-3.md#searchallpagehit), [SearchAllResponse](protocol.part-3.md#searchallresponse), [SeedAppliedIdList](protocol.part-3.md#seedappliedidlist), [SeedAppliedLanded](protocol.part-3.md#seedappliedlanded), [SetPresenceRequest](protocol.part-3.md#setpresencerequest), [SetPresenceResponse](protocol.part-3.md#setpresenceresponse), [UninstallPackageRequest](protocol.part-3.md#uninstallpackagerequest), [UninstallPackageResponse](protocol.part-3.md#uninstallpackageresponse), [UnregisterDeviceRequest](protocol.part-3.md#unregisterdevicerequest), [UnregisterDeviceResponse](protocol.part-3.md#unregisterdeviceresponse), [UpdateAiConversationRequest](protocol.part-3.md#updateaiconversationrequest), [UpdateDataRequest](protocol.part-3.md#updatedatarequest), [UpdateDataResponse](protocol.part-3.md#updatedataresponse), [UpdateManyDataRequest](protocol.part-3.md#updatemanydatarequest), [UpdateManyDataResponse](protocol.part-3.md#updatemanydataresponse), [UpdateNotificationPreferencesRequest](protocol.part-3.md#updatenotificationpreferencesrequest), [UpdateNotificationPreferencesResponse](protocol.part-3.md#updatenotificationpreferencesresponse), [ValidateDataIssue](protocol.part-3.md#validatedataissue), [ValidateDataRequest](protocol.part-3.md#validatedatarequest), [ValidateDataResponse](protocol.part-3.md#validatedataresponse) +- Part 2: [GetMetaItemResponse](protocol.part-2.md#getmetaitemresponse), [GetMetaItemsRequest](protocol.part-2.md#getmetaitemsrequest), [GetMetaItemsResponse](protocol.part-2.md#getmetaitemsresponse), [GetMetaTypesRequest](protocol.part-2.md#getmetatypesrequest), [GetMetaTypesResponse](protocol.part-2.md#getmetatypesresponse), [GetNotificationPreferencesRequest](protocol.part-2.md#getnotificationpreferencesrequest), [GetNotificationPreferencesResponse](protocol.part-2.md#getnotificationpreferencesresponse), [GetObjectPermissionsRequest](protocol.part-2.md#getobjectpermissionsrequest), [GetObjectPermissionsResponse](protocol.part-2.md#getobjectpermissionsresponse), [GetPackageRequest](protocol.part-2.md#getpackagerequest), [GetPackageResponse](protocol.part-2.md#getpackageresponse), [GetPresenceRequest](protocol.part-2.md#getpresencerequest), [GetPresenceResponse](protocol.part-2.md#getpresenceresponse), [GetPublishedMetaItemResponse](protocol.part-2.md#getpublishedmetaitemresponse), [GetRecordFieldAccessResponse](protocol.part-2.md#getrecordfieldaccessresponse), [GetTranslationsRequest](protocol.part-2.md#gettranslationsrequest), [GetTranslationsResponse](protocol.part-2.md#gettranslationsresponse), [GetUiViewRequest](protocol.part-2.md#getuiviewrequest), [GetUiViewResponse](protocol.part-2.md#getuiviewresponse), [HistoryMetaItemRequest](protocol.part-2.md#historymetaitemrequest), [HistoryMetaItemResponse](protocol.part-2.md#historymetaitemresponse), [HttpFindQueryParams](protocol.part-2.md#httpfindqueryparams), [InstallPackageRequest](protocol.part-2.md#installpackagerequest), [InstallPackageResponse](protocol.part-2.md#installpackageresponse), [ListAiConversationsRequest](protocol.part-2.md#listaiconversationsrequest), [ListAiConversationsResponse](protocol.part-2.md#listaiconversationsresponse), [ListAiPendingActionsRequest](protocol.part-2.md#listaipendingactionsrequest), [ListAiPendingActionsResponse](protocol.part-2.md#listaipendingactionsresponse), [ListDraftsResponse](protocol.part-2.md#listdraftsresponse), [ListNotificationsRequest](protocol.part-2.md#listnotificationsrequest), [ListNotificationsResponse](protocol.part-2.md#listnotificationsresponse), [ListPackagesRequest](protocol.part-2.md#listpackagesrequest), [ListPackagesResponse](protocol.part-2.md#listpackagesresponse), [MarkAllNotificationsReadRequest](protocol.part-2.md#markallnotificationsreadrequest), [MarkAllNotificationsReadResponse](protocol.part-2.md#markallnotificationsreadresponse), [MarkNotificationsReadRequest](protocol.part-2.md#marknotificationsreadrequest), [MarkNotificationsReadResponse](protocol.part-2.md#marknotificationsreadresponse), [MetadataAuthoringClient](protocol.part-2.md#metadataauthoringclient), [MetadataAuthoringSurface](protocol.part-2.md#metadataauthoringsurface), [MetadataConflictError](protocol.part-2.md#metadataconflicterror), [Notification](protocol.part-2.md#notification), [NotificationPreferences](protocol.part-2.md#notificationpreferences), [PublicFormSubmitResponse](protocol.part-2.md#publicformsubmitresponse), [PublishMetaItemRequest](protocol.part-2.md#publishmetaitemrequest), [PublishMetaItemResponse](protocol.part-2.md#publishmetaitemresponse), [PublishPackageDraftsRequest](protocol.part-2.md#publishpackagedraftsrequest), [PublishPackageDraftsResponse](protocol.part-2.md#publishpackagedraftsresponse), [RealtimeConnectRequest](protocol.part-2.md#realtimeconnectrequest), [RealtimeConnectResponse](protocol.part-2.md#realtimeconnectresponse), [RealtimeDisconnectRequest](protocol.part-2.md#realtimedisconnectrequest), [RealtimeDisconnectResponse](protocol.part-2.md#realtimedisconnectresponse), [RealtimeSubscribeRequest](protocol.part-2.md#realtimesubscriberequest), [RealtimeSubscribeResponse](protocol.part-2.md#realtimesubscriberesponse), [RealtimeUnsubscribeRequest](protocol.part-2.md#realtimeunsubscriberequest), [RealtimeUnsubscribeResponse](protocol.part-2.md#realtimeunsubscriberesponse), [RegisterDeviceRequest](protocol.part-2.md#registerdevicerequest), [RegisterDeviceResponse](protocol.part-2.md#registerdeviceresponse), [RejectAiPendingActionResponse](protocol.part-2.md#rejectaipendingactionresponse), [RollbackMetaItemRequest](protocol.part-2.md#rollbackmetaitemrequest) +- Part 3: [RollbackMetaItemResponse](protocol.part-3.md#rollbackmetaitemresponse), [RuntimeAuthoringIssue](protocol.part-3.md#runtimeauthoringissue), [RuntimeBuildIssue](protocol.part-3.md#runtimebuildissue), [SaveMetaItemRequest](protocol.part-3.md#savemetaitemrequest), [SaveMetaItemResponse](protocol.part-3.md#savemetaitemresponse), [SearchAllHit](protocol.part-3.md#searchallhit), [SearchAllPageHit](protocol.part-3.md#searchallpagehit), [SearchAllResponse](protocol.part-3.md#searchallresponse), [SeedAppliedIdList](protocol.part-3.md#seedappliedidlist), [SeedAppliedLanded](protocol.part-3.md#seedappliedlanded), [SetPresenceRequest](protocol.part-3.md#setpresencerequest), [SetPresenceResponse](protocol.part-3.md#setpresenceresponse), [UninstallPackageRequest](protocol.part-3.md#uninstallpackagerequest), [UninstallPackageResponse](protocol.part-3.md#uninstallpackageresponse), [UnregisterDeviceRequest](protocol.part-3.md#unregisterdevicerequest), [UnregisterDeviceResponse](protocol.part-3.md#unregisterdeviceresponse), [UpdateAiConversationRequest](protocol.part-3.md#updateaiconversationrequest), [UpdateDataRequest](protocol.part-3.md#updatedatarequest), [UpdateDataResponse](protocol.part-3.md#updatedataresponse), [UpdateManyDataRequest](protocol.part-3.md#updatemanydatarequest), [UpdateManyDataResponse](protocol.part-3.md#updatemanydataresponse), [UpdateNotificationPreferencesRequest](protocol.part-3.md#updatenotificationpreferencesrequest), [UpdateNotificationPreferencesResponse](protocol.part-3.md#updatenotificationpreferencesresponse), [ValidateDataIssue](protocol.part-3.md#validatedataissue), [ValidateDataRequest](protocol.part-3.md#validatedatarequest), [ValidateDataResponse](protocol.part-3.md#validatedataresponse) > **Source:** `packages/spec/src/api/protocol.zod.ts` diff --git a/packages/spec/docs/references/api/protocol.part-2.md b/packages/spec/docs/references/api/protocol.part-2.md index 9ff4b0da30f..ec258a8ebd3 100644 --- a/packages/spec/docs/references/api/protocol.part-2.md +++ b/packages/spec/docs/references/api/protocol.part-2.md @@ -419,9 +419,9 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **label** | `string \| Record` | optional | Human-readable label shown in metadata lists. | | **object** | `string` | optional | Object this container binds to — how a stack-level `views: [...]` entry says which object its views belong to; read by `getViewsByObject()` / `GET /meta/view?object=`. | | **list** | `{ name?: string; label?: string \| Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }` | optional | | -| **form** | `{ type?: Enum<'simple' \| 'tabbed' \| 'wizard'>; layout?: Enum<'vertical' \| 'horizontal'>; columns?: integer; title?: string; … }` | optional | | +| **form** | `never` | optional | [REMOVED] `view.form` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7) — a form is its own metadata type, and a `view` holds lists only. Move the form to the stack's `forms:` as a `form` item named `OBJECT.form` (`defineForm({ name, object, sections, … })`, the body at the top level and bound with `object`); a record's New and Edit dialogs lay out by the object's `fieldGroups` and read no form, so a create or edit form that nothing else opens is deleted, not moved. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **listViews** | `Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }>` | optional | Additional named list views (views mode — dropdown userFilters allowed, no tabs; ADR-0047) | -| **formViews** | `Record; layout?: Enum<'vertical' \| 'horizontal'>; columns?: integer; title?: string; … }>` | optional | Additional named form views | +| **formViews** | `never` | optional | [REMOVED] `view.formViews` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7) — a form is its own metadata type, and a `view` holds lists only. Move each entry to the stack's `forms:` as a `form` item named `OBJECT.KEY` (`defineForm({ name, object, sections, … })`, the body at the top level and bound with `object`); the name stays the one it is served under, so a `type: 'form'` action and a public link keep reaching it. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **protection** | `{ lock: Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>; reason: string; docsUrl?: string }` | optional | Package author protection block — lock policy for this view. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | @@ -483,34 +483,6 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **aria** | `{ ariaLabel?: string \| Record; ariaDescribedBy?: string; role?: string }` | optional | ARIA accessibility attributes for the list view | | **userFilters** | `{ element?: Enum<'dropdown' \| 'toggle'>; fields?: object[] }` | optional | | -### Nested Shape: `GetUiViewResponse.form` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **type** | `Enum<'simple' \| 'tabbed' \| 'wizard'>` | optional (default: `"simple"`) | Form layout: 'simple' (stacked sections, the default), 'tabbed' (one tab per section) or 'wizard' (one gated step per section). Where the form opens is the caller's choice, not the form's | -| **layout** | `Enum<'vertical' \| 'horizontal'>` | optional | Field layout direction — 'vertical' (the renderer default) or 'horizontal'. Multi-column is not a layout value: set `columns` | -| **columns** | `integer` | optional | Number of columns for the form body | -| **title** | `string` | optional | Form title | -| **description** | `string` | optional | Form description | -| **defaultTab** | `string` | optional | Initially active tab (tabbed forms) | -| **tabPosition** | `Enum<'top' \| 'bottom' \| 'left' \| 'right'>` | optional | Tab strip position (tabbed forms) | -| **allowSkip** | `boolean` | optional | Wizard step-gate opt-out: allow entering a later step without submitting the one before it. Navigation freedom, NOT a validation exemption — the final submit still re-validates every step and returns to the first failing one. Default (absent/false): steps unlock in array order as each prior step submits validly. UI admission only, never authorization. | -| **showStepIndicator** | `boolean` | optional | Show the wizard step indicator (renderer default: shown). Step progress (completed/current/upcoming/invalid) is derived from the step gate — this boolean is the only authorable progress surface. | -| **splitDirection** | `never` | optional | [REMOVED] `view.form.splitDirection` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it set the pane orientation of a split form, and the split form renderer retired in the same release, so no form draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitSize** | `never` | optional | [REMOVED] `view.form.splitSize` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it sized the primary pane of a `type: 'split'` form, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitResizable** | `never` | optional | [REMOVED] `view.form.splitResizable` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it made the panes of a `type: 'split'` form resizable, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerSide** | `never` | optional | [REMOVED] `view.form.drawerSide` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it. Delete the key: an object's list opens a record in its drawer from the hover icon, and the React `ObjectForm` block keeps its own `drawerSide` prop for the drawer it opens with `formType='drawer'`. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerWidth** | `never` | optional | [REMOVED] `view.form.drawerWidth` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it, and a pixel width cannot be chosen without knowing the client viewport. Delete the key: a list's record drawer takes its starting width from the `navigation.size` bucket, and the React `ObjectForm` block keeps its own `drawerWidth` prop for the drawer it opens. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **modalSize** | `never` | optional | [REMOVED] `view.form.modalSize` was removed in @objectstack/spec 19.0.0 (ADR-0049) — no form view opens in a dialog, so nothing reads it from a form view. Delete the key: the console's New and Edit dialogs lay a record out by the object's `fieldGroups` and choose their own size, a form opened by name gets a page of its own, and the React `ObjectForm` block keeps its own `modalSize` prop for the modal it opens with `formType='modal'`. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **data** | `{ provider: 'object'; object: string } \| { provider: 'value'; items: any[] } \| { provider: 'schema'; schemaId: string; schema?: Record }` | optional | Data source configuration (defaults to "object" provider) | -| **sections** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | | -| **groups** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | [LEGACY ALIAS → `sections`] Accepted for back-compat and folded onto `sections` at parse; `sections` wins when both are present. Prefer `sections`. | -| **subforms** | `{ childObject: string; relationshipField?: string; columns?: object[]; amountField?: string; … }[]` | optional | Inline master-detail child collections | -| **sharing** | `{ enabled?: boolean; publicLink?: string; password?: string; allowedDomains?: string[]; … }` | optional | Public sharing configuration for this form | -| **submitBehavior** | `{ kind: 'thank-you'; title?: string; message?: string } \| { kind: 'redirect'; url: string; delayMs?: integer } \| { kind: 'continue' } \| { kind: 'next-record' }` | optional | Post-submit behavior. On the `redirect` arm, `url` is relative-only and interpolates only declared record fields as `{{record.field_name}}`, URL-escaped. | -| **buttons** | `{ submit?: object; cancel?: object }` | optional | Form action-button visibility & labels; folded onto the flat renderer props by ObjectUI ObjectForm. | -| **defaults** | `Record` | optional | Initial field values for create-mode forms (folded into ObjectUI ObjectForm initial values;). | - ### Nested Shape: `GetUiViewResponse.listViews[string]` | Property | Type | Required | Description | @@ -563,34 +535,6 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **aria** | `{ ariaLabel?: string \| Record; ariaDescribedBy?: string; role?: string }` | optional | ARIA accessibility attributes for the list view | | **userFilters** | `{ element?: Enum<'dropdown' \| 'toggle'>; fields?: object[] }` | optional | | -### Nested Shape: `GetUiViewResponse.formViews[string]` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **type** | `Enum<'simple' \| 'tabbed' \| 'wizard'>` | optional (default: `"simple"`) | Form layout: 'simple' (stacked sections, the default), 'tabbed' (one tab per section) or 'wizard' (one gated step per section). Where the form opens is the caller's choice, not the form's | -| **layout** | `Enum<'vertical' \| 'horizontal'>` | optional | Field layout direction — 'vertical' (the renderer default) or 'horizontal'. Multi-column is not a layout value: set `columns` | -| **columns** | `integer` | optional | Number of columns for the form body | -| **title** | `string` | optional | Form title | -| **description** | `string` | optional | Form description | -| **defaultTab** | `string` | optional | Initially active tab (tabbed forms) | -| **tabPosition** | `Enum<'top' \| 'bottom' \| 'left' \| 'right'>` | optional | Tab strip position (tabbed forms) | -| **allowSkip** | `boolean` | optional | Wizard step-gate opt-out: allow entering a later step without submitting the one before it. Navigation freedom, NOT a validation exemption — the final submit still re-validates every step and returns to the first failing one. Default (absent/false): steps unlock in array order as each prior step submits validly. UI admission only, never authorization. | -| **showStepIndicator** | `boolean` | optional | Show the wizard step indicator (renderer default: shown). Step progress (completed/current/upcoming/invalid) is derived from the step gate — this boolean is the only authorable progress surface. | -| **splitDirection** | `never` | optional | [REMOVED] `view.form.splitDirection` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it set the pane orientation of a split form, and the split form renderer retired in the same release, so no form draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitSize** | `never` | optional | [REMOVED] `view.form.splitSize` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it sized the primary pane of a `type: 'split'` form, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitResizable** | `never` | optional | [REMOVED] `view.form.splitResizable` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it made the panes of a `type: 'split'` form resizable, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerSide** | `never` | optional | [REMOVED] `view.form.drawerSide` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it. Delete the key: an object's list opens a record in its drawer from the hover icon, and the React `ObjectForm` block keeps its own `drawerSide` prop for the drawer it opens with `formType='drawer'`. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerWidth** | `never` | optional | [REMOVED] `view.form.drawerWidth` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it, and a pixel width cannot be chosen without knowing the client viewport. Delete the key: a list's record drawer takes its starting width from the `navigation.size` bucket, and the React `ObjectForm` block keeps its own `drawerWidth` prop for the drawer it opens. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **modalSize** | `never` | optional | [REMOVED] `view.form.modalSize` was removed in @objectstack/spec 19.0.0 (ADR-0049) — no form view opens in a dialog, so nothing reads it from a form view. Delete the key: the console's New and Edit dialogs lay a record out by the object's `fieldGroups` and choose their own size, a form opened by name gets a page of its own, and the React `ObjectForm` block keeps its own `modalSize` prop for the modal it opens with `formType='modal'`. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **data** | `{ provider: 'object'; object: string } \| { provider: 'value'; items: any[] } \| { provider: 'schema'; schemaId: string; schema?: Record }` | optional | Data source configuration (defaults to "object" provider) | -| **sections** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | | -| **groups** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | [LEGACY ALIAS → `sections`] Accepted for back-compat and folded onto `sections` at parse; `sections` wins when both are present. Prefer `sections`. | -| **subforms** | `{ childObject: string; relationshipField?: string; columns?: object[]; amountField?: string; … }[]` | optional | Inline master-detail child collections | -| **sharing** | `{ enabled?: boolean; publicLink?: string; password?: string; allowedDomains?: string[]; … }` | optional | Public sharing configuration for this form | -| **submitBehavior** | `{ kind: 'thank-you'; title?: string; message?: string } \| { kind: 'redirect'; url: string; delayMs?: integer } \| { kind: 'continue' } \| { kind: 'next-record' }` | optional | Post-submit behavior. On the `redirect` arm, `url` is relative-only and interpolates only declared record fields as `{{record.field_name}}`, URL-escaped. | -| **buttons** | `{ submit?: object; cancel?: object }` | optional | Form action-button visibility & labels; folded onto the flat renderer props by ObjectUI ObjectForm. | -| **defaults** | `Record` | optional | Initial field values for create-mode forms (folded into ObjectUI ObjectForm initial values;). | - ### Nested Shape: `GetUiViewResponse.protection` | Property | Type | Required | Description | @@ -1184,3 +1128,247 @@ The authoring surface of a metadata write. Closed: `copilot` is an AI assistant' --- +## PublishPackageDraftsResponse + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **success** | `boolean` | ✅ | True only when every pending draft promoted (`failed` empty) AND at least one item published. A pre-flight refusal or an ADR-0067 D2 rollback answers false on a 200 — but so does a publish with nothing to promote, so false alone is NOT a refusal: read `outcome`, not this boolean or the HTTP status. Always equal to `outcome === 'published'` (pinned), so it is also false on `published_unregistered`, where the drafts landed but an object is not served. It does NOT cover the best-effort receipts below, each of which reports its own `success`. | +| **outcome** | `Enum<'published' \| 'published_unregistered' \| 'refused' \| 'nothing_to_publish'>` | ✅ | First-class discriminant for WHICH exit answered — the fact `success` compresses into one boolean. `published`: at least one draft promoted, none refused, and the runtime registry took every promoted object. `published_unregistered`: the drafts landed exactly as on `published` — the metadata is live and stays live — but the runtime registry refused at least one promoted object, so that object is not served: until something registers it, data reads, writes and seed loads against it answer OBJECT_NOT_FOUND. `unregistered[]` names each such object; do not seed or read it before it is registered (publish it again, or restart). `refused`: the batch was refused — a pre-flight violation or the ADR-0067 D2 all-or-nothing rollback; the per-item story is in `failed[]`, which is non-empty exactly on this outcome (the invariant consumers previously had to reverse-engineer, now stated by the producer). `nothing_to_publish`: the package had no pending drafts — nothing landed AND nothing was refused; `success` stays false (a no-op is not a successful publish), which before this field made that answer indistinguishable from a refusal. Producer invariants, pinned in the conformance suites: `success === (outcome === 'published')`; `refused` if and only if `failed.length > 0`; `nothing_to_publish` if and only if `published.length === 0 && failed.length === 0`; `published_unregistered` if and only if `unregistered` is present. Values are lowercase snake, matching the `sys_metadata_audit` outcome vocabulary. | +| **publishedCount** | `integer` | ✅ | Number of drafts promoted to active — `published.length`. 0 on every refusal path (the batch is all-or-nothing, ADR-0067 D2). | +| **failedCount** | `integer` | ✅ | Number of items that did not publish — `failed.length`. On a rollback this counts the WHOLE batch: the causal item plus every sibling marked BATCH_ABORTED. | +| **published** | `{ type: string; name: string; version: string; advisories?: object[] }[]` | ✅ | Every draft promoted to active, in publish order. Empty on every refusal path. | +| **failed** | `{ type: string; name: string; error: string; code?: string; … }[]` | ✅ | Items that did not publish. Because the batch is all-or-nothing (ADR-0067 D2), a non-empty list means NOTHING landed: `published: []`, `publishedCount: 0`. | +| **unregistered** | `{ type: string; name: string; rule: Enum<'object-registry-refused'> }[]` | optional | Present ONLY on `outcome: 'published_unregistered'`, and then non-empty: each promoted object the runtime registry refused, in publish order. Every entry also appears in `published[]` — its metadata IS live, nothing was rolled back (ADR-0067 D2 runs the registration after the metadata commit) — but the object is not served until something registers it, so a caller about to seed or read it should publish it again or restart first. Absent on every other outcome; an empty array is never emitted. | +| **seedApplied** | `{ success: boolean; inserted?: integer; updated?: integer; error?: string; … }` | optional | Aggregate outcome of materializing EVERY published `seed` body in one multi-pass loader run (cross-seed references need the whole set). Present ONLY when the batch published at least one seed. Two producers, one key: the batch itself self-applies (`applySeedBodies`), and the REST door back-fills the same key for custom protocols that do not — never both (an externalId-less seed would double-insert). Best-effort: a seed problem is surfaced here, never thrown. | +| **materializeApplied** | `{ success: boolean; inserted: integer; updated: integer; failures: object[] }` | optional | ADR-0086 P2 — aggregate result of publish-time materializers across the batch (e.g. `flow`, whose draft credentials become the live ones), including side-effect failures surfaced by the per-item effects loop. Present ONLY when at least one published item had a registered materializer or a side-effect failure. Best-effort, same contract as `seedApplied`. | +| **probes** | `{ issues: object[]; checked: object }` | optional | ADR-0038 L3 post-publish runtime probe report — one real read per published artifact (seeded objects have rows, views are readable, widget dataset selections execute and return data, an object's own field-name lists resolve). `issues[]` carries the findings, each with the agent-facing `message` / `fix` and the `userMessage` sentence for the person who published; `checked` counts the probes that ran per plane. Present only when something was publishable; probes never fail the publish. | +| **commitId** | `string` | optional | ADR-0067 — id of the commit this publish recorded. Absent when nothing published. | +| **backfillApplied** | `{ success: boolean; fields: object[] }` | optional | The opt-in `backfill` request key's receipt: the literal `defaultValue` of each named field this publish added, written into the object's existing rows whose value is absent, page by page, as the caller (permissions, RLS/FLS and record hooks apply as on their own edit). Present ONLY when the request named at least one field and the batch published; absent means nothing was asked. A request that names a field this publish does not add, or one without a literal default, is refused with a 400 before anything is published, so this key never reports a refusal. | +| **unhiddenApps** | `string[]` | optional | ADR-0045 §3 — names of the apps whose `_unpublished` gate this publish cleared (publish = live AND visible; a materialized additive build has no drafts, only this flip). Attached by the REST door, not the protocol helper. Present ONLY when at least one app flipped — on a mid-loop failure it names the apps that DID persist, beside `unhideError` ('s split report). Spelling is a permanent wire contract (see the door's note). | +| **unhideError** | `string` | optional | Present when the ADR-0045 visibility flip failed (wholly or partway): the drafts ARE published, but apps still stored `_unpublished: true` stay externally unobservable. Client-facing text only — undeclared driver text is withheld per ADR-0112; the full cause is in the server log. The route is idempotent: re-run it once the cause is resolved. | +| **rebindError** | `string` | optional | Present when the post-publish `metadata:reloaded` announce failed: everything is published and stored, but boot-cached consumers keep the pre-publish view until re-run or restart (a newly published record-triggered flow does not bind its trigger). Client-facing text only, same ADR-0112 withhold as `unhideError`. | + +### Nested Shape: `PublishPackageDraftsResponse.published[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | Metadata type of the promoted draft (canonical singular). | +| **name** | `string` | ✅ | Item name of the promoted draft. | +| **version** | `string` | ✅ | Version token of the promoted row — the same keyed ADR-0008 optimistic-concurrency token the single-item doors return: echo it back as `If-Match` on the next write to this item. A keyed digest of the stored content hash, never the hash itself. Opaque to callers; currently `hmac-sha256:` plus 64 hex characters, but the format is not part of this contract. | +| **advisories** | `{ rule: string; path: string; where: string; message: string; … }[]` | optional | Non-gating findings the runtime authoring gate raised against THIS draft's promotion (the same element shape and the same omitted-when-empty discipline as `PublishMetaItemResponseSchema.advisories`, riding each element rather than a parallel top-level map). Present ONLY when at least one finding was raised — an empty array is never emitted, so an advisory-free batch's response bytes are unchanged. Advisory by construction: every entry is `warning`/`info`, because an `error` finding refuses the promotion and — the batch being all-or-nothing — aborts the whole batch as `failed[]` instead; `failed[]` elements never carry this key. | + +### Nested Shape: `PublishPackageDraftsResponse.failed[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | Metadata type of the item that did not publish. | +| **name** | `string` | ✅ | Item name. | +| **error** | `string` | ✅ | What refused it. On a rollback, the causal item carries its real error and every sibling carries the all-or-nothing explanation. A refusal that produced structured findings states a one-sentence HEADLINE here (what failed, where, which rules, how many); the per-path detail rides `issues[]` instead of being restated in this string (consumers rendering both channels were showing every finding twice). | +| **code** | `string` | optional | Machine code for the refusal class (SCREAMING_SNAKE, ADR-0112 vocabulary) — e.g. a pre-flight violation code, or BATCH_ABORTED on the non-causal items of a rolled-back batch. | +| **issues** | `{ rule: string; path: string; where: string; message: string; … }[]` | optional | The structured findings behind the refusal, when the refusing error carried them — today the author-time gate's INVALID_METADATA refusal on the causal item. The producer has emitted this key; declaring it is what lets a typed consumer read it back, and what lets `error` stay a headline without losing the per-path detail. Same element shape as `published[].advisories` and the single-item 422's `issues[]` (— one dialect, declared once). Present ONLY on the causal item and only when the refusal produced structured findings; BATCH_ABORTED siblings never carry it. Absent means "this refusal carried no structured findings", never "no problems". | + +### Nested Shape: `PublishPackageDraftsResponse.unregistered[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | Metadata type of the published item the registry refused (`object`). | +| **name** | `string` | ✅ | Name of the object that is published but not served. | +| **rule** | `Enum<'object-registry-refused'>` | ✅ | Why it is not served, as a stable rule id: the same id as the warning on this object's `published[]` element, whose `message` and `hint` say what happened and how to fix it. | + +### Nested Shape: `PublishPackageDraftsResponse.seedApplied` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **success** | `boolean` | ✅ | False when the seed rows did not fully land. The publish itself still succeeded — check this rather than assuming data went live. | +| **inserted** | `integer` | optional | Rows created by the externalId-keyed upsert. Optional ONLY because the route-level fallback producer (custom protocols that do not self-apply) reports early failures without counters; the in-batch producer always emits both counters. | +| **updated** | `integer` | optional | Rows updated by the externalId-keyed upsert. Same optionality rationale as `inserted`. | +| **error** | `string` | optional | Single failure message, present when the apply failed before the loader ran (including "no readable seed bodies"). When the failure is the seed bodies' own schema refusal, this is a one-sentence headline and the per-path detail rides `issues[]`. | +| **errors** | `any[]` | optional | Per-record failures reported by the seed loader, plus any seed-body read failures. May be present and empty on a clean load. | +| **issues** | `{ path: string; message: string; code?: string }[]` | optional | Structured spec-validation findings behind `error`, present when the apply was refused by the seed bodies' own schema — the declared 422 `seedRequestValidationError` mints. The per-path detail lives HERE, once; `error` stays a one-sentence headline. Absent on non-validation failures (driver faults, unreadable bodies), whose whole story is `error` / `errors[]`. | +| **landed** | `{ object: string; inserted: object; matched: object }[]` | optional | Per object, the stored rows the seed landed on: `inserted` (created by this publish) and `matched` (pre-existing rows a seed key matched), each capped at `SEED_APPLIED_LANDED_IDS_CAP` (200) ids with `total` and `truncated` stating any cut. One entry per object the loader ran, empty lists included. When the load threw part-way (`success: false` with `error`), it lists only the datasets that FINISHED before the throw, and is EMPTY when none had; the dataset that threw is not listed (its rows are in the counts, its object in `error`). ABSENT means "not reported" — the apply failed before any load ran (see `error`), or the producer reports no ids — never "no rows landed". | + +### Nested Shape: `PublishPackageDraftsResponse.materializeApplied` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **success** | `boolean` | ✅ | False when any item's materializer failed; the publish still succeeded. | +| **inserted** | `integer` | ✅ | Data-plane rows created across the batch. | +| **updated** | `integer` | ✅ | Data-plane rows updated across the batch. | +| **failures** | `{ type: string; name: string; error: string }[]` | ✅ | Each item whose data-plane projection did NOT land — named per-item, unlike the single-item door's scalar `error`, because one aggregate boolean over N items would hide WHICH ones never went live. | + +### Nested Shape: `PublishPackageDraftsResponse.probes` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **issues** | `{ layer: 'runtime'; severity: Enum<'error' \| 'warning'>; artifact: object; ref?: object; … }[]` | ✅ | The findings, in probe order (seeds, views, objects, dashboard widgets). Empty when every probe passed. | +| **checked** | `{ seeds: integer; views: integer; widgets: integer; objects: integer }` | ✅ | How many probes actually ran, per plane. A 0 means nothing of that kind was probed, never that something was probed and passed: read it beside `issues`, so that "no object was inspected" and "every object was clean" are different numbers. | + +### Nested Shape: `PublishPackageDraftsResponse.backfillApplied` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **success** | `boolean` | ✅ | False when any field stopped short (its entry carries `error`). The publish itself still succeeded and is not undone. | +| **fields** | `{ object: string; field: string; updated: integer; error?: string; … }[]` | ✅ | One element per requested field, in request order. | + + +--- + +## RealtimeConnectRequest + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **transport** | `Enum<'websocket' \| 'sse' \| 'polling'>` | optional | Preferred transport protocol | +| **channels** | `string[]` | optional | Channels to subscribe to on connect | +| **token** | `string` | optional | Authentication token | + + +--- + +## RealtimeConnectResponse + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **connectionId** | `string` | ✅ | Unique connection identifier | +| **transport** | `Enum<'websocket' \| 'sse' \| 'polling'>` | ✅ | Negotiated transport protocol | +| **url** | `string` | optional | WebSocket/SSE endpoint URL | + + +--- + +## RealtimeDisconnectRequest + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **connectionId** | `string` | optional | Connection ID to disconnect | + + +--- + +## RealtimeDisconnectResponse + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **success** | `boolean` | ✅ | Whether disconnection succeeded | + + +--- + +## RealtimeSubscribeRequest + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **channel** | `string` | ✅ | Channel name to subscribe to | +| **events** | `string[]` | optional | Specific event types to listen for | +| **filter** | `Record` | optional | Event filter criteria | + + +--- + +## RealtimeSubscribeResponse + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **subscriptionId** | `string` | ✅ | Unique subscription identifier | +| **channel** | `string` | ✅ | Subscribed channel name | + + +--- + +## RealtimeUnsubscribeRequest + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **subscriptionId** | `string` | ✅ | Subscription ID to cancel | + + +--- + +## RealtimeUnsubscribeResponse + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **success** | `boolean` | ✅ | Whether unsubscription succeeded | + + +--- + +## RegisterDeviceRequest + +Register or refresh a push device for the signed-in user + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **token** | `string` | ✅ | Device push notification token | +| **platform** | `Enum<'ios' \| 'android' \| 'web'>` | ✅ | Device platform | +| **deviceId** | `string` | optional | Client-held device id, stable per app install. Re-registering the same deviceId refreshes that device; absent, the server mints one and answers it, and the client keeps it for later registrations and unregister | +| **name** | `string` | optional | Device friendly name | +| **vendor** | `Enum<'apns' \| 'fcm'>` | optional | Push vendor the token belongs to: apns or fcm. Absent, the server derives it from platform: ios means apns, android means fcm. web has no default vendor: a web registration names apns or fcm, and one without vendor is refused | +| **appId** | `string` | optional | App the token was issued to: the iOS bundle ID or the Android application ID | +| **locale** | `string` | optional | Device locale (BCP 47, for example zh-CN). Stored on the device row; no push renders by it: a push arrives in the recipient's language (sys_user.locale, then the deployment default) | +| **origin** | `string` | optional | The origin the Console was loaded from (window.location.origin, for example https://crm.example.com): the address the mobile shell saved for this server. The Console writes it; the server stores it on the device row and every push to the device carries it back, so a shell with several saved servers opens the push on the one that sent it. http or https, a lowercase host and an optional port; a path, another scheme or a bare host is refused | + + +--- + +## RegisterDeviceResponse + +Answer to a device registration: the device id the client keeps + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **deviceId** | `string` | ✅ | Registered device ID | +| **success** | `boolean` | ✅ | Whether registration succeeded | + + +--- + +## RejectAiPendingActionResponse + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **status** | `'rejected'` | ✅ | Always "rejected" | +| **id** | `string` | ✅ | The rejected action id | + + +--- + +## RollbackMetaItemRequest + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | Metadata type name | +| **name** | `string` | ✅ | Item name | +| **toVersion** | `integer` | ✅ | The history version whose body is restored as the new live row: a whole number of at least 1, as the history lists it. The rollback door reads this declaration and refuses anything else `400`. | +| **message** | `string` | optional | Rollback note, recorded on the new history row. | +| **member** | `string` | optional | Bundle member selector, for a metadata type whose identity is a pair (today only `email_template`, identified by `(name, locale)`): the member this request addresses, spelled as its discriminator value (`zh-CN`). Absent, the canonical member (`en-US` for `email_template`), which is what a bare-name read answers; naming the canonical value is the same request. It is not the response translation locale, which `?locale=` and `Accept-Language` choose. Refused with 400 `VALIDATION_ERROR` on a type that has no members, and for a blank value or one longer than a stored member can be (100 characters). A well-formed member with nothing stored or shipped answers as that door answers an absent item. | +| **packageId** | `string` | optional | Optional package ID (`?package=` on the REST door, the `/layers` spelling) — for a type stored per (package, name), the holder whose versions to address: the slot of the row a read naming the package serves (its own row, its `.custom` pair's declared override, or the package-less row that read falls back to), else the package's own empty slot when it ships the name; a package that neither holds nor ships the name is refused 409 `not-held-by-qualifier` (ADR-0150 D3/D4). Versions attributed to no package, or to the environment, are that slot's only while it is the name's sole slot. Absent, a name two holders hold (in stored rows or in code) is refused 409 naming every holder, except where the read naming no package serves the row-held base (a bundled type's member of a name no package ships in code, whose active rows a base package and one or more packages declaring it hold, with no package-unbound row beside them): there the base's slot is addressed, as naming the base addresses it. Two packages neither of which declares the other are still refused. Refused with 400 `VALIDATION_ERROR` on a type not stored per (package, name). | + + +--- + diff --git a/packages/spec/docs/references/api/protocol.part-3.md b/packages/spec/docs/references/api/protocol.part-3.md index 2ba9f948afe..a085e7ddee6 100644 --- a/packages/spec/docs/references/api/protocol.part-3.md +++ b/packages/spec/docs/references/api/protocol.part-3.md @@ -4,250 +4,6 @@ > Part 3 of [Protocol schema — API Protocol reference](protocol.md), which lists every part. ---- - -## PublishPackageDraftsResponse - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **success** | `boolean` | ✅ | True only when every pending draft promoted (`failed` empty) AND at least one item published. A pre-flight refusal or an ADR-0067 D2 rollback answers false on a 200 — but so does a publish with nothing to promote, so false alone is NOT a refusal: read `outcome`, not this boolean or the HTTP status. Always equal to `outcome === 'published'` (pinned), so it is also false on `published_unregistered`, where the drafts landed but an object is not served. It does NOT cover the best-effort receipts below, each of which reports its own `success`. | -| **outcome** | `Enum<'published' \| 'published_unregistered' \| 'refused' \| 'nothing_to_publish'>` | ✅ | First-class discriminant for WHICH exit answered — the fact `success` compresses into one boolean. `published`: at least one draft promoted, none refused, and the runtime registry took every promoted object. `published_unregistered`: the drafts landed exactly as on `published` — the metadata is live and stays live — but the runtime registry refused at least one promoted object, so that object is not served: until something registers it, data reads, writes and seed loads against it answer OBJECT_NOT_FOUND. `unregistered[]` names each such object; do not seed or read it before it is registered (publish it again, or restart). `refused`: the batch was refused — a pre-flight violation or the ADR-0067 D2 all-or-nothing rollback; the per-item story is in `failed[]`, which is non-empty exactly on this outcome (the invariant consumers previously had to reverse-engineer, now stated by the producer). `nothing_to_publish`: the package had no pending drafts — nothing landed AND nothing was refused; `success` stays false (a no-op is not a successful publish), which before this field made that answer indistinguishable from a refusal. Producer invariants, pinned in the conformance suites: `success === (outcome === 'published')`; `refused` if and only if `failed.length > 0`; `nothing_to_publish` if and only if `published.length === 0 && failed.length === 0`; `published_unregistered` if and only if `unregistered` is present. Values are lowercase snake, matching the `sys_metadata_audit` outcome vocabulary. | -| **publishedCount** | `integer` | ✅ | Number of drafts promoted to active — `published.length`. 0 on every refusal path (the batch is all-or-nothing, ADR-0067 D2). | -| **failedCount** | `integer` | ✅ | Number of items that did not publish — `failed.length`. On a rollback this counts the WHOLE batch: the causal item plus every sibling marked BATCH_ABORTED. | -| **published** | `{ type: string; name: string; version: string; advisories?: object[] }[]` | ✅ | Every draft promoted to active, in publish order. Empty on every refusal path. | -| **failed** | `{ type: string; name: string; error: string; code?: string; … }[]` | ✅ | Items that did not publish. Because the batch is all-or-nothing (ADR-0067 D2), a non-empty list means NOTHING landed: `published: []`, `publishedCount: 0`. | -| **unregistered** | `{ type: string; name: string; rule: Enum<'object-registry-refused'> }[]` | optional | Present ONLY on `outcome: 'published_unregistered'`, and then non-empty: each promoted object the runtime registry refused, in publish order. Every entry also appears in `published[]` — its metadata IS live, nothing was rolled back (ADR-0067 D2 runs the registration after the metadata commit) — but the object is not served until something registers it, so a caller about to seed or read it should publish it again or restart first. Absent on every other outcome; an empty array is never emitted. | -| **seedApplied** | `{ success: boolean; inserted?: integer; updated?: integer; error?: string; … }` | optional | Aggregate outcome of materializing EVERY published `seed` body in one multi-pass loader run (cross-seed references need the whole set). Present ONLY when the batch published at least one seed. Two producers, one key: the batch itself self-applies (`applySeedBodies`), and the REST door back-fills the same key for custom protocols that do not — never both (an externalId-less seed would double-insert). Best-effort: a seed problem is surfaced here, never thrown. | -| **materializeApplied** | `{ success: boolean; inserted: integer; updated: integer; failures: object[] }` | optional | ADR-0086 P2 — aggregate result of publish-time materializers across the batch (e.g. `flow`, whose draft credentials become the live ones), including side-effect failures surfaced by the per-item effects loop. Present ONLY when at least one published item had a registered materializer or a side-effect failure. Best-effort, same contract as `seedApplied`. | -| **probes** | `{ issues: object[]; checked: object }` | optional | ADR-0038 L3 post-publish runtime probe report — one real read per published artifact (seeded objects have rows, views are readable, widget dataset selections execute and return data, an object's own field-name lists resolve). `issues[]` carries the findings, each with the agent-facing `message` / `fix` and the `userMessage` sentence for the person who published; `checked` counts the probes that ran per plane. Present only when something was publishable; probes never fail the publish. | -| **commitId** | `string` | optional | ADR-0067 — id of the commit this publish recorded. Absent when nothing published. | -| **backfillApplied** | `{ success: boolean; fields: object[] }` | optional | The opt-in `backfill` request key's receipt: the literal `defaultValue` of each named field this publish added, written into the object's existing rows whose value is absent, page by page, as the caller (permissions, RLS/FLS and record hooks apply as on their own edit). Present ONLY when the request named at least one field and the batch published; absent means nothing was asked. A request that names a field this publish does not add, or one without a literal default, is refused with a 400 before anything is published, so this key never reports a refusal. | -| **unhiddenApps** | `string[]` | optional | ADR-0045 §3 — names of the apps whose `_unpublished` gate this publish cleared (publish = live AND visible; a materialized additive build has no drafts, only this flip). Attached by the REST door, not the protocol helper. Present ONLY when at least one app flipped — on a mid-loop failure it names the apps that DID persist, beside `unhideError` ('s split report). Spelling is a permanent wire contract (see the door's note). | -| **unhideError** | `string` | optional | Present when the ADR-0045 visibility flip failed (wholly or partway): the drafts ARE published, but apps still stored `_unpublished: true` stay externally unobservable. Client-facing text only — undeclared driver text is withheld per ADR-0112; the full cause is in the server log. The route is idempotent: re-run it once the cause is resolved. | -| **rebindError** | `string` | optional | Present when the post-publish `metadata:reloaded` announce failed: everything is published and stored, but boot-cached consumers keep the pre-publish view until re-run or restart (a newly published record-triggered flow does not bind its trigger). Client-facing text only, same ADR-0112 withhold as `unhideError`. | - -### Nested Shape: `PublishPackageDraftsResponse.published[number]` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **type** | `string` | ✅ | Metadata type of the promoted draft (canonical singular). | -| **name** | `string` | ✅ | Item name of the promoted draft. | -| **version** | `string` | ✅ | Version token of the promoted row — the same keyed ADR-0008 optimistic-concurrency token the single-item doors return: echo it back as `If-Match` on the next write to this item. A keyed digest of the stored content hash, never the hash itself. Opaque to callers; currently `hmac-sha256:` plus 64 hex characters, but the format is not part of this contract. | -| **advisories** | `{ rule: string; path: string; where: string; message: string; … }[]` | optional | Non-gating findings the runtime authoring gate raised against THIS draft's promotion (the same element shape and the same omitted-when-empty discipline as `PublishMetaItemResponseSchema.advisories`, riding each element rather than a parallel top-level map). Present ONLY when at least one finding was raised — an empty array is never emitted, so an advisory-free batch's response bytes are unchanged. Advisory by construction: every entry is `warning`/`info`, because an `error` finding refuses the promotion and — the batch being all-or-nothing — aborts the whole batch as `failed[]` instead; `failed[]` elements never carry this key. | - -### Nested Shape: `PublishPackageDraftsResponse.failed[number]` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **type** | `string` | ✅ | Metadata type of the item that did not publish. | -| **name** | `string` | ✅ | Item name. | -| **error** | `string` | ✅ | What refused it. On a rollback, the causal item carries its real error and every sibling carries the all-or-nothing explanation. A refusal that produced structured findings states a one-sentence HEADLINE here (what failed, where, which rules, how many); the per-path detail rides `issues[]` instead of being restated in this string (consumers rendering both channels were showing every finding twice). | -| **code** | `string` | optional | Machine code for the refusal class (SCREAMING_SNAKE, ADR-0112 vocabulary) — e.g. a pre-flight violation code, or BATCH_ABORTED on the non-causal items of a rolled-back batch. | -| **issues** | `{ rule: string; path: string; where: string; message: string; … }[]` | optional | The structured findings behind the refusal, when the refusing error carried them — today the author-time gate's INVALID_METADATA refusal on the causal item. The producer has emitted this key; declaring it is what lets a typed consumer read it back, and what lets `error` stay a headline without losing the per-path detail. Same element shape as `published[].advisories` and the single-item 422's `issues[]` (— one dialect, declared once). Present ONLY on the causal item and only when the refusal produced structured findings; BATCH_ABORTED siblings never carry it. Absent means "this refusal carried no structured findings", never "no problems". | - -### Nested Shape: `PublishPackageDraftsResponse.unregistered[number]` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **type** | `string` | ✅ | Metadata type of the published item the registry refused (`object`). | -| **name** | `string` | ✅ | Name of the object that is published but not served. | -| **rule** | `Enum<'object-registry-refused'>` | ✅ | Why it is not served, as a stable rule id: the same id as the warning on this object's `published[]` element, whose `message` and `hint` say what happened and how to fix it. | - -### Nested Shape: `PublishPackageDraftsResponse.seedApplied` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **success** | `boolean` | ✅ | False when the seed rows did not fully land. The publish itself still succeeded — check this rather than assuming data went live. | -| **inserted** | `integer` | optional | Rows created by the externalId-keyed upsert. Optional ONLY because the route-level fallback producer (custom protocols that do not self-apply) reports early failures without counters; the in-batch producer always emits both counters. | -| **updated** | `integer` | optional | Rows updated by the externalId-keyed upsert. Same optionality rationale as `inserted`. | -| **error** | `string` | optional | Single failure message, present when the apply failed before the loader ran (including "no readable seed bodies"). When the failure is the seed bodies' own schema refusal, this is a one-sentence headline and the per-path detail rides `issues[]`. | -| **errors** | `any[]` | optional | Per-record failures reported by the seed loader, plus any seed-body read failures. May be present and empty on a clean load. | -| **issues** | `{ path: string; message: string; code?: string }[]` | optional | Structured spec-validation findings behind `error`, present when the apply was refused by the seed bodies' own schema — the declared 422 `seedRequestValidationError` mints. The per-path detail lives HERE, once; `error` stays a one-sentence headline. Absent on non-validation failures (driver faults, unreadable bodies), whose whole story is `error` / `errors[]`. | -| **landed** | `{ object: string; inserted: object; matched: object }[]` | optional | Per object, the stored rows the seed landed on: `inserted` (created by this publish) and `matched` (pre-existing rows a seed key matched), each capped at `SEED_APPLIED_LANDED_IDS_CAP` (200) ids with `total` and `truncated` stating any cut. One entry per object the loader ran, empty lists included. When the load threw part-way (`success: false` with `error`), it lists only the datasets that FINISHED before the throw, and is EMPTY when none had; the dataset that threw is not listed (its rows are in the counts, its object in `error`). ABSENT means "not reported" — the apply failed before any load ran (see `error`), or the producer reports no ids — never "no rows landed". | - -### Nested Shape: `PublishPackageDraftsResponse.materializeApplied` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **success** | `boolean` | ✅ | False when any item's materializer failed; the publish still succeeded. | -| **inserted** | `integer` | ✅ | Data-plane rows created across the batch. | -| **updated** | `integer` | ✅ | Data-plane rows updated across the batch. | -| **failures** | `{ type: string; name: string; error: string }[]` | ✅ | Each item whose data-plane projection did NOT land — named per-item, unlike the single-item door's scalar `error`, because one aggregate boolean over N items would hide WHICH ones never went live. | - -### Nested Shape: `PublishPackageDraftsResponse.probes` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **issues** | `{ layer: 'runtime'; severity: Enum<'error' \| 'warning'>; artifact: object; ref?: object; … }[]` | ✅ | The findings, in probe order (seeds, views, objects, dashboard widgets). Empty when every probe passed. | -| **checked** | `{ seeds: integer; views: integer; widgets: integer; objects: integer }` | ✅ | How many probes actually ran, per plane. A 0 means nothing of that kind was probed, never that something was probed and passed: read it beside `issues`, so that "no object was inspected" and "every object was clean" are different numbers. | - -### Nested Shape: `PublishPackageDraftsResponse.backfillApplied` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **success** | `boolean` | ✅ | False when any field stopped short (its entry carries `error`). The publish itself still succeeded and is not undone. | -| **fields** | `{ object: string; field: string; updated: integer; error?: string; … }[]` | ✅ | One element per requested field, in request order. | - - ---- - -## RealtimeConnectRequest - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **transport** | `Enum<'websocket' \| 'sse' \| 'polling'>` | optional | Preferred transport protocol | -| **channels** | `string[]` | optional | Channels to subscribe to on connect | -| **token** | `string` | optional | Authentication token | - - ---- - -## RealtimeConnectResponse - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **connectionId** | `string` | ✅ | Unique connection identifier | -| **transport** | `Enum<'websocket' \| 'sse' \| 'polling'>` | ✅ | Negotiated transport protocol | -| **url** | `string` | optional | WebSocket/SSE endpoint URL | - - ---- - -## RealtimeDisconnectRequest - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **connectionId** | `string` | optional | Connection ID to disconnect | - - ---- - -## RealtimeDisconnectResponse - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **success** | `boolean` | ✅ | Whether disconnection succeeded | - - ---- - -## RealtimeSubscribeRequest - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **channel** | `string` | ✅ | Channel name to subscribe to | -| **events** | `string[]` | optional | Specific event types to listen for | -| **filter** | `Record` | optional | Event filter criteria | - - ---- - -## RealtimeSubscribeResponse - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **subscriptionId** | `string` | ✅ | Unique subscription identifier | -| **channel** | `string` | ✅ | Subscribed channel name | - - ---- - -## RealtimeUnsubscribeRequest - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **subscriptionId** | `string` | ✅ | Subscription ID to cancel | - - ---- - -## RealtimeUnsubscribeResponse - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **success** | `boolean` | ✅ | Whether unsubscription succeeded | - - ---- - -## RegisterDeviceRequest - -Register or refresh a push device for the signed-in user - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **token** | `string` | ✅ | Device push notification token | -| **platform** | `Enum<'ios' \| 'android' \| 'web'>` | ✅ | Device platform | -| **deviceId** | `string` | optional | Client-held device id, stable per app install. Re-registering the same deviceId refreshes that device; absent, the server mints one and answers it, and the client keeps it for later registrations and unregister | -| **name** | `string` | optional | Device friendly name | -| **vendor** | `Enum<'apns' \| 'fcm'>` | optional | Push vendor the token belongs to: apns or fcm. Absent, the server derives it from platform: ios means apns, android means fcm. web has no default vendor: a web registration names apns or fcm, and one without vendor is refused | -| **appId** | `string` | optional | App the token was issued to: the iOS bundle ID or the Android application ID | -| **locale** | `string` | optional | Device locale (BCP 47, for example zh-CN). Stored on the device row; no push renders by it: a push arrives in the recipient's language (sys_user.locale, then the deployment default) | -| **origin** | `string` | optional | The origin the Console was loaded from (window.location.origin, for example https://crm.example.com): the address the mobile shell saved for this server. The Console writes it; the server stores it on the device row and every push to the device carries it back, so a shell with several saved servers opens the push on the one that sent it. http or https, a lowercase host and an optional port; a path, another scheme or a bare host is refused | - - ---- - -## RegisterDeviceResponse - -Answer to a device registration: the device id the client keeps - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **deviceId** | `string` | ✅ | Registered device ID | -| **success** | `boolean` | ✅ | Whether registration succeeded | - - ---- - -## RejectAiPendingActionResponse - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **status** | `'rejected'` | ✅ | Always "rejected" | -| **id** | `string` | ✅ | The rejected action id | - - ---- - -## RollbackMetaItemRequest - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **type** | `string` | ✅ | Metadata type name | -| **name** | `string` | ✅ | Item name | -| **toVersion** | `integer` | ✅ | The history version whose body is restored as the new live row: a whole number of at least 1, as the history lists it. The rollback door reads this declaration and refuses anything else `400`. | -| **message** | `string` | optional | Rollback note, recorded on the new history row. | -| **member** | `string` | optional | Bundle member selector, for a metadata type whose identity is a pair (today only `email_template`, identified by `(name, locale)`): the member this request addresses, spelled as its discriminator value (`zh-CN`). Absent, the canonical member (`en-US` for `email_template`), which is what a bare-name read answers; naming the canonical value is the same request. It is not the response translation locale, which `?locale=` and `Accept-Language` choose. Refused with 400 `VALIDATION_ERROR` on a type that has no members, and for a blank value or one longer than a stored member can be (100 characters). A well-formed member with nothing stored or shipped answers as that door answers an absent item. | -| **packageId** | `string` | optional | Optional package ID (`?package=` on the REST door, the `/layers` spelling) — for a type stored per (package, name), the holder whose versions to address: the slot of the row a read naming the package serves (its own row, its `.custom` pair's declared override, or the package-less row that read falls back to), else the package's own empty slot when it ships the name; a package that neither holds nor ships the name is refused 409 `not-held-by-qualifier` (ADR-0150 D3/D4). Versions attributed to no package, or to the environment, are that slot's only while it is the name's sole slot. Absent, a name two holders hold (in stored rows or in code) is refused 409 naming every holder, except where the read naming no package serves the row-held base (a bundled type's member of a name no package ships in code, whose active rows a base package and one or more packages declaring it hold, with no package-unbound row beside them): there the base's slot is addressed, as naming the base addresses it. Two packages neither of which declares the other are still refused. Refused with 400 `VALIDATION_ERROR` on a type not stored per (package, name). | - - --- ## RollbackMetaItemResponse diff --git a/packages/spec/docs/references/system/translation.md b/packages/spec/docs/references/system/translation.md index e24a4358521..58712ea1155 100644 --- a/packages/spec/docs/references/system/translation.md +++ b/packages/spec/docs/references/system/translation.md @@ -88,7 +88,7 @@ Translation data for a single object | **pluralLabel** | `string` | optional | Translated plural label | | **description** | `string` | optional | Translated object description | | **fields** | `Record; … }>` | optional | Field-level translations | -| **_views** | `Record` | optional | View translations keyed by view name | +| **_views** | `Record }>` | optional | View translations keyed by view name | | **_actions** | `Record` | optional | Action translations keyed by action name | | **_sections** | `Record }>` | optional | Section translations keyed by section name | | **_tabs** | `Record` | optional | Filter-preset tab translations keyed by tab name | @@ -115,8 +115,8 @@ Translation data for a single field | :--- | :--- | :--- | :--- | | **label** | `string` | optional | Translated view label | | **description** | `string` | optional | Translated view description | -| **title** | `string` | optional | Translated form view title — overlays a form view's own `title` (`FormViewSchema.title`); only a form that authors one is translated | -| **submitBehavior** | `{ title?: string; message?: string }` | optional | Translated thank-you panel copy — overlays a form view's `submitBehavior` `title` / `message` when its `kind` is `'thank-you'`; only copy the form authors is translated | +| **title** | `never` | optional | [REMOVED] `translation.objects.OBJECT._views.KEY.title` was removed in @objectstack/spec 19.0.0 (ADR-0159 D8) — a form is a `form` item, and no view carries a heading. Move the string to `forms['OBJECT.KEY'].title`, the address the translator reads a form's heading from. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +| **submitBehavior** | `never` | optional | [REMOVED] `translation.objects.OBJECT._views.KEY.submitBehavior` was removed in @objectstack/spec 19.0.0 (ADR-0159 D8) — a form is a `form` item, and no view has a thank-you panel. Move the `title` and `message` to `forms['OBJECT.KEY'].submitBehavior`, the address the translator reads a form's panel from. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **emptyState** | `{ title?: string; message?: string }` | optional | Translated empty-state copy shown when the view has no rows | | **bulkActions** | `Record }>` | optional | Selection-bar translations keyed by bulk-action def name (`BulkActionDefSchema.name`) | @@ -221,7 +221,7 @@ Translation data for a single object | **pluralLabel** | `string` | optional | Translated plural label | | **description** | `string` | optional | Translated object description | | **fields** | `Record; … }>` | optional | Field-level translations | -| **_views** | `Record` | optional | View translations keyed by view name | +| **_views** | `Record }>` | optional | View translations keyed by view name | | **_actions** | `Record` | optional | Action translations keyed by action name | | **_sections** | `Record }>` | optional | Section translations keyed by section name | | **_tabs** | `Record` | optional | Filter-preset tab translations keyed by tab name | @@ -432,7 +432,7 @@ Translation data for a single object | **pluralLabel** | `string` | optional | Translated plural label | | **description** | `string` | optional | Translated object description | | **fields** | `Record; … }>` | optional | Field-level translations | -| **_views** | `Record` | optional | View translations keyed by view name | +| **_views** | `Record }>` | optional | View translations keyed by view name | | **_actions** | `Record` | optional | Action translations keyed by action name | | **_sections** | `Record }>` | optional | Section translations keyed by section name | | **_tabs** | `Record` | optional | Filter-preset tab translations keyed by tab name | @@ -706,7 +706,7 @@ Translation data for a single object | **pluralLabel** | `string` | optional | Translated plural label | | **description** | `string` | optional | Translated object description | | **fields** | `Record; … }>` | optional | Field-level translations | -| **_views** | `Record` | optional | View translations keyed by view name | +| **_views** | `Record }>` | optional | View translations keyed by view name | | **_actions** | `Record` | optional | Action translations keyed by action name | | **_sections** | `Record }>` | optional | Section translations keyed by section name | | **_tabs** | `Record` | optional | Filter-preset tab translations keyed by tab name | @@ -949,7 +949,7 @@ Translation data for a single object | **pluralLabel** | `string` | optional | Translated plural label | | **description** | `string` | optional | Translated object description | | **fields** | `Record; … }>` | optional | Field-level translations | -| **_views** | `Record` | optional | View translations keyed by view name | +| **_views** | `Record }>` | optional | View translations keyed by view name | | **_actions** | `Record` | optional | Action translations keyed by action name | | **_sections** | `Record }>` | optional | Section translations keyed by section name | | **_tabs** | `Record` | optional | Filter-preset tab translations keyed by tab name | diff --git a/packages/spec/dropped-refinements.baseline.json b/packages/spec/dropped-refinements.baseline.json index eb97e8de57f..4f0ac8131fd 100644 --- a/packages/spec/dropped-refinements.baseline.json +++ b/packages/spec/dropped-refinements.baseline.json @@ -3,7 +3,7 @@ "measured": { "zod": "4.4.3", "publishedSchemasWithDroppedRefinements": 284, - "droppedRefinementSites": 1262, + "droppedRefinementSites": 1242, "refinementSitesThatDidProject": 728, "refinementSitesWithNoJsonFormToCompare": 0 }, @@ -249,7 +249,6 @@ "manifest.translations.element.valueType.flows.valueType.screens.valueType.description", "manifest.translations.element.valueType.flows.valueType.screens.valueType.title", "manifest.translations.element.valueType.flows.valueType.successMessage", - "manifest.views.element.form", "manifest.views.element.list", "manifest.views.element.list.bulkActionDefs.element", "manifest.views.element.list.emptyState.link.url", @@ -448,7 +447,6 @@ "data.options[1].manifest.translations.element.valueType.flows.valueType.screens.valueType.description", "data.options[1].manifest.translations.element.valueType.flows.valueType.screens.valueType.title", "data.options[1].manifest.translations.element.valueType.flows.valueType.successMessage", - "data.options[1].manifest.views.element.form", "data.options[1].manifest.views.element.list", "data.options[1].manifest.views.element.list.bulkActionDefs.element", "data.options[1].manifest.views.element.list.emptyState.link.url", @@ -502,10 +500,6 @@ }, "api/GetUiViewResponse": { "sites": [ - "form", - "form.sections.element", - "form.subforms.element.columns.element", - "form.submitBehavior.options[1].url", "list", "list.bulkActionDefs.element", "list.emptyState.link.url", @@ -634,7 +628,6 @@ "options[1].manifest.translations.element.valueType.flows.valueType.screens.valueType.description", "options[1].manifest.translations.element.valueType.flows.valueType.screens.valueType.title", "options[1].manifest.translations.element.valueType.flows.valueType.successMessage", - "options[1].manifest.views.element.form", "options[1].manifest.views.element.list", "options[1].manifest.views.element.list.bulkActionDefs.element", "options[1].manifest.views.element.list.emptyState.link.url", @@ -744,7 +737,6 @@ "data.packages.element.options[1].manifest.translations.element.valueType.flows.valueType.screens.valueType.description", "data.packages.element.options[1].manifest.translations.element.valueType.flows.valueType.screens.valueType.title", "data.packages.element.options[1].manifest.translations.element.valueType.flows.valueType.successMessage", - "data.packages.element.options[1].manifest.views.element.form", "data.packages.element.options[1].manifest.views.element.list", "data.packages.element.options[1].manifest.views.element.list.bulkActionDefs.element", "data.packages.element.options[1].manifest.views.element.list.emptyState.link.url", @@ -2315,10 +2307,6 @@ }, "ui/View": { "sites": [ - "form", - "form.sections.element", - "form.subforms.element.columns.element", - "form.submitBehavior.options[1].url", "list", "list.bulkActionDefs.element", "list.emptyState.link.url", @@ -2356,11 +2344,7 @@ "options[0].config.gantt.groupByField", "options[0].config.grouping.fields.element.field", "options[0].config.kanban.groupByField", - "options[0].config.timeline.groupByField", - "options[1].config", - "options[1].config.sections.element", - "options[1].config.subforms.element.columns.element", - "options[1].config.submitBehavior.options[1].url" + "options[0].config.timeline.groupByField" ] }, "ui/ViewItemWire": { @@ -2373,11 +2357,7 @@ "options[0].config.gantt.groupByField", "options[0].config.grouping.fields.element.field", "options[0].config.kanban.groupByField", - "options[0].config.timeline.groupByField", - "options[1].config", - "options[1].config.sections.element", - "options[1].config.subforms.element.columns.element", - "options[1].config.submitBehavior.options[1].url" + "options[0].config.timeline.groupByField" ] }, "ui/ViewTab": { diff --git a/packages/spec/export-origins/api.json b/packages/spec/export-origins/api.json index d218e9d6b2d..0f639dda4b2 100644 --- a/packages/spec/export-origins/api.json +++ b/packages/spec/export-origins/api.json @@ -571,6 +571,7 @@ "GetTranslationsRequestSchema": "src/api/protocol.zod.ts#GetTranslationsRequestSchema (const)", "GetTranslationsResponse": "src/api/protocol.zod.ts#GetTranslationsResponse (type)", "GetTranslationsResponseSchema": "src/api/protocol.zod.ts#GetTranslationsResponseSchema (const)", + "GetUiViewFormScaffold": "src/api/protocol.zod.ts#GetUiViewFormScaffold (type)", "GetUiViewRequest": "src/api/protocol.zod.ts#GetUiViewRequest (type)", "GetUiViewRequestSchema": "src/api/protocol.zod.ts#GetUiViewRequestSchema (const)", "GetUiViewResponse": "src/api/protocol.zod.ts#GetUiViewResponse (type)", diff --git a/packages/spec/export-origins/root.json b/packages/spec/export-origins/root.json index 14a1c341671..8d2173d3f3c 100644 --- a/packages/spec/export-origins/root.json +++ b/packages/spec/export-origins/root.json @@ -176,6 +176,7 @@ "defineViewItem": "src/ui/view.zod.ts#defineViewItem (function)", "defineWebhook": "src/automation/webhook.zod.ts#defineWebhook (function)", "deriveViewContainerObject": "src/ui/view-container-object.ts#deriveViewContainerObject (function)", + "expandServedViewContainer": "src/ui/view.zod.ts#expandServedViewContainer (function)", "expandViewContainer": "src/ui/view.zod.ts#expandViewContainer (function)", "expandViewContainerWithDiagnostics": "src/ui/view.zod.ts#expandViewContainerWithDiagnostics (function)", "expression": "src/shared/expression.zod.ts#expression (function)", @@ -187,6 +188,7 @@ "hasStackProvenance": "src/stack-provenance.ts#hasStackProvenance (function)", "isAggregatedViewContainer": "src/ui/view.zod.ts#isAggregatedViewContainer (function)", "isKnownPlatformCapability": "src/kernel/platform-capabilities.ts#isKnownPlatformCapability (function)", + "isServedViewItem": "src/ui/view.zod.ts#isServedViewItem (function)", "isViewContainerShaped": "src/ui/assembled-views.zod.ts#isViewContainerShaped (function)", "lintUnknownAuthoringKeys": "src/kernel/metadata-authoring-lint.ts#lintUnknownAuthoringKeys (function)", "lintUnknownKeysAgainstSchema": "src/kernel/metadata-authoring-lint.ts#lintUnknownKeysAgainstSchema (function)", diff --git a/packages/spec/export-origins/ui.json b/packages/spec/export-origins/ui.json index 8cb354427ed..af3e866500e 100644 --- a/packages/spec/export-origins/ui.json +++ b/packages/spec/export-origins/ui.json @@ -460,6 +460,7 @@ "SelectionConfig": "src/ui/view.zod.ts#SelectionConfig (type)", "SelectionConfigParsed": "src/ui/view.zod.ts#SelectionConfigParsed (type)", "SelectionConfigSchema": "src/ui/view.zod.ts#SelectionConfigSchema (const)", + "ServedViewItem": "src/ui/view.zod.ts#ServedViewItem (type)", "SharingConfig": "src/ui/sharing.zod.ts#SharingConfig (type)", "SharingConfigParsed": "src/ui/sharing.zod.ts#SharingConfigParsed (type)", "SharingConfigSchema": "src/ui/sharing.zod.ts#SharingConfigSchema (const)", @@ -593,6 +594,7 @@ "deriveColumnSummary": "src/ui/view-grouping-query.ts#deriveColumnSummary (function)", "deriveViewContainerObject": "src/ui/view-container-object.ts#deriveViewContainerObject (function)", "diagnoseViewMetadata": "src/ui/view.zod.ts#diagnoseViewMetadata (function)", + "expandServedViewContainer": "src/ui/view.zod.ts#expandServedViewContainer (function)", "expandViewContainer": "src/ui/view.zod.ts#expandViewContainer (function)", "expandViewContainerWithDiagnostics": "src/ui/view.zod.ts#expandViewContainerWithDiagnostics (function)", "expressionBindableTextKeysFor": "src/ui/expression-bindable-text-keys.zod.ts#expressionBindableTextKeysFor (function)", @@ -605,6 +607,7 @@ "isExpressionBindableTextKey": "src/ui/expression-bindable-text-keys.zod.ts#isExpressionBindableTextKey (function)", "isKnownComponentType": "src/ui/component-type-vocabulary.ts#isKnownComponentType (function)", "isRecordContextBlockType": "src/ui/react-blocks.ts#isRecordContextBlockType (function)", + "isServedViewItem": "src/ui/view.zod.ts#isServedViewItem (function)", "isViewContainerShaped": "src/ui/assembled-views.zod.ts#isViewContainerShaped (function)", "isViewFilterOrGroup": "src/ui/view.zod.ts#isViewFilterOrGroup (function)", "listViewGroupKeyPredicate": "src/ui/view-grouping-query.ts#listViewGroupKeyPredicate (function)", diff --git a/packages/spec/liveness/README.md b/packages/spec/liveness/README.md index 62a83bb31de..62929099bce 100644 --- a/packages/spec/liveness/README.md +++ b/packages/spec/liveness/README.md @@ -995,7 +995,7 @@ marker where the Notes cell goes, never a guess at what belongs there. | skill | `permissions` REMOVED 2026-07 (#3704); `triggerPhrases` REMOVED 2026-07-30 (#3896 close-out sweep — phrases were never matched; activation is `triggerConditions` + the agent's `skills[]` + /skill-name pinning) | | dataset | `measures.certified` (declared-but-unenforced governance flag) REMOVED in 16.0 (#2377) | | page | live, plus the one dead tombstone below. The `print` declaration (#22158, 2026-10-08: the container, its eight keys and the four `margins` sides) was declared spec-first by card ① of the #8346 ruling (B′) — its REFUSALS live (the parse's `checkPagePrintComposition`, lint's `validatePrintPageBlocks`), its keys `planned` with `authorWarn` on the container — and flipped `live` 2026-10-16 (#23710) once card ②, the console's print rendering, reached the `.objectui-sha` pin: `PageRenderer` mounts objectui's `buildPagePrintStylesheet`, which reads every key. `authorWarn` went with the flip, so an author who writes `print` is no longer told the layout is not applied. Its earlier `planned` row, `requires`, flipped `live` 2026-10-02 (#20871): the save door refuses an html page whose written list disagrees with its source and stores the derived one, and boot hydration reports a stored page whose list names a plugin the deployment's SDUI manifest does not carry. Dead `assignedProfiles` REMOVED 2026-09-12 (ADR-0090 D2 + ADR-0049 — a per-page audience list named for the concept D2 deleted, with zero readers in either repo, so the page was open to everyone who could reach it). The row stays because `retiredKey` keeps the key in the walked shape (the `rls.priority` precedent). Its prior `live` verdict is the #12516 class twice over: the objectui bridge it cited never existed (lit control — two sibling objectui citations in the same file resolve), and the entry carried no `verifiedAt`, so nothing ever re-asked | -| view | list/form drilled via `children` (#2998 Track B); list.{responsive,performance} + form.{defaultSort,aria} REMOVED 2026-07-30 (#3896 close-out sweep — list aria/data stay live); **form.data was that sweep's one CORRECTION** — the removal attempt broke the build (`defineMetadataForm` writes `data.provider='schema'` onto every metadata form, `metadata-protocol` serves it), so it stands `live` with re-verified evidence; form.{buttons,defaults} live (framework#1894 / #2998); audit-era DEAD lines superseded by re-verification. **The dead set is six, not the four removals above**: #4534 (the last #4001 batch, batch 6e) declared three CONTAINER-level keys this row had never classified — `name` and `label`, both `dead`, and `object`, `live`. All three are properties of the `views: [...]` *container*, not of a view: `name` is dead because authoring it changes nothing — an authored value restates the key the container already registers under or contradicts it — and `label` is container display metadata with no reader. Neither is `authorWarn`'d and both are deliberately KEPT — the metadata door itself stamps the save name into every saved view body (`normalizeViewMetadata`) and its overlay paths key on that copy, so tombstoning `name` would reject the platform's own saves (re-measured 2026-10-02, #20301 stage 2: the earlier attribution to artifact-shipped containers and the metadata-validation sweep was the door's stamp misread; neither carries one). `object` is the container's object binding, and it was *stripped on every parse* until #4534 declared it. Separately, the level-2 dead residue (userActions.buttons, tabs[].order; addRecord.mode/formView until their #24692 removal) is noted on parents and is **not** in the counts — one drill level only **#9340**: `list.map` declared — the eighth visualization block (`ListMapConfigSchema`), keys mirroring objectui plugin-map's documented read set. FLIPPED `planned` → `live` 2026-08-24 (#11442): objectui#5908 landed `resolveListMapConfig`, which merges the view-level `map` block over the legacy `options.map` bag before `ListView.tsx`'s `case 'map'` forwards it into `ObjectMap`, with the same merged config also feeding the visualization-switcher's capability gate so a view binding coordinates only in the spec block is no longer filtered out of `allowedVisualizations` either (objectui#5042) **#22611** (2026-10-10): `list.requiredPermissions` is this type's only `planned` row (the `list.map` precedent above flipped `live`) — the audience gate (a list of capabilities, all required), declared spec-first under the ruling of record 6095014058, letter A, with `authorWarn` and an `authorHint` because no server reads it until the `/meta` read gate applies it (#22639, the carrier). The warning reaches a container's `list` only: the lint flattens one level of `children`, so a named `listViews` entry is not walked, and the key's describe carries the not-enforced clause for that door | +| view | list drilled via `children` (#2998 Track B; `form` was drilled the same way until its tombstone, the last note of this row); list.{responsive,performance} + form.{defaultSort,aria} REMOVED 2026-07-30 (#3896 close-out sweep — list aria/data stay live); **form.data was that sweep's one CORRECTION** — the removal attempt broke the build (`defineMetadataForm` writes `data.provider='schema'` onto every metadata form, `metadata-protocol` serves it), so it stands `live` with re-verified evidence; form.{buttons,defaults} live (framework#1894 / #2998); audit-era DEAD lines superseded by re-verification. **The dead set is six, not the four removals above**: #4534 (the last #4001 batch, batch 6e) declared three CONTAINER-level keys this row had never classified — `name` and `label`, both `dead`, and `object`, `live`. All three are properties of the `views: [...]` *container*, not of a view: `name` is dead because authoring it changes nothing — an authored value restates the key the container already registers under or contradicts it — and `label` is container display metadata with no reader. Neither is `authorWarn`'d and both are deliberately KEPT — the metadata door itself stamps the save name into every saved view body (`normalizeViewMetadata`) and its overlay paths key on that copy, so tombstoning `name` would reject the platform's own saves (re-measured 2026-10-02, #20301 stage 2: the earlier attribution to artifact-shipped containers and the metadata-validation sweep was the door's stamp misread; neither carries one). `object` is the container's object binding, and it was *stripped on every parse* until #4534 declared it. Separately, the level-2 dead residue (userActions.buttons, tabs[].order; addRecord.mode/formView until their #24692 removal) is noted on parents and is **not** in the counts — one drill level only **#9340**: `list.map` declared — the eighth visualization block (`ListMapConfigSchema`), keys mirroring objectui plugin-map's documented read set. FLIPPED `planned` → `live` 2026-08-24 (#11442): objectui#5908 landed `resolveListMapConfig`, which merges the view-level `map` block over the legacy `options.map` bag before `ListView.tsx`'s `case 'map'` forwards it into `ObjectMap`, with the same merged config also feeding the visualization-switcher's capability gate so a view binding coordinates only in the spec block is no longer filtered out of `allowedVisualizations` either (objectui#5042) **#22611** (2026-10-10): `list.requiredPermissions` is this type's only `planned` row (the `list.map` precedent above flipped `live`) — the audience gate (a list of capabilities, all required), declared spec-first under the ruling of record 6095014058, letter A, with `authorWarn` and an `authorHint` because no server reads it until the `/meta` read gate applies it (#22639, the carrier). The warning reaches a container's `list` only: the lint flattens one level of `children`, so a named `listViews` entry is not walked, and the key's describe carries the not-enforced clause for that door **ADR-0159 D7** (2026-12-01): `form` and `formViews` are tombstones in protocol 19, because a form is its own metadata type (`form`, under the stack's `forms:`) and a `view` holds lists only. Both rows are `dead` and stay, since `retiredKey` keeps each key in the walked shape; `form`'s drilled `children` left this ledger with the container (the walk does not drill a tombstone), so every `form.*` sentence above is the record of what those rows said and no longer names a row here. A form's keys are classified in the `form` row's ledger, which was seeded from those rows. `viewKind: 'form'` left as a VALUE (`enumWithRetiredValues`), so it adds no row and no `RETIRED_KEYS_BY_MAJOR` entry | | report | dataset-bound (ADR-0021); the aria/performance LEDGER entries were stale — the keys left the schema in the report-liveness close-out; deleted 2026-07-30 as hygiene. Audit-era `chart` DEAD superseded (framework#1890 / #3441) — live on non-joined reports only: a `joined` report's container `chart` is refused and `blocks[].chart` was removed (#20161, 2026-09-27; nothing drew either) | | dashboard | ADR-0021 dataset widgets (#3251; DashboardWidgetSchema `.strict()`); `aria`/`performance` (and widget `performance` + PerformanceConfigSchema) REMOVED 2026-07-30 (#3896 close-out sweep — no renderer applied any of them); audit-era `globalFilters`/`dateRange` DEAD superseded (framework#2501) **#4956**: `widgets` DRILLED — the row jumps 20 → 41 classified because all 22 widget-level keys enter the count at once. They had never been classified at all: the entry carried one blanket `live` plus a `note` asserting they were classified "in the DashboardWidgetSchema subtree", and no such subtree existed in any of the 28 ledger files. That gap, not any evidence, is what carried `widgets[].responsive` through the #3896 sweep that removed both its sibling `widgets[].performance` and its literal namesake `view.responsive` — `view` is drilled, so `list.responsive` got asked and went out. New dead 6 = `responsive` (retired #4876/#4995, tombstone keeps the row) + `colorVariant` + `actionUrl`/`actionType`/`actionIcon` + `aria`. The action trio is the sharpest: no renderer draws a per-widget action button at all (every `actionUrl` read in DashboardRenderer is scoped to `header.actions[]`), yet `validate-dashboard-action-refs.ts` enforces reference integrity on it and its docblock calls it "the per-widget button" — a lint guarding an affordance that does not exist. `requiresService` is the counter-example worth remembering: dead by every objectui measurement, and LIVE server-side (`filterDashboardForUser`, ADR-0057 D10) — judging a widget key from the renderer repo alone would have retired an enforced gate. `compareTo` is `live` on ONE path only (inline object-provider charts); on the ADR-0021 dataset path the string arms are dropped and `{ offset }` throws in the executor. **#6774** moves the row 33/8 → 34/7: `colorVariant` CORRECTED dead → live 2026-08-09, the enforce leg of #5010 ruling B landing from the renderer side (objectui#3359 / PR objectui#3799, absorbed by pin `09987b68`). Worth reading beside `requiresService` above, because it is the same lesson from the other end — that row warns against judging a widget key from the renderer repo alone, and this one is a `dead` verdict that was correct in this repo AND correct in the renderer repo on the day it was measured, and stopped being either when a cross-repo decision was implemented. A ledger row is a claim with a timestamp; `verifiedAt` is what makes the claim re-askable. It also empties the dashboard warn set, so the author-side lint now says nothing about any widget key — `dashboard` stays in the lint's TYPE_COLLECTIONS all the same (the `webhook`/`email_template` resolved state). **#17385** DRILLS `widgets.chartConfig` — 14 per-key verdicts where the row had carried one blanket `live`, re-measured against `.objectui-sha` pin `53ded82bf7a4`: 12 live (the nine chrome keys `chartConfigPresentation` lowers, plus `xAxis`/`yAxis`/`series`, whose PRESENTATION merges onto the derived bindings while `ChartAxis.field` and `ChartSeries.name` are dropped so membership stays with the dataset) and dead 2 — `type`, which parses and does nothing because the widget's own `type` owns the chart family, and `aria`, which has no reader on either face. Both are pinned as NEGATIVES in objectui, which is what makes them re-askable rather than merely asserted. ⚠️ The drill made SIX containers one level further down visible for the first time (`xAxis`/`yAxis`/`series`/`annotations`/`interaction`/`aria`, 39 child keys); they are RECORDED, not drilled — fanning this row's verdicts down over them would manufacture verdicts, and the evidence work is a separate measurement. Note the cell's previous last stated position (`34/7`) had already drifted one `dead` behind the generated artifact before this change; the counts columns are generated and are the authority **#22611** (2026-10-10): `requiredPermissions` is this type's only `planned` row — the audience gate (a list of capabilities, all required) shared word for word with the list view's, declared spec-first under the ruling of record 6095014058, letter A, with `authorWarn` and an `authorHint` because no server reads it until the `/meta` read gate applies it (#22639, the carrier) | | query | **not a metadata type** — the REQUEST surface (`QuerySchema`: client SDK QueryBuilder output; the `POST /data/:object/query` body), governed via `SPEC_ONLY_SCHEMAS` (#4286). The gate resolves 1 experimental at the depth this ledger drills; the 7 marker-experimental search affordances sit one level deeper, below what this ledger declares (the walk recurses since #17424, but only where a `children` map is written, and none is written here) — resolved from `[EXPERIMENTAL — not enforced]` describe markers, not ledger entries (search `fuzzy`/`operator`/`boost`/`minScore`/`language`/`highlight` + `aggregations[].filter` — declared engine affordances no executor receives). The #4286 sweep closed out same-release: `having` ENFORCED 2026-07-31 (engine-side post-aggregation filter, both paths; was finding 1); dead 4 = the tombstoned removals `joins`/`windowFunctions`/`cursor`/`distinct` — REMOVED 2026-07-31 (retiredKey keeps each in the walked shape so the rows stay; protocol-17 semantic migrations; the JoinNode + WindowFunctionNode clusters and the `QueryBuilder.cursor()`/`.distinct()` producers deleted with their keys; `distinct`'s mis-wired REST count suppression deleted too — finding 2). **#6815** adds the 5th dead: `aggregations[].distinct` REMOVED 2026-08-09 (live → dead, `-1` live). It is the one member of this ledger the #4286 sweep could not have caught with the question it asked — that sweep looked for keys NO executor reads, and this one had a reader: the objectql in-memory fallback deduplicated before applying the function while all five other faces (driver-sql, driver-turso, driver-mongodb, driver-memory, service-analytics' `AGGREGATE_SQL`) ignored it, so one query answered two plausible NUMBERS depending on which backend served it. The lesson for the next audit is the question, not the key: a per-key `live` verdict is only as good as the count of faces it was measured across, and this row's 2026-07-31 evidence (`in-memory-aggregation.ts:167,204-206`) was TRUE and still the wrong verdict. `count_distinct` is the surviving spelling (enforce leg, #6409) | @@ -1009,7 +1009,7 @@ marker where the Notes cell goes, never a guess at what belongs there. | mapping | seeded 2026-08-01 (#4488) at 8/11 live; **0 dead since #4509** retired the three that were not. The import half (#2611) is loudly enforced — unsupported transforms/formats are 400s, `mode`/`upsertKey` default the request, the wizard picker renders `label`. RETIRED 17.0.0: `extractQuery` (authorWarn — "for export only" promised an export path no exporter implements) + `errorPolicy`/`batchSize`, which were dead AND **unwarnable** (schema defaults materialize at parse, so presence ≠ authored — `_authorWarnSkipped`, the non-boolean instance of the default(true) rule). That unwarnability is why they went out in the 17.0.0 window rather than after a deprecation cycle: removal was the only channel that could ever reach the author. Rows DELETED, not tombstoned — MappingSchema is strict, so the keys left the walked shape. `connectorSource` (2026-09-30) is this type's first `planned` row: the pull binding the connector-attached sync family MOVED here when the connector's `syncConfig` / `fieldMappings` retired to tombstones, seeded contract-first with `authorWarn` (its seven drilled rows — five children and `watermark`'s two — `planned` with it) because the pull executor is the next stage. **Live since 2026-10-01 (#20919)**: the connector sync executor reads every key. The container's `authorWarn` left with that re-grade (#21127) — kept at first, it made the author-side lint throw, so `os validate` / `os lint` exited 1 on every stack that authored the binding; the caveat it carried (nothing schedules a pull until the `job` stage lands) is on the key's description | | picklist | seeded 2026-09-30 (#19518) with every key `planned`, ahead of its runtime reader by ruling; **live since the runtime layer (#19519)**: the ObjectQL registry merges `picklistExtensions` into the list (additive only, a repeated value refused) and resolves it onto every field that names it, the write door judges against that set, and a field naming an undeclared list fails the boot. `field.picklist` left `authorWarn` with it. Display keys (`label`, `description`, `options.color`) are graded by their served form. | | seed | seeded 2026-08-01 (#4488). Fully live via SeedLoaderService on both doors (boot/per-org replay + runtime-draft publish). `records` is the z.record walk boundary: the keys an author writes are the target object's fields, governed by that object's own definitions — recorded in the entry, not silently skipped | -| translation | seeded 2026-08-01 (#4488) — after fixing the walker: the registered schema is a z.preprocess pipe (#3778 retired-dialect guard) whose transform side the unwrap always took, so the type was literally unwalkable. 11 of 12 groups live across spec resolvers, REST localization, objectui client resolvers and plugin-audit (whose composed-key `t()` calls make `messages` easy to mis-verify as dead) — `flows` was the one that was not, and was `planned` at seeding. **#14253** added the twelfth, `datasets`, seeded LIVE and DRILLED (label / description / dimensions / measures) with its reader in the same change: `translateDataset` in the dispatch table, which is what `TRANSLATABLE_METADATA_TYPES` is derived from, so the REST boundary followed with nothing else to remember. The same change gave `objects.._views..bulkActions` and `objects.._validations..message` their first keys — both beneath the walk boundary, so neither adds a row here. Dead 1 = `validationMessages` (authorWarn) at seeding: nothing resolved it, and #3778's own legacy-key migration table steered `errors:` authors into it — a shipped false signpost, the capabilities.readOnly shape. **#4667**: `validationMessages` REMOVED (row deleted) — removed from the shared translationDataShape(), so it retired at BOTH doors at once, closing the item-only asymmetry #3778's original guard had. #3778's own `errors` guidance was rewritten in the same change: it had been steering authors INTO this dead group. ⚠️ **What that left behind is this table's own worked example of the defect it warns about** (#7377): the same commit that deleted the `validationMessages` row wrote a count column of `dead 2` beside a sentence that named exactly one dead key — and that one was the key it had just removed. The real two were `name` and `label`, which the cell never mentioned. Measured at that commit, not inferred: the ledger's dead set there is `{name, label}` and `validationMessages` is absent from `props`. The number was right and the prose was false, in the same cell, on the day it was written — which is why the counts are now generated and this cell holds prose only. **#7131** (PR #7425) resolves it: `name` and `label` re-grade `dead` → `live` under the designer-previews-count-as-consumers ruling (objectui `TranslationPreview.tsx:67` reads `label` first and falls back to `name`, both rendering at `:100`), so the dead set is empty and there is no dead-set sentence left to keep true. As on `job`, the ADR-0033 docs-shaped exemption is untouched — nothing about enforce-or-remove moved. **#19620** (ruling batch #210 item 2 letter B): `settings` row DELETED — the strict-delete route, because `TranslationItemSchema` no longer declares the key and refuses it by name (the item door now takes the per-app face, as the file door has since #15178). ⚠️ The deleted row read `live`, and that verdict was TRUE and stays true of the platform: its evidence read the SERVED tree, which the platform bundle feeds, so the deletion retires the key from the application-authored item and nothing else — the capability lives on `PlatformTranslationDataSchema`, outside this ledger. **#20296**: `flows` is now half-read. `flows.screens` re-graded `planned` → `live`: objectui's FlowRunner reads each screen's `title` and each field's `label` / `placeholder` at the `.objectui-sha` pin f8a9d0fb. `flows.label` stays `planned` because nothing reads it yet (#20318), and so does the container's `authorWarn`, whose `authorHint` now names the read half and the unread one. **#23710**: the terminal toasts `flows.successMessage` / `flows.errorMessage` (child rows added `planned` by #22507) re-graded `live`: objectui's `translatedFlowMessage` asks `translateFlow` for both at the `.objectui-sha` pin daeb77fc84dd. **#24979**: `flows.approvals` and its one drilled key `label` (added `planned` as the spec half of #24863) re-graded `live`: plugin-approvals' `reader-locale-labels.ts` (commit ba69b168be) serves an approval request's step label from `flows..approvals..label` in the reader's locale, falling back to the stored snapshot, so the type's planned set is empty. | +| translation | seeded 2026-08-01 (#4488) — after fixing the walker: the registered schema is a z.preprocess pipe (#3778 retired-dialect guard) whose transform side the unwrap always took, so the type was literally unwalkable. 11 of 12 groups live across spec resolvers, REST localization, objectui client resolvers and plugin-audit (whose composed-key `t()` calls make `messages` easy to mis-verify as dead) — `flows` was the one that was not, and was `planned` at seeding. **#14253** added the twelfth, `datasets`, seeded LIVE and DRILLED (label / description / dimensions / measures) with its reader in the same change: `translateDataset` in the dispatch table, which is what `TRANSLATABLE_METADATA_TYPES` is derived from, so the REST boundary followed with nothing else to remember. The same change gave `objects.._views..bulkActions` and `objects.._validations..message` their first keys — both beneath the walk boundary, so neither adds a row here. Dead 1 = `validationMessages` (authorWarn) at seeding: nothing resolved it, and #3778's own legacy-key migration table steered `errors:` authors into it — a shipped false signpost, the capabilities.readOnly shape. **#4667**: `validationMessages` REMOVED (row deleted) — removed from the shared translationDataShape(), so it retired at BOTH doors at once, closing the item-only asymmetry #3778's original guard had. #3778's own `errors` guidance was rewritten in the same change: it had been steering authors INTO this dead group. ⚠️ **What that left behind is this table's own worked example of the defect it warns about** (#7377): the same commit that deleted the `validationMessages` row wrote a count column of `dead 2` beside a sentence that named exactly one dead key — and that one was the key it had just removed. The real two were `name` and `label`, which the cell never mentioned. Measured at that commit, not inferred: the ledger's dead set there is `{name, label}` and `validationMessages` is absent from `props`. The number was right and the prose was false, in the same cell, on the day it was written — which is why the counts are now generated and this cell holds prose only. **#7131** (PR #7425) resolves it: `name` and `label` re-grade `dead` → `live` under the designer-previews-count-as-consumers ruling (objectui `TranslationPreview.tsx:67` reads `label` first and falls back to `name`, both rendering at `:100`), so the dead set is empty and there is no dead-set sentence left to keep true. As on `job`, the ADR-0033 docs-shaped exemption is untouched — nothing about enforce-or-remove moved. **#19620** (ruling batch #210 item 2 letter B): `settings` row DELETED — the strict-delete route, because `TranslationItemSchema` no longer declares the key and refuses it by name (the item door now takes the per-app face, as the file door has since #15178). ⚠️ The deleted row read `live`, and that verdict was TRUE and stays true of the platform: its evidence read the SERVED tree, which the platform bundle feeds, so the deletion retires the key from the application-authored item and nothing else — the capability lives on `PlatformTranslationDataSchema`, outside this ledger. **#20296**: `flows` is now half-read. `flows.screens` re-graded `planned` → `live`: objectui's FlowRunner reads each screen's `title` and each field's `label` / `placeholder` at the `.objectui-sha` pin f8a9d0fb. `flows.label` stays `planned` because nothing reads it yet (#20318), and so does the container's `authorWarn`, whose `authorHint` now names the read half and the unread one. **#23710**: the terminal toasts `flows.successMessage` / `flows.errorMessage` (child rows added `planned` by #22507) re-graded `live`: objectui's `translatedFlowMessage` asks `translateFlow` for both at the `.objectui-sha` pin daeb77fc84dd. **#24979**: `flows.approvals` and its one drilled key `label` (added `planned` as the spec half of #24863) re-graded `live`: plugin-approvals' `reader-locale-labels.ts` (commit ba69b168be) serves an approval request's step label from `flows..approvals..label` in the reader's locale, falling back to the stored snapshot, so the type's planned set is empty. **ADR-0159 D8** (2026-12-01): the two form tails under a view's translations, `objects.._views..title` and `.submitBehavior`, are tombstones in protocol 19 (a form's heading and thank-you panel are `forms..title` / `.submitBehavior`, and the translator's fallback read of the tails left with them). Both sit beneath the walk boundary, like the `_views` keys #14253 added, so neither adds a row here; the `forms` row carries the record | | qa | seeded 2026-08-10 (#6247) — **not a metadata type**: `TestSuiteSchema` is the FILE surface of the shipped `os test` command (`qa/*.test.json`), governed through the same `SPEC_ONLY_SCHEMAS` override as `query`/`webhook`/`validation`. It is in the table as the clearest worked example of a **false `dead` measurement**: #6247 reported the whole domain declared-but-inert on a grep that scanned only `*Schema` identifiers, and every consumer here reads the **type** names (`QA.TestSuite`, `QA.TestStep`, `QA.TestAction`) — so an entire execution chain (core's `TestRunner` + `HttpTestAdapter`, published via `export * as QA`, driven by a documented CLI command) read as zero consumers, and a retire ruling was issued on it before being withdrawn. The `evidenceScope` table one section up says no amount of specifier matching is sufficient for a negative claim; this is the same lesson for **identifier** matching. What was really wrong was narrower and real: the type was the contract and the schema had no `parse` site, so the CLI's `JSON.parse(content) as QA.TestSuite` cast admitted anything — ENFORCED in the same change (`TestSuiteSchema.safeParse` at the load site, pinned). The seeding recorded Dead 5 — `name`, `scenarios.name`, `scenarios.description`, `scenarios.tags` and `scenarios.requires` — and #20289 (family `qa-runner`, verdict ENFORCE) made all FIVE live: the suite `name` heads the suite in `os test`'s report and is stamped as `suiteName` on every TestResult the suite produces; `scenarios.name` is printed beside the id and carried as `scenarioName`; `scenarios.description` is carried and printed under a failed scenario; `scenarios.tags` is read by `os test --tags` (any-of, exact; deselected scenarios are counted and never passed); and `scenarios.requires` is judged by the TestRunner before a scenario's first step — `params` against the environment of the process running `os test`, `services` against the target's discovery `services` (enabled and `available`) — so an unmet entry SKIPS the scenario with its reason, counted apart and never passed. `requires` was put to the maintainer first rather than guessed (ruled B): over HTTP no server surface lists the loaded plugins, so `requires.plugins` is a `retiredKey()` tombstone inside the block whose prescription names `requires.services`. It does not carry `authorWarn` and the omission is deliberate (`_authorWarnSkipped`): the lint walks stack **collections**, a QA suite is a loose file in no stack, so a warn flag here would emit nothing — a silent no-op inside the mechanism built to catch silent no-ops | | validation | seeded 2026-08-01 (#4488). The ADR-0020 carrier: the evaluator honors active/events/priority/severity/type/condition/message (the zod header's "only reads type/condition/…" prose is STALE — trust the ledger). Dead 3 = label/description/tags, declared governance metadata, kept unmarked. Union walk boundary recorded: only base + `script` keys walked; per-variant keys are governed by the evaluator's tests, not ledger rows. **No longer a registered metadata kind** — #4509 retired it under ADR-0088 (a standalone rule had no object-binding key and every variant is `.strict()`, so it bound to nothing and gated no write; a state machine authored that way saved cleanly and did nothing). The rule VOCABULARY is untouched and fully live via `object.validations[]`, so the ledger keeps governing it through the gate's spec-only override, alongside `webhook` and `query`. The contrast with the two bridges in the same batch is the point: enforce-or-remove picked ENFORCE where the feature existed and only the wiring was missing, and REMOVE where the shape itself could not carry the feature | | api | seeded 2026-08-04 (#5271, part of #5206; PR #5312) — **not a metadata type until that same change made it one**, which is the row's point: governance and registration landed together, the treatment `datasource` did not get (#4487) and paid for with six inert keys found by hand. What #5206 measured before the fix: `api` was in neither `DEFAULT_METADATA_TYPE_REGISTRY` nor `BUILTIN_METADATA_TYPE_SCHEMAS`, so `saveMetaItem`'s `resolveOverlaySchema('api', …)` → `getMetadataTypeSchema('api')` returned `undefined` and took its own documented branch — an unregistered type is stored **unvalidated** — while `getMetaTypes()` could not enumerate the type at all, so Studio rendered neither list nor form. That issue names the shape precisely and it is the inverse of this ledger's usual one: **enforced but undeclared** (the matcher was already indexing these entries, #5089), where `dead` is declared-but-unenforced. The seeding pass classified 27 keys — live 25 / planned 2 / dead 0 — each cited `file:line` at the consumer layer that reads it: the MATCHER (`packages/metadata/src/endpoint-matcher.ts`) indexes `name`/`path`/`method`; the EXECUTOR (`packages/runtime/src/endpoint-executor.ts`) dispatches on `type` and reads `target`/`objectParams`; the POLICY chain (`packages/runtime/src/endpoint-policy.ts` + `security/inbound-rate-limit.ts`) enforces `authRequired`/`rateLimit`/`cacheTtl`; the MAPPING layer (`packages/runtime/src/api-mapping.ts`) applies `inputMapping`/`outputMapping`; and OpenAPI enrichment (`packages/rest/src/openapi-endpoints.ts`) emits `summary`/`description`. Timing was the reason it was cheap: #5040's E-series had built every one of those consumers and all of it was on main, so each key had a real evidence path rather than a promise. **Planned 2 = `inputMapping.transform` + `outputMapping.transform`, and `planned` rather than `dead` is load-bearing**: `dead` here means parsed with no consumer — a silent no-op — and these are the opposite, parsed and then LOUDLY REFUSED at publish (`endpoint-publish-gate.ts` mappingGate) and again at runtime, because no transformation-function registry exists anywhere in the platform. An author who writes one is told so and told what to do instead, so there is nothing for enforce-or-remove to chase; they stay in the vocabulary because admitting them needs a function registry **and** a sandbox ruling (#5040 §3.4), which is a design decision, not a key to quietly delete. Zero dead | @@ -1028,7 +1028,7 @@ marker where the Notes cell goes, never a guess at what belongs there. | assignment_rule | seeded 2026-10-26 with the type itself (#25769, ADR-0142 D5): registered governed. Declared only — organization-authored rules are deferred (ADR-0142 merge question 11) — and read on every insert by the engine's `AssignmentRuleEvaluator`, after every `beforeInsert` hook, for a row whose `owner_id` and `queue` are both still empty. All rows `live`, and `entries.assignTo` is drilled (`type`, `value`) rather than inherited. `name` and `entries.name` key the round-robin cursor (`sys_assignment_cursor`, per rule, entry and organization), so a rename restarts a rotation; `object` gates evaluation to objects carrying the platform `queue` column; `entries.load` is the `least_loaded` count predicate, required with that strategy and refused otherwise. `kernel:ready` refuses a stack that declares rules or queues with no `ownership-queue` service registered, so no row is inert by a missing service. | | template_manifest | seeded 2026-11-06 with the marketplace taxonomy, through `SPEC_ONLY_SCHEMAS` (the sixth category: a package-listing file surface — `objectstack.manifest.json`, read by `os package publish` and create-objectstack, never by a boot). The facet keys `businessFunctions` / `industries` / `maturity` are `planned`: the CLI judges and forwards them, and their consumers are the cloud catalog (objectstack-ai/cloud#3661, which drops them until it lands) and the console marketplace card. `solutionType` is `live` through the publish cross-check. `category` is the tombstone. The other `dead` rows are what entering the denominator measured: `name`, `specVersion`, `skills`, `scaffold` and the warned-and-unsent `visibility` were then retired as tombstones (ADR-0049); `publisher` / `isStarter`, which publish named in a warning and did not send but a first-party publish script did, were then retired too (maintainer ruling: a trust claim does not belong in an author-editable file). | | ai_context | seeded 2026-11-25 with the type itself (#37140, ADR-0160 D1): registered governed, never a `PENDING_GOVERNANCE` debt. Every key is read by the one `get_record_context` executor (`@objectstack/service-record-context`), served over the MCP door on HTTP and stdio; `name`, `object`, `fields`, `related.*` and `body.field` are `live` there, and `label` is the answer's pack header. | -| form | seeded 2026-11-26 with the type itself (#37086, ADR-0159 card ②): registered governed, never a `PENDING_GOVERNANCE` debt. `name`, `object` and `label` are the item's own rows, each `live` on the effective `form` read and the anonymous doors. The body rows carry view.json `form.*`'s verdicts, because the body IS `FormViewSchema`'s shape by reference and the doors serve it to the same public renderer an old-shape form reaches; each row says so and names card ③ (#37087) as the re-verification, the card that lets the console open a `form` item from an action. `overrides` is the planned ADR-0146 row every overridable type carries. The ADR-0010 envelope is auto-live (`null`). | +| form | seeded 2026-11-26 with the type itself (#37086, ADR-0159 card ②): registered governed, never a `PENDING_GOVERNANCE` debt. `name`, `object` and `label` are the item's own rows, each `live` on the effective `form` read and the anonymous doors. The body rows were seeded with view.json `form.*`'s verdicts, because the body IS `FormViewSchema`'s shape by reference and the doors serve it to the public renderer an old-shape form reached until protocol 19; each row says so and names card ③ (#37087) as the re-verification, the card that lets the console open a `form` item from an action. **ADR-0159 D7** (2026-12-01): view.json's `form.*` rows left with the container's tombstone, so these rows are the one classification of a form's keys; `columns` and `sections`, which view.json had re-cited after the seed, were brought level before its rows left. `overrides` is the planned ADR-0146 row every overridable type carries. The ADR-0010 envelope is auto-live (`null`). | | knowledge_source | seeded 2026-11-26 with the type itself (#37304, ADR-0161 K4): registered governed, never a `PENDING_GOVERNANCE` debt. Every key that parses is read by the knowledge service (`@objectstack/service-knowledge`), whose loader registers the published items: `name` is the source's slot and index key, `label` / `description` / `aiExposed` are read by `search_knowledge`, `adapter`, `source.*` and `refresh.onRecordChange` by the build, the event sync and the reap guard. The 6 `dead` keys are ADR-0161 K6's tombstones, removed in the same PR: `id`, `source.contentFields`, `adapterConfig`, `embedding`, `vectorStore`, `refresh.cron`. | The `dead` set across types is the enforce-or-remove worklist (ADR-0049); a `dead` diff --git a/packages/spec/liveness/form.json b/packages/spec/liveness/form.json index 883519689ec..b293b44cd23 100644 --- a/packages/spec/liveness/form.json +++ b/packages/spec/liveness/form.json @@ -1,6 +1,6 @@ { "type": "form", - "_note": "FormSchema (ADR-0159 D2) — the `form` metadata type: `name` (`OBJECT.KEY`), `object`, `label`, a form view's body at the top level (FormViewSchema's keys by reference, less `data`), the override declaration and the ADR-0010 envelope. Seeded 2026-11-26 with the type itself (card ②, #37086). The body rows carry view.json `form.*`'s verdicts, because the body IS that schema and the doors serve it to the same renderer; each says so and names the re-verification card.", + "_note": "FormSchema (ADR-0159 D2) — the `form` metadata type: `name` (`OBJECT.KEY`), `object`, `label`, a form view's body at the top level (FormViewSchema's keys by reference, less `data`), the override declaration and the ADR-0010 envelope. Seeded 2026-11-26 with the type itself (card ②, #37086). The body rows were seeded with view.json `form.*`'s verdicts, because the body IS that schema and the doors serve it to the same renderer; each says so and names the re-verification card. 2026-12-01 (ADR-0159 D7): the view container's `form` and `formViews` are tombstones in protocol 19, so view.json's `form.*` rows left with them and these rows are the one classification of a form's keys. The two rows view.json had re-cited after the seed were brought level the same day, before its rows left: `columns` (re-cited 2026-11-26) and `sections` (re-read 2026-11-27).", "props": { "name": { "status": "live", @@ -23,115 +23,116 @@ "status": "live", "verifiedAt": "2026-10-28", "evidenceScope": "in-repo", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. NARROWED 2026-10-28 (#27155, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) to the form's LAYOUT: simple / tabbed / wizard. The key stays live — ui/packages/plugin-form/src/ObjectForm.tsx routes tabbed and wizard to TabbedForm / WizardForm and simple to its own arm; ui/apps/console/src/components/FormPage.tsx forwards it for a named or public form (since #36425 the record create / edit surfaces load no internal form view, so RecordFormPage and the record dialog no longer read it). `split`, `drawer` and `modal` are refused by name (enumWithRetiredValues carries each prescription; a value-level narrowing, so this row stays and no RETIRED_KEYS_BY_MAJOR entry exists for them) and deleted from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion, which lands the form on the `simple` default. Where a form opens is the caller's open mode. The renderer's split / drawer / modal arms for a form view leave on #27159." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. NARROWED 2026-10-28 (#27155, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) to the form's LAYOUT: simple / tabbed / wizard. The key stays live — ui/packages/plugin-form/src/ObjectForm.tsx routes tabbed and wizard to TabbedForm / WizardForm and simple to its own arm; ui/apps/console/src/components/FormPage.tsx forwards it for a named or public form (since #36425 the record create / edit surfaces load no internal form view, so RecordFormPage and the record dialog no longer read it). `split`, `drawer` and `modal` are refused by name (enumWithRetiredValues carries each prescription; a value-level narrowing, so this row stays and no RETIRED_KEYS_BY_MAJOR entry exists for them) and deleted from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion, which lands the form on the `simple` default. Where a form opens is the caller's open mode. The renderer's split / drawer / modal arms for a form view leave on #27159." }, "layout": { "status": "live", "verifiedAt": "2026-09-27", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui @ f8a9d0fb0: plugin-form ObjectForm.tsx:1408 (simple arm) and :463/:499 (drawer/modal hand-off), DrawerForm.tsx:575, ModalForm.tsx:597 — each reads vertical/horizontal only. The enum was narrowed to those two arms 2026-09-27 (#20221, ADR-0049 enforce-or-remove): every arm folded 'inline' and 'grid' to vertical, so both were a declared value the renderer threw away; multi-column is the sibling `columns` key. The key itself stays live." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui @ f8a9d0fb0: plugin-form ObjectForm.tsx:1408 (simple arm) and :463/:499 (drawer/modal hand-off), DrawerForm.tsx:575, ModalForm.tsx:597 — each reads vertical/horizontal only. The enum was narrowed to those two arms 2026-09-27 (#20221, ADR-0049 enforce-or-remove): every arm folded 'inline' and 'grid' to vertical, so both were a declared value the renderer threw away; multi-column is the sibling `columns` key. The key itself stays live." }, "columns": { "status": "live", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ModalForm.tsx:247-258 / DrawerForm.tsx:478 applyAutoLayout column count." + "verifiedAt": "2026-11-26", + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. RE-CITED 2026-11-26 (#37665, ruling A on #37638): the form view's `columns` is the grid width of a sectioned form, capping each section's count; an undeclared section takes it. Readers: ui/apps/console/src/components/FormPage.tsx#buildSections, the named (`/forms/:name`) and public (`/f/:slug`) form page, and the Setup preview canvas, ui/packages/app-shell/src/views/metadata-admin/previews/ViewPreview.tsx#buildFormPreviewSchema handing it to ui/packages/plugin-form/src/ObjectForm.tsx; both resolve through ui/packages/plugin-form/src/autoLayout.ts#sectionedGridLayout. The previous ModalForm / DrawerForm citation was stale: those hosts no longer receive a stored form view." }, "title": { "status": "live", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ModalForm.tsx:662 / DrawerForm.tsx:528 header; ObjectView form adapter (audit L25)." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ModalForm.tsx:662 / DrawerForm.tsx:528 header; ObjectView form adapter (audit L25)." }, "description": { "status": "live", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ModalForm.tsx:662-681 / DrawerForm.tsx:528-558 render it under the title." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ModalForm.tsx:662-681 / DrawerForm.tsx:528-558 render it under the title." }, "defaultTab": { "status": "live", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ObjectForm.tsx:185 → tabbed variant." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ObjectForm.tsx:185 → tabbed variant." }, "tabPosition": { "status": "live", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ObjectForm.tsx:186 → tabbed variant." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ObjectForm.tsx:186 → tabbed variant." }, "allowSkip": { "status": "live", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: WizardForm.tsx:397-444 (step navigation gating)." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: WizardForm.tsx:397-444 (step navigation gating)." }, "showStepIndicator": { "status": "live", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: WizardForm.tsx:438." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: WizardForm.tsx:438." }, "splitDirection": { "status": "dead", "verifiedAt": "2026-10-28", "evidenceScope": "in-repo", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-10-28 (#27159, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape) and stripped from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion, which #27159 widened before 18.3.0 shipped. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It oriented the split form's panes. Its form-view reader left with `type: 'split'` on #27155; its last reader, ui/packages/plugin-form/src/SplitForm.tsx behind the React `ObjectForm` block's `formType='split'`, was deleted with that value on #27159 (the `object-form` block's own splitDirection is tombstoned in the same change); nothing to write instead — a `tabbed` form gives each section its own tab." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-10-28 (#27159, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape) and stripped from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion, which #27159 widened before 18.3.0 shipped. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It oriented the split form's panes. Its form-view reader left with `type: 'split'` on #27155; its last reader, ui/packages/plugin-form/src/SplitForm.tsx behind the React `ObjectForm` block's `formType='split'`, was deleted with that value on #27159 (the `object-form` block's own splitDirection is tombstoned in the same change); nothing to write instead — a `tabbed` form gives each section its own tab." }, "splitSize": { "status": "dead", "verifiedAt": "2026-10-28", "evidenceScope": "in-repo", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-10-28 (#27155, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms and the flattened form overlay) and stripped from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It sized the split form's primary pane. Its only reader was ui/packages/plugin-form/src/SplitForm.tsx, reached through ObjectForm's `split` arm and RecordFormPage's split hand-off, both behind `type: 'split'`, which left the enum in the same change; nothing to write instead — a `tabbed` form gives each section its own tab." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-10-28 (#27155, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms and the flattened form overlay) and stripped from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It sized the split form's primary pane. Its only reader was ui/packages/plugin-form/src/SplitForm.tsx, reached through ObjectForm's `split` arm and RecordFormPage's split hand-off, both behind `type: 'split'`, which left the enum in the same change; nothing to write instead — a `tabbed` form gives each section its own tab." }, "splitResizable": { "status": "dead", "verifiedAt": "2026-10-28", "evidenceScope": "in-repo", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-10-28 (#27155, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms and the flattened form overlay) and stripped from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It made the split form's panes resizable. Its only reader was ui/packages/plugin-form/src/SplitForm.tsx, reached through ObjectForm's `split` arm and RecordFormPage's split hand-off, both behind `type: 'split'`, which left the enum in the same change; nothing to write instead — a `tabbed` form gives each section its own tab." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-10-28 (#27155, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms and the flattened form overlay) and stripped from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It made the split form's panes resizable. Its only reader was ui/packages/plugin-form/src/SplitForm.tsx, reached through ObjectForm's `split` arm and RecordFormPage's split hand-off, both behind `type: 'split'`, which left the enum in the same change; nothing to write instead — a `tabbed` form gives each section its own tab." }, "drawerSide": { "status": "dead", "verifiedAt": "2026-11-02", "evidenceScope": "in-repo", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-11-02 (#29012, ADR-0049 enforce-or-remove, triage ruling 6571544001: retire) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms and the flattened form overlay) and stripped from stored rows and sources by the protocol-18 form-view-drawer-keys-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). Its form-view reader sat behind `type: 'drawer'`, which left the enum on #27155; measured at origin/main 104cd1a5, no metadata form-view surface reads it (ui/packages/plugin-form/src/ObjectFormContainer.tsx is the only caller that hands it to DrawerForm.tsx, and it serves the `object-form` block's `formType='drawer'`, which a form view's `type` cannot reach). The React `ObjectForm` block keeps the prop in its own overlay (packages/spec/src/ui/react-blocks.ts), and the `object-form` page block declares it in ObjectFormPropsSchema; nothing to write on a form view instead — a list opens a clicked record in its drawer (`navigation.mode`)." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-11-02 (#29012, ADR-0049 enforce-or-remove, triage ruling 6571544001: retire) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms and the flattened form overlay) and stripped from stored rows and sources by the protocol-18 form-view-drawer-keys-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). Its form-view reader sat behind `type: 'drawer'`, which left the enum on #27155; measured at origin/main 104cd1a5, no metadata form-view surface reads it (ui/packages/plugin-form/src/ObjectFormContainer.tsx is the only caller that hands it to DrawerForm.tsx, and it serves the `object-form` block's `formType='drawer'`, which a form view's `type` cannot reach). The React `ObjectForm` block keeps the prop in its own overlay (packages/spec/src/ui/react-blocks.ts), and the `object-form` page block declares it in ObjectFormPropsSchema; nothing to write on a form view instead — a list opens a clicked record in its drawer (`navigation.mode`)." }, "drawerWidth": { "status": "dead", "verifiedAt": "2026-11-02", "evidenceScope": "in-repo", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-11-02 (#29012, ADR-0049 enforce-or-remove, triage ruling 6571544001: retire) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape) and stripped from stored rows and sources by the protocol-18 form-view-drawer-keys-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It was already DEPRECATED (#2578 → size buckets) with no size-bucket conversion of its own, and inert on a form view since `type: 'drawer'` left the enum on #27155: the only reader, DrawerForm.tsx, is reached only through the `object-form` block's `formType='drawer'` (ObjectFormContainer.tsx). The React `ObjectForm` block keeps the prop in its own overlay (packages/spec/src/ui/react-blocks.ts); nothing to write on a form view instead — a list's record drawer takes its starting width from `navigation.size`." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-11-02 (#29012, ADR-0049 enforce-or-remove, triage ruling 6571544001: retire) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape) and stripped from stored rows and sources by the protocol-18 form-view-drawer-keys-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It was already DEPRECATED (#2578 → size buckets) with no size-bucket conversion of its own, and inert on a form view since `type: 'drawer'` left the enum on #27155: the only reader, DrawerForm.tsx, is reached only through the `object-form` block's `formType='drawer'` (ObjectFormContainer.tsx). The React `ObjectForm` block keeps the prop in its own overlay (packages/spec/src/ui/react-blocks.ts); nothing to write on a form view instead — a list's record drawer takes its starting width from `navigation.size`." }, "modalSize": { "status": "dead", "verifiedAt": "2026-11-28", "evidenceScope": "in-repo", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-11-28 (#36544, ADR-0049 enforce-or-remove, seat ruling on the card: retire) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms, the flattened form overlay and the `form` item) and stripped from stored rows and sources by the protocol-19 form-view-modal-size-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). Its one form-view reader was the console's New / Edit record dialog, which copied it from the object's internal form view until #36425 retired that read. Measured at origin/main 0e361201, no form-view surface reads it: ui/apps/console/src/components/FormPage.tsx, the page a named or public form opens on, names every other form key it draws and never this one; ui/packages/app-shell/src/utils/recordFormNavigation.ts#resolveRecordFormModalLayout writes `modalSize: 'full'` only from the surface the host derived; ui/packages/app-shell/src/hooks/useActionModal.tsx takes it from the action's own descriptor; and packages/rest, packages/runtime, packages/objectql and packages/metadata* never name it. ui/packages/plugin-form/src/ModalForm.tsx still reads a `modalSize`, the `object-form` block's own prop (ObjectFormContainer.tsx hands it over for `formType='modal'`), which a form view cannot reach. The React `ObjectForm` block keeps the prop in its own overlay (packages/spec/src/ui/react-blocks.ts), and the `object-form` page block declares it in ObjectFormPropsSchema; nothing to write on a form view instead — the record dialog chooses its own size from the fields it draws." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-11-28 (#36544, ADR-0049 enforce-or-remove, seat ruling on the card: retire) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms, the flattened form overlay and the `form` item) and stripped from stored rows and sources by the protocol-19 form-view-modal-size-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). Its one form-view reader was the console's New / Edit record dialog, which copied it from the object's internal form view until #36425 retired that read. Measured at origin/main 0e361201, no form-view surface reads it: ui/apps/console/src/components/FormPage.tsx, the page a named or public form opens on, names every other form key it draws and never this one; ui/packages/app-shell/src/utils/recordFormNavigation.ts#resolveRecordFormModalLayout writes `modalSize: 'full'` only from the surface the host derived; ui/packages/app-shell/src/hooks/useActionModal.tsx takes it from the action's own descriptor; and packages/rest, packages/runtime, packages/objectql and packages/metadata* never name it. ui/packages/plugin-form/src/ModalForm.tsx still reads a `modalSize`, the `object-form` block's own prop (ObjectFormContainer.tsx hands it over for `formType='modal'`), which a form view cannot reach. The React `ObjectForm` block keeps the prop in its own overlay (packages/spec/src/ui/react-blocks.ts), and the `object-form` page block declares it in ObjectFormPropsSchema; nothing to write on a form view instead — the record dialog chooses its own size from the fields it draws." }, "sections": { "status": "live", "verifiedAt": "2026-08-11", "evidenceScope": "cross-repo", "evidence": "objectui: form renderers + spec-bridge form-view.ts:169 (audit L17); packages/rest/src/form-routes.ts registerFormEndpoints (the two /forms/:slug routes walk sections: resolve strips every lookup/master_detail/user field from the anonymous rendering, submit builds allowedFields from them)", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. This row carries the blanket verdict for the whole FormField subtree beneath it (undrilled inheritance). [#7467] had added the anonymous public-form picker block to that subtree, read only by the anonymous lookup route; [#21180] REMOVED it 2026-10-01 (ADR-0087 D2, ruling E on #21079): the key is now a retiredKey() tombstone in FormFieldBaseSchema carrying the prescription, the route is deleted, and the resolve route strips lookup/master_detail/user fields from the anonymous rendering unconditionally. The subtree has no per-key rows, so the tombstone adds none; the retirement is registered as ui/FormField:publicPicker in RETIRED_KEYS_BY_MAJOR[18]. [#12174] drills the six FormField constraint keys out of the blanket verdict — maxLength/minLength/min/max/precision/scale are all LIVE, measured at objectui@f7c52e2 (2026-08-26): two independent spec-to-runtime routes copy all six onto the runtime field (packages/react/src/spec-bridge/bridges/form-view.ts mapField, objectui#5898; packages/plugin-form/src/sectionFields.ts normalizeSectionField), the console FormPage merges override.maxLength ?? def.maxLength onto the rendered input (apps/console/src/components/FormPage.tsx:548, objectui#5595), packages/fields buildValidationRules turns minLength/maxLength/min/max into react-hook-form rules, ObjectForm.tsx:691 derives the number input step from precision, and NumberField.tsx:21 reads scale; server-side, GET /forms/:slug (packages/rest/src/rest-server.ts) serves the rows verbatim to anonymous renderers (a conduit, no key-level read). On that measurement the four count-shaped keys tightened to the #11566/#11949/#8321 value shapes (lengths int>=1, precision/scale int>=0; min/max stay bare numbers — they are values, not counts). Form-row `span` / `scale` read points (FormFieldBaseSchema in packages/spec/src/ui/view.zod.ts; moved out of spec source, #23434), re-read at objectui @b9814b334 on 2026-10-14: objectui @b9814b334 packages/plugin-form/src/autoLayout.ts#resolveColSpan resolves 'full' to the grid's full column count and sizes 'auto' from the widget type, objectui @b9814b334 packages/plugin-form/src/autoLayout.ts#WIDE_FIELD_TYPES makes textarea, markdown, html, richtext and repeater (via the wide `field:grid` widget) span the full count, and objectui @b9814b334 packages/components/src/renderers/form/form.tsx#spanLadderFor emits one clamped col-span class per multi-column tier (`@md:col-span-2 @2xl:col-span-3` for a 3-column grid; the widest-tier-only under-span of #17328 ended with objectui#9244 / objectui#9253). A form row's `scale` reaches `Intl.NumberFormat` through plugin-form (see field.json row `scale`). [#27155] The section key `pane` (split-pane placement) is REMOVED 2026-10-28 with `type: 'split'` (ADR-0050): a retiredKey() tombstone in FormSectionSchema carrying the prescription, stripped by the protocol-18 form-view-presentation-types-removed conversion. The subtree has no per-key rows, so the tombstone adds none; the retirement is registered as ui/FormSection:pane in RETIRED_KEYS_BY_MAJOR[18]." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. This row carries the blanket verdict for the whole FormField subtree beneath it (undrilled inheritance). [#7467] had added the anonymous public-form picker block to that subtree, read only by the anonymous lookup route; [#21180] REMOVED it 2026-10-01 (ADR-0087 D2, ruling E on #21079): the key is now a retiredKey() tombstone in FormFieldBaseSchema carrying the prescription, the route is deleted, and the resolve route strips lookup/master_detail/user fields from the anonymous rendering unconditionally. The subtree has no per-key rows, so the tombstone adds none; the retirement is registered as ui/FormField:publicPicker in RETIRED_KEYS_BY_MAJOR[18]. [#12174] drills the six FormField constraint keys out of the blanket verdict — maxLength/minLength/min/max/precision/scale are all LIVE, measured at objectui@f7c52e2 (2026-08-26): two independent spec-to-runtime routes copy all six onto the runtime field (packages/react/src/spec-bridge/bridges/form-view.ts mapField, objectui#5898; packages/plugin-form/src/sectionFields.ts normalizeSectionField), the console FormPage merges override.maxLength ?? def.maxLength onto the rendered input (apps/console/src/components/FormPage.tsx:548, objectui#5595), packages/fields buildValidationRules turns minLength/maxLength/min/max into react-hook-form rules, ObjectForm.tsx:691 derives the number input step from precision, and NumberField.tsx:21 reads scale; server-side, GET /forms/:slug (packages/rest/src/rest-server.ts) serves the rows verbatim to anonymous renderers (a conduit, no key-level read). On that measurement the four count-shaped keys tightened to the #11566/#11949/#8321 value shapes (lengths int>=1, precision/scale int>=0; min/max stay bare numbers — they are values, not counts). Form-row `span` / `scale` read points (FormFieldBaseSchema in packages/spec/src/ui/view.zod.ts; moved out of spec source, #23434), re-read at objectui @b9814b334 on 2026-10-14: objectui @b9814b334 packages/plugin-form/src/autoLayout.ts#resolveColSpan resolves 'full' to the grid's full column count and sizes 'auto' from the widget type, objectui @b9814b334 packages/plugin-form/src/autoLayout.ts#WIDE_FIELD_TYPES makes textarea, markdown, html, richtext and repeater (via the wide `field:grid` widget) span the full count (re-read 2026-11-27, #37677: since objectui#11448 repeater maps to the shared `field:object` JSON editor, so autoLayout.ts#WIDE_DECLARED_FIELD_TYPES widens it by its object-field type, read in both form renderers), and objectui @b9814b334 packages/components/src/renderers/form/form.tsx#spanLadderFor emits one clamped col-span class per multi-column tier (`@md:col-span-2 @2xl:col-span-3` for a 3-column grid; the widest-tier-only under-span of #17328 ended with objectui#9244 / objectui#9253). A form row's `scale` reaches `Intl.NumberFormat` through plugin-form (see field.json row `scale`). [#27155] The section key `pane` (split-pane placement) is REMOVED 2026-10-28 with `type: 'split'` (ADR-0050): a retiredKey() tombstone in FormSectionSchema carrying the prescription, stripped by the protocol-18 form-view-presentation-types-removed conversion. The subtree has no per-key rows, so the tombstone adds none; the retirement is registered as ui/FormSection:pane in RETIRED_KEYS_BY_MAJOR[18]." }, "groups": { "status": "live", "verifiedAt": "2026-08-09", "evidenceScope": "in-repo", "evidence": "packages/spec/src/ui/view.zod.ts (foldFormGroupsIntoSections + the .overwrite on FormViewSchema — the PRODUCER fold, #6926: groups-only folds onto sections, sections wins when both are present, and groups is absent from every parsed form); ui/packages/plugin-form/src/ObjectForm.tsx (:129-142 at objectui @7b3e048) (objectui @7b3e048 — the pre-existing boundary folds, now redundant for parsed forms and retiring in a later cross-repo lap)", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. WHERE THE FOLD LIVES: at the producer, as of #6926 — a `.overwrite()` on FormViewSchema, inherited by every parse door (ViewSchema.form/.formViews.*, both ViewItemSchema form arms, and ViewMetadataSchema's container AND flattened form-overlay members, which picks it up through .extend()). Before #6926 the alias was declared but folded NOWHERE in this repo: it was honored one boundary downstream in objectui (alias-at-one-boundary, objectui#2545, after a groups-only spec rendered nothing), while the framework's REST public-form routes read `sections` only — so the same authored form rendered in the console and degraded on GET /forms/:slug, POST /forms/:slug/submit and GET /forms/:slug/lookup/:field. That omission is what let #6926 be filed reading a live key as dead; it is recorded here so the next reader cannot repeat it. STILL NOT FOLDED (measured 2026-08-09, #6926): a RUNTIME-saved sys_metadata row — saveMetaItem validates through ViewMetadataSchema and then deliberately discards parsed.data to keep Studio round-trip keys, and the read replays the ADR-0087 stored-row conversion chain, which is not a zod parse. Code-authored views (defineView/defineMetadataForm → registry) DO reach REST folded. Pre-parse consumers still read the authored key and are right to: packages/lint's view rules walk authored sources. Audit L24 drift resolved by alias-at-one-boundary; superseded by the producer fold. 2026-10-26 (#25712, objectui merged into this repo as ui/): the spec-bridge clause (`form-view.ts:169`) was dropped, not repointed: objectui#6632 retired the spec-bridge. ObjectForm's line range is kept as the @7b3e048 reading; it does not match today's file." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. WHERE THE FOLD LIVES: at the producer, as of #6926 — a `.overwrite()` on FormViewSchema, inherited by every parse door (ViewSchema.form/.formViews.*, both ViewItemSchema form arms, and ViewMetadataSchema's container AND flattened form-overlay members, which picks it up through .extend()). Before #6926 the alias was declared but folded NOWHERE in this repo: it was honored one boundary downstream in objectui (alias-at-one-boundary, objectui#2545, after a groups-only spec rendered nothing), while the framework's REST public-form routes read `sections` only — so the same authored form rendered in the console and degraded on GET /forms/:slug, POST /forms/:slug/submit and GET /forms/:slug/lookup/:field. That omission is what let #6926 be filed reading a live key as dead; it is recorded here so the next reader cannot repeat it. STILL NOT FOLDED (measured 2026-08-09, #6926): a RUNTIME-saved sys_metadata row — saveMetaItem validates through ViewMetadataSchema and then deliberately discards parsed.data to keep Studio round-trip keys, and the read replays the ADR-0087 stored-row conversion chain, which is not a zod parse. Code-authored views (defineView/defineMetadataForm → registry) DO reach REST folded. Pre-parse consumers still read the authored key and are right to: packages/lint's view rules walk authored sources. Audit L24 drift resolved by alias-at-one-boundary; superseded by the producer fold. 2026-10-26 (#25712, objectui merged into this repo as ui/): the spec-bridge clause (`form-view.ts:169`) was dropped, not repointed: objectui#6632 retired the spec-bridge. ObjectForm's line range is kept as the @7b3e048 reading; it does not match today's file." }, "subforms": { "status": "live", "verifiedAt": "2026-08-10", "evidenceScope": "in-repo", "evidence": "ui/packages/plugin-form/src/ObjectForm.tsx (:175 at objectui @11c1e71e) branches on schema.subforms and :197 hands it to MasterDetailForm as `details`; the plugin-form master-detail form (:315 at objectui @11c1e71e) reads it as schema.details and :240 renders one panel per entry, with :227 summing their amount fields; ui/packages/plugin-form/src/ModalForm.tsx:1080 and ui/packages/plugin-form/src/DrawerForm.tsx:909 take the same key through their own envelopes (ModalForm applies at :1117/:1153, DrawerForm at :921) — measured objectui @11c1e71e", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. RE-CITED 2026-08-10 (#7133/#7142): the old citation named deriveMasterDetail.ts:338 and LineItemsPanel.tsx:45, and neither file mentions `subforms` at objectui @11c1e71e. deriveMasterDetail DERIVES master-detail panels from relationship metadata — its output is merged with the authored key one level up, in app-shell MetadataProvider.tsx:304-307 — and LineItemsPanel.tsx:41-55 is the per-panel schema, one hop past the rename to `details`. The form renderers are the readers that branch on the authored key. Verdict unchanged: LIVE, master-detail fully wired (audit L17)." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. RE-CITED 2026-08-10 (#7133/#7142): the old citation named deriveMasterDetail.ts:338 and LineItemsPanel.tsx:45, and neither file mentions `subforms` at objectui @11c1e71e. deriveMasterDetail DERIVES master-detail panels from relationship metadata — its output is merged with the authored key one level up, in app-shell MetadataProvider.tsx:304-307 — and LineItemsPanel.tsx:41-55 is the per-panel schema, one hop past the rename to `details`. The form renderers are the readers that branch on the authored key. Verdict unchanged: LIVE, master-detail fully wired (audit L17)." }, "sharing": { "status": "live", - "verifiedAt": "2026-11-26", - "evidence": "packages/rest/src/form-routes.ts#findPublicForm (`const open = openFormAt(forms ?? [], layer, slug);` — the public form doors serve only an open form of the effective `form` list whose slug matches, an old shape among them as the `form` item it projects); packages/spec/src/ui/form-intake-layer.ts#openFormAt (`if (layer.closedLinks.has(slug)) return null;`, then `if (anonymousFormIntakeSlug(form.sharing) !== slug) continue;` and `if (name === undefined || layer.withdrawn.has(name)) continue;` — a `form` item's own `sharing` decides its address, under the withdrawal layer); packages/spec/src/ui/anonymous-form-intake.ts#anonymousFormIntakeSlug (the slug rule reads all three keys: `if (s.enabled !== true) return null;`, `if (s.allowAnonymous !== true) return null;`, `if (typeof s.publicLink !== 'string' || !s.publicLink) return null;`); packages/rest/src/form-routes.ts#resolveFormBySlug (both doors resolve the match through it, and the submit door grants `publicFormGrant: { object: match.object }` for the matched form's object)", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. Framework-side consumer: public (anonymous) form endpoints opt in via FormView.sharing — /forms/:slug resolves sharing.publicLink across form + formViews (rest-server.ts:1716, :4366-4405) and grants publicFormGrant. Renderer-side the config is not read (audit L20) — the public form is served, not re-parsed client-side. 2026-08-28: RE-ANCHORED (commit 8f10a79f7) and REPOINTED — `:4384` had rotted onto a comment about `api`-only route enumeration, ~4,020 lines above the form endpoints; the note's own inline pointers (`:1716`, `:4366-4405`) had gone with it and are superseded by the anchors. Re-closed by hand against 8cb96ec41." + "verifiedAt": "2026-12-01", + "evidence": "packages/rest/src/form-routes.ts#findPublicForm (`const open = openFormAt(forms ?? [], layer, slug);` — the public form doors serve only an open form of the effective `form` list whose slug matches; since protocol 19 that list holds `form` items only, and no form is answered out of a `view` body, ADR-0159 D7); packages/spec/src/ui/form-intake-layer.ts#openFormAt (`if (layer.closedLinks.has(slug)) return null;`, then `if (anonymousFormIntakeSlug(form.sharing) !== slug) continue;` and `if (name === undefined || layer.withdrawn.has(name)) continue;` — a `form` item's own `sharing` decides its address, under the withdrawal layer); packages/spec/src/ui/anonymous-form-intake.ts#anonymousFormIntakeSlug (the slug rule reads all three keys: `if (s.enabled !== true) return null;`, `if (s.allowAnonymous !== true) return null;`, `if (typeof s.publicLink !== 'string' || !s.publicLink) return null;`); packages/rest/src/form-routes.ts#resolveFormBySlug (both doors resolve the match through it, and the submit door grants `publicFormGrant: { object: match.object }` for the matched form's object)", + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. Framework-side consumer: public (anonymous) form endpoints opt in via FormView.sharing — /forms/:slug resolves sharing.publicLink across form + formViews (rest-server.ts:1716, :4366-4405) and grants publicFormGrant. Renderer-side the config is not read (audit L20) — the public form is served, not re-parsed client-side. 2026-08-28: RE-ANCHORED (commit 8f10a79f7) and REPOINTED — `:4384` had rotted onto a comment about `api`-only route enumeration, ~4,020 lines above the form endpoints; the note's own inline pointers (`:1716`, `:4366-4405`) had gone with it and are superseded by the anchors. Re-closed by hand against 8cb96ec41." }, "submitBehavior": { "status": "live", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: WizardForm.tsx:315-316 + ObjectForm.tsx dispatch thank-you/redirect/continue/next-record; covered by ObjectForm.submitBehavior.test.tsx / WizardForm.successBehavior.test.tsx. Supersedes the 2026-06 audit's DEAD line (L20) — wiring landed with the objectui#2545/#2552 reconciliation." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: WizardForm.tsx:315-316 + ObjectForm.tsx dispatch thank-you/redirect/continue/next-record; covered by ObjectForm.submitBehavior.test.tsx / WizardForm.successBehavior.test.tsx. Supersedes the 2026-06 audit's DEAD line (L20) — wiring landed with the objectui#2545/#2552 reconciliation." }, "buttons": { "status": "live", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ObjectForm.tsx foldFormButtons() reads schema.buttons and folds submit/cancel {show,label} onto the flat showSubmit/submitText/showCancel/cancelText props (framework#1894 / #2998); ObjectView forwards it, and every console form entry point resolves submit/cancel through resolveFormViewChrome / readFormButton (#26843). Flat keys kept as deprecated back-compat (explicit flat key wins). SUB-KEY buttons.reset REMOVED 2026-10-28 (#27153, ADR-0049 enforce-or-remove, ruled retire): measured at origin/main fbe344b3, six button bars (components form.tsx, console FormPage, ModalForm, DrawerForm, WizardForm, MasterDetailForm) drew submit/cancel and none drew reset; reset.label had no reader; the one fold of reset.show landed on ObjectForm showReset, which means clear-after-save (resetOnSubmit), not a button. Tombstoned inside the buttons block (retiredKey carries the prescription) and stripped from stored rows and sources by the protocol-18 form-view-buttons-reset-removed conversion; the fold was removed in the same change. Sub-keys cannot be drilled (one level only), so the removal is recorded here; submit and cancel keep this row live." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ObjectForm.tsx foldFormButtons() reads schema.buttons and folds submit/cancel {show,label} onto the flat showSubmit/submitText/showCancel/cancelText props (framework#1894 / #2998); ObjectView forwards it, and every console form entry point resolves submit/cancel through resolveFormViewChrome / readFormButton (#26843). Flat keys kept as deprecated back-compat (explicit flat key wins). SUB-KEY buttons.reset REMOVED 2026-10-28 (#27153, ADR-0049 enforce-or-remove, ruled retire): measured at origin/main fbe344b3, six button bars (components form.tsx, console FormPage, ModalForm, DrawerForm, WizardForm, MasterDetailForm) drew submit/cancel and none drew reset; reset.label had no reader; the one fold of reset.show landed on ObjectForm showReset, which means clear-after-save (resetOnSubmit), not a button. Tombstoned inside the buttons block (retiredKey carries the prescription) and stripped from stored rows and sources by the protocol-18 form-view-buttons-reset-removed conversion; the fold was removed in the same change. Sub-keys cannot be drilled (one level only), so the removal is recorded here; submit and cancel keep this row live." }, "defaults": { "status": "live", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ObjectForm.tsx foldFormButtons() reads schema.defaults and folds it into create-mode initialValues (framework#1894 / #2998); an explicit initialValues (URL prefill) still wins." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ObjectForm.tsx foldFormButtons() reads schema.defaults and folds it into create-mode initialValues (framework#1894 / #2998); an explicit initialValues (URL prefill) still wins." }, "protection": null, "_lock": null, diff --git a/packages/spec/liveness/state-counts/view.md b/packages/spec/liveness/state-counts/view.md index f13052fddda..2de50457f18 100644 --- a/packages/spec/liveness/state-counts/view.md +++ b/packages/spec/liveness/state-counts/view.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `view` | 74 | 0 | 0 | 12 | 0 | 86 | +| `view` | 56 | 0 | 0 | 8 | 0 | 64 | diff --git a/packages/spec/liveness/translation.json b/packages/spec/liveness/translation.json index bdad54f3bfc..a57122a25ce 100644 --- a/packages/spec/liveness/translation.json +++ b/packages/spec/liveness/translation.json @@ -28,7 +28,7 @@ "status": "live", "verifiedAt": "2026-08-28", "evidence": "packages/spec/src/system/i18n-resolver.ts#lookupObjectField (`objects..label` / `pluralLabel` / `description`); packages/spec/src/system/i18n-resolver.ts#lookupObjectFieldAttr (`objects..fields..`); packages/spec/src/system/i18n-resolver.ts#resolveViewLabel (`objects.._views..label`); packages/spec/src/system/i18n-resolver.ts#actionTranslationNode (`objects.._actions`, the one address of a bound action — never followed by globalActions); packages/spec/src/system/i18n-resolver.ts#lookupTabLabel (`objects.._tabs`); packages/spec/src/system/i18n-resolver.ts#lookupRelatedListLabel (`objects.._relatedLists`, read by translateObject); ui/packages/i18n/src/useObjectLabel.ts (:397-400 at objectui @940ba24)", - "note": "the largest group, fully live: label/pluralLabel/description (translateObject), fields.{label,help,placeholder,options}, _views (resolveViewLabel + empty-state copy), _actions (label/description/confirmText/successMessage/outcomeMessages/params/resultDialog — a bound action's only address; it never falls back to globalActions), _sections (objectui record:details section labels). Served through REST translateMetaItem(s) and the /api/v1/i18n endpoints; objectui re-resolves client-side via the spec-translations transform. 2026-08-28: RE-ANCHORED (commit 8f10a79f7) and REPOINTED — this entry named SIX positions in i18n-resolver.ts and only the first, `:735`, was parsable as a citation at all; it had rotted onto `widgets?: WidgetLike[]` in the `DashboardLike` INTERFACE. The other five (`:751`, `:159`, `:197`, `:873`, `:900`) were bare line suffixes with no path in front of them, so they were never resolved, bounded or key-checked by anything — the largest instance in this batch of the class `flow.status` and `dashboard.widgets.suppressWarnings` also carried. The five anchors above are the five distinct group readers, named. Re-closed by hand against 8cb96ec41." + "note": "the largest group, fully live: label/pluralLabel/description (translateObject), fields.{label,help,placeholder,options}, _views (resolveViewLabel + empty-state copy; a list's strings only since protocol 19 — a form's `title` / `submitBehavior` tails are tombstoned there and live under `forms`, ADR-0159 D8), _actions (label/description/confirmText/successMessage/outcomeMessages/params/resultDialog — a bound action's only address; it never falls back to globalActions), _sections (objectui record:details section labels). Served through REST translateMetaItem(s) and the /api/v1/i18n endpoints; objectui re-resolves client-side via the spec-translations transform. 2026-08-28: RE-ANCHORED (commit 8f10a79f7) and REPOINTED — this entry named SIX positions in i18n-resolver.ts and only the first, `:735`, was parsable as a citation at all; it had rotted onto `widgets?: WidgetLike[]` in the `DashboardLike` INTERFACE. The other five (`:751`, `:159`, `:197`, `:873`, `:900`) were bare line suffixes with no path in front of them, so they were never resolved, bounded or key-checked by anything — the largest instance in this batch of the class `flow.status` and `dashboard.widgets.suppressWarnings` also carried. The five anchors above are the five distinct group readers, named. Re-closed by hand against 8cb96ec41." }, "picklists": { "status": "live", @@ -154,9 +154,9 @@ }, "forms": { "status": "live", - "verifiedAt": "2026-11-26", - "evidence": "packages/spec/src/system/i18n-resolver.ts#translateForm (`forms..{label,description,title,submitBehavior.title,submitBehavior.message}` first; `title` and `submitBehavior` fall back to the `_views.` tails; `_views..label` is never read); packages/lint/src/i18n-walk.ts#walkForms (the extractor emits the `forms..*` keys and no `_views` tail)", - "note": "ADR-0159 card ② item 8: the `form` metadata type's translation family.", + "verifiedAt": "2026-12-01", + "evidence": "packages/spec/src/system/i18n-resolver.ts#translateForm (`forms..{label,description,title,submitBehavior.title,submitBehavior.message}`, the one address of a form's own strings since protocol 19: the fallback read of the `_views..title` / `.submitBehavior` tails left with their tombstones, ADR-0159 D8; `_views..label` was never read for a form); packages/lint/src/i18n-walk.ts#walkForms (the extractor emits the `forms..*` keys and no `_views` tail)", + "note": "ADR-0159 card ② item 8: the `form` metadata type's translation family. 2026-12-01 (ADR-0159 D8): the one address of a form's heading and thank-you panel. The two form tails a form defined in a view had under `objects.._views.` (`title`, `submitBehavior`) are tombstoned in protocol 19 (retiredKey carries the prescription naming `forms['OBJECT.KEY']`) and moved by the protocol-19 conversion translation-view-form-tails-to-forms. Both sit under a record's value shape, beneath this ledger's walk boundary and the authorable-surface walk alike, so the tombstones add no row here and no RETIRED_KEYS_BY_MAJOR entry: the D3 semantic entry translation-form-tails-move-to-forms is their registration.", "children": { "label": { "status": "live", diff --git a/packages/spec/liveness/view.json b/packages/spec/liveness/view.json index 52ad1580820..c49e33afe72 100644 --- a/packages/spec/liveness/view.json +++ b/packages/spec/liveness/view.json @@ -1,6 +1,6 @@ { "type": "view", - "_note": "ViewSchema (object view container: list/form/listViews/formViews). Seeded from docs/audits/archive/2026-06/2026-06-viewschema-property-liveness.md (objectui consumer cross-reference) and re-verified against objectui@fb35e48 (2026-07-16) — several audit-era DEAD findings have since gone LIVE (submitBehavior, sharing.lockedBy, ViewData providers on the list path) and are classified from the current reads, not the stale audit lines. objectui paths cited as 'objectui: ' prose (not resolved against this repo). Sub-sub-key divergences (userActions.buttons, addRecord.mode/formView, tabs[].order) can't be drilled (one level only) — captured in the parent entry's note and tracked in the enforce-or-remove worklist (#2998 Track B / ADR-0049). 2026-07-30 (#3896 close-out sweep): the dead authoring keys were REMOVED — tombstoned at the schema with prescriptions (retiredKey) and stripped by the protocol-17 close-out conversions; entries deleted per the #3715 precedent. widget.performance (no ledger file of its own) was verified dead the corrected way — zero readers in either repo; objectui virtual scrolling reads the LIVE top-level virtualScroll — and removed with them. 2026-08-28 (commit 8f10a79f7): all five `path:NNN` citations in this file were re-anchored to their consuming symbols, and all five were wrong. Two pairs shared one wrong line each — `list.name`/`listViews` on a schema declaration, `form.sharing`/`formViews` on a comment about API routes — and `object` was falsified in PROSE as well as position, naming a function that lives in another package.", + "_note": "ViewSchema (object view container: list/listViews; form/formViews REMOVED in 19, ADR-0159 D7). Seeded from docs/audits/archive/2026-06/2026-06-viewschema-property-liveness.md (objectui consumer cross-reference) and re-verified against objectui@fb35e48 (2026-07-16) — several audit-era DEAD findings have since gone LIVE (submitBehavior, sharing.lockedBy, ViewData providers on the list path) and are classified from the current reads, not the stale audit lines. objectui paths cited as 'objectui: ' prose (not resolved against this repo). Sub-sub-key divergences (userActions.buttons, addRecord.mode/formView, tabs[].order) can't be drilled (one level only) — captured in the parent entry's note and tracked in the enforce-or-remove worklist (#2998 Track B / ADR-0049). 2026-07-30 (#3896 close-out sweep): the dead authoring keys were REMOVED — tombstoned at the schema with prescriptions (retiredKey) and stripped by the protocol-17 close-out conversions; entries deleted per the #3715 precedent. widget.performance (no ledger file of its own) was verified dead the corrected way — zero readers in either repo; objectui virtual scrolling reads the LIVE top-level virtualScroll — and removed with them. 2026-08-28 (commit 8f10a79f7): all five `path:NNN` citations in this file were re-anchored to their consuming symbols, and all five were wrong. Two pairs shared one wrong line each — `list.name`/`listViews` on a schema declaration, `form.sharing`/`formViews` on a comment about API routes — and `object` was falsified in PROSE as well as position, naming a function that lives in another package.", "props": { "name": { "status": "dead", @@ -278,129 +278,9 @@ } }, "form": { - "children": { - "data": { - "status": "live", - "verifiedAt": "2026-07-30", - "evidence": "packages/spec/src/ui/view.zod.ts defineMetadataForm (writes data.provider=schema + schemaId onto every metadata form); packages/metadata-protocol/src/protocol.ts:1580,1598 (serves schemaId with the form to the metadata-admin pipeline)", - "note": "CORRECTED 2026-07-30: the #3896 sweep attempted removal on the prior dead verdict and the build itself refuted it — defineMetadataForm authors the key on every *.metadata-form.ts. The record-form provider VALUES (object/value) may still lack readers; that is a value-subset audit, not a key removal. 2026-10-13: the `api` value is RETIRED on the union itself (see `list.data`'s retirement record) — a form's `data` no longer admits a request block; a submit-to-endpoint is not a view concern." - }, - "type": { - "status": "live", - "verifiedAt": "2026-10-28", - "evidenceScope": "in-repo", - "note": "NARROWED 2026-10-28 (#27155, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) to the form's LAYOUT: simple / tabbed / wizard. The key stays live — ui/packages/plugin-form/src/ObjectForm.tsx routes tabbed and wizard to TabbedForm / WizardForm and simple to its own arm; ui/apps/console/src/components/FormPage.tsx forwards it for a named or public form (since #36425 the record create / edit surfaces load no internal form view, so RecordFormPage and the record dialog no longer read it). `split`, `drawer` and `modal` are refused by name (enumWithRetiredValues carries each prescription; a value-level narrowing, so this row stays and no RETIRED_KEYS_BY_MAJOR entry exists for them) and deleted from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion, which lands the form on the `simple` default. Where a form opens is the caller's open mode. The renderer's split / drawer / modal arms for a form view leave on #27159." - }, - "layout": { - "status": "live", - "verifiedAt": "2026-09-27", - "note": "objectui @ f8a9d0fb0: plugin-form ObjectForm.tsx:1408 (simple arm) and :463/:499 (drawer/modal hand-off), DrawerForm.tsx:575, ModalForm.tsx:597 — each reads vertical/horizontal only. The enum was narrowed to those two arms 2026-09-27 (#20221, ADR-0049 enforce-or-remove): every arm folded 'inline' and 'grid' to vertical, so both were a declared value the renderer threw away; multi-column is the sibling `columns` key. The key itself stays live." - }, - "columns": { - "status": "live", - "verifiedAt": "2026-11-26", - "note": "RE-CITED 2026-11-26 (#37665, ruling A on #37638): the form view's `columns` is the grid width of a sectioned form, capping each section's count; an undeclared section takes it. Readers: ui/apps/console/src/components/FormPage.tsx#buildSections, the named (`/forms/:name`) and public (`/f/:slug`) form page, and the Setup preview canvas, ui/packages/app-shell/src/views/metadata-admin/previews/ViewPreview.tsx#buildFormPreviewSchema handing it to ui/packages/plugin-form/src/ObjectForm.tsx; both resolve through ui/packages/plugin-form/src/autoLayout.ts#sectionedGridLayout. The previous ModalForm / DrawerForm citation was stale: those hosts no longer receive a stored form view." - }, - "title": { - "status": "live", - "note": "objectui: ModalForm.tsx:662 / DrawerForm.tsx:528 header; ObjectView form adapter (audit L25)." - }, - "description": { - "status": "live", - "note": "objectui: ModalForm.tsx:662-681 / DrawerForm.tsx:528-558 render it under the title." - }, - "defaultTab": { - "status": "live", - "note": "objectui: ObjectForm.tsx:185 → tabbed variant." - }, - "tabPosition": { - "status": "live", - "note": "objectui: ObjectForm.tsx:186 → tabbed variant." - }, - "allowSkip": { - "status": "live", - "note": "objectui: WizardForm.tsx:397-444 (step navigation gating)." - }, - "showStepIndicator": { - "status": "live", - "note": "objectui: WizardForm.tsx:438." - }, - "splitDirection": { - "status": "dead", - "verifiedAt": "2026-10-28", - "evidenceScope": "in-repo", - "note": "REMOVED 2026-10-28 (#27159, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape) and stripped from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion, which #27159 widened before 18.3.0 shipped. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It oriented the split form's panes. Its form-view reader left with `type: 'split'` on #27155; its last reader, ui/packages/plugin-form/src/SplitForm.tsx behind the React `ObjectForm` block's `formType='split'`, was deleted with that value on #27159 (the `object-form` block's own splitDirection is tombstoned in the same change); nothing to write instead — a `tabbed` form gives each section its own tab." - }, - "splitSize": { - "status": "dead", - "verifiedAt": "2026-10-28", - "evidenceScope": "in-repo", - "note": "REMOVED 2026-10-28 (#27155, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms and the flattened form overlay) and stripped from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It sized the split form's primary pane. Its only reader was ui/packages/plugin-form/src/SplitForm.tsx, reached through ObjectForm's `split` arm and RecordFormPage's split hand-off, both behind `type: 'split'`, which left the enum in the same change; nothing to write instead — a `tabbed` form gives each section its own tab." - }, - "splitResizable": { - "status": "dead", - "verifiedAt": "2026-10-28", - "evidenceScope": "in-repo", - "note": "REMOVED 2026-10-28 (#27155, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms and the flattened form overlay) and stripped from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It made the split form's panes resizable. Its only reader was ui/packages/plugin-form/src/SplitForm.tsx, reached through ObjectForm's `split` arm and RecordFormPage's split hand-off, both behind `type: 'split'`, which left the enum in the same change; nothing to write instead — a `tabbed` form gives each section its own tab." - }, - "drawerSide": { - "status": "dead", - "verifiedAt": "2026-11-02", - "evidenceScope": "in-repo", - "note": "REMOVED 2026-11-02 (#29012, ADR-0049 enforce-or-remove, triage ruling 6571544001: retire) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms and the flattened form overlay) and stripped from stored rows and sources by the protocol-18 form-view-drawer-keys-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). Its form-view reader sat behind `type: 'drawer'`, which left the enum on #27155; measured at origin/main 104cd1a5, no metadata form-view surface reads it (ui/packages/plugin-form/src/ObjectFormContainer.tsx is the only caller that hands it to DrawerForm.tsx, and it serves the `object-form` block's `formType='drawer'`, which a form view's `type` cannot reach). The React `ObjectForm` block keeps the prop in its own overlay (packages/spec/src/ui/react-blocks.ts), and the `object-form` page block declares it in ObjectFormPropsSchema; nothing to write on a form view instead — a list opens a clicked record in its drawer (`navigation.mode`)." - }, - "drawerWidth": { - "status": "dead", - "verifiedAt": "2026-11-02", - "evidenceScope": "in-repo", - "note": "REMOVED 2026-11-02 (#29012, ADR-0049 enforce-or-remove, triage ruling 6571544001: retire) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape) and stripped from stored rows and sources by the protocol-18 form-view-drawer-keys-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It was already DEPRECATED (#2578 → size buckets) with no size-bucket conversion of its own, and inert on a form view since `type: 'drawer'` left the enum on #27155: the only reader, DrawerForm.tsx, is reached only through the `object-form` block's `formType='drawer'` (ObjectFormContainer.tsx). The React `ObjectForm` block keeps the prop in its own overlay (packages/spec/src/ui/react-blocks.ts); nothing to write on a form view instead — a list's record drawer takes its starting width from `navigation.size`." - }, - "modalSize": { - "status": "dead", - "verifiedAt": "2026-11-28", - "evidenceScope": "in-repo", - "note": "REMOVED 2026-11-28 (#36544, ADR-0049 enforce-or-remove, seat ruling on the card: retire) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms, the flattened form overlay and the `form` item) and stripped from stored rows and sources by the protocol-19 form-view-modal-size-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). Its one form-view reader was the console's New / Edit record dialog, which copied it from the object's internal form view until #36425 retired that read. Measured at origin/main 0e361201, no form-view surface reads it: ui/apps/console/src/components/FormPage.tsx, the page a named or public form opens on, names every other form key it draws and never this one; ui/packages/app-shell/src/utils/recordFormNavigation.ts#resolveRecordFormModalLayout writes `modalSize: 'full'` only from the surface the host derived; ui/packages/app-shell/src/hooks/useActionModal.tsx takes it from the action's own descriptor; and packages/rest, packages/runtime, packages/objectql and packages/metadata* never name it. ui/packages/plugin-form/src/ModalForm.tsx still reads a `modalSize`, the `object-form` block's own prop (ObjectFormContainer.tsx hands it over for `formType='modal'`), which a form view cannot reach. The React `ObjectForm` block keeps the prop in its own overlay (packages/spec/src/ui/react-blocks.ts), and the `object-form` page block declares it in ObjectFormPropsSchema; nothing to write on a form view instead — the record dialog chooses its own size from the fields it draws." - }, - "sections": { - "status": "live", - "verifiedAt": "2026-08-11", - "evidenceScope": "cross-repo", - "evidence": "objectui: form renderers + spec-bridge form-view.ts:169 (audit L17); packages/rest/src/form-routes.ts registerFormEndpoints (the two /forms/:slug routes walk sections: resolve strips every lookup/master_detail/user field from the anonymous rendering, submit builds allowedFields from them)", - "note": "This row carries the blanket verdict for the whole FormField subtree beneath it (undrilled inheritance). [#7467] had added the anonymous public-form picker block to that subtree, read only by the anonymous lookup route; [#21180] REMOVED it 2026-10-01 (ADR-0087 D2, ruling E on #21079): the key is now a retiredKey() tombstone in FormFieldBaseSchema carrying the prescription, the route is deleted, and the resolve route strips lookup/master_detail/user fields from the anonymous rendering unconditionally. The subtree has no per-key rows, so the tombstone adds none; the retirement is registered as ui/FormField:publicPicker in RETIRED_KEYS_BY_MAJOR[18]. [#12174] drills the six FormField constraint keys out of the blanket verdict — maxLength/minLength/min/max/precision/scale are all LIVE, measured at objectui@f7c52e2 (2026-08-26): two independent spec-to-runtime routes copy all six onto the runtime field (packages/react/src/spec-bridge/bridges/form-view.ts mapField, objectui#5898; packages/plugin-form/src/sectionFields.ts normalizeSectionField), the console FormPage merges override.maxLength ?? def.maxLength onto the rendered input (apps/console/src/components/FormPage.tsx:548, objectui#5595), packages/fields buildValidationRules turns minLength/maxLength/min/max into react-hook-form rules, ObjectForm.tsx:691 derives the number input step from precision, and NumberField.tsx:21 reads scale; server-side, GET /forms/:slug (packages/rest/src/rest-server.ts) serves the rows verbatim to anonymous renderers (a conduit, no key-level read). On that measurement the four count-shaped keys tightened to the #11566/#11949/#8321 value shapes (lengths int>=1, precision/scale int>=0; min/max stay bare numbers — they are values, not counts). Form-row `span` / `scale` read points (FormFieldBaseSchema in packages/spec/src/ui/view.zod.ts; moved out of spec source, #23434), re-read at objectui @b9814b334 on 2026-10-14: objectui @b9814b334 packages/plugin-form/src/autoLayout.ts#resolveColSpan resolves 'full' to the grid's full column count and sizes 'auto' from the widget type, objectui @b9814b334 packages/plugin-form/src/autoLayout.ts#WIDE_FIELD_TYPES makes textarea, markdown, html, richtext and repeater (via the wide `field:grid` widget) span the full count (re-read 2026-11-27, #37677: since objectui#11448 repeater maps to the shared `field:object` JSON editor, so autoLayout.ts#WIDE_DECLARED_FIELD_TYPES widens it by its object-field type, read in both form renderers), and objectui @b9814b334 packages/components/src/renderers/form/form.tsx#spanLadderFor emits one clamped col-span class per multi-column tier (`@md:col-span-2 @2xl:col-span-3` for a 3-column grid; the widest-tier-only under-span of #17328 ended with objectui#9244 / objectui#9253). A form row's `scale` reaches `Intl.NumberFormat` through plugin-form (see field.json row `scale`). [#27155] The section key `pane` (split-pane placement) is REMOVED 2026-10-28 with `type: 'split'` (ADR-0050): a retiredKey() tombstone in FormSectionSchema carrying the prescription, stripped by the protocol-18 form-view-presentation-types-removed conversion. The subtree has no per-key rows, so the tombstone adds none; the retirement is registered as ui/FormSection:pane in RETIRED_KEYS_BY_MAJOR[18]." - }, - "groups": { - "status": "live", - "verifiedAt": "2026-08-09", - "evidenceScope": "in-repo", - "evidence": "packages/spec/src/ui/view.zod.ts (foldFormGroupsIntoSections + the .overwrite on FormViewSchema — the PRODUCER fold, #6926: groups-only folds onto sections, sections wins when both are present, and groups is absent from every parsed form); ui/packages/plugin-form/src/ObjectForm.tsx (:129-142 at objectui @7b3e048) (objectui @7b3e048 — the pre-existing boundary folds, now redundant for parsed forms and retiring in a later cross-repo lap)", - "note": "WHERE THE FOLD LIVES: at the producer, as of #6926 — a `.overwrite()` on FormViewSchema, inherited by every parse door (ViewSchema.form/.formViews.*, both ViewItemSchema form arms, and ViewMetadataSchema's container AND flattened form-overlay members, which picks it up through .extend()). Before #6926 the alias was declared but folded NOWHERE in this repo: it was honored one boundary downstream in objectui (alias-at-one-boundary, objectui#2545, after a groups-only spec rendered nothing), while the framework's REST public-form routes read `sections` only — so the same authored form rendered in the console and degraded on GET /forms/:slug, POST /forms/:slug/submit and GET /forms/:slug/lookup/:field. That omission is what let #6926 be filed reading a live key as dead; it is recorded here so the next reader cannot repeat it. STILL NOT FOLDED (measured 2026-08-09, #6926): a RUNTIME-saved sys_metadata row — saveMetaItem validates through ViewMetadataSchema and then deliberately discards parsed.data to keep Studio round-trip keys, and the read replays the ADR-0087 stored-row conversion chain, which is not a zod parse. Code-authored views (defineView/defineMetadataForm → registry) DO reach REST folded. Pre-parse consumers still read the authored key and are right to: packages/lint's view rules walk authored sources. Audit L24 drift resolved by alias-at-one-boundary; superseded by the producer fold. 2026-10-26 (#25712, objectui merged into this repo as ui/): the spec-bridge clause (`form-view.ts:169`) was dropped, not repointed: objectui#6632 retired the spec-bridge. ObjectForm's line range is kept as the @7b3e048 reading; it does not match today's file." - }, - "subforms": { - "status": "live", - "verifiedAt": "2026-08-10", - "evidenceScope": "in-repo", - "evidence": "ui/packages/plugin-form/src/ObjectForm.tsx (:175 at objectui @11c1e71e) branches on schema.subforms and :197 hands it to MasterDetailForm as `details`; ui/packages/plugin-form/src/MasterDetailForm.tsx (:315 at objectui @11c1e71e) reads schema.details and :240 renders one panel per entry, with :227 summing their amount fields; ui/packages/plugin-form/src/ModalForm.tsx:1080 and ui/packages/plugin-form/src/DrawerForm.tsx:909 take the same key through their own envelopes (ModalForm applies at :1117/:1153, DrawerForm at :921) — measured objectui @11c1e71e", - "note": "RE-CITED 2026-08-10 (#7133/#7142): the old citation named deriveMasterDetail.ts:338 and LineItemsPanel.tsx:45, and neither file mentions `subforms` at objectui @11c1e71e. deriveMasterDetail DERIVES master-detail panels from relationship metadata — its output is merged with the authored key one level up, in app-shell MetadataProvider.tsx:304-307 — and LineItemsPanel.tsx:41-55 is the per-panel schema, one hop past the rename to `details`. The form renderers are the readers that branch on the authored key. Verdict unchanged: LIVE, master-detail fully wired (audit L17)." - }, - "sharing": { - "status": "live", - "verifiedAt": "2026-08-28", - "evidence": "packages/rest/src/form-routes.ts#findPublicForm (`for (const c of anonymousFormIntakeCandidates(view))` then `if (c.slug !== slug) continue;` — the public form doors serve only a candidate whose slug matches); packages/spec/src/ui/anonymous-form-intake.ts#anonymousFormIntakeCandidates (hands each form's `sharing` to `anonymousFormIntakeSlug`, across the nested `form`, every `formViews` entry and the flattened `config` of a `viewKind: 'form'` item); packages/spec/src/ui/anonymous-form-intake.ts#anonymousFormIntakeSlug (the slug rule reads all three keys: `if (s.enabled !== true) return null;`, `if (s.allowAnonymous !== true) return null;`, `if (typeof s.publicLink !== 'string' || !s.publicLink) return null;`); packages/rest/src/form-routes.ts#resolveFormBySlug (both doors resolve the match through it, and the submit door grants `publicFormGrant: { object: match.object }` for the matched form's object)", - "note": "Framework-side consumer: public (anonymous) form endpoints opt in via FormView.sharing — /forms/:slug resolves sharing.publicLink across form + formViews (rest-server.ts:1716, :4366-4405) and grants publicFormGrant. Renderer-side the config is not read (audit L20) — the public form is served, not re-parsed client-side. 2026-08-28: RE-ANCHORED (commit 8f10a79f7) and REPOINTED — `:4384` had rotted onto a comment about `api`-only route enumeration, ~4,020 lines above the form endpoints; the note's own inline pointers (`:1716`, `:4366-4405`) had gone with it and are superseded by the anchors. Re-closed by hand against 8cb96ec41." - }, - "submitBehavior": { - "status": "live", - "note": "objectui: WizardForm.tsx:315-316 + ObjectForm.tsx dispatch thank-you/redirect/continue/next-record; covered by ObjectForm.submitBehavior.test.tsx / WizardForm.successBehavior.test.tsx. Supersedes the 2026-06 audit's DEAD line (L20) — wiring landed with the objectui#2545/#2552 reconciliation." - }, - "buttons": { - "status": "live", - "note": "objectui: ObjectForm.tsx foldFormButtons() reads schema.buttons and folds submit/cancel {show,label} onto the flat showSubmit/submitText/showCancel/cancelText props (framework#1894 / #2998); ObjectView forwards it, and every console form entry point resolves submit/cancel through resolveFormViewChrome / readFormButton (#26843). Flat keys kept as deprecated back-compat (explicit flat key wins). SUB-KEY buttons.reset REMOVED 2026-10-28 (#27153, ADR-0049 enforce-or-remove, ruled retire): measured at origin/main fbe344b3, six button bars (components form.tsx, console FormPage, ModalForm, DrawerForm, WizardForm, MasterDetailForm) drew submit/cancel and none drew reset; reset.label had no reader; the one fold of reset.show landed on ObjectForm showReset, which means clear-after-save (resetOnSubmit), not a button. Tombstoned inside the buttons block (retiredKey carries the prescription) and stripped from stored rows and sources by the protocol-18 form-view-buttons-reset-removed conversion; the fold was removed in the same change. Sub-keys cannot be drilled (one level only), so the removal is recorded here; submit and cancel keep this row live." - }, - "defaults": { - "status": "live", - "note": "objectui: ObjectForm.tsx foldFormButtons() reads schema.defaults and folds it into create-mode initialValues (framework#1894 / #2998); an explicit initialValues (URL prefill) still wins." - } - } + "status": "dead", + "verifiedAt": "2026-12-01", + "note": "REMOVED 2026-12-01 (ADR-0159 D7) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error) and moved out of sources by the protocol-19 conversion view-forms-to-form-items. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent); a form is its own metadata type, authored under the stack's `forms:` as a `form` item named `OBJECT.form`, and its keys are classified in liveness/form.json. The per-key `children` this row carried went with the container: the walk no longer drills a tombstone. Stored rows are not rewritten: a view read serves lists only and drops the form member, and the kept withdrawal reader still reads a stored row's form through the projection (ADR-0159 D6 rules 10 and 11)." }, "listViews": { "status": "live", @@ -409,10 +289,9 @@ "note": "Named list views. Framework: expandViewContainer flattens container views into per-object view items (collision diagnostics via expandViewContainerWithDiagnostics). objectui: MetadataProvider.tsx:118-146 merges view metadata into objectDef.listViews — the saved-view switcher (ViewTabBar) reads only listViews (ADR-0047 'views' mode). Same inner shape as `list`; per-key classification lives under list.children. 2026-08-28: RE-ANCHORED (commit 8f10a79f7) and REPOINTED — `:1432` had rotted onto the same schema-declaration line its sibling `list.name` carried; two keys shared one wrong pointer. Re-closed by hand against 8cb96ec41." }, "formViews": { - "status": "live", - "verifiedAt": "2026-08-28", - "evidence": "packages/spec/src/ui/anonymous-form-intake.ts#anonymousFormIntakeCandidates (`for (const [key, fv] of Object.entries(v.formViews)) forms.push({ form: fv, key });` — every named form view is a public-link candidate); packages/spec/src/ui/view.zod.ts#expandViewContainerWithDiagnostics (flattens them into independent ViewItems)", - "note": "Named form views. Framework: public-form slug resolution scans form + every formViews entry (rest-server.ts:4384-4405); expandViewContainer flattens them. objectui: MetadataProvider routes viewKind:'form' items into objectDef.formViews (never into the list switcher). Same inner shape as `form`; per-key classification lives under form.children. 2026-08-28: RE-ANCHORED (commit 8f10a79f7) and REPOINTED — `:4384` had rotted onto the same `api`-only comment its sibling `form.sharing` cited; the note's `rest-server.ts:4384-4405` range went with it. Re-closed by hand against 8cb96ec41." + "status": "dead", + "verifiedAt": "2026-12-01", + "note": "REMOVED 2026-12-01 (ADR-0159 D7) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error) and moved out of sources by the protocol-19 conversion view-forms-to-form-items. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent); each named form is a `form` item `OBJECT.KEY` under the stack's `forms:` (a create or edit form nothing else opens is deleted, not moved), classified in liveness/form.json. Stored rows are not rewritten: a view read drops the member, and the kept withdrawal reader still reads it through the projection (ADR-0159 D6 rules 10 and 11)." } } } diff --git a/packages/spec/scripts/build-schemas-check-mode.git-topology.test.ts b/packages/spec/scripts/build-schemas-check-mode.git-topology.test.ts index 16521fb533d..cc6794da034 100644 --- a/packages/spec/scripts/build-schemas-check-mode.git-topology.test.ts +++ b/packages/spec/scripts/build-schemas-check-mode.git-topology.test.ts @@ -292,7 +292,8 @@ describe('build-schemas.ts — the drift notice names the direction it measured /** Only in `mainTip`: what origin/main added after the anchor. */ const LANDED_KEY = 'data/Object:description'; /** A key in a DIFFERENT shard, so the unordered fixture's two sides merge without conflict. */ - const UI_KEY = 'ui/View:form'; + // [ADR-0159 D7] `ui/View:form` until protocol 19 tombstoned it ([RETIRED] in the baseline). + const UI_KEY = 'ui/View:listViews'; /** The branch's fork point: upstream, and behind the committed anchor. */ let older: string; diff --git a/packages/spec/scripts/liveness/key-mention.baseline.json b/packages/spec/scripts/liveness/key-mention.baseline.json index 7f4cbd3d47f..dd6b8528ecb 100644 --- a/packages/spec/scripts/liveness/key-mention.baseline.json +++ b/packages/spec/scripts/liveness/key-mention.baseline.json @@ -65,11 +65,6 @@ "path": "ui/packages/plugin-grid/src/ObjectGrid.tsx", "why": "A RENAMED key: ListView forwards `inlineEdit` to the grid node as `editable`, and ObjectGrid reads `schema.editable` (the cell editor, renderCellEditor, and the save/cancel column). The entry's ListView citation names `inlineEdit`. Surfaced when the citation moved from objectui into ui/ (#25712)." }, - { - "entry": "view/form.subforms", - "path": "ui/packages/plugin-form/src/MasterDetailForm.tsx", - "why": "A RENAMED key: ObjectForm hands `subforms` to MasterDetailForm as `details`, and this file reads `details` (`MasterDetailDetailConfig[]`, one panel per entry). The entry's ObjectForm citation names `subforms`. Surfaced when the citation moved from objectui into ui/ (#25712)." - }, { "entry": "translation/flows.screens", "path": "ui/packages/app-shell/src/views/ScreenView.tsx", diff --git a/packages/spec/scripts/liveness/undrilled-containers.baseline.json b/packages/spec/scripts/liveness/undrilled-containers.baseline.json index 28b887127dc..6dff1ceb1ee 100644 --- a/packages/spec/scripts/liveness/undrilled-containers.baseline.json +++ b/packages/spec/scripts/liveness/undrilled-containers.baseline.json @@ -30,11 +30,6 @@ "to": "view/list", "why": "the ViewItem container's list surface — `view.list` is the drilled coordinate for it." }, - { - "container": "view/formViews", - "to": "view/form", - "why": "the ViewItem container's form surface — `view.form` is the drilled coordinate for it." - }, { "container": "manifest/data", "to": "seed", @@ -136,11 +131,6 @@ "translation/objects", "translation/pages", "translation/settingsCommon", - "view/form.buttons", - "view/form.groups", - "view/form.sections", - "view/form.sharing", - "view/form.subforms", "view/list.addRecord", "view/list.appearance", "view/list.aria", diff --git a/packages/spec/scripts/zod-graph.test.ts b/packages/spec/scripts/zod-graph.test.ts index a3ab62f5afa..b199bd4756e 100644 --- a/packages/spec/scripts/zod-graph.test.ts +++ b/packages/spec/scripts/zod-graph.test.ts @@ -231,17 +231,19 @@ describe('pipeAuthorableSide — the registered metadata-type roots (#5317)', () const shape = zodShapeOf(schema!); expect(shape).not.toBeNull(); - // Not a key count (89 today, and every view feature moves it) — one key that - // ONLY a given member declares, so the assertion fails if the merge ever - // silently collapses to a single member. All four members are represented, - // the first of them a nested union: + // Not a key count (every view feature moves it) — one key that ONLY a + // given member declares, so the assertion fails if the merge ever silently + // collapses to a single member. All three members are represented, the + // first of them a nested union: expect(Object.keys(shape ?? {})).toEqual( expect.arrayContaining([ 'isPinned', // member 0 only — and member 0 is itself a union 'list', // the defineView container member 'pagination', // the flattened list-view member - 'sections', // the flattened form-view member ]), ); + // [ADR-0159 D7] There were four members until protocol 19; the flattened + // form-view member left with the form arm, and its keys with it. + expect(Object.keys(shape ?? {})).not.toContain('sections'); }); }); diff --git a/packages/spec/src/api/error-code-ledger.test.ts b/packages/spec/src/api/error-code-ledger.test.ts index 730c6eb2c56..8401cb47f03 100644 --- a/packages/spec/src/api/error-code-ledger.test.ts +++ b/packages/spec/src/api/error-code-ledger.test.ts @@ -295,6 +295,25 @@ describe('ErrorCode (standard ∪ registered)', () => { expect(STANDARD_SYNONYM_WAIVERS.map((w) => w.code)).not.toContain(code); }); + it('accepts the protocol-19 boot refusal\'s code under the runtime, as its own meaning (door: none)', () => { + // ADR-0159 D7, ruling 7303149461: `os serve` refuses a database whose + // protocol-19 switch is not recorded. `@objectstack/runtime`'s + // `FormTypeSwitchBootRefusal` stamps it and its kernel suite asserts this + // exact string by value — pinned here too. Thrown at boot, before any + // socket opens: registered on the "door or no door" rule, like the v18 + // organization-ownership refusal beside it. + const code = 'FORM_TYPE_SWITCH_REQUIRED'; + expect(ErrorCode.parse(code)).toBe(code); + expect(ERROR_CODE_LEDGER['@objectstack/runtime'], `${code} registered under runtime`).toContain(code); + expect(REGISTERED_ERROR_CODES).toContain(code); + // FORM, TYPE and SWITCH are tokens no standard member carries: not a + // synonym of any standard code, and no waiver. + expect(standardSynonymOf(code), `${code} needs no waiver`).toBeUndefined(); + expect(STANDARD_SYNONYM_WAIVERS.map((w) => w.code)).not.toContain(code); + // Not a re-spelling of the v18 refusal: both stay registered, each its own act. + expect(ERROR_CODE_LEDGER['@objectstack/runtime']).toContain('ORGANIZATION_OWNERSHIP_MIGRATION_REQUIRED'); + }); + it('accepts the package disable door\'s dependent-validation-rule refusal code, registered ahead of its runtime producer', () => { // ADR-0141 Open item 4, ruling A on #30379: the disable door answers 409 // while an enabled package's validation rule reads a field the package diff --git a/packages/spec/src/api/error-code-ledger.zod.ts b/packages/spec/src/api/error-code-ledger.zod.ts index 8aedf2dab8d..fa783eb63a7 100644 --- a/packages/spec/src/api/error-code-ledger.zod.ts +++ b/packages/spec/src/api/error-code-ledger.zod.ts @@ -513,6 +513,21 @@ export const ERROR_CODE_LEDGER = { // WALLED_MEMBERSHIP_POLICY_UNDECLARED precedent); the `code` lets a host // discriminate the refusal structurally. No escape hatch exists (D10). 'ORGANIZATION_OWNERSHIP_MIGRATION_REQUIRED', + // [ADR-0159 D7, ruling 7303149461] The protocol-19 boot refusal + // (`FormTypeSwitchBootGuardPlugin`, `form-type-switch-boot-guard.ts`): + // `os serve` refuses to start against a database whose protocol-19 switch + // is not recorded: the `sys_migration` row `adr-0159-form-type-switch` is + // absent, unverified or unreadable, and the boot did not create the + // database from empty. Thrown from the plugin's `start()`, or by `os serve` + // before the kernel starts when another plugin took the guard's name, so + // no request is ever served (`door: 'none'`, the + // ORGANIZATION_OWNERSHIP_MIGRATION_REQUIRED precedent one row up); the + // `code` lets a host discriminate the refusal structurally. No switch + // skips it. The remedy is the command the message names: + // `os migrate protocol --to 19`. FORM, TYPE and SWITCH are tokens no + // standard member carries, and it is not a synonym of the row above: that + // one is the v18 organization-ownership ceremony, this one the v19 switch. + 'FORM_TYPE_SWITCH_REQUIRED', // [#7557] `DELETE /packages/:id` on the DISPATCHER door — per-item failures // used to ride inside a 200 with a hardcoded `success: true`. Second // EMITTER of the code `@objectstack/rest` already registers for the diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 6538b76a6c0..5e36c90b34d 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -3318,6 +3318,12 @@ export const GetUiViewRequestSchema = lazySchema(() => z.object({ /** * Get UI View Response + * + * For `type: 'list'` the answer is a view (`ViewSchema`). For `type: 'form'` + * it is the form scaffold `{ object, form }`, its `form` a form body + * (`FormViewSchema`): the {@link GetUiViewResponse} type is the union of the + * two. [ADR-0159 D7] A view holds lists only since @objectstack/spec 19, so + * the scaffold is typed on its own; the answer is the same as before. */ export const GetUiViewResponseSchema = lazySchema(() => ViewSchema); @@ -5170,9 +5176,11 @@ export type GetMetaItemCachedResponse = z.input; export type GetUiViewRequest = z.input; -export type GetUiViewResponse = z.input; +/** [ADR-0159 D7] The form scaffold `getUiView` answers for `type: 'form'`. */ +export type GetUiViewFormScaffold = { object: string; form: z.input }; +export type GetUiViewResponse = z.input | GetUiViewFormScaffold; /** Post-parse shape of {@link GetUiViewResponse} — defaults applied, transforms run (ADR-0122). */ -export type GetUiViewResponseParsed = z.infer; +export type GetUiViewResponseParsed = z.infer | { object: string; form: z.infer }; type AnalyticsQueryRequest = z.infer; type AnalyticsResultResponse = z.infer; diff --git a/packages/spec/src/index.ts b/packages/spec/src/index.ts index 57b18cd7332..98f13545dbf 100644 --- a/packages/spec/src/index.ts +++ b/packages/spec/src/index.ts @@ -111,7 +111,7 @@ export type { DefineStackOptions, ComposeStacksOptions, ConflictStrategy, Object export * from './stack.zod'; // DX Helper Functions (re-exported for convenience) -export { defineView, defineForm, defineMetadataForm, defineViewItem, isAggregatedViewContainer, expandViewContainer, expandViewContainerWithDiagnostics } from './ui/view.zod'; +export { defineView, defineForm, defineMetadataForm, defineViewItem, isAggregatedViewContainer, expandViewContainer, expandServedViewContainer, isServedViewItem, expandViewContainerWithDiagnostics } from './ui/view.zod'; // [#22934] Which object an aggregated `views` container binds to — the registrars' // slot key, and the identity the stack's same-stack duplicate-entry refusal reads. // `@objectstack/metadata` re-exports this declaration under the same name. diff --git a/packages/spec/src/inline-grid-column-carriers.test.ts b/packages/spec/src/inline-grid-column-carriers.test.ts index 0b59eeae0a6..c3f0a54c95d 100644 --- a/packages/spec/src/inline-grid-column-carriers.test.ts +++ b/packages/spec/src/inline-grid-column-carriers.test.ts @@ -47,7 +47,7 @@ import { ALL_CONVERSIONS } from './conversions/registry'; import { applyConversionsToStoredItem } from './conversions/stored'; import { InlineGridColumnSchema } from './data/field.zod'; import { applyMetaMigrations } from './migrations/chain'; -import { FormViewSchema, ViewMetadataSchema } from './ui/view.zod'; +import { FormSchema, FormViewSchema, ViewMetadataSchema } from './ui/view.zod'; import { ComponentPropsMap } from './ui/component.zod'; import { defineStack } from './stack.zod'; @@ -97,18 +97,24 @@ const childObject = (inlineColumns?: unknown[]) => ({ type FormSlot = 'form' | 'formViews'; -const stackWithSubformColumns = (columns: unknown[], slot: FormSlot = 'form', child = 'crm_invoice_line') => { - const form = { ...FORM_BASE, subforms: [{ childObject: child, columns }] }; - return { - manifest, - objects: [PARENT, childObject()], - views: [{ - name: 'crm_invoice', - object: 'crm_invoice', - ...(slot === 'form' ? { form } : { formViews: { entry: form } }), - }], - }; -}; +/** + * [ADR-0159 D7] Until protocol 19 the form carrier sat on a view container, + * as its default `form` or a named `formViews` entry. A view holds lists only + * since protocol 19, so each slot is a `form` item now: the default form is + * `crm_invoice.form`, the named entry `crm_invoice.entry`. + */ +const FORM_NAME: Record = { form: 'crm_invoice.form', formViews: 'crm_invoice.entry' }; + +const stackWithSubformColumns = (columns: unknown[], slot: FormSlot = 'form', child = 'crm_invoice_line') => ({ + manifest, + objects: [PARENT, childObject()], + forms: [{ + name: FORM_NAME[slot], + object: 'crm_invoice', + ...FORM_BASE, + subforms: [{ childObject: child, columns }], + }], +}); const stackWithInlineColumns = (inlineColumns: unknown[]) => ({ manifest, @@ -197,17 +203,19 @@ describe('the form-view carrier references the column contract', () => { }); describe('defineStack judges an identity-only column by the type it renders as', () => { - it('refuses the card\'s identity-only column over a currency child field on the form view\'s `form`', () => { + // [ADR-0159 D7] These two read `View[0].form…` and `View[0].formViews.entry…` + // until protocol 19; the carrier is a `form` item now, located by its name. + it('refuses the card\'s identity-only column over a currency child field on a `form` item (the pre-19 default `form`)', () => { expectHydratedCurrencyRefusal( stackWithSubformColumns([{ name: 'quantity' }, IDENTITY_ONLY_WITH_SCALE]), - 'View[0].form.subforms[0].columns[1].scale', + "Form 'crm_invoice.form'.subforms[0].columns[1].scale", ); }); - it('refuses it on a named `formViews` entry too', () => { + it('refuses it on a second `form` item too (the pre-19 named `formViews` entry)', () => { expectHydratedCurrencyRefusal( stackWithSubformColumns([IDENTITY_ONLY_WITH_SCALE], 'formViews'), - 'View[0].formViews.entry.subforms[0].columns[0].scale', + "Form 'crm_invoice.entry'.subforms[0].columns[0].scale", ); }); @@ -359,12 +367,28 @@ describe('the `field` → `name` respelling is a chain step on the form-view car expect(conversion()?.retiredAfter).toBe('17.5.0'); }); - it('a stored row in each `view` spelling is respelled, and only then parses', () => { + /** The form body a stored row carries, in whichever spelling it is stored. */ + const formBodyOf = (row: Record): Record => { + if (row.formViews?.entry) return row.formViews.entry; + if (row.config) return row.config; + const { name: _n, object: _o, viewKind: _k, ...body } = row; + return body; + }; + + // [ADR-0159 D7] Until protocol 19 the respelled row then parsed as a `view`. + // The stored seam still respells it (stored rows are not rewritten into + // `form` items), but a view holds lists only now: the respelled row is + // refused at the `view` door, and its form body parses as a `form` item. + it('a stored row in each `view` spelling is respelled; its form body then parses as a `form` item', () => { for (const [spelling, row] of Object.entries(storedRows(LEGACY))) { expect(ViewMetadataSchema.safeParse(row).success, `${spelling}, as stored`).toBe(false); const converted = applyConversionsToStoredItem('view', structuredClone(row)) as Record; expect(columnsOf(converted), spelling).toEqual(RESPELLED); - expect(ViewMetadataSchema.safeParse(converted).success, `${spelling}, converted`).toBe(true); + expect(ViewMetadataSchema.safeParse(converted).success, `${spelling}, converted, at the view door`).toBe(false); + const asItem = FormSchema.safeParse({ name: 'crm_invoice.entry', object: 'crm_invoice', ...formBodyOf(converted) }); + expect(asItem.success, `${spelling}, converted, as a form item: ${JSON.stringify(asItem.error?.issues)}`).toBe(true); + expect(FormSchema.safeParse({ name: 'crm_invoice.entry', object: 'crm_invoice', ...formBodyOf(row) }).success, + `${spelling}, as stored, as a form item`).toBe(false); } }); @@ -376,7 +400,14 @@ describe('the `field` → `name` respelling is a chain step on the form-view car }); it('`os migrate meta` replays it: the step-18 chain respells a source stack, one edit per column', () => { - const result = applyMetaMigrations(structuredClone(stackWithSubformColumns(LEGACY, 'formViews')), 17, 18); + // A protocol-17 source: the form still sits on the view container, as it + // did then ([ADR-0159 D7] the 18 → 19 step moves it to a `form` item). + const source17 = { + manifest, + objects: [PARENT, childObject()], + views: [{ name: 'crm_invoice', object: 'crm_invoice', formViews: { entry: form(LEGACY) } }], + }; + const result = applyMetaMigrations(structuredClone(source17), 17, 18); const views = result.stack.views as Array>; expect(views[0].formViews.entry.subforms[0].columns).toEqual(RESPELLED); expect(result.applied.filter((a) => a.conversionId === ID).map((a) => a.path)).toEqual([ diff --git a/packages/spec/src/migrations/entries/retired-keys/19.api__GetUiViewResponse__form.ts b/packages/spec/src/migrations/entries/retired-keys/19.api__GetUiViewResponse__form.ts new file mode 100644 index 00000000000..5b12960a09a --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-keys/19.api__GetUiViewResponse__form.ts @@ -0,0 +1,6 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// ADR-0159 D7 — `GetUiViewResponseSchema` is `ViewSchema` by reference, so the +// response carries the `ui/View:form` tombstone (see that row): a view read +// serves lists only. +export const entry = 'api/GetUiViewResponse:form'; diff --git a/packages/spec/src/migrations/entries/retired-keys/19.api__GetUiViewResponse__formViews.ts b/packages/spec/src/migrations/entries/retired-keys/19.api__GetUiViewResponse__formViews.ts new file mode 100644 index 00000000000..bedd8a40eb6 --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-keys/19.api__GetUiViewResponse__formViews.ts @@ -0,0 +1,5 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// ADR-0159 D7 — `GetUiViewResponseSchema` is `ViewSchema` by reference, so the +// response carries the `ui/View:formViews` tombstone (see that row). +export const entry = 'api/GetUiViewResponse:formViews'; diff --git a/packages/spec/src/migrations/entries/retired-keys/19.ui__View__form.ts b/packages/spec/src/migrations/entries/retired-keys/19.ui__View__form.ts new file mode 100644 index 00000000000..5b8e4086424 --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-keys/19.ui__View__form.ts @@ -0,0 +1,9 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// ADR-0159 D7 — a `view` holds lists only, and a form is its own metadata type +// (`form`, under the stack's `forms:`). The container's default `form` is +// tombstoned with `retiredKey()`, its prescription naming the `form` item +// `OBJECT.form`. Stored rows are not rewritten (they are read by the kept +// withdrawal reader and dropped from what a view serves); sources are moved by +// the D2 conversion `view-forms-to-form-items`. +export const entry = 'ui/View:form'; diff --git a/packages/spec/src/migrations/entries/retired-keys/19.ui__View__formViews.ts b/packages/spec/src/migrations/entries/retired-keys/19.ui__View__formViews.ts new file mode 100644 index 00000000000..ddebe7a3ff9 --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-keys/19.ui__View__formViews.ts @@ -0,0 +1,7 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// ADR-0159 D7 — the container's named forms, the sibling of `ui/View:form` +// (see that row). Each entry moves to a `form` item `OBJECT.KEY` by the D2 +// conversion `view-forms-to-form-items`; a create or edit form that nothing +// else opens is deleted, not moved (#36425). +export const entry = 'ui/View:formViews'; diff --git a/packages/spec/src/shared/retired-key-removal-version.pin.test.ts b/packages/spec/src/shared/retired-key-removal-version.pin.test.ts index 9de26725f91..c014e7479bc 100644 --- a/packages/spec/src/shared/retired-key-removal-version.pin.test.ts +++ b/packages/spec/src/shared/retired-key-removal-version.pin.test.ts @@ -511,7 +511,8 @@ const JOIN: Readonly> = { // refusal is read off a parse. 'view-column-state-removed': [ tombstone(VIEW_METADATA_MEMBERS.listOverlay, 'view (list overlay)', 'columnState'), - tombstone(VIEW_METADATA_MEMBERS.formOverlay, 'view (form overlay)', 'columnState'), + // [ADR-0159 D7] The form overlay member that carried the second tombstone + // was retired in protocol 19; the list overlay and the record remain. refusal( 'a view item record carrying columnState', () => VIEW_METADATA_MEMBERS.viewItem.safeParse({ diff --git a/packages/spec/src/stack-compose-duplicate-entry-census.test.ts b/packages/spec/src/stack-compose-duplicate-entry-census.test.ts index 05a9282098c..582a33e1124 100644 --- a/packages/spec/src/stack-compose-duplicate-entry-census.test.ts +++ b/packages/spec/src/stack-compose-duplicate-entry-census.test.ts @@ -111,10 +111,11 @@ const CENSUS: readonly Row[] = [ byName('aiContexts', 'AI context pack', { name: 'dupe_pack', label: 'Pack', object: 'dupe_thing', fields: ['title'] }), { // The second container binds the same object the other way round: no - // top-level `object`, the binding read off its form. + // top-level `object`, the binding read off its list. [ADR-0159 D7] It read + // the binding off a `form` until protocol 19; a view holds lists only now. key: 'views', first: { object: 'dupe_thing', list: listOf('dupe_thing') }, - second: { form: { type: 'simple', data: { provider: 'object', object: 'dupe_thing' }, sections: [{ fields: ['title'] }] } }, + second: { list: listOf('dupe_thing') }, subject: "View container 'dupe_thing'", }, { diff --git a/packages/spec/src/stack-duplicate-entry.test.ts b/packages/spec/src/stack-duplicate-entry.test.ts index b33f3ea7532..09de5778670 100644 --- a/packages/spec/src/stack-duplicate-entry.test.ts +++ b/packages/spec/src/stack-duplicate-entry.test.ts @@ -150,10 +150,10 @@ const BATCH: readonly Row[] = [ entry: { object: 'dupe_thing', list: listOf('dupe_thing') }, identity: 'dupe_thing', // A second container for the same object, written the other way round: - // no top-level `object`, the binding read off its form instead. - sameIdentity: () => ({ - form: { type: 'simple', data: { provider: 'object', object: 'dupe_thing' }, sections: [{ fields: ['title'] }] }, - }), + // no top-level `object`, the binding read off its list instead. + // [ADR-0159 D7] It read the binding off a `form` until protocol 19; a + // view holds lists only now. + sameIdentity: () => ({ list: listOf('dupe_thing') }), otherIdentity: () => ({ object: 'dupe_second', list: listOf('dupe_second') }), subject: "View container 'dupe_thing'", context: { objects: [thing, { ...thing, name: 'dupe_second', label: 'Second' }] }, diff --git a/packages/spec/src/stack-extension-hook-view-foreign-object.test.ts b/packages/spec/src/stack-extension-hook-view-foreign-object.test.ts index 22444a52b0f..a899d23163a 100644 --- a/packages/spec/src/stack-extension-hook-view-foreign-object.test.ts +++ b/packages/spec/src/stack-extension-hook-view-foreign-object.test.ts @@ -9,9 +9,11 @@ * build, even when the stack extends that object through `objectExtensions`. * ADR-0130 §1.5 records that refusal as deliberate: "the split must follow * hook ownership". A hook on an object the stack defines is accepted; - * - a top-level view whose `list` or `form` data source is an object the stack - * does not define is refused the same way, extended or not. A view on an - * object the stack defines is accepted. + * - a top-level view whose `list` data source is an object the stack does not + * define is refused the same way, extended or not. A view on an object the + * stack defines is accepted. ([ADR-0159 D7] A view's `form` was judged here + * too until protocol 19; a view holds lists only now, and a view carrying a + * `form` is refused at the schema parse, before any cross-reference.) * * Both refusals come from `validateCrossReferences` in `stack.zod.ts`, which * keeps exactly what it accepts and refuses; only the guidance text names it. @@ -65,10 +67,15 @@ describe('defineStack and a top-level view whose data source is an object outsid expect(err.message).toContain(`View[0].list references object '${FOREIGN}'`); }); - it('refuses a view whose `form` reads an object the stack only extends', () => { - const err = refusalOf({ manifest, objects: [OWN], objectExtensions: extendsForeign, views: [formView(FOREIGN)] }); - expect(err).toMatchObject({ code: 'STACK_CROSS_REFERENCE_INVALID', status: 422 }); - expect(err.message).toContain(`View[0].form references object '${FOREIGN}'`); + // [ADR-0159 D7] Refused as a cross-reference until protocol 19. The view's + // `form` is tombstoned now, so the refusal moves earlier, to the schema + // parse, and carries the D7 prescription whatever object the form reads. + it('refuses a view whose `form` reads an object the stack only extends — at the schema parse since protocol 19', () => { + for (const object of [FOREIGN, OWN.name]) { + const err = refusalOf({ manifest, objects: [OWN], objectExtensions: extendsForeign, views: [formView(object)] }); + expect(err).toMatchObject({ code: 'STACK_SCHEMA_INVALID', status: 422 }); + expect(err.message).toContain('`view.form` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7)'); + } }); it('accepts a view on an object the stack defines (the control)', () => { diff --git a/packages/spec/src/stack.zod.ts b/packages/spec/src/stack.zod.ts index 2ec4ff50a96..8c5c4aece4d 100644 --- a/packages/spec/src/stack.zod.ts +++ b/packages/spec/src/stack.zod.ts @@ -3479,11 +3479,10 @@ const SAME_STACK_ENTRY_IDENTITY = Object.freeze({ subject: (object) => `View container '${object}'`, consequence: () => 'The runtime files a `views` container under the object it binds to (`object`, else ' + - '`list.data.object`, else `form.data.object`, else its `name`), so these entries occupy one ' + + '`list.data.object`, else its `name`), so these entries occupy one ' + 'registry slot and only the last of them is kept in it.', remedy: () => - 'Keep one container per object: merge their `list`, `form`, `listViews` and `formViews` into a ' + - 'single entry.', + 'Keep one container per object: merge their `list` and `listViews` into a single entry.', }, apis: { identity: readEntryName, @@ -5074,9 +5073,9 @@ function collectExtensionPlacementErrors(config: ObjectStackDefinition): string[ * * - a relationship field's `inlineColumns` — the field sits on the CHILD * object, so a column names a field of the object that owns the field; - * - a form view's `subforms[].columns` (the container's `form` and each - * `formViews` entry) — a column names a field of the subform's - * `childObject`; + * - a `form` item's `subforms[].columns` — a column names a field of the + * subform's `childObject` (ADR-0159: a form is a `form` item; the view + * container's `form` and `formViews` were retired in protocol 19); * - [#20928] an `object-master-detail-form` page block's `details[].columns`, * wherever the block sits on a page ({@link forEachPageComponent}) — a column * names a field of the detail entry's `childObject`; @@ -5133,20 +5132,14 @@ function collectHydratedInlineColumnErrors(config: ObjectStackDefinition): strin } } - for (const [i, view] of (config.views ?? []).entries()) { - const forms: Array<[where: string, form: unknown]> = []; - if (view.form) forms.push([`View[${i}].form`, view.form]); - for (const [key, form] of Object.entries(view.formViews ?? {})) { - forms.push([`View[${i}].formViews.${key}`, form]); - } - for (const [where, form] of forms) { - const subforms = isRecord(form) ? form.subforms : undefined; - if (!Array.isArray(subforms)) continue; - subforms.forEach((subform: unknown, j: number) => { - if (!isRecord(subform) || typeof subform.childObject !== 'string') return; - judge(subform.columns, subform.childObject, `${where}.subforms[${j}].columns`); - }); - } + for (const [i, form] of (config.forms ?? []).entries()) { + const where = isRecord(form) && typeof form.name === 'string' ? `Form '${form.name}'` : `Form[${i}]`; + const subforms = isRecord(form) ? form.subforms : undefined; + if (!Array.isArray(subforms)) continue; + subforms.forEach((subform: unknown, j: number) => { + if (!isRecord(subform) || typeof subform.childObject !== 'string') return; + judge(subform.columns, subform.childObject, `${where}.subforms[${j}].columns`); + }); } // [#20928] The page carriers: `properties` is an open record the stack's @@ -6491,9 +6484,6 @@ function validateCrossReferences( if (view.list?.data) { checkViewData(view.list.data, `View[${i}].list`); } - if (view.form?.data) { - checkViewData(view.form.data, `View[${i}].form`); - } } } diff --git a/packages/spec/src/system/i18n-resolver.form-item.test.ts b/packages/spec/src/system/i18n-resolver.form-item.test.ts index 4372c56175c..10eee6fd229 100644 --- a/packages/spec/src/system/i18n-resolver.form-item.test.ts +++ b/packages/spec/src/system/i18n-resolver.form-item.test.ts @@ -2,10 +2,11 @@ /** * [ADR-0159 card ② item 8] The `forms` translation family: a `form` item's - * `label`, `description`, `title` and `submitBehavior` read `forms.NAME` - * first; `title` and `submitBehavior` fall back to the `_views.KEY` tails a - * pack keyed under the old view address carries; `_views.KEY.label` is never - * read (a view's label names the view, not the form). + * `label`, `description`, `title` and `submitBehavior` read `forms.NAME`. + * Until protocol 19 `title` and `submitBehavior` fell back to the `_views.KEY` + * tails a pack keyed under the old view address carried; [ADR-0159 D8] those + * tails are tombstoned in protocol 19 and read by nothing, and `_views.KEY.label` + * was never read (a view's label names the view, not the form). */ import { describe, expect, it } from 'vitest'; @@ -42,7 +43,7 @@ const ZH_VIEWS_ONLY = { }, }; -describe('translateForm — the `forms` family, `_views` tails as fallback', () => { +describe('translateForm — the `forms` family, and no `_views` tail since protocol 19', () => { it('composes a legal pack: the `forms` group is part of the translation data', () => { const parsed = TranslationDataSchema.safeParse(ZH_FORMS); expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); @@ -59,12 +60,17 @@ describe('translateForm — the `forms` family, `_views` tails as fallback', () }); }); - it('falls back to the `_views.KEY` tails for title and submitBehavior, never for the label', () => { + // [ADR-0159 D8] This case pinned the fallback until protocol 19; the + // fallback is gone, so a pack keyed only under the old address translates + // nothing of the form. + it('reads no `_views.KEY` tail for title, submitBehavior or the label (protocol 19)', () => { const bundle: TranslationBundle = { 'zh-CN': ZH_VIEWS_ONLY as any }; - const out = translateForm(clone(FORM), bundle, { locale: 'zh-CN' }) as any; - expect(out.title).toBe('旧地址标题'); - expect(out.submitBehavior.message).toBe('旧地址消息'); + const doc = clone(FORM); + const out = translateForm(doc, bundle, { locale: 'zh-CN' }) as any; + expect(out.title).toBe('Contact us'); + expect(out.submitBehavior.message).toBe('We will be in touch.'); expect(out.label).toBe('Web to lead'); + expect(out).toBe(doc); }); it('`forms.NAME` wins over the `_views` tail when both are present', () => { diff --git a/packages/spec/src/system/i18n-resolver.form-sections.test.ts b/packages/spec/src/system/i18n-resolver.form-sections.test.ts index a00fb05a0b8..8690de737ed 100644 --- a/packages/spec/src/system/i18n-resolver.form-sections.test.ts +++ b/packages/spec/src/system/i18n-resolver.form-sections.test.ts @@ -1,11 +1,11 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * Pin: `translateView` localizes a served FORM view's `sections` — each - * section's `label` and `description` — through + * Pin: a form's `sections` — each section's `label` and `description`, and + * each entry's `label`, `placeholder` and `helpText` — are localized through * `objects.._sections.`, on the shared locale chain and under - * the same catalog-vs-explicit-override rule as every other string the view - * translator overlays (ADR-0029 D9.2a). + * the same catalog-vs-explicit-override rule as every other overlaid string + * (ADR-0029 D9.2a). * * Before this, `TranslationDataSchema` declared the key, the i18n extractor * scaffolded it and objectui's form renderers resolved it client-side, but no @@ -14,24 +14,31 @@ * bundle — served every section heading as authored, beside translated field * labels. * - * The served documents below are what `expandViewContainer` emits from an - * authored container (the composer the registrars run), and both the - * container and the bundle's object node are PARSED by the authoring schemas, - * so a section address or a catalog key neither schema carries cannot pass. + * [ADR-0159 D7] Until protocol 19 these were FORM views, served by + * `expandViewContainer` with the sections under `config` and translated by + * `translateView`. A view holds lists only since protocol 19: the same bodies + * are `form` items, sections at the top level, translated by + * {@link translateForm} (whose own `forms.NAME.sections` node is pinned in + * `i18n-resolver.form-item.test.ts`; `_sections` is the object-level default + * read here). Every fixture is PARSED by `FormSchema` and the pack by the + * bundle schema, so a section address or a catalog key neither schema carries + * cannot pass. */ import { describe, it, expect } from 'vitest'; -import { translateView, translateMetadataDocument } from './i18n-resolver'; +import { translateForm, translateMetadataDocument } from './i18n-resolver'; import { ObjectTranslationDataSchema, type TranslationBundle } from './translation.zod'; -import { ViewSchema, expandViewContainer } from '../ui/view.zod'; +import { FormSchema } from '../ui/view.zod'; const clone = (v: T): T => JSON.parse(JSON.stringify(v)); -/** The container as the package ships it. */ -const CONTAINER = { - form: { - type: 'simple' as const, - data: { provider: 'object' as const, object: 'crm_lead' }, +/** The forms as the package ships them. */ +const FORMS: Record = { + // The pre-19 default form, keyed by its runtime identity `form`. + 'crm_lead.form': { + name: 'crm_lead.form', + object: 'crm_lead', + type: 'simple', sections: [ { name: 'basics', label: 'Basics', description: 'Who is asking', fields: ['name'] }, // No bundle entry — the negative control for a missing key. @@ -43,19 +50,19 @@ const CONTAINER = { { name: 'extra', fields: ['phone'] }, ], }, - formViews: { - // Retargeted at another object: its sections key under the form's OWN - // binding, the object the extractor and the linter bind them to. - referral: { - type: 'simple' as const, - data: { provider: 'object' as const, object: 'crm_contact' }, - sections: [{ name: 'basics', label: 'Basics', fields: ['name'] }], - }, + // Bound to another object: its sections key under the form's OWN binding, + // the object the extractor and the linter bind them to. (Until protocol 19 + // this was a `crm_lead` view retargeted through `data.object`.) + 'crm_contact.referral': { + name: 'crm_contact.referral', + object: 'crm_contact', + type: 'simple', + sections: [{ name: 'basics', label: 'Basics', fields: ['name'] }], }, }; const served = (name: string): any => { - const item = expandViewContainer('crm_lead', CONTAINER).find((v) => v.name === name); + const item = FORMS[name]; if (!item) throw new Error(`fixture missing ${name}`); return item; }; @@ -80,111 +87,112 @@ const BUNDLE: TranslationBundle = { 'zh-CN': { objects: { crm_lead: LEAD_ZH, crm_contact: CONTACT_ZH } } as any, }; -const section = (view: any, name: string): any => view.config.sections.find((s: any) => s.name === name); +const section = (form: any, name: string): any => form.sections.find((s: any) => s.name === name); -describe('translateView — a form view\'s sections, keyed under `_sections`', () => { - it('composes the identity this test is pinned to — legal fixtures, sections live under `config`', () => { - expect(ViewSchema.safeParse(CONTAINER).success).toBe(true); +describe('translateForm — a form\'s sections, keyed under `_sections`', () => { + it('composes the identity this test is pinned to — legal fixtures, sections are the form item\'s own key', () => { + for (const f of Object.values(FORMS)) { + const parsed = FormSchema.safeParse(f); + expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); + } for (const node of [LEAD_ZH, LEAD_EN, CONTACT_ZH]) { expect(ObjectTranslationDataSchema.safeParse(node).success).toBe(true); } - expect(PACKAGED.viewKind).toBe('form'); expect(PACKAGED.object).toBe('crm_lead'); - expect(PACKAGED.sections).toBeUndefined(); - expect(PACKAGED.config.sections.map((s: any) => s.name)).toEqual(['basics', 'notes', undefined, 'extra']); + expect(PACKAGED.sections.map((s: any) => s.name)).toEqual(['basics', 'notes', undefined, 'extra']); }); it('a zh-CN pack with a `_sections` key yields the translated label and description', () => { - const out = translateMetadataDocument('view', clone(PACKAGED), BUNDLE, { locale: 'zh-CN' }); + const out = translateMetadataDocument('form', clone(PACKAGED), BUNDLE, { locale: 'zh-CN' }); expect(section(out, 'basics')).toMatchObject({ label: '基本信息', description: '咨询人是谁', fields: ['name'] }); }); it('a missing key yields the authored text', () => { - const out = translateMetadataDocument('view', clone(PACKAGED), BUNDLE, { locale: 'zh-CN' }); - expect(section(out, 'notes')).toEqual(PACKAGED.config.sections[1]); + const out = translateMetadataDocument('form', clone(PACKAGED), BUNDLE, { locale: 'zh-CN' }); + expect(section(out, 'notes')).toEqual(PACKAGED.sections[1]); // A key that carries a label but no description leaves the description as authored. - const label = translateMetadataDocument('view', clone(served('crm_lead.referral')), BUNDLE, { locale: 'zh-CN' }); + const label = translateMetadataDocument('form', clone(served('crm_contact.referral')), BUNDLE, { locale: 'zh-CN' }); expect(section(label, 'basics').label).toBe('联系人基本信息'); expect(section(label, 'basics').description).toBeUndefined(); }); it('a section with no `name` is left as authored — it has no key, and its label is never slugged into one', () => { const doc = clone(PACKAGED); - const out = translateView(doc, BUNDLE, { locale: 'zh-CN' }) as any; - expect(out.config.sections[2]).toBe(doc.config.sections[2]); - expect(out.config.sections[2]).toMatchObject({ label: 'Contact Details', description: 'How to reach them' }); + const out = translateForm(doc, BUNDLE, { locale: 'zh-CN' }) as any; + expect(out.sections[2]).toBe(doc.sections[2]); + expect(out.sections[2]).toMatchObject({ label: 'Contact Details', description: 'How to reach them' }); }); it('the catalog translates authored copy only — it never adds a heading or a description', () => { - const out = translateView(clone(PACKAGED), BUNDLE, { locale: 'zh-CN' }) as any; + const out = translateForm(clone(PACKAGED), BUNDLE, { locale: 'zh-CN' }) as any; expect(section(out, 'extra').label).toBeUndefined(); expect(section(out, 'extra').description).toBeUndefined(); }); it('an inline locale map heading is authored text and takes the catalog, as a view label does', () => { const doc = clone(PACKAGED); - doc.config.sections[0].label = { en: 'Basics', 'zh-CN': '基础' }; - const out = translateView(doc, BUNDLE, { locale: 'zh-CN' }) as any; + doc.sections[0].label = { en: 'Basics', 'zh-CN': '基础' }; + const out = translateForm(doc, BUNDLE, { locale: 'zh-CN' }) as any; expect(section(out, 'basics').label).toBe('基本信息'); }); - it('keys a retargeted form\'s sections under the form\'s own `data.object`', () => { - const referral = served('crm_lead.referral'); - expect(referral.object).toBe('crm_lead'); - const out = translateView(clone(referral), BUNDLE, { locale: 'zh-CN' }) as any; + it('keys a form\'s sections under the form\'s own `object`', () => { + const referral = served('crm_contact.referral'); + expect(referral.object).toBe('crm_contact'); + const out = translateForm(clone(referral), BUNDLE, { locale: 'zh-CN' }) as any; // `crm_lead._sections.basics` would read 基本信息; the form binds crm_contact. expect(section(out, 'basics').label).toBe('联系人基本信息'); }); it('walks the shared locale chain — BCP-47 ladder, declared fallback chain, default locale', () => { - expect(section(translateView(clone(PACKAGED), BUNDLE, { locale: 'zh' }), 'basics').label).toBe('基本信息'); - const viaChain = translateView(clone(PACKAGED), BUNDLE, { locale: 'fr-FR', fallbackChain: ['zh-CN'] }); + expect(section(translateForm(clone(PACKAGED), BUNDLE, { locale: 'zh' }), 'basics').label).toBe('基本信息'); + const viaChain = translateForm(clone(PACKAGED), BUNDLE, { locale: 'fr-FR', fallbackChain: ['zh-CN'] }); expect(section(viaChain, 'basics').label).toBe('基本信息'); // A request for the default locale never walks the chain: the authored text answers. - const asDefault = translateView(clone(PACKAGED), BUNDLE, { + const asDefault = translateForm(clone(PACKAGED), BUNDLE, { locale: 'fr-FR', defaultLocale: 'fr-FR', fallbackChain: ['zh-CN'], }); expect(section(asDefault, 'basics').label).toBe('Basics'); }); - it('returns the SAME `config` reference when no section gained a translation, and never mutates its input', () => { + it('returns the SAME document when no section gained a translation, and never mutates its input', () => { const doc = clone(PACKAGED); - expect((translateView(doc, { 'ja-JP': {} }, { locale: 'ja-JP' }) as any).config).toBe(doc.config); + expect(translateForm(doc, { 'ja-JP': {} }, { locale: 'ja-JP' })).toBe(doc); const before = clone(doc); - translateView(doc, BUNDLE, { locale: 'zh-CN' }); + translateForm(doc, BUNDLE, { locale: 'zh-CN' }); expect(doc).toEqual(before); }); }); -describe('translateView — a form section\'s copy loses to an explicit override (ADR-0029 D9.2a)', () => { - it('an unedited form view gets the catalog for every section string', () => { - const out = translateView(clone(PACKAGED), BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }); +describe('translateForm — a form section\'s copy loses to an explicit override (ADR-0029 D9.2a)', () => { + it('an unedited form gets the catalog for every section string', () => { + const out = translateForm(clone(PACKAGED), BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }); expect(section(out, 'basics')).toMatchObject({ label: '基本信息', description: '咨询人是谁' }); }); it('an edited heading is served as edited — in zh-CN and in the source locale — and judged apart from its description', () => { const doc = clone(PACKAGED); - doc.config.sections[0].label = 'Basics (edited)'; + doc.sections[0].label = 'Basics (edited)'; for (const locale of ['zh-CN', 'en']) { - const out = translateView(doc, BUNDLE, { locale, packagedBase: PACKAGED }); + const out = translateForm(doc, BUNDLE, { locale, packagedBase: PACKAGED }); expect(section(out, 'basics').label, locale).toBe('Basics (edited)'); } - expect(section(translateView(doc, BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }), 'basics').description) + expect(section(translateForm(doc, BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }), 'basics').description) .toBe('咨询人是谁'); }); it('a section the package does not ship was authored after the fact and keeps its strings', () => { const doc = clone(PACKAGED); - doc.config.sections[0].name = 'contact_details'; - doc.config.sections[0].label = 'Added by the org'; - const out = translateView(doc, BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }); + doc.sections[0].name = 'contact_details'; + doc.sections[0].label = 'Added by the org'; + const out = translateForm(doc, BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }); expect(section(out, 'contact_details').label).toBe('Added by the org'); }); it('NO packaged base supplied → the catalog applies (the control)', () => { const doc = clone(PACKAGED); - doc.config.sections[0].label = 'Basics (edited)'; - expect(section(translateView(doc, BUNDLE, { locale: 'zh-CN' }), 'basics').label).toBe('基本信息'); + doc.sections[0].label = 'Basics (edited)'; + expect(section(translateForm(doc, BUNDLE, { locale: 'zh-CN' }), 'basics').label).toBe('基本信息'); }); }); @@ -193,32 +201,29 @@ describe('translateView — a form section\'s copy loses to an explicit override * `helpText` for that form alone, and those three are addressed under the * section's own node: `objects.._sections.
.fields.`. */ -const ENTRY_CONTAINER = { - form: { - type: 'simple' as const, - data: { provider: 'object' as const, object: 'crm_case' }, - sections: [ - { - name: 'submitter', - label: 'About you', - fields: [ - { field: 'contact_name', label: 'Your name', placeholder: 'Jane Doe', helpText: 'As on your ID' }, - // Authors only a label: the catalog never adds a placeholder or help text. - { field: 'contact_email', label: 'Your email' }, - // A bare name authors no copy at all. - 'subject', - // No bundle entry — the negative control for a missing key. - { field: 'phone', label: 'Your phone', placeholder: '+1 555', helpText: 'Optional' }, - ], - }, - // No `name`: its entries have no address, whatever the bundle carries. - { label: 'Details', fields: [{ field: 'description', label: 'What happened' }] }, - ], - }, +const ENTRY_PACKAGED: any = { + name: 'crm_case.form', + object: 'crm_case', + type: 'simple', + sections: [ + { + name: 'submitter', + label: 'About you', + fields: [ + { field: 'contact_name', label: 'Your name', placeholder: 'Jane Doe', helpText: 'As on your ID' }, + // Authors only a label: the catalog never adds a placeholder or help text. + { field: 'contact_email', label: 'Your email' }, + // A bare name authors no copy at all. + 'subject', + // No bundle entry — the negative control for a missing key. + { field: 'phone', label: 'Your phone', placeholder: '+1 555', helpText: 'Optional' }, + ], + }, + // No `name`: its entries have no address, whatever the bundle carries. + { label: 'Details', fields: [{ field: 'description', label: 'What happened' }] }, + ], }; -const ENTRY_PACKAGED: any = expandViewContainer('crm_case', ENTRY_CONTAINER).find((v) => v.name === 'crm_case.form'); - const CASE_ZH = { _sections: { submitter: { @@ -235,72 +240,72 @@ const CASE_ZH = { const ENTRY_BUNDLE: TranslationBundle = { 'zh-CN': { objects: { crm_case: CASE_ZH } } as any }; -const entry = (view: any, sectionIndex: number, field: string): any => - view.config.sections[sectionIndex].fields.find((f: any) => (typeof f === 'string' ? f : f.field) === field); +const entry = (form: any, sectionIndex: number, field: string): any => + form.sections[sectionIndex].fields.find((f: any) => (typeof f === 'string' ? f : f.field) === field); -describe('translateView — a form section entry\'s copy, keyed under `_sections.
.fields.`', () => { - it('composes legal fixtures — the container and the pack node both parse', () => { - expect(ViewSchema.safeParse(ENTRY_CONTAINER).success).toBe(true); +describe('translateForm — a form section entry\'s copy, keyed under `_sections.
.fields.`', () => { + it('composes legal fixtures — the form and the pack node both parse', () => { + expect(FormSchema.safeParse(ENTRY_PACKAGED).success).toBe(true); expect(ObjectTranslationDataSchema.safeParse(CASE_ZH).success).toBe(true); - expect(ENTRY_PACKAGED.config.sections[0].fields).toHaveLength(4); + expect(ENTRY_PACKAGED.sections[0].fields).toHaveLength(4); }); it('a zh-CN pack yields the translated entry `label`', () => { - const out = translateView(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN' }); + const out = translateForm(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN' }); expect(entry(out, 0, 'contact_name').label).toBe('您的姓名'); }); it('a zh-CN pack yields the translated entry `placeholder`', () => { - const out = translateView(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN' }); + const out = translateForm(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN' }); expect(entry(out, 0, 'contact_name').placeholder).toBe('张三'); }); it('a zh-CN pack yields the translated entry `helpText`', () => { - const out = translateView(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN' }); + const out = translateForm(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN' }); expect(entry(out, 0, 'contact_name').helpText).toBe('与证件一致'); // The section heading beside it is translated by the same reading. - expect(out.config.sections[0].label).toBe('关于您'); + expect(out.sections[0].label).toBe('关于您'); }); it('a missing key yields the authored entry copy', () => { - const out = translateView(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN' }); - expect(entry(out, 0, 'phone')).toEqual(ENTRY_PACKAGED.config.sections[0].fields[3]); + const out = translateForm(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN' }); + expect(entry(out, 0, 'phone')).toEqual(ENTRY_PACKAGED.sections[0].fields[3]); }); it('only authored copy is translated — the catalog never adds a placeholder or help text, nor copy to a bare name', () => { - const out = translateView(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN' }); + const out = translateForm(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN' }); expect(entry(out, 0, 'contact_email')).toEqual({ field: 'contact_email', label: '您的邮箱' }); expect(entry(out, 0, 'subject')).toBe('subject'); }); it('an entry of a section with no `name` is left as authored', () => { const doc = clone(ENTRY_PACKAGED); - const out = translateView(doc, ENTRY_BUNDLE, { locale: 'zh-CN' }) as any; - expect(out.config.sections[1]).toBe(doc.config.sections[1]); + const out = translateForm(doc, ENTRY_BUNDLE, { locale: 'zh-CN' }) as any; + expect(out.sections[1]).toBe(doc.sections[1]); }); it('an edited entry string keeps its value against the packaged base, judged apart from its siblings', () => { const doc = clone(ENTRY_PACKAGED); - doc.config.sections[0].fields[0].label = 'Full name (edited)'; - const out = translateView(doc, ENTRY_BUNDLE, { locale: 'zh-CN', packagedBase: ENTRY_PACKAGED }); + doc.sections[0].fields[0].label = 'Full name (edited)'; + const out = translateForm(doc, ENTRY_BUNDLE, { locale: 'zh-CN', packagedBase: ENTRY_PACKAGED }); expect(entry(out, 0, 'contact_name')).toMatchObject({ label: 'Full name (edited)', placeholder: '张三', helpText: '与证件一致', }); // NO packaged base supplied → the catalog applies (the control). - expect(entry(translateView(doc, ENTRY_BUNDLE, { locale: 'zh-CN' }), 0, 'contact_name').label).toBe('您的姓名'); + expect(entry(translateForm(doc, ENTRY_BUNDLE, { locale: 'zh-CN' }), 0, 'contact_name').label).toBe('您的姓名'); }); it('an entry the packaged section does not carry was authored after the fact and keeps its strings', () => { const base = clone(ENTRY_PACKAGED); - base.config.sections[0].fields = base.config.sections[0].fields.slice(1); - const out = translateView(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN', packagedBase: base }); + base.sections[0].fields = base.sections[0].fields.slice(1); + const out = translateForm(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN', packagedBase: base }); expect(entry(out, 0, 'contact_name').label).toBe('Your name'); }); it('never mutates its input', () => { const doc = clone(ENTRY_PACKAGED); const before = clone(doc); - translateView(doc, ENTRY_BUNDLE, { locale: 'zh-CN' }); + translateForm(doc, ENTRY_BUNDLE, { locale: 'zh-CN' }); expect(doc).toEqual(before); }); }); diff --git a/packages/spec/src/system/i18n-resolver.form-thank-you.test.ts b/packages/spec/src/system/i18n-resolver.form-thank-you.test.ts index 9b23c4874af..2ae04bbe5da 100644 --- a/packages/spec/src/system/i18n-resolver.form-thank-you.test.ts +++ b/packages/spec/src/system/i18n-resolver.form-thank-you.test.ts @@ -1,184 +1,157 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * Pin: `translateView` localizes a served FORM view's thank-you panel — the - * `title` and `message` of a `kind: 'thank-you'` `FormViewSchema - * .submitBehavior`, served at `config.submitBehavior` — through - * `objects.._views..submitBehavior.{title,message}`, on the - * shared locale chain and under the same catalog-vs-explicit-override rule as - * every other string the view translator overlays (ADR-0029 D9.2a). + * Pin: a form's thank-you panel (the `title` and `message` of a + * `kind: 'thank-you'` `submitBehavior`) is localized on the shared locale chain + * and under the same catalog-vs-explicit-override rule as every other overlaid + * string (ADR-0029 D9.2a). * - * Before this, the panel had no translation key at all: the strict `_views` - * entry declared no `submitBehavior`, and `translateView` never read - * `config.submitBehavior`. A public form read in another language showed a - * translated heading and field labels, then confirmed the submit in the - * authoring language. - * - * The served documents below are what `expandViewContainer` emits from an - * authored container, and both the container and the bundle's object node are - * PARSED by the authoring schemas, so an address neither schema carries cannot - * pass. + * Before protocol 19 the panel belonged to a FORM view, served at + * `config.submitBehavior`, and was translated through + * `objects.._views..submitBehavior.{title,message}`. + * [ADR-0159 D7/D8] A view holds lists only since protocol 19 and a form is a + * `form` item: the panel is translated through `forms..submitBehavior` + * by {@link translateForm}, and `translateView` reads no `_views` form tail. + * Each case below is the pre-19 case, rewritten to that answer; the last blocks + * pin the panel face at its new address and the old address as refused. */ import { describe, it, expect } from 'vitest'; -import { translateView, translateMetadataDocument } from './i18n-resolver'; -import { ObjectTranslationDataSchema, type TranslationBundle } from './translation.zod'; -import { ViewSchema, expandViewContainer } from '../ui/view.zod'; +import { translateForm, translateView, translateMetadataDocument } from './i18n-resolver'; +import { ObjectTranslationDataSchema, TranslationDataSchema, type TranslationBundle } from './translation.zod'; +import { FormSchema, expandViewContainer } from '../ui/view.zod'; const clone = (v: T): T => JSON.parse(JSON.stringify(v)); -const data = { provider: 'object' as const, object: 'crm_lead' }; const sections = [{ name: 'basics', label: 'Basics', fields: ['name'] }]; +const form = (name: string, extra: Record): any => ({ + name: `crm_lead.${name}`, + object: 'crm_lead', + type: 'simple', + sections, + ...extra, +}); -const CONTAINER = { - form: { - type: 'simple' as const, - data, - sections, - submitBehavior: { kind: 'thank-you' as const, title: 'Saved', message: 'The lead is in.' }, - }, - formViews: { - web_to_lead: { - type: 'simple' as const, - data, - title: 'Contact us', - sections, - submitBehavior: { kind: 'thank-you' as const, title: 'Thanks!', message: 'We will reach out shortly.' }, - }, - // Authors a title and no message: the bundle's message must not invent one. - title_only: { - type: 'simple' as const, - data, - sections, - submitBehavior: { kind: 'thank-you' as const, title: 'Got it' }, - }, - // Not a thank-you panel: its keys translate nothing. - redirect: { - type: 'simple' as const, - data, - sections, - submitBehavior: { kind: 'redirect' as const, url: '/thanks' }, - }, - // Authors a panel the bundle carries no key for. - referral: { - type: 'simple' as const, - data, - sections, - submitBehavior: { kind: 'thank-you' as const, title: 'Referral sent', message: 'Thank you for the referral.' }, - }, - }, -}; - -const served = (name: string): any => { - const item = expandViewContainer('crm_lead', CONTAINER).find((v) => v.name === name); - if (!item) throw new Error(`fixture missing ${name}`); - return item; +const FORMS: Record = { + // The pre-19 default form, keyed by its runtime identity `form`. + form: form('form', { submitBehavior: { kind: 'thank-you', title: 'Saved', message: 'The lead is in.' } }), + web_to_lead: form('web_to_lead', { + title: 'Contact us', + submitBehavior: { kind: 'thank-you', title: 'Thanks!', message: 'We will reach out shortly.' }, + }), + // Authors a title and no message: the bundle's message must not invent one. + title_only: form('title_only', { submitBehavior: { kind: 'thank-you', title: 'Got it' } }), + // Not a thank-you panel: its keys translate nothing. + redirect: form('redirect', { submitBehavior: { kind: 'redirect', url: '/thanks' } }), + // Authors a panel the bundle carries no key for. + referral: form('referral', { + submitBehavior: { kind: 'thank-you', title: 'Referral sent', message: 'Thank you for the referral.' }, + }), }; -const LEAD_ZH = { - _views: { - web_to_lead: { +const ZH = { + forms: { + 'crm_lead.web_to_lead': { title: '联系我们', submitBehavior: { title: '感谢您!', message: '我们会尽快与您联系。' }, }, - form: { submitBehavior: { title: '已保存', message: '线索已录入。' } }, - title_only: { submitBehavior: { title: '收到', message: 'MUST-NOT-APPLY' } }, - redirect: { submitBehavior: { title: 'MUST-NOT-APPLY', message: 'MUST-NOT-APPLY' } }, + 'crm_lead.form': { submitBehavior: { title: '已保存', message: '线索已录入。' } }, + 'crm_lead.title_only': { submitBehavior: { title: '收到', message: 'MUST-NOT-APPLY' } }, + 'crm_lead.redirect': { submitBehavior: { title: 'MUST-NOT-APPLY', message: 'MUST-NOT-APPLY' } }, }, }; -const LEAD_EN = { _views: { web_to_lead: { submitBehavior: { title: 'Thanks!' } } } }; +const EN = { forms: { 'crm_lead.web_to_lead': { submitBehavior: { title: 'Thanks!' } } } }; const BUNDLE: TranslationBundle = { - en: { objects: { crm_lead: LEAD_EN } } as any, - 'zh-CN': { objects: { crm_lead: LEAD_ZH } } as any, + en: EN as any, + 'zh-CN': ZH as any, }; -describe("translateView — a form view's thank-you panel, keyed `_views..submitBehavior`", () => { - it('composes the identity this test is pinned to — legal fixtures, the panel lives under `config`', () => { - expect(ViewSchema.safeParse(CONTAINER).success).toBe(true); - for (const node of [LEAD_ZH, LEAD_EN]) { - const parsed = ObjectTranslationDataSchema.safeParse(node); +describe("translateForm — a form's thank-you panel, keyed `forms..submitBehavior` (protocol 19)", () => { + it('composes the identity this test is pinned to — legal fixtures, the panel is the form item\'s own key', () => { + for (const f of Object.values(FORMS)) { + const parsed = FormSchema.safeParse(f); + expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); + } + for (const pack of [ZH, EN]) { + const parsed = TranslationDataSchema.safeParse(pack); expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); } - const item = served('crm_lead.web_to_lead'); - expect(item.viewKind).toBe('form'); - expect(item.config.submitBehavior).toEqual(CONTAINER.formViews.web_to_lead.submitBehavior); }); it('a zh-CN pack yields the translated panel title and message', () => { - const out = translateMetadataDocument('view', clone(served('crm_lead.web_to_lead')), BUNDLE, { locale: 'zh-CN' }); - expect(out.config.submitBehavior).toEqual({ kind: 'thank-you', title: '感谢您!', message: '我们会尽快与您联系。' }); + const out = translateMetadataDocument('form', clone(FORMS.web_to_lead), BUNDLE, { locale: 'zh-CN' }) as any; + expect(out.submitBehavior).toEqual({ kind: 'thank-you', title: '感谢您!', message: '我们会尽快与您联系。' }); // The form heading is translated beside it, from its own key. - expect(out.config.title).toBe('联系我们'); - // The default form is keyed by its runtime identity, `form`. - const def = translateMetadataDocument('view', clone(served('crm_lead.form')), BUNDLE, { locale: 'zh-CN' }); - expect(def.config.submitBehavior).toEqual({ kind: 'thank-you', title: '已保存', message: '线索已录入。' }); + expect(out.title).toBe('联系我们'); + const def = translateMetadataDocument('form', clone(FORMS.form), BUNDLE, { locale: 'zh-CN' }) as any; + expect(def.submitBehavior).toEqual({ kind: 'thank-you', title: '已保存', message: '线索已录入。' }); }); it('a locale the bundle lacks reads the declared fallback chain — ja-JP over `[zh-CN]`', () => { - const out = translateView(clone(served('crm_lead.web_to_lead')), BUNDLE, { locale: 'ja-JP', fallbackChain: ['zh-CN'] }) as any; - expect(out.config.submitBehavior.title).toBe('感谢您!'); - expect(out.config.submitBehavior.message).toBe('我们会尽快与您联系。'); + const out = translateForm(clone(FORMS.web_to_lead), BUNDLE, { locale: 'ja-JP', fallbackChain: ['zh-CN'] }) as any; + expect(out.submitBehavior.title).toBe('感谢您!'); + expect(out.submitBehavior.message).toBe('我们会尽快与您联系。'); }); it('a missing key yields the authored panel', () => { - const out = translateView(clone(served('crm_lead.referral')), BUNDLE, { locale: 'zh-CN' }) as any; - expect(out.config.submitBehavior).toEqual(CONTAINER.formViews.referral.submitBehavior); + const out = translateForm(clone(FORMS.referral), BUNDLE, { locale: 'zh-CN' }) as any; + expect(out.submitBehavior).toEqual(FORMS.referral.submitBehavior); }); it('CONTROL: a panel that authors no message gains none — the bundle key does not invent one', () => { - const out = translateView(clone(served('crm_lead.title_only')), BUNDLE, { locale: 'zh-CN' }) as any; - expect(out.config.submitBehavior).toEqual({ kind: 'thank-you', title: '收到' }); - expect('message' in out.config.submitBehavior).toBe(false); + const out = translateForm(clone(FORMS.title_only), BUNDLE, { locale: 'zh-CN' }) as any; + expect(out.submitBehavior).toEqual({ kind: 'thank-you', title: '收到' }); + expect('message' in out.submitBehavior).toBe(false); }); - it('CONTROL: a `redirect` behavior is not a panel — its keys translate nothing and its `config` reference is kept', () => { - const doc = clone(served('crm_lead.redirect')); - const out = translateView(doc, BUNDLE, { locale: 'zh-CN' }) as any; - expect(out.config).toBe(doc.config); - expect(out.config.submitBehavior).toEqual({ kind: 'redirect', url: '/thanks' }); + it('CONTROL: a `redirect` behavior is not a panel — its keys translate nothing and its reference is kept', () => { + const doc = clone(FORMS.redirect); + const out = translateForm(doc, BUNDLE, { locale: 'zh-CN' }) as any; + expect(out.submitBehavior).toBe(doc.submitBehavior); + expect(out.submitBehavior).toEqual({ kind: 'redirect', url: '/thanks' }); }); it('CONTROL: the panel title key does not reach the form heading, and the heading key does not reach the panel', () => { const headingOnly: TranslationBundle = { - 'zh-CN': { objects: { crm_lead: { _views: { web_to_lead: { title: '联系我们' } } } } } as any, + 'zh-CN': { forms: { 'crm_lead.web_to_lead': { title: '联系我们' } } } as any, }; - const viaHeading = translateView(clone(served('crm_lead.web_to_lead')), headingOnly, { locale: 'zh-CN' }) as any; - expect(viaHeading.config.title).toBe('联系我们'); - expect(viaHeading.config.submitBehavior.title).toBe('Thanks!'); + const viaHeading = translateForm(clone(FORMS.web_to_lead), headingOnly, { locale: 'zh-CN' }) as any; + expect(viaHeading.title).toBe('联系我们'); + expect(viaHeading.submitBehavior.title).toBe('Thanks!'); const panelOnly: TranslationBundle = { - 'zh-CN': { objects: { crm_lead: { _views: { web_to_lead: { submitBehavior: { title: '感谢您!' } } } } } } as any, + 'zh-CN': { forms: { 'crm_lead.web_to_lead': { submitBehavior: { title: '感谢您!' } } } } as any, }; - const viaPanel = translateView(clone(served('crm_lead.web_to_lead')), panelOnly, { locale: 'zh-CN' }) as any; - expect(viaPanel.config.title).toBe('Contact us'); - expect(viaPanel.config.submitBehavior.title).toBe('感谢您!'); + const viaPanel = translateForm(clone(FORMS.web_to_lead), panelOnly, { locale: 'zh-CN' }) as any; + expect(viaPanel.title).toBe('Contact us'); + expect(viaPanel.submitBehavior.title).toBe('感谢您!'); }); - it('an override beats the catalog — an edited panel string keeps the edit against the packaged view, per string', () => { - const packaged = served('crm_lead.web_to_lead'); + it('an override beats the catalog — an edited panel string keeps the edit against the packaged form, per string', () => { + const packaged = FORMS.web_to_lead; const edited = clone(packaged); - edited.config.submitBehavior.message = 'Sales will call you (edited)'; - const out = translateView(edited, BUNDLE, { locale: 'zh-CN', packagedBase: packaged }) as any; - expect(out.config.submitBehavior.message).toBe('Sales will call you (edited)'); + edited.submitBehavior.message = 'Sales will call you (edited)'; + const out = translateForm(edited, BUNDLE, { locale: 'zh-CN', packagedBase: packaged }) as any; + expect(out.submitBehavior.message).toBe('Sales will call you (edited)'); // The unedited sibling string, judged against the same base, translates. - expect(out.config.submitBehavior.title).toBe('感谢您!'); - // A packaged view with no panel makes every served string an authored one. + expect(out.submitBehavior.title).toBe('感谢您!'); + // A packaged form with no panel makes every served string an authored one. const bare = clone(packaged); - delete bare.config.submitBehavior; - const authored = translateView(clone(packaged), BUNDLE, { locale: 'zh-CN', packagedBase: bare }) as any; - expect(authored.config.submitBehavior.title).toBe('Thanks!'); + delete bare.submitBehavior; + const authored = translateForm(clone(packaged), BUNDLE, { locale: 'zh-CN', packagedBase: bare }) as any; + expect(authored.submitBehavior.title).toBe('Thanks!'); }); it('the served document is not mutated', () => { - const doc = clone(served('crm_lead.web_to_lead')); - translateView(doc, BUNDLE, { locale: 'zh-CN' }); - expect(doc.config.submitBehavior).toEqual(CONTAINER.formViews.web_to_lead.submitBehavior); + const doc = clone(FORMS.web_to_lead); + translateForm(doc, BUNDLE, { locale: 'zh-CN' }); + expect(doc.submitBehavior).toEqual(FORMS.web_to_lead.submitBehavior); }); }); -describe('the `_views..submitBehavior` translation face', () => { +describe('the `forms..submitBehavior` translation face', () => { const issuesOf = (node: unknown) => { - const parsed = ObjectTranslationDataSchema.safeParse({ _views: { web_to_lead: node } }); + const parsed = TranslationDataSchema.safeParse({ forms: { 'crm_lead.web_to_lead': node } }); return parsed.success ? [] : parsed.error.issues; }; @@ -186,7 +159,7 @@ describe('the `_views..submitBehavior` translation face', () => { expect(issuesOf({ submitBehavior: { title: '感谢您!', message: '我们会尽快与您联系。' } })).toEqual([]); const [issue] = issuesOf({ submitBehavior: { title: '感谢您!', url: '/zh/thanks' } }); expect(issue?.code).toBe('unrecognized_keys'); - expect(issue?.path).toEqual(['_views', 'web_to_lead', 'submitBehavior']); + expect(issue?.path).toEqual(['forms', 'crm_lead.web_to_lead', 'submitBehavior']); }); it('refuses a copied `kind` with a prescription naming the two translatable strings', () => { @@ -195,3 +168,27 @@ describe('the `_views..submitBehavior` translation face', () => { expect(issue?.message).toContain('`title` and `message`'); }); }); + +describe('the pre-19 address `objects.._views..submitBehavior` (ADR-0159 D8)', () => { + const OLD_PACK = { _views: { web_to_lead: { submitBehavior: { title: '感谢您!', message: '我们会尽快与您联系。' } } } }; + + it('is refused at the bundle, with the prescription naming `forms[\'OBJECT.KEY\'].submitBehavior`', () => { + const r = ObjectTranslationDataSchema.safeParse(OLD_PACK); + expect(r.success).toBe(false); + const issue = r.error?.issues.find((i) => i.path.join('.') === '_views.web_to_lead.submitBehavior'); + expect(issue?.message, JSON.stringify(r.error?.issues)).toMatch( + /^`translation\.objects\.OBJECT\._views\.KEY\.submitBehavior` was removed in @objectstack\/spec 19\.0\.0 \(ADR-0159 D8\)/, + ); + expect(issue?.message).toContain("forms['OBJECT.KEY'].submitBehavior"); + }); + + it('is read by nothing: neither `translateForm` nor `translateView` takes a panel string from it', () => { + const bundle: TranslationBundle = { 'zh-CN': { objects: { crm_lead: OLD_PACK } } as any }; + expect((translateForm(clone(FORMS.web_to_lead), bundle, { locale: 'zh-CN' }) as any).submitBehavior) + .toEqual(FORMS.web_to_lead.submitBehavior); + // A served view is a list since protocol 19; the tail reaches no key of it. + const list = clone(expandViewContainer('crm_lead', { list: { type: 'grid', columns: ['name'] } })[0]!) as any; + const out = translateView(list, bundle, { locale: 'zh-CN' }) as any; + expect(out.config.submitBehavior).toBeUndefined(); + }); +}); diff --git a/packages/spec/src/system/i18n-resolver.form-title.test.ts b/packages/spec/src/system/i18n-resolver.form-title.test.ts index 262b84d13f4..a0529801700 100644 --- a/packages/spec/src/system/i18n-resolver.form-title.test.ts +++ b/packages/spec/src/system/i18n-resolver.form-title.test.ts @@ -1,154 +1,152 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * Pin: `translateView` localizes a served FORM view's `title` - * (`FormViewSchema.title`, served at `config.title`) through - * `objects.._views..title`, on the shared locale chain and under - * the same catalog-vs-explicit-override rule as every other string the view - * translator overlays (ADR-0029 D9.2a). + * Pin: a form's `title` (the heading a public form shows above its sections) + * is localized on the shared locale chain and under the same + * catalog-vs-explicit-override rule as every other overlaid string + * (ADR-0029 D9.2a). * - * Before this, the title had no translation key at all: the `_views` entry - * named `title` as a rename onto `label`, and `translateView` never read - * `config.title`. A public form that declared a title served it in the - * authoring language to every visitor, so an app could not give a public form - * a localized title. + * Before protocol 19 the heading belonged to a FORM view, served at + * `config.title`, and was translated through `objects.._views..title`. + * [ADR-0159 D7/D8] A view holds lists only since protocol 19 and a form is a + * `form` item: the heading is translated through `forms..title` by + * {@link translateForm}, and `translateView` reads no `_views` form tail. Each + * case below is the pre-19 case, rewritten to that answer; the last block pins + * the old address as refused at the bundle and read by nothing. * - * `title` is its own key, not the view's `label` key, because they are two - * authored strings: a view item's `label` names the view (and a form-family - * container entry carries none), while the form's `title` is the heading the - * form shows. One translation cannot stand for two source strings. - * - * The served documents below are what `expandViewContainer` emits from an - * authored container, and both the container and the bundle's object node are - * PARSED by the authoring schemas, so an address neither schema carries cannot - * pass. + * `title` is its own key, not the form's `label` key, because they are two + * authored strings: the `label` names the form, the `title` is its heading. One + * translation cannot stand for two source strings. */ import { describe, it, expect } from 'vitest'; -import { translateView, translateMetadataDocument } from './i18n-resolver'; -import { ObjectTranslationDataSchema, type TranslationBundle } from './translation.zod'; -import { ViewSchema, expandViewContainer } from '../ui/view.zod'; +import { translateForm, translateView, translateMetadataDocument } from './i18n-resolver'; +import { ObjectTranslationDataSchema, TranslationDataSchema, type TranslationBundle } from './translation.zod'; +import { FormSchema, ViewSchema, expandViewContainer } from '../ui/view.zod'; const clone = (v: T): T => JSON.parse(JSON.stringify(v)); -const CONTAINER = { - form: { - type: 'simple' as const, - data: { provider: 'object' as const, object: 'crm_lead' }, - title: 'New lead', - sections: [{ name: 'basics', label: 'Basics', fields: ['name'] }], - }, - formViews: { - web_to_lead: { - type: 'simple' as const, - data: { provider: 'object' as const, object: 'crm_lead' }, - title: 'Contact us', - sections: [{ name: 'basics', label: 'Basics', fields: ['name'] }], - }, - // Authors no title: the bundle's key must not invent one. - quick: { - type: 'simple' as const, - data: { provider: 'object' as const, object: 'crm_lead' }, - sections: [{ name: 'basics', label: 'Basics', fields: ['name'] }], - }, - // Authors a title the bundle carries no key for. - referral: { - type: 'simple' as const, - data: { provider: 'object' as const, object: 'crm_lead' }, - title: 'Refer a friend', - sections: [{ name: 'basics', label: 'Basics', fields: ['name'] }], - }, - }, -}; +const form = (name: string, extra: Record = {}): any => ({ + name: `crm_lead.${name}`, + object: 'crm_lead', + type: 'simple', + sections: [{ name: 'basics', label: 'Basics', fields: ['name'] }], + ...extra, +}); -const served = (name: string): any => { - const item = expandViewContainer('crm_lead', CONTAINER).find((v) => v.name === name); - if (!item) throw new Error(`fixture missing ${name}`); - return item; +const FORMS: Record = { + // The pre-19 default form, keyed by its runtime identity `form`. + form: form('form', { title: 'New lead' }), + web_to_lead: form('web_to_lead', { label: 'Web to lead', title: 'Contact us' }), + // Authors no title: the bundle's key must not invent one. + quick: form('quick'), + // Authors a title the bundle carries no key for. + referral: form('referral', { title: 'Refer a friend' }), }; -const LEAD_ZH = { - label: '线索', - _views: { - web_to_lead: { title: '联系我们' }, - form: { title: '新建线索' }, - quick: { title: 'MUST-NOT-APPLY' }, +const ZH = { + forms: { + 'crm_lead.web_to_lead': { title: '联系我们' }, + 'crm_lead.form': { title: '新建线索' }, + 'crm_lead.quick': { title: 'MUST-NOT-APPLY' }, }, }; -const LEAD_EN = { _views: { web_to_lead: { title: 'Contact us' } } }; +const EN = { forms: { 'crm_lead.web_to_lead': { title: 'Contact us' } } }; const BUNDLE: TranslationBundle = { - en: { objects: { crm_lead: LEAD_EN } } as any, - 'zh-CN': { objects: { crm_lead: LEAD_ZH } } as any, + en: EN as any, + 'zh-CN': ZH as any, }; -describe('translateView — a form view\'s title, keyed `_views..title`', () => { - it('composes the identity this test is pinned to — legal fixtures, the title lives under `config`', () => { - expect(ViewSchema.safeParse(CONTAINER).success).toBe(true); - for (const node of [LEAD_ZH, LEAD_EN]) { - const parsed = ObjectTranslationDataSchema.safeParse(node); +describe('translateForm — a form\'s title, keyed `forms..title` (protocol 19)', () => { + it('composes the identity this test is pinned to — legal fixtures, the title is the form item\'s own key', () => { + for (const f of Object.values(FORMS)) { + const parsed = FormSchema.safeParse(f); + expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); + } + for (const pack of [ZH, EN]) { + const parsed = TranslationDataSchema.safeParse(pack); expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); } - const item = served('crm_lead.web_to_lead'); - expect(item.viewKind).toBe('form'); - expect(item.label).toBeUndefined(); - expect(item.config.title).toBe('Contact us'); + expect(FORMS.web_to_lead.title).toBe('Contact us'); }); - it('a zh-CN pack with a `_views..title` key yields the translated title', () => { - const out = translateMetadataDocument('view', clone(served('crm_lead.web_to_lead')), BUNDLE, { locale: 'zh-CN' }); - expect(out.config.title).toBe('联系我们'); - // The default form is keyed by its runtime identity, `form`. - const def = translateMetadataDocument('view', clone(served('crm_lead.form')), BUNDLE, { locale: 'zh-CN' }); - expect(def.config.title).toBe('新建线索'); + it('a zh-CN pack with a `forms..title` key yields the translated title', () => { + const out = translateMetadataDocument('form', clone(FORMS.web_to_lead), BUNDLE, { locale: 'zh-CN' }) as any; + expect(out.title).toBe('联系我们'); + const def = translateMetadataDocument('form', clone(FORMS.form), BUNDLE, { locale: 'zh-CN' }) as any; + expect(def.title).toBe('新建线索'); }); it('a locale the bundle lacks reads the declared fallback chain — ja-JP over `[zh-CN]`', () => { - const out = translateView(clone(served('crm_lead.web_to_lead')), BUNDLE, { locale: 'ja-JP', fallbackChain: ['zh-CN'] }) as any; - expect(out.config.title).toBe('联系我们'); + const out = translateForm(clone(FORMS.web_to_lead), BUNDLE, { locale: 'ja-JP', fallbackChain: ['zh-CN'] }) as any; + expect(out.title).toBe('联系我们'); }); it('a missing key yields the authored title', () => { - const out = translateView(clone(served('crm_lead.referral')), BUNDLE, { locale: 'zh-CN' }) as any; - expect(out.config.title).toBe('Refer a friend'); + const out = translateForm(clone(FORMS.referral), BUNDLE, { locale: 'zh-CN' }) as any; + expect(out.title).toBe('Refer a friend'); }); it('CONTROL: a form that authors no title gains none — the bundle key does not invent one', () => { - const doc = clone(served('crm_lead.quick')); - const out = translateView(doc, BUNDLE, { locale: 'zh-CN' }) as any; - expect(out.config.title).toBeUndefined(); - expect('title' in out.config).toBe(false); + const out = translateForm(clone(FORMS.quick), BUNDLE, { locale: 'zh-CN' }) as any; + expect(out.title).toBeUndefined(); + expect('title' in out).toBe(false); }); - it('CONTROL: the title key does not leak into the view `label`, and the `label` key does not reach the title', () => { - const out = translateView(clone(served('crm_lead.web_to_lead')), BUNDLE, { locale: 'zh-CN' }) as any; - // No `_views.web_to_lead.label` key: the label falls back to the item's - // name, exactly as before this change. - expect(out.label).toBe('crm_lead.web_to_lead'); + it('CONTROL: the title key does not leak into the form `label`, and the `label` key does not reach the title', () => { + const out = translateForm(clone(FORMS.web_to_lead), BUNDLE, { locale: 'zh-CN' }) as any; + expect(out.label).toBe('Web to lead'); const labelOnly: TranslationBundle = { - 'zh-CN': { objects: { crm_lead: { _views: { web_to_lead: { label: '网页线索' } } } } } as any, + 'zh-CN': { forms: { 'crm_lead.web_to_lead': { label: '网页线索' } } } as any, }; - const viaLabel = translateView(clone(served('crm_lead.web_to_lead')), labelOnly, { locale: 'zh-CN' }) as any; + const viaLabel = translateForm(clone(FORMS.web_to_lead), labelOnly, { locale: 'zh-CN' }) as any; expect(viaLabel.label).toBe('网页线索'); - expect(viaLabel.config.title).toBe('Contact us'); + expect(viaLabel.title).toBe('Contact us'); }); - it('an override beats the catalog — an edited title keeps the edit against the packaged view', () => { - const packaged = served('crm_lead.web_to_lead'); + it('an override beats the catalog — an edited title keeps the edit against the packaged form', () => { + const packaged = FORMS.web_to_lead; const edited = clone(packaged); - edited.config.title = 'Talk to sales (edited)'; - const out = translateView(edited, BUNDLE, { locale: 'zh-CN', packagedBase: packaged }) as any; - expect(out.config.title).toBe('Talk to sales (edited)'); + edited.title = 'Talk to sales (edited)'; + const out = translateForm(edited, BUNDLE, { locale: 'zh-CN', packagedBase: packaged }) as any; + expect(out.title).toBe('Talk to sales (edited)'); // CONTROL: the unedited title, judged against the same base, translates. - const same = translateView(clone(packaged), BUNDLE, { locale: 'zh-CN', packagedBase: packaged }) as any; - expect(same.config.title).toBe('联系我们'); + const same = translateForm(clone(packaged), BUNDLE, { locale: 'zh-CN', packagedBase: packaged }) as any; + expect(same.title).toBe('联系我们'); }); - it('the served document is not mutated, and a form with nothing to translate keeps its `config` reference', () => { - const doc = clone(served('crm_lead.web_to_lead')); - translateView(doc, BUNDLE, { locale: 'zh-CN' }); - expect(doc.config.title).toBe('Contact us'); - const quick = clone(served('crm_lead.quick')); - expect((translateView(quick, BUNDLE, { locale: 'zh-CN' }) as any).config).toBe(quick.config); + it('the served document is not mutated, and a form with nothing to translate is returned as is', () => { + const doc = clone(FORMS.web_to_lead); + translateForm(doc, BUNDLE, { locale: 'zh-CN' }); + expect(doc.title).toBe('Contact us'); + const referral = clone(FORMS.referral); + expect(translateForm(referral, BUNDLE, { locale: 'zh-CN' })).toBe(referral); + }); +}); + +describe('the pre-19 address `objects.._views..title` (ADR-0159 D8)', () => { + const OLD_PACK = { _views: { web_to_lead: { title: '联系我们' } } }; + + it('is refused at the bundle, with the prescription naming `forms[\'OBJECT.KEY\'].title`', () => { + const r = ObjectTranslationDataSchema.safeParse(OLD_PACK); + expect(r.success).toBe(false); + const issue = r.error?.issues.find((i) => i.path.join('.') === '_views.web_to_lead.title'); + expect(issue?.message, JSON.stringify(r.error?.issues)).toMatch( + /^`translation\.objects\.OBJECT\._views\.KEY\.title` was removed in @objectstack\/spec 19\.0\.0 \(ADR-0159 D8\)/, + ); + expect(issue?.message).toContain("forms['OBJECT.KEY'].title"); + }); + + it('is read by nothing: neither `translateForm` nor `translateView` takes a heading from it', () => { + const bundle: TranslationBundle = { 'zh-CN': { objects: { crm_lead: OLD_PACK } } as any }; + expect((translateForm(clone(FORMS.web_to_lead), bundle, { locale: 'zh-CN' }) as any).title).toBe('Contact us'); + // A served view is a list since protocol 19; the tail reaches no key of it. + const container = { list: { type: 'grid' as const, columns: ['name'] } }; + expect(ViewSchema.safeParse(container).success).toBe(true); + const list = clone(expandViewContainer('crm_lead', container)[0]!) as any; + const out = translateView(list, bundle, { locale: 'zh-CN' }) as any; + expect(out.config.title).toBeUndefined(); + expect(out.title).toBeUndefined(); }); }); diff --git a/packages/spec/src/system/i18n-resolver.test.ts b/packages/spec/src/system/i18n-resolver.test.ts index 53a15d16b60..139667ab71f 100644 --- a/packages/spec/src/system/i18n-resolver.test.ts +++ b/packages/spec/src/system/i18n-resolver.test.ts @@ -245,11 +245,12 @@ describe('resolveViewLabel — served view-document shape', () => { columns: [{ field: 'name' }], }, }, - // A default form carries no `data` at all, so top-level `object` is the - // ONLY field that can identify its object. - form: { - type: 'simple' as const, - sections: [{ label: 'Details', fields: [{ field: 'name' }] }], + // A default list that carries no `data` at all, so top-level `object` is + // the ONLY field that can identify its object. [ADR-0159 D7] This was a + // default FORM until protocol 19; a view holds lists only now. + list: { + type: 'grid' as const, + columns: [{ field: 'name' }], }, }; @@ -296,13 +297,13 @@ describe('resolveViewLabel — served view-document shape', () => { .toBe('Recent Accounts'); }); - it('resolves an object whose config carries no `data` (default form)', () => { - const form = served.find((v) => v.viewKind === 'form')!; - expect((form.config as any).data).toBeUndefined(); + it('resolves an object whose config carries no `data` (default list)', () => { + const list = served.find((v) => !v.name.endsWith('_accounts'))!; + expect((list.config as any).data).toBeUndefined(); // No `_views` entry for it — but it must reach the lookup on top-level // `object` instead of bailing at the `!objectName` guard, i.e. fall back to // the literal name rather than to `undefined`. - expect(resolveViewLabel(bundle, form as any, { locale: 'zh-CN' })).toBe(form.name); + expect(resolveViewLabel(bundle, list as any, { locale: 'zh-CN' })).toBe(list.name); }); it('translates through the REST boundary entry point', () => { diff --git a/packages/spec/src/system/i18n-resolver.ts b/packages/spec/src/system/i18n-resolver.ts index dcf489fb230..96c17d7d372 100644 --- a/packages/spec/src/system/i18n-resolver.ts +++ b/packages/spec/src/system/i18n-resolver.ts @@ -1673,49 +1673,13 @@ function translateFormSectionEntries( return changed ? next : entries; } -/** - * A served form view's translated `title` (`FormViewSchema.title`, at - * `config.title`), read from `objects.._views..title` — - * the SAME `_views` node, object and view key the view's own `label` is read - * from ({@link lookupViewText}), so the two strings of one view share one - * address and never a second key convention. - * - * Returns `title` itself (the same value) when nothing applies, so the caller - * can tell "unchanged" by identity: - * - * - only an AUTHORED title is translated — a non-empty string, which is all - * `FormViewSchema.title` admits. A form without one gains none, so its - * heading keeps falling back to the object label (the anonymous form - * page's `label ?? form.title ?? objectSchema.label`); - * - an explicit override beats the catalog (ADR-0029 D9.2a): when the - * packaged view's `config` is known and its `title` differs from the - * served one, the served title was authored on top of the package, and the - * catalog — the translation of the PACKAGED title — does not overwrite it; - * - a missing key keeps the authored title. - */ -function translateFormTitle( - title: unknown, - catalogs: LabelCatalogs, - objectName: string, - viewKey: string, - opts: ResolveOptions | undefined, - packagedConfig: Record | undefined, -): unknown { - if (typeof title !== 'string' || title.length === 0) return title; - const catalog = catalogFor(catalogs, valueOverridesPackagedBase(packagedConfig, 'title', title)); - return lookupViewText(catalog, objectName, viewKey, 'title', opts) ?? title; -} - /** * A form's translated thank-you panel (`FormViewSchema.submitBehavior`) — the * ONE comparison both of its carriers run, each supplying its own address as * `lookup`: * - * - a served form view, at `config.submitBehavior`, read from - * `objects.._views..submitBehavior.{title,message}` — the - * same `_views` node {@link translateFormTitle} reads the form's heading - * from, one level down, the way the authored copy sits one level down - * ({@link translateView}); + * - a `form` item, at `submitBehavior`, read from + * `forms..submitBehavior.{title,message}` ({@link translateForm}); * - a page `object-form` component, at `properties.submitBehavior` (the form * view's member by reference), read from * `pages..components..submitBehavior.{title,message}` @@ -1762,25 +1726,6 @@ function translateFormSubmitBehavior( /** The two strings a thank-you panel authors, and so the two its translation carries. */ type SubmitBehaviorCopyKey = 'title' | 'message'; -/** - * One string off a view's `_views..submitBehavior` node, across the - * locale chain — `undefined` when no locale carries it. - */ -function lookupSubmitBehaviorText( - bundle: TranslationBundle | undefined, - objectName: string, - viewKey: string, - attr: SubmitBehaviorCopyKey, - opts: ResolveOptions | undefined, -): string | undefined { - if (!bundle) return undefined; - for (const code of localeChain(opts)) { - const candidate = pickData(bundle, code)?.objects?.[objectName]?._views?.[viewKey]?.submitBehavior?.[attr]; - if (typeof candidate === 'string' && candidate.length > 0) return candidate; - } - return undefined; -} - /** * Apply the active locale to a view metadata document by overwriting `label` * and `description` with translated values when available, and overlaying the @@ -1836,51 +1781,13 @@ function lookupSubmitBehaviorText( * diverged. No base supplied is the pre-#20731 behaviour, unchanged: the * catalog applies. * - * ## [#23632] A form view's `sections` are translated HERE too - * - * A served form view carries its sections at `config.sections` — the form arm - * of `ViewItemSchema` nests the whole `FormViewSchema` under `config`, as the - * list arm nests its `bulkActionDefs` — and each section's heading and - * description are addressed at `objects.._sections.`, the - * convention `TranslationDataSchema` declares, the i18n extractor scaffolds and - * objectui's form renderers resolve client-side. A caller that cannot load the - * bundle itself — the anonymous public form — had no exported reading of that - * key, so its section titles stayed in the source language beside translated - * field labels. {@link translateFormSections} is that reading, on the same - * locale chain and the same override rule as every other string here; a - * container's form slot receives it through the same `config` projection its - * bulk-action defs do. - * - * A section's entries override an object field's `label`, `placeholder` and - * `helpText` for that form alone, and those three are addressed under the - * same node, at `objects.._sections..fields.` — so an - * entry's copy is served in the reader's language beside its section heading, - * by the same reading and the same rules. - * - * ## A form view's `title` is translated HERE too - * - * A served form view carries its heading at `config.title` - * (`FormViewSchema.title`), and it is addressed at - * `objects.._views..title` — the view's own `_views` node, - * beside its `label`, not the `label` key itself: a view item's `label` names - * the view and a container's form entries carry none, while `title` is what - * the form draws, so they are two strings with two keys. Before this the - * title had no key, and the anonymous public form — whose visitor cannot load - * the bundle — served it in the authoring language beside translated section - * headings and field labels. {@link translateFormTitle} applies it, on the - * same locale chain and the same override rule as every other string here. - * - * ## …and its thank-you panel - * - * The confirmation a form shows after a submit is its `submitBehavior`'s - * `title` and `message` when the `kind` is `'thank-you'`, served at - * `config.submitBehavior` and addressed at - * `objects.._views..submitBehavior` — nested the way the - * authored copy is nested, so the panel's heading never shares a key with the - * form's own `title`. Before this the panel had no key, and a public form - * read in another language confirmed the submit in the authoring language - * under a translated heading. {@link translateFormSubmitBehavior} applies it, - * by the same rules. + * ## [ADR-0159 D7] A view is a list + * + * A view serves lists only since @objectstack/spec 19: a form is a `form` + * item, translated by {@link translateForm} from `forms.`. The form + * strings a view used to carry under `config` (`sections`, `title`, + * `submitBehavior`) and their `_views..title` / `.submitBehavior` + * tails are no longer read here. */ export function translateView( view: T, @@ -1907,7 +1814,7 @@ export function translateView( const objectName = viewObjectName(view); if (config && typeof config === 'object' && catalogs.unchanged && objectName) { // The base's own `config` — `{}` when the base is known but carries none, - // so every def and section on the served view then counts as authored. + // so every def on the served view then counts as authored. const packagedConfig = base === undefined ? undefined : asRecord(base.config) ?? {}; const defs = translateBulkActionDefs( config.bulkActionDefs, @@ -1917,42 +1824,7 @@ export function translateView( opts, packagedConfig, ); - const sections = translateFormSections( - config.sections, - catalogs, - formSectionObjectName(config, objectName), - opts, - packagedConfig, - ); - const title = translateFormTitle( - config.title, - catalogs, - objectName, - viewTranslationKey(view, objectName), - opts, - packagedConfig, - ); - const viewKey = viewTranslationKey(view, objectName); - const submitBehavior = translateFormSubmitBehavior( - config.submitBehavior, - catalogs, - (catalog, attr) => lookupSubmitBehaviorText(catalog, objectName, viewKey, attr, opts), - packagedConfig, - ); - if ( - defs !== config.bulkActionDefs - || sections !== config.sections - || title !== config.title - || submitBehavior !== config.submitBehavior - ) { - config = { - ...config, - ...(defs !== config.bulkActionDefs ? { bulkActionDefs: defs } : {}), - ...(sections !== config.sections ? { sections } : {}), - ...(title !== config.title ? { title } : {}), - ...(submitBehavior !== config.submitBehavior ? { submitBehavior } : {}), - }; - } + if (defs !== config.bulkActionDefs) config = { ...config, bulkActionDefs: defs }; } return { @@ -1994,12 +1866,10 @@ function lookupFormText( /** * [ADR-0159 D8] Apply the active locale to a `form` item. * - * Every string reads `forms.` FIRST. The form tails a form defined in a - * view had under `objects.._views.` (`title`, and the thank-you - * panel's `submitBehavior`) are the declared fallback, read when the family - * has no value, so a bundle written for the old shape keeps translating the - * same form. `label` and `description` read `forms.` only: under - * `_views.` they are the view's own strings, never a form's. Section + * Every string reads `forms.`. The form tails a form defined in a view + * had under `objects.._views.` (`title`, and the thank-you + * panel's `submitBehavior`) were tombstoned in @objectstack/spec 19 and are + * no longer read: the 19 conversion moves them to `forms.`. Section * copy reads `forms..sections.
` first and keeps * `objects.._sections.
` as its object-level default, key by * key ({@link translateFormSections}). The override rule is the view's: @@ -2016,7 +1886,6 @@ export function translateForm( const catalogs = labelCatalogs(bundle, opts); const name = form.name; const objectName = form.object; - const key = name.startsWith(`${objectName}.`) ? name.slice(objectName.length + 1) : name; const own = (attr: 'label' | 'description'): string | undefined => { const value = form[attr]; if (typeof value !== 'string' || value.length === 0) return undefined; @@ -2027,15 +1896,12 @@ export function translateForm( let title: unknown = form.title; if (typeof form.title === 'string' && form.title.length > 0) { const catalog = catalogFor(catalogs, valueOverridesPackagedBase(base, 'title', form.title)); - title = lookupFormText(catalog, name, ['title'], opts) - ?? lookupViewText(catalog, objectName, key, 'title', opts) - ?? form.title; + title = lookupFormText(catalog, name, ['title'], opts) ?? form.title; } const submitBehavior = translateFormSubmitBehavior( form.submitBehavior, catalogs, - (catalog, attr) => lookupFormText(catalog, name, ['submitBehavior', attr], opts) - ?? lookupSubmitBehaviorText(catalog, objectName, key, attr, opts), + (catalog, attr) => lookupFormText(catalog, name, ['submitBehavior', attr], opts), base, ); const sections = catalogs.unchanged @@ -2207,8 +2073,9 @@ const METADATA_DOCUMENT_TRANSLATORS: Readonly` first, its old-shape `_views` - // tails as the declared fallback. + // [ADR-0159 D8] A `form` item, translated from `forms.`. The fallback + // read of its old-shape `_views` tails left with their tombstones in + // protocol 19. form: translateForm, } satisfies Record<(typeof TRANSLATED_METADATA_TYPE_NAMES)[number], MetadataDocumentTranslator>; diff --git a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts index daf67e7e108..cc0958b12d4 100644 --- a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts +++ b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts @@ -538,13 +538,8 @@ const LEDGER: ReadonlyArray = [ key: 'titleFormat', why: "`[DEPRECATED → nameField (ADR-0079)]` render-only title template the server cannot return or query, deliberately not offered to new authors; its own describe prescribes the migration — a single-field title to `nameField`, a composite title that import, sort or search must match to a stored computed field (a non-formula field with an `expression`) designated as `nameField`, a text formula staying legal for display only — and every target is authorable", }, - { - kind: 'omit', - type: 'view', - path: ROOT_PATH, - key: 'groups', - why: '`[LEGACY ALIAS → sections]` accepted for back-compat and folded onto `sections` at parse (`sections` wins when both are present), deliberately not offered to new authors', - }, + // [ADR-0159 D7] The `view` form's `groups` omit left in protocol 19: it was + // a key of the form overlay member, and a view holds lists only now. // Renderer-owned vocabulary — a key is admitted here only when all three // hold: its `describe()` says the spec declares no vocabulary for its value; diff --git a/packages/spec/src/system/migration.zod.ts b/packages/spec/src/system/migration.zod.ts index a938e72e16f..072cf7e93de 100644 --- a/packages/spec/src/system/migration.zod.ts +++ b/packages/spec/src/system/migration.zod.ts @@ -290,22 +290,43 @@ export const NOTIFICATION_EVENT_MIGRATION_ID = 'adr-0030-notification-event'; * `viewKind: 'form'` item) has moved to a `form` row or been removed as an * internal record form. * - * Written by `os migrate protocol --to 19 --apply` ONLY, and only after the - * stored-form ceremony committed (`applyStoredFormsOf`, - * `@objectstack/metadata-protocol`) AND a re-run of its census - * (`listStoredFormsOf`) found the deployment can switch with nothing left to - * move or remove: `verified_at` is then set. ⛔ A run the precheck holds writes - * nothing, this row included: the ceremony is all or nothing with the switch - * (ruling record 7142585849, item 2), and a row recording a failed attempt is a - * write before the switch verdict. + * It has two writers and no third: * - * It is the switch's record, not a gate: no boot reads it in this release (the - * boot guard is a separate decision). `details` carries the census counts of - * the verifying run and the rows the ceremony wrote. + * 1. `os migrate protocol --to 19 --apply`, only after the stored-form + * ceremony committed (`applyStoredFormsOf`, + * `@objectstack/metadata-protocol`) AND a re-run of its census + * (`listStoredFormsOf`) found the deployment can switch with nothing left + * to move or remove: `verified_at` is then set, and `applied_at` with it. + * On a datastore with no `sys_metadata` table there is no stored row to + * move and no ceremony to run: the command records the row on the census + * alone, verified, and leaves `applied_at` unset. ⛔ A run the precheck + * holds writes nothing, this row included: the ceremony is all or nothing + * with the switch (ruling record 7142585849, item 2), and a row recording + * a failed attempt is a write before the switch verdict. + * 2. A boot, on a datastore it observed being CREATED FROM EMPTY (ruling + * record 7308112533): the store's BIRTH MARKER, verified, `applied_at` + * unset, with `details.birth` = `{ protocol, platformVersion, createdAt }` + * naming the protocol major the store was born on, the platform version + * that created it and when. It claims no ceremony ran: it records that + * none was owed, because a store with no prior data holds no stored form. + * Written by the form-type-switch boot guard of `os serve` and by the + * birth half every CLI data and schema boot composes + * (`@objectstack/runtime`). ⛔ Never for a store that was found rather + * than created: a database an earlier release created runs the command + * once, even when it holds no stored form. * - * ⛔ Not a member of {@link CREATION_ATTESTED_MIGRATION_IDS}: a datastore born - * empty holds no old-shape row, but a row claiming the ceremony ran where none - * did would read as the switch it records. + * The served boot reads it (ruling record 7303149461): `os serve` refuses to + * start on a datastore whose row is absent or not verified, names + * `os migrate protocol --to 19`, and no variable, flag or config key skips the + * check. Only `verified_at` and `blocking` are decided on + * ({@link isDataMigrationFlagVerified}); `details` is provenance: the + * command's row carries the census counts of the verifying run and the rows + * the ceremony wrote, the birth marker carries `details.birth`. + * + * ⛔ Not a member of {@link CREATION_ATTESTED_MIGRATION_IDS}: those rows are + * written by `attestFreshDatastore` in one uniform shape once the seed has + * settled, and this row is judged before any plugin writes and must say which + * of its two writers wrote it. */ export const FORM_TYPE_SWITCH_MIGRATION_ID = 'adr-0159-form-type-switch'; diff --git a/packages/spec/src/system/translation.test.ts b/packages/spec/src/system/translation.test.ts index 3eaf82bc2dc..463fd1a0c85 100644 --- a/packages/spec/src/system/translation.test.ts +++ b/packages/spec/src/system/translation.test.ts @@ -2337,24 +2337,36 @@ describe('retired translation.validationMessages', () => { }); // ────────────────────────────────────────────────────────────────────────── -// `_views..title` — a form view's heading (`FormViewSchema.title`) +// `_views..title` — a form view's heading (`FormViewSchema.title`), +// RETIRED in protocol 19 (ADR-0159 D8): a form's heading is `forms.NAME.title` // ────────────────────────────────────────────────────────────────────────── -describe('`objects.._views..title`, the key a form view\'s title is translated through', () => { +describe('`objects.._views..title`, the key a form view\'s title was translated through', () => { const parse = (view: unknown) => ObjectTranslationDataSchema.safeParse({ label: 'Lead', _views: { web_to_lead: view } }); - it('accepts `title` as its own key, beside the view\'s `label`', () => { + // [ADR-0159 D8] Accepted as its own key until protocol 19; tombstoned now, + // with the prescription naming the `forms` address. The `label` beside it stays. + it('refuses `title` at its own path with the D8 prescription; the view\'s `label` stays', () => { const result = parse({ label: '网页线索', title: '联系我们' }); - expect(result.success, JSON.stringify(result.error?.issues)).toBe(true); - expect(result.success && result.data._views?.web_to_lead).toEqual({ label: '网页线索', title: '联系我们' }); + expect(result.success).toBe(false); + const issue = result.error?.issues.find((i) => i.path.join('.') === '_views.web_to_lead.title'); + expect(issue?.message, JSON.stringify(result.error?.issues)).toMatch( + /^`translation\.objects\.OBJECT\._views\.KEY\.title` was removed in @objectstack\/spec 19\.0\.0 \(ADR-0159 D8\)/, + ); + expect(issue?.message).toContain("forms['OBJECT.KEY'].title"); + expect(parse({ label: '网页线索' }).success).toBe(true); }); - it('a heading-shaped neighbour is named as a rename onto `title`, not onto `label`', () => { + // [ADR-0159 D8] Named as a rename onto `title` until protocol 19; the + // neighbour now carries the same retirement prescription, never a rename + // onto a key that is itself refused, and never onto `label`. + it('a heading-shaped neighbour carries the retirement prescription, not a rename', () => { const result = parse({ heading: '联系我们' }); expect(result.success).toBe(false); - const issue = result.error?.issues.find((i) => i.code === 'unrecognized_keys'); - expect(issue?.message).toContain('this view translation'); - expect(issue?.message).toContain('`heading` → `title`'); + const text = JSON.stringify(result.error?.issues); + expect(text).toContain("forms['OBJECT.KEY'].title"); + expect(text).not.toContain('`heading` → `title`'); + expect(text).not.toContain('`heading` → `label`'); }); it('CONTROL: the entry stays closed — a key it does not declare is still refused', () => { diff --git a/packages/spec/src/system/translation.zod.ts b/packages/spec/src/system/translation.zod.ts index ab9e8b44ad1..2bab92247bb 100644 --- a/packages/spec/src/system/translation.zod.ts +++ b/packages/spec/src/system/translation.zod.ts @@ -525,9 +525,29 @@ const actionTranslationSchema = (surface: string) => strictObject({ * } * ``` */ +/** + * [ADR-0159 D8, #37112] The two form tails under a view's translations, + * RETIRED in protocol 19: a form is a `form` item, and its copy lives in the + * bundle's `forms` family (`forms.NAME.title`, `forms.NAME.submitBehavior`). + * The conversion `translation-view-form-tails-to-forms` moves each tail of a + * form that is a `form` item; `label` and `description` under `_views` stay, + * because a list carries them too. + */ +const VIEW_TRANSLATION_FORM_TITLE_RETIRED = + '`translation.objects.OBJECT._views.KEY.title` was removed in @objectstack/spec 19.0.0 (ADR-0159 D8) — a ' + + 'form is a `form` item, and no view carries a heading. Move the string to `forms[\'OBJECT.KEY\'].title`, ' + + 'the address the translator reads a form\'s heading from. ' + + 'Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand.'; + +const VIEW_TRANSLATION_FORM_SUBMIT_RETIRED = + '`translation.objects.OBJECT._views.KEY.submitBehavior` was removed in @objectstack/spec 19.0.0 (ADR-0159 D8) ' + + '— a form is a `form` item, and no view has a thank-you panel. Move the `title` and `message` to ' + + '`forms[\'OBJECT.KEY\'].submitBehavior`, the address the translator reads a form\'s panel from. ' + + 'Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand.'; + /** * A form's thank-you panel translation — one shape, used at two addresses: a - * form view's `_views..submitBehavior` and a page `object-form` + * form item's `forms..submitBehavior` and a page `object-form` * component's `pages..components..submitBehavior` (the block * `ObjectFormPropsSchema.submitBehavior` takes from the form view by * reference). Built by a factory for {@link actionTranslationSchema}'s @@ -623,9 +643,6 @@ export const ObjectTranslationDataSchema = lazySchema(() => strictObject({ * Convention (auto-resolved by `resolveViewLabel`): * objects.._views..label * objects.._views..description - * objects.._views..title (a form view's heading) - * objects.._views..submitBehavior.title / .message - * (a form's thank-you panel) * objects.._views..emptyState.title * objects.._views..emptyState.message * objects.._views..bulkActions..* @@ -634,19 +651,20 @@ export const ObjectTranslationDataSchema = lazySchema(() => strictObject({ surface: 'this view translation', history: TRANSLATION_HISTORY, aliases: { - // `title` is a declared key below (a form view's heading), so it is no - // longer named as a rename onto `label`; the heading-shaped neighbours - // are named as renames onto it. - name: 'label', heading: 'title', formTitle: 'title', empty: 'emptyState', emptyMessage: 'emptyState', + // [ADR-0159 D8] `title` and `submitBehavior` (a form's heading and + // thank-you panel) were retired in protocol 19; the heading-shaped + // neighbours that were renames onto them are named in `guidance` below. + name: 'label', empty: 'emptyState', emptyMessage: 'emptyState', // The authoring key is `bulkActionDefs`; the translation group drops the // `Defs` suffix the way `_actions` drops nothing and `_tabs` drops // `tabs[]`'s bracket — one address per surface, and the authoring // spelling is the one an author reaches for first. bulkActionDefs: 'bulkActions', bulkActionDef: 'bulkActions', bulk: 'bulkActions', - // The panel's everyday name; the address mirrors the authoring key. - thankYou: 'submitBehavior', }, guidance: { + heading: VIEW_TRANSLATION_FORM_TITLE_RETIRED, + formTitle: VIEW_TRANSLATION_FORM_TITLE_RETIRED, + thankYou: VIEW_TRANSLATION_FORM_SUBMIT_RETIRED, rowActions: '`rowActions` names actions the OBJECT declares — a row-action label is translated where the ' + "action lives: 'objects.._actions..label' (or 'globalActions..label' " @@ -656,42 +674,10 @@ export const ObjectTranslationDataSchema = lazySchema(() => strictObject({ }, { label: z.string().optional().describe('Translated view label'), description: z.string().optional().describe('Translated view description'), - /** - * A FORM view's heading — overlays `FormViewSchema.title`, which a served - * form item carries at `config.title` (the title an anonymous public form - * shows above its sections). - * - * **Its own key, not the view's `label` key.** They are two authored - * strings on two layers: a view item's `label` names the view, and a - * form-family container entry (`formViews.`, the default `form`) - * carries no `label` at all, while `title` is the heading the form itself - * draws. One translation cannot stand for two source strings, so the key - * mirrors the authored one, the way `emptyState.title` does. - * - * Applied by `translateView` only where the form AUTHORS a title: a form - * without one gains none, and its heading keeps falling back to the - * object label. A list view carries no title, so the key over one - * resolves nothing (`objectstack validate` refuses it). - */ - title: z.string().optional().describe("Translated form view title — overlays a form view's own `title` (`FormViewSchema.title`); only a form that authors one is translated"), - /** - * A FORM view's thank-you panel — overlays the `title` and `message` of - * `FormViewSchema.submitBehavior` when its `kind` is `'thank-you'`, which - * a served form item carries at `config.submitBehavior` (the confirmation - * an anonymous public form shows after a submit). - * - * **Nested under `submitBehavior`, not flattened onto the view node.** - * The address mirrors the authored path, the way `emptyState.title` - * does: the panel's `title` is a second heading beside the form's own - * `title` above, and one key cannot stand for two source strings. The - * three other kinds (`redirect`, `continue`, `next-record`) author no - * copy, so this face carries the thank-you member's two strings only. - * - * Applied by `translateView` only where the form authors a thank-you - * `title` / `message`: a form with another kind, or none, gains no - * panel copy, and the console's own default wording stays in charge. - */ - submitBehavior: submitBehaviorTranslationSchema('this form submit behavior translation').optional().describe("Translated thank-you panel copy — overlays a form view's `submitBehavior` `title` / `message` when its `kind` is `'thank-you'`; only copy the form authors is translated"), + // [ADR-0159 D8] RETIRED in protocol 19 — a form's heading and thank-you + // panel are translated under `forms.NAME` (see the constants above). + title: retiredKey(VIEW_TRANSLATION_FORM_TITLE_RETIRED), + submitBehavior: retiredKey(VIEW_TRANSLATION_FORM_SUBMIT_RETIRED), emptyState: strictObject({ surface: 'this view empty-state translation', history: TRANSLATION_HISTORY, diff --git a/packages/spec/src/ui/anonymous-form-intake.ts b/packages/spec/src/ui/anonymous-form-intake.ts index d4bf389b212..838ac93745d 100644 --- a/packages/spec/src/ui/anonymous-form-intake.ts +++ b/packages/spec/src/ui/anonymous-form-intake.ts @@ -88,13 +88,17 @@ export function anonymousFormIntakeSlug(sharing: unknown): string | null { /** * The object an open form candidate submits into: the form's own `data.object`, - * else the view's `list.data.object`, `form.data.object` and `object`. The one - * rung order both anonymous doors and the authoring lint resolve by. + * else the body's `form.data.object` and `object`. The one rung order the + * projection of a stored old-shape body resolves by. + * + * [ADR-0159 D7] A form no longer reads its binding off a list: the rung that + * read the container's `list.data.object` left with the old shapes in + * @objectstack/spec 19. A `form` item names its object itself (`object`). */ export function anonymousFormObjectName(view: unknown, form: unknown): string | undefined { const v = (view && typeof view === 'object' ? view : {}) as Record; const f = (form && typeof form === 'object' ? form : {}) as Record; - return f.data?.object ?? v.list?.data?.object ?? v.form?.data?.object ?? v.object; + return f.data?.object ?? v.form?.data?.object ?? v.object; } /** Every form candidate of a `view` body that is open to anonymous intake, in scan order. */ diff --git a/packages/spec/src/ui/assembled-view-artifact-type.test.ts b/packages/spec/src/ui/assembled-view-artifact-type.test.ts index a94154c802b..b2e904ef342 100644 --- a/packages/spec/src/ui/assembled-view-artifact-type.test.ts +++ b/packages/spec/src/ui/assembled-view-artifact-type.test.ts @@ -39,14 +39,12 @@ const viewItem: AssembledViewArtifact = { config: { type: 'grid', data: { provider: 'object', object: 'crm_lead' }, columns: ['name'] }, }; const listOverlay: AssembledViewArtifact = { type: 'grid', columns: ['name'], object: 'crm_lead', viewKind: 'list' }; -const formOverlay: AssembledViewArtifact = { - type: 'simple', - sections: [{ label: 'Main', fields: ['name'] }], - object: 'crm_lead', - viewKind: 'form', -}; +// [ADR-0159 D7] The form overlay member was retired in protocol 19 (a view is a list): its body no +// longer type-checks as an artifact, and the schema refuses it (pinned below). +// @ts-expect-error -- a flattened form overlay is no view artifact since protocol 19. +const formOverlay: AssembledViewArtifact = { type: 'simple', sections: [{ label: 'Main', fields: ['name'] }], object: 'crm_lead', viewKind: 'form' }; -const BODY_OF_EACH_MEMBER: Record = { viewItem, listOverlay, formOverlay }; +const BODY_OF_EACH_MEMBER: Record = { viewItem, listOverlay }; // ── What the two types refuse at compile time ──────────────────────────────────────────────── @@ -63,6 +61,10 @@ const parsedFromUnknown: AssembledViewArtifactParsed = someValue; void [fromUnknown, container, undeclaredKey, parsedFromUnknown]; describe('AssembledViewArtifact is a non-container view artifact, not unknown', () => { + it('[ADR-0159 D7] the retired form overlay body is refused by the artifact schema', () => { + expect(AssembledViewArtifactSchema.safeParse(formOverlay).success).toBe(false); + }); + it('has a typed body for every non-container member', () => { expect(Object.keys(BODY_OF_EACH_MEMBER).sort()).toEqual( VIEW_METADATA_BRANCHES.filter((branch) => branch !== 'container').sort(), diff --git a/packages/spec/src/ui/assembled-views.test.ts b/packages/spec/src/ui/assembled-views.test.ts index 01390d92775..74f59e38a5e 100644 --- a/packages/spec/src/ui/assembled-views.test.ts +++ b/packages/spec/src/ui/assembled-views.test.ts @@ -27,6 +27,7 @@ import { AssembledViewArtifactSchema, partitionAssembledViewArtifacts, expandViewContainer, + expandServedViewContainer, } from './index'; import { ObjectStackDefinitionSchema } from '../stack.zod'; @@ -34,10 +35,16 @@ const DATA = { provider: 'object', object: 'account' } as const; /** The minimal schema-valid container of the fork's probe: a default list and * a default form → expands to `account.default` + `account.form`. */ +/** [ADR-0159 D7] A container holds lists only since protocol 19 (it carried a `form` before). */ const CONTAINER = { name: 'account', object: 'account', list: { type: 'grid', columns: ['name'], data: DATA }, +} as const; + +/** The pre-19 container: the same list plus a view-held `form`, as a stored row may still hold it. */ +const OLD_SHAPE_CONTAINER = { + ...CONTAINER, form: { type: 'simple', sections: [{ label: 'Details', fields: [{ field: 'name' }] }] }, } as const; @@ -73,7 +80,7 @@ describe('AssembledViewArtifactSchema — the declared home for non-container vi expect(r.success, JSON.stringify((r as { error?: unknown }).error)).toBe(true); }); - it('accepts a flattened form overlay (vocabulary branch 4)', () => { + it('[ADR-0159 D7] refuses a flattened form overlay (vocabulary branch 4 until protocol 19)', () => { const r = AssembledViewArtifactSchema.safeParse({ name: 'account.form', object: 'account', @@ -81,7 +88,7 @@ describe('AssembledViewArtifactSchema — the declared home for non-container vi type: 'simple', sections: [{ label: 'Details', fields: [{ field: 'name' }] }], }); - expect(r.success, JSON.stringify((r as { error?: unknown }).error)).toBe(true); + expect(r.success).toBe(false); }); it('refuses a container — containers travel in `views:`, not `viewItems:`', () => { @@ -99,7 +106,7 @@ describe('partitionAssembledViewArtifacts — re-aggregation where a container e // the bare object key AND its expanded items (dual-read) — the exact 3-entry // set the fork's probe read back from `getMetaItems('view', pkg)`. const expanded = expandViewContainer('account', CONTAINER); - expect(expanded.map((v) => v.name).sort()).toEqual(['account.default', 'account.form']); + expect(expanded.map((v) => v.name).sort()).toEqual(['account.default']); const { views, viewItems, folded } = partitionAssembledViewArtifacts([ CONTAINER, @@ -107,7 +114,14 @@ describe('partitionAssembledViewArtifacts — re-aggregation where a container e ]); expect(views).toEqual([CONTAINER]); expect(viewItems).toEqual([]); - expect(folded.sort()).toEqual(['account.default', 'account.form']); + expect(folded.sort()).toEqual(['account.default']); + }); + + it('[ADR-0159 D7] an old-shape container is SERVED as its lists only — its `form` is not served', () => { + expect(expandServedViewContainer('account', OLD_SHAPE_CONTAINER).map((v) => v.name)).toEqual(['account.default']); + // …while the raw expansion still sees the stored form: the replacement + // check and the stored-form ceremony read a stored container through it. + expect(expandViewContainer('account', OLD_SHAPE_CONTAINER).map((v) => v.name)).toEqual(['account.default', 'account.form']); }); it('keeps a standalone ViewItem — no container to re-aggregate from', () => { @@ -185,5 +199,10 @@ describe('authored `viewItems:` is refused loudly (machine-assembled only)', () views: [CONTAINER], }); expect(r.success, JSON.stringify((r as { error?: unknown }).error)).toBe(true); + // [ADR-0159 D7] …and an old-shape container is refused at its `form`. + expect(ObjectStackDefinitionSchema.safeParse({ + manifest: { id: 'com.test.app', name: 'test', version: '1.0.0', type: 'app' }, + views: [OLD_SHAPE_CONTAINER], + }).success).toBe(false); }); }); diff --git a/packages/spec/src/ui/form-field-public-picker-retirement.test.ts b/packages/spec/src/ui/form-field-public-picker-retirement.test.ts index 0d0b44cd570..98e57d08076 100644 --- a/packages/spec/src/ui/form-field-public-picker-retirement.test.ts +++ b/packages/spec/src/ui/form-field-public-picker-retirement.test.ts @@ -47,7 +47,7 @@ import { ALL_CONVERSIONS } from '../conversions/registry'; import { applyConversionsToStoredItem } from '../conversions/stored'; import { MIGRATIONS_BY_MAJOR, RETIRED_KEYS_BY_MAJOR } from '../migrations/registry'; import { defineStack } from '../stack.zod'; -import { FormFieldSchema, FormViewSchema, ViewMetadataSchema, type FormFieldInput } from './view.zod'; +import { FormFieldSchema, FormSchema, FormViewSchema, ViewMetadataSchema, type FormFieldInput } from './view.zod'; /** The block as an author wrote it before the retirement — every key it declared. */ const PICKER = { displayFields: ['name'], maxResults: 10, object: 'crm_contact' }; @@ -71,6 +71,16 @@ const viewItem = (fields: unknown[]) => ({ }, }); +/** [ADR-0159 D7] The same form as a `form` item (`forms:`, the `form` save door): body at the top level, bound with `object`. */ +const formItem = (fields: unknown[]) => ({ + name: 'crm_inquiry.contact', + object: 'crm_inquiry', + label: 'Contact us', + type: 'simple', + sections: [{ label: 'About you', fields }], + sharing: { allowAnonymous: true, publicLink: '/forms/contact' }, +}); + describe('form field publicPicker retirement — the tombstone, at every door that carries a form field', () => { it('the form field schema refuses `publicPicker` at its path, with the prescription', () => { const r = FormFieldSchema.safeParse({ field: 'contact', publicPicker: PICKER }); @@ -107,13 +117,22 @@ describe('form field publicPicker retirement — the tombstone, at every door th expect(flat).toContain('"publicPicker"'); }); - it('the stored-view write door (ViewMetadataSchema, ViewItem branch) refuses it with the prescription', () => { - const r = ViewMetadataSchema.safeParse(viewItem(['subject', { field: 'contact', publicPicker: PICKER }])); + it('the `form` item door (FormSchema) refuses it with the prescription', () => { + const r = FormSchema.safeParse(formItem(['subject', { field: 'contact', publicPicker: PICKER }])); expect(r.success).toBe(false); if (r.success) return; expect(JSON.stringify(r.error.issues)).toMatch(PRESCRIPTION); // CONTROL: the same item without the key is accepted by the same door. - expect(ViewMetadataSchema.safeParse(viewItem(['subject', { field: 'contact' }])).success).toBe(true); + expect(FormSchema.safeParse(formItem(['subject', { field: 'contact' }])).success).toBe(true); + }); + + it('[ADR-0159 D7] the stored-view write door refuses a form view item whatever it carries, with the D7 prescription', () => { + for (const fields of [['subject', { field: 'contact', publicPicker: PICKER }], ['subject', { field: 'contact' }]]) { + const r = ViewMetadataSchema.safeParse(viewItem(fields)); + expect(r.success).toBe(false); + if (r.success) continue; + expect(JSON.stringify(r.error.issues)).toContain("`view.viewKind: 'form'` was removed in @objectstack/spec 19.0.0"); + } }); it('the authoring door, defineStack, refuses it with the STACK_SCHEMA_INVALID envelope — never rewrites it', () => { @@ -127,15 +146,13 @@ describe('form field publicPicker retirement — the tombstone, at every door th contact: { type: 'lookup', label: 'Contact', reference: 'crm_contact' }, }, }], - views: [{ - formViews: { - contact: { - type: 'simple', - data: { provider: 'object', object: 'crm_inquiry' }, - sections: [{ label: 'About you', fields: ['subject', field] }], - sharing: { enabled: true, allowAnonymous: true, publicLink: '/forms/contact' }, - }, - }, + // [ADR-0159 D7] The form is a `form` item since protocol 19 (it was a `formViews` entry). + forms: [{ + name: 'crm_inquiry.contact', + object: 'crm_inquiry', + type: 'simple', + sections: [{ label: 'About you', fields: ['subject', field] }], + sharing: { enabled: true, allowAnonymous: true, publicLink: '/forms/contact' }, }], }); let thrown: unknown; @@ -240,14 +257,17 @@ describe('form field publicPicker retirement — the D2 conversion', () => { expect(twice.stack).toBe(once.stack); }); - it('a STORED view row carrying the key replays clean through the rehydration seam, and the write door accepts the result', () => { + it('a STORED view row carrying the key replays clean through the rehydration seam; the form view door accepts the replayed body', () => { const stored = viewItem(['subject', { field: 'contact', publicPicker: PICKER }]); // Before: the retired key is refused at parse — the row a pre-retirement // author left behind would be badged invalid without the replay. expect(ViewMetadataSchema.safeParse(stored).success).toBe(false); const converted = applyConversionsToStoredItem('view', stored) as ReturnType; expect(converted.config.sections[0]!.fields).toEqual(['subject', { field: 'contact' }]); - expect(ViewMetadataSchema.safeParse(converted).success).toBe(true); + // [ADR-0159 D7] The replayed row is still a form view item, which the 19 write door refuses + // whatever it carries; its replayed body is what the form view door accepts. + expect(ViewMetadataSchema.safeParse(converted).success).toBe(false); + expect(FormViewSchema.safeParse(converted.config).success).toBe(true); }); it('is retired from the load path — a live author is refused at parse, never silently rewritten', () => { diff --git a/packages/spec/src/ui/form-intake-layer.ts b/packages/spec/src/ui/form-intake-layer.ts index b9e1c00bb57..03d52abc3d8 100644 --- a/packages/spec/src/ui/form-intake-layer.ts +++ b/packages/spec/src/ui/form-intake-layer.ts @@ -7,13 +7,14 @@ import { oldShapeFormWithdrawals } from './old-shape-form-withdrawals'; /** * [ADR-0159 D6] The anonymous doors' withdrawal judgement over BOTH types. * - * The doors offer the open forms of the effective `form` read (authored - * items and the projection of the old shapes, resolved over both types). - * Each candidate is judged against a layer never narrower than the one the - * doors judged before card ②: the effective lists and the per-package layers - * of both `form` and `view`, the old shapes passed through the projection - * first. Narrowing only, in both directions: a withdrawal held in either type - * closes the form served from either type. + * The doors offer the open forms of the effective `form` read: `form` items, + * resolved over both types (rule 11). Since @objectstack/spec 19 the + * projection of the old shapes serves no content (D7), so no candidate is a + * projected item. Each candidate is judged against the layer the doors judged + * before: the effective lists and the per-package layers of both `form` and + * `view`, the old shapes passed through the projection first (rule 10). + * Narrowing only, in both directions: a withdrawal held in either type closes + * the form. * * - **Identity is the served name** (rule 6): inside one name, the whole * item. A body of the form's name that explicitly withdraws a form (its @@ -52,9 +53,9 @@ const nameOf = (item: unknown): string | undefined => { /** * Build the two-type layer from what the doors read: `forms` (the effective - * and per-package `form` lists, authored and projected items alike), `views` - * (the effective and per-package `view` lists, raw), and `unreadable` (the - * stored bodies the protocol could not project, rule 7). + * and per-package `form` lists), `views` (the effective and per-package + * `view` lists, raw), and `unreadable` (the stored bodies the protocol could + * not project, rule 7). */ export function formIntakeLayer(input: { forms: ReadonlyArray; diff --git a/packages/spec/src/ui/form-layout-inline-grid-retired.test.ts b/packages/spec/src/ui/form-layout-inline-grid-retired.test.ts index f454d317b40..e66260cbeb8 100644 --- a/packages/spec/src/ui/form-layout-inline-grid-retired.test.ts +++ b/packages/spec/src/ui/form-layout-inline-grid-retired.test.ts @@ -33,7 +33,8 @@ import { CONVERSIONS_BY_MAJOR } from '../conversions/registry.js'; import { applyConversionsToStoredItem } from '../conversions/stored.js'; import { MIGRATIONS_BY_MAJOR } from '../migrations/registry.js'; import { ComponentPropsMap, ObjectFormPropsSchema } from './component.zod.js'; -import { FormViewSchema, VIEW_METADATA_MEMBERS, ViewSchema } from './view.zod.js'; +import { FormSchema, FormViewSchema, ViewSchema } from './view.zod.js'; +import { RETIRED_VIEW_FORM_DOORS, expectRetiredViewFormDoorRefuses } from './retired-view-form-doors.testkit.js'; const CONVERSION_ID = 'form-layout-inline-grid-to-vertical'; const SEMANTIC_ID = 'ui-form-layout-inline-grid-retired'; @@ -67,21 +68,13 @@ const DOORS: readonly Door[] = [ parse: (layout) => FormViewSchema.safeParse({ type: 'simple', layout }), layoutPath: ['layout'], }, + // [ADR-0159 D7] The two view-held doors this table listed (a container's + // `formViews.*` and the flattened form overlay) refuse the whole form since + // protocol 19, pinned below from `RETIRED_VIEW_FORM_DOORS`; a form body is + // judged as a `form` item, whose body keys are the form view's by reference. { - name: 'ViewSchema.formViews.* (a container)', - parse: (layout) => ViewSchema.safeParse({ formViews: { quick: { type: 'simple', layout } } }), - layoutPath: ['formViews', 'quick', 'layout'], - }, - { - // The flattened form overlay spreads `FormViewSchema`'s shape, so the - // narrowing reaches it without an edit of its own. - name: 'VIEW_METADATA_MEMBERS.formOverlay (the flattened form overlay)', - parse: (layout) => VIEW_METADATA_MEMBERS.formOverlay.safeParse({ - object: 'crm_lead', - viewKind: 'form', - type: 'simple', - layout, - }), + name: '`form` item', + parse: (layout) => FormSchema.safeParse({ name: 'crm_lead.quick', object: 'crm_lead', type: 'simple', layout }), layoutPath: ['layout'], }, ]; @@ -128,6 +121,10 @@ describe('form `layout` — the retired arms are refused with the prescription', }); } + it.each(RETIRED_VIEW_FORM_DOORS.map((d) => [d.name, d] as const))('[ADR-0159 D7] %s refuses a form of any layout — at its own key, with the D7 prescription', (_, door) => { + for (const layout of ['grid', 'inline', 'vertical', 'horizontal']) expectRetiredViewFormDoorRefuses(door, { type: 'simple', layout }); + }); + it('the two schemas speak the same two-arm vocabulary, each under its own surface name', () => { const objectForm = ObjectFormPropsSchema.safeParse({ layout: 'grid' }); const formView = FormViewSchema.safeParse({ layout: 'grid' }); @@ -183,20 +180,24 @@ describe(`D2 conversion \`${CONVERSION_ID}\``, () => { expect(out.pages[0]!.regions[0]!.components[0]!.properties.layout).toBe('grid'); }); - it("a stored form view row replays clean: 'grid' → 'vertical', `columns` kept, and the row parses", () => { + // [ADR-0159 D7] A stored row is not rewritten past the conversion (constraint 1), + // and its view-held form is refused by the 19 door whatever it carries; the + // replayed form body is what the form door accepts. + it("a stored form view row replays clean: 'grid' → 'vertical', `columns` kept, and the form body parses", () => { const row = { object: 'crm_lead', form: { type: 'simple', layout: 'grid', columns: 3 } }; expect(ViewSchema.safeParse(row).success).toBe(false); const replayed = applyConversionsToStoredItem('view', structuredClone(row))!; expect(replayed.form).toEqual({ type: 'simple', layout: 'vertical', columns: 3 }); - expect(ViewSchema.safeParse(replayed).success).toBe(true); + expect(FormViewSchema.safeParse(replayed.form).success).toBe(true); + expect(ViewSchema.safeParse(replayed).success).toBe(false); }); - it("a stored flattened form overlay replays clean: 'inline' → 'vertical', and the overlay parses", () => { + it("a stored flattened form overlay replays clean: 'inline' → 'vertical', and the form body parses", () => { const row = { object: 'crm_lead', viewKind: 'form', type: 'simple', layout: 'inline' }; - expect(VIEW_METADATA_MEMBERS.formOverlay.safeParse(row).success).toBe(false); + expect(FormViewSchema.safeParse({ type: row.type, layout: row.layout }).success).toBe(false); const replayed = applyConversionsToStoredItem('view', structuredClone(row))!; expect(replayed.layout).toBe('vertical'); - expect(VIEW_METADATA_MEMBERS.formOverlay.safeParse(replayed).success).toBe(true); + expect(FormViewSchema.safeParse({ type: replayed.type, layout: replayed.layout }).success).toBe(true); }); it("leaves the surviving arm, and the same key on a non-`object-form` component, untouched", () => { diff --git a/packages/spec/src/ui/form-view-buttons-reset-retirement.test.ts b/packages/spec/src/ui/form-view-buttons-reset-retirement.test.ts index 486dcd23045..9837ee7756c 100644 --- a/packages/spec/src/ui/form-view-buttons-reset-retirement.test.ts +++ b/packages/spec/src/ui/form-view-buttons-reset-retirement.test.ts @@ -38,7 +38,8 @@ import { applyConversionsToStoredItem } from '../conversions/stored'; import type { ConversionNotice } from '../conversions/types'; import { MIGRATIONS_BY_MAJOR, RETIRED_KEYS_BY_MAJOR } from '../migrations/registry'; import { defineStack } from '../stack.zod'; -import { FormViewSchema, VIEW_METADATA_MEMBERS, ViewItemSchema, ViewSchema } from './view.zod'; +import { FormViewSchema, ViewItemSchema, ViewSchema } from './view.zod'; +import { FORM_ITEM_DOOR, RETIRED_VIEW_FORM_DOORS, expectRetiredViewFormDoorRefuses } from './retired-view-form-doors.testkit'; const CONVERSION_ID = 'form-view-buttons-reset-removed'; const D3_ID = 'ui-form-view-buttons-reset-retired'; @@ -54,21 +55,18 @@ type Door = { name: string; parse: (form: Record) => Parse; at: const SECTIONS = [{ label: 'Main', fields: ['name'] }]; -/** Every door a form view payload is parsed through, with the path the payload sits at. */ +/** + * Every door a form view payload is parsed through, with the path the payload sits at. + * + * [ADR-0159 D7] Since protocol 19 a form body is judged by `FormViewSchema` and the `form` item + * only. The four view-held doors this table also listed (`view.form`, `view.formViews.*`, a + * `viewKind: 'form'` record, the flattened form overlay) refuse the whole form at their own key + * with the D7 prescription, whatever it carries — pinned below from + * {@link RETIRED_VIEW_FORM_DOORS}. + */ const DOORS: readonly Door[] = [ { name: 'FormViewSchema', parse: (f) => FormViewSchema.safeParse(f), at: [] }, - { name: 'view.form', parse: (f) => ViewSchema.safeParse({ form: f }), at: ['form'] }, - { name: 'view.formViews.*', parse: (f) => ViewSchema.safeParse({ formViews: { quick: f } }), at: ['formViews', 'quick'] }, - { - name: 'ViewItem form record', - parse: (f) => ViewItemSchema.safeParse({ name: 'crm_lead.quick', object: 'crm_lead', viewKind: 'form', config: f }), - at: ['config'], - }, - { - name: 'flattened form overlay', - parse: (f) => VIEW_METADATA_MEMBERS.formOverlay.safeParse({ ...f, object: 'crm_lead', viewKind: 'form' }), - at: [], - }, + FORM_ITEM_DOOR, ]; /** The issues a door reports under the payload — a wrapper may report others of its own. */ @@ -88,6 +86,11 @@ describe('FormView.buttons.reset — a tombstone inside the live `buttons` block } }); + it.each(RETIRED_VIEW_FORM_DOORS.map((d) => [d.name, d] as const))('[ADR-0159 D7] %s refuses a form carrying `buttons.reset`, or not — at its own key, with the D7 prescription', (_, door) => { + expectRetiredViewFormDoorRefuses(door, { sections: SECTIONS, buttons: { submit: { label: 'Save' }, reset: { show: true } } }); + expectRetiredViewFormDoorRefuses(door, { sections: SECTIONS, buttons: { submit: { show: true, label: 'Save' }, cancel: { show: false } } }); + }); + it.each(DOORS.map((d) => [d.name, d] as const))('%s still accepts `submit` and `cancel`', (_, door) => { const r = door.parse({ sections: SECTIONS, buttons: { submit: { show: true, label: 'Save' }, cancel: { show: false } } }); expect(r.success, JSON.stringify(r.error?.issues)).toBe(true); @@ -103,16 +106,17 @@ describe('FormView.buttons.reset — a tombstone inside the live `buttons` block it('defineStack refuses it with the ADR-0112 envelope and the prescription', () => { let refusal: unknown; try { - defineStack({ views: [{ object: 'crm_lead', formViews: { quick: { sections: SECTIONS, buttons: { reset: { show: true } } } } }] } as never); + // [ADR-0159 D7] The form is a `form` item since protocol 19 (it was a `formViews` entry). + defineStack({ forms: [{ name: 'crm_lead.quick', object: 'crm_lead', sections: SECTIONS, buttons: { reset: { show: true } } }] } as never); } catch (error) { refusal = error; } expect(refusal).toMatchObject({ code: 'STACK_SCHEMA_INVALID', status: 422 }); const issues = (refusal as { issues: { path: PropertyKey[]; message: string }[] }).issues; - expect(issues.map((i) => i.path.join('.'))).toEqual(['views.0.formViews.quick.buttons.reset']); + expect(issues.map((i) => i.path.join('.'))).toEqual(['forms.0.buttons.reset']); expect(issues[0]!.message.startsWith(FIRST_SENTENCE)).toBe(true); expect(() => defineStack({ - views: [{ object: 'crm_lead', formViews: { quick: { sections: SECTIONS, buttons: { cancel: { label: 'Back' } } } } }], + forms: [{ name: 'crm_lead.quick', object: 'crm_lead', sections: SECTIONS, buttons: { cancel: { label: 'Back' } } }], } as never)).not.toThrow(); }); @@ -151,8 +155,9 @@ describe(`the D2 conversion ${CONVERSION_ID}`, () => { expect(notices.filter(ours).map(brief)).toEqual([ { conversionId: CONVERSION_ID, path: 'views[0].formViews.quick.buttons.reset', from: 'reset', to: '(removed)' }, ]); - const parsed = ViewSchema.parse(out); - expect(parsed.formViews?.quick?.buttons).toEqual({ cancel: { show: false } }); + // [ADR-0159 D7] The replayed row still holds a view-held form, which the 19 door refuses. + expect(out.formViews.quick.buttons).toEqual({ cancel: { show: false } }); + expect(ViewSchema.safeParse(out).success).toBe(false); // A form without `reset` is the author's and is never touched. expect(out.form).toBe(row.form); // Copy-on-write: the stored row is not mutated. @@ -165,7 +170,8 @@ describe(`the D2 conversion ${CONVERSION_ID}`, () => { const out = applyConversionsToStoredItem('view', row, { onNotice: (n) => notices.push(n) }) as typeof row; expect(notices.filter(ours).map((n) => n.path)).toEqual(['views[0].config.buttons.reset']); expect(out.config).toEqual({ sections: SECTIONS, buttons: {} }); - expect(ViewItemSchema.safeParse(out).success).toBe(true); + // [ADR-0159 D7] A form view item is refused by the 19 door whatever its config carries. + expect(ViewItemSchema.safeParse(out).success).toBe(false); }); it('is idempotent by construction: a second replay converts nothing', () => { diff --git a/packages/spec/src/ui/form-view-drawer-keys-retirement.test.ts b/packages/spec/src/ui/form-view-drawer-keys-retirement.test.ts index 1712ec96c17..825bd6d6d35 100644 --- a/packages/spec/src/ui/form-view-drawer-keys-retirement.test.ts +++ b/packages/spec/src/ui/form-view-drawer-keys-retirement.test.ts @@ -61,7 +61,8 @@ import { MIGRATIONS_BY_MAJOR, RETIRED_KEYS_BY_MAJOR } from '../migrations/regist import { defineStack } from '../stack.zod'; import { ObjectFormPropsSchema } from './component.zod'; import { REACT_BLOCKS, REACT_OVERLAY_SHADOWS } from './react-blocks'; -import { FormSchema, FormViewSchema, VIEW_METADATA_MEMBERS, ViewItemSchema, ViewSchema } from './view.zod'; +import { FormSchema, FormViewSchema, ViewItemSchema, ViewSchema } from './view.zod'; +import { FORM_ITEM_DOOR, RETIRED_VIEW_FORM_DOORS, expectRetiredViewFormDoorRefuses } from './retired-view-form-doors.testkit'; const CONVERSION_ID = 'form-view-drawer-keys-removed'; const D3_ID = 'ui-form-view-drawer-keys-retired'; @@ -85,21 +86,18 @@ type Door = { name: string; parse: (form: Record) => Parse; at: const SECTIONS = [{ label: 'Main', fields: ['name'] }]; -/** Every door a form view payload is parsed through, with the path the payload sits at. */ +/** + * Every door a form view payload is parsed through, with the path the payload sits at. + * + * [ADR-0159 D7] Since protocol 19 a form body is judged by `FormViewSchema` and the `form` item + * only. The four view-held doors this table also listed (`view.form`, `view.formViews.*`, a + * `viewKind: 'form'` record, the flattened form overlay) refuse the whole form at their own key + * with the D7 prescription, whatever it carries — pinned per key below from + * {@link RETIRED_VIEW_FORM_DOORS}. + */ const DOORS: readonly Door[] = [ { name: 'FormViewSchema', parse: (f) => FormViewSchema.safeParse(f), at: [] }, - { name: 'view.form', parse: (f) => ViewSchema.safeParse({ form: f }), at: ['form'] }, - { name: 'view.formViews.*', parse: (f) => ViewSchema.safeParse({ formViews: { quick: f } }), at: ['formViews', 'quick'] }, - { - name: 'ViewItem form record', - parse: (f) => ViewItemSchema.safeParse({ name: 'crm_lead.quick', object: 'crm_lead', viewKind: 'form', config: f }), - at: ['config'], - }, - { - name: 'flattened form overlay', - parse: (f) => VIEW_METADATA_MEMBERS.formOverlay.safeParse({ ...f, object: 'crm_lead', viewKind: 'form' }), - at: [], - }, + FORM_ITEM_DOOR, ]; /** The issues a door reports under the payload — a wrapper may report others of its own. */ @@ -121,6 +119,16 @@ describe('FormView.drawerSide / drawerWidth — tombstones at every form-view do }); } + for (const key of KEYS) { + it.each(RETIRED_VIEW_FORM_DOORS.map((d) => [d.name, d] as const))(`[ADR-0159 D7] %s refuses a form carrying \`${key}\` — at its own key, with the D7 prescription`, (_, door) => { + for (const value of VALUES[key]) expectRetiredViewFormDoorRefuses(door, { type: 'simple', sections: SECTIONS, [key]: value }); + }); + } + + it.each(RETIRED_VIEW_FORM_DOORS.map((d) => [d.name, d] as const))('[ADR-0159 D7] CONTROL: %s refuses the same form without the keys too — a view is a list', (_, door) => { + expectRetiredViewFormDoorRefuses(door, { type: 'simple', sections: SECTIONS, columns: 2 }); + }); + it.each(DOORS.map((d) => [d.name, d] as const))('CONTROL: %s still accepts the same form without the keys, a live key beside them included', (_, door) => { // [#36544] The live key was `modalSize` until it became a tombstone too. const r = door.parse({ type: 'simple', sections: SECTIONS, columns: 2 }); @@ -130,8 +138,9 @@ describe('FormView.drawerSide / drawerWidth — tombstones at every form-view do it('defineStack refuses them with the ADR-0112 envelope and the prescription', () => { let refusal: unknown; try { + // [ADR-0159 D7] The form is a `form` item since protocol 19 (it was a `formViews` entry). defineStack({ - views: [{ object: 'crm_lead', formViews: { quick: { sections: SECTIONS, drawerSide: 'left', drawerWidth: '480px' } } }], + forms: [{ name: 'crm_lead.quick', object: 'crm_lead', sections: SECTIONS, drawerSide: 'left', drawerWidth: '480px' }], } as never); } catch (error) { refusal = error; @@ -139,15 +148,15 @@ describe('FormView.drawerSide / drawerWidth — tombstones at every form-view do expect(refusal).toMatchObject({ code: 'STACK_SCHEMA_INVALID', status: 422 }); const issues = (refusal as { issues: { path: PropertyKey[]; message: string }[] }).issues; expect(issues.map((i) => i.path.join('.')).sort()).toEqual([ - 'views.0.formViews.quick.drawerSide', - 'views.0.formViews.quick.drawerWidth', + 'forms.0.drawerSide', + 'forms.0.drawerWidth', ]); for (const issue of issues) { const key = issue.path[issue.path.length - 1] as (typeof KEYS)[number]; expect(issue.message.startsWith(FIRST_SENTENCE[key]), issue.message).toBe(true); } expect(() => defineStack({ - views: [{ object: 'crm_lead', formViews: { quick: { sections: SECTIONS, columns: 2 } } }], + forms: [{ name: 'crm_lead.quick', object: 'crm_lead', sections: SECTIONS, columns: 2 }], } as never)).not.toThrow(); }); @@ -213,10 +222,12 @@ describe(`the D2 conversion ${CONVERSION_ID}`, () => { { conversionId: CONVERSION_ID, path: 'views[0].formViews.quick.drawerSide', from: 'drawerSide', to: '(removed)' }, { conversionId: CONVERSION_ID, path: 'views[0].formViews.quick.drawerWidth', from: 'drawerWidth', to: '(removed)' }, ]); - const parsed = ViewSchema.parse(out); - expect(parsed.formViews?.quick).not.toHaveProperty('drawerSide'); - expect(parsed.formViews?.quick).not.toHaveProperty('drawerWidth'); - expect(parsed.formViews?.quick?.columns).toBe(2); + // [ADR-0159 D7] The replayed row still holds a view-held form, which the 19 door refuses + // whatever it carries (a read serves the row's lists only; the stored row is not rewritten). + expect(out.formViews.quick).not.toHaveProperty('drawerSide'); + expect(out.formViews.quick).not.toHaveProperty('drawerWidth'); + expect(out.formViews.quick.columns).toBe(2); + expect(ViewSchema.safeParse(out).success).toBe(false); // A form without the keys is the author's and is never touched. expect(out.form).toBe(row.form); // Copy-on-write: the stored row is not mutated. @@ -229,7 +240,8 @@ describe(`the D2 conversion ${CONVERSION_ID}`, () => { const out = applyConversionsToStoredItem('view', row, { onNotice: (n) => notices.push(n) }) as typeof row; expect(notices.filter(ours).map((n) => n.path)).toEqual(['views[0].config.drawerWidth']); expect(out.config).toEqual({ sections: SECTIONS }); - expect(ViewItemSchema.safeParse(out).success).toBe(true); + // [ADR-0159 D7] A form view item is refused by the 19 door whatever its config carries. + expect(ViewItemSchema.safeParse(out).success).toBe(false); }); it('never touches the `object-form` page block, whose drawer reads the keys', () => { @@ -290,15 +302,8 @@ const MODAL_MIGRATE_SENTENCE = 'Run `os migrate meta --from 18` to list the mech /** Every value the key accepted while it was declared. */ const MODAL_VALUES = ['sm', 'default', 'lg', 'xl', 'full'] as const; -/** The form-view doors, and the `form` item (ADR-0159), whose body keys are the form view's by reference. */ -const MODAL_DOORS: readonly Door[] = [ - ...DOORS, - { - name: '`form` item', - parse: (f) => FormSchema.safeParse({ name: 'crm_lead.intake', object: 'crm_lead', ...f }), - at: [], - }, -]; +/** The form-view doors: `FormViewSchema` and the `form` item (ADR-0159), whose body keys are the form view's by reference. */ +const MODAL_DOORS: readonly Door[] = DOORS; describe('FormView.modalSize — a tombstone at every form-view door', () => { it.each(MODAL_DOORS.map((d) => [d.name, d] as const))('%s refuses `modalSize`, whatever it carries, with its prescription', (_, door) => { @@ -313,6 +318,10 @@ describe('FormView.modalSize — a tombstone at every form-view door', () => { } }); + it.each(RETIRED_VIEW_FORM_DOORS.map((d) => [d.name, d] as const))('[ADR-0159 D7] %s refuses a form carrying `modalSize` — at its own key, with the D7 prescription', (_, door) => { + for (const value of MODAL_VALUES) expectRetiredViewFormDoorRefuses(door, { type: 'simple', sections: SECTIONS, modalSize: value }); + }); + it.each(MODAL_DOORS.map((d) => [d.name, d] as const))('CONTROL: %s still accepts the same form without the key', (_, door) => { const r = door.parse({ type: 'simple', sections: SECTIONS, columns: 2 }); expect(r.success, JSON.stringify(r.error?.issues)).toBe(true); @@ -321,8 +330,12 @@ describe('FormView.modalSize — a tombstone at every form-view door', () => { it('defineStack refuses it with the ADR-0112 envelope and the prescription', () => { let refusal: unknown; try { + // [ADR-0159 D7] The two forms are `form` items since protocol 19 (a container's `form` and a `formViews` entry before). defineStack({ - views: [{ object: 'crm_lead', form: { sections: SECTIONS, modalSize: 'full' }, formViews: { quick: { sections: SECTIONS, modalSize: 'lg' } } }], + forms: [ + { name: 'crm_lead.form', object: 'crm_lead', sections: SECTIONS, modalSize: 'full' }, + { name: 'crm_lead.quick', object: 'crm_lead', sections: SECTIONS, modalSize: 'lg' }, + ], } as never); } catch (error) { refusal = error; @@ -330,8 +343,8 @@ describe('FormView.modalSize — a tombstone at every form-view door', () => { expect(refusal).toMatchObject({ code: 'STACK_SCHEMA_INVALID', status: 422 }); const issues = (refusal as { issues: { path: PropertyKey[]; message: string }[] }).issues; expect(issues.map((i) => i.path.join('.')).sort()).toEqual([ - 'views.0.form.modalSize', - 'views.0.formViews.quick.modalSize', + 'forms.0.modalSize', + 'forms.1.modalSize', ]); for (const issue of issues) { expect(issue.message.startsWith(MODAL_FIRST_SENTENCE), issue.message).toBe(true); @@ -399,9 +412,10 @@ describe(`the D2 conversion ${MODAL_CONVERSION_ID}`, () => { expect(notices.filter(oursModal).map(brief)).toEqual([ { conversionId: MODAL_CONVERSION_ID, path: 'views[0].formViews.quick.modalSize', from: 'modalSize', to: '(removed)' }, ]); - const parsed = ViewSchema.parse(out); - expect(parsed.formViews?.quick).not.toHaveProperty('modalSize'); - expect(parsed.formViews?.quick?.columns).toBe(2); + // [ADR-0159 D7] The replayed row still holds a view-held form, which the 19 door refuses. + expect(out.formViews.quick).not.toHaveProperty('modalSize'); + expect(out.formViews.quick.columns).toBe(2); + expect(ViewSchema.safeParse(out).success).toBe(false); // A form without the key is the author's and is never touched. expect(out.form).toBe(row.form); // Copy-on-write: the stored row is not mutated. @@ -414,7 +428,8 @@ describe(`the D2 conversion ${MODAL_CONVERSION_ID}`, () => { const out = applyConversionsToStoredItem('view', row, { onNotice: (n) => notices.push(n) }) as typeof row; expect(notices.filter(oursModal).map((n) => n.path)).toEqual(['views[0].config.modalSize']); expect(out.config).toEqual({ sections: SECTIONS }); - expect(ViewItemSchema.safeParse(out).success).toBe(true); + // [ADR-0159 D7] A form view item is refused by the 19 door whatever its config carries. + expect(ViewItemSchema.safeParse(out).success).toBe(false); }); it('a STORED `form` item converts its top-level body', () => { diff --git a/packages/spec/src/ui/form-view-type-layout-retirement.test.ts b/packages/spec/src/ui/form-view-type-layout-retirement.test.ts index 94303af5e92..5ca67ef2c85 100644 --- a/packages/spec/src/ui/form-view-type-layout-retirement.test.ts +++ b/packages/spec/src/ui/form-view-type-layout-retirement.test.ts @@ -57,7 +57,8 @@ import type { ConversionNotice } from '../conversions/types'; import { MIGRATIONS_BY_MAJOR, RETIRED_KEYS_BY_MAJOR } from '../migrations/registry'; import { defineStack } from '../stack.zod'; import { ObjectFormPropsSchema, ObjectMasterDetailFormPropsSchema } from './component.zod'; -import { FormSectionSchema, FormViewSchema, VIEW_METADATA_MEMBERS, ViewItemSchema, ViewSchema } from './view.zod'; +import { FormSectionSchema, FormViewSchema, ViewItemSchema, ViewSchema } from './view.zod'; +import { FORM_ITEM_DOOR, RETIRED_VIEW_FORM_DOORS, expectRetiredViewFormDoorRefuses } from './retired-view-form-doors.testkit'; const CONVERSION_ID = 'form-view-presentation-types-removed'; const D3_ID = 'ui-form-view-type-layout-only'; @@ -107,21 +108,18 @@ type Door = { name: string; parse: (form: Record) => Parse; at: const SECTIONS = [{ label: 'Main', fields: ['name'] }]; -/** Every door a form view payload is parsed through, with the path the payload sits at. */ +/** + * Every door a form view payload is parsed through, with the path the payload sits at. + * + * [ADR-0159 D7] Since protocol 19 a form body is judged by `FormViewSchema` and the `form` item + * only. The four view-held doors this table also listed (`view.form`, `view.formViews.*`, a + * `viewKind: 'form'` record, the flattened form overlay) refuse the whole form at their own key + * with the D7 prescription, whatever it carries — pinned below from + * {@link RETIRED_VIEW_FORM_DOORS}. + */ const DOORS: readonly Door[] = [ { name: 'FormViewSchema', parse: (f) => FormViewSchema.safeParse(f), at: [] }, - { name: 'view.form', parse: (f) => ViewSchema.safeParse({ form: f }), at: ['form'] }, - { name: 'view.formViews.*', parse: (f) => ViewSchema.safeParse({ formViews: { quick: f } }), at: ['formViews', 'quick'] }, - { - name: 'ViewItem form record', - parse: (f) => ViewItemSchema.safeParse({ name: 'crm_lead.quick', object: 'crm_lead', viewKind: 'form', config: f }), - at: ['config'], - }, - { - name: 'flattened form overlay', - parse: (f) => VIEW_METADATA_MEMBERS.formOverlay.safeParse({ ...f, object: 'crm_lead', viewKind: 'form' }), - at: [], - }, + FORM_ITEM_DOOR, ]; /** The issues a door reports under the payload — a wrapper may report others of its own. */ @@ -148,6 +146,10 @@ describe('FormView.type — `simple | tabbed | wizard`, default `simple`', () => } }); + it.each(RETIRED_VIEW_FORM_DOORS.map((d) => [d.name, d] as const))('[ADR-0159 D7] %s refuses a form of any layout — at its own key, with the D7 prescription', (_, door) => { + for (const type of [...RETIRED_TYPES, ...LIVE_TYPES]) expectRetiredViewFormDoorRefuses(door, { type, sections: SECTIONS }); + }); + it.each(DOORS.map((d) => [d.name, d] as const))('%s accepts each live layout', (_, door) => { for (const type of LIVE_TYPES) { expect(door.parse({ type, sections: SECTIONS }).success, type).toBe(true); @@ -165,18 +167,19 @@ describe('FormView.type — `simple | tabbed | wizard`, default `simple`', () => for (const type of RETIRED_TYPES) { let refusal: unknown; try { - defineStack({ views: [{ object: 'crm_lead', formViews: { quick: { type, sections: SECTIONS } } }] } as never); + // [ADR-0159 D7] The form is a `form` item since protocol 19 (it was a `formViews` entry). + defineStack({ forms: [{ name: 'crm_lead.quick', object: 'crm_lead', type, sections: SECTIONS }] } as never); } catch (error) { refusal = error; } expect(refusal, type).toMatchObject({ code: 'STACK_SCHEMA_INVALID', status: 422 }); const issues = (refusal as { issues: { path: PropertyKey[]; message: string }[] }).issues; - expect(issues.map((i) => i.path.join('.'))).toEqual(['views.0.formViews.quick.type']); + expect(issues.map((i) => i.path.join('.'))).toEqual(['forms.0.type']); expect(issues[0]!.message.startsWith(TYPE_FIRST_SENTENCE[type])).toBe(true); } for (const type of LIVE_TYPES) { const sections = [{ label: 'Step', fields: ['name'] }]; - expect(() => defineStack({ views: [{ object: 'crm_lead', formViews: { quick: { type, sections } } }] } as never)).not.toThrow(); + expect(() => defineStack({ forms: [{ name: 'crm_lead.quick', object: 'crm_lead', type, sections }] } as never)).not.toThrow(); } }); @@ -439,11 +442,15 @@ describe(`the D2 conversion ${CONVERSION_ID}`, () => { { conversionId: CONVERSION_ID, path: 'views[0].formViews.beside.sections[1].pane', from: 'pane', to: '(removed)' }, { conversionId: CONVERSION_ID, path: 'views[0].formViews.quick.type', from: 'drawer', to: '(removed)' }, ]); - const parsed = ViewSchema.parse(out); - expect(parsed.formViews?.beside?.type).toBe('simple'); - expect(parsed.formViews?.beside).not.toHaveProperty('splitDirection'); - expect(parsed.formViews?.quick?.type).toBe('simple'); - expect(parsed.formViews?.quick?.columns).toBe(2); + // [ADR-0159 D7] The replayed row still holds view-held forms, which the 19 door refuses; each + // replayed form body is what the form door accepts, landing on `simple`. + expect(ViewSchema.safeParse(out).success).toBe(false); + const beside = FormViewSchema.parse(out.formViews.beside); + const quick = FormViewSchema.parse(out.formViews.quick); + expect(beside.type).toBe('simple'); + expect(beside).not.toHaveProperty('splitDirection'); + expect(quick.type).toBe('simple'); + expect(quick.columns).toBe(2); // A live layout is the author's and is never touched. expect(out.form).toBe(row.form); // Copy-on-write: the stored row is not mutated. @@ -456,7 +463,8 @@ describe(`the D2 conversion ${CONVERSION_ID}`, () => { const out = applyConversionsToStoredItem('view', row, { onNotice: (n) => notices.push(n) }) as typeof row; expect(notices.filter(ours).map((n) => n.path)).toEqual(['views[0].config.type']); expect(out.config).toEqual({ columns: 2, sections: SECTIONS }); - expect(ViewItemSchema.safeParse(out).success).toBe(true); + // [ADR-0159 D7] A form view item is refused by the 19 door whatever its config carries. + expect(ViewItemSchema.safeParse(out).success).toBe(false); }); it('is idempotent by construction: a second replay converts nothing', () => { diff --git a/packages/spec/src/ui/retired-view-form-doors.testkit.ts b/packages/spec/src/ui/retired-view-form-doors.testkit.ts new file mode 100644 index 00000000000..c12a65e1b68 --- /dev/null +++ b/packages/spec/src/ui/retired-view-form-doors.testkit.ts @@ -0,0 +1,84 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0159 D7] The four view-held form doors, retired in protocol 19, as ONE + * table for the form-key retirement tests. + * + * Before protocol 19 a form view body was parsed through five doors: the bare + * `FormViewSchema`, a container's `form`, a container's `formViews.*`, a + * `viewKind: 'form'` view item's `config`, and the flattened form overlay. A + * view holds lists only since protocol 19, so the last four refuse the WHOLE + * form, whatever it carries, with the D7 tombstone's prescription at the + * door's own key — never with a prescription of a key inside the body. The + * `form` item (`forms:`) is where a form body is judged key by key now. + * + * The retirement tests keep their old door rows (never deleted) and judge them + * here, against the major's answer. Not exported from `ui/index.ts` and not a + * tsup entry, so it never reaches the package's public surface. + */ + +import { expect } from 'vitest'; +import { FormSchema, VIEW_METADATA_MEMBERS, ViewItemSchema, ViewSchema } from './view.zod'; + +type Issue = { code: string; path: PropertyKey[]; message: string }; +type Parse = { success: boolean; data?: unknown; error?: { issues: Issue[] } }; + +/** One retired view-held form door: where its refusal sits, and the prescription it opens with. */ +export interface RetiredViewFormDoor { + readonly name: string; + readonly parse: (form: Record) => Parse; + /** The path of the refusal: the door's own key, never a key inside the form body. */ + readonly at: readonly PropertyKey[]; + /** The opening of the D7 prescription the door answers. */ + readonly opening: string; +} + +const KIND_RETIRED = "`view.viewKind: 'form'` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7)"; + +/** The four view-held form doors, named as the retirement tests named them before protocol 19. */ +export const RETIRED_VIEW_FORM_DOORS: readonly RetiredViewFormDoor[] = [ + { + name: 'view.form', + parse: (f) => ViewSchema.safeParse({ form: f }) as Parse, + at: ['form'], + opening: '`view.form` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7)', + }, + { + name: 'view.formViews.*', + parse: (f) => ViewSchema.safeParse({ formViews: { quick: f } }) as Parse, + at: ['formViews'], + opening: '`view.formViews` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7)', + }, + { + name: 'ViewItem form record', + parse: (f) => ViewItemSchema.safeParse({ name: 'crm_lead.quick', object: 'crm_lead', viewKind: 'form', config: f }) as Parse, + at: ['viewKind'], + opening: KIND_RETIRED, + }, + { + name: 'flattened form overlay', + // The form overlay member is gone; the list member claims a form-bound flat body. + parse: (f) => VIEW_METADATA_MEMBERS.listOverlay.safeParse({ ...f, object: 'crm_lead', viewKind: 'form' }) as Parse, + at: ['viewKind'], + opening: KIND_RETIRED, + }, +]; + +/** The door a form body is judged through since protocol 19: the `form` item, body at the top level. */ +export const FORM_ITEM_DOOR = { + name: '`form` item', + parse: (f: Record) => FormSchema.safeParse({ name: 'crm_lead.quick', object: 'crm_lead', ...f }) as Parse, + at: [] as PropertyKey[], +}; + +/** + * Assert a retired view-held door refuses `form` at its own key with the D7 + * prescription — the answer it gives whatever the form body carries. + */ +export function expectRetiredViewFormDoorRefuses(door: RetiredViewFormDoor, form: Record): void { + const r = door.parse(form); + expect(r.success, `${door.name} must refuse a form body since protocol 19`).toBe(false); + const atDoor = (r.error?.issues ?? []).find((i) => door.at.every((seg, k) => i.path[k] === seg) && i.path.length === door.at.length); + expect(atDoor, `${door.name}: ${JSON.stringify(r.error?.issues)}`).toBeDefined(); + expect(atDoor!.message.startsWith(door.opening), atDoor!.message).toBe(true); +} diff --git a/packages/spec/src/ui/view-authoring-wire-split.test.ts b/packages/spec/src/ui/view-authoring-wire-split.test.ts index 828498fa5f4..d0fa98fbc14 100644 --- a/packages/spec/src/ui/view-authoring-wire-split.test.ts +++ b/packages/spec/src/ui/view-authoring-wire-split.test.ts @@ -137,7 +137,10 @@ describe('`ViewItemSchema` is the authoring gate and is now strict', () => { expect(msg).toContain('config'); }); - it('an undeclared key is rejected on BOTH arms, at the arm where it lives', () => { + // [ADR-0159 D7] The item had a list arm and a form arm until protocol 19. + // The form arm is gone: a form record is refused whole at `viewKind`, with + // the D7 prescription, before any key inside it is judged. + it('an undeclared key is rejected on the list arm; a form record is refused whole at `viewKind`', () => { expect(reject(ViewItemSchema, { ...RECORD, notAViewItemKey: 1 })).toContain('notAViewItemKey'); expect( reject(ViewItemSchema, { @@ -147,7 +150,7 @@ describe('`ViewItemSchema` is the authoring gate and is now strict', () => { config: { type: 'simple', sections: [{ fields: ['name'] }] }, notAViewItemKey: 1, }), - ).toContain('notAViewItemKey'); + ).toContain("`view.viewKind: 'form'` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7)"); }); it('the wire keys are rejected HERE, each with the prescription for its layer', () => { @@ -173,13 +176,15 @@ describe('`ViewItemSchema` is the authoring gate and is now strict', () => { label: 'All Leads', config: { type: 'grid', columns: [], data: { provider: 'object', object: 'crm_lead' } }, }); - accept(ViewItemSchema, { + // [ADR-0159 D7] The form body this emitter also wrote is refused since + // protocol 19: a form is created as a `form` item (`forms:`), not a view. + expect(ViewItemSchema.safeParse({ name: 'crm_lead.intake', object: 'crm_lead', viewKind: 'form', label: 'Intake', config: { type: 'tabbed', data: { provider: 'object', object: 'crm_lead' }, sections: [] }, - }); + }).success).toBe(false); }); it('the two nested console-decorated blocks now reject `id` at their own path', () => { @@ -378,19 +383,20 @@ describe('`stripViewConsoleDecorations`, the write-path mirror of `stripReadDeco // 5. The two landmines the ruling named // =========================================================================== describe('landmine 1: `/api/v1/meta/types/view` must still get an `anyOf`', () => { - it('the REGISTERED schema converts to a four-member `anyOf`, through the preprocess', () => { + // [ADR-0159 D7] Four members until protocol 19; the form overlay left. + it('the REGISTERED schema converts to a three-member `anyOf`, through the preprocess', () => { // Studio's SchemaForm is built from this. `z.preprocess` makes the root a // pipe; a pipe converts to its output side, so the union survives — but // that is a fact about zod, so it is asserted rather than assumed. const json = z.toJSONSchema(getMetadataTypeSchema('view')!, { unrepresentable: 'any' }) as Record; expect(Array.isArray(json.anyOf)).toBe(true); - expect((json.anyOf as unknown[]).length).toBe(4); + expect((json.anyOf as unknown[]).length).toBe(3); }); it('converts in the INPUT direction too — the form is built from what an author sends', () => { const json = z.toJSONSchema(ViewMetadataSchema, { unrepresentable: 'any', io: 'input' }) as Record; expect(Array.isArray(json.anyOf)).toBe(true); - expect((json.anyOf as unknown[]).length).toBe(4); + expect((json.anyOf as unknown[]).length).toBe(3); }); it('the emitted schema does NOT advertise `id` on a filter/sort row', () => { @@ -414,13 +420,15 @@ describe('landmine 1: `/api/v1/meta/types/view` must still get an `anyOf`', () = for (const io of ['output', 'input'] as const) { const json = z.toJSONSchema(getMetadataTypeSchema('view')!, { unrepresentable: 'any', io }) as Record; const members = json.anyOf as Array>; - expect(members).toHaveLength(4); - // Member 1 is the discriminated ViewItem record (a nested union); members - // 2-4 are plain objects. A degraded emission loses exactly this shape. + // [ADR-0159 D7] Four until protocol 19; the form overlay left. + expect(members).toHaveLength(3); + // Member 1 is the discriminated ViewItem record (a nested union, one arm + // since protocol 19); members 2-3 are plain objects. A degraded emission + // loses exactly this shape. expect(Array.isArray(members[0]!.oneOf ?? members[0]!.anyOf)).toBe(true); for (const member of members.slice(1)) expect(member.type).toBe('object'); // The form needs real property sets, not an empty permissive schema. - expect(Object.keys((members[3]!.properties ?? {}) as object).length).toBeGreaterThan(10); + expect(Object.keys((members[2]!.properties ?? {}) as object).length).toBeGreaterThan(10); } }); }); diff --git a/packages/spec/src/ui/view-column-state-retirement.test.ts b/packages/spec/src/ui/view-column-state-retirement.test.ts index e723b512794..22aaf44ac36 100644 --- a/packages/spec/src/ui/view-column-state-retirement.test.ts +++ b/packages/spec/src/ui/view-column-state-retirement.test.ts @@ -61,7 +61,8 @@ type Issue = { code: string; path: PropertyKey[]; message: string; errors?: Issu const MEMBERS = [ ['viewItem', VIEW_METADATA_MEMBERS.viewItem, RECORD], ['listOverlay', VIEW_METADATA_MEMBERS.listOverlay, LIST_OVERLAY], - ['formOverlay', VIEW_METADATA_MEMBERS.formOverlay, FORM_OVERLAY], + // [ADR-0159 D7] The flattened form overlay member was retired in protocol 19; + // a form-bound row is refused by the door below. ] as const; describe('columnState retirement — the tombstone, at every door that parses a stored row', () => { @@ -82,13 +83,16 @@ describe('columnState retirement — the tombstone, at every door that parses a it('the `view` write door refuses every row shape carrying it, the claimed member locating the key', () => { const door = getMetadataTypeSchema('view'); expect(door).toBe(ViewMetadataSchema); - for (const row of [LIST_OVERLAY, FORM_OVERLAY, RECORD]) { + for (const row of [LIST_OVERLAY, RECORD]) { const r = door!.safeParse({ ...row, columnState: VALUE }); expect(r.success, JSON.stringify(row)).toBe(false); if (r.success) continue; const top = r.error.issues[0] as unknown as Issue; expect(top.message).toMatch(PRESCRIPTION); } + // [ADR-0159 D7] A form-bound row is refused whatever it carries: a view is a list. + expect(door!.safeParse({ ...FORM_OVERLAY, columnState: VALUE }).success).toBe(false); + expect(door!.safeParse({ ...FORM_OVERLAY }).success).toBe(false); }); it('the assembled-manifest channel refuses it too — which is why the D2 conversion reaches `viewItems`', () => { @@ -117,7 +121,6 @@ describe('columnState retirement — the tombstone, at every door that parses a for (const [label, schema, body] of [ ['viewItem member', VIEW_METADATA_MEMBERS.viewItem, { ...RECORD, isPinned: true }], ['listOverlay member', VIEW_METADATA_MEMBERS.listOverlay, { ...LIST_OVERLAY, isDefault: true }], - ['formOverlay member', VIEW_METADATA_MEMBERS.formOverlay, { ...FORM_OVERLAY, isDefault: true }], ['door (list)', ViewMetadataSchema, { ...LIST_OVERLAY, hiddenFields: ['name'] }], ] as const) { const r = schema.safeParse(body); diff --git a/packages/spec/src/ui/view-form-slots-retirement.test.ts b/packages/spec/src/ui/view-form-slots-retirement.test.ts new file mode 100644 index 00000000000..c648712b610 --- /dev/null +++ b/packages/spec/src/ui/view-form-slots-retirement.test.ts @@ -0,0 +1,288 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `view` is lists only since protocol 19 (ADR-0159 D7): the container's `form` + * and `formViews` slots and the `viewKind: 'form'` item are tombstones, and a + * form is a `form` item (`defineForm`). The refusals, the prescriptions and the + * conversion have their own pins beside this file (`retired-view-form-doors.testkit.ts` + * and the suites that read it). This one is the tree-scoped absence leg: nothing + * an author copies from still writes a form into a `view`. + * + * What is judged is the AUTHORING SHAPE, three arms: + * + * A. `formViews` in key position (TS / JS / JSON / YAML); + * B. the item kind, `viewKind: 'form'` (and YAML's bare `viewKind: form`); + * C. a `defineView({ … })` container whose own braces hold a `form` member, + * written `form: …` or shorthand. + * + * Inline code spans are prose and are not judged, so a page may still SAY that + * `formViews` was removed; a fenced block, a comment inside one and a file of + * metadata are judged. + * + * The population is every place an author copies from, inside the radius + * `scripts/cross-package-test-inputs.mjs` declares for this package: + * + * - `skills/`, `content/` and `scripts/`, whole; + * - `examples/`: the non-code files and each app's `src/` tree; + * - `packages/`: what a package TEACHES — its Markdown and YAML. + * + * A package's code and JSON are not judged, and that is the bound, stated: + * typed authoring there is refused by `tsc` at the tombstone (the input type of + * each retired slot is `never`), and what names the shapes untyped is the + * reader of rows stored before protocol 19 (ADR-0159 D6 rule 10, D7's + * conversion and ceremony) with the tests and fixtures that feed it. Spelling + * the shapes is that code's job for as long as such a row can exist, so its + * presence is no resurrection and this walk does not ask for its absence. + * + * Also outside what the walk sees: a container literal that is not wrapped in + * `defineView(` (a bare `views: [{ object, form }]`), a member assembled by + * spread or a computed key, and a container in JSON or YAML that holds `form` + * alone (the key is too common to judge without the wrapper; `formViews` and + * the item kind are judged there). + */ + +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { describe, expect, it } from 'vitest'; + +import { listRepoWalkFiles } from '../../scripts/lib/repo-walk-testkit'; + +const SPEC_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..'); +const REPO_ROOT = path.resolve(SPEC_ROOT, '../..'); + +const WALK_ROOTS = ['packages', 'examples', 'skills', 'content', 'scripts']; +const SCANNED_EXT = new Set(['.ts', '.mts', '.cts', '.js', '.mjs', '.cjs', '.json', '.md', '.mdx', '.yaml', '.yml']); +const EXAMPLES_EXT = new Set(['.json', '.md', '.mdx', '.yaml', '.yml']); +const EXAMPLE_APP_SRC_TS = /^examples\/[^/]+\/src\/.+\.ts$/; +/** What a package teaches. Its code and JSON are the bound the header states. */ +const PACKAGES_EXT = new Set(['.md', '.mdx', '.yaml', '.yml']); +/** Where a bare YAML scalar can be the item kind. */ +const YAML_BEARING_EXT = new Set(['.yaml', '.yml', '.md', '.mdx']); +const SKIPPED_DIRS = new Set(['node_modules', 'dist', '.turbo', '.cache', '.objectstack', 'coverage', '.next', '.source']); + +type Arm = 'formViews' | "viewKind: 'form'" | 'defineView({ form })'; + +/** A. `formViews` as a key. The lookbehind keeps a member READ (`x.formViews ? a : b`) out. */ +const FORM_VIEWS_KEY = /(? 0; i += 1) { + const c = text[i]!; + if (/\s/.test(c)) continue; + if (c === '/' && text[i + 1] === '/') { + const eol = text.indexOf('\n', i); + i = eol === -1 ? text.length : eol; + continue; + } + if (c === '/' && text[i + 1] === '*') { + const end = text.indexOf('*/', i + 2); + i = end === -1 ? text.length : end + 1; + continue; + } + if (c === '"' || c === "'" || c === '`') { + const end = closeQuote(text, i); + const quotedKey = keyPosition && text.slice(i + 1, end) === 'form'; + if (quotedKey && /^\s*:/.test(text.slice(end + 1, end + 40))) return true; + i = end; + keyPosition = false; + continue; + } + if (c === '{' || c === '[' || c === '(') { + depth += 1; + keyPosition = false; + continue; + } + if (c === '}' || c === ']' || c === ')') { + depth -= 1; + keyPosition = false; + continue; + } + if (c === ',') { + keyPosition = depth === 1; + continue; + } + if (keyPosition) { + word.lastIndex = i; + const key = word.exec(text)?.[0]; + if (key !== undefined) { + if (key === 'form' && /^\s*[:,}]/.test(text.slice(i + key.length, i + key.length + 40))) return true; + i += key.length - 1; + } + } + keyPosition = false; + } + } + return false; +} + +/** Inline code spans are prose; newline-bounded, so a fenced example is still judged. */ +const stripInlineCode = (text: string): string => text.replace(/`[^`\n]*`/g, ''); + +/** The arms a file's text authors. `ext` decides whether a bare YAML scalar can be the kind. */ +function judge(text: string, ext: string): Arm[] { + const judged = stripInlineCode(text); + const arms: Arm[] = []; + if (FORM_VIEWS_KEY.test(judged)) arms.push('formViews'); + if (VIEW_KIND_FORM.test(judged) || (YAML_BEARING_EXT.has(ext) && VIEW_KIND_FORM_YAML.test(judged))) { + arms.push("viewKind: 'form'"); + } + if (containerAuthorsForm(judged)) arms.push('defineView({ form })'); + return arms; +} + +/** Whether the walk judges this file at all: the population the header states. */ +function inPopulation(rel: string, ext: string): boolean { + if (rel.startsWith('examples/')) return EXAMPLES_EXT.has(ext) || EXAMPLE_APP_SRC_TS.test(rel); + if (rel.startsWith('packages/')) return PACKAGES_EXT.has(ext); + return SCANNED_EXT.has(ext); +} + +/** + * Structural exclusions, each with its reason. ⛔ NOT an allowlist file + * (`spec-property-retirement` §4): an entry is here because spelling the + * retired shape is its JOB, never because it has not been cleaned up yet. + */ +const EXCLUDED_PREFIXES = [ + // Release-owned prose records the removal; never edited by a code PR. + 'content/docs/releases/', +]; +/** + * Excused from arms A and C only, and still judged on the item kind. Each + * entry READS the pre-19 container as its input, so it has to spell the slots + * it looks for; nothing has the job of teaching a `form` view item. + */ +const READS_THE_OLD_CONTAINER = new Set([ + // ADR-0017's reporter: scans `defineView` containers and looks for their `formViews` block. + 'scripts/codemod/view-to-viewitem.mjs', +]); +const TSUP_BUNDLED_CONFIG = /\.bundled_[^./]+\.mjs$/; + +const readIfPresent = (full: string): string | undefined => { + try { + return fs.readFileSync(full, 'utf-8'); + } catch (err) { + if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') throw err; + return undefined; + } +}; + +describe('view is lists only — the retired form slots are authored nowhere an author copies from', () => { + it('the matcher recognises each authoring arm and ignores its neighbours (anti-vacuity)', () => { + // A — `formViews` as a key. + expect(judge("defineView({ object: 'task', listViews: {}, formViews: { edit: {} } })", '.ts')).toEqual(['formViews']); + expect(judge('{ "object": "task", "formViews": { "edit": {} } }', '.json')).toEqual(['formViews']); + expect(judge('object: task\nformViews:\n edit:\n type: simple\n', '.yaml')).toEqual(['formViews']); + // B — the item kind, in each spelling. + expect(judge("defineViewItem({ name: 'task.edit', object: 'task', viewKind: 'form', config: {} })", '.ts')).toEqual(["viewKind: 'form'"]); + expect(judge('{ "name": "task.edit", "viewKind": "form" }', '.json')).toEqual(["viewKind: 'form'"]); + expect(judge('- name: task.edit\n viewKind: form\n config: {}\n', '.yaml')).toEqual(["viewKind: 'form'"]); + expect(judge('Prose.\n\n```yaml\nviewKind: form # the record form\n```\n', '.mdx')).toEqual(["viewKind: 'form'"]); + // C — a container's own `form` member: keyed, quoted, shorthand, and inside a fenced comment. + expect(judge("defineView({\n object: 'task',\n list: { type: 'grid' },\n form: { sections: [] },\n})", '.ts')).toEqual(['defineView({ form })']); + expect(judge('defineView({ "object": "task", "form": {} })', '.ts')).toEqual(['defineView({ form })']); + expect(judge('const v = defineView({ object, list, form });', '.ts')).toEqual(['defineView({ form })']); + expect(judge('```ts\n// A view is authored with defineView({ list, form }); both are nested.\n```\n', '.mdx')).toEqual(['defineView({ form })']); + + // Neighbours that must NOT match. + expect(judge("defineView({ object: 'task', list: { type: 'grid' }, listViews: { mine: { type: 'grid' } } })", '.ts')).toEqual([]); + expect(judge("defineViewItem({ name: 'task.all', object: 'task', viewKind: 'list', config: {} })", '.ts')).toEqual([]); + expect(judge("defineForm({ name: 'task.edit', object: 'task', sections: [] })", '.ts')).toEqual([]); + // Prose: an inline span says what was removed. + expect(judge('`formViews: { … }` and `viewKind: \'form\'` were removed in protocol 19; `defineView({ list, form })` is refused.', '.mdx')).toEqual([]); + // A `form` that is not the container's own member: nested deeper, or a value. + expect(judge("defineView({ object: 'task', list: { rowActions: [{ form: 'task.edit' }] } })", '.ts')).toEqual([]); + expect(judge("defineView({ object: 'task', list: { type: form } })", '.ts')).toEqual([]); + expect(judge("defineView({ object: 'task', list: { type: 'grid', form: 'task.edit' } })", '.ts')).toEqual([]); + expect(judge("defineView({ object: 'task', list: {} }); const form = defineForm({ form: 1 });", '.ts')).toEqual([]); + // A line comment, a block comment and a string inside a container are not members. + expect(judge("defineView({\n object: 'task', // was: list, form, listViews\n list: {},\n})", '.ts')).toEqual([]); + expect(judge("defineView({\n object: 'task', /* gone, form: a form item now */\n list: {},\n})", '.ts')).toEqual([]); + expect(judge("defineView({ object: 'task', description: 'list, form: both once', list: {} })", '.ts')).toEqual([]); + // A member READ is not an authoring; neither is a bare scalar in code. + expect(judge('const forms = view.formViews ? view.formViews : {};', '.ts')).toEqual([]); + expect(judge('const item = { viewKind: form };', '.ts')).toEqual([]); + // The kit's own spellings of the tombstones. + expect(judge("'ui/View:formViews [RETIRED]',", '.json')).toEqual([]); + expect(judge("export const entry = 'ui/View:formViews';", '.ts')).toEqual([]); + }); + + it('the population is the authoring surfaces, and a package contributes what it teaches', () => { + expect(inPopulation('skills/objectstack-ui/rules/list-views.md', '.md')).toBe(true); + expect(inPopulation('content/docs/concepts/architecture.mdx', '.mdx')).toBe(true); + expect(inPopulation('scripts/codemod/view-to-viewitem.mjs', '.mjs')).toBe(true); + expect(inPopulation('examples/app-crm/src/views/lead.view.ts', '.ts')).toBe(true); + expect(inPopulation('examples/app-crm/README.md', '.md')).toBe(true); + expect(inPopulation('packages/cli/README.md', '.md')).toBe(true); + // An example's code outside its `src/` tree is judged by its own `tsc`, as the radius declares. + // Joined, never one quoted path: the radius gate reads a quoted repo path as a file this suite + // reads, and no declared glob covers an example's test (the declaration says why). + expect(inPopulation(['examples', 'app-crm', 'test', 'smoke.test.ts'].join('/'), '.ts')).toBe(false); + // A package's code and JSON: the bound the header states. + expect(inPopulation('packages/metadata/src/plugin.ts', '.ts')).toBe(false); + expect(inPopulation('packages/rest/src/form-old-shape-before.json', '.json')).toBe(false); + }); + + it('no file inside the population still authors a form into a `view`', () => { + const offenders: string[] = []; + let visited = 0; + let mentioning = 0; + const skipDir = (name: string) => SKIPPED_DIRS.has(name) || name.startsWith('.'); + for (const root of WALK_ROOTS) { + for (const full of listRepoWalkFiles(path.join(REPO_ROOT, root), { skipDir })) { + const rel = path.relative(REPO_ROOT, full).split(path.sep).join('/'); + const name = path.basename(full); + const ext = path.extname(name); + if (!inPopulation(rel, ext)) continue; + if (name === 'CHANGELOG.md') continue; // release prose records the removal + if (EXCLUDED_PREFIXES.some((p) => rel.startsWith(p))) continue; + if (TSUP_BUNDLED_CONFIG.test(name)) continue; + visited += 1; + const text = readIfPresent(full); + if (text === undefined) continue; + if (text.includes('formViews') || text.includes('viewKind')) mentioning += 1; + let arms = judge(text, ext); + if (READS_THE_OLD_CONTAINER.has(rel)) arms = arms.filter((arm) => arm === "viewKind: 'form'"); + if (arms.length > 0) offenders.push(`${rel} [${arms.join(' + ')}]`); + } + } + // Anti-vacuity: the walk covered the population, and files that name the + // shapes at all (in prose, mostly) were really judged. + expect(visited).toBeGreaterThan(1000); + expect(mentioning).toBeGreaterThan(5); + expect( + offenders, + 'a form authored into a `view` is refused since protocol 19 (ADR-0159 D7) — write a `form` item (`defineForm`), and say so wherever this teaches', + ).toEqual([]); + }); +}); diff --git a/packages/spec/src/ui/view-inline-object-binding.test.ts b/packages/spec/src/ui/view-inline-object-binding.test.ts index 77ed593bb61..84e1a2cc865 100644 --- a/packages/spec/src/ui/view-inline-object-binding.test.ts +++ b/packages/spec/src/ui/view-inline-object-binding.test.ts @@ -87,13 +87,14 @@ describe('the runtime write door refuses the unbound inline view config', () => }; // The union envelope other consumers key on (ADR-0112 at the issue level). expect(root.code).toBe('invalid_union'); - expect(root.errors).toHaveLength(4); + // [ADR-0159 D7] Three members since the form overlay was retired in protocol 19. + expect(root.errors).toHaveLength(3); // Branch 2 is the listOverlay the body claims (`type: 'grid'`); #7510's - // focusing mutes the other three, so the author reads ONLY the binding + // focusing mutes the other two, so the author reads ONLY the binding // prescription, at the paths of the keys to add. const claimed = root.errors[2]!; expect(claimed.map((i) => i.path)).toEqual([['object'], ['viewKind']]); - for (const index of [0, 1, 3]) { + for (const index of [0, 1]) { expect(root.errors[index]).toHaveLength(1); expect(root.errors[index]![0]!.message).toContain('this body reads as `listOverlay`'); } @@ -200,8 +201,9 @@ describe('the emitted contract declares what it enforces', () => { const json = z.toJSONSchema(door(), { unrepresentable: 'any', io }) as { anyOf?: Array<{ required?: string[] }>; }; - expect(json.anyOf).toHaveLength(4); - for (const member of [json.anyOf![2]!, json.anyOf![3]!]) { + // [ADR-0159 D7] One inline arm since the form overlay was retired in protocol 19. + expect(json.anyOf).toHaveLength(3); + for (const member of [json.anyOf![2]!]) { expect(member.required ?? []).toEqual(expect.arrayContaining(['object', 'viewKind'])); } } diff --git a/packages/spec/src/ui/view-item-config-type.test.ts b/packages/spec/src/ui/view-item-config-type.test.ts index 15001ef2477..4abfbde3a1e 100644 --- a/packages/spec/src/ui/view-item-config-type.test.ts +++ b/packages/spec/src/ui/view-item-config-type.test.ts @@ -40,12 +40,10 @@ const listItem: ViewItem = { viewKind: 'list', config: { type: 'kanban', data: { provider: 'object', object: 'crm_lead' }, columns: ['name', 'stage'] }, }; -const formItem: ViewItem = { - name: 'crm_lead.intake', - object: 'crm_lead', - viewKind: 'form', - config: { type: 'simple', sections: [{ label: 'Main', fields: ['name'] }] }, -}; +// [ADR-0159 D7] The form arm was retired in protocol 19 (a view item is a list): this body no +// longer type-checks, and both doors refuse it at `viewKind` (pinned below). +// @ts-expect-error -- a form view item is no ViewItem since protocol 19. +const formItem: ViewItem = { name: 'crm_lead.intake', object: 'crm_lead', viewKind: 'form', config: { type: 'simple', sections: [{ label: 'Main', fields: ['name'] }] } }; const wireItem: ViewItemWire = { ...listItem, isPinned: true, sortOrder: 2 }; // ── What the arm-typed `config` refuses at compile time ────────────────────────────────────── @@ -53,7 +51,7 @@ const wireItem: ViewItemWire = { ...listItem, isPinned: true, sortOrder: 2 }; const LIST_CONFIG = { type: 'grid', data: { provider: 'object', object: 'crm_lead' }, columns: ['name'] } as const; // @ts-expect-error -- a list item's config is a ListView config, not a scalar. const scalarConfig: ViewItem = { name: 'crm_lead.x', object: 'crm_lead', viewKind: 'list', config: 42 }; -// @ts-expect-error -- the form arm's config is a FormView config: `grid` is not a form type. +// @ts-expect-error -- no form arm since protocol 19: `viewKind: 'form'` is not a ViewItem's. const listConfigOnFormArm: ViewItem = { name: 'crm_lead.x', object: 'crm_lead', viewKind: 'form', config: LIST_CONFIG }; // @ts-expect-error -- the same on the wire member. const wireScalarConfig: ViewItemWire = { name: 'crm_lead.x', object: 'crm_lead', viewKind: 'list', config: 42 }; @@ -82,18 +80,26 @@ void [ describe('a ViewItem config is typed by its arm, not unknown', () => { it('each body typed through the published names parses at its door', () => { expect(ViewItemSchema.safeParse(listItem).success).toBe(true); - expect(ViewItemSchema.safeParse(formItem).success).toBe(true); expect(ViewItemWireSchema.safeParse(wireItem).success).toBe(true); }); it('the bodies the type refuses are refused at `config` by both doors', () => { const scalar = { name: 'crm_lead.x', object: 'crm_lead', viewKind: 'list', config: 42 }; + for (const door of [ViewItemSchema, ViewItemWireSchema]) { + const result = door.safeParse(scalar); + expect(result.success).toBe(false); + expect(result.error?.issues.every((issue) => issue.path[0] === 'config')).toBe(true); + } + }); + + it('[ADR-0159 D7] a form item — any config — is refused at `viewKind` by both doors, with the prescription', () => { const formWithListConfig = { name: 'crm_lead.x', object: 'crm_lead', viewKind: 'form', config: LIST_CONFIG }; for (const door of [ViewItemSchema, ViewItemWireSchema]) { - for (const body of [scalar, formWithListConfig]) { + for (const body of [formItem, formWithListConfig]) { const result = door.safeParse(body); expect(result.success).toBe(false); - expect(result.error?.issues.every((issue) => issue.path[0] === 'config')).toBe(true); + expect(result.error?.issues.every((issue) => issue.path[0] === 'viewKind')).toBe(true); + expect(result.error?.issues[0]?.message).toMatch(/^`view\.viewKind: 'form'` was removed in @objectstack\/spec 19\.0\.0/); } } }); diff --git a/packages/spec/src/ui/view-metadata-schema.test.ts b/packages/spec/src/ui/view-metadata-schema.test.ts index 66405ad43df..c3a0b2a07c6 100644 --- a/packages/spec/src/ui/view-metadata-schema.test.ts +++ b/packages/spec/src/ui/view-metadata-schema.test.ts @@ -47,14 +47,18 @@ describe('ViewMetadataSchema — genuine validation across the three runtime sha expect(r.success).toBe(false); }); - it('accepts a well-formed form ViewItem', () => { + // [ADR-0159 D7] A view holds lists only since protocol 19: the + // well-formed form ViewItem this case accepted is refused whole, at + // `viewKind`, with the D7 prescription naming `forms:`. + it('REFUSES a well-formed form ViewItem at `viewKind` since protocol 19', () => { const r = ViewMetadataSchema.safeParse({ name: 'crm_lead.edit', object: 'crm_lead', viewKind: 'form', config: { type: 'simple', sections: [{ label: 'Details', fields: ['name'] }] }, }); - expect(r.success).toBe(true); + expect(r.success).toBe(false); + expect(JSON.stringify(r.error?.issues)).toContain("`view.viewKind: 'form'` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7)"); }); it('REJECTS a form ViewItem carrying an invalid form `type` (config validated, not stripped)', () => { @@ -148,7 +152,8 @@ describe('ViewMetadataSchema — genuine validation across the three runtime sha expect(text).toContain('Wrap it: `defineView({ list: { type, data, columns, … } })`'); }); - it('accepts a raw form config overlay', () => { + // [ADR-0159 D7] The form overlay member is gone with the form arm. + it('REFUSES a raw form config overlay since protocol 19', () => { const r = ViewMetadataSchema.safeParse({ type: 'simple', sections: [{ label: 'Details', fields: ['name'] }], @@ -156,7 +161,7 @@ describe('ViewMetadataSchema — genuine validation across the three runtime sha viewKind: 'form', object: 'crm_lead', }); - expect(r.success).toBe(true); + expect(r.success).toBe(false); }); it('REJECTS a flattened list overlay whose kanban binding is broken (genuine, not stripped)', () => { @@ -252,7 +257,10 @@ describe('ViewMetadataSchema — genuine validation across the three runtime sha // Guards against the mirror-image defect: a precondition that rejects the // platform's own writes is strictly worse than the hole it closed. // [#7741] The minimal accepted overlay now carries its binding pair. - expect(ViewMetadataSchema.safeParse({ type: 'simple', object: 'crm_lead', viewKind: 'form' }).success).toBe(true); + // [ADR-0159 D7] It was a form-bound `{ type: 'simple' }`; a view holds + // lists only since protocol 19, so the minimal overlay is list-bound. + expect(ViewMetadataSchema.safeParse({ type: 'grid', columns: ['name'], object: 'crm_lead', viewKind: 'list' }).success).toBe(true); + expect(ViewMetadataSchema.safeParse({ type: 'simple', object: 'crm_lead', viewKind: 'form' }).success).toBe(false); }); // Every shape the platform itself writes carries a declared key, so the @@ -277,7 +285,8 @@ describe('ViewMetadataSchema — genuine validation across the three runtime sha ['a switcher-reorder PUT', { sortOrder: 3, object: 'crm_lead', viewKind: 'list' }], ['a column-only overlay', { columns: ['name'], object: 'crm_lead', viewKind: 'list' }], ['a filter-only overlay', { filter: [{ field: 'name', operator: 'contains', value: 'x' }], object: 'crm_lead', viewKind: 'list' }], - ['an order-only overlay', { order: 2, object: 'crm_lead', viewKind: 'form' }], + // [ADR-0159 D7] form-bound until protocol 19; `order` is a list key too. + ['an order-only overlay', { order: 2, object: 'crm_lead', viewKind: 'list' }], ['a renamed view that still carries its config', { label: 'New name', columns: ['name'], object: 'crm_lead', viewKind: 'list' }], ])('leaves %s alone', (_label, body) => { expect(ViewMetadataSchema.safeParse(body).success).toBe(true); @@ -289,7 +298,8 @@ describe('ViewMetadataSchema — genuine validation across the three runtime sha // inert on it, and the refusal belongs to the overlay member, carrying the // retirement prescription at the key. it('REFUSES a hide PUT on a real view at the member, with the retirement prescription', () => { - const bound = { object: 'crm_lead', viewKind: 'form' } as const; + // [ADR-0159 D7] form-bound until protocol 19; a real view is a list now. + const bound = { object: 'crm_lead', viewKind: 'list' } as const; const r = ViewMetadataSchema.safeParse({ ...bound, hidden: true }); expect(r.success).toBe(false); if (r.success) return; @@ -361,11 +371,12 @@ describe('ViewMetadataSchema — genuine validation across the three runtime sha it('…but identity PLUS any real view key is fine — leanness is not the bar', () => { // [#7741] "identity" here means the FULL binding pair: `object` alone or // `viewKind` alone is half a binding and the members refuse it now. - expect(ViewMetadataSchema.safeParse({ name: 'v', object: 'o', viewKind: 'form', order: 2 }).success).toBe(true); + // [ADR-0159 D7] The first line was form-bound until protocol 19. + expect(ViewMetadataSchema.safeParse({ name: 'v', object: 'o', viewKind: 'list', order: 2 }).success).toBe(true); expect(ViewMetadataSchema.safeParse({ name: 'v', object: 'o', viewKind: 'list', isPinned: true }).success).toBe(true); // [#20230] …a RETIRED key is not a real view key: `hidden` used to stand // in the first line above, and the same identity plus it is refused now. - const identity = { name: 'v', object: 'o', viewKind: 'form' } as const; + const identity = { name: 'v', object: 'o', viewKind: 'list' } as const; expect(ViewMetadataSchema.safeParse({ ...identity, hidden: true }).success).toBe(false); }); @@ -384,7 +395,13 @@ describe('ViewMetadataSchema — genuine validation across the three runtime sha // by hand. ([#7741] full acceptance additionally needs the binding pair; // the vocabulary question this test asks is unchanged. [#29012] It was // `drawerSide` until that key became a tombstone.) - expect(ViewMetadataSchema.safeParse({ showStepIndicator: true, object: 'crm_lead', viewKind: 'form' }).success).toBe(true); + // [ADR-0159 D7] The form member left the union in protocol 19, so its + // keys left the vocabulary with it: `showStepIndicator` is now refused + // by the precondition, and the example is a list key nobody would + // allow-list by hand. + expect(ViewMetadataSchema.safeParse({ showRecordCount: true, object: 'crm_lead', viewKind: 'list' }).success).toBe(true); + const formKey = ViewMetadataSchema.safeParse({ showStepIndicator: true, object: 'crm_lead', viewKind: 'list' }); + expect(formKey.success).toBe(false); // …and a key that exists only NESTED (inside `config`) is not top-level // vocabulary, so it cannot smuggle a garbage body through. expect(ViewMetadataSchema.safeParse({ groupByField: 'stage' }).success).toBe(false); @@ -440,6 +457,7 @@ describe('ViewMetadataSchema — genuine validation across the three runtime sha it('converts to a JSON Schema anyOf (union → anyOf) without throwing', () => { const json = z.toJSONSchema(ViewMetadataSchema, { unrepresentable: 'any' }) as Record; expect(Array.isArray(json.anyOf)).toBe(true); - expect((json.anyOf as unknown[]).length).toBe(4); + // [ADR-0159 D7] Four members until protocol 19; the form overlay left. + expect((json.anyOf as unknown[]).length).toBe(3); }); }); diff --git a/packages/spec/src/ui/view-metadata-type.test.ts b/packages/spec/src/ui/view-metadata-type.test.ts index 8907cdebecd..2fb5283b71a 100644 --- a/packages/spec/src/ui/view-metadata-type.test.ts +++ b/packages/spec/src/ui/view-metadata-type.test.ts @@ -22,6 +22,7 @@ import { describe, it, expect } from 'vitest'; import { + ViewMetadataSchema, VIEW_METADATA_BRANCHES, VIEW_METADATA_MEMBERS, diagnoseViewMetadata, @@ -43,18 +44,14 @@ const container: ViewMetadata = { list: { type: 'grid', data: { provider: 'object', object: 'crm_lead' }, columns: ['name'] }, }; const listOverlay: ViewMetadata = { type: 'grid', columns: ['name'], object: 'crm_lead', viewKind: 'list' }; -const formOverlay: ViewMetadata = { - type: 'simple', - sections: [{ label: 'Main', fields: ['name'] }], - object: 'crm_lead', - viewKind: 'form', -}; +// [ADR-0159 D7] The form overlay member was retired in protocol 19 (a view is a list). +// @ts-expect-error -- a flattened form overlay is no view body since protocol 19. +const formOverlay: ViewMetadata = { type: 'simple', sections: [{ label: 'Main', fields: ['name'] }], object: 'crm_lead', viewKind: 'form' }; const BODY_OF_EACH_MEMBER: Record = { viewItem, container, listOverlay, - formOverlay, }; // ── What `ViewMetadata` refuses at compile time ────────────────────────────────────────────── @@ -81,6 +78,8 @@ void [parsedFromUnknown, parsedUndeclaredKey, parsedScalar]; describe('ViewMetadata is a view body, not unknown', () => { it('has a typed body for every member of the union', () => { expect(Object.keys(BODY_OF_EACH_MEMBER).sort()).toEqual([...VIEW_METADATA_BRANCHES].sort()); + // [ADR-0159 D7] The retired form overlay body is refused by the door. + expect(ViewMetadataSchema.safeParse(formOverlay).success).toBe(false); }); for (const branch of VIEW_METADATA_BRANCHES) { diff --git a/packages/spec/src/ui/view-overlay-options-bag.test.ts b/packages/spec/src/ui/view-overlay-options-bag.test.ts index b4a03d48d31..99089d8e810 100644 --- a/packages/spec/src/ui/view-overlay-options-bag.test.ts +++ b/packages/spec/src/ui/view-overlay-options-bag.test.ts @@ -192,11 +192,13 @@ describe('what the fold cannot decide stays as stored, with a TODO', () => { }); describe('the form overlay cannot take the bag the list overlay refused', () => { + // [ADR-0159 D7] The flattened form overlay member was retired in protocol 19 + // (a view is a list), so no member is left to take the bag the list member + // refuses, and a form-bound body is refused with the D7 prescription. it('a column-less, type-less body with a bad `options` bag is refused, not accepted as a form', () => { - // Without the form overlay's `options` pin this body is ACCEPTED: the list - // member refuses it (no `columns`, and the bag), the form member — which - // `.strip()`s and requires no list key — takes it, and the bag is stored - // unjudged after all. + // Before protocol 19, without the form overlay's `options` pin this body + // was ACCEPTED: the list member refused it (no `columns`, and the bag), the + // form member — which `.strip()`ped and required no list key — took it. const body = { name: 'crm_lead.all', object: 'crm_lead', @@ -205,11 +207,10 @@ describe('the form overlay cannot take the bag the list overlay refused', () => options: { timeline: { metaFields: ['region'] } }, }; expect(ViewMetadataSchema.safeParse(body).success).toBe(false); - const form = VIEW_METADATA_MEMBERS.formOverlay.safeParse(body); - expect(form.success).toBe(false); + expect(Object.keys(VIEW_METADATA_MEMBERS)).not.toContain('formOverlay'); }); - it('a flat form overlay carrying `options` is refused with the list-view prescription', () => { + it('a flat form overlay carrying `options` is refused, by the list member, with the D7 prescription', () => { const body = { name: 'lead.contact_us', object: 'lead', @@ -220,14 +221,14 @@ describe('the form overlay cannot take the bag the list overlay refused', () => const d = diagnoseViewMetadata(body); expect(d.success).toBe(false); if (d.success) return; - expect(d.branch).toBe('formOverlay'); - const hit = (d.issues as unknown as Issue[]).find((i) => i.path[0] === 'options'); - expect(hit?.message).toContain('A form view carries no `options` bag'); + expect(d.branch).toBe('listOverlay'); + const hit = (d.issues as unknown as Issue[]).find((i) => i.path[0] === 'viewKind'); + expect(hit?.message).toMatch(/^`view\.viewKind: 'form'` was removed in @objectstack\/spec 19\.0\.0/); }); - it('CONTROL: a flat form overlay without `options` still parses', () => { + it('CONTROL: a flat form overlay without `options` is refused too since 19 (a view is a list)', () => { const body = { name: 'lead.contact_us', object: 'lead', viewKind: 'form', type: 'simple' }; - expect(ViewMetadataSchema.safeParse(body).success).toBe(true); + expect(ViewMetadataSchema.safeParse(body).success).toBe(false); }); }); @@ -269,15 +270,19 @@ describe('a ViewItem record carries no top-level `options` bag', () => { expect(VIEW_METADATA_MEMBERS.viewItem.safeParse(record({ options: {} })).success).toBe(false); }); - it('on the form arm too', () => { - const hit = recordIssueAtOptions({ + it('on the form arm — retired since 19, so the record is refused at `viewKind` with the D7 prescription', () => { + const d = diagnoseViewMetadata({ name: 'lead.contact_us', object: 'lead', viewKind: 'form', config: { type: 'simple', data: { provider: 'object', object: 'lead' } }, options: { timeline: { titleField: 'name' } }, }); - expect(hit.message).toMatch(/^A view item record carries no top-level `options` bag/); + expect(d.success).toBe(false); + if (d.success) return; + expect(d.branch).toBe('viewItem'); + const hit = (d.issues as unknown as Issue[]).find((i) => i.path[0] === 'viewKind'); + expect(hit?.message).toMatch(/^`view\.viewKind: 'form'` was removed in @objectstack\/spec 19\.0\.0/); }); it('CONTROL: the record without the bag parses, and `config.kanban` is where the block lives', () => { diff --git a/packages/spec/src/ui/view-overlay-owner-hidden-retirement.test.ts b/packages/spec/src/ui/view-overlay-owner-hidden-retirement.test.ts index 0265bbf2b13..ad0de9e0d82 100644 --- a/packages/spec/src/ui/view-overlay-owner-hidden-retirement.test.ts +++ b/packages/spec/src/ui/view-overlay-owner-hidden-retirement.test.ts @@ -76,7 +76,8 @@ const RETIRED = [ const MEMBERS = [ ['listOverlay', VIEW_METADATA_MEMBERS.listOverlay, LIST_OVERLAY], - ['formOverlay', VIEW_METADATA_MEMBERS.formOverlay, FORM_OVERLAY], + // [ADR-0159 D7] The flattened form overlay member was retired in protocol 19; + // a form-bound overlay is refused by the door (pinned below). ] as const; type Issue = { code: string; path: PropertyKey[]; message: string; errors?: Issue[][] }; @@ -114,7 +115,9 @@ describe('overlay owner/hidden retirement — the tombstones, at every door that // `PUT /api/v1/meta/view/:name` body against. const door = getMetadataTypeSchema('view'); expect(door).toBe(ViewMetadataSchema); - for (const overlay of [LIST_OVERLAY, FORM_OVERLAY]) { + // [ADR-0159 D7] A form-bound overlay is refused whatever it carries. + expect(door!.safeParse({ ...FORM_OVERLAY, [key]: value }).success).toBe(false); + for (const overlay of [LIST_OVERLAY]) { const r = door!.safeParse({ ...overlay, [key]: value }); expect(r.success, `${overlay.viewKind} overlay`).toBe(false); if (r.success) continue; @@ -138,13 +141,16 @@ describe('overlay owner/hidden retirement — the tombstones, at every door that }); } + it('[ADR-0159 D7] a form-bound overlay without the keys is refused too: a view is a list since 19', () => { + const live = { isDefault: true, order: 2, scope: 'shared', label: 'Leads' } as const; + expect(ViewMetadataSchema.safeParse({ ...FORM_OVERLAY, ...live }).success).toBe(false); + }); + it('CONTROL: the same overlays without the keys pass every door, live round-trip keys intact', () => { const live = { isDefault: true, order: 2, scope: 'shared', label: 'Leads' } as const; for (const [label, schema, body] of [ ['listOverlay member', VIEW_METADATA_MEMBERS.listOverlay, { ...LIST_OVERLAY, ...live }], - ['formOverlay member', VIEW_METADATA_MEMBERS.formOverlay, { ...FORM_OVERLAY, ...live }], ['door (list)', ViewMetadataSchema, { ...LIST_OVERLAY, ...live }], - ['door (form)', ViewMetadataSchema, { ...FORM_OVERLAY, ...live }], ['assembled (list)', AssembledViewArtifactSchema, { ...LIST_OVERLAY, ...live }], ] as const) { const r = schema.safeParse(body); @@ -200,12 +206,24 @@ describe('overlay owner/hidden retirement — the D2 conversion', () => { // CONTROL: the live round-trip keys on the same row survive. expect(rehydrated.isDefault).toBe(true); expect(rehydrated.label).toBe('Edit lead'); - // …and, because this row carries content (`isDefault`), the rehydrated row - // is what the write door accepts now, so a whole-row re-save of it saves. - // The row that carries NO content is the residue pinned below. - expect(ViewMetadataSchema.safeParse(rehydrated).success).toBe(true); - // CONTROL: the stored row itself, unconverted, is what the door now refuses. + // [ADR-0159 D7] This stored row is a FORM overlay: since protocol 19 the + // write door refuses it whatever it carries (a view is a list), so a + // whole-row re-save of it is refused with the D7 prescription. The stored + // row is not rewritten by the read (constraint 1); the list-bound twin + // below is the row a re-save still saves. + expect(ViewMetadataSchema.safeParse(rehydrated).success).toBe(false); + // CONTROL: the stored row itself, unconverted, is refused too. expect(ViewMetadataSchema.safeParse(stored).success).toBe(false); + + // The list-bound twin: because this row carries content (`isDefault`), the + // rehydrated row is what the write door accepts, so a whole-row re-save of + // it saves. The row that carries NO content is the residue pinned below. + const storedList = { ...LIST_OVERLAY, label: 'All leads', isDefault: true, owner: 'usr_7', hidden: true }; + const rehydratedList = applyConversionsToStoredItem('view', storedList) as Record; + expect(rehydratedList).not.toHaveProperty('owner'); + expect(rehydratedList).not.toHaveProperty('hidden'); + expect(ViewMetadataSchema.safeParse(rehydratedList).success).toBe(true); + expect(ViewMetadataSchema.safeParse(storedList).success).toBe(false); }); it('strips a flat row that has no `viewKind` yet — the write path heals that in, then would refuse the key', () => { diff --git a/packages/spec/src/ui/view-overlay-viewkind-arm.test.ts b/packages/spec/src/ui/view-overlay-viewkind-arm.test.ts index 47c8f111b93..5ab88d992b1 100644 --- a/packages/spec/src/ui/view-overlay-viewkind-arm.test.ts +++ b/packages/spec/src/ui/view-overlay-viewkind-arm.test.ts @@ -45,6 +45,14 @@ * list overlay WITH `columns`. ⛔ Deliberately NOT pinned here as desired * behaviour: it is a named same-family residual (the PR's acceptance notes), * not a contract. + * + * ## [ADR-0159 D7] Since protocol 19: one flattened member + * + * A view holds lists only, so the flattened FORM overlay member was retired + * with the rest of the view-held forms. A `viewKind: 'form'` body is claimed + * by the list member, which refuses it with the retired value's prescription + * (it names the `form` item). The rows below that pinned the form member's + * verdicts are kept and re-measured to that answer. */ import { describe, expect, it } from 'vitest'; import { z } from 'zod'; @@ -165,21 +173,24 @@ describe('a column-less list overlay that NAMES a `type` stays refused — at `c }); }); -describe('the mirror: a `viewKind: form` body is judged by the form member', () => { - it('list `columns` on a form overlay is REFUSED under formOverlay, at `columns`, with the count prescription', () => { +describe('the mirror: a `viewKind: form` body is claimed by the list member, and refused (ADR-0159 D7)', () => { + // Before protocol 19 the form member judged these bodies; it is retired, and + // a form's body-column count is a `form` item's `columns` now. + it('list `columns` on a form-bound body is REFUSED under listOverlay, at `viewKind`, with the D7 prescription', () => { const r = refusal({ ...FORM, columns: ['name'] }); expect(r.topCodes).toEqual(['invalid_union']); - expect(r.branch).toBe('formOverlay'); + expect(r.branch).toBe('listOverlay'); expect(r.issues).toHaveLength(1); - expect(r.issues[0]).toMatchObject({ code: 'invalid_type', path: ['columns'] }); - expect(r.issues[0]!.message).toMatch(/^On a form view `columns` is the NUMBER of body columns/); - expect(r.issues[0]!.message).toContain('set `viewKind: "list"`'); + expect(r.issues[0]).toMatchObject({ path: ['viewKind'] }); + expect(r.issues[0]!.message).toMatch(/^`view\.viewKind: 'form'` was removed in @objectstack\/spec 19\.0\.0/); }); - it('…while a form body-column COUNT is still accepted (the form schema\'s own constraints, unchanged)', () => { - expect(acceptance({ ...FORM, columns: 2 }).branch).toBe('formOverlay'); - const r = refusal({ ...FORM, columns: 0 }); - expect(r.issues[0]).toMatchObject({ code: 'too_small', path: ['columns'] }); + it('…and so is a form body-column COUNT, which only a `form` item carries now', () => { + for (const columns of [2, 0]) { + const r = refusal({ ...FORM, columns }); + expect(r.branch).toBe('listOverlay'); + expect(r.issues.some((i) => i.path[0] === 'viewKind' && /removed in @objectstack\/spec 19\.0\.0/.test(i.message))).toBe(true); + } }); }); @@ -197,16 +208,12 @@ describe('W2 — a list-legal value under a key both arms declare differently is }); describe('controls — byte-identical parse output (measured on origin/main ce70876e)', () => { - it('a real form overlay', () => { - const { data, branch } = acceptance({ + it('a real form overlay — accepted until protocol 19, refused since (ADR-0159 D7)', () => { + const r = refusal({ name: 'acct.f', object: 'account', viewKind: 'form', type: 'simple', sections: [{ label: 'Main', fields: ['name'] }], }); - expect(branch).toBe('formOverlay'); - expect(JSON.stringify(data)).toBe( - // No `columns`: a section's undeclared density is the renderer's, and the parse adds no default. - '{"type":"simple","sections":[{"label":"Main","collapsible":false,"collapsed":false,"fields":["name"]}],' - + '"name":"acct.f","object":"account","viewKind":"form"}', - ); + expect(r.branch).toBe('listOverlay'); + expect(r.issues.some((i) => i.path[0] === 'viewKind' && /removed in @objectstack\/spec 19\.0\.0/.test(i.message))).toBe(true); }); it('a list overlay WITH `columns` (and no `type` — the default still lands in its own key position)', () => { @@ -221,23 +228,21 @@ describe('controls — byte-identical parse output (measured on origin/main ce70 }); describe('each member judges ONE viewKind — read off the members themselves', () => { - it('a direct parse of the form member names where a list body is judged', () => { - const r = VIEW_METADATA_MEMBERS.formOverlay.safeParse({ ...LIST, sort: [{ field: 'name', order: 'asc' }] }); - expect(r.success).toBe(false); - const issue = r.error!.issues.find((i) => i.path[0] === 'viewKind'); - expect(issue?.message).toMatch(/^This is the flattened FORM overlay member, which judges `viewKind: "form"` only\./); - expect(issue?.message).toContain('`VIEW_METADATA_MEMBERS.listOverlay`'); + it('[ADR-0159 D7] there is no form member any more; the list member is the one flattened member', () => { + expect(Object.keys(VIEW_METADATA_MEMBERS)).not.toContain('formOverlay'); + expect(VIEW_METADATA_MEMBERS.listOverlay.safeParse({ ...LIST, sort: [{ field: 'name', order: 'asc' }] }).success).toBe(true); }); - it('…and the list member refuses a form body the same way', () => { + it('…and the list member refuses a form body with the retired value\'s prescription', () => { const r = VIEW_METADATA_MEMBERS.listOverlay.safeParse({ ...FORM, columns: ['name'] }); expect(r.success).toBe(false); const issue = r.error!.issues.find((i) => i.path[0] === 'viewKind'); - expect(issue?.message).toMatch(/^This is the flattened LIST overlay member, which judges `viewKind: "list"` only\./); + expect(issue?.message).toMatch(/^`view\.viewKind: 'form'` was removed in @objectstack\/spec 19\.0\.0 \(ADR-0159 D7\)/); + expect(issue?.message).toContain('`form` item'); }); - it('an ABSENT viewKind keeps the binding prescription, on both members', () => { - for (const member of [VIEW_METADATA_MEMBERS.listOverlay, VIEW_METADATA_MEMBERS.formOverlay]) { + it('an ABSENT viewKind keeps the binding prescription', () => { + for (const member of [VIEW_METADATA_MEMBERS.listOverlay]) { const r = member.safeParse({ object: 'crm_lead', hidden: true }); const issue = r.error!.issues.find((i) => i.path[0] === 'viewKind'); expect(issue?.message).toContain('This inline view config names no `viewKind`'); @@ -246,22 +251,20 @@ describe('each member judges ONE viewKind — read off the members themselves', }); describe('the premise: no pipe, and the served JSON Schema moves only by the contract', () => { - it('both overlay members are still plain object schemas', () => { + it('the overlay member is still a plain object schema', () => { // A pipe serves its INPUT side to `/api/v1/meta/types/view`, and for a // transform that is `{}` (the `assertViewIdentity` docblock). The input-side // refusal and the default are both CHECKS on the object instead. expect((VIEW_METADATA_MEMBERS.listOverlay as unknown as { _zod: { def: { type: string } } })._zod.def.type).toBe('object'); - expect((VIEW_METADATA_MEMBERS.formOverlay as unknown as { _zod: { def: { type: string } } })._zod.def.type).toBe('object'); }); - it.each(['input', 'output'] as const)('the %s JSON Schema: four members, one viewKind per overlay arm, list `type` default kept', (io) => { + it.each(['input', 'output'] as const)('the %s JSON Schema: three members (the form overlay retired), viewKind `list` on the overlay, list `type` default kept', (io) => { const json = z.toJSONSchema(ViewMetadataSchema, { unrepresentable: 'any', io }) as { anyOf: Array<{ properties: Record; required?: string[] }>; }; - expect(json.anyOf).toHaveLength(4); - const [, , list, form] = json.anyOf; + expect(json.anyOf).toHaveLength(3); + const [, , list] = json.anyOf; expect(list!.properties.viewKind!.enum).toEqual(['list']); - expect(form!.properties.viewKind!.enum).toEqual(['form']); expect(list!.properties.type!.default).toBe('grid'); expect(list!.required).not.toContain('columns'); expect(list!.required).toEqual(expect.arrayContaining(['object', 'viewKind'])); diff --git a/packages/spec/src/ui/view-overlay-viewkind-type.test.ts b/packages/spec/src/ui/view-overlay-viewkind-type.test.ts index 08d6107f2e8..42190d7d2e9 100644 --- a/packages/spec/src/ui/view-overlay-viewkind-type.test.ts +++ b/packages/spec/src/ui/view-overlay-viewkind-type.test.ts @@ -2,7 +2,9 @@ /** * [#19920] Each flattened overlay member's static `viewKind` is its own arm's literal: `'list'` on - * the list overlay, `'form'` on the form overlay. The list overlay's `type` and `columns` carry the + * the list overlay. [ADR-0159 D7] The form overlay was retired in protocol 19 (a view is a list), + * so the list overlay is the one flattened member, and a `viewKind: 'form'` body answers the + * retired value's prescription. The list overlay's `type` and `columns` carry the * list shape's own types, not `unknown`. And the list overlay's `type` default, which the parse * applies and the output type does not carry, is what the `ViewMetadataParsed` / * `AssembledViewArtifactParsed` TSDoc says it is. @@ -34,6 +36,7 @@ import type { z } from 'zod'; import { VIEW_METADATA_MEMBERS, ViewMetadataSchema, + diagnoseViewMetadata, type ViewMetadata, type ViewMetadataParsed, } from './view.zod'; @@ -45,23 +48,15 @@ import { type ListOverlayIn = z.input; type ListOverlayOut = z.output; -type FormOverlayIn = z.input; -type FormOverlayOut = z.output; // ── Each member's `viewKind` is its own arm's literal ──────────────────────────────────────── const listKindIn: ListOverlayIn['viewKind'] = 'list'; const listKindOut: ListOverlayOut['viewKind'] = 'list'; -const formKindIn: FormOverlayIn['viewKind'] = 'form'; -const formKindOut: FormOverlayOut['viewKind'] = 'form'; // @ts-expect-error -- the list overlay member judges `viewKind: 'list'` only. const listKindInForm: ListOverlayIn['viewKind'] = 'form'; // @ts-expect-error -- on its output too. const listKindOutForm: ListOverlayOut['viewKind'] = 'form'; -// @ts-expect-error -- the form overlay member judges `viewKind: 'form'` only. -const formKindInList: FormOverlayIn['viewKind'] = 'list'; -// @ts-expect-error -- on its output too. -const formKindOutList: FormOverlayOut['viewKind'] = 'list'; // ── The body both doors refuse no longer type-checks as any union type ─────────────────────── @@ -73,7 +68,7 @@ const parsedArtifact: AssembledViewArtifactParsed = { type: 'grid', columns: ['n const metadata: ViewMetadata = { type: 'grid', columns: ['name'], object: 'crm_lead', viewKind: 'form' }; // @ts-expect-error -- nor a parsed one. const parsedMetadata: ViewMetadataParsed = { type: 'grid', columns: ['name'], object: 'crm_lead', viewKind: 'form' }; -void [listKindIn, listKindOut, formKindIn, formKindOut, listKindInForm, listKindOutForm, formKindInList, formKindOutList]; +void [listKindIn, listKindOut, listKindInForm, listKindOutForm]; void [artifact, parsedArtifact, metadata, parsedMetadata]; // ── The list overlay's `type` and `columns` carry the list shape's types ───────────────────── @@ -113,11 +108,21 @@ describe('the flattened overlay members keep their own viewKind literal', () => it('the list-shaped `viewKind: "form"` body is refused by every door that judges it', () => { const body = { type: 'grid', columns: ['name'], object: 'crm_lead', viewKind: 'form' }; expect(VIEW_METADATA_MEMBERS.listOverlay.safeParse(body).success).toBe(false); - expect(VIEW_METADATA_MEMBERS.formOverlay.safeParse(body).success).toBe(false); expect(ViewMetadataSchema.safeParse(body).success).toBe(false); expect(AssembledViewArtifactSchema.safeParse(body).success).toBe(false); }); + it("[ADR-0159 D7] the refusal is the retired `viewKind: 'form'` prescription, naming the `form` item", () => { + const body = { type: 'grid', columns: ['name'], object: 'crm_lead', viewKind: 'form' }; + expect(ViewMetadataSchema.safeParse(body).success).toBe(false); + const d = diagnoseViewMetadata(body); + expect(d.success).toBe(false); + if (d.success) return; + expect(d.branch).toBe('listOverlay'); + const messages = d.issues.map((i) => i.message).join('\n'); + expect(messages).toMatch(/`view\.viewKind: 'form'` was removed in @objectstack\/spec 19\.0\.0.*`form` item/s); + }); + it('a list overlay whose `columns` is a number is refused by every door that judges it', () => { const body = { object: 'crm_lead', viewKind: 'list', columns: 42 }; expect(VIEW_METADATA_MEMBERS.listOverlay.safeParse(body).success).toBe(false); diff --git a/packages/spec/src/ui/view-union-branch-focus.test.ts b/packages/spec/src/ui/view-union-branch-focus.test.ts index 95373042a46..849834baf8a 100644 --- a/packages/spec/src/ui/view-union-branch-focus.test.ts +++ b/packages/spec/src/ui/view-union-branch-focus.test.ts @@ -55,6 +55,12 @@ * every misdirected body is asserted to have picked `container` under it. * Delete the `.check()` in `view.zod.ts` and the tests in §1 go red; that * assertion is what says so without needing the revert. + * + * [ADR-0159 D7] Since protocol 19 a view item is a list: the form arm, and the + * flattened form overlay, were retired. The form-item bodies below are kept; + * each is now refused at `viewKind` with the retired value's prescription, and + * that prescription is what the claimed branch surfaces in place of the + * container text — the focusing this file pins, on the major's answer. */ import { describe, expect, it } from 'vitest'; @@ -129,21 +135,24 @@ function rendered(body: unknown): string { * The general case the card asked to confirm before sizing: four unrelated * ViewItem-branch failures, each expected to name its OWN key. */ +/** [ADR-0159 D7] What a form-item body surfaces since protocol 19: the retired value's prescription. */ +const FORM_KIND_RETIRED = "`view.viewKind: 'form'` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7)"; + const MISDIRECTED: Array<[string, unknown, string]> = [ [ - 'the card\'s repro, on `keyField` — an unknown subkey inside a nested form-field block', + 'the card\'s repro, on `keyField` — a form item, refused since 19 at `viewKind`', formItem({ field: 'owner', keyField: { field: 'name', sort: [{ field: 'email', order: 'desc' }] } }), - 'sort', + FORM_KIND_RETIRED, ], [ - 'the retired `publicPicker` key itself — its prescription, not the container text', + 'the retired `publicPicker` key on a form item — the D7 prescription, not the container text', formItem({ field: 'owner', publicPicker: { displayFields: ['name'] } }), - 'publicPicker', + FORM_KIND_RETIRED, ], [ - 'an unknown key on the form FIELD itself', + 'an unknown key on a form item\'s FIELD — the D7 prescription, not the container text', formItem({ field: 'owner', widthh: 6 }), - 'widthh', + FORM_KIND_RETIRED, ], [ 'a typo\'d column summary inside a LIST item', @@ -181,11 +190,14 @@ describe('a ViewItem-branch failure surfaces the ViewItem branch', () => { } }); - it('the byte-identical body minus the bad subkey still saves', () => { - // The card's own control: this is what makes the rejection a diagnostic - // problem rather than an acceptance one. - const r = ViewMetadataSchema.safeParse(formItem({ field: 'owner', keyField: { field: 'name' } })); - expect(r.success, JSON.stringify((r as any).error?.issues)).toBe(true); + it('the byte-identical body minus the bad subkey is refused too since 19, with the same prescription', () => { + // The card's own control, re-measured on the major (ADR-0159 D7): a form + // item no longer saves through the view door at all. The list-item row + // above keeps the diagnostic-versus-acceptance contrast for a live arm. + const body = formItem({ field: 'owner', keyField: { field: 'name' } }); + expect(ViewMetadataSchema.safeParse(body).success).toBe(false); + expect(rendered(body)).toContain(FORM_KIND_RETIRED); + expect(rendered(body)).not.toContain(CONTAINER_MISDIRECT); }); }); @@ -221,17 +233,17 @@ describe('the container diagnostic still belongs to containers', () => { describe('the union\'s error payload is focused, never reshaped', () => { const CLAIMED = formItem({ field: 'owner', keyField: { field: 'name', sort: [] } }); - it('keeps four branches, in position — a positional consumer still finds its member', () => { + it('keeps every branch, in position — a positional consumer still finds its member (three since the form overlay was retired)', () => { const issue = ViewMetadataSchema.safeParse(CLAIMED).error!.issues[0] as unknown as { code: string; errors: unknown[][]; }; expect(issue.code).toBe('invalid_union'); - expect(issue.errors).toHaveLength(4); + expect(issue.errors).toHaveLength(3); // Branch 0 is the claimed one and keeps its own issues; the rest are muted // in place rather than filtered out (objectui#3624's canary read errors[2]). - expect(issue.errors[0]).toMatchObject([{ path: ['config', 'sections', 0, 'fields', 0] }]); - for (const index of [1, 2, 3]) { + expect(issue.errors[0]).toMatchObject([{ path: ['viewKind'], message: expect.stringContaining(FORM_KIND_RETIRED) }]); + for (const index of [1, 2]) { expect(issue.errors[index]).toHaveLength(1); expect(issue.errors[index]![0]).toMatchObject({ code: 'invalid_type', path: [] }); } @@ -248,7 +260,7 @@ describe('the union\'s error payload is focused, never reshaped', () => { errors: { code?: string }[][]; }; expect(issue.code).toBe('invalid_union'); - expect(issue.errors).toHaveLength(4); + expect(issue.errors).toHaveLength(3); expect(issue.errors.some((branch) => branch.some((i) => i.code === 'unrecognized_keys'))).toBe(true); }); @@ -276,17 +288,23 @@ describe('⛔ the branch focusing did not move the acceptance face', () => { // this list is now REFUSED (pinned below, with the MISDIRECTED case that // shows its prescription reaching the author). Its slot here is taken by the // same form item with a `keyField` block, the nested control. + // + // [ADR-0159 D7] A third deliberate move, by the major: a view holds lists + // only, so the three form-shaped ACCEPTED entries (a form item, a + // container's `formViews`, a bound form overlay) are REFUSED since protocol + // 19 and pinned at the head of REFUSED below. const ACCEPTED: unknown[] = [ - formItem({ field: 'owner', keyField: { field: 'name' } }), { name: 'crm_lead.all', object: 'crm_lead', viewKind: 'list', config: { type: 'grid', columns: ['name'] } }, { object: 'crm_lead', list: { type: 'grid', columns: ['name'] } }, - { object: 'crm_lead', formViews: { my: { type: 'simple' } } }, { type: 'grid', columns: ['name'], isDefault: true, order: 2, object: 'crm_lead', viewKind: 'list' }, - { type: 'simple', object: 'crm_lead', viewKind: 'form' }, { isPinned: true, object: 'crm_lead', viewKind: 'list' }, ]; const REFUSED: Array<[unknown, string[]]> = [ + // [ADR-0159 D7] the three form-shaped bodies ACCEPTED before protocol 19. + [formItem({ field: 'owner', keyField: { field: 'name' } }), ['invalid_union']], + [{ object: 'crm_lead', formViews: { my: { type: 'simple' } } }, ['invalid_union']], + [{ type: 'simple', object: 'crm_lead', viewKind: 'form' }, ['invalid_union']], // [#7741] the unbound originals of the last three ACCEPTED entries. [{ type: 'grid', columns: ['name'], isDefault: true, order: 2 }, ['invalid_union']], [{ type: 'simple' }, ['invalid_union']], diff --git a/packages/spec/src/ui/view-union-diagnostics.test.ts b/packages/spec/src/ui/view-union-diagnostics.test.ts index fce177b362e..01e1059d76d 100644 --- a/packages/spec/src/ui/view-union-diagnostics.test.ts +++ b/packages/spec/src/ui/view-union-diagnostics.test.ts @@ -60,12 +60,13 @@ function unionOptions(): readonly unknown[] { } describe('the union members are contractual, not positional', () => { - it('exposes exactly four branches, in the union\'s own order', () => { + // [ADR-0159 D7] Three since protocol 19: the flattened FORM overlay was + // retired with the rest of the view-held forms (a view is a list). + it('exposes exactly three branches, in the union\'s own order', () => { expect([...VIEW_METADATA_BRANCHES]).toEqual([ 'viewItem', 'container', 'listOverlay', - 'formOverlay', ]); expect(Object.keys(VIEW_METADATA_MEMBERS)).toEqual([...VIEW_METADATA_BRANCHES]); }); @@ -94,8 +95,11 @@ describe('the union members are contractual, not positional', () => { // [#7741] The overlay arms require the `object` + `viewKind` binding. expect(VIEW_METADATA_MEMBERS.listOverlay.safeParse({ type: 'grid', columns: ['name'], object: 'crm_lead', viewKind: 'list' }).success).toBe(true); expect(VIEW_METADATA_MEMBERS.listOverlay.safeParse({ type: 'grid', columns: ['name'] }).success).toBe(false); - expect(VIEW_METADATA_MEMBERS.formOverlay.safeParse({ type: 'wizard', object: 'crm_lead', viewKind: 'form' }).success).toBe(true); - expect(VIEW_METADATA_MEMBERS.formOverlay.safeParse({ type: 'wizard' }).success).toBe(false); + // [ADR-0159 D7] The form overlay is gone; a form-bound flat body is the + // list overlay's to refuse, with the retired value's prescription. + expect(VIEW_METADATA_MEMBERS.listOverlay.safeParse({ type: 'wizard', object: 'crm_lead', viewKind: 'form' }).success).toBe(false); + expect(VIEW_METADATA_MEMBERS.listOverlay.safeParse({ object: 'crm_lead', viewKind: 'form' }).error!.issues[0]!.message) + .toMatch(/^`view\.viewKind: 'form'` was removed in @objectstack\/spec 19\.0\.0/); }); }); @@ -105,9 +109,12 @@ describe('selectViewMetadataBranch reads the members\' own discriminants', () => ['…even when the config is the broken part', { viewKind: 'list', config: { type: 'grid', columns: 1 } }, 'viewItem'], ['a container slot is a container', { object: 'a', list: LIST_CFG }, 'container'], ['listViews too', { object: 'a', listViews: {} }, 'container'], - ['an inherited viewKind settles a flat overlay', { viewKind: 'form', title: 'T' }, 'formOverlay'], + // [ADR-0159 D7] `viewKind: 'form'` claims the list overlay, whose parse + // names the retired value's prescription; a form-family `type` alone + // settles nothing, as an unknown type does. + ['an inherited viewKind settles a flat overlay', { viewKind: 'form', title: 'T' }, 'listOverlay'], ['so does a list-family type', { type: 'kanban' }, 'listOverlay'], - ['and a form-family type', { type: 'wizard' }, 'formOverlay'], + ['a form-family type settles nothing since 19', { type: 'wizard' }, null], ['nothing settles a bare aux PUT', { isPinned: true }, null], ['nor an unknown type', { type: 'sideways' }, null], ['non-objects claim nothing', 'nope', null], @@ -119,11 +126,11 @@ describe('selectViewMetadataBranch reads the members\' own discriminants', () => // The `type` enums are read off the member schemas, never re-listed here, so // a new view type cannot make the dispatch disagree with the members. - it('covers every declared list/form type', () => { + it('covers every declared list type; a form type claims nothing since 19', () => { const listTypes = ['grid', 'kanban', 'gallery', 'calendar', 'timeline', 'gantt', 'map', 'chart', 'tree']; const formTypes = ['simple', 'tabbed', 'wizard']; for (const type of listTypes) expect(selectViewMetadataBranch({ type })).toBe('listOverlay'); - for (const type of formTypes) expect(selectViewMetadataBranch({ type })).toBe('formOverlay'); + for (const type of formTypes) expect(selectViewMetadataBranch({ type })).toBe(null); }); // [#27155] The retired form `type` members left the enum, so on their own @@ -132,7 +139,7 @@ describe('selectViewMetadataBranch reads the members\' own discriminants', () => it('a retired form type settles nothing on its own; viewKind still does', () => { for (const type of ['split', 'drawer', 'modal']) { expect(selectViewMetadataBranch({ type })).toBe(null); - expect(selectViewMetadataBranch({ type, viewKind: 'form' })).toBe('formOverlay'); + expect(selectViewMetadataBranch({ type, viewKind: 'form' })).toBe('listOverlay'); } }); }); @@ -164,7 +171,7 @@ describe('diagnoseViewMetadata names the failing branch', () => { errors: unknown[][]; }; expect(root.code).toBe('invalid_union'); - expect(root.errors).toHaveLength(4); + expect(root.errors).toHaveLength(3); expect(root.errors[2]).toMatchObject([{ path: ['columns'] }]); }); @@ -254,9 +261,6 @@ describe('diagnoseViewMetadata names the failing branch', () => { // parse output re-measured, and the unbound original moves to REFUSED so the // flip itself is pinned rather than silently absorbed. describe('the acceptance face of ViewMetadataSchema — frozen by the diagnostics work; every move since is deliberate and pinned', () => { - // A section's `columns` has no default: an undeclared density is the renderer's, - // so the parse adds no `columns` key (it added `columns: 1` before the default was dropped). - const SECTION = { label: 'Main', collapsible: false, collapsed: false, fields: ['name'] }; /** [#7741] The binding pair the write path inherits onto a shadowing overlay. */ const BOUND_LIST = { object: 'crm_lead', viewKind: 'list' } as const; const BOUND_FORM = { object: 'crm_lead', viewKind: 'form' } as const; @@ -282,15 +286,10 @@ describe('the acceptance face of ViewMetadataSchema — frozen by the diagnostic const ACCEPTED: Array<[string, unknown, unknown]> = [ ['viewItem.list', { name: 'crm_lead.all', object: 'crm_lead', viewKind: 'list', config: LIST_CFG }, { viewKind: 'list', config: LIST_CFG, name: 'crm_lead.all', object: 'crm_lead' }], - ['viewItem.form', { name: 'crm_lead.edit', object: 'crm_lead', viewKind: 'form', config: FORM_CFG }, - { viewKind: 'form', config: { type: 'simple', sections: [SECTION] }, name: 'crm_lead.edit', object: 'crm_lead' }], ['viewItem.wire.aux', { name: 'a.b', object: 'a', viewKind: 'list', config: LIST_CFG, isPinned: true, sortOrder: 3 }, { viewKind: 'list', config: LIST_CFG, name: 'a.b', object: 'a', isPinned: true, sortOrder: 3 }], ['container.list', { object: 'crm_lead', list: LIST_CFG }, { object: 'crm_lead', list: LIST_CFG }], - ['container.form', { object: 'crm_lead', form: FORM_CFG }, { object: 'crm_lead', form: { type: 'simple', sections: [SECTION] } }], ['container.listViews', { object: 'crm_lead', listViews: { my: LIST_CFG } }, { object: 'crm_lead', listViews: { my: LIST_CFG } }], - ['container.formViews', { object: 'crm_lead', formViews: { my: FORM_CFG } }, - { object: 'crm_lead', formViews: { my: { type: 'simple', sections: [SECTION] } } }], ['overlay.list.columns', { columns: ['name', 'stage'], ...BOUND_LIST }, { type: 'grid', columns: ['name', 'stage'], ...BOUND_LIST }], // [#20230] `hidden` left this row: the overlay's `owner` / `hidden` are @@ -298,11 +297,6 @@ describe('the acceptance face of ViewMetadataSchema — frozen by the diagnostic // same row WITH `hidden` is now in REFUSED as `overlay.list.aux.retiredHidden`. ['overlay.list.aux', { type: 'grid', columns: ['name'], isDefault: true, order: 2, ...BOUND_LIST }, { type: 'grid', columns: ['name'], isDefault: true, order: 2, ...BOUND_LIST }], - ['overlay.form.min', { type: 'simple', ...BOUND_FORM }, { type: 'simple', ...BOUND_FORM }], - ['overlay.form.sections', { sections: [{ label: 'Main', fields: ['name'] }], ...BOUND_FORM }, - { type: 'simple', sections: [SECTION], ...BOUND_FORM }], - ['overlay.form.identity', { name: 'x', object: 'crm_lead', viewKind: 'form', type: 'wizard' }, - { type: 'wizard', name: 'x', object: 'crm_lead', viewKind: 'form' }], ['overlay.list.consoleSortId', { sort: [{ id: 'row-1', field: 'name', order: 'asc' }], ...BOUND_LIST }, { type: 'grid', sort: [{ field: 'name', order: 'asc' }], ...BOUND_LIST }], ['overlay.list.consoleFilterId', { filter: [{ id: 'row-1', field: 'name', operator: 'equals', value: 'x' }], ...BOUND_LIST }, @@ -320,6 +314,18 @@ describe('the acceptance face of ViewMetadataSchema — frozen by the diagnostic ]; const REFUSED: Array<[string, unknown, string[]]> = [ + // [ADR-0159 D7] Formerly ACCEPTED: a view holds lists only since protocol + // 19. Each form shape is refused, and the claimed member's message is the + // retired key's (or value's) prescription naming the `form` item — pinned + // below. `overlay.form.sections` names no view key the identity check + // knows any more (`sections` was the form overlay's), so it is refused + // before the union runs, as any non-view body is. + ['viewItem.form', { name: 'crm_lead.edit', object: 'crm_lead', viewKind: 'form', config: FORM_CFG }, ['invalid_union']], + ['container.form', { object: 'crm_lead', form: FORM_CFG }, ['invalid_union']], + ['container.formViews', { object: 'crm_lead', formViews: { my: FORM_CFG } }, ['invalid_union']], + ['overlay.form.min', { type: 'simple', ...BOUND_FORM }, ['invalid_union']], + ['overlay.form.sections', { sections: [{ label: 'Main', fields: ['name'] }], ...BOUND_FORM }, ['custom']], + ['overlay.form.identity', { name: 'x', object: 'crm_lead', viewKind: 'form', type: 'wizard' }, ['invalid_union']], ['viewItem.badKind', { name: 'a.b', object: 'a', viewKind: 'chart', config: LIST_CFG }, ['invalid_union']], ['viewItem.badConfig', { name: 'a.b', object: 'a', viewKind: 'list', config: { type: 'grid', columns: 'nope' } }, ['invalid_union']], ['viewItem.typoConfg', { name: 'a.b', object: 'a', viewKind: 'list', confg: LIST_CFG }, ['custom']], @@ -336,7 +342,10 @@ describe('the acceptance face of ViewMetadataSchema — frozen by the diagnostic // `put.hidden`): the overlay's `hidden` / `owner` are retired, and a bound // overlay carrying either is refused at the key with the prescription. ['overlay.list.aux.retiredHidden', { type: 'grid', columns: ['name'], isDefault: true, order: 2, hidden: false, ...BOUND_LIST }, ['invalid_union']], - ['put.hidden', { hidden: true, ...BOUND_FORM }, ['invalid_union']], + // [ADR-0159 D7] Bound as a list now: a form binding is itself retired, and + // its prescription would come first (`put.hidden.formBound` keeps that row). + ['put.hidden', { hidden: true, ...BOUND_LIST }, ['invalid_union']], + ['put.hidden.formBound', { hidden: true, ...BOUND_FORM }, ['invalid_union']], ['put.owner', { owner: 'usr_7', ...BOUND_LIST }, ['invalid_union']], // [#26711] Formerly ACCEPTED with `filter` / `sort` stripped by the form // overlay, which declares neither: the save stored a bare form overlay. @@ -351,7 +360,9 @@ describe('the acceptance face of ViewMetadataSchema — frozen by the diagnostic ['unbound.overlay.list.columns', { columns: ['name', 'stage'] }, ['invalid_union']], ['unbound.overlay.list.aux', { type: 'grid', columns: ['name'], isDefault: true, order: 2, hidden: false }, ['invalid_union']], ['unbound.overlay.form.min', { type: 'simple' }, ['invalid_union']], - ['unbound.overlay.form.sections', { sections: [{ label: 'Main', fields: ['name'] }] }, ['invalid_union']], + // [ADR-0159 D7] `sections` is no view key the identity check knows since + // the form overlay was retired, so the body is refused before the union. + ['unbound.overlay.form.sections', { sections: [{ label: 'Main', fields: ['name'] }] }, ['custom']], ['unbound.overlay.badOperator', { filter: [{ field: 'name', operator: 'sorta_equals', value: 'x' }] }, ['invalid_union']], ['unbound.overlay.consoleSortId', { sort: [{ id: 'row-1', field: 'name', order: 'asc' }] }, ['invalid_union']], ['unbound.overlay.consoleFilterId', { filter: [{ id: 'row-1', field: 'name', operator: '=', value: 'x' }] }, ['invalid_union']], @@ -414,13 +425,33 @@ describe('the acceptance face of ViewMetadataSchema — frozen by the diagnostic } }); + // [ADR-0159 D7] The form rows are refused BY the retirement: the claimed + // member's first message is the prescription that names the `form` item. + it('the view-held form rows are refused by the D7 tombstones, with their prescription', () => { + const expected: Record = { + 'viewItem.form': /^`view\.viewKind: 'form'` was removed in @objectstack\/spec 19\.0\.0/, + 'container.form': /^`view\.form` was removed in @objectstack\/spec 19\.0\.0/, + 'container.formViews': /^`view\.formViews` was removed in @objectstack\/spec 19\.0\.0/, + 'put.hidden.formBound': /^`view\.viewKind: 'form'` was removed in @objectstack\/spec 19\.0\.0/, + }; + for (const [label, pattern] of Object.entries(expected)) { + const row = REFUSED.find(([l]) => l === label); + expect(row, label).toBeDefined(); + const d = diagnoseViewMetadata(row![1]); + expect(d.success, label).toBe(false); + if (d.success) continue; + expect(d.issues[0]!.message, label).toMatch(pattern); + expect(d.issues[0]!.message, label).toMatch(/`form` item/); + } + }); + // The JSON-Schema face the `/api/v1/meta/types/view` endpoint serves is // pinned in `view-metadata-schema.test.ts`; re-asserted here in the one // dimension this change could have moved — the member COUNT. - it('still emits an anyOf of exactly four members', () => { + it('still emits an anyOf of exactly three members (four before the form overlay was retired)', () => { const json = z.toJSONSchema(ViewMetadataSchema, { unrepresentable: 'any', io: 'input' }) as { anyOf?: unknown[]; }; - expect(json.anyOf).toHaveLength(4); + expect(json.anyOf).toHaveLength(3); }); }); diff --git a/packages/spec/src/ui/view-union-retirement-prescription.test.ts b/packages/spec/src/ui/view-union-retirement-prescription.test.ts index f117e15982c..47f50be0d9e 100644 --- a/packages/spec/src/ui/view-union-retirement-prescription.test.ts +++ b/packages/spec/src/ui/view-union-retirement-prescription.test.ts @@ -126,15 +126,18 @@ const BRANCH_PINS: ReadonlyArray> = { - // The ViewItem record's top-level `options` bag, on both arms: the record's - // per-kind blocks live under `config` (stage (iv) of #20051, Q3). + // The ViewItem record's top-level `options` bag: the record's per-kind + // blocks live under `config` (stage (iv) of #20051, Q3). [ADR-0159 D7] One + // arm since protocol 19 (the form arm, `|1`, was retired). 'viewItem.|0.options': /^A view item record carries no top-level `options` bag: .*Move each `options\.KIND` block to `config\.KIND`/, - 'viewItem.|1.options': /^A view item record carries no top-level `options` bag: .*Move each `options\.KIND` block to `config\.KIND`/, }; describe('§2 population — every non-catchall `never` leaf on this surface is a prescription', () => { diff --git a/packages/spec/src/ui/view-wire-unknown-key-refusal.test.ts b/packages/spec/src/ui/view-wire-unknown-key-refusal.test.ts index 23db5247e77..54aade174a3 100644 --- a/packages/spec/src/ui/view-wire-unknown-key-refusal.test.ts +++ b/packages/spec/src/ui/view-wire-unknown-key-refusal.test.ts @@ -13,6 +13,10 @@ * key, the member named), a retired key's prescription in both channels the * protocol has for it, the alias spellings the #20456 census found, and a * clean body of each shape still saving with what the console writes. + * + * [ADR-0159 D7] Since protocol 19 the flattened form overlay member is + * retired (a view is a list). Its clean body is kept, and pinned refused with + * the D7 prescription whatever else it carries. */ import { describe, expect, it } from 'vitest'; import { z } from 'zod'; @@ -23,7 +27,7 @@ import { ViewMetadataSchema, diagnoseViewMetadata, type ViewMetadataBranch } fro const DATA = { provider: 'object', object: 'crm_lead' } as const; /** One clean body per member the change closed, as the write path delivers it. */ -const CLEAN: Record<'viewItem' | 'listOverlay' | 'formOverlay', { body: Record; surface: string }> = { +const CLEAN: Record<'viewItem' | 'listOverlay', { body: Record; surface: string }> = { viewItem: { body: { name: 'crm_lead.mine', @@ -39,12 +43,12 @@ const CLEAN: Record<'viewItem' | 'listOverlay' | 'formOverlay', { body: Record; /** The claimed member's issues, read the way Studio and an MCP author get them. */ @@ -132,3 +136,16 @@ describe('the alias spellings the census found point at the declared key', () => expect(issues[0]!.message).toContain('Did you mean `id` → `name`?'); }); }); + +describe('[ADR-0159 D7] the retired form overlay body is refused, whatever it carries', () => { + it.each([ + ['clean', {}], + ['an unknown key', { zzz_junk_key: true }], + ['`objectName`', { objectName: 'crm_lead' }], + ['a top-level `id`', { id: 'crm_lead.mine' }], + ])('%s', (_label, extra) => { + const { branch, issues } = refusal({ ...FORM_OVERLAY_BODY, ...extra }); + expect(branch).toBe('listOverlay'); + expect(issues.some((i) => i.path[0] === 'viewKind' && FORM_KIND_RETIRED.test(i.message))).toBe(true); + }); +}); diff --git a/packages/spec/src/ui/view.test.ts b/packages/spec/src/ui/view.test.ts index 035299981a6..f3f6ae8c51e 100644 --- a/packages/spec/src/ui/view.test.ts +++ b/packages/spec/src/ui/view.test.ts @@ -42,11 +42,12 @@ import { type HttpRequest, defineView, defineMetadataForm, - ViewItemSchema, ViewMetadataSchema, VIEW_METADATA_MEMBERS, TreeConfigSchema, + FormSchema, } from './view.zod'; +import { RETIRED_VIEW_FORM_DOORS, expectRetiredViewFormDoorRefuses } from './retired-view-form-doors.testkit'; import { exportNamesOf, @@ -952,11 +953,14 @@ describe('FormViewSchema', () => { expect(issueAt(r, 'groups.0.visibleWhen')?.message).toMatch(/no predicate slot/); }); - it('covers the runtime-overlay door for step KEYS (the pane precedent\'s reach)', () => { - const r = VIEW_METADATA_MEMBERS.formOverlay.safeParse({ - type: 'wizard', + // [ADR-0159 D7] This case read the flattened form overlay member until + // protocol 19. That member left with the form arm; the door a form body is + // judged through now is the `form` item, and the step-key refusal reaches it. + it('covers the `form` item door for step KEYS (the pane precedent\'s reach)', () => { + const r = FormSchema.safeParse({ + name: 'crm_lead.wiz', object: 'crm_lead', - viewKind: 'form', + type: 'wizard', sections: [{ label: 'Step', collapsible: true, fields: ['name'] }], }); expect(r.success).toBe(false); @@ -1006,16 +1010,15 @@ describe('FormViewSchema', () => { expect(issueAt(r, 'sections')?.message).toMatch(/empty/); }); - it('the flattened runtime overlay stays EXEMPT — a partial patch is its contract, and the union corpus pins it accepted', () => { - // `{ type: 'wizard' }` beside the required binding, `sections` supplied - // by the shadowed base view — the `overlay.form.identity` shape the - // #7025 corpus pins as ACCEPTED. Moving that membership needs its own - // ruling (#7741's precedent); this pin keeps the D7 refusal off it. - expect(VIEW_METADATA_MEMBERS.formOverlay.safeParse({ - type: 'wizard', - object: 'crm_lead', - viewKind: 'form', - }).success).toBe(true); + // [ADR-0159 D7] Until protocol 19 the flattened form overlay was EXEMPT + // here: a partial patch was its contract. The overlay is refused whole + // since protocol 19, at `viewKind`, with the retirement prescription, + // never with the wizard's step refusal. + it('the flattened runtime overlay is refused whole at `viewKind`, never with the step refusal', () => { + const door = RETIRED_VIEW_FORM_DOORS.find((d) => d.name === 'flattened form overlay')!; + expectRetiredViewFormDoorRefuses(door, { type: 'wizard' }); + const r = door.parse({ type: 'wizard' }); + expect(JSON.stringify(r.error?.issues)).not.toMatch(/must declare its steps/); }); it('…but the ViewItem record door carries a COMPLETE view, so D7 fires there', () => { @@ -1101,22 +1104,27 @@ describe('FormViewSchema — the `groups` legacy alias folds onto `sections`', ( }); describe('every parse door inherits the fold (one declaration, not per-door)', () => { - it('ViewSchema.form', () => { - const parsed = ViewSchema.parse({ form: { type: 'simple', groups: [S('Account')] } }); - expect(has(parsed.form, 'groups')).toBe(false); - expect(parsed.form?.sections?.map((s) => s.label)).toEqual(['Account']); - }); + // [ADR-0159 D7] Until protocol 19 the fold was pinned at four view-held + // doors (`ViewSchema.form`, `.formViews.*`, the `form` record arm and the + // flattened form overlay) and at `defineView` and the container member. + // A view holds lists only since protocol 19: each of those doors refuses + // the WHOLE form at its own key, and the fold is pinned where a form body + // is judged now, the `form` item. + for (const door of RETIRED_VIEW_FORM_DOORS) { + it(`${door.name} refuses the form whole (protocol 19)`, () => { + expectRetiredViewFormDoorRefuses(door, { type: 'simple', groups: [S('Account')] }); + }); + } - it('ViewSchema.formViews.*', () => { - const parsed = ViewSchema.parse({ formViews: { edit: { type: 'simple', groups: [S('Account')] } } }); - expect(has(parsed.formViews?.edit, 'groups')).toBe(false); - expect(parsed.formViews?.edit?.sections?.map((s) => s.label)).toEqual(['Account']); + it('defineView (the authored container door) refuses `form` (protocol 19)', () => { + expect(() => defineView({ form: { type: 'simple', groups: [S('Account')] } } as never)) + .toThrow(/`view\.form` was removed in @objectstack\/spec 19\.0\.0/); }); - it('defineView (the authored container door)', () => { - const view = defineView({ form: { type: 'simple', groups: [S('Account')] } }); - expect(has(view.form, 'groups')).toBe(false); - expect(view.form?.sections?.map((s) => s.label)).toEqual(['Account']); + it('ViewMetadataSchema — the container member refuses `form` (protocol 19)', () => { + const r = ViewMetadataSchema.safeParse({ form: { type: 'simple', groups: [S('Account')] } }); + expect(r.success).toBe(false); + expect(JSON.stringify(r.error?.issues)).toContain('`view.form` was removed in @objectstack/spec 19.0.0'); }); it('defineMetadataForm (the metadata-admin form door)', () => { @@ -1125,30 +1133,9 @@ describe('FormViewSchema — the `groups` legacy alias folds onto `sections`', ( expect(form.sections?.map((s) => s.label)).toEqual(['Account']); }); - it('ViewItemSchema — the standalone `form` record arm', () => { - const parsed = ViewItemSchema.parse({ - name: 'crm_account.edit', - object: 'account', - viewKind: 'form', - config: { type: 'simple', groups: [S('Account')] }, - }); - const config = (parsed as { config: Record }).config; - expect(has(config, 'groups')).toBe(false); - expect((config.sections as Array<{ label?: string }>).map((s) => s.label)).toEqual(['Account']); - }); - - it('ViewMetadataSchema — the container member', () => { - const parsed = ViewMetadataSchema.parse({ form: { type: 'simple', groups: [S('Account')] } }) as { - form?: Record; - }; - expect(has(parsed.form, 'groups')).toBe(false); - expect((parsed.form?.sections as Array<{ label?: string }>).map((s) => s.label)).toEqual(['Account']); - }); - - it('ViewMetadataSchema — the FLATTENED form-overlay member (`.extend()` inherits the fold)', () => { - // [#7741] the overlay arm requires the `object` + `viewKind` binding. - const parsed = ViewMetadataSchema.parse({ - viewKind: 'form', + it('FormSchema — the `form` item, where a form body is judged since protocol 19', () => { + const parsed = FormSchema.parse({ + name: 'account.edit', object: 'account', type: 'simple', groups: [S('Account')], @@ -1159,6 +1146,31 @@ describe('FormViewSchema — the `groups` legacy alias folds onto `sections`', ( }); }); +/** + * [ADR-0159 D7] A container that still carries a view-held form, typed as the + * pre-19 container was, so the rewritten cases keep their authored fixtures. + */ +type OldShapeView = Omit & { form?: FormView; formViews?: Record }; + +/** + * [ADR-0159 D7] The major's answer to a pre-19 container: its lists parse on + * their own, and the whole container is refused at each view-held form key, + * with that key's D7 prescription. + */ +function expectListsParseAndFormsRefused(view: OldShapeView): void { + const { form, formViews, ...lists } = view; + expect(() => ViewSchema.parse(lists)).not.toThrow(); + const r = ViewSchema.safeParse(view); + expect(r.success).toBe(false); + for (const [key, present] of [['form', form], ['formViews', formViews]] as const) { + if (present === undefined) continue; + const issue = r.error?.issues.find((i) => i.path.length === 1 && i.path[0] === key); + expect(issue?.message, JSON.stringify(r.error?.issues)).toMatch( + new RegExp(`^\`view\\.${key}\` was removed in @objectstack/spec 19\\.0\\.0 \\(ADR-0159 D7\\)`), + ); + } +} + describe('ViewSchema', () => { it('should accept minimal view schema', () => { const view: View = {}; @@ -1166,8 +1178,9 @@ describe('ViewSchema', () => { expect(() => ViewSchema.parse(view)).not.toThrow(); }); - it('should accept view with default list and form', () => { - const view: View = { + // [ADR-0159 D7] Accepted whole until protocol 19; a view holds lists only now. + it('accepts the lists of view with default list and form and refuses its view-held form (protocol 19)', () => { + const view: OldShapeView = { list: { columns: ['name', 'status'], }, @@ -1178,7 +1191,7 @@ describe('ViewSchema', () => { }, }; - expect(() => ViewSchema.parse(view)).not.toThrow(); + expectListsParseAndFormsRefused(view); }); it('should accept view with named list views', () => { @@ -1207,8 +1220,9 @@ describe('ViewSchema', () => { expect(() => ViewSchema.parse(view)).not.toThrow(); }); - it('should accept view with named form views', () => { - const view: View = { + // [ADR-0159 D7] Accepted whole until protocol 19; a view holds lists only now. + it('accepts the lists of view with named form views and refuses its view-held form (protocol 19)', () => { + const view: OldShapeView = { form: { type: 'simple', sections: [{ fields: ['name'] }], @@ -1228,12 +1242,13 @@ describe('ViewSchema', () => { }, }; - expect(() => ViewSchema.parse(view)).not.toThrow(); + expectListsParseAndFormsRefused(view); }); describe('Real-World View Examples', () => { - it('should accept CRM opportunity views', () => { - const opportunityViews: View = { + // [ADR-0159 D7] Accepted whole until protocol 19; a view holds lists only now. + it('accepts the lists of CRM opportunity views and refuses its view-held form (protocol 19)', () => { + const opportunityViews: OldShapeView = { list: { type: 'grid', columns: ['name', 'account_name', 'amount', 'stage', 'close_date'], @@ -1288,11 +1303,12 @@ describe('ViewSchema', () => { }, }; - expect(() => ViewSchema.parse(opportunityViews)).not.toThrow(); + expectListsParseAndFormsRefused(opportunityViews); }); - it('should accept project task views with calendar and gantt', () => { - const taskViews: View = { + // [ADR-0159 D7] Accepted whole until protocol 19; a view holds lists only now. + it('accepts the lists of project task views with calendar and gantt and refuses its view-held form (protocol 19)', () => { + const taskViews: OldShapeView = { list: { columns: ['subject', 'status', 'priority', 'assigned_to', 'due_date'], }, @@ -1338,7 +1354,7 @@ describe('ViewSchema', () => { }, }; - expect(() => ViewSchema.parse(taskViews)).not.toThrow(); + expectListsParseAndFormsRefused(taskViews); }); }); }); @@ -2042,8 +2058,9 @@ describe('Enhanced FormViewSchema with Complex Fields', () => { }); describe('Real-World Enhanced View Examples', () => { - it('should accept CRM account view with enhanced columns', () => { - const accountViews: View = { + // [ADR-0159 D7] Accepted whole until protocol 19; a view holds lists only now. + it('accepts the lists of CRM account view with enhanced columns and refuses its view-held form (protocol 19)', () => { + const accountViews: OldShapeView = { list: { type: 'grid', columns: [ @@ -2094,11 +2111,12 @@ describe('Real-World Enhanced View Examples', () => { }, }; - expect(() => ViewSchema.parse(accountViews)).not.toThrow(); + expectListsParseAndFormsRefused(accountViews); }); - it('should accept project management view with all enhancements', () => { - const projectViews: View = { + // [ADR-0159 D7] Accepted whole until protocol 19; a view holds lists only now. + it('accepts the lists of project management view with all enhancements and refuses its view-held form (protocol 19)', () => { + const projectViews: OldShapeView = { list: { type: 'grid', columns: [ @@ -2157,7 +2175,7 @@ describe('Real-World Enhanced View Examples', () => { }, }; - expect(() => ViewSchema.parse(projectViews)).not.toThrow(); + expectListsParseAndFormsRefused(projectViews); }); }); @@ -3107,8 +3125,9 @@ describe('Airtable-style ListView enhancements', () => { expect(() => ListViewSchema.parse(airtableView)).not.toThrow(); }); - it('should accept complete Airtable-style View container with multiple view types', () => { - const views: View = { + // [ADR-0159 D7] Accepted whole until protocol 19; a view holds lists only now. + it('accepts the lists of complete Airtable-style View container with multiple view types and refuses its view-held form (protocol 19)', () => { + const views: OldShapeView = { list: { type: 'grid', columns: [ @@ -3168,7 +3187,7 @@ describe('Airtable-style ListView enhancements', () => { }, }; - expect(() => ViewSchema.parse(views)).not.toThrow(); + expectListsParseAndFormsRefused(views); }); }); @@ -3282,24 +3301,24 @@ describe('defineView', () => { expect(result.list?.columns).toEqual(['name', 'status']); }); - it('should return a parsed view with form config', () => { - const result = defineView({ + // [ADR-0159 D7] defineView returned a parsed `form` until protocol 19; it + // refuses the key now, with the D7 prescription naming `forms:`. + it('refuses a view with form config (protocol 19)', () => { + expect(() => defineView({ form: { type: 'simple', sections: [{ fields: ['name', 'email'] }], }, - }); - expect(result.form).toBeDefined(); - expect(result.form?.type).toBe('simple'); + } as never)).toThrow(/`view\.form` was removed in @objectstack\/spec 19\.0\.0 \(ADR-0159 D7\)/); }); - it('should return a parsed view with list and form', () => { - const result = defineView({ + it('refuses a view with list and form, and returns the list alone (protocol 19)', () => { + expect(() => defineView({ list: { type: 'kanban', columns: ['name'] }, form: { type: 'tabbed', sections: [{ fields: ['name'] }] }, - }); + } as never)).toThrow(/`view\.form` was removed/); + const result = defineView({ list: { type: 'kanban', columns: ['name'] } }); expect(result.list?.type).toBe('kanban'); - expect(result.form?.type).toBe('tabbed'); }); it('should accept named list views', () => { @@ -4583,7 +4602,11 @@ describe("ListViewSchema — the RETIRED `page` view type", () => { // match the list arm and have its `sections` stripped. The page mount was the // one view type that made `columns: []` look like a wart worth relaxing; it // is gone, and the property it would have broken is pinned here regardless. - it('still tells a flattened FORM overlay apart from a list overlay', () => { + // + // [ADR-0159 D7] Since protocol 19 the form overlay member is gone, so the + // property is: a flattened FORM body never matches the list arm with its + // `sections` stripped. It is refused whole, at `viewKind`. + it('still never lets a flattened FORM overlay pass as a list overlay', () => { const form = ViewMetadataSchema.safeParse({ name: 'crm_lead.edit', object: 'crm_lead', @@ -4591,8 +4614,8 @@ describe("ListViewSchema — the RETIRED `page` view type", () => { type: 'simple', sections: [{ label: 'Basics', fields: [{ field: 'name' }] }], }); - expect(form.success).toBe(true); - expect((form as { data: { sections?: unknown[] } }).data.sections).toHaveLength(1); + expect(form.success).toBe(false); + expect(JSON.stringify(form.error?.issues)).toContain("`view.viewKind: 'form'` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7)"); }); // `page` was never a visualization users could switch to, and it must not diff --git a/packages/spec/src/ui/view.zod.ts b/packages/spec/src/ui/view.zod.ts index 35866620614..861eba7f34f 100644 --- a/packages/spec/src/ui/view.zod.ts +++ b/packages/spec/src/ui/view.zod.ts @@ -19,7 +19,7 @@ * |:---|:---|:---|:---| * | standalone **ViewItem record** | a nested `config` | {@link ViewItemNameSchema} — `QUALIFIED_ITEM_NAME_PATTERN`, dot REQUIRED | **rejected**, located at `["name"]` | * | flattened runtime **overlay** | an inline view config; no `config`, no container slot | `z.string().optional()` — no grammar at all | accepted | - * | `defineView` **container** | a container slot (`list` / `form` / `listViews` / `formViews`) | `z.string().optional()` on {@link ViewSchema} — no grammar at all | accepted, and normally IS flat | + * | `defineView` **container** | a container slot (`list` / `listViews`; a body that names the retired `form` / `formViews` is read as a container too, and refused with their prescription) | `z.string().optional()` on {@link ViewSchema} — no grammar at all | accepted, and normally IS flat | * * The two permissive rows are deliberate, not gaps left to tighten later: * @@ -4927,21 +4927,19 @@ type WithFormSectionAlias = { sections?: unknown; groups?: unknown }; * ## Why `.overwrite()` and not `.transform()` (measured, #6926) * * Both fold identically at parse. `.transform()` returns a `ZodPipe`, and this - * schema is consumed as an OBJECT in two places in this file that a pipe breaks: - * {@link FormViewOverlayWireSchema} builds the flattened form-overlay union - * member with `FormViewSchema.extend(...)` (a pipe has no `.extend`), and - * {@link selectViewMetadataBranch} reads `._zod.def.shape.type` through - * `overlayTypeValues` — which a pipe answers with an EMPTY set, i.e. a silent - * mis-dispatch rather than an error. Splitting into an object schema plus a + * schema is consumed as an OBJECT in this file in ways a pipe breaks: the + * `form` item ({@link FormSchema}) is built from its shape, and the flattened + * form-overlay member (retired in protocol 19, ADR-0159 D7) was built with + * `FormViewSchema.extend(...)` (a pipe has no `.extend`). Splitting into an object schema plus a * piped export would require re-applying the fold on the overlay branch by * hand, which is the re-transcription that lets two doors disagree. * * `.overwrite()` is zod 4's "transform that does not change the type", which is * precisely what a `FormSectionSchema[]` → `FormSectionSchema[]` alias fold is. * It keeps the schema a `ZodObject`, and `.extend()` INHERITS the check, so the - * fold reaches every parse door with one declaration: `FormViewSchema` itself, - * `ViewSchema.form` / `.formViews.*`, both `ViewItemSchema` form arms, and the - * flattened `formOverlay` member of `ViewMetadataSchema`. The cost is that the + * fold reaches every parse door with one declaration: `FormViewSchema` itself + * and the `form` item built from it (the `view` doors that held a form body + * were retired in protocol 19, ADR-0159 D7). The cost is that the * INFERRED output type still declares `groups?` even though a parsed form never * carries it; the runtime contract is the enforced one. (Narrowing the exported * `FormViewParsed` by hand is not the fix — ADR-0122's gate requires it to read @@ -5583,9 +5581,11 @@ function checkFormViewBody(view: any, ctx: z.RefinementCtx): void { // accepted-but-ignored shape. ⛔ No "at least 2 steps" floor: a one-step // wizard is legal and renders. // - // Scoped to the doors where the body claims to be a COMPLETE authored form - // view (`ViewSchema.form` / `formViews`, the ViewItem config arms). The - // flattened runtime-overlay member (`FormViewOverlayWireSchema` = + // Scoped to the doors where the body claims to be a COMPLETE authored form: + // `FormViewSchema` itself and the `form` item built from its shape (until + // protocol 19 also `ViewSchema.form` / `formViews` and the ViewItem config + // arm, which now refuse a form whole, ADR-0159 D7). The + // flattened runtime-overlay member (the retired form overlay, built as // `.extend(flattenedViewOverlayFields()).strip()`) is exempt: an overlay is // a partial patch over a shadowed registry entry — `{ type: 'wizard' }` // beside the required `object`+`viewKind` binding, with `sections` supplied @@ -6047,6 +6047,60 @@ const VIEW_WRAP_REMEDY = 'Wrap it: `defineView({ list: { type, data, columns, … } })`, or name it — ' + '`defineView({ listViews: { my_view: { … } } })`.'; +/** + * [ADR-0159 D7, #37112] The three old form shapes, RETIRED in protocol 19: a + * form is a `form` item (`forms:`), never a member of a `view`. Each shape + * answers with its prescription: the container's `form` and `formViews` + * ({@link ViewSchema}, `retiredKey`) and the `form` member of + * {@link ViewKindSchema} (a `viewKind: 'form'` item or flattened body). + * + * The source conversion `view-forms-to-form-items` moves each form a source + * authors in `views[]` to `forms[]`; stored rows move only through the + * deployment's switch (`os migrate protocol --to 19 --apply`). A stored row the + * switch did not move is still read, never refused at the read: the kept + * withdrawal reader and rule 11's replacement check read its raw body + * (`projectViewForms`, ADR-0159 D6 rules 10 and 11), and no `view` or `form` + * read serves its form content. + * + * Declared ABOVE {@link ViewSchema} on purpose: under `OS_EAGER_SCHEMAS=1` + * every `lazySchema` factory runs at module init in file order, and a `const` + * below its first eager reader is a TDZ error. + */ +const VIEW_FORM_RETIRED = + '`view.form` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7) — a form is its own metadata type, and ' + + 'a `view` holds lists only. Move the form to the stack\'s `forms:` as a `form` item named `OBJECT.form` ' + + '(`defineForm({ name, object, sections, … })`, the body at the top level and bound with `object`); a ' + + 'record\'s New and Edit dialogs lay out by the object\'s `fieldGroups` and read no form, so a create or ' + + 'edit form that nothing else opens is deleted, not moved. ' + + 'Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand.'; + +const VIEW_FORM_VIEWS_RETIRED = + '`view.formViews` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7) — a form is its own metadata type, ' + + 'and a `view` holds lists only. Move each entry to the stack\'s `forms:` as a `form` item named ' + + '`OBJECT.KEY` (`defineForm({ name, object, sections, … })`, the body at the top level and bound with ' + + '`object`); the name stays the one it is served under, so a `type: \'form\'` action and a public link keep ' + + 'reaching it. ' + + 'Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand.'; + +const VIEW_KIND_FORM_RETIRED = + "`view.viewKind: 'form'` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7) — a form is its own metadata " + + 'type, and a view item is a list. Save the form as a `form` item (`forms:`, or `PUT /api/v1/meta/form/NAME`) ' + + 'with its `config` body at the top level and `object` naming the object it submits into; the name stays ' + + '`OBJECT.KEY`. ' + + 'Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand.'; + +/** + * The error a view item's discriminated union answers when no arm matches its + * `viewKind`: the retired `form` value gets its prescription + * ({@link VIEW_KIND_FORM_RETIRED}); any other value keeps zod's own message. + */ +function retiredFormViewKindError(issue: { input?: unknown }): string | undefined { + const input = issue.input; + return input !== null && typeof input === 'object' && (input as { viewKind?: unknown }).viewKind === 'form' + ? VIEW_KIND_FORM_RETIRED + : undefined; +} + /** * Master View Schema * Can define multiple named views. @@ -6058,7 +6112,6 @@ const VIEW_WRAP_REMEDY = * @example * { * list: { type: "grid", columns: ["name"] }, - * form: { type: "simple", fields: ["name"] }, * listViews: { * "all": { label: "All", filter: [] }, * "my": { label: "Mine", filter: [["owner", "=", "{current_user_id}"]] } @@ -6103,7 +6156,7 @@ export const ViewSchema = lazySchema(() => strictObject({ // entry is a claim about the schema, and claims need verifying like code. guidance: Object.fromEntries( ['type', 'columns', 'data', 'viewKind', 'filters', 'sort'] - .map((k) => [k, `\`${k}\` belongs to a single VIEW, not to the container. ${VIEW_WRAP_REMEDY} The container's own keys are \`list\`, \`form\`, \`listViews\`, \`formViews\`.`]), + .map((k) => [k, `\`${k}\` belongs to a single VIEW, not to the container. ${VIEW_WRAP_REMEDY} The container's own keys are \`list\` and \`listViews\`.`]), ), }, { // Item identity. The container is a registered metadata item, so the door @@ -6118,9 +6171,11 @@ export const ViewSchema = lazySchema(() => strictObject({ label: I18nLabelSchema.optional().describe('Human-readable label shown in metadata lists.'), object: z.string().optional().describe('Object this container binds to — how a stack-level `views: [...]` entry says which object its views belong to; read by `getViewsByObject()` / `GET /meta/view?object=`.'), list: ObjectListViewSchema.optional(), // Default list view (views mode — dropdown userFilters allowed, no tabs; ADR-0047) - form: FormViewSchema.optional(), // Default form view + // [ADR-0159 D7] RETIRED in protocol 19 — see {@link VIEW_FORM_RETIRED}. + form: retiredKey(VIEW_FORM_RETIRED), listViews: z.record(z.string(), ObjectListViewSchema).optional().describe('Additional named list views (views mode — dropdown userFilters allowed, no tabs; ADR-0047)'), - formViews: z.record(z.string(), FormViewSchema).optional().describe('Additional named form views'), + // [ADR-0159 D7] RETIRED in protocol 19 — see {@link VIEW_FORM_VIEWS_RETIRED}. + formViews: retiredKey(VIEW_FORM_VIEWS_RETIRED), /** * ADR-0010 §3.7 — Package-level protection envelope. Package * authors declare lock policy here, in a code package's source; @@ -6156,10 +6211,6 @@ export const ViewSchema = lazySchema(() => strictObject({ * data: { provider: 'object', object: 'task' }, * columns: ['subject', 'status', 'priority', 'due_date'], * }, - * form: { - * type: 'simple', - * sections: [{ label: 'Details', fields: [{ field: 'subject' }] }], - * }, * }); * ``` */ @@ -6167,13 +6218,11 @@ export function defineView(config: z.input): ViewParsed { const parsed = ViewSchema.parse(config); const viewCount = (parsed.list ? 1 : 0) + - (parsed.form ? 1 : 0) + - Object.keys(parsed.listViews ?? {}).length + - Object.keys(parsed.formViews ?? {}).length; + Object.keys(parsed.listViews ?? {}).length; if (viewCount === 0) { throw new Error( 'defineView: the container defines no views — nothing registers and no view appears in the Console. ' - + 'Declare at least one of `list`, `form`, `listViews`, `formViews`. ' + + 'Declare at least one of `list`, `listViews`. ' + 'If you passed a flat list view ({ name, label, type, columns, ... }), wrap it: ' + 'defineView({ list: { type, data, columns, ... } }).' ); @@ -6261,10 +6310,15 @@ const VIEW_SCOPE_RETIRED = { export const ViewScopeSchema = enumWithRetiredValues(['package', 'shared'], VIEW_SCOPE_RETIRED) .describe('View identity layer: package | shared.'); -/** Discriminator for the kind of view a {@link ViewItemSchema} carries. */ -export const ViewKindSchema = z - .enum(['list', 'form']) - .describe('Whether `config` is a ListView (list family) or a FormView.'); +/** + * Discriminator for the kind of view a {@link ViewItemSchema} carries: a list. + * + * [ADR-0159 D7] `form` was a member until protocol 19 and is RETIRED: it + * answers with {@link VIEW_KIND_FORM_RETIRED}'s prescription. A form is a + * `form` item. + */ +export const ViewKindSchema = enumWithRetiredValues(['list'], { form: VIEW_KIND_FORM_RETIRED }) + .describe('The family of the view: a list (`form` was retired in protocol 19 — a form is a `form` item).'); /** * [#20085] Prescriptions for the view item's two retired identity keys — @@ -6418,9 +6472,13 @@ function viewItemBaseShape() { * read off {@link VIEW_METADATA_MEMBERS}: `config: 42` type-checked while both * doors refuse it. */ -function viewItemArmShape(viewKind: K, config: C) { +function viewItemArmShape(viewKind: K, config: C) { return { - viewKind: z.literal(viewKind), + // [ADR-0159 D7] A list is the one kind; a retired `form` answers with its + // prescription rather than zod's bare literal mismatch. + viewKind: z.literal(viewKind, { + error: (issue) => (issue.input === 'form' ? VIEW_KIND_FORM_RETIRED : undefined), + }), config, ...viewItemBaseShape(), }; @@ -6437,7 +6495,7 @@ function viewItemArmShape(vie * carried a full copy of both config types (+170 KB of `view.zod.d.ts`, * measured); annotated, the file is smaller than when `config` was erased. */ -type ViewItemArmShape = ReturnType>; +type ViewItemArmShape = ReturnType>; /** * [#19920] {@link ViewItemArmShape} plus the wire arm's round-trip keys: the @@ -6445,7 +6503,7 @@ type ViewItemArmShape = Retur * object type rather than an intersection, so the annotation is IDENTICAL to * the type the spread infers, not merely assignable to it. */ -type ViewItemWireArmShape = { +type ViewItemWireArmShape = { [P in keyof (ViewItemArmShape & ReturnType)]: (ViewItemArmShape & ReturnType)[P]; }; @@ -6546,12 +6604,17 @@ const VIEW_ITEM_SURFACE = { */ export const ViewItemSchema: z.ZodDiscriminatedUnion<[ z.ZodObject, z.core.$strict>, - z.ZodObject, z.core.$strict>, ], 'viewKind'> = lazySchema(() => - z.discriminatedUnion('viewKind', [ - strictObject(VIEW_ITEM_SURFACE, viewItemArmShape('list', ListViewSchema.describe('List-family view configuration.'))), - strictObject(VIEW_ITEM_SURFACE, viewItemArmShape('form', FormViewSchema.describe('Form view configuration.'))), - ]), + // [ADR-0159 D7] One arm: a view item is a list. The `form` arm was retired in + // protocol 19 (a form is a `form` item), and `viewKind: 'form'` answers with + // its prescription ({@link VIEW_KIND_FORM_RETIRED}). The arm stays inside the + // discriminated union a view item always was, so every walker that reads it + // as a union of arms, and the published JSON Schema, keep their shape. + z.discriminatedUnion( + 'viewKind', + [strictObject(VIEW_ITEM_SURFACE, viewItemArmShape('list', ListViewSchema.describe('List-family view configuration.')))], + { error: retiredFormViewKindError }, + ), ); /** @@ -6654,7 +6717,7 @@ function viewItemWireFields() { columnState: retiredKey(VIEW_COLUMN_STATE_RETIRED), // [#20051] Pinned ABSENT, refused by name — see // {@link VIEW_ITEM_OPTIONS_REFUSED}. `z.never()` rather than the form - // overlay's `z.undefined()` ({@link FORM_OVERLAY_OPTIONS_REFUSED}): this + // overlay's former `z.undefined()` (retired in protocol 19): this // member is published on its own as `ViewItemWire.json`, and `never` has a // JSON Schema form (`not: {}`) where `undefined` has none. options: z.never({ error: () => VIEW_ITEM_OPTIONS_REFUSED }).optional() @@ -6697,12 +6760,6 @@ const LIST_OVERLAY_WIRE_SURFACE: StrictObjectOptions = { aliases: VIEW_WIRE_ALIASES, }; -/** [#26711] The unknown-key refusal of member 4, the flattened form overlay. */ -const FORM_OVERLAY_WIRE_SURFACE: StrictObjectOptions = { - surface: 'this inline form view', - history: VIEW_WIRE_HISTORY, - aliases: VIEW_WIRE_ALIASES, -}; /** * [#26711] Close a wire member's TOP level, with its own unknown-key refusal. @@ -6746,18 +6803,18 @@ function closeWireMember, z.core.$strict>, - z.ZodObject, z.core.$strict>, ], 'viewKind'> = lazySchema(() => - z.discriminatedUnion('viewKind', [ - strictObject(VIEW_ITEM_WIRE_SURFACE, { - ...viewItemArmShape('list', ListViewSchema.describe('List-family view configuration.')), - ...viewItemWireFields(), - }), - strictObject(VIEW_ITEM_WIRE_SURFACE, { - ...viewItemArmShape('form', FormViewSchema.describe('Form view configuration.')), - ...viewItemWireFields(), - }), - ]), + // [ADR-0159 D7] One arm, as {@link ViewItemSchema}: the `form` arm was retired. + z.discriminatedUnion( + 'viewKind', + [ + strictObject(VIEW_ITEM_WIRE_SURFACE, { + ...viewItemArmShape('list', ListViewSchema.describe('List-family view configuration.')), + ...viewItemWireFields(), + }), + ], + { error: retiredFormViewKindError }, + ), ); /** @@ -6786,9 +6843,9 @@ export function defineViewItem(config: z.input): ViewItem /** * [ADR-0159 D2] The prescription a `data` key on a `form` item answers with. A - * `form` item's object binding has ONE rung, its `object`; the four-rung - * resolution of an old-shape form ({@link anonymousFormObjectName}) lives only - * inside {@link projectViewForms}. A form bound to a JSON Schema + * `form` item's object binding has ONE rung, its `object`; the rung + * resolution of a stored old-shape form ({@link anonymousFormObjectName}) lives + * only inside {@link projectViewForms}. A form bound to a JSON Schema * (`data.provider: 'schema'`) is a Studio metadata form * ({@link defineMetadataForm}), not a `form` item. */ @@ -6925,14 +6982,17 @@ export function defineForm(config: z.input): FormParsed { // and a console personalization overlay (raw view config + inherited identity) // both parse to `{}` — silently "valid" while their `config` is never checked. // -// The three legitimate runtime shapes, each validated GENUINELY here: +// The three legitimate runtime shapes, each validated GENUINELY here. A view is +// a list since protocol 19 (ADR-0159 D7): the form family of each shape (a +// container's `form` / `formViews`, a `viewKind: 'form'` record or flattened +// body) is refused with its prescription, never validated as a view: // // 1. `defineView` aggregate **container** — at least one of -// `list`/`form`/`listViews`/`formViews`. An empty container is rejected +// `list`/`listViews`. An empty container is rejected // (it registers zero views; mirrors the {@link defineView} guard). // 2. Standalone **ViewItem record** — `{ viewKind, config, … }`; the nested -// `config` is validated against ListView/FormView. -// 3. **Flattened runtime overlay** — a raw ListView/FormView config at the +// `config` is validated against ListView. +// 3. **Flattened runtime overlay** — a raw ListView config at the // top level plus optional identity fields (`viewKind`/`object`/`label`, // inherited from the shadowed registry entry by `normalizeViewMetadata`; // see #2555). This is what a personalization PUT (column sort, inline @@ -7039,36 +7099,6 @@ const INLINE_VIEW_KIND_REQUIRED = + '(`{ name, object, viewKind, config: { … } }`), or make it a container. ' + VIEW_WRAP_REMEDY; -/** The other flattened overlay family — the `viewKind` the given arm does NOT judge. */ -function otherViewKind(kind: 'list' | 'form'): 'list' | 'form' { - return kind === 'list' ? 'form' : 'list'; -} - -/** - * [#20186] The refusal one flattened overlay member gives a body that names the - * OTHER family's `viewKind`. - * - * Each member judges exactly one `viewKind`, so a body is judged by the arm its - * `viewKind` names and by no other. Before this, both members shared one - * `list | form` enum, and a `viewKind: 'list'` body the list member refused - * (it carried no `columns`) was ACCEPTED by the form member, which `.strip()`s - * every list key unread: its `sort`, `searchableFields` and `timeline` were - * never judged, and the write door stored them as sent. - * - * Seen only by a consumer that parses one member directly - * (`VIEW_METADATA_MEMBERS.formOverlay.safeParse(…)`): through the union, the - * member the body does not claim is muted in favour of the one it does - * ({@link focusClaimedBranch}), so the author reads the claimed arm's own - * diagnosis. So the text says where the diagnosis is, not how to "fix" a - * `viewKind` that is correct. - */ -function overlayViewKindArmMismatch(kind: 'list' | 'form'): string { - const other = otherViewKind(kind); - return `This is the flattened ${kind.toUpperCase()} overlay member, which judges \`viewKind: "${kind}"\` only. ` - + `A \`viewKind: "${other}"\` body is judged by the ${other} overlay member ` - + `(\`VIEW_METADATA_MEMBERS.${other}Overlay\`), and that member's issues are its diagnosis.`; -} - /** * Identity + structural-guard fields layered onto the two "flattened runtime * overlay" members. The `config`/`list`/`form`/`listViews`/`formViews` guards @@ -7097,7 +7127,7 @@ function overlayViewKindArmMismatch(kind: 'list' | 'form'): string { * `viewKind: 'form'` type-checked, through the list member, as every union * type read off {@link VIEW_METADATA_MEMBERS}, while both doors refuse it. */ -function flattenedViewOverlayFields(kind: K) { +function flattenedViewOverlayFields(kind: K) { return { // No grammar, deliberately: the write path stamps this name rather than an // author writing it, so a flat overlay name is legal here while the SAME @@ -7115,7 +7145,8 @@ function flattenedViewOverlayFields(kind: K) { .enum([kind], { error: (issue) => { if (issue.input === undefined) return INLINE_VIEW_KIND_REQUIRED; - return issue.input === otherViewKind(kind) ? overlayViewKindArmMismatch(kind) : undefined; + // [ADR-0159 D7] The retired form family answers with its prescription. + return issue.input === 'form' ? VIEW_KIND_FORM_RETIRED : undefined; }, }) .describe( @@ -7326,8 +7357,8 @@ function assertViewIdentity(body: unknown, ctx: z.RefinementCtx): boolean { path: [], message: 'Not a `view` body: no recognized `view` key. Expected at least one of a container slot ' + - '(`list` / `form` / `listViews` / `formViews`), a ViewItem record (`viewKind` + `config`), ' + - 'or an inline view config (`type`, `columns`, `sections`, `filter`, …). ' + + '(`list` / `listViews`), a ViewItem record (`viewKind` + `config`), ' + + 'or an inline view config (`type`, `columns`, `filter`, `sort`, …). ' + (keys.length === 0 ? 'Received `{}`.' : 'Received ') + (unknown.length > 0 ? `unrecognized ${unknown.length === 1 ? 'key' : 'keys'} ${quote(unknown)}` : '') + (unknown.length > 0 && identity.length > 0 ? ', and ' : '') + @@ -7400,7 +7431,7 @@ function assertViewIdentity(body: unknown, ctx: z.RefinementCtx): boolean { const ViewContainerWireSchema = lazySchema(() => ViewSchema.refine(containerHasAView, { message: - 'A view container must define at least one of `list`, `form`, `listViews`, or `formViews`.', + 'A view container must define at least one of `list` or `listViews`.', }), ); @@ -7427,7 +7458,7 @@ const ViewContainerWireSchema = lazySchema(() => * source files. * * Declared on the list overlay member only. The form overlay pins the bag - * absent with its own text ({@link FORM_OVERLAY_OPTIONS_REFUSED}), and the + * absent with its own text (until it was retired in protocol 19), and the * view item record with {@link VIEW_ITEM_OPTIONS_REFUSED}. */ const LIST_OVERLAY_OPTIONS_REFUSED = @@ -7438,21 +7469,6 @@ const LIST_OVERLAY_OPTIONS_REFUSED = + '`filter`, …) are top-level keys of the view. Stored views are folded on read. ' + 'Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand.'; -/** - * [#20051] The refusal the flattened FORM overlay gives an `options` bag. - * - * `options` is list-view vocabulary, so a body carrying it is a list overlay — - * the same structural-guard reasoning as `config` / `list` / `form` pinned - * absent in {@link flattenedViewOverlayFields}. Without this pin the form - * member, which `.strip()`s and requires no list key, would ACCEPT a list - * overlay the list member refused over its `options` bag (a column-less, - * type-less personalization body reaches it), and the bag would be stored - * unjudged after all. - */ -const FORM_OVERLAY_OPTIONS_REFUSED = - 'A form view carries no `options` bag: `options.kanban`, `options.timeline` and the other per-kind blocks ' - + 'belong to a list view. Remove `options`, or save this body as a list view (`viewKind: "list"` with its `columns`).'; - /** [#20186] The list type a flattened list overlay that names none parses to. */ const LIST_OVERLAY_DEFAULT_TYPE = 'grid'; @@ -7466,15 +7482,6 @@ const LIST_OVERLAY_TYPE_NEEDS_COLUMNS = + 'it shadows (`sort`, `hiddenFields`, `rowHeight`, `inlineEdit`, …) sets no `type` and needs no `columns`: ' + 'remove `type` to save this body as a patch on the view it shadows.'; -/** - * [#20186] The refusal the flattened FORM overlay gives a field LIST under - * `columns`. - */ -const FORM_OVERLAY_COLUMNS_IS_A_COUNT = - 'On a form view `columns` is the NUMBER of body columns (an integer, 1 or more), not a list of fields, ' - + 'and this body says `viewKind: "form"`. A list of fields is a list view\'s `columns`: if this is a ' - + 'list view, set `viewKind: "list"`; if it is a form, list its fields in `sections: [{ fields: [...] }]`.'; - /** * [#20186] The two keys the flattened LIST overlay member declares differently * from the authoring {@link ListViewSchema}: `columns` optional, and `type` @@ -7595,25 +7602,6 @@ function applyListOverlayTypeDefault(view: T): T { return out as T; } -/** - * [#20186] `columns` on the flattened FORM overlay: the form's own count, - * refused with {@link FORM_OVERLAY_COLUMNS_IS_A_COUNT} when a field list - * arrives there. A clone of {@link FormViewSchema}'s own `columns` schema with - * an error map added, so its constraints are that schema's and cannot drift. - */ -function formOverlayColumnsField(): z.ZodOptional { - const optional = (FormViewSchema as unknown as { shape: { columns: z.ZodOptional } }).shape.columns; - const count = optional.unwrap(); - const withPrescription = count.clone({ - ...count._zod.def, - // The def's issue type is `never` for a number's own map; the runtime hands - // it the raw issue, whose `input` is what this reads. - error: (issue: { input?: unknown }) => (Array.isArray(issue.input) ? FORM_OVERLAY_COLUMNS_IS_A_COUNT : undefined), - }); - const description = optional.description; - return description ? withPrescription.optional().describe(description) : withPrescription.optional(); -} - /** * [#6391] Member 3 of {@link ViewMetadataSchema} — a flattened runtime LIST * overlay: an inline `ListView` config at the top level plus the optional @@ -7675,32 +7663,11 @@ const ListViewOverlayWireSchema = lazySchema(() => .overwrite(applyListOverlayTypeDefault), ); -/** - * [#6391] Member 4 of {@link ViewMetadataSchema} — a flattened runtime FORM - * overlay, published as `VIEW_METADATA_MEMBERS.formOverlay`. Same construction - * as {@link ListViewOverlayWireSchema}, and closed at the top level the same way - * (#26711). - * - * [#20051] `options` is pinned ABSENT here — see - * {@link FORM_OVERLAY_OPTIONS_REFUSED} for the fall-through it closes. - * - * [#20186] It judges `viewKind: 'form'` only. Before, it was the union's - * fall-through for every flattened body the list member refused — a - * column-less `viewKind: 'list'` patch among them — and it accepted those with - * their list keys stripped unread. Its `columns` (the form's body-column - * COUNT) now answers a field list with {@link FORM_OVERLAY_COLUMNS_IS_A_COUNT}. - */ -const FormViewOverlayWireSchema = lazySchema(() => - // `.safeExtend()`: this member now re-declares a key the form shape carries - // (`columns`, see {@link formOverlayColumnsField}), and {@link FormViewSchema} - // carries refinements, which `.extend()` refuses to combine with an overwrite. - // The two differ in that throw only — the refinements ride along either way. - closeWireMember(FormViewSchema.safeExtend({ - ...flattenedViewOverlayFields('form'), - options: z.undefined({ error: () => FORM_OVERLAY_OPTIONS_REFUSED }).optional(), - columns: formOverlayColumnsField(), - }), FORM_OVERLAY_WIRE_SURFACE), -); +// [ADR-0159 D7] Member 4, the flattened FORM overlay (`viewKind: 'form'` at the +// top level), was retired in protocol 19 with the `form` member of +// {@link ViewKindSchema}: a form is a `form` item. A flattened body that names +// `viewKind: 'form'` is judged by the list overlay member, which answers with +// {@link VIEW_KIND_FORM_RETIRED}'s prescription. /** * [#6391] The branch names of {@link ViewMetadataSchema}'s union, in @@ -7711,7 +7678,7 @@ const FormViewOverlayWireSchema = lazySchema(() => * branch by name via {@link VIEW_METADATA_MEMBERS}, or let * {@link diagnoseViewMetadata} name the branch for it. */ -export const VIEW_METADATA_BRANCHES = ['viewItem', 'container', 'listOverlay', 'formOverlay'] as const; +export const VIEW_METADATA_BRANCHES = ['viewItem', 'container', 'listOverlay'] as const; /** [#6391] One branch of {@link ViewMetadataSchema}'s union, by name. */ export type ViewMetadataBranch = (typeof VIEW_METADATA_BRANCHES)[number]; @@ -7738,10 +7705,9 @@ export const VIEW_METADATA_MEMBERS = { viewItem: ViewItemWireSchema as typeof ViewItemWireSchema, // 2. Non-empty defineView container. container: ViewContainerWireSchema, - // 3/4. Flattened runtime overlay — inline ListView / FormView config + identity, - // each judging only the `viewKind` it names (#20186). + // 3. Flattened runtime overlay — inline ListView config + identity (#20186). + // [ADR-0159 D7] Its form twin was retired in protocol 19. listOverlay: ListViewOverlayWireSchema, - formOverlay: FormViewOverlayWireSchema, } as const satisfies Record; /** @@ -7857,12 +7823,10 @@ export function selectViewMetadataBranch(body: unknown): ViewMetadataBranch | nu if (b.list !== undefined || b.form !== undefined || b.listViews !== undefined || b.formViews !== undefined) { return 'container'; } - if (b.viewKind === 'form') return 'formOverlay'; - if (b.viewKind === 'list') return 'listOverlay'; - if (typeof b.type === 'string') { - if (overlayTypeValues(FormViewSchema).has(b.type)) return 'formOverlay'; - if (overlayTypeValues(ListViewSchema).has(b.type)) return 'listOverlay'; - } + // [ADR-0159 D7] A flattened `viewKind: 'form'` body is claimed by the list + // overlay, whose `viewKind` answers it with the retirement's prescription. + if (b.viewKind === 'list' || b.viewKind === 'form') return 'listOverlay'; + if (typeof b.type === 'string' && overlayTypeValues(ListViewSchema).has(b.type)) return 'listOverlay'; return null; } @@ -8443,11 +8407,41 @@ export function expandViewContainerWithDiagnostics(object: string, container: an * Thin wrapper over {@link expandViewContainerWithDiagnostics} that discards the * collision diagnostics — the shape every runtime loader consumes. Behaviour is * unchanged: colliding names are still renamed so the registry key stays unique. + * + * [ADR-0159 D7] This is the RAW expansion: a stored old-shape container still + * expands its `form` and `formViews` members here, because the readers that + * must still see a stored old-shape form read through it: the stored-row + * holdings the replacement check and the stored-form ceremony read + * (ADR-0159 D6 rule 11, D7), and the projection the kept withdrawal reader + * reads (rule 10). What a `view` read SERVES is lists only: + * {@link expandServedViewContainer}. */ export function expandViewContainer(object: string, container: any): ExpandedViewItem[] { return expandViewContainerWithDiagnostics(object, container).items; } +/** A served view item: a list (ADR-0159 D7). */ +export type ServedViewItem = ExpandedViewItem & { viewKind: 'list' }; + +/** Whether an expanded or stored view item is one a `view` read serves: a list (ADR-0159 D7). */ +export function isServedViewItem(item: unknown): boolean { + return !!item && typeof item === 'object' && (item as { viewKind?: unknown }).viewKind !== 'form'; +} + +/** + * [ADR-0159 D7] The ViewItems a `view` read serves from an aggregated + * container: {@link expandViewContainer}, lists only. A view serves lists only + * since @objectstack/spec 19, so the form members of a stored old-shape + * container (`form`, `formViews`) are not served: they are dropped here, never + * refused, and the stored row is not rewritten. The form family is expanded + * after the list family, so dropping it renames no list. + */ +export function expandServedViewContainer(object: string, container: any): ServedViewItem[] { + return expandViewContainer(object, container).filter( + (item): item is ServedViewItem => item.viewKind === 'list', + ); +} + // ─────────────────────────────────────────────────────────────────────────── // [ADR-0159 D5] The projection of the three old form shapes into `form` items // ─────────────────────────────────────────────────────────────────────────── @@ -8463,7 +8457,7 @@ export const PROJECTED_FORM_SOURCE_KEY = '_formDefinedIn' as const; export interface ProjectedFormItem { /** The name the form is served under today: a stored item's own `name`, or the name `expandViewContainer` gives a container's form. */ name: string; - /** The object the form submits into, by today's four-rung resolution ({@link anonymousFormObjectName}). */ + /** The object the form submits into, by the old shapes' rung resolution ({@link anonymousFormObjectName}). */ object: string; /** The form body, unchanged, at the top level (ruled question 5), plus the item's own `label`, `overrides` and envelope. */ [key: string]: unknown; @@ -8538,7 +8532,7 @@ function projectedItem( * * - A projected item takes the name it is served under today (a stored item's * own `name`; for a container, the name {@link expandViewContainerWithDiagnostics} - * gives it), `object` from today's four-rung resolution + * gives it), `object` from the old shapes' rung resolution * ({@link anonymousFormObjectName}), and its body UNCHANGED, lifted to the top * level (ruled question 5). It is marked {@link PROJECTED_FORM_SOURCE_KEY}. * - ⛔ A projected item is never parsed by {@link FormSchema}: the authored-only @@ -8591,7 +8585,7 @@ export function projectViewForms(body: unknown, options: { object?: string } = { const config = (item.config ?? {}) as Record; const carrier: Record = { ...v, label: item.label }; // The doors read a container's forms as the items it expands to, so the - // four rungs are asked of the expanded item: the form's own + // rungs are asked of the expanded item: the form's own // `data.object`, else the object the container expands under. out.forms.push(projectedItem(item.name, anonymousFormObjectName({ object: item.object }, config) ?? item.object, config, carrier)); } @@ -8616,7 +8610,7 @@ export function projectViewForms(body: unknown, options: { object?: string } = { * [ADR-0159 D5] Every `form` item a set of `view` bodies carries, one per name * in scan order (the first body that projects a name keeps it): the source * half of the `form` read for one package's old shapes. A container comes - * before the items it expands, so the four-rung `object` is the container's. + * before the items it expands, so the resolved `object` is the container's. */ export function projectedFormsOf(bodies: ReadonlyArray): ProjectedFormItem[] { const seen = new Set(); diff --git a/packages/spec/src/ui/visibility-alias-keys-retirement.test.ts b/packages/spec/src/ui/visibility-alias-keys-retirement.test.ts index 6cc170e7513..90f273bcb3f 100644 --- a/packages/spec/src/ui/visibility-alias-keys-retirement.test.ts +++ b/packages/spec/src/ui/visibility-alias-keys-retirement.test.ts @@ -38,7 +38,7 @@ import { applyConversionsToStoredItem } from '../conversions/stored'; import { MIGRATIONS_BY_MAJOR, RETIRED_KEYS_BY_MAJOR } from '../migrations/registry'; import { defineStack } from '../stack.zod'; import { PageComponentSchema, PageSchema, type PageComponent } from './page.zod'; -import { FormFieldSchema, FormSectionSchema, ViewSchema, type FormFieldInput, type FormSection } from './view.zod'; +import { FormFieldSchema, FormSectionSchema, FormViewSchema, ViewSchema, type FormFieldInput, type FormSection } from './view.zod'; const VIEW_CONVERSION = 'view-visibleOn-to-visibleWhen'; const PAGE_CONVERSION = 'page-component-visibility-to-visibleWhen'; @@ -58,6 +58,9 @@ const legacyView = () => ({ }, }); +/** [ADR-0159 D7] The same form as a `form` item: how a form is authored since protocol 19. */ +const legacyForm = () => ({ name: 'crm_lead.form', object: 'crm_lead', ...legacyView().form }); + /** A page written before 18: one component gated through `visibility`. */ const legacyPage = () => ({ name: 'crm_home', @@ -103,7 +106,7 @@ describe('visibility alias keys retirement — the type channel', () => { }); describe('visibility alias keys retirement — the authoring funnel refuses, the stored seam converts', () => { - it('an authored legacy view reaches defineStack as written and is refused at both keys', () => { + it('[ADR-0159 D7] an authored legacy view-held form is refused at the container key since 19', () => { let refusal: unknown; try { defineStack({ views: [legacyView()] } as never); @@ -111,6 +114,19 @@ describe('visibility alias keys retirement — the authoring funnel refuses, the refusal = error; } expect(refusal).toMatchObject({ code: 'STACK_SCHEMA_INVALID', status: 422 }); + const issues = (refusal as { issues: Issue[] }).issues; + expect(issues.map((i) => i.path.join('.'))).toEqual(['views.0.form']); + expect(issues[0]!.message).toMatch(/^`view\.form` was removed in @objectstack\/spec 19\.0\.0/); + }); + + it('an authored legacy form reaches defineStack as written and is refused at both keys', () => { + let refusal: unknown; + try { + defineStack({ forms: [legacyForm()] } as never); + } catch (error) { + refusal = error; + } + expect(refusal).toMatchObject({ code: 'STACK_SCHEMA_INVALID', status: 422 }); const issues = flatten((refusal as { issues: Issue[] }).issues); const retired = issues.filter((i) => /visibleOn` was removed in @objectstack\/spec 18/.test(i.message)); // The section's own key, and the field's (nested inside the `fields` union). @@ -140,7 +156,7 @@ describe('visibility alias keys retirement — the authoring funnel refuses, the expect(stack).toEqual(input); }); - it('a STORED view row written with `visibleOn` loads, renamed, and parses', () => { + it('a STORED view row written with `visibleOn` loads, renamed, and its form body parses', () => { const notices: string[] = []; const row = applyConversionsToStoredItem('view', legacyView(), { onNotice: (n) => notices.push(`${n.conversionId} ${n.path}`) }); expect(notices).toEqual([ @@ -148,7 +164,10 @@ describe('visibility alias keys retirement — the authoring funnel refuses, the `${VIEW_CONVERSION} views[0].form.sections[0].fields[1].visibleWhen`, ]); expect(JSON.stringify(row)).not.toContain('visibleOn'); - expect(ViewSchema.safeParse(row).success).toBe(true); + // [ADR-0159 D7] The replayed row still holds a view-held form, which the 19 door refuses; + // its replayed form body is what the form view door accepts. + expect(ViewSchema.safeParse(row).success).toBe(false); + expect(FormViewSchema.safeParse((row as { form: unknown }).form).success).toBe(true); }); it('a STORED page row written with `visibility` loads, renamed, and parses', () => { diff --git a/packages/spec/variant-docs.json b/packages/spec/variant-docs.json index fdbd42c0278..41a77afb9bb 100644 --- a/packages/spec/variant-docs.json +++ b/packages/spec/variant-docs.json @@ -125,10 +125,10 @@ "reason": "Declared by a settings manifest that Setup/Studio ships and consumes; it is not part of the metadata a tenant authors. (Was labelled generated-reference-only, though its own reason already said so.)" }, { - "key": "viewKind:form|list", + "key": "viewKind:list", "label": "view item kind", "exempt": "not-authorable", - "reason": "Loader-derived. Authors write the `list` / `listViews` / `formViews` containers; the loader expands them and stamps `viewKind`. No author ever types it." + "reason": "Loader-derived. Authors write the `list` / `listViews` containers; the loader expands them and stamps `viewKind`. No author ever types it. `form` left the variant set in protocol 19 (ADR-0159 D7): a form is a `form` item, and a `viewKind: 'form'` body is refused with that prescription." }, { "key": "code:QUOTA_EXCEEDED|RATE_LIMIT_EXCEEDED|UNAUTHENTICATED", diff --git a/packages/spec/vitest.repo-tests.json b/packages/spec/vitest.repo-tests.json index 4f80758a464..5a38a99375a 100644 --- a/packages/spec/vitest.repo-tests.json +++ b/packages/spec/vitest.repo-tests.json @@ -88,6 +88,7 @@ "src/ui/page-header-show-star-retirement.test.ts", "src/ui/page-slots-tabs-retirement.test.ts", "src/ui/view-data-api-provider-retirement.test.ts", + "src/ui/view-form-slots-retirement.test.ts", "src/ui/view-item-owner-hidden-retirement.test.ts", "src/ui/view-list-filterable-fields-retirement.test.ts", "src/ui/view-list-tabs-retirement.test.ts", diff --git a/scripts/cross-package-test-inputs.mjs b/scripts/cross-package-test-inputs.mjs index fc34a400e03..229f67aec4b 100644 --- a/scripts/cross-package-test-inputs.mjs +++ b/scripts/cross-package-test-inputs.mjs @@ -254,6 +254,12 @@ export const CROSS_PACKAGE_TEST_INPUTS = { // per-extension rule, so it is the second witness on every row, and // src/conversions/conversion-conflict-channel-retirement.test.ts (the // conversion-conflict channel's retirement) the third, for the same reason. + // src/ui/view-form-slots-retirement.test.ts (the view container's form + // slots and the form view item, ADR-0159 D7) walks the same five roots + // and judges a narrower population, so it is a further witness on the + // rows of the extensions it reads and on no other: under `packages/` + // what a package teaches (Markdown and YAML), under `examples/` every + // non-code extension. 'packages/**/*.mts': [ 'packages/spec/src/system/compliance-families-retirement.test.ts', 'packages/spec/src/ui/view-data-api-provider-retirement.test.ts', @@ -291,26 +297,31 @@ export const CROSS_PACKAGE_TEST_INPUTS = { 'packages/spec/src/system/compliance-families-retirement.test.ts', 'packages/spec/src/ui/view-data-api-provider-retirement.test.ts', 'packages/spec/src/conversions/conversion-conflict-channel-retirement.test.ts', + 'packages/spec/src/ui/view-form-slots-retirement.test.ts', ], 'packages/**/*.mdx': [ 'packages/spec/src/system/compliance-families-retirement.test.ts', 'packages/spec/src/ui/view-data-api-provider-retirement.test.ts', 'packages/spec/src/conversions/conversion-conflict-channel-retirement.test.ts', + 'packages/spec/src/ui/view-form-slots-retirement.test.ts', ], 'packages/**/*.yaml': [ 'packages/spec/src/system/compliance-families-retirement.test.ts', 'packages/spec/src/ui/view-data-api-provider-retirement.test.ts', 'packages/spec/src/conversions/conversion-conflict-channel-retirement.test.ts', + 'packages/spec/src/ui/view-form-slots-retirement.test.ts', ], 'packages/**/*.yml': [ 'packages/spec/src/system/compliance-families-retirement.test.ts', 'packages/spec/src/ui/view-data-api-provider-retirement.test.ts', 'packages/spec/src/conversions/conversion-conflict-channel-retirement.test.ts', + 'packages/spec/src/ui/view-form-slots-retirement.test.ts', ], 'examples/**/*.json': [ 'packages/spec/src/system/compliance-families-retirement.test.ts', 'packages/spec/src/ui/view-data-api-provider-retirement.test.ts', 'packages/spec/src/conversions/conversion-conflict-channel-retirement.test.ts', + 'packages/spec/src/ui/view-form-slots-retirement.test.ts', // The template-manifest retirement's absence walk: every // `objectstack.manifest.json` under `packages/` and `examples/`. 'packages/spec/src/marketplace/template-manifest-inert-keys-retirement.test.ts', @@ -319,21 +330,25 @@ export const CROSS_PACKAGE_TEST_INPUTS = { 'packages/spec/src/system/compliance-families-retirement.test.ts', 'packages/spec/src/ui/view-data-api-provider-retirement.test.ts', 'packages/spec/src/conversions/conversion-conflict-channel-retirement.test.ts', + 'packages/spec/src/ui/view-form-slots-retirement.test.ts', ], 'examples/**/*.mdx': [ 'packages/spec/src/system/compliance-families-retirement.test.ts', 'packages/spec/src/ui/view-data-api-provider-retirement.test.ts', 'packages/spec/src/conversions/conversion-conflict-channel-retirement.test.ts', + 'packages/spec/src/ui/view-form-slots-retirement.test.ts', ], 'examples/**/*.yaml': [ 'packages/spec/src/system/compliance-families-retirement.test.ts', 'packages/spec/src/ui/view-data-api-provider-retirement.test.ts', 'packages/spec/src/conversions/conversion-conflict-channel-retirement.test.ts', + 'packages/spec/src/ui/view-form-slots-retirement.test.ts', ], 'examples/**/*.yml': [ 'packages/spec/src/system/compliance-families-retirement.test.ts', 'packages/spec/src/ui/view-data-api-provider-retirement.test.ts', 'packages/spec/src/conversions/conversion-conflict-channel-retirement.test.ts', + 'packages/spec/src/ui/view-form-slots-retirement.test.ts', ], }, },