From 8a3430afdd6ddb45e8dd3efdd648a2951665174f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 00:31:06 +0000 Subject: [PATCH 01/29] feat(spec)!: form is a metadata type of its own, and the form doors read a form over both types MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ADR-0159 card ②, everything past the rename (PR B of the card's cut): FormSchema derived from FormViewSchema by reference with defineForm and *.form.ts; the registry row, the stack's forms collection and the forms translation family; one projection of the three old view shapes; the effective form read resolved over both types; the form write's removal of the old-shape row; the address clash refusal (FORM_ADDRESS_TAKEN); the package-less list-at-a-form's-name refusal on save, publish and restore; the anonymous doors' two-type withdrawal layer with rule 7's closed links; the lint rules, the liveness ledger and the showcase form. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .changeset/37086-form-metadata-type.md | 33 + .../docs/references/api/automation-api.mdx | 3 +- content/docs/references/api/contract.mdx | 3 +- .../docs/references/api/error-code-ledger.mdx | 1 + content/docs/references/api/metadata.mdx | 5 +- .../references/api/package-api-assembled.mdx | 2 + content/docs/references/api/protocol.mdx | 1 + content/docs/references/index.mdx | 10 +- .../references/kernel/metadata-plugin.mdx | 6 +- .../docs/references/system/translation.mdx | 40 ++ content/docs/references/ui/view.mdx | 144 ++++- .../system.md | 2 +- .../ui.md | 12 +- examples/app-showcase/objectstack.config.ts | 3 + examples/app-showcase/src/coverage.ts | 2 + .../src/ui/forms/feedback.form.ts | 47 ++ examples/app-showcase/src/ui/forms/index.ts | 3 + packages/cli/src/utils/i18n-coverage.ts | 1 + packages/lint/src/authoring-rules.ts | 32 + packages/lint/src/i18n-walk.ts | 37 ++ .../lint/src/reference-integrity-suite.ts | 16 + packages/lint/src/rule-explanations.ts | 65 ++ packages/lint/src/runtime-gate.ts | 1 + packages/lint/src/validate-form-items.test.ts | 112 ++++ packages/lint/src/validate-form-items.ts | 212 +++++++ .../src/validate-public-form-file-fields.ts | 36 ++ packages/metadata-core/src/types.ts | 1 + packages/metadata-protocol/src/plugin.ts | 12 + .../src/protocol-authoring-gate.ts | 15 +- .../src/protocol-diff-delete-load.ts | 37 +- .../src/protocol-form-reads.ts | 343 ++++++++++ .../src/protocol-form-writes.ts | 259 ++++++++ .../src/protocol-history-and-publish.ts | 49 +- .../src/protocol-meta-item-reads.ts | 40 +- .../src/protocol-meta-list-reads.ts | 20 +- .../src/protocol-packaged-base-refusal.ts | 19 +- .../metadata-protocol/src/protocol-save.ts | 59 +- packages/metadata-protocol/src/protocol.ts | 19 + .../src/runtime-authoring-gate.ts | 29 +- packages/metadata/src/plugin.ts | 1 + packages/objectql/src/engine-top-level.ts | 2 +- packages/rest/src/form-routes.ts | 134 +++- packages/rest/src/meta-item-read-gate.ts | 30 + .../public-form-two-type-withdrawal.test.ts | 467 ++++++++++++++ packages/runtime/src/app-plugin.ts | 2 +- packages/spec/api-surface-signatures.json | 1 + packages/spec/api-surface/root.json | 1 + packages/spec/api-surface/system.json | 2 + packages/spec/api-surface/ui.json | 17 + packages/spec/authorable-defaults/ui.json | 1 + packages/spec/authorable-surface/system.json | 4 + packages/spec/authorable-surface/ui.json | 34 + packages/spec/declaration-map/ui.json | 2 + .../spec/dropped-refinements.baseline.json | 28 +- packages/spec/export-origins/root.json | 1 + packages/spec/export-origins/system.json | 2 + packages/spec/export-origins/ui.json | 17 + packages/spec/json-schema.manifest/ui.json | 1 + packages/spec/liveness/README.md | 3 +- packages/spec/liveness/form.json | 162 +++++ packages/spec/liveness/state-counts/form.md | 15 + .../spec/liveness/state-counts/translation.md | 2 +- packages/spec/liveness/translation.json | 40 ++ packages/spec/liveness/view.json | 2 +- .../spec/scripts/liveness/check-liveness.mts | 2 +- .../undrilled-containers.baseline.json | 5 + .../spec/src/api/error-code-ledger.zod.ts | 4 + packages/spec/src/index.ts | 2 +- .../spec/src/kernel/customization-package.ts | 3 + .../spec/src/kernel/metadata-plugin.zod.ts | 5 + .../spec/src/kernel/metadata-type-schemas.ts | 3 +- .../manifest-collection-spelling.ts | 1 + .../meta-spelling/meta-url-data.generated.ts | 2 + ...-form-and-packageless-list-at-form-name.ts | 35 ++ packages/spec/src/stack.zod.ts | 5 +- .../system/i18n-resolver.form-item.test.ts | 80 +++ packages/spec/src/system/i18n-resolver.ts | 94 +++ packages/spec/src/system/translation.zod.ts | 56 +- packages/spec/src/ui/anonymous-form-intake.ts | 22 + packages/spec/src/ui/form-intake-layer.ts | 110 ++++ packages/spec/src/ui/form-item.test.ts | 162 +++++ packages/spec/src/ui/index.ts | 2 + .../spec/src/ui/old-shape-form-withdrawals.ts | 32 + packages/spec/src/ui/view.zod.ts | 594 ++++++++++++++---- .../packages__rest__src__form-routes.ts.json | 5 +- ...rc__ui__old-shape-form-withdrawals.ts.json | 8 + 86 files changed, 3700 insertions(+), 234 deletions(-) create mode 100644 .changeset/37086-form-metadata-type.md create mode 100644 examples/app-showcase/src/ui/forms/feedback.form.ts create mode 100644 examples/app-showcase/src/ui/forms/index.ts create mode 100644 packages/lint/src/validate-form-items.test.ts create mode 100644 packages/lint/src/validate-form-items.ts create mode 100644 packages/metadata-protocol/src/protocol-form-reads.ts create mode 100644 packages/metadata-protocol/src/protocol-form-writes.ts create mode 100644 packages/rest/src/public-form-two-type-withdrawal.test.ts create mode 100644 packages/spec/liveness/form.json create mode 100644 packages/spec/liveness/state-counts/form.md create mode 100644 packages/spec/src/migrations/entries/semantic/18.form-type-define-form-and-packageless-list-at-form-name.ts create mode 100644 packages/spec/src/system/i18n-resolver.form-item.test.ts create mode 100644 packages/spec/src/ui/form-intake-layer.ts create mode 100644 packages/spec/src/ui/form-item.test.ts create mode 100644 packages/spec/src/ui/old-shape-form-withdrawals.ts create mode 100644 scripts/adr-anchors/packages__spec__src__ui__old-shape-form-withdrawals.ts.json diff --git a/.changeset/37086-form-metadata-type.md b/.changeset/37086-form-metadata-type.md new file mode 100644 index 00000000000..f3fb12b7d60 --- /dev/null +++ b/.changeset/37086-form-metadata-type.md @@ -0,0 +1,33 @@ +--- +'@objectstack/spec': minor +'@objectstack/metadata-protocol': minor +'@objectstack/rest': minor +'@objectstack/lint': minor +'@objectstack/metadata': minor +'@objectstack/metadata-core': minor +'@objectstack/objectql': minor +'@objectstack/runtime': minor +'@objectstack/cli': minor +--- + +feat(spec)!: `form` is a metadata type of its own — `defineForm`, `*.form.ts` and a stack's `forms:` — and the anonymous form doors read a form over both types (ADR-0159 card ②) + +Clause-②: yes (narrowing) +Metadata-protocol: narrowed + +ADR-0159 makes a public form a `form` item: `name` (`OBJECT.KEY`, the name it is served under), `object` (its one binding) and a form view's body at the top level, its keys taken from `FormViewSchema` by reference. A stack lists them under `forms:`, one per `*.form.ts` module built with `defineForm`. The three old `view` shapes that carry a form (a container's `form`, a `formViews` entry, a `viewKind: 'form'` item) keep loading and serving exactly as before: one projection reads them as `form` items, under the names they are served as today, and nothing an author wrote stops loading. + + + +**BREAKING** (the protocol is narrowed, and a published export changes meaning): + +- **The export.** `defineForm` on `@objectstack/spec` and `@objectstack/spec/ui` builds a `form` item. FROM: (since the previous change) no `defineForm`; before that, the Studio metadata-form helper. TO: `defineForm({ name: 'crm_lead.web_to_lead', object: 'crm_lead', sections, sharing })`. The fix for a Studio form: `defineMetadataForm`, as the rename's own entry says; the compiler names every call (a Studio body is refused by `FormSchema`: it has no `name` and `object`). +- **The refusal.** A package-less `view` write that would store a LIST at a name a read-only package authors as a `form` item is refused with `400 VALIDATION_ERROR`, naming the package — on the save, on the publish of a draft saved before the gate, and on a rollback or revert that restores such a body. Items and container expansions alike. Saves admitted today that it refuses: a list at a name several packages ship; a list at a name whose base has no pair; a re-save of a row the base's pair already holds; a container that overlays the package's own. The door that remains: save the list under another key, or into an app of the environment's own. It bites for a name only from the release in which a package authors it as a `form` item. + +What lands with the type: + +- `@objectstack/spec`: `FormSchema`, `defineForm`, the registry row (`*.form.ts|yml|json`, overlay-capable, no environment overlay), `form` in the customization package's listed types, the stack's `forms` collection, the `forms` translation family (`forms.NAME` first, the `_views.KEY` title and thank-you tails as the fallback, `_views.KEY.label` never read), the projection `projectViewForms`, the intake layer `formIntakeLayer` / `openFormAt`, and the error code `FORM_ADDRESS_TAKEN`. +- `@objectstack/metadata-protocol`: the effective `form` read resolves a form over both types in the one served-row order (a stored `view` row over a package's form keeps replacing it when the package moves to `forms:`); a `form` save, reset or delete at a package removes that package's old-shape row of the name in the same transaction (form content only — a list of the name is untouched); a `form` left open on a public address another form holds is refused with `409 FORM_ADDRESS_TAKEN`, naming both (a switched-off form that keeps its link still holds the address; a save that leaves the form closed is never refused); the override gate accepts a `form` override over a base that ships the form as an old shape; a stored body whose form content cannot be read is reported once at boot, at `error`, naming the row, the links it closes and the repair save. +- `@objectstack/rest`: `GET /forms/:slug` and its submit read candidates from the effective `form` read and judge withdrawal across `form` and `view`, effective and per-package, old shapes projected first — narrowing only, in both directions; a body that cannot be read closes the links it names. `/meta/form/NAME` refuses whom `/meta/view/NAME` refuses. `GET /meta/view` answers as before. +- `@objectstack/lint`: `form-public-address-taken` (gating), `form-consumer-less` (advisory, never for an `overrides` item), `form-object-outside-closure` / `form-object-unknown`; the i18n walk emits `forms.NAME.*` keys and no `_views` tail for a `form` item. No new advisory for an old shape. +- `@objectstack/metadata`, `@objectstack/metadata-core`, `@objectstack/objectql`, `@objectstack/runtime`, `@objectstack/cli`: the `forms` collection is loaded, typed, registered and counted for i18n coverage like every other. diff --git a/content/docs/references/api/automation-api.mdx b/content/docs/references/api/automation-api.mdx index fc99a77682c..5e280caa4a5 100644 --- a/content/docs/references/api/automation-api.mdx +++ b/content/docs/references/api/automation-api.mdx @@ -425,7 +425,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' \| … +380 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' \| … +381 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` @@ -615,6 +615,7 @@ const result = AutomationApiErrorCode.parse(data); * `FLOW_INPUT_SCHEMA_INVALID` * `FLOW_NO_START_NODE` * `FORBIDDEN` +* `FORM_ADDRESS_TAKEN` * `FORM_NOT_FOUND` * `FORM_RESOLVE_FAILED` * `HOOK_ABORTED` diff --git a/content/docs/references/api/contract.mdx b/content/docs/references/api/contract.mdx index 1660e81c3fc..1ef99c50701 100644 --- a/content/docs/references/api/contract.mdx +++ b/content/docs/references/api/contract.mdx @@ -28,7 +28,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' \| … +380 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' \| … +381 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`. | @@ -225,6 +225,7 @@ const result = ApiErrorSchema.parse(data); * `FLOW_INPUT_SCHEMA_INVALID` * `FLOW_NO_START_NODE` * `FORBIDDEN` +* `FORM_ADDRESS_TAKEN` * `FORM_NOT_FOUND` * `FORM_RESOLVE_FAILED` * `HOOK_ABORTED` diff --git a/content/docs/references/api/error-code-ledger.mdx b/content/docs/references/api/error-code-ledger.mdx index 317cc7145ee..ad80d36d0ab 100644 --- a/content/docs/references/api/error-code-ledger.mdx +++ b/content/docs/references/api/error-code-ledger.mdx @@ -392,6 +392,7 @@ const result = ErrorCode.parse(data); * `FLOW_INPUT_SCHEMA_INVALID` * `FLOW_NO_START_NODE` * `FORBIDDEN` +* `FORM_ADDRESS_TAKEN` * `FORM_NOT_FOUND` * `FORM_RESOLVE_FAILED` * `HOOK_ABORTED` diff --git a/content/docs/references/api/metadata.mdx b/content/docs/references/api/metadata.mdx index 1774d86847e..e6bf19d6629 100644 --- a/content/docs/references/api/metadata.mdx +++ b/content/docs/references/api/metadata.mdx @@ -642,7 +642,7 @@ Metadata query with filtering, sorting, and pagination | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **types** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| 'dataset' \| 'flow' \| 'job' \| 'datasource' \| 'external_catalog' \| 'translation' \| 'api' \| 'email_template' \| 'doc' \| 'book' \| 'permission' \| 'position' \| 'capability' \| 'sharing_rule' \| 'queue' \| 'assignment_rule' \| 'agent' \| 'tool' \| 'skill' \| 'ai_context'>[]` | optional | Filter by metadata types | +| **types** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'form' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| 'dataset' \| 'flow' \| 'job' \| 'datasource' \| 'external_catalog' \| 'translation' \| 'api' \| 'email_template' \| 'doc' \| 'book' \| 'permission' \| 'position' \| 'capability' \| 'sharing_rule' \| 'queue' \| 'assignment_rule' \| 'agent' \| 'tool' \| 'skill' \| 'ai_context'>[]` | optional | Filter by metadata types | | **namespaces** | `string[]` | optional | Filter by namespaces | | **packageId** | `string` | optional | Filter by owning package | | **search** | `string` | optional | Full-text search query | @@ -709,7 +709,7 @@ Metadata query with filtering, sorting, and pagination | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **type** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| 'dataset' \| … +19 more>` | ✅ | Metadata type | +| **type** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'form' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| … +20 more>` | ✅ | Metadata type | | **name** | `string` | ✅ | Item name (snake_case) | | **data** | `Record` | ✅ | Metadata payload | | **namespace** | `string` | optional | Optional namespace | @@ -724,6 +724,7 @@ Metadata query with filtering, sorting, and pagination * `mapping` * `picklist` * `view` +* `form` * `page` * `dashboard` * `app` diff --git a/content/docs/references/api/package-api-assembled.mdx b/content/docs/references/api/package-api-assembled.mdx index ae24a5dd680..b744b9b6612 100644 --- a/content/docs/references/api/package-api-assembled.mdx +++ b/content/docs/references/api/package-api-assembled.mdx @@ -118,6 +118,7 @@ Installed package row whose manifest is the assembled package body | **apps** | `{ name: string; label: string \| Record; description?: string \| Record; icon?: string; … }[]` | optional | Applications | | **views** | `{ name?: string; label?: string \| Record; object?: string; list?: object; … }[]` | optional | List Views | | **viewItems** | `never` | optional | [MACHINE-ASSEMBLED] Non-container view artifacts of a runtime-assembled manifest (standalone ViewItems, flattened overlays) — written by package export and artifact factories, refused in authored stack sources. | +| **forms** | `{ name: string; object: string; label?: string \| Record; type?: Enum<'simple' \| 'tabbed' \| 'wizard'>; … }[]` | optional | Data-entry forms, one object each (ADR-0159): `defineForm` items named `OBJECT.KEY` | | **pages** | `{ name: string; label: string \| Record; description?: string \| Record; icon?: string; … }[]` | optional | Custom Pages | | **dashboards** | `{ name: string; label: string \| Record; description?: string \| Record; header?: object; … }[]` | optional | Dashboards | | **reports** | `{ name: string; label: string \| Record; description?: string \| Record; type?: Enum<'tabular' \| 'summary' \| 'matrix' \| 'joined'>; … }[]` | optional | Analytics Reports | @@ -369,6 +370,7 @@ This schema accepts one of the following structures: | **apps** | `{ name: string; label: string \| Record; description?: string \| Record; icon?: string; … }[]` | optional | Applications | | **views** | `{ name?: string; label?: string \| Record; object?: string; list?: object; … }[]` | optional | List Views | | **viewItems** | `never` | optional | [MACHINE-ASSEMBLED] Non-container view artifacts of a runtime-assembled manifest (standalone ViewItems, flattened overlays) — written by package export and artifact factories, refused in authored stack sources. | +| **forms** | `{ name: string; object: string; label?: string \| Record; type?: Enum<'simple' \| 'tabbed' \| 'wizard'>; … }[]` | optional | Data-entry forms, one object each (ADR-0159): `defineForm` items named `OBJECT.KEY` | | **pages** | `{ name: string; label: string \| Record; description?: string \| Record; icon?: string; … }[]` | optional | Custom Pages | | **dashboards** | `{ name: string; label: string \| Record; description?: string \| Record; header?: object; … }[]` | optional | Dashboards | | **reports** | `{ name: string; label: string \| Record; description?: string \| Record; type?: Enum<'tabular' \| 'summary' \| 'matrix' \| 'joined'>; … }[]` | optional | Analytics Reports | diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index fe21995a428..4636c688135 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -1944,6 +1944,7 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **datasets** | `Record; measures?: Record }>` | optional | Analytics dataset translations keyed by dataset name | | **reports** | `Record }>` | optional | Report translations keyed by report name | | **pages** | `Record` | optional | Page translations keyed by page name | +| **forms** | `Record` | optional | Form translations keyed by form name (ADR-0159 D8) | | **flows** | `Record; … }>` | optional | Screen-flow translations keyed by flow name | | **hooks** | `Record; texts?: Record }>` | optional | Hook translations keyed by hook name | | **positions** | `Record` | optional | Position translations keyed by position name | diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 4b17f8699a1..b30730820d0 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1732 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1733 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -33,8 +33,8 @@ counts are sums of the rows they head. Regenerate with | [Shared Protocol](/docs/references/shared) | 10 | 31 | Primitives used across every protocol — identifiers, HTTP, expressions, error maps, enums. | | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | -| [UI Protocol](/docs/references/ui) | 16 | 184 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **221** | **1732** | 14 protocol modules | +| [UI Protocol](/docs/references/ui) | 16 | 185 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | +| **Total** | **221** | **1733** | 14 protocol modules | --- @@ -388,7 +388,7 @@ The runtime environment — logging, jobs, cache, metrics, notifications, i18n a ## UI Protocol -**Source:** `packages/spec/src/ui/` · **Import:** `@objectstack/spec/ui` · **16 pages, 184 schemas** +**Source:** `packages/spec/src/ui/` · **Import:** `@objectstack/spec/ui` · **16 pages, 185 schemas** Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. @@ -409,7 +409,7 @@ Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI lay | [`report.zod.ts`](/docs/references/ui/report) | `JoinedReportBlock`, `Report`, `ReportChart`, `ReportSort`, `ReportType` | | [`responsive.zod.ts`](/docs/references/ui/responsive) | `ResponsiveStyles`, `StyleMap` | | [`sharing.zod.ts`](/docs/references/ui/sharing) | `SharingConfig` | -| [`view.zod.ts`](/docs/references/ui/view) | `AddRecordConfig`, `AppearanceConfig`, `CalendarConfig`, `ColumnPrefix`, `ColumnSummary`, `ColumnSummaryConfig`, `EmptyState`, `FormButtonConfig`, `FormField`, `FormSection`, `FormSelectOption`, `FormView`, `GalleryConfig`, `GanttConfig`, `GanttQuickFilter`, `GroupingConfig`, `GroupingField`, `HttpMethodSubset`, `HttpRequest`, `KanbanConfig`, `KanbanLaneSummary`, `ListChartConfig`, `ListColumn`, `ListMapConfig`, `ListView`, `MetadataListCellType`, `MetadataListColumn`, `MetadataListView`, `NavigationConfig`, `NavigationMode`, `ObjectListView`, `ObjectUserFilters`, `PaginationConfig`, `RowColorConfig`, `RowHeight`, `SelectionConfig`, `TimelineConfig`, `TimesheetConfig`, `TreeConfig`, `UserActionsConfig`, `UserFilterField`, `UserFilters`, `View`, `ViewData`, `ViewFilterElement`, `ViewFilterOrGroup`, `ViewFilterRule`, `ViewItem`, `ViewItemName`, `ViewItemWire`, `ViewKind`, `ViewScope`, `ViewSharing`, `ViewTab`, `VisualizationType` | +| [`view.zod.ts`](/docs/references/ui/view) | `AddRecordConfig`, `AppearanceConfig`, `CalendarConfig`, `ColumnPrefix`, `ColumnSummary`, `ColumnSummaryConfig`, `EmptyState`, `Form`, `FormButtonConfig`, `FormField`, `FormSection`, `FormSelectOption`, `FormView`, `GalleryConfig`, `GanttConfig`, `GanttQuickFilter`, `GroupingConfig`, `GroupingField`, `HttpMethodSubset`, `HttpRequest`, `KanbanConfig`, `KanbanLaneSummary`, `ListChartConfig`, `ListColumn`, `ListMapConfig`, `ListView`, `MetadataListCellType`, `MetadataListColumn`, `MetadataListView`, `NavigationConfig`, `NavigationMode`, `ObjectListView`, `ObjectUserFilters`, `PaginationConfig`, `RowColorConfig`, `RowHeight`, `SelectionConfig`, `TimelineConfig`, `TimesheetConfig`, `TreeConfig`, `UserActionsConfig`, `UserFilterField`, `UserFilters`, `View`, `ViewData`, `ViewFilterElement`, `ViewFilterOrGroup`, `ViewFilterRule`, `ViewItem`, `ViewItemName`, `ViewItemWire`, `ViewKind`, `ViewScope`, `ViewSharing`, `ViewTab`, `VisualizationType` | --- diff --git a/content/docs/references/kernel/metadata-plugin.mdx b/content/docs/references/kernel/metadata-plugin.mdx index 379e844b085..8fc86c41bfd 100644 --- a/content/docs/references/kernel/metadata-plugin.mdx +++ b/content/docs/references/kernel/metadata-plugin.mdx @@ -179,7 +179,7 @@ const result = MetadataBulkResultSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **types** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| 'dataset' \| 'flow' \| 'job' \| 'datasource' \| 'external_catalog' \| 'translation' \| 'api' \| 'email_template' \| 'doc' \| 'book' \| 'permission' \| 'position' \| 'capability' \| 'sharing_rule' \| 'queue' \| 'assignment_rule' \| 'agent' \| 'tool' \| 'skill' \| 'ai_context'>[]` | optional | Filter by metadata types | +| **types** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'form' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| 'dataset' \| 'flow' \| 'job' \| 'datasource' \| 'external_catalog' \| 'translation' \| 'api' \| 'email_template' \| 'doc' \| 'book' \| 'permission' \| 'position' \| 'capability' \| 'sharing_rule' \| 'queue' \| 'assignment_rule' \| 'agent' \| 'tool' \| 'skill' \| 'ai_context'>[]` | optional | Filter by metadata types | | **namespaces** | `string[]` | optional | Filter by namespaces | | **packageId** | `string` | optional | Filter by owning package | | **search** | `string` | optional | Full-text search query | @@ -233,6 +233,7 @@ const result = MetadataBulkResultSchema.parse(data); * `mapping` * `picklist` * `view` +* `form` * `page` * `dashboard` * `app` @@ -268,7 +269,7 @@ const result = MetadataBulkResultSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **type** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| 'dataset' \| … +19 more>` | ✅ | Metadata type identifier | +| **type** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'form' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| … +20 more>` | ✅ | Metadata type identifier | | **label** | `string` | ✅ | Display label for the metadata type | | **description** | `string` | optional | Description of the metadata type | | **filePatterns** | `string[]` | ✅ | Glob patterns to discover files of this type | @@ -292,6 +293,7 @@ const result = MetadataBulkResultSchema.parse(data); * `mapping` * `picklist` * `view` +* `form` * `page` * `dashboard` * `app` diff --git a/content/docs/references/system/translation.mdx b/content/docs/references/system/translation.mdx index f432f6a5987..8b9fe046694 100644 --- a/content/docs/references/system/translation.mdx +++ b/content/docs/references/system/translation.mdx @@ -198,6 +198,7 @@ Platform translation data — the per-app groups plus the platform-only `setting | **datasets** | `Record; measures?: Record }>` | optional | Analytics dataset translations keyed by dataset name | | **reports** | `Record }>` | optional | Report translations keyed by report name | | **pages** | `Record` | optional | Page translations keyed by page name | +| **forms** | `Record` | optional | Form translations keyed by form name (ADR-0159 D8) | | **flows** | `Record; … }>` | optional | Screen-flow translations keyed by flow name | | **hooks** | `Record; texts?: Record }>` | optional | Hook translations keyed by hook name | | **positions** | `Record` | optional | Position translations keyed by position name | @@ -295,6 +296,15 @@ Translation data for a single object | **subtitle** | `string` | optional | Translated `page:header` subtitle | | **components** | `Record` | optional | Per-component copy keyed by component id (`PageComponentSchema.id`) | +### Nested Shape: `PlatformTranslationData.forms[string]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **label** | `string` | optional | Translated form label | +| **description** | `string` | optional | Translated form description | +| **title** | `string` | optional | Translated form heading (overlays the form's `title`) | +| **submitBehavior** | `{ title?: string; message?: string }` | optional | Translated thank-you panel copy — overlays the form's `submitBehavior` `title` / `message` when its `kind` is `'thank-you'` | + ### Nested Shape: `PlatformTranslationData.flows[string]` | Property | Type | Required | Description | @@ -390,6 +400,7 @@ Served translation data — the platform groups the browser reads, without the s | **datasets** | `Record; measures?: Record }>` | optional | Analytics dataset translations keyed by dataset name | | **reports** | `Record }>` | optional | Report translations keyed by report name | | **pages** | `Record` | optional | Page translations keyed by page name | +| **forms** | `Record` | optional | Form translations keyed by form name (ADR-0159 D8) | | **flows** | `Record; … }>` | optional | Screen-flow translations keyed by flow name | | **hooks** | `Record; texts?: Record }>` | optional | Hook translations keyed by hook name | | **positions** | `Record` | optional | Position translations keyed by position name | @@ -486,6 +497,15 @@ Translation data for a single object | **subtitle** | `string` | optional | Translated `page:header` subtitle | | **components** | `Record` | optional | Per-component copy keyed by component id (`PageComponentSchema.id`) | +### Nested Shape: `ServedTranslationData.forms[string]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **label** | `string` | optional | Translated form label | +| **description** | `string` | optional | Translated form description | +| **title** | `string` | optional | Translated form heading (overlays the form's `title`) | +| **submitBehavior** | `{ title?: string; message?: string }` | optional | Translated thank-you panel copy — overlays the form's `submitBehavior` `title` / `message` when its `kind` is `'thank-you'` | + ### Nested Shape: `ServedTranslationData.flows[string]` | Property | Type | Required | Description | @@ -644,6 +664,7 @@ Per-app translation data for objects, apps, and UI messages | **datasets** | `Record; measures?: Record }>` | optional | Analytics dataset translations keyed by dataset name | | **reports** | `Record }>` | optional | Report translations keyed by report name | | **pages** | `Record` | optional | Page translations keyed by page name | +| **forms** | `Record` | optional | Form translations keyed by form name (ADR-0159 D8) | | **flows** | `Record; … }>` | optional | Screen-flow translations keyed by flow name | | **hooks** | `Record; texts?: Record }>` | optional | Hook translations keyed by hook name | | **positions** | `Record` | optional | Position translations keyed by position name | @@ -740,6 +761,15 @@ Translation data for a single object | **subtitle** | `string` | optional | Translated `page:header` subtitle | | **components** | `Record` | optional | Per-component copy keyed by component id (`PageComponentSchema.id`) | +### Nested Shape: `TranslationData.forms[string]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **label** | `string` | optional | Translated form label | +| **description** | `string` | optional | Translated form description | +| **title** | `string` | optional | Translated form heading (overlays the form's `title`) | +| **submitBehavior** | `{ title?: string; message?: string }` | optional | Translated thank-you panel copy — overlays the form's `submitBehavior` `title` / `message` when its `kind` is `'thank-you'` | + ### Nested Shape: `TranslationData.flows[string]` | Property | Type | Required | Description | @@ -856,6 +886,7 @@ One locale of translations — the `translation` metadata type | **datasets** | `Record; measures?: Record }>` | optional | Analytics dataset translations keyed by dataset name | | **reports** | `Record }>` | optional | Report translations keyed by report name | | **pages** | `Record` | optional | Page translations keyed by page name | +| **forms** | `Record` | optional | Form translations keyed by form name (ADR-0159 D8) | | **flows** | `Record; … }>` | optional | Screen-flow translations keyed by flow name | | **hooks** | `Record; texts?: Record }>` | optional | Hook translations keyed by hook name | | **positions** | `Record` | optional | Position translations keyed by position name | @@ -963,6 +994,15 @@ Translation data for a single object | **subtitle** | `string` | optional | Translated `page:header` subtitle | | **components** | `Record` | optional | Per-component copy keyed by component id (`PageComponentSchema.id`) | +### Nested Shape: `TranslationItem.forms[string]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **label** | `string` | optional | Translated form label | +| **description** | `string` | optional | Translated form description | +| **title** | `string` | optional | Translated form heading (overlays the form's `title`) | +| **submitBehavior** | `{ title?: string; message?: string }` | optional | Translated thank-you panel copy — overlays the form's `submitBehavior` `title` / `message` when its `kind` is `'thank-you'` | + ### Nested Shape: `TranslationItem.flows[string]` | Property | Type | Required | Description | diff --git a/content/docs/references/ui/view.mdx b/content/docs/references/ui/view.mdx index b2559b43a93..8d6d9ba868c 100644 --- a/content/docs/references/ui/view.mdx +++ b/content/docs/references/ui/view.mdx @@ -59,8 +59,8 @@ nothing. The one item-name grammar itself lives in ## TypeScript Usage ```typescript -import { AddRecordConfigSchema, AppearanceConfigSchema, CalendarConfigSchema, ColumnPrefixSchema, ColumnSummarySchema, ColumnSummaryConfigSchema, EmptyStateSchema, FormButtonConfigSchema, FormFieldSchema, FormSectionSchema, FormSelectOptionSchema, FormViewSchema, GalleryConfigSchema, GanttConfigSchema, GanttQuickFilterSchema, GroupingConfigSchema, GroupingFieldSchema, HttpMethodSubsetSchema, HttpRequestSchema, KanbanConfigSchema, KanbanLaneSummarySchema, ListChartConfigSchema, ListColumnSchema, ListMapConfigSchema, ListViewSchema, MetadataListCellTypeSchema, MetadataListColumnSchema, MetadataListViewSchema, NavigationConfigSchema, NavigationModeSchema, ObjectListViewSchema, ObjectUserFiltersSchema, PaginationConfigSchema, RowColorConfigSchema, RowHeightSchema, SelectionConfigSchema, TimelineConfigSchema, TimesheetConfigSchema, TreeConfigSchema, UserActionsConfigSchema, UserFilterFieldSchema, UserFiltersSchema, ViewSchema, ViewDataSchema, ViewFilterElementSchema, ViewFilterOrGroupSchema, ViewFilterRuleSchema, ViewItemSchema, ViewItemNameSchema, ViewItemWireSchema, ViewKindSchema, ViewScopeSchema, ViewSharingSchema, ViewTabSchema, VisualizationTypeSchema } from '@objectstack/spec/ui'; -import type { AddRecordConfig, AppearanceConfig, CalendarConfig, ColumnPrefix, ColumnSummary, ColumnSummaryConfig, EmptyState, FormButtonConfig, FormField, FormSection, FormSelectOption, FormView, GalleryConfig, GanttConfig, GanttQuickFilter, GroupingConfig, HttpMethodSubset, HttpRequest, KanbanConfig, KanbanLaneSummary, ListChartConfig, ListColumn, ListMapConfig, ListView, MetadataListCellType, MetadataListColumn, MetadataListView, NavigationConfig, NavigationMode, PaginationConfig, RowColorConfig, RowHeight, SelectionConfig, TimelineConfig, TimesheetConfig, TreeConfig, UserActionsConfig, UserFilterField, UserFilters, View, ViewData, ViewFilterElement, ViewFilterOrGroup, ViewFilterRule, ViewItem, ViewItemName, ViewItemWire, ViewKind, ViewScope, ViewSharing, ViewTab, VisualizationType } from '@objectstack/spec/ui'; +import { AddRecordConfigSchema, AppearanceConfigSchema, CalendarConfigSchema, ColumnPrefixSchema, ColumnSummarySchema, ColumnSummaryConfigSchema, EmptyStateSchema, FormSchema, FormButtonConfigSchema, FormFieldSchema, FormSectionSchema, FormSelectOptionSchema, FormViewSchema, GalleryConfigSchema, GanttConfigSchema, GanttQuickFilterSchema, GroupingConfigSchema, GroupingFieldSchema, HttpMethodSubsetSchema, HttpRequestSchema, KanbanConfigSchema, KanbanLaneSummarySchema, ListChartConfigSchema, ListColumnSchema, ListMapConfigSchema, ListViewSchema, MetadataListCellTypeSchema, MetadataListColumnSchema, MetadataListViewSchema, NavigationConfigSchema, NavigationModeSchema, ObjectListViewSchema, ObjectUserFiltersSchema, PaginationConfigSchema, RowColorConfigSchema, RowHeightSchema, SelectionConfigSchema, TimelineConfigSchema, TimesheetConfigSchema, TreeConfigSchema, UserActionsConfigSchema, UserFilterFieldSchema, UserFiltersSchema, ViewSchema, ViewDataSchema, ViewFilterElementSchema, ViewFilterOrGroupSchema, ViewFilterRuleSchema, ViewItemSchema, ViewItemNameSchema, ViewItemWireSchema, ViewKindSchema, ViewScopeSchema, ViewSharingSchema, ViewTabSchema, VisualizationTypeSchema } from '@objectstack/spec/ui'; +import type { AddRecordConfig, AppearanceConfig, CalendarConfig, ColumnPrefix, ColumnSummary, ColumnSummaryConfig, EmptyState, Form, FormButtonConfig, FormField, FormSection, FormSelectOption, FormView, GalleryConfig, GanttConfig, GanttQuickFilter, GroupingConfig, HttpMethodSubset, HttpRequest, KanbanConfig, KanbanLaneSummary, ListChartConfig, ListColumn, ListMapConfig, ListView, MetadataListCellType, MetadataListColumn, MetadataListView, NavigationConfig, NavigationMode, PaginationConfig, RowColorConfig, RowHeight, SelectionConfig, TimelineConfig, TimesheetConfig, TreeConfig, UserActionsConfig, UserFilterField, UserFilters, View, ViewData, ViewFilterElement, ViewFilterOrGroup, ViewFilterRule, ViewItem, ViewItemName, ViewItemWire, ViewKind, ViewScope, ViewSharing, ViewTab, VisualizationType } from '@objectstack/spec/ui'; // Validate data const result = AddRecordConfigSchema.parse(data); @@ -184,6 +184,146 @@ Column footer summary configuration | **url** | `string` | ✅ | Where the link goes — a target a `type: 'url'` action opens: an in-app path that starts with `/` or `./` (such as `/docs/connect`), or an address that opens with `http://`, `https://` or `mailto:`. Any other scheme, a protocol-relative `//host`, a bare relative path and a tab, line feed or carriage return are refused at parse; a template that opens with `${…}`, such as `${ctx.origin}/docs`, is judged when it is clicked, after interpolation. | +--- + +## Form + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **name** | `string` | ✅ | The form's name, `OBJECT.KEY` (ADR-0159 D3): the name it is served under, the target of an action of `type: 'form'`, and the key a declared override names. The part before the last segment is the form's `object`. | +| **object** | `string` | ✅ | The object the form submits into — its one binding (ADR-0159 D2). It must name an object the package can reference. | +| **label** | `string \| Record` | optional | The form's name in lists (Setup, Studio). When absent a surface shows `title`, then the name. | +| **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** | `Enum<'sm' \| 'default' \| 'lg' \| 'xl' \| 'full'>` | optional | Size bucket of the dialog a caller opens this form in: the console's New / Edit dialog, or the modal container of the React `ObjectForm` block (formType 'modal') | +| **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;). | +| **protection** | `{ lock: Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>; reason: string; docsUrl?: string }` | optional | Package author protection block — lock policy for this form. | +| **_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: `Form.sections[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **name** | `string` | optional | Stable section identifier for i18n lookup (snake_case) | +| **label** | `string \| Record` | optional | Display label — the default-language string, or an inline locale map (`{ en, "zh-CN" }`) resolved at render time | +| **description** | `string` | optional | Optional description rendered under the section header. | +| **collapsible** | `boolean` | optional (default: `false`) | Whether the section renders a disclosure control, so a reader can close it and open it again. Default `false`: a section declaring neither collapse key is always open and shows no control. ⚠️ `collapsed: true` IMPLIES this key — an explicit `collapsible: false` beside it does NOT take the control away. The renderer resolves that from the DECLARATION; parse never rewrites the pair, so a parsed section still reports the `false` that was authored. Only `true` is refused on a wizard step and beside `group`; `false` is accepted in both, because it declares exactly what those surfaces already deliver. | +| **collapsed** | `boolean` | optional (default: `false`) | Whether the section starts closed. Default `false`. ⚠️ `collapsed: true` IMPLIES `collapsible` and is sufficient ON ITS OWN — a section that starts closed always carries the disclosure control that reopens it, and it outranks an explicit `collapsible: false`, so writing `collapsed: true` alone is a correct way to say "collapsed by default". The implication is a renderer rule, never a parse-time rewrite: `{ collapsed: true }` still parses to `collapsible: false, collapsed: true`, so the parsed `collapsible` must never be read as "a control renders". Only `true` is refused on a wizard step (steps do not collapse) and beside `group`, whose field group declares the pair. | +| **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Visibility predicate (CEL) — section shown only when TRUE. Root: `record` (+ `previous`, `parent`) in runtime forms, or `data` in metadata forms. `current_user` (and the ADR-0068 aliases `user` / `ctx.user` / `os.user`) resolves here too — CLIENT-SIDE only: nothing server-side evaluates a form-view section `visibleWhen`, so a role test here hides the controls and protects no data (declare permission-set field-level security for that), and on the public `/f/:slug` route no host publishes a scope, so the root is unbound and the predicate faults open. No `features.*` on ANY form-view predicate — refused at parse: unbound on the standalone form routes, where the predicate would fault open. | +| **visibleOn** | `never` | optional | [REMOVED] `view.form.sections[].visibleOn` was removed in @objectstack/spec 18 (ADR-0089 D2) — it was the form view's deprecated spelling of a section's conditional-visibility predicate, which the parse folded into `visibleWhen` until this release. Use `visibleWhen`. Rename the key; the value (a CEL predicate, which hides the whole section when false) is unchanged. Where a section writes both, `visibleWhen` is the one that was in effect: delete `visibleOn`. | +| **columns** | `Enum<'1' \| '2' \| '3' \| '4'> \| 1 \| 2 \| 3 \| 4` | optional | Fields per row, 1–4 ('1'–'4' parse to the number). Declared: the author's ceiling — at most that many per row where the container is wide enough; a renderer collapses it on narrow containers. Undeclared: the renderer's choice by available width — the parse adds no default, so declare `columns: 1` to keep a section single-column. | +| **pane** | `never` | optional | [REMOVED] `view.form.sections[].pane` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it placed a section in one 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: a `tabbed` form gives each section its own tab, and a `simple` form stacks them. 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. | +| **group** | `string` | optional | Field group key (snake_case) whose members and presentation this section inherits, from the bound object's `fieldGroups` (ADR-0085 §5 `deriveFieldGroupLayout`). Mutually exclusive with `fields`, and with every key the group itself declares (`name`, `label`, `description`, `collapsible`, `collapsed`, `visibleWhen`). Not valid on a wizard step. Must name a declared group — checked by reference diagnostics. | +| **fields** | `(string \| { field: string; type?: Enum<'text' \| 'textarea' \| 'email' \| 'url' \| 'phone' \| 'password' \| 'secret' \| …>; options?: object[]; reference?: string; … })[]` | optional | | + +### Nested Shape: `Form.groups[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **name** | `string` | optional | Stable section identifier for i18n lookup (snake_case) | +| **label** | `string \| Record` | optional | Display label — the default-language string, or an inline locale map (`{ en, "zh-CN" }`) resolved at render time | +| **description** | `string` | optional | Optional description rendered under the section header. | +| **collapsible** | `boolean` | optional (default: `false`) | Whether the section renders a disclosure control, so a reader can close it and open it again. Default `false`: a section declaring neither collapse key is always open and shows no control. ⚠️ `collapsed: true` IMPLIES this key — an explicit `collapsible: false` beside it does NOT take the control away. The renderer resolves that from the DECLARATION; parse never rewrites the pair, so a parsed section still reports the `false` that was authored. Only `true` is refused on a wizard step and beside `group`; `false` is accepted in both, because it declares exactly what those surfaces already deliver. | +| **collapsed** | `boolean` | optional (default: `false`) | Whether the section starts closed. Default `false`. ⚠️ `collapsed: true` IMPLIES `collapsible` and is sufficient ON ITS OWN — a section that starts closed always carries the disclosure control that reopens it, and it outranks an explicit `collapsible: false`, so writing `collapsed: true` alone is a correct way to say "collapsed by default". The implication is a renderer rule, never a parse-time rewrite: `{ collapsed: true }` still parses to `collapsible: false, collapsed: true`, so the parsed `collapsible` must never be read as "a control renders". Only `true` is refused on a wizard step (steps do not collapse) and beside `group`, whose field group declares the pair. | +| **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Visibility predicate (CEL) — section shown only when TRUE. Root: `record` (+ `previous`, `parent`) in runtime forms, or `data` in metadata forms. `current_user` (and the ADR-0068 aliases `user` / `ctx.user` / `os.user`) resolves here too — CLIENT-SIDE only: nothing server-side evaluates a form-view section `visibleWhen`, so a role test here hides the controls and protects no data (declare permission-set field-level security for that), and on the public `/f/:slug` route no host publishes a scope, so the root is unbound and the predicate faults open. No `features.*` on ANY form-view predicate — refused at parse: unbound on the standalone form routes, where the predicate would fault open. | +| **visibleOn** | `never` | optional | [REMOVED] `view.form.sections[].visibleOn` was removed in @objectstack/spec 18 (ADR-0089 D2) — it was the form view's deprecated spelling of a section's conditional-visibility predicate, which the parse folded into `visibleWhen` until this release. Use `visibleWhen`. Rename the key; the value (a CEL predicate, which hides the whole section when false) is unchanged. Where a section writes both, `visibleWhen` is the one that was in effect: delete `visibleOn`. | +| **columns** | `Enum<'1' \| '2' \| '3' \| '4'> \| 1 \| 2 \| 3 \| 4` | optional | Fields per row, 1–4 ('1'–'4' parse to the number). Declared: the author's ceiling — at most that many per row where the container is wide enough; a renderer collapses it on narrow containers. Undeclared: the renderer's choice by available width — the parse adds no default, so declare `columns: 1` to keep a section single-column. | +| **pane** | `never` | optional | [REMOVED] `view.form.sections[].pane` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it placed a section in one 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: a `tabbed` form gives each section its own tab, and a `simple` form stacks them. 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. | +| **group** | `string` | optional | Field group key (snake_case) whose members and presentation this section inherits, from the bound object's `fieldGroups` (ADR-0085 §5 `deriveFieldGroupLayout`). Mutually exclusive with `fields`, and with every key the group itself declares (`name`, `label`, `description`, `collapsible`, `collapsed`, `visibleWhen`). Not valid on a wizard step. Must name a declared group — checked by reference diagnostics. | +| **fields** | `(string \| { field: string; type?: Enum<'text' \| 'textarea' \| 'email' \| 'url' \| 'phone' \| 'password' \| 'secret' \| …>; options?: object[]; reference?: string; … })[]` | optional | | + +### Nested Shape: `Form.subforms[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **childObject** | `string` | ✅ | Child object whose records are entered inline | +| **relationshipField** | `string` | optional | FK on the child pointing back to the parent (auto-detected when omitted) | +| **columns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| …>; width?: number; … }[]` | optional | Editable grid columns (derived from the child object when omitted). Each entry is the strict, name-keyed inline grid column a relationship field's `inlineColumns` takes (`{ name, label?, type?, … }` — objectui GridColumn); identity-only entries (`{ name }`) hydrate everything else from the child object's fields. Unknown keys and the retired `field` spelling are refused at parse. | +| **amountField** | `string` | optional | Numeric child column summed for the running total | +| **totalField** | `string` | optional | Parent field to receive the rolled-up sum | +| **title** | `string` | optional | Section title | +| **addLabel** | `string` | optional | Add-row button label | +| **minRows** | `number` | optional | | +| **maxRows** | `number` | optional | | + +### Nested Shape: `Form.sharing` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **enabled** | `boolean` | optional (default: `false`) | Enable public sharing | +| **publicLink** | `string` | optional | Public slug of the form, chosen by the author: not a URL, and never generated. `/forms/x`, `forms/x` and `x` name one slug, `x`. It is served to anonymous visitors only while `enabled` and `allowAnonymous` are both true: the REST form door answers `GET /api/v1/forms/:slug` (default API base), and a host that serves the console shows the form at `/_console/f/:slug` and redirects `/forms/:slug` there, query string carried. | +| **password** | `string` | optional | Password required to access shared link | +| **allowedDomains** | `string[]` | optional | Restrict access to specific email domains (e.g. ["example.com"]) | +| **expiresAt** | `string` | optional | Expiration date/time in ISO 8601 format | +| **allowAnonymous** | `boolean` | optional (default: `false`) | Allow access without authentication | + +### Nested Shape: `Form.submitBehavior[kind='thank-you']` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **kind** | `'thank-you'` | ✅ | | +| **title** | `string` | optional | Heading of the confirmation panel. May name a field of the submitted record as `{{record.field_name}}`, and only a field the engine generates on insert (an `autonumber` field, e.g. a case number): a hook-derived value never reaches an anonymous visitor. | +| **message** | `string` | optional | Body of the confirmation panel. May name a field of the submitted record as `{{record.field_name}}`, and only a field the engine generates on insert (an `autonumber` field, e.g. a case number): a hook-derived value never reaches an anonymous visitor. | + +### Nested Shape: `Form.submitBehavior[kind='redirect']` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **kind** | `'redirect'` | ✅ | | +| **url** | `string` | ✅ | Where the browser goes after a successful submit. (1) RELATIVE paths only — it must start with `/`, and absolute or protocol-relative URLs are refused, which is what closes the open-redirect face; (2) interpolation ONLY from declared record fields, spelled `{{record.field_name}}`, and every interpolated value is URL-escaped when the redirect is built; (3) a verbatim redirect on the resolved relative path is the intended consumption. To send the browser OUT of the app, use an app navigation item (`{ type: 'url', url }`) instead. | +| **delayMs** | `integer` | optional | | + +### Nested Shape: `Form.buttons` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **submit** | `{ show?: boolean; label?: string \| Record }` | optional | Submit button | +| **cancel** | `{ show?: boolean; label?: string \| Record }` | optional | Cancel button | +| **reset** | `never` | optional | [REMOVED] `view.form.buttons.reset` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form ever drew a reset button, and its label was never read. Delete the key: a form has `submit` and `cancel` buttons only, and Cancel leaves the form without saving. `reset.show: true` used to clear the form after each save (the ObjectForm fold that ObjectView and the record form page render); a form converted by this release no longer clears after a save, and a form that should declares `submitBehavior: { kind: 'continue' }`. 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. | + +### Nested Shape: `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: `Form.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). | + + --- ## FormButtonConfig diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/system.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/system.md index e35ee35f184..22a10369642 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/system.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/system.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `system/` | 409 | +| `system/` | 410 | 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 77859989f1f..b7944172efe 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/` | 230 | 220 | 6 | 0 | 4 | +| `ui/` | 231 | 221 | 6 | 0 | 4 | ## `ui/` — sites @@ -44,9 +44,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` | 65 | +| `view.zod.ts` | 66 | | `widget.zod.ts` | 1 | -| **total** | **230** | +| **total** | **231** | ## `ui/` — open @@ -54,15 +54,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 230**, 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 | 65 | +| `view.zod.ts` | 1 | 66 | | `widget.zod.ts` | 1 | 1 | -| **total** | **4** | **230** | +| **total** | **4** | **231** | | Bucket | Sites | |---|---| diff --git a/examples/app-showcase/objectstack.config.ts b/examples/app-showcase/objectstack.config.ts index 845985fa8e0..f398b28bcfa 100644 --- a/examples/app-showcase/objectstack.config.ts +++ b/examples/app-showcase/objectstack.config.ts @@ -21,6 +21,7 @@ import { setupShowcaseExternalDatasource } from './src/system/datasources/extern import { registerShowcaseApprovalDemo } from './src/security/seed-approval-demo.js'; import { TaskViews, ProjectViews, InquiryViews, BusinessUnitViews, ContactViews, FieldZooViews } from './src/ui/views/index.js'; import { ShowcaseApp } from './src/ui/apps/index.js'; +import { FeedbackForm } from './src/ui/forms/index.js'; import { ChartGalleryDashboard, OpsDashboard, RevenuePulseDashboard } from './src/ui/dashboards/index.js'; import { ShowcaseTaskDataset, ShowcaseProjectDataset, ShowcaseInvoiceDataset, ShowcaseAccountDataset } from './src/ui/datasets/index.js'; import { allReports } from './src/ui/reports/index.js'; @@ -214,6 +215,8 @@ export default defineStack({ // UI apps: [ShowcaseApp], views: [TaskViews, ProjectViews, InquiryViews, BusinessUnitViews, ContactViews, FieldZooViews], + // [ADR-0159] The authored `form` item (`defineForm`), on an address of its own. + forms: [FeedbackForm], pages: [CapabilityMapPage, StartHerePage, ComponentGalleryPage, ProjectWorkspacePage, ProjectDetailPage, TaskWorkbenchPage, TaskTriagePage, TaskBoardPage, TaskCalendarPage, TaskGalleryPage, TaskSchedulePage, TaskTimelinePage, TaskMapPage, TaskAllViewsPage, ActiveProjectsPage, TaskDetailPage, InvoiceDocumentPage, ReviewQueuePage, NewProjectWizardPage, MyWorkPage, SettingsPage, StylingGalleryPage, CommandCenterPage, CommandCenterJsxPage, CrmWorkbenchPage, TaskDeskPage, PageVariablesPage, ContactFormPage, RenewalsPipelinePage], dashboards: [ChartGalleryDashboard, OpsDashboard, RevenuePulseDashboard], books: allBooks, diff --git a/examples/app-showcase/src/coverage.ts b/examples/app-showcase/src/coverage.ts index 6d471433705..dd07862193b 100644 --- a/examples/app-showcase/src/coverage.ts +++ b/examples/app-showcase/src/coverage.ts @@ -93,6 +93,8 @@ export const KIND_COVERAGE: Record = { // ── ui ── view: { status: 'demonstrated', files: ['src/ui/views/task.view.ts', 'src/ui/views/project.view.ts'] }, + // [ADR-0159] One authored `form` item, a public form on an address no other form holds. + form: { status: 'demonstrated', files: ['src/ui/forms/feedback.form.ts'] }, page: { status: 'demonstrated', files: ['src/ui/pages/index.ts'] }, dashboard: { status: 'demonstrated', diff --git a/examples/app-showcase/src/ui/forms/feedback.form.ts b/examples/app-showcase/src/ui/forms/feedback.form.ts new file mode 100644 index 00000000000..4f58548cb43 --- /dev/null +++ b/examples/app-showcase/src/ui/forms/feedback.form.ts @@ -0,0 +1,47 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { defineForm } from '@objectstack/spec'; + +/** + * [ADR-0159] The showcase's one authored `form` item: a public feedback form + * on `showcase_inquiry`, served at its own address (`/forms/showcase-feedback`; + * `/forms/contact-us` is the old-shape form in `inquiry.view.ts`, and two + * forms on one address are refused). + * + * GET /api/v1/forms/showcase-feedback → resolved form + whitelisted schema + * POST /api/v1/forms/showcase-feedback/submit → INSERT a showcase_inquiry + * GET /api/v1/meta/form/showcase_inquiry.feedback + * + * The name is `OBJECT.KEY` and its prefix is the form's `object`; the body is + * at the top level (no `config`, no `data`). ⛔ No action opens it: the console + * reads forms from `view` until card ③ (#37087), so an action-opened `form` + * item would answer not found. + */ +export const FeedbackForm = defineForm({ + name: 'showcase_inquiry.feedback', + object: 'showcase_inquiry', + label: 'Share feedback', + type: 'simple', + sections: [ + { + name: 'feedback', + label: 'Your feedback', + columns: 1, + fields: [ + { field: 'name', required: true }, + { field: 'email', required: true }, + { field: 'message', required: true }, + ], + }, + ], + sharing: { + enabled: true, + allowAnonymous: true, + publicLink: '/forms/showcase-feedback', + }, + submitBehavior: { + kind: 'thank-you', + title: 'Thank you', + message: 'Your feedback reached the showcase team.', + }, +}); diff --git a/examples/app-showcase/src/ui/forms/index.ts b/examples/app-showcase/src/ui/forms/index.ts new file mode 100644 index 00000000000..a991b95a055 --- /dev/null +++ b/examples/app-showcase/src/ui/forms/index.ts @@ -0,0 +1,3 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +export { FeedbackForm } from './feedback.form.js'; diff --git a/packages/cli/src/utils/i18n-coverage.ts b/packages/cli/src/utils/i18n-coverage.ts index 164a55830fe..4907eac0fc9 100644 --- a/packages/cli/src/utils/i18n-coverage.ts +++ b/packages/cli/src/utils/i18n-coverage.ts @@ -463,6 +463,7 @@ const SOURCE_SURFACE: Record = { report: 'reports', picklist: 'picklists', page: 'pages', + form: 'forms', flow: 'flow screens, steps, approval steps, toasts and refusals', hook: 'hook refusals', position: 'positions', diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 4f3cbcedc0b..6addfd6fbe2 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -134,6 +134,7 @@ import { validateSemanticRoles } from './validate-semantic-roles.js'; import { validateFormLayout } from './validate-form-layout.js'; import { validateInternalFormViews } from './validate-internal-form-views.js'; import { validatePublicFormFileFields } from './validate-public-form-file-fields.js'; +import { validateFormConsumers, validateFormPublicAddresses } from './validate-form-items.js'; import { validateThankYouRecordFields } from './validate-thank-you-record-fields.js'; import { validateAssignmentRules } from './validate-assignment-rules.js'; import { validateAiContext } from './validate-ai-context.js'; @@ -1860,6 +1861,37 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ 'to refuse, and the Studio no longer offers internal form views to save.', run: (stack) => validateInternalFormViews(stack), }, + // [ADR-0159 ruled question 3 = A] An authored `form` left open on a public + // address another form of the stack holds (authored or projected out of an + // old `view` shape). Gating. The runtime half is the save door's own + // `FORM_ADDRESS_TAKEN` refusal, judged over the effective `form` read, which + // a per-write snapshot does not carry. + { + name: 'validateFormPublicAddresses', + tier: 'gating', + input: 'parsed', + commands: ALL, + source: 'packages/lint/src/validate-form-items.ts', + surfaces: CLI_ONLY, + surfaceReason: + 'The runtime door judges the same clash over the effective `form` read (`formAddressClashRefusal`, ' + + '`409 FORM_ADDRESS_TAKEN`): a per-write snapshot carries no other form, so the gate would judge nothing.', + run: (stack) => validateFormPublicAddresses(stack), + }, + // [ADR-0159 D1] An authored `form` no link and no action reaches: the + // successor of `form-view-internal-not-loaded` for `form` items. Advisory. + { + name: 'validateFormConsumers', + tier: 'advisory', + input: 'normalized', + commands: ALL, + source: 'packages/lint/src/validate-form-items.ts', + surfaces: CLI_ONLY, + surfaceReason: + 'Advisory for the app author at the check tools: a form nothing reaches still installs and runs, so the ' + + 'runtime door has nothing to refuse.', + run: (stack) => validateFormConsumers(stack), + }, // Ruling C on #25572 (#25650) — a form open to anonymous intake that // declares a file field (a `FILE_REFERENCE_TYPES` type on the bound object) // is refused: no visitor can upload a file, so the field can never be diff --git a/packages/lint/src/i18n-walk.ts b/packages/lint/src/i18n-walk.ts index 71d67f76614..2c79a816de8 100644 --- a/packages/lint/src/i18n-walk.ts +++ b/packages/lint/src/i18n-walk.ts @@ -263,6 +263,7 @@ export interface ExpectedEntry { | 'report' | 'picklist' | 'page' + | 'form' | 'flow' | 'hook' | 'position' @@ -1243,6 +1244,16 @@ function walkObjectSections(config: any, out: ExpectedEntry[]): void { } } + // (b) [ADR-0159 D8] authored `form` items' sections, keyed under the + // object they bind (the object-level default the translator keeps). + const forms: any[] = Array.isArray(config?.forms) ? config.forms : []; + for (const form of forms) { + if (!form || typeof form !== 'object') continue; + const formObject = viewObjectName(form) ?? (typeof form.object === 'string' ? form.object : undefined); + addSectionList(index, form.sections, formObject); + addSectionEntries(entries, form.sections, formObject); + } + // (b) authored page sections — a record page's `record:details`. // // Reuses `@objectstack/lint`'s shared page traversal rather than growing a @@ -1846,6 +1857,9 @@ export function collectExpectedEntries( // ── Import mappings (`mappings..label`) ───────────────────── walkMappings(config, out); + // ── [ADR-0159 D8] `form` items (`forms..…`) ───────────────── + walkForms(config, out); + // ── Pages + their `page:header` copy ────────────────────────────── const pages: any[] = Array.isArray(config?.pages) ? config.pages : []; for (const page of pages) { @@ -2217,6 +2231,29 @@ function walkMappings(config: any, out: ExpectedEntry[]): void { } } +/** + * [ADR-0159 D8] Emit `forms..{label, description, title}` and its + * thank-you panel's `forms..submitBehavior.{title, message}` for each + * authored `form` item — the address `translateForm` reads first. ⛔ No + * `objects.._views.` tail is emitted for an authored `form`: that + * address is the old shapes' fallback, read, never scaffolded for the new + * type. Section copy stays the object's (`objects.._sections.…`), + * walked with the object's sections. + */ +function walkForms(config: any, out: ExpectedEntry[]): void { + const forms: any[] = Array.isArray(config?.forms) ? config.forms : []; + for (const form of forms) { + if (!form || typeof form !== 'object') continue; + const name = form.name; + if (typeof name !== 'string' || name.length === 0) continue; + const extra = typeof form.object === 'string' && form.object ? { objectName: form.object } : undefined; + pushOptional(out, ['forms', name, 'label'], form.label, 'form', extra); + pushOptional(out, ['forms', name, 'description'], form.description, 'form', extra); + pushOptional(out, ['forms', name, 'title'], form.title, 'form', extra); + pushThankYouPanel(out, ['forms', name], form.submitBehavior, 'form', extra); + } +} + // ─── Screen flows (`flows..screens..…`) ───────────────── /** diff --git a/packages/lint/src/reference-integrity-suite.ts b/packages/lint/src/reference-integrity-suite.ts index 93bd20d55df..2f5371f3b20 100644 --- a/packages/lint/src/reference-integrity-suite.ts +++ b/packages/lint/src/reference-integrity-suite.ts @@ -101,6 +101,7 @@ * so the gap stays visible instead of being rediscovered. */ +import { validateFormObjectBindings } from './validate-form-items.js'; import { validateObjectReferences } from './validate-object-references.js'; import { validateSearchableFields } from './validate-searchable-fields.js'; import { validateSortableFields } from './validate-sortable-fields.js'; @@ -421,6 +422,21 @@ export const REFERENCE_INTEGRITY_RULES: readonly ReferenceIntegrityRule[] = [ : undefined, ), }, + // [ADR-0159 D2] A `form`'s `object`, judged where a list view's is: under + // the stated closure, or against the whole collection of a runtime write. + { + name: 'validateFormObjectBindings', + runtimeTypes: ['form'], + run: (stack, ctx) => + validateFormObjectBindings( + stack, + ctx?.packageScope + ? { packageScope: ctx.packageScope } + : ctx?.runtimeWriteType !== undefined + ? { wholeCollection: true } + : undefined, + ), + }, // [#15254] The same question, one surface IN: the field-name lists the // OBJECT itself carries (`highlightFields`, `publicSharing.redactFields`), // which the three list-view members above do not walk because they are not diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 167dfcb23b0..46a762f37c2 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -5179,6 +5179,67 @@ const FORM_VIEW_INTERNAL_NOT_LOADED_EXPLANATION: RuleExplanation = { ], }; +// ── Form items (`validate-form-items.ts`, ADR-0159) ─────────────────────────── + +const FORM_PUBLIC_ADDRESS_TAKEN_EXPLANATION: RuleExplanation = { + rule: 'form-public-address-taken', + covers: 'why two forms cannot share one public address', + paragraphs: [ + 'A public form answers at `/forms/`, the slug its `sharing.publicLink` names. Two forms on one ' + + 'address answer one of them, and nothing says which: the anonymous doors take the first form that ' + + 'is open there, so a second form can take over an address an administrator thinks is closed.', + 'A form HOLDS an address while its `sharing.publicLink` names it, switched on or off: a form that ' + + 'keeps its link with `enabled: false` or `allowAnonymous: false` still holds it, so a successor on ' + + 'the same address is refused until the retired form\'s link is cleared. The forms read are every ' + + 'authored `form` item and every form an old `view` shape carries (a container\'s `form`, a ' + + '`formViews` entry, a `viewKind: \'form\'` item), under the names they are served as.', + 'Only an authored `form` left OPEN on a held address is refused; a closed form is never refused, and ' + + 'two old-shape forms on one address keep today\'s behaviour. The runtime `form` write door refuses ' + + 'the same save with `409 FORM_ADDRESS_TAKEN`. To clear it, give the form another public link, or ' + + 'clear the link of the form that holds the address.', + ], +}; + +const FORM_CONSUMER_LESS_EXPLANATION: RuleExplanation = { + rule: 'form-consumer-less', + covers: 'what counts as a consumer of a form', + paragraphs: [ + 'A `form` item is a named form with a consumer (ADR-0159 D1): a public link (`sharing.publicLink`), ' + + 'or an action of `type: \'form\'` whose `target` is the form\'s name. A form with neither is reached ' + + 'by nothing: it installs and steers nothing. A record create or edit form is not a `form` item; it ' + + 'is the object\'s `fieldGroups`.', + 'Not raised for an item that declares `overrides`: an override with no link over a base form that has ' + + 'a consumer is what keeps that address closed, and removing it would re-open the base\'s form. The ' + + 'rule is a warning. To clear it, give the form a public link, open it from an action of type `form`, ' + + 'or remove it.', + ], +}; + +const FORM_OBJECT_OUTSIDE_CLOSURE_EXPLANATION: RuleExplanation = { + rule: 'form-object-outside-closure', + covers: 'which objects a form may bind', + paragraphs: [ + 'A `form` item submits into the one object its `object` names (ADR-0159 D2). Under a stated package ' + + 'scope that object must be inside the package\'s closure: its own objects, the objects of the ' + + 'packages its manifest declares in `dependencies`, and platform objects — the closure a list view\'s ' + + 'object is judged against. A form bound outside it installs into a deployment where the object may ' + + 'not exist, and its public submit has nowhere to write.', + 'To clear it, bind the form to an object inside the closure, or declare a dependency on the package ' + + 'that ships the object.', + ], +}; + +const FORM_OBJECT_UNKNOWN_EXPLANATION: RuleExplanation = { + rule: 'form-object-unknown', + covers: 'why a form must bind an object that exists', + paragraphs: [ + 'A `form` item submits into the one object its `object` names (ADR-0159 D2). Judged against the whole ' + + 'collection a runtime write is judged against, the object exists nowhere in the deployment, so the ' + + 'form has nothing to render and its submit nothing to write into.', + 'To clear it, bind the form to an object that exists, or save the object before you publish the form.', + ], +}; + // ── Flow template paths (`validate-flow-template-paths.ts`) ─────────────────── const FLOW_TEMPLATE_FIELD_UNPROVISIONED_EXPLANATION: RuleExplanation = { @@ -7014,6 +7075,10 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [PAGE_SECTION_GROUP_UNKNOWN_EXPLANATION.rule]: PAGE_SECTION_GROUP_UNKNOWN_EXPLANATION, [FORM_SECTION_GROUP_UNKNOWN_EXPLANATION.rule]: FORM_SECTION_GROUP_UNKNOWN_EXPLANATION, [FORM_VIEW_INTERNAL_NOT_LOADED_EXPLANATION.rule]: FORM_VIEW_INTERNAL_NOT_LOADED_EXPLANATION, + [FORM_PUBLIC_ADDRESS_TAKEN_EXPLANATION.rule]: FORM_PUBLIC_ADDRESS_TAKEN_EXPLANATION, + [FORM_CONSUMER_LESS_EXPLANATION.rule]: FORM_CONSUMER_LESS_EXPLANATION, + [FORM_OBJECT_OUTSIDE_CLOSURE_EXPLANATION.rule]: FORM_OBJECT_OUTSIDE_CLOSURE_EXPLANATION, + [FORM_OBJECT_UNKNOWN_EXPLANATION.rule]: FORM_OBJECT_UNKNOWN_EXPLANATION, [FLOW_TEMPLATE_FIELD_UNPROVISIONED_EXPLANATION.rule]: FLOW_TEMPLATE_FIELD_UNPROVISIONED_EXPLANATION, [FLOW_TEMPLATE_LOOKUP_TRAVERSAL_EXPLANATION.rule]: FLOW_TEMPLATE_LOOKUP_TRAVERSAL_EXPLANATION, [FLOW_DOUBLE_BRACE_INTERPOLATION_EXPLANATION.rule]: FLOW_DOUBLE_BRACE_INTERPOLATION_EXPLANATION, diff --git a/packages/lint/src/runtime-gate.ts b/packages/lint/src/runtime-gate.ts index 881be5b4d18..1ee5ef9e59d 100644 --- a/packages/lint/src/runtime-gate.ts +++ b/packages/lint/src/runtime-gate.ts @@ -97,6 +97,7 @@ const TYPE_TO_STACK_KEY: Readonly> = { flow: 'flows', object: 'objects', view: 'views', + form: 'forms', action: 'actions', page: 'pages', dashboard: 'dashboards', diff --git a/packages/lint/src/validate-form-items.test.ts b/packages/lint/src/validate-form-items.test.ts new file mode 100644 index 00000000000..02d0baa5f84 --- /dev/null +++ b/packages/lint/src/validate-form-items.test.ts @@ -0,0 +1,112 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0159 card ② items 7 and 9] The authoring rules of the `form` type: + * the public-address refusal (ruled question 3 = A), the consumer-less + * advisory (not raised for an `overrides` item), and the object binding. + */ + +import { describe, expect, it } from 'vitest'; +import { + FORM_CONSUMER_LESS, + FORM_OBJECT_OUTSIDE_CLOSURE, + FORM_OBJECT_UNKNOWN, + FORM_PUBLIC_ADDRESS_TAKEN, + stackForms, + validateFormConsumers, + validateFormObjectBindings, + validateFormPublicAddresses, +} from './validate-form-items.js'; +import { AUTHORING_RULES } from './authoring-rules.js'; +import { explainRule } from './rule-explanations.js'; + +const sections = [{ fields: ['name'] }]; +const link = (enabled: boolean, slug = 'contact-us') => ({ enabled, allowAnonymous: true, publicLink: `/forms/${slug}` }); +const form = (name: string, over: Record = {}) => ({ name, object: 'lead', type: 'simple', sections, ...over }); + +describe('stackForms — one walk over authored items and the projection', () => { + it('reads authored `forms:` and the forms the old `view` shapes carry, under their served names', () => { + const forms = stackForms({ + forms: [form('lead.web')], + views: [{ name: 'lead', object: 'lead', formViews: { contact: { sections } } }], + }); + expect(forms.map((f) => [f.name, f.definedIn])).toEqual([['lead.web', 'form'], ['lead.contact', 'view']]); + }); +}); + +describe(FORM_PUBLIC_ADDRESS_TAKEN, () => { + it('refuses an authored form left open on an address an old-shape form holds, naming both', () => { + const findings = validateFormPublicAddresses({ + forms: [form('lead.web', { sharing: link(true) })], + views: [{ name: 'lead', object: 'lead', formViews: { contact: { sections, sharing: link(true) } } }], + }); + expect(findings).toHaveLength(1); + expect(findings[0]).toMatchObject({ severity: 'error', rule: FORM_PUBLIC_ADDRESS_TAKEN }); + expect(findings[0].message).toContain('lead.web'); + expect(findings[0].message).toContain('lead.contact'); + }); + + it('a switched-off form that keeps its link still holds the address', () => { + expect(validateFormPublicAddresses({ + forms: [form('lead.web', { sharing: link(true) }), form('lead.retired', { sharing: link(false) })], + }).map((f) => f.where)).toEqual(['form "lead.web"']); + }); + + it('CONTROL: a closed authored form is never refused, and two old-shape forms keep today\'s behaviour', () => { + expect(validateFormPublicAddresses({ + forms: [form('lead.retired', { sharing: link(false) })], + views: [ + { name: 'lead', object: 'lead', formViews: { a: { sections, sharing: link(true) }, b: { sections, sharing: link(true) } } }, + ], + })).toEqual([]); + }); +}); + +describe(FORM_CONSUMER_LESS, () => { + it('warns on an authored form with no link and no action', () => { + const findings = validateFormConsumers({ forms: [form('lead.orphan')] }); + expect(findings.map((f) => [f.severity, f.rule])).toEqual([['warning', FORM_CONSUMER_LESS]]); + }); + + it('is silent for a form an action of type `form` opens, a linked form, and an `overrides` item', () => { + expect(validateFormConsumers({ + forms: [ + form('lead.opened'), + form('lead.linked', { sharing: link(false) }), + form('lead.custom', { overrides: { package: 'com.acme', basedOn: '1.0.0' } }), + ], + actions: [{ name: 'open_form', type: 'form', target: 'lead.opened' }], + })).toEqual([]); + }); + + it('raises no new advisory for an old shape', () => { + expect(validateFormConsumers({ views: [{ name: 'lead', object: 'lead', formViews: { quiet: { sections } } }] })).toEqual([]); + }); +}); + +describe('form object bindings', () => { + const stack = { objects: [{ name: 'lead' }], forms: [form('lead.web'), form('ghost.web', { object: 'ghost' })] }; + + it('judges an authored form\'s object against a stated package closure', () => { + const findings = validateFormObjectBindings(stack, { packageScope: { packageId: 'com.acme', dependencies: [] } }); + expect(findings.map((f) => [f.rule, f.path])).toEqual([[FORM_OBJECT_OUTSIDE_CLOSURE, 'forms[1].object']]); + }); + + it('judges it against the whole collection a runtime write is judged against', () => { + expect(validateFormObjectBindings(stack, { wholeCollection: true }).map((f) => f.rule)).toEqual([FORM_OBJECT_UNKNOWN]); + }); + + it('CONTROL: judges nothing it cannot see', () => { + expect(validateFormObjectBindings(stack)).toEqual([]); + }); +}); + +describe('registration', () => { + it('registers the address refusal as gating and the consumer rule as advisory; `os explain` knows all four', () => { + expect(AUTHORING_RULES.find((r) => r.name === 'validateFormPublicAddresses')?.tier).toBe('gating'); + expect(AUTHORING_RULES.find((r) => r.name === 'validateFormConsumers')?.tier).toBe('advisory'); + for (const rule of [FORM_PUBLIC_ADDRESS_TAKEN, FORM_CONSUMER_LESS, FORM_OBJECT_OUTSIDE_CLOSURE, FORM_OBJECT_UNKNOWN]) { + expect(explainRule(rule)?.rule).toBe(rule); + } + }); +}); diff --git a/packages/lint/src/validate-form-items.ts b/packages/lint/src/validate-form-items.ts new file mode 100644 index 00000000000..9ee00efd5d9 --- /dev/null +++ b/packages/lint/src/validate-form-items.ts @@ -0,0 +1,212 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0159] The authoring rules of the `form` metadata type (card ② items 1, + * 7 and 9). Every rule reads a stack's forms through ONE walk, + * {@link stackForms}: the authored `forms:` items and the projection of the + * three old `view` shapes (`projectViewForms`), so no rule re-reads + * `formViews` by hand. + * + * - `form-public-address-taken` (gating, ruled question 3 = A): an authored + * `form` left open on a `/forms/SLUG` another form of the stack holds, + * authored or projected. A form holds an address while its + * `sharing.publicLink` names it, switched on or off. A refusal on the new + * type only: two old-shape forms on one slug keep today's first-match + * behaviour, and a closed authored form is never refused. + * - `form-consumer-less` (advisory, D1; the successor of + * `form-view-internal-not-loaded` for `form` items): an authored `form` + * with no public link that no `type: 'form'` action targets steers + * nothing. ⛔ Not raised for an item that declares `overrides`: an + * override with no link over a base form that has a consumer is what keeps + * that address closed, and a warning that it steers nothing would invite + * its removal (the base is not in the stack, so its consumers cannot be + * read here; the rule stays silent rather than guess). ⛔ No advisory for + * an old shape: `form-view-internal-not-loaded` stays the only one (D5). + * - `form-object-outside-closure` / `form-object-unknown` (gating, D2): a + * `form`'s `object` judged where a list view's object is judged + * (`validateListViewFieldRefs`): under a stated package closure, or + * against the whole collection a runtime write is judged against. The CLI + * judges no binding it cannot see (a dependency package's object). + */ + +import { + anonymousFormIntakeSlug, + isAggregatedViewContainer, + projectViewForms, + publicFormSlug, +} from '@objectstack/spec/ui'; +import { collectionEntries } from './collection-entries.js'; +import { recordsOf } from './object-graph.js'; +import { walkPageComponents } from './page-walk.js'; + +export const FORM_PUBLIC_ADDRESS_TAKEN = 'form-public-address-taken'; +export const FORM_CONSUMER_LESS = 'form-consumer-less'; +export const FORM_OBJECT_OUTSIDE_CLOSURE = 'form-object-outside-closure'; +export const FORM_OBJECT_UNKNOWN = 'form-object-unknown'; + +type AnyRec = Record; + +const isRec = (v: unknown): v is AnyRec => !!v && typeof v === 'object' && !Array.isArray(v); +const strName = (v: unknown): string | undefined => (typeof v === 'string' && v.length > 0 ? v : undefined); + +export interface FormItemFinding { + severity: 'error' | 'warning'; + rule: typeof FORM_PUBLIC_ADDRESS_TAKEN | typeof FORM_CONSUMER_LESS | typeof FORM_OBJECT_OUTSIDE_CLOSURE | typeof FORM_OBJECT_UNKNOWN; + where: string; + path: string; + message: string; + hint: string; +} + +/** One form of a stack: an authored `form` item, or one the projection reads out of a `view`. */ +export interface StackForm { + name: string; + object: string | undefined; + form: AnyRec; + /** `form`: authored in `forms:`; `view`: projected from an old shape. */ + definedIn: 'form' | 'view'; + path: string; +} + +/** + * [ADR-0159 D5] Every form of a stack: the authored `forms:` entries, then + * the forms the projection reads out of `views:` (containers expanded under + * the object the registrars bind them to, items under their own name). + */ +export function stackForms(stack: AnyRec): StackForm[] { + const out: StackForm[] = []; + for (const { rec, path } of collectionEntries(stack.forms, 'forms')) { + const name = strName(rec.name); + if (!name) continue; + out.push({ name, object: strName(rec.object), form: rec, definedIn: 'form', path }); + } + for (const { rec, path } of collectionEntries(stack.views, 'views')) { + for (const form of projectViewForms(rec).forms) { + out.push({ + name: form.name, + object: strName(form.object), + form: form as AnyRec, + definedIn: 'view', + path: isAggregatedViewContainer(rec) ? `${path} (${form.name})` : `${path}.config`, + }); + } + } + return out; +} + +/** The slug a form's `sharing.publicLink` names, switched on or off. */ +function heldSlug(form: AnyRec): string | undefined { + const sharing = form.sharing; + const link = isRec(sharing) ? strName(sharing.publicLink) : undefined; + return link ? publicFormSlug(link) : undefined; +} + +/** Every form name a `type: 'form'` action of the stack targets literally. */ +function formTargets(stack: AnyRec): Set { + const out = new Set(); + const add = (action: unknown) => { + if (!isRec(action) || action.type !== 'form') return; + const target = strName(action.target); + if (target && !target.includes('{')) out.add(target); + }; + for (const action of recordsOf(stack.actions)) add(action); + for (const obj of recordsOf(stack.objects)) for (const action of recordsOf(obj.actions)) add(action); + const pages = recordsOf(stack.pages); + for (let i = 0; i < pages.length; i++) { + for (const { component } of walkPageComponents(pages[i], `pages[${i}]`)) { + if (isRec(component.properties)) add(component.properties.action); + } + } + return out; +} + +/** [ruled question 3 = A] An authored `form` left open on an address another form holds. */ +export function validateFormPublicAddresses(stack: AnyRec): FormItemFinding[] { + const findings: FormItemFinding[] = []; + const forms = stackForms(stack); + for (const form of forms) { + if (form.definedIn !== 'form') continue; + const slug = anonymousFormIntakeSlug(form.form.sharing); + if (slug === null) continue; + const holder = forms.find((other) => other !== form && other.name !== form.name && heldSlug(other.form) === slug); + if (!holder) continue; + findings.push({ + severity: 'error', + rule: FORM_PUBLIC_ADDRESS_TAKEN, + where: `form "${form.name}"`, + path: `${form.path}.sharing.publicLink`, + message: + `the form "${form.name}" opens /forms/${slug}, which the form "${holder.name}" (${holder.path}) already holds. ` + + 'Two forms on one public address answer one of them, and nothing says which.', + hint: + `Give "${form.name}" another public link, or clear the link of "${holder.name}". A form holds an address ` + + 'while its public link names it, switched on or off.', + }); + } + return findings; +} + +/** [ADR-0159 D1] An authored `form` that no link and no action reaches. */ +export function validateFormConsumers(stack: AnyRec): FormItemFinding[] { + const findings: FormItemFinding[] = []; + const targets = formTargets(stack); + for (const form of stackForms(stack)) { + if (form.definedIn !== 'form') continue; + if (isRec(form.form.overrides)) continue; + if (heldSlug(form.form) !== undefined) continue; + if (targets.has(form.name)) continue; + findings.push({ + severity: 'warning', + rule: FORM_CONSUMER_LESS, + where: `form "${form.name}"`, + path: form.path, + message: + `the form "${form.name}" has no public link and no \`type: 'form'\` action opens it, so nothing reaches it: ` + + 'it installs and steers nothing.', + hint: + `Give "${form.name}" a public link (\`sharing.publicLink\`), open it from an action of type \`form\` whose ` + + 'target is its name, or remove it.', + }); + } + return findings; +} + +/** Options mirroring `validateListViewFieldRefs`': where a binding is judged. */ +export interface FormObjectBindingOptions { + packageScope?: { readonly packageId: string; readonly dependencies: readonly string[] }; + wholeCollection?: boolean; +} + +/** [ADR-0159 D2] An authored `form`'s `object`, judged where a list view's object is. */ +export function validateFormObjectBindings(stack: AnyRec, options?: FormObjectBindingOptions): FormItemFinding[] { + const findings: FormItemFinding[] = []; + const scope = options?.packageScope; + if (!scope && options?.wholeCollection !== true) return findings; + const objects = new Set(recordsOf(stack.objects).map((o) => strName(o.name)).filter((n): n is string => !!n)); + // An empty whole collection means the host supplied no universe, as the + // list-view rule reads it. + if (!scope && objects.size === 0) return findings; + for (const form of stackForms(stack)) { + if (form.definedIn !== 'form' || form.object === undefined || objects.has(form.object)) continue; + findings.push(scope + ? { + severity: 'error', + rule: FORM_OBJECT_OUTSIDE_CLOSURE, + where: `form "${form.name}"`, + path: `${form.path}.object`, + message: + `binds object "${form.object}", which is outside package "${scope.packageId}"'s closure (its own objects, ` + + 'the objects of the packages its manifest declares in `dependencies`, and platform objects).', + hint: `Bind the form to an object inside that closure, or declare a dependency on the package that ships "${form.object}".`, + } + : { + severity: 'error', + rule: FORM_OBJECT_UNKNOWN, + where: `form "${form.name}"`, + path: `${form.path}.object`, + message: `binds object "${form.object}", which exists nowhere in this deployment.`, + hint: `Bind the form to an object that exists, or save the object "${form.object}" before you publish the form.`, + }); + } + return findings; +} diff --git a/packages/lint/src/validate-public-form-file-fields.ts b/packages/lint/src/validate-public-form-file-fields.ts index e770bfb1ce0..86a03739c7e 100644 --- a/packages/lint/src/validate-public-form-file-fields.ts +++ b/packages/lint/src/validate-public-form-file-fields.ts @@ -46,6 +46,7 @@ import { FILE_REFERENCE_TYPES } from '@objectstack/spec/data'; import { anonymousFormIntakeCandidates, + anonymousFormIntakeSlug, anonymousFormObjectName, type AnonymousFormIntakeCandidate, } from '@objectstack/spec/ui'; @@ -170,5 +171,40 @@ export function validatePublicFormFileFields(stack: AnyRec): PublicFormFileField } } + // [ADR-0159] …and every authored `form` item open to anonymous intake, the + // same judgement at the form's own root. + for (const { rec: form, path: formPath } of collectionEntries(stack.forms, 'forms')) { + const formName = strName(form.name) ?? formPath; + const slug = anonymousFormIntakeSlug(form.sharing); + const objectName = strName(form.object); + const types = slug !== null && objectName ? fieldTypes.get(objectName) : undefined; + if (!types) continue; + for (const bucket of ['sections', 'groups'] as const) { + const sections = Array.isArray(form[bucket]) ? (form[bucket] as unknown[]) : []; + for (let s = 0; s < sections.length; s++) { + const section = sections[s]; + const entries = isRec(section) && Array.isArray(section.fields) ? (section.fields as unknown[]) : []; + for (let f = 0; f < entries.length; f++) { + const fieldName = fieldNameOf(entries[f]); + const type = fieldName ? types.get(fieldName) : undefined; + if (!fieldName || !type || !FILE_REFERENCE_TYPES.has(type)) continue; + findings.push({ + severity: 'error', + rule: PUBLIC_FORM_FILE_FIELD, + where: `form "${formName}"`, + path: `${formPath}.${bucket}[${s}].fields[${f}]`, + message: + `${formName}: the form is open to anonymous intake (its sharing publishes /forms/${slug} with ` + + `allowAnonymous: true) and declares "${fieldName}", a ${type} field on object "${objectName}". A ` + + `public form takes no attachment: an anonymous visitor has no upload door, so this field can never be filled.`, + hint: + `Take "${fieldName}" off this public form. To collect a file from a visitor, have them register and ` + + `sign in, then fill a form that is not open to anonymous intake and declares "${fieldName}".`, + }); + } + } + } + } + return findings; } diff --git a/packages/metadata-core/src/types.ts b/packages/metadata-core/src/types.ts index 84526f59b6c..0a46357b9e0 100644 --- a/packages/metadata-core/src/types.ts +++ b/packages/metadata-core/src/types.ts @@ -23,6 +23,7 @@ export const MetadataTypeSchema = z.enum([ 'hook', 'mapping', 'view', + 'form', 'page', 'dashboard', 'app', diff --git a/packages/metadata-protocol/src/plugin.ts b/packages/metadata-protocol/src/plugin.ts index 4d8c704b705..4b60842e0e5 100644 --- a/packages/metadata-protocol/src/plugin.ts +++ b/packages/metadata-protocol/src/plugin.ts @@ -476,6 +476,18 @@ export function assembleMetadataProtocol( plans?.register?.(createRecordedBySentinelPlan()); }); + // [ADR-0159 D6 rule 7] A stored `view` body the `form` projection + // cannot read closes the public links it names on both anonymous + // doors; the boot says so once at `error`, naming the row, the + // links and the repair save. Reads only; never fails a bootstrap. + (ctx as any)?.hook?.('kernel:ready', async () => { + try { + await protocolShim.getUnreadableFormBodies(); + } catch { + // An unreadable store is the doors' own question per request. + } + }); + // NO `analytics` fallback rides here anymore (#3891 / #3878). The // degraded shim this assembly used to register dropped the request's // ExecutionContext (aggregates ran without RLS/tenant predicates) diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index 855948f119f..52d2ea1bd8d 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -101,6 +101,12 @@ export interface AuthoringGateHost { unknownGrantObjectSaveRefusal: ObjectStackProtocolImplementation['unknownGrantObjectSaveRefusal']; unknownPicklistBindingSaveRefusal: ObjectStackProtocolImplementation['unknownPicklistBindingSaveRefusal']; seedExternalIdSaveRefusal: ObjectStackProtocolImplementation['seedExternalIdSaveRefusal']; + /** + * [ADR-0159 card ② item 5] The save door's package-less list-over-form + * refusal ({@link packagelessListOverFormRefusal}), asked of a restored + * body against the binding it is restored into. + */ + listOverFormRefusal: (type: string, item: unknown, name: string, binding: string | null) => Error | undefined; /** [#34776] The automation engine's sealed node-type vocabulary ({@link sealedFlowNodeTypeVocabulary}). */ sealedFlowNodeTypeVocabulary: () => readonly string[] | undefined; } @@ -115,7 +121,7 @@ export function restoredBodyDerivation( /** The body of `ObjectStackProtocolImplementation#restoredBodyWriter`; the method's docblock there is its contract. */ export function restoredBodyWriter( - this: Pick, + this: Pick, type: string, name: string, binding: string | null, source: string): (historyBody: unknown) => Promise { const derive = this.restoredBodyDerivation(type); return async (historyBody) => { @@ -129,6 +135,13 @@ export function restoredBodyWriter( // [#28574] An `object_extension` version against its address, on the same binding. const extensionRefusal = this.objectExtensionItemRefusal(type, historyBody, name, binding); if (extensionRefusal) throw extensionRefusal; + // [ADR-0159 card ② item 5] …and a package-less view whose restored + // body would store a list at the name a read-only package authors as a + // `form`: the save door refuses that body (`VALIDATION_ERROR`, 400), + // so a rollback or a revert restoring it is refused with the same + // sentence before anything is written. + const listOverForm = this.listOverFormRefusal(type, historyBody, name, binding); + if (listOverForm) throw listOverForm; await this.refuseRestoredBodyTheSaveDoorRefuses(type, name, historyBody, binding, source); // [#37013] A restore is never the platform's registration: the body is // written without the platform's mark, read where the store reads it. diff --git a/packages/metadata-protocol/src/protocol-diff-delete-load.ts b/packages/metadata-protocol/src/protocol-diff-delete-load.ts index 1c2294d6482..394bcf043d8 100644 --- a/packages/metadata-protocol/src/protocol-diff-delete-load.ts +++ b/packages/metadata-protocol/src/protocol-diff-delete-load.ts @@ -23,6 +23,7 @@ * not move. */ +import { applyOldShapeFormRowRemovals, type OldShapeFormRowRemoval } from './protocol-form-writes.js'; import { overlayMemberWhere } from './migrations/overlay-index.js'; import { historyRowsOfMember, @@ -455,7 +456,7 @@ export class ProtocolDiffDeleteLoadFacet { } /** [#28355] The body of {@link deleteMetaItem} before its refusal audit; that method's docblock is the contract. */ - static async deleteMetaItemUnaudited(host: Pick, request: DeleteMetaItemRequest): Promise<{ + static async deleteMetaItemUnaudited(host: Pick, request: DeleteMetaItemRequest): Promise<{ success: boolean; message?: string; reset?: boolean; @@ -894,7 +895,27 @@ export class ProtocolDiffDeleteLoadFacet { ? ((await host.storedParentForToken(ref, request.parentVersion, current.hash)) ?? current.hash) : current.hash; - const result = await repo.delete(ref, { + // [ADR-0159 D5, card ② item 5] A `form` reset or delete also + // removes the old-shape row that carries the form at the same + // address, in the same transaction (the repository's `delete` + // joins it). ⛔ Form content only. + let removedOldShapeRows: OldShapeFormRowRemoval[] = []; + const formRowRemoval = targetState === 'active' && singularTypeForRepo === 'form'; + const deleteFormAware = async (del: () => Promise): Promise => { + if (!formRowRemoval) return del(); + const run = async () => { + const removed = await del(); + removedOldShapeRows = await applyOldShapeFormRowRemovals(host, { + name: request.name, + packageId: packageId ?? null, + actor: request.actor ?? null, + source: 'protocol.deleteMetaItem', + }); + return removed; + }; + return typeof host.engine?.transaction === 'function' ? host.engine.transaction(run) : run(); + }; + const result = await deleteFormAware(() => repo.delete(ref, { parentVersion, // #4556 — NULL, not 'system', for an actor-less delete. actor: request.actor ?? null, @@ -915,7 +936,17 @@ export class ProtocolDiffDeleteLoadFacet { // row it meets. packageId, ...memberOption(member), - }); + })); + for (const removal of removedOldShapeRows) { + if (removal.kind === 'delete') { + await host.restoreArtifactRegistryView('view', removal.row.name, null, removal.row.packageId); + } else { + await host.applyRegistryWriteThrough({ + type: 'view', name: removal.row.name, item: removal.body, + packageId: removal.row.packageId, organizationId: null, + }); + } + } // Heal the registry: drop the overlay's runtime shadow so the // packaged artifact is visible again (all kernels), and on diff --git a/packages/metadata-protocol/src/protocol-form-reads.ts b/packages/metadata-protocol/src/protocol-form-reads.ts new file mode 100644 index 00000000000..80c9c7c8d4c --- /dev/null +++ b/packages/metadata-protocol/src/protocol-form-reads.ts @@ -0,0 +1,343 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0159 D5, D6 rule 11] The effective `form` read: the `form` items a + * caller is served, resolved over BOTH types. + * + * Until card ⑤ every first-party form is still an old shape (a `view` + * container's `form`, a `formViews` entry, a `viewKind: 'form'` item), and a + * package may move its source to `forms:` while a stored `view` row still + * stands over the form. So the `form` read is three readings, combined per + * package address `(package, name)`: + * + * 1. **The generic `form` list** — the authored `form` items the registry + * holds and the stored `form` rows over them, merged as every type is + * merged ({@link ProtocolHost.readFlattenedMetaItems}). + * 2. **The projection of the served `view` list** — at an address whose + * package still authors its form as an old shape, the `view` type + * resolves the address today, so the `view` row the served-row order + * serves there is the form's body. Each item of the effective `view` + * list is projected ({@link projectViewForms}); a projected item is + * marked in its envelope ({@link PROJECTED_FORM_SOURCE_KEY}). ⛔ Never + * parsed by `FormSchema`: the authored-only refusals do not apply to it. + * 3. **The cross-type resolution** — at an address whose package authors + * the form as a `form` item it has LEFT the `view` type, so the `view` + * merge no longer resolves that address. The `form` read asks the + * served-row order itself ({@link servedOverlayRowCandidates}), at that + * package's address, over the stored rows of both types: the first place + * that holds a row of the name decides, a stored `form` row winning over + * a stored `view` row at the same place, an item row over a container's + * expansion. A `view` row there serves the form it projects; a `view` row + * that projects no form at the name (a list, or a body the projection + * cannot read) closes the address: nothing is served for the name from + * the package (the closed reading, fail-closed). ⛔ "Served" is asked at + * each package's address, never taken from the effective `view` list: + * one row can be the served row at one package's address and be passed + * over at another's. + * + * Inside one package and one layer an authored item shadows a projected one + * of the same name; a package's source item never shadows the projection of + * a stored row (step 3 runs over the stored rows first). + * + * Pure over what the host reads: no write, no registry mutation. + */ + +import { pairsOf, type InstalledManifestLookup } from '@objectstack/metadata-core'; +import { PROJECTED_FORM_SOURCE_KEY, isAggregatedViewContainer, 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'; +import type { StoredOverlayEntry } from './protocol-stored-overlay-types.js'; + +/** What one stored row holds at a form's name, as the `form` read reads it. */ +type StoredHolding = + | { readonly kind: 'form'; readonly item: Record } + | { readonly kind: 'closed'; readonly reason: 'list' | 'unreadable' }; + +/** One stored row of either type, with its binding and what it holds per name. */ +interface StoredFormPlace { + readonly type: 'form' | 'view'; + readonly packageId: string | undefined; + readonly entry: StoredOverlayEntry; + /** `item` for a row stored under the name itself, `expansion` for a container that expands it. */ + readonly grain: 'item' | 'expansion'; + readonly holds: ReadonlyMap; +} + +/** The host members the effective `form` read reads. */ +export type FormReadHost = Pick; + +const keyOf = (pkg: unknown, name: unknown): string => `${typeof pkg === 'string' ? pkg : ''}\u0000${String(name)}`; + +/** A listed item's package, as its envelope states it. */ +function packageOf(item: unknown): string | undefined { + const pkg = (item as { _packageId?: unknown } | null)?._packageId; + return typeof pkg === 'string' && pkg !== '' ? pkg : undefined; +} + +/** The base package a stored body declares it overrides, if any. */ +function declaredOverrideOf(body: unknown): string | undefined { + const overrides = (body as { overrides?: unknown } | null)?.overrides; + const pkg = overrides && typeof overrides === 'object' ? (overrides as { package?: unknown }).package : undefined; + return typeof pkg === 'string' && pkg !== '' ? pkg : undefined; +} + +/** + * [ADR-0159 D5] What a stored `view` body holds per name: a projected form, or + * a closing holding (a list at the name, a body the projection cannot read). + */ +function viewHoldings(body: unknown): Map { + const out = new Map(); + const projection = projectViewForms(body); + for (const form of projection.forms) if (!out.has(form.name)) out.set(form.name, { kind: 'form', item: form }); + for (const list of projection.lists) if (!out.has(list)) out.set(list, { kind: 'closed', reason: 'list' }); + if (projection.unreadable !== undefined) { + const name = (body as { name?: unknown } | null)?.name; + if (typeof name === 'string' && name !== '' && !out.has(name)) out.set(name, { kind: 'closed', reason: 'unreadable' }); + } + return out; +} + +/** Read the active stored rows of one type as parsed entries; an unprovisioned store reads none. */ +async function storedEntries(host: FormReadHost, type: 'form' | 'view'): Promise { + try { + const rows = await host.readActiveOverlayRows({ type }); + return rows.length === 0 ? [] : host.storedOverlayEntries({ type }, rows); + } catch (error) { + host.rethrowUnlessMetadataStoreUnprovisioned(error, 'sys_metadata'); + return []; + } +} + +/** Every stored row of both types as a {@link StoredFormPlace}. */ +async function storedFormPlaces(host: FormReadHost): Promise { + const places: StoredFormPlace[] = []; + for (const entry of await storedEntries(host, 'form')) { + const name = typeof entry.data?.name === 'string' && entry.data.name !== '' ? entry.data.name : entry.name; + if (typeof name !== 'string' || name === '') continue; + places.push({ type: 'form', packageId: entry.packageId, entry, grain: 'item', holds: new Map([[name, { kind: 'form', item: entry.data }]]) }); + } + const views = await storedEntries(host, 'view'); + const containers = views.filter((entry) => isAggregatedViewContainer(entry.data)); + for (const entry of views) { + if (isAggregatedViewContainer(entry.data)) continue; + places.push({ type: 'view', packageId: entry.packageId, entry, grain: 'item', holds: viewHoldings(entry.data) }); + } + // A stored container is read as the items the runtime door expands it to, + // the same expansion the `view` list serves, so a projected name is the + // served one. + const byContainer = new Map>(); + for (const { item, container } of host.expandStoredViewContainers('view', containers)) { + const holds = byContainer.get(container) ?? new Map(); + for (const [name, holding] of viewHoldings(item)) holds.set(name, holding); + byContainer.set(container, holds); + } + for (const container of containers) { + const projection = projectViewForms(container.data); + const holds = byContainer.get(container) ?? new Map(); + // A container the projection cannot read holds nothing it can name; + // the doors close the links it names (rule 7), the read serves nothing new. + if (projection.unreadable !== undefined && holds.size === 0) continue; + places.push({ type: 'view', packageId: container.packageId, entry: container, grain: 'expansion', holds }); + } + return places; +} + +/** + * [ADR-0159 D5, rule 11] The stored row the served-row order picks for `name` + * at `packageId`'s address, over both types: `undefined` when no place holds a + * row of the name (the package's source item is served). + */ +export function servedFormHolding( + places: readonly StoredFormPlace[], + name: string, + packageId: string, + installed: InstalledManifestLookup, +): { holding: StoredHolding; place: StoredFormPlace; overrideOf?: string } | undefined { + for (const candidate of servedOverlayRowCandidates({ packageId, servedOverride: true, installed })) { + // Both spellings are read as one: the `form` read parses rows of + // either spelling of its type, and the spelling decides nothing here. + if (candidate.spelling === 'other') continue; + const at = places.filter((place) => place.holds.has(name) + && (candidate.packageId === undefined || (place.packageId ?? null) === candidate.packageId) + && holdsServedOverlayCandidate(candidate, + { type: place.entry.type, package_id: place.packageId ?? null, metadata: place.entry.data }, installed, undefined)); + // A stored `form` row wins over a stored `view` row at the same place; + // an item row over a container's expansion. + const rank = (place: StoredFormPlace): number => (place.type === 'form' ? 0 : place.grain === 'item' ? 1 : 2); + const hit = [...at].sort((a, b) => rank(a) - rank(b))[0]; + if (hit !== undefined) { + return candidate.overrideOf === undefined + ? { holding: hit.holds.get(name)!, place: hit } + : { holding: hit.holds.get(name)!, place: hit, overrideOf: candidate.overrideOf }; + } + } + return undefined; +} + +/** A projected item, marked and served under `packageId`'s envelope. */ +function projectedServed(item: Record, packageId: string | undefined): Record { + const out: Record = { ...item, [PROJECTED_FORM_SOURCE_KEY]: 'view' }; + if (packageId !== undefined) out._packageId = packageId; + else delete out._packageId; + return out; +} + +/** + * [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. + */ +export async function readEffectiveForms( + host: FormReadHost, + request: { type: string; packageId?: string; names?: readonly string[]; previewDrafts?: boolean }, + audience: 'served' | 'execution', +): Promise { + const { packageId: scope, names, ...rest } = request; + const unscoped = { ...rest, type: 'form' }; + const generic = (await host.readFlattenedMetaItems(unscoped, audience)).items as unknown[]; + const views = (await host.readFlattenedMetaItems({ ...unscoped, type: 'view' }, audience)).items as unknown[]; + const installed = installedManifestsOfEngine(host.engine); + + // The packages that author a form of each name as a `form` item: the + // addresses that have left the `view` type (step 3). + const authored = new Map>(); + for (const item of host.engine.registry.listItems('form') as unknown[]) { + const name = (item as { name?: unknown } | null)?.name; + const pkg = packageOf(item); + if (typeof name !== 'string' || pkg === undefined) continue; + const set = authored.get(name) ?? new Set(); + set.add(pkg); + authored.set(name, set); + } + const leftView = (pkg: string | undefined, name: string): boolean => pkg !== undefined && authored.get(name)?.has(pkg) === true; + + // Step 2: the projection of the served `view` list, per (package, name). + const projected = new Map>(); + const projectedOrder: string[] = []; + for (const view of views) { + const pkg = packageOf(view); + for (const form of projectViewForms(view).forms) { + const key = keyOf(pkg, form.name); + if (projected.has(key)) continue; + projected.set(key, projectedServed(form, pkg)); + projectedOrder.push(key); + } + } + + // Step 1: the generic list, a declared override of a base that ships the + // name only as an old shape re-keyed to its base: it is the base's item. + const out = new Map(); + const order: string[] = []; + const put = (key: string, item: unknown): void => { + if (!out.has(key)) order.push(key); + out.set(key, item); + }; + const genericByKey = new Map(); + for (let item of generic) { + const name = (item as { name?: unknown } | null)?.name; + if (typeof name !== 'string') continue; + let pkg = packageOf(item); + const base = declaredOverrideOf(item); + if (base !== undefined && pkg !== base && pairsOf(base, installed).includes(pkg ?? '') + && projected.has(keyOf(base, name))) { + pkg = base; + item = { ...(item as object), _packageId: base }; + } + genericByKey.set(keyOf(pkg, name), item); + } + + // Step 3 needs the stored rows of both types, read only when an address + // has left the `view` type. + let places: StoredFormPlace[] | undefined; + const placesOf = async (): Promise => (places ??= await storedFormPlaces(host)); + + for (const [key, item] of genericByKey) { + const name = String((item as { name?: unknown }).name); + const pkg = packageOf(item); + if (!leftView(pkg, name)) { + put(key, item); + continue; + } + const served = servedFormHolding(await placesOf(), name, pkg!, installed); + if (served === undefined || served.place.type === 'form') { + // No stored row, or a stored `form` row: the generic merge served + // the same candidate order over the `form` rows alone. + 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)); + // …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 + // item withheld) is not re-introduced here. + + // Step 2's items, where no generic item holds the same address. An + // authored item shadows a projected one of the same package and name. + const genericNames = new Set([...genericByKey.values()].map((item) => String((item as { name?: unknown }).name))); + for (const key of projectedOrder) { + if (genericByKey.has(key)) continue; + const item = projected.get(key)!; + const pkg = packageOf(item); + const name = String(item.name); + // An address that has left the `view` type is resolved by step 3. + if (leftView(pkg, name)) continue; + // A package-less projection stands in for the addresses of the name + // that step 1 resolved (they read it as a candidate): never listed twice. + if (pkg === undefined && genericNames.has(name)) continue; + put(key, item); + } + + let items = order.map((key) => out.get(key)); + if (scope !== undefined) items = items.filter((item) => packageOf(item) === scope); + if (names !== undefined) { + const wanted = new Set(names); + items = items.filter((item) => wanted.has(String((item as { name?: unknown }).name))); + } + return items; +} + +/** The rows {@link readUnreadableFormBodies} has reported, so each is said once per process. */ +const REPORTED_UNREADABLE = new Set(); + +/** + * [ADR-0159 D6 rule 7] Every stored `view` body the projection cannot turn + * into `form` items, with the `sharing.publicLink` slugs it names: the doors + * close each of those links. Each such row is said ONCE at `error`, naming the + * row (type, name, package), the links it closed, and the way out this release + * ships: an old-shape save that repairs the body. ⛔ No command that does not + * ship is named (the ceremony card, ⑤a, adds its name). + */ +export async function readUnreadableFormBodies( + host: Pick, + report: (line: string) => void = (line) => console.error(line), +): Promise { + const out: UnreadableFormBody[] = []; + for (const entry of await storedEntries(host as FormReadHost, 'view')) { + const projection = projectViewForms(entry.data); + if (projection.unreadable === undefined) continue; + const body: UnreadableFormBody = { + type: 'view', + name: entry.name, + ...(entry.packageId !== undefined ? { packageId: entry.packageId } : {}), + reason: projection.unreadable.reason, + links: projection.unreadable.links, + }; + out.push(body); + const key = `${body.type}\u0000${body.name}\u0000${body.packageId ?? ''}\u0000${body.reason}\u0000${body.links.join(',')}`; + if (REPORTED_UNREADABLE.has(key)) continue; + REPORTED_UNREADABLE.add(key); + const where = body.packageId !== undefined ? `package '${body.packageId}'` : 'no package'; + const closed = body.links.length > 0 ? body.links.map((l) => `/forms/${l}`).join(', ') : 'no public link'; + report( + `[Protocol] The stored view '${body.name}' (${where}) carries form content that cannot be read: ` + + `${body.reason}. The public forms it names are closed: ${closed}. ` + + `Save the view again with its form content repaired (a \`form\` or \`formViews\` entry that is an object) to re-open them (ADR-0159 D6 rule 7).`, + ); + } + return out; +} diff --git a/packages/metadata-protocol/src/protocol-form-writes.ts b/packages/metadata-protocol/src/protocol-form-writes.ts new file mode 100644 index 00000000000..04c6e48374e --- /dev/null +++ b/packages/metadata-protocol/src/protocol-form-writes.ts @@ -0,0 +1,259 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0159 D5, D7] The write-side judgements the `form` type adds: + * + * - {@link packagelessListOverFormRefusal} — card ② item 5's refusal: a + * package-less `view` write that would store a LIST at a name a read-only + * package authors as a `form` item. Kept as long as rule 11's replacement + * check is kept. + * - {@link formAddressClashRefusal} — ruled question 3 (A): a `form` whose + * open public address another form already holds. + * - {@link oldShapeFormRowRemovals} — what a `form` save, reset or delete at + * `(package, name)` removes of the old-shape row that carries that form at + * that address, in the same transaction. + * + * Each judges bodies through THE projection ({@link projectViewForms}), never + * by re-reading `formViews` by hand. + */ + +import { PLURAL_TO_SINGULAR } from '@objectstack/spec/shared'; +import { anonymousFormIntakeSlug, isAggregatedViewContainer, projectViewForms, publicFormSlug } from '@objectstack/spec/ui'; +import type { ProtocolHost } from './protocol-host.js'; +import { readEffectiveForms, type FormReadHost } from './protocol-form-reads.js'; + +/** The error code of the public address clash (ruled question 3): ledgered in `check:error-code-casing`. */ +export const FORM_ADDRESS_TAKEN = 'FORM_ADDRESS_TAKEN' as const; + +const isPackageless = (packageId: string | null | undefined): boolean => + packageId === undefined || packageId === null || packageId === ''; + +/** + * The names a `view` body would store a LIST at, as the readers place it: an + * item's own name when it carries no form, and every list a container's + * expansion writes (the runtime door's expansion, bound to no package). + */ +function listNamesOf( + host: Pick, + type: string, + body: Record, + saveName: string, +): string[] { + const stamped = typeof body.name === 'string' && body.name !== '' ? body : { ...body, name: saveName }; + if (isAggregatedViewContainer(stamped)) { + const names: string[] = []; + for (const expanded of host.expandRuntimeViewContainer(type, stamped, { packageId: null })) { + names.push(...projectViewForms(expanded).lists); + } + return [...new Set(names)]; + } + return projectViewForms(stamped).lists; +} + +/** + * [ADR-0159 D5, card ② item 5] Refuse a package-less `view` write that would + * store a list at a name a READ-ONLY package authors as a `form` item (in + * `forms:`; a form the projection reads out of a package's old shape does not + * trigger it). Such a row would be read as written over the form: nothing + * would be served for the name from the package (the closed reading), and no + * door of today refuses it where the package's form has left the `view` type. + * + * ⛔ Not an extension of ADR-0146 D11's close (`packagelessOverlayWriteRefusal`): + * it never asks the state of the base's pair or how many packages ship the + * name. A body that carries a FORM at the name is an old-shape write of the + * form and saves as before. The callers are the save door (beside the + * container name-collision refusal), the publish of a draft and the rollback + * to a version; a delete stores nothing and is not judged. + * + * `VALIDATION_ERROR` / `400`, the container name-collision refusal's envelope. + * The message names the form and the two saves that work whether or not the + * base has a pair; ⛔ it never prescribes a save under a name another stored + * row holds. + */ +export function packagelessListOverFormRefusal( + host: Pick, + type: string, + item: unknown, + saveName: string, + packageId: string | null | undefined, +): (Error & { code: 'VALIDATION_ERROR'; status: 400 }) | undefined { + if ((PLURAL_TO_SINGULAR[type] ?? type) !== 'view') return undefined; + if (!isPackageless(packageId)) return undefined; + if (!item || typeof item !== 'object' || Array.isArray(item)) return undefined; + for (const name of listNamesOf(host, type, item as Record, saveName)) { + for (const artifact of host.shippedArtifactsOf('form', name)) { + const owner = (artifact as { _packageId?: unknown } | null)?._packageId; + if (typeof owner !== 'string' || owner === '' || host.isWritablePackage(owner)) continue; + const err = new Error( + `Invalid view: it would store a list at '${name}', the name of the form the package '${owner}' ` + + `authors. Give the list another key, or save it into an app of the environment's own. A list and a ` + + `form of one name are two items, and a list stored here, bound to no package, would be read over ` + + `the package's form: nothing would be served for '${name}' from '${owner}'.`, + ) as Error & { code: 'VALIDATION_ERROR'; status: 400 }; + err.code = 'VALIDATION_ERROR'; + err.status = 400; + return err; + } + } + return undefined; +} + +/** The slug a form body's `sharing.publicLink` names, open or not, or `undefined`. */ +export function formHeldSlug(form: unknown): string | undefined { + const sharing = (form as { sharing?: unknown } | null)?.sharing; + const link = sharing && typeof sharing === 'object' ? (sharing as { publicLink?: unknown }).publicLink : undefined; + return typeof link === 'string' && link !== '' ? publicFormSlug(link) : undefined; +} + +/** + * [ADR-0159 ruled question 3 = A] Refuse a `form` write that leaves the form + * OPEN on a public address another form already holds, naming both forms. + * + * A form holds an address while its `sharing.publicLink` names it, switched on + * or off: a switched-off form that keeps its link still holds it. "Another + * form" is judged over the effective `form` read, so a projected old-shape + * form holding the slug counts. A write that leaves the form closed is never + * refused, so switching off either form of a clashing pair saves. ⛔ A + * refusal on the new type only: an old-shape `view` write keeps today's + * first-match behaviour. + * + * `409`, code {@link FORM_ADDRESS_TAKEN}. + */ +export async function formAddressClashRefusal( + host: FormReadHost, + type: string, + item: unknown, + name: string, + packageId: string | null | undefined, +): Promise<(Error & { code: typeof FORM_ADDRESS_TAKEN; status: 409 }) | undefined> { + if ((PLURAL_TO_SINGULAR[type] ?? type) !== 'form') return undefined; + if (!item || typeof item !== 'object' || Array.isArray(item)) return undefined; + const slug = anonymousFormIntakeSlug((item as { sharing?: unknown }).sharing); + if (slug === null) return undefined; + const pkg = isPackageless(packageId) ? undefined : packageId as string; + const forms = await readEffectiveForms(host, { type: 'form' }, 'execution'); + const holder = forms.find((form) => { + const f = form as { name?: unknown; _packageId?: unknown; overrides?: { package?: unknown } }; + if (formHeldSlug(form) !== slug) return false; + // The form being written is not "another form": its own address, the + // base it declares it overrides, and — written bound to no package — + // every address of its name it stands in for. + if (f.name === name) { + const formPkg = typeof f._packageId === 'string' && f._packageId !== '' ? f._packageId : undefined; + const declared = (item as { overrides?: { package?: unknown } }).overrides?.package; + if (formPkg === pkg || pkg === undefined || (typeof declared === 'string' && declared === formPkg)) return false; + } + return true; + }) as { name?: unknown; _packageId?: unknown } | undefined; + if (holder === undefined) return undefined; + const owner = typeof holder._packageId === 'string' && holder._packageId !== '' ? ` of the package '${holder._packageId}'` : ''; + const err = new Error( + `The form '${name}' cannot open the public address '/forms/${slug}': the form '${String(holder.name)}'${owner} ` + + `holds it. Give '${name}' another public link, or clear the link of '${String(holder.name)}' first. A form ` + + `holds an address while its public link names it, switched on or off.`, + ) as Error & { code: typeof FORM_ADDRESS_TAKEN; status: 409 }; + err.code = FORM_ADDRESS_TAKEN; + err.status = 409; + return err; +} + +/** One write the `form` door makes to the old-shape row carrying a form at its address. */ +export type OldShapeFormRowRemoval = + | { readonly kind: 'delete'; readonly row: { readonly name: string; readonly packageId: string | null } } + | { readonly kind: 'resave'; readonly row: { readonly name: string; readonly packageId: string | null }; readonly body: Record }; + +/** + * [ADR-0159 D5, card ② item 5] What a `form` save, reset or delete at + * `(packageId, name)` does to the stored old-shape row that carries that form + * at the same address (the same `package_id`): an item-shaped `view` row that + * carries the form is deleted; a stored container that expands it is re-saved + * without the member (its lists byte-equal). ⛔ Form content only: a `view` + * row that carries a LIST at the name is left untouched. + * + * `rows` are the active stored `view` rows at that address, parsed + * (`{ name, data }`); `expansionKeyOf` answers which `formViews` key (or the + * nested `form`) of a container expands to `name`. + */ +export function oldShapeFormRowRemovals( + rows: ReadonlyArray<{ name: string; data: unknown }>, + name: string, + packageId: string | null, +): OldShapeFormRowRemoval[] { + const out: OldShapeFormRowRemoval[] = []; + for (const row of rows) { + const body = row.data; + if (!body || typeof body !== 'object' || Array.isArray(body)) continue; + const projection = projectViewForms(body); + if (!projection.forms.some((form) => form.name === name)) continue; + if (!isAggregatedViewContainer(body)) { + out.push({ kind: 'delete', row: { name: row.name, packageId } }); + continue; + } + const container = body as Record; + const next: Record = { ...container }; + // Drop exactly the member that expands to `name`: re-project after + // each candidate removal, so the projection decides which one it is. + const without = (patch: Record) => projectViewForms({ ...container, ...patch }).forms.every((f) => f.name !== name); + let removed = false; + if (container.formViews && typeof container.formViews === 'object' && !Array.isArray(container.formViews)) { + for (const key of Object.keys(container.formViews as object)) { + const { [key]: _gone, ...rest } = container.formViews as Record; + if (without({ formViews: rest })) { + next.formViews = rest; + if (Object.keys(rest).length === 0) delete next.formViews; + removed = true; + break; + } + } + } + if (!removed && container.form !== undefined && without({ form: undefined })) { + delete next.form; + removed = true; + } + if (removed) out.push({ kind: 'resave', row: { name: row.name, packageId }, body: next }); + } + return out; +} + +/** + * [ADR-0159 D5, card ② item 5] Apply {@link oldShapeFormRowRemovals} at + * `(packageId, name)`: read the active stored `view` rows bound to exactly + * that package (`null`: the package-less ones), and delete or re-save the one + * that carries the form, through the repository the `form` write wrote with. + * Called INSIDE the `form` write's transaction, so a `form` write that fails + * leaves both rows as they were (the repository's own `withTxn` joins the + * ambient one, ADR-0067 D2). Returns the rows it changed, for the registry + * heal the caller runs once the transaction has committed. + */ +export async function applyOldShapeFormRowRemovals( + host: Pick, + args: { name: string; packageId: string | null; actor: string | null; source: string }, +): Promise { + const rows = await host.readActiveOverlayRows({ type: 'view' }); + const at: Array<{ name: string; data: unknown; hash: string | null }> = []; + for (const row of rows) { + if (((row?.package_id ?? null) || null) !== (args.packageId || null)) continue; + const entry = host.storedOverlayEntries({ type: 'view' }, [row])[0]; + if (entry === undefined) continue; + at.push({ name: entry.name, data: entry.data, hash: typeof row?.checksum === 'string' ? row.checksum : null }); + } + const removals = oldShapeFormRowRemovals(at, args.name, args.packageId); + if (removals.length === 0) return removals; + const repo = host.getOverlayRepo(); + for (const removal of removals) { + const stored = at.find((row) => row.name === removal.row.name); + const ref = { type: 'view', name: removal.row.name, org: 'env' } as Parameters[0]; + const intent = host.isArtifactBacked('view', removal.row.name) ? 'override-artifact' as const : 'runtime-only' as const; + const options = { + parentVersion: stored?.hash ?? null, + actor: args.actor, + source: args.source, + intent, + state: 'active' as const, + packageId: args.packageId, + }; + if (removal.kind === 'delete') await repo.delete(ref, options as Parameters[1]); + else await repo.put(ref, removal.body, options as Parameters[2]); + } + return removals; +} diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index d986866a4ca..07259a12217 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -23,6 +23,7 @@ * not move. */ +import { applyOldShapeFormRowRemovals, packagelessListOverFormRefusal, type OldShapeFormRowRemoval } from './protocol-form-writes.js'; import { stampHtmlPageRequires } from './runtime-authoring-gate.js'; import type { RuntimeAuthoringIssue, RuntimePendingDeclarations } from './runtime-authoring-gate.js'; import { DraftConflictError, packagelessAddressAmbiguityRefusal } from './sys-metadata-repository.js'; @@ -674,7 +675,7 @@ export class ProtocolHistoryAndPublishFacet { * `recordPendingDenialAudit`, rethrow. Skip it and the refusal is silent * again — the pre-#7748 state, not merely a worse one. */ - static async promoteDraftForPublish(host: Pick, request: { + static async promoteDraftForPublish(host: Pick, request: { type: string; name: string; actor?: string; message?: string; /** * [#8907] ADR-0048 — the package binding of the draft being promoted, @@ -1116,6 +1117,18 @@ export class ProtocolHistoryAndPublishFacet { ); if (nameCollision) throw nameCollision; } + // [ADR-0159 card ② item 5] …and a package-less view draft that would + // store a list at the name a read-only package authors as a `form`: + // the save door refuses that body (`VALIDATION_ERROR`, 400), and a + // draft saved before the gate is refused here with the same sentence + // before `repo.promoteDraft` writes. See + // {@link packagelessListOverFormRefusal}. + if (draftForGate) { + const listOverForm = packagelessListOverFormRefusal( + host, singularType, draftForGate.body, request.name, promoteInto, + ); + if (listOverForm) throw listOverForm; + } // [#28905, ADR-0146 D1, D11] …and the promotion INTO the read-only // base itself, of an item of one of the five overlay types it ships: // the active row it writes is bound to the base, outside the pair D1 @@ -1357,7 +1370,27 @@ export class ProtocolHistoryAndPublishFacet { }); expectedActiveHash = await host.storedParentForToken(ref, request.parentVersion, activeHead.head?.hash ?? null); } - const result = await repo.promoteDraft(ref, { + // [ADR-0159 D5, card ② item 5] A `form` made active here removes + // the promoted-into package's old-shape row of the name in the + // same transaction, as the published save does + // ({@link applyOldShapeFormRowRemovals}); the registry is healed + // after the commit. ⛔ Form content only. + let removedOldShapeRows: OldShapeFormRowRemoval[] = []; + const promoteFormAware = async (promote: () => Promise): Promise => { + if (singularType !== 'form' || request.judgeOnly) return promote(); + const run = async () => { + const promoted = await promote(); + removedOldShapeRows = await applyOldShapeFormRowRemovals(host, { + name: request.name, + packageId: promoteInto, + actor: request.actor ?? null, + source: 'protocol.publishMetaItem', + }); + return promoted; + }; + return typeof host.engine?.transaction === 'function' ? host.engine.transaction(run) : run(); + }; + const result = await promoteFormAware(() => repo.promoteDraft(ref, { deriveActiveBody: (draftBody) => stampHtmlPageRequires(singularType, draftBody, sduiManifest), // #4556 — NULL, not 'system', for an actor-less publish. actor: request.actor ?? null, @@ -1389,7 +1422,17 @@ export class ProtocolHistoryAndPublishFacet { ...(expectedActiveHash !== undefined ? { expectedActiveHash } : {}), // [#22877] …of the member that was judged. ...memberOption(request.member), - }); + })); + for (const removal of removedOldShapeRows) { + if (removal.kind === 'delete') { + await host.restoreArtifactRegistryView('view', removal.row.name, null, removal.row.packageId); + } else { + await host.applyRegistryWriteThrough({ + type: 'view', name: removal.row.name, item: removal.body, + packageId: removal.row.packageId, organizationId: null, + }); + } + } return { singularType, advisories: runtimeAdvisories, diff --git a/packages/metadata-protocol/src/protocol-meta-item-reads.ts b/packages/metadata-protocol/src/protocol-meta-item-reads.ts index e45ab949c25..059878f2e01 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-reads.ts @@ -50,6 +50,7 @@ import { } from './protocol-bundle-members.js'; import { packagelessContentPackage } from './protocol-environment-rows.js'; import type { ProtocolHost } from './protocol-host.js'; +import { readEffectiveForms, type FormReadHost } from './protocol-form-reads.js'; import { admitExactQualifier, declinedCopyReplaced, @@ -642,7 +643,7 @@ export async function judgeDroppedServiceRefusal( } /** The body of `ObjectStackProtocolImplementation#getMetaItem`; the method's docblock there is its contract. */ -export async function getMetaItem(host: Pick, request: { +export async function getMetaItem(host: Pick & FormReadHost, request: { type: string, name: string, packageId?: string, state?: 'active' | 'draft', previewDrafts?: boolean, /** [#22877] The bundle member to read — {@link resolveBundleMemberSelector}; omitted, the canonical one. */ member?: string, @@ -652,6 +653,13 @@ export async function getMetaItem(host: Pick host.readMetaItemFace(canonical, 'served')); } +/** + * [ADR-0159 D5] The active by-name `form` read: the generic read's answer + * (its envelope, lock and trailers), with the item the effective `form` list + * serves at the address ({@link readEffectiveForms}). Naming a package, that + * package's item; naming none, the item the generic read chose when the list + * serves it, else the list's first item of the name. When the list serves no + * item of the name at the address (the closed reading), no `item` is served, + * which both transports answer `404`. + */ +async function readEffectiveFormItem( + host: Pick & FormReadHost, + request: { type: string; name: string; packageId?: string; member?: string; userTextLocales?: readonly string[] }, +): Promise { + const generic: any = await host.readMetaItemFace(request, 'served'); + const listed = await readEffectiveForms(host, { + type: 'form', + names: [request.name], + ...(request.packageId !== undefined ? { packageId: request.packageId } : {}), + }, 'served'); + const pkgOf = (item: unknown): unknown => (item as { _packageId?: unknown } | null)?._packageId; + const genericItem = generic?.item; + const served = listed.find((item) => genericItem !== undefined && pkgOf(item) === pkgOf(genericItem)) ?? listed[0]; + if (served === undefined) { + if (generic === null || typeof generic !== 'object') return generic; + const { item: _item, ...rest } = generic; + return rest; + } + return { ...(generic && typeof generic === 'object' ? generic : { type: 'form', name: request.name }), item: served }; +} + /** The body of `ObjectStackProtocolImplementation#getMetaItemForExecution`; the method's docblock there is its contract. */ export async function getMetaItemForExecution(host: Pick, request: { type: string, name: string, packageId?: string, state?: 'active' | 'draft', previewDrafts?: boolean, diff --git a/packages/metadata-protocol/src/protocol-meta-list-reads.ts b/packages/metadata-protocol/src/protocol-meta-list-reads.ts index f234a68b0ce..35b51582a7c 100644 --- a/packages/metadata-protocol/src/protocol-meta-list-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-list-reads.ts @@ -34,6 +34,7 @@ import { } from './protocol-authoring-refusals.js'; import { shippingPackageIds } from './protocol-environment-rows.js'; import type { ProtocolHost } from './protocol-host.js'; +import { readEffectiveForms, type FormReadHost } from './protocol-form-reads.js'; import { canonicalizeMetaRequestType } from './protocol-meta-type-schema.js'; import { mergePackageAwareOverlay, servedViewExpansion, withoutServedRowName } from './protocol-overlay-merge.js'; import { @@ -60,7 +61,7 @@ import { } from './protocol-exact-qualifier.js'; /** The body of `ObjectStackProtocolImplementation#getMetaItems`; the method's docblock there is its contract. */ -export async function getMetaItems(host: Pick, request: { type: string; packageId?: string; names?: readonly string[]; previewDrafts?: boolean }) { +export async function getMetaItems(host: FormReadHost, request: { type: string; packageId?: string; names?: readonly string[]; previewDrafts?: boolean }) { // #4432 — CANONICAL TYPE KEY. See {@link canonicalMetaType}. This one // is load-bearing twice over: the SchemaRegistry indexes code-authored // items under the SINGULAR type, and the overlay-hydration branch below @@ -71,13 +72,24 @@ export async function getMetaItems(host: Pick, request: { type: string; packageId?: string; previewDrafts?: boolean }) { +export async function getMetaItemsForExecution(host: FormReadHost, request: { type: string; packageId?: string; previewDrafts?: boolean }) { // The same #4432 fold {@link getMetaItems} applies, for the same reason. - return host.readFlattenedMetaItems(canonicalizeMetaRequestType(request), 'execution'); + const canonical = canonicalizeMetaRequestType(request); + if (canonical.type === 'form') { + const list = await host.readFlattenedMetaItems(canonical, 'execution'); + return { ...list, items: await readEffectiveForms(host, canonical, 'execution') }; + } + return host.readFlattenedMetaItems(canonical, 'execution'); } /** The body of `ObjectStackProtocolImplementation#getMetaItemsPerPackage`; the method's docblock there is its contract. */ diff --git a/packages/metadata-protocol/src/protocol-packaged-base-refusal.ts b/packages/metadata-protocol/src/protocol-packaged-base-refusal.ts index c4b487140cc..71bbd31be11 100644 --- a/packages/metadata-protocol/src/protocol-packaged-base-refusal.ts +++ b/packages/metadata-protocol/src/protocol-packaged-base-refusal.ts @@ -35,6 +35,7 @@ * re-exports this module, so the published surface does not move. */ +import { projectViewForms } from '@objectstack/spec/ui'; import type { ObjectStackProtocolImplementation } from './protocol.js'; import { isOriginGatedType, @@ -1420,8 +1421,8 @@ export function overrideWriteVerdict( || overrideWriteActionObjectOf(a) === overrideWriteActionObjectOf(request.item); const shippers = dependencies === undefined || dependencies.length === 0 ? [] - : Array.from(new Set( - this.shippedArtifactsOf(request.type, request.name, undefined, member) + : Array.from(new Set([ + ...this.shippedArtifactsOf(request.type, request.name, undefined, member) .filter((a) => overrideWriteMemberOf(request.type, a) === member && onItsObject(a)) .map((a) => (a as { _packageId?: unknown } | null | undefined)?._packageId) // An override replaces an item of an INSTALLED, read-only base @@ -1431,7 +1432,19 @@ export function overrideWriteVerdict( // (`registerApp` → `manifests`), so this keeps no real base out. .filter((id): id is string => typeof id === 'string' && dependencies.includes(id) && !this.isWritablePackage(id)), - )); + // [ADR-0159 D4, D7-b] …and, for a `form`, a base that ships the form + // as an OLD SHAPE: the `view` artifacts of the name read through the + // projection (the expanded `viewKind: 'form'` items a container + // registers, a form `view` item). Until card ④ every first-party form + // is an old shape, and its `form` override switches it off. + ...((PLURAL_TO_SINGULAR[request.type] ?? request.type) === 'form' + ? this.shippedArtifactsOf('view', request.name) + .filter((a) => projectViewForms(a).forms.some((form) => form.name === request.name)) + .map((a) => (a as { _packageId?: unknown } | null | undefined)?._packageId) + .filter((id): id is string => typeof id === 'string' && dependencies.includes(id) + && !this.isWritablePackage(id)) + : []), + ])); // [#30065] The base's own item, the one a declared action override is // judged against: the shipping artifact under that base's envelope. const baseItemOf = (basePackageId: string): unknown => this.shippedArtifactsOf(request.type, request.name, undefined, member) diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index 6c4d09bb3b0..2f53e61780f 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -23,6 +23,7 @@ * not move. */ +import { applyOldShapeFormRowRemovals, formAddressClashRefusal, packagelessListOverFormRefusal, type OldShapeFormRowRemoval } from './protocol-form-writes.js'; import { MetadataAuthoringSurfaceSchema } from '@objectstack/spec/api'; import { stampHtmlPageRequires } from './runtime-authoring-gate.js'; import { SysMetadataRepository, actionCustomizationHoldersOf, actionHeldOnlyOnOtherObjects, actionRowsBindingObjectOf, isPackageBoundRow, packagelessAddressAmbiguityRefusal } from './sys-metadata-repository.js'; @@ -340,7 +341,7 @@ export class ProtocolSaveFacet { } /** [#28355] The body of {@link saveMetaItem} before its refusal audit; that method's docblock is the contract. */ - static async saveMetaItemUnaudited(host: Pick, request: SaveMetaItemRequest) { + static async saveMetaItemUnaudited(host: Pick, request: SaveMetaItemRequest) { // [ADR-0131 D6] FIRST, before every other gate and every read: an // organization-scoped write is refused for every type, draft or // publish. See {@link organizationScopedWriteRefusal}. @@ -1486,6 +1487,26 @@ export class ProtocolSaveFacet { ); if (containerCollision) throw containerCollision; } + // [ADR-0159 D5, card ② item 5] …and a package-less `view` write + // that would store a LIST at a name a read-only package authors + // as a `form` item, with the same envelope. See + // {@link packagelessListOverFormRefusal}. + { + const listOverForm = packagelessListOverFormRefusal( + host, singularType, request.item, request.name, request.packageId, + ); + if (listOverForm) throw listOverForm; + } + // [ADR-0159 ruled question 3 = A] …and a `form` that would be left + // open on a public address another form holds (the effective + // `form` read, projected old shapes included), `409` + // `FORM_ADDRESS_TAKEN`. See {@link formAddressClashRefusal}. + { + const clash = await formAddressClashRefusal( + host, singularType, request.item, request.name, request.packageId, + ); + if (clash) throw clash; + } let baseline: unknown; if ((PLURAL_TO_SINGULAR[request.type] ?? request.type) === 'view' && typeof host.engine.registry?.getItem === 'function') { @@ -2281,8 +2302,28 @@ export class ProtocolSaveFacet { }); } } + // [ADR-0159 D5, card ② item 5] A published `form` write also removes + // the old-shape row that carries the form at its address, in the same + // transaction (the repository's `put` joins it): a `form` write that + // fails leaves both rows as they were. ⛔ Form content only. + const formRowRemoval = mode === 'publish' && singularTypeForRepo === 'form'; + let removedOldShapeRows: OldShapeFormRowRemoval[] = []; + const putFormAware = async (put: () => Promise): Promise => { + if (!formRowRemoval) return put(); + const run = async () => { + const written = await put(); + removedOldShapeRows = await applyOldShapeFormRowRemovals(host, { + name: request.name, + packageId: request.packageId ?? null, + actor: request.actor ?? null, + source: writeSource ?? 'protocol.saveMetaItem', + }); + return written; + }; + return typeof host.engine?.transaction === 'function' ? host.engine.transaction(run) : run(); + }; try { - const result = await repo.put(ref, request.item, { + const result = await putFormAware(() => repo.put(ref, request.item, { parentVersion, // #4556 — `actor` lands in `sys_metadata_history.recorded_by`, // a lookup('sys_user'). No caller actor → NULL, never the @@ -2303,7 +2344,19 @@ export class ProtocolSaveFacet { ...(request.client !== undefined ? { draftChangesClient: authoringClientOf(request.client) } : {}), } : {}), - }); + })); + // [ADR-0159 D5] The registry heal of each old-shape row the write + // removed or re-saved, after the commit. + for (const removal of removedOldShapeRows) { + if (removal.kind === 'delete') { + await host.restoreArtifactRegistryView('view', removal.row.name, null, removal.row.packageId); + } else { + await host.applyRegistryWriteThrough({ + type: 'view', name: removal.row.name, item: removal.body, + packageId: removal.row.packageId, organizationId: null, + }); + } + } // Persistence succeeded — NOW it's safe to mutate the // in-memory registry. If put() had thrown, the registry // would still reflect the prior state. Drafts are NOT diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index c672534b9fe..1856228b5ee 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -1,5 +1,8 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. +import { packagelessListOverFormRefusal } from './protocol-form-writes.js'; +import { readUnreadableFormBodies } from './protocol-form-reads.js'; +import type { UnreadableFormBody } from '@objectstack/spec/ui'; import type { DataProtocol, FlowRegistration, @@ -1623,6 +1626,11 @@ export class ObjectStackProtocolImplementation implements private restoredBodyWriter(type: string, name: string, binding: string | null, source: string): (historyBody: unknown) => Promise { // [#25467 cut 8] The body moved to `protocol-authoring-gate.ts` (see `AuthoringGateHost`). const host: ThisParameterType = { + listOverFormRefusal: (t, item, n, binding) => packagelessListOverFormRefusal({ + expandRuntimeViewContainer: (...a) => this.expandRuntimeViewContainer(...a), + isWritablePackage: (...a) => this.isWritablePackage(...a), + shippedArtifactsOf: (...a) => this.shippedArtifactsOf(...a), + }, t, item, n, binding), objectExtensionItemRefusal: (...a) => this.objectExtensionItemRefusal(...a), refuseRestoredBodyTheSaveDoorRefuses: (...a) => this.refuseRestoredBodyTheSaveDoorRefuses(...a), restoredBodyDerivation: (...a) => this.restoredBodyDerivation(...a), @@ -3523,6 +3531,17 @@ export class ObjectStackProtocolImplementation implements return getMetaItemsPerPackage(protocolHost(this), request); } + /** + * [ADR-0159 D6 rule 7] The stored `view` bodies the `form` projection + * cannot read, each with the public links it names: the anonymous form + * doors close every one of those links (a server-only extension the doors + * feature-detect). Each such row is said once at `error`, naming the row, + * the links and the repair save. See `readUnreadableFormBodies`. + */ + async getUnreadableFormBodies(): Promise { + return readUnreadableFormBodies(protocolHost(this)); + } + /** * [#28411, ADR-0146 D8 item 4] The served overrides of a base package's * items: each ACTIVE row of its paired `.custom` package that diff --git a/packages/metadata-protocol/src/runtime-authoring-gate.ts b/packages/metadata-protocol/src/runtime-authoring-gate.ts index 649cdcd04e1..2c3c4b2b246 100644 --- a/packages/metadata-protocol/src/runtime-authoring-gate.ts +++ b/packages/metadata-protocol/src/runtime-authoring-gate.ts @@ -86,6 +86,7 @@ import { findHierarchyScopeGrants, type TenancyPosture } from '@objectstack/spec // location and in the words the admin read uses. import { anonymousFormIntakeCandidates, + anonymousFormIntakeSlug, anonymousFormIntakeUnavailability, anonymousFormIntakeUnavailableMessage, anonymousFormIntakeUnavailableRemedy, @@ -430,7 +431,31 @@ export function findPublicFormIntakeGaps(args: { /** The tenancy posture IN FORCE (`anonymousFormIntakePosture`); absent = no tenancy service. */ tenancyPostureInForce?: TenancyPosture; }): RuntimeAuthoringIssue[] { - if (args.type !== 'view' || !isRec(args.body)) return []; + if (!isRec(args.body)) return []; + // [ADR-0159 D6 rule 9] A `form` write is judged as the same form in a + // `view` write is: the form itself is its one candidate, at `forms[0]`. + if (args.type === 'form') { + const form = args.body; + const slug = anonymousFormIntakeSlug(form.sharing); + const object = typeof form.object === 'string' && form.object ? form.object : undefined; + if (slug === null || object === undefined) return []; + const unavailable = anonymousFormIntakeUnavailability( + object, + args.tenancyPostureInForce, + (): unknown => args.objects.find((o) => isRec(o) && o.name === object), + ); + if (!unavailable) return []; + const formName = typeof form.name === 'string' && form.name ? form.name : args.name; + return [{ + severity: 'warning', + rule: PUBLIC_FORM_INTAKE_UNAVAILABLE, + where: `form "${formName}" · public form "/forms/${slug}"`, + path: 'forms[0].sharing', + message: anonymousFormIntakeUnavailableMessage(slug, unavailable), + hint: anonymousFormIntakeUnavailableRemedy(unavailable), + }]; + } + if (args.type !== 'view') return []; const view = args.body; const candidates = anonymousFormIntakeCandidates(view); if (candidates.length === 0) return []; @@ -1642,7 +1667,7 @@ export function evaluateRuntimeAuthoringGate(args: { const rulesRun = [ ...result.rulesRun, ...(args.type === 'flow' ? [FLOW_UNDECLARED_CYCLE, PLATFORM_SCHEDULE_CREATE_RECORD_ORG_MISSING] : []), - ...(args.type === 'view' ? [PUBLIC_FORM_INTAKE_UNAVAILABLE] : []), + ...(args.type === 'view' || args.type === 'form' ? [PUBLIC_FORM_INTAKE_UNAVAILABLE] : []), ...(args.type === 'permission' && args.hierarchyResolverMounted !== undefined ? [HIERARCHY_SCOPE_CAPABILITY_REQUIRED] : []), diff --git a/packages/metadata/src/plugin.ts b/packages/metadata/src/plugin.ts index 2ed3bb25088..d6a4f5122fa 100644 --- a/packages/metadata/src/plugin.ts +++ b/packages/metadata/src/plugin.ts @@ -134,6 +134,7 @@ const ARTIFACT_FIELD_TO_TYPE: Record = { objectExtensions: 'object_extension', apps: 'app', views: 'view', + forms: 'form', pages: 'page', dashboards: 'dashboard', reports: 'report', diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index 51660e8dd0f..e21c7da4222 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -4530,7 +4530,7 @@ const METADATA_ARRAY_KEYS = [ // name instead of registering as items of their own. 'picklists', 'picklistExtensions', // UI Protocol - 'actions', 'views', 'pages', 'dashboards', 'reports', 'datasets', 'themes', + 'actions', 'views', 'forms', 'pages', 'dashboards', 'reports', 'datasets', 'themes', // Automation Protocol 'flows', 'workflows', 'approvals', 'webhooks', 'jobs', diff --git a/packages/rest/src/form-routes.ts b/packages/rest/src/form-routes.ts index 8e7901ca4b9..ae0737b5bfd 100644 --- a/packages/rest/src/form-routes.ts +++ b/packages/rest/src/form-routes.ts @@ -76,7 +76,14 @@ 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 { thankYouRecordFieldNames } from '@objectstack/spec/ui'; +import { + PROJECTED_FORM_SOURCE_KEY, + formIntakeLayer, + openFormAt, + thankYouRecordFieldNames, + type FormIntakeLayer, + type UnreadableFormBody, +} from '@objectstack/spec/ui'; import { validationFailure } from '@objectstack/types'; import { FILE_REFERENCE_TYPES, RUNTIME_OWNED_FIELD_TYPES } from '@objectstack/spec/data'; import type { ServerScopedDataRequest } from './data-action-routes.js'; @@ -158,6 +165,23 @@ function thankYouAnswerFields( * server as `this`. The method's own docblock, which the published declaration * carries, names the two routes and what authorizes them. */ +/** + * [ADR-0159 D2] The body of a `form` item the doors serve as the form: the + * item without its envelope (its identity, its label — served beside the form + * — its override declaration and protection, and every `_` envelope key), so + * an authored `form` is answered in the shape an old-shape form is. + */ +function formBodyOf(item: unknown): any { + if (!item || typeof item !== 'object') return item; + const body: Record = {}; + for (const [key, value] of Object.entries(item as Record)) { + if (key.startsWith('_') || key === 'name' || key === 'object' || key === 'label' + || key === 'overrides' || key === 'protection') continue; + body[key] = value; + } + return body; +} + export function registerFormEndpoints(this: FormRouteHost, basePath: string): void { const isScoped = basePath.includes('/environments/:environmentId'); @@ -189,22 +213,49 @@ 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. - const findPublicFormView = ( + // [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 + // 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 + // whole item (rule 6), so a same-name withdrawal closes the form whatever + // slug either side declares; a definition under another name is a + // 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. + const findPublicForm = ( + forms: any[], views: any[], - withdrawalLayer: any[], + layer: FormIntakeLayer, slug: string, - ): { view: any; form: any; object: string } | null => { - for (const view of views ?? []) { - if (!view || typeof view !== 'object') continue; - for (const c of anonymousFormIntakeCandidates(view)) { - if (c.slug !== slug) continue; - if (anonymousFormIntakeWithdrawnIn(withdrawalLayer, view, c)) continue; + ): { view: any; 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' || view.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) continue; - return { view, form: c.form, object: objectName }; + if (objectName !== open.object) continue; + return { view, form: c.form, object: objectName, formItem: item }; } } - return null; + // 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 }; }; // [ADR-0131 D6, C7] WHICH metadata an anonymous form request reads: @@ -236,7 +287,7 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo environmentId: string | undefined, req: any, slug: string, - ): Promise<{ view: any; form: any; object: string } | null> => { + ): Promise<{ view: any; 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); @@ -249,15 +300,27 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo : Array.isArray(result) ? result : []); - const items = listOf(await p.getMetaItems(viewsRequest)); - // [#28409] The per-package layer, where the protocol serves one: a + const formsRequest: TransportScopedMetaRequest = { ...viewsRequest, type: 'form' }; + const views = listOf(await p.getMetaItems(viewsRequest)); + const forms = typeof (p as any).getMetaItems === 'function' ? listOf(await p.getMetaItems(formsRequest)) : []; + // [#28409] The per-package layers, where the protocol serves them: a // server-only extension, feature-detected like the other extensions // the doors read. A protocol without it serves no narrower list than // the one it lists, which is then the whole layer. - const perPackage = typeof (p as any).getMetaItemsPerPackage === 'function' - ? listOf(await (p as any).getMetaItemsPerPackage(viewsRequest)) + const perPackage = async (request: TransportScopedMetaRequest): Promise => + (typeof (p as any).getMetaItemsPerPackage === 'function' + ? listOf(await (p as any).getMetaItemsPerPackage(request)) + : []); + // [ADR-0159 D6 rule 7] …and the stored bodies the projection cannot read. + const unreadable: UnreadableFormBody[] = typeof (p as any).getUnreadableFormBodies === 'function' + ? await (p as any).getUnreadableFormBodies() : []; - const match = findPublicFormView(items, [...items, ...perPackage], slug); + const layer = formIntakeLayer({ + forms: [...forms, ...(await perPackage(formsRequest))], + views: [...views, ...(await perPackage(viewsRequest))], + unreadable, + }); + const match = findPublicForm(forms, views, 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 @@ -329,7 +392,7 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo // view 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?.label ?? match.form?.label; + let servedLabel: any = match.view !== undefined ? (match.view?.label ?? match.form?.label) : match.formItem?.label; try { const p = await this.resolveProtocol(environmentId, req); if (typeof (p as any).getMetaItems === 'function') { @@ -435,15 +498,30 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo // reads ask, of the view as the protocol served it // (its envelope names the base). `undefined` keeps // the override's own text, as before. - 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; + 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; + } } } } catch (e: any) { diff --git a/packages/rest/src/meta-item-read-gate.ts b/packages/rest/src/meta-item-read-gate.ts index fae5b4840e6..0bfde0bdf4e 100644 --- a/packages/rest/src/meta-item-read-gate.ts +++ b/packages/rest/src/meta-item-read-gate.ts @@ -1815,6 +1815,23 @@ export function createMetaItemReadGate( }; } + if (metaType === 'form') { + // [ADR-0159, card ② item 2] A `form` item's audience: the form's own + // `requiredPermissions` (a projected item carries its view item's gate + // too, `projectViewForms`). A caller refused a form's document at + // `/meta/view/NAME` is refused it at `/meta/form/NAME`, whole. + return async (document) => { + if (document == null) return serve(document); + const ctx = await resolveCallerOnce(); + const sysPerms = callerSystemPermissions(ctx); + if (!sysPerms) return serve(document); + if (!holdsRequiredPermissions((document as any).requiredPermissions, sysPerms)) { + return refuse(await audienceRefusal(sources, ctx)); + } + return serve(document); + }; + } + if (metaType === 'object') { // [#22639] An object's own `listViews` — see {@link filterObjectListViewsForUser}. return async (document) => { @@ -1995,6 +2012,19 @@ export function createMetaListReadGate( }; } + if (metaType === 'form') { + // [ADR-0159] The list face of the `form` arm above: a form the caller + // does not hold is left out. + return async (items) => { + if (items.length === 0) return items; + const sysPerms = callerSystemPermissions(await sources.resolveCaller()); + if (!sysPerms) return items; + const kept = items.filter((it: any) => !it || typeof it !== 'object' + || holdsRequiredPermissions(it.requiredPermissions, sysPerms)); + return kept.length === items.length ? items : kept; + }; + } + if (metaType === 'object') { return async (items) => { if (items.length === 0) return items; diff --git a/packages/rest/src/public-form-two-type-withdrawal.test.ts b/packages/rest/src/public-form-two-type-withdrawal.test.ts new file mode 100644 index 00000000000..72c92cd5fbc --- /dev/null +++ b/packages/rest/src/public-form-two-type-withdrawal.test.ts @@ -0,0 +1,467 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0159 D6, card ② "Done when"] The anonymous form doors read a form over + * BOTH metadata types — the `form` item and the three old `view` shapes, the + * latter through ONE projection — and a withdrawal in either type, in any + * layer, closes the form in both (narrowing only, in both directions). + * + * Every pin runs the REAL protocol over a real `ObjectQL` engine and a real + * SQL store (as `public-form-withdrawal-effective-read.test.ts` does): the + * base ships through `registerApp`, the pair and the dependent package are + * installed through the package door, and their rows are written through the + * draft save and the per-item publish. A row the save door refuses today (a + * dependent package's row under a base's name; a `view` override over a base + * that authors the name as a `form` item) is a row stored before that gate: + * the gate's verdict is held at `not_concerned` for that one write. + * + * Each pin asserts the refusal's status and `code` on BOTH doors and that no + * record was written. The ablation each pin names was run by hand (remove the + * named read, watch the pin turn red, restore) and is recorded on the PR. + */ +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } 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.forms37086'; +const PAIR = `${BASE}.custom`; +const DEPENDENT = 'com.default.acme-forms37086'; +const OBJECT = 'ftt_inquiry'; +const NAME = `${OBJECT}.contact`; +const SLUG = 'contact-37086'; +const OTHER_SLUG = 'elsewhere-37086'; + +const sharing = (open: boolean, slug = SLUG) => ({ enabled: true, allowAnonymous: open, publicLink: `/forms/${slug}` }); +const body = (open: boolean | null, slug = SLUG) => ({ + type: 'simple', + sections: [{ fields: ['name', 'email'] }], + ...(open === null ? {} : { sharing: sharing(open, slug) }), +}); + +/** An authored `form` item at {@link NAME}. */ +const formItem = (open: boolean | null, extra: Record = {}, slug = SLUG) => ({ + name: NAME, object: OBJECT, label: 'Contact us', ...body(open, slug), ...extra, +}); +/** An old-shape `viewKind: 'form'` item at {@link NAME}. */ +const viewItem = (open: boolean | null, extra: Record = {}, slug = SLUG) => ({ + name: NAME, object: OBJECT, viewKind: 'form', label: 'Contact us', + config: { ...body(open, slug), data: { provider: 'object', object: OBJECT } }, + ...extra, +}); +/** An old-shape container whose `formViews.contact` expands to {@link NAME}. */ +const container = (open: boolean | null) => ({ + object: OBJECT, + formViews: { contact: { ...body(open), data: { provider: 'object', object: OBJECT } } }, +}); +const overrides = { overrides: { package: BASE, basedOn: '1.0.0' } }; + +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, + 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 } + +async function boot(ships: { forms?: unknown[]; views?: unknown[] }) { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any); + const engine = new ObjectQL(); + 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: 'forms37086', + version: '1.0.0', + namespace: 'ftt', + objects: [INQUIRY], + ...(ships.forms ? { forms: ships.forms } : {}), + ...(ships.views ? { views: ships.views } : {}), + } 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) => { + const found = rest.getRoutes().find((r: any) => r.method === method && r.path === path); + expect(found, `${method} ${path} is registered`).toBeDefined(); + return found!; + }; + const resolve = route('GET', '/api/v1/forms/:slug'); + const submit = route('POST', '/api/v1/forms/:slug/submit'); + const get = async (slug = SLUG): Promise => { + const res = makeRes(); + await resolve.handler({ params: { slug }, query: {}, headers: {} } as any, res); + return { status: res._status ?? 200, body: res._json }; + }; + const post = async (slug = SLUG): Promise => { + const res = makeRes(); + await submit.handler({ params: { 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 any)) as unknown[]).length; + const install = async (id: string) => protocol.installPackage({ + manifest: { + id, name: id.split('.').join('-'), version: '0.1.0', type: 'app', + ...(id === PAIR ? { namespace: 'ftt_custom', dependencies: { [BASE]: '^1' } } : { dependencies: { [BASE]: '*' } }), + }, + }); + const saveInto = async (type: 'view' | 'form', packageId: string | undefined, item: Record, name = NAME) => { + await protocol.saveMetaItem({ type, name, item, mode: 'draft', ...(packageId ? { packageId } : {}) }); + await protocol.publishMetaItem({ type, name, ...(packageId ? { packageId } : {}) }); + }; + /** A write the override gate refuses today, stored as a pre-gate save left it. */ + const saveBeforeTheGate = async (type: 'view' | 'form', packageId: string | undefined, item: Record, name = NAME) => { + protocol.overrideWriteVerdict = () => ({ verdict: 'not_concerned' }); + try { + await saveInto(type, packageId, item, name); + } finally { + delete protocol.overrideWriteVerdict; + } + }; + /** A stored row as it exists at rest, written past every door (a body no door admits). */ + 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 } } as any); + }; + return { engine, protocol, get, post, records, install, saveInto, saveBeforeTheGate, seedRow }; +} + +type Booted = Awaited>; +const answered = (a: Answer) => [a.status, a.body?.code]; + +/** Both doors refuse with `404 FORM_NOT_FOUND`, and nothing was written. */ +async function closedOnBothDoors(b: Booted, slug = SLUG) { + const before = await b.records(); + expect(answered(await b.get(slug))).toEqual([404, 'FORM_NOT_FOUND']); + expect(answered(await b.post(slug))).toEqual([404, 'FORM_NOT_FOUND']); + expect(await b.records()).toBe(before); +} + +/** + * Both doors match the form: the resolve door serves it, and the submit door + * gets past the match (the tenancy intake rule, which runs after the match, + * answers for this bare fixture — ADR-0159 D6 rule 8). + */ +async function openOnBothDoors(b: Booted, slug = SLUG) { + const served = await b.get(slug); + expect(served.status, JSON.stringify(served.body)).toBe(200); + expect(answered(await b.post(slug))).not.toEqual([404, 'FORM_NOT_FOUND']); +} + +describe('[ADR-0159 D6] the form doors read both types: a withdrawal in either closes the form in both', () => { + const engines: ObjectQL[] = []; + 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(() => {}); + }); + const booted = async (ships: { forms?: unknown[]; views?: unknown[] }): Promise => { + const b = await boot(ships); + engines.push(b.engine); + return b; + }; + + it('CONTROL: an authored `form` item open in the base is served on both doors', async () => { + const b = await booted({ forms: [formItem(true)] }); + const forms = ((await b.protocol.getMetaItems({ type: 'form' })).items as any[]).filter((f) => f?.name === NAME); + expect(forms.map((f) => [f._packageId, f.sharing?.allowAnonymous])).toEqual([[BASE, true]]); + await openOnBothDoors(b); + }); + + it('CONTROL: an old-shape form open in the base is served on both doors, and read as a `form` item', async () => { + const b = await booted({ views: [container(true)] }); + const forms = ((await b.protocol.getMetaItems({ type: 'form' })).items as any[]).filter((f) => f?.name === NAME); + expect(forms.map((f) => [f._packageId, f.object, f._formDefinedIn])).toEqual([[BASE, OBJECT, 'view']]); + await openOnBothDoors(b); + }); + + it('pin 1 — withdrawn by a `view` override in `.custom`, open as an authored `form` item: closed (ablate: the `view` half of the layer)', async () => { + const b = await booted({ forms: [formItem(true)] }); + await b.install(PAIR); + await b.saveBeforeTheGate('view', PAIR, viewItem(false, overrides)); + await closedOnBothDoors(b); + }); + + it('pin 2 — the mirror: withdrawn by a `form` override, open as an old-shape item in the base (ablate: the `form` half)', async () => { + const b = await booted({ views: [container(true)] }); + await b.install(PAIR); + await b.saveInto('form', PAIR, formItem(false, overrides)); + await closedOnBothDoors(b); + }); + + it('pin 3 — withdrawn in a container\'s `formViews` entry, open as a `form` item named for the expansion (ablate: the projection step)', async () => { + // One package authors both: an old-shape container whose `formViews.contact` + // withdraws the form, and an open `form` item under the name that entry + // expands to. The authored item shadows the projection for what is SERVED; + // it never removes the withdrawal (rule 5). + const b = await booted({ forms: [formItem(true)], views: [container(false)] }); + await closedOnBothDoors(b); + }); + + it('pin 4 — withdrawn in a body of the same name whose link names another slug: closed at the open definition\'s address (ablate: the whole-item match)', async () => { + // The open definition is the base's old-shape form at SLUG; the effective + // lists serve it alone. A dependent package's row of the same name keeps + // its link on ANOTHER slug, switched off: the body of the name withdraws + // the form, whatever slug it points at (rule 6). + const b = await booted({ views: [container(true)] }); + await b.install(DEPENDENT); + await b.saveBeforeTheGate('view', DEPENDENT, viewItem(false, {}, OTHER_SLUG)); + const effective = ((await b.protocol.getMetaItems({ type: 'form' })).items as any[]).filter((f) => f?.name === NAME); + expect(effective.map((f) => [f._packageId, f.sharing?.publicLink, f.sharing?.allowAnonymous])).toEqual([[BASE, `/forms/${SLUG}`, true]]); + await closedOnBothDoors(b); + }); + + it.each(['form', 'view'] as const)('pin 5 — a per-package-layer withdrawal in `%s` closes the form (ablate: getMetaItemsPerPackage for that type)', async (type) => { + // The base ships the name in the withdrawing row's own type, so the + // effective list of that type serves the base's document alone and the + // dependent's row sits in the per-package layer only. + const b = await booted(type === 'form' ? { forms: [formItem(true)] } : { views: [container(true)] }); + await b.install(DEPENDENT); + if (type === 'form') await b.seedRow('form', NAME, DEPENDENT, formItem(false)); + else await b.saveBeforeTheGate('view', DEPENDENT, viewItem(false)); + // The premise, for `view`: the effective read serves the base's open + // form alone, and the withdrawing row sits in the per-package layer only. + // (A dependent's `form` row under the base's name is sealed at the write + // door; at rest the effective `form` read itself serves its withdrawal.) + if (type === 'view') { + const effective = ((await b.protocol.getMetaItems({ type: 'form' })).items as any[]).filter((f) => f?.name === NAME); + expect(effective.map((f) => f.sharing?.allowAnonymous)).toEqual([true]); + } + await closedOnBothDoors(b); + }); + + it('pin 6 — an unreadable old-shape body closes the links it names, and says so once at error (ablate: rule 7)', async () => { + const b = await booted({ forms: [formItem(true)] }); + // A `viewKind: 'form'` item with no `config`: no door admits it, so it is a row at rest. + await b.seedRow('view', `${OBJECT}.broken`, null, { name: `${OBJECT}.broken`, viewKind: 'form', sharing: sharing(true) }); + const lines: string[] = []; + const spy = vi.spyOn(console, 'error').mockImplementation((...a: unknown[]) => { lines.push(a.map(String).join(' ')); }); + try { + const unreadable = await b.protocol.getUnreadableFormBodies(); + expect(unreadable.map((u: any) => [u.name, u.links])).toEqual([[`${OBJECT}.broken`, [SLUG]]]); + await b.protocol.getUnreadableFormBodies(); + } finally { + spy.mockRestore(); + } + const said = lines.filter((l) => l.includes(`${OBJECT}.broken`)); + expect(said).toHaveLength(1); + expect(said[0]).toContain(SLUG); + await closedOnBothDoors(b); + }); + + it('pin 7 — replacement across the types: a `view` override with no link over an open authored `form` item closes the address (ablate: the cross-type resolution of D5)', async () => { + const b = await booted({ forms: [formItem(true)] }); + await b.install(PAIR); + await b.saveBeforeTheGate('view', PAIR, viewItem(null, overrides)); + await closedOnBothDoors(b); + }); + + it('pin 7, twin — a package-less `view` row with no link over an open authored `form` item closes the address', async () => { + const b = await booted({ forms: [formItem(true)] }); + await b.seedRow('view', NAME, null, viewItem(null)); + await closedOnBothDoors(b); + }); + + it('narrowing only: an open `form` override cannot re-open a form the base\'s old shape withdraws', async () => { + const b = await booted({ views: [container(false)] }); + await closedOnBothDoors(b); + await b.install(PAIR); + await b.saveInto('form', PAIR, formItem(true, overrides)); + await closedOnBothDoors(b); + }); +}); + +describe('[ADR-0159 ruled question 3 = A] a `form` left open on an address another form holds is refused', () => { + const engines: ObjectQL[] = []; + afterAll(async () => { + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + const booted = async (ships: { forms?: unknown[]; views?: unknown[] }): Promise => { + const b = await boot(ships); + engines.push(b.engine); + return b; + }; + const SECOND = `${OBJECT}.second`; + + it('refuses a second open form on a held address with 409 FORM_ADDRESS_TAKEN, naming both forms', async () => { + const b = await booted({ views: [container(true)] }); + await b.install(PAIR); + const err = await b.protocol.saveMetaItem({ type: 'form', name: SECOND, packageId: PAIR, mode: 'draft', item: { ...formItem(true), name: SECOND } }) + .then(() => undefined, (e: any) => e); + expect(err).toMatchObject({ code: 'FORM_ADDRESS_TAKEN', status: 409 }); + expect(String(err.message)).toContain(NAME); + expect(String(err.message)).toContain(SECOND); + }); + + it('a switched-off form that keeps its link still holds the address', async () => { + const b = await booted({ forms: [formItem(false)] }); + await b.install(PAIR); + await expect(b.protocol.saveMetaItem({ type: 'form', name: SECOND, packageId: PAIR, mode: 'draft', item: { ...formItem(true), name: SECOND } })) + .rejects.toMatchObject({ code: 'FORM_ADDRESS_TAKEN', status: 409 }); + }); + + it('CONTROL: a save that leaves the form closed is never refused', async () => { + const b = await booted({ forms: [formItem(true)] }); + await b.install(PAIR); + await expect(b.saveInto('form', PAIR, { ...formItem(false), name: SECOND }, SECOND)).resolves.toBeUndefined(); + }); +}); + +describe('[ADR-0159 D5] the `form` writes: the old-shape row goes with the save; a list of the name stays', () => { + const engines: ObjectQL[] = []; + afterAll(async () => { + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + const booted = async (ships: { forms?: unknown[]; views?: unknown[] }): Promise => { + const b = await boot(ships); + engines.push(b.engine); + return b; + }; + /** The pair's ACTIVE stored `view` rows of the name, read off the store itself. */ + const storedViews = async (b: Booted, name = NAME) => { + const rows = (await b.engine.find('sys_metadata', { where: { type: 'view', name, package_id: PAIR, state: 'active' } }, { context: { isSystem: true } } as any)) as any[]; + return rows.map((r) => (typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata)); + }; + + it('a `form` save at a package removes that package\'s old-shape row of the name, in the same write', async () => { + const b = await booted({ views: [container(true)] }); + await b.install(PAIR); + await b.saveInto('view', PAIR, viewItem(true, { ...overrides, label: 'Old shape' })); + expect((await storedViews(b)).length).toBe(1); + await b.saveInto('form', PAIR, formItem(true, { ...overrides, label: 'New type' })); + expect(await storedViews(b)).toEqual([]); + const served = await b.get(); + expect(served.status, JSON.stringify(served.body)).toBe(200); + expect(JSON.stringify(served.body)).toContain('New type'); + }); + + it('a `form` write leaves a list row of the same name untouched', async () => { + const b = await booted({ views: [container(true)] }); + await b.install(PAIR); + const list = { name: NAME, object: OBJECT, viewKind: 'list', label: 'A list', config: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } } }; + await b.saveBeforeTheGate('view', PAIR, list); + await b.saveInto('form', PAIR, formItem(true, overrides)); + expect((await storedViews(b)).map((v) => v.viewKind)).toEqual(['list']); + }); +}); + +describe('[ADR-0159 D5] a package-less list at the name a read-only package authors as a `form` is refused', () => { + const engines: ObjectQL[] = []; + afterAll(async () => { + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + const booted = async (ships: { forms?: unknown[]; views?: unknown[] }): Promise => { + const b = await boot(ships); + engines.push(b.engine); + return b; + }; + const list = { name: NAME, object: OBJECT, viewKind: 'list', label: 'A list', config: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } } }; + + it('refuses the save of a list item with 400 VALIDATION_ERROR, naming the package', async () => { + const b = await booted({ forms: [formItem(true)] }); + const err = await b.protocol.saveMetaItem({ type: 'view', name: NAME, mode: 'draft', item: list }).then(() => undefined, (e: any) => e); + expect(err).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(String(err.message)).toContain(BASE); + }); + + it('refuses a container whose expansion writes a list at the name', async () => { + const b = await booted({ forms: [{ ...formItem(true), name: `${OBJECT}.all`, sharing: undefined }] }); + // A package-less container on the package's object expands under its own + // name: its bare `list` is `.`, here the form's. + const listContainer = { name: 'all', object: OBJECT, list: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } } }; + await expect(b.protocol.saveMetaItem({ type: 'view', name: 'all', mode: 'draft', item: listContainer })) + .rejects.toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + }); + + it('refuses the publish of a list draft saved before the gate', async () => { + const b = await booted({ forms: [formItem(true)] }); + const shipped = b.protocol.shippedArtifactsOf; + b.protocol.shippedArtifactsOf = (type: string, name: string) => (type === 'form' ? [] : shipped.call(b.protocol, type, name)); + try { + await b.protocol.saveMetaItem({ type: 'view', name: NAME, mode: 'draft', item: list }); + } finally { + b.protocol.shippedArtifactsOf = shipped; + } + await expect(b.protocol.publishMetaItem({ type: 'view', name: NAME })) + .rejects.toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + }); + + it('CONTROL: a form-carrying view at the name is not a list, and the same list in an app of the environment\'s own is admitted', async () => { + const b = await booted({ forms: [formItem(true)] }); + const err = await b.protocol.saveMetaItem({ type: 'view', name: NAME, mode: 'draft', item: viewItem(true) }).then(() => undefined, (e: any) => e); + expect(err?.code).not.toBe('VALIDATION_ERROR'); + await b.install(DEPENDENT); + const other = await b.protocol.saveMetaItem({ type: 'view', name: NAME, mode: 'draft', packageId: DEPENDENT, item: list }).then(() => undefined, (e: any) => e); + expect(other?.code).not.toBe('VALIDATION_ERROR'); + }); +}); + +describe('[ADR-0159 D7-b, measure first] does a write door admit a declared override that carries no form at a form\'s name?', () => { + const engines: ObjectQL[] = []; + afterAll(async () => { + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + + const listOverride = { name: NAME, object: OBJECT, viewKind: 'list', ...overrides, config: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } } }; + const measure = async (ships: { forms?: unknown[]; views?: unknown[] }) => { + const b = await boot(ships); + engines.push(b.engine); + await b.install(PAIR); + const outcome = await b.saveInto('view', PAIR, listOverride).then(() => 'admitted', (e: any) => `${e.status} ${e.code}`); + return { b, outcome }; + }; + + it('over a base that authors the name as a `form` item: refused, 403 NOT_OVERRIDABLE (the base ships no `view` there)', async () => { + expect((await measure({ forms: [formItem(true)] })).outcome).toBe('403 NOT_OVERRIDABLE'); + }); + + it('over a base that ships the form as an old shape: ADMITTED, and the stored list closes the base\'s address (D7-b, rule 11)', async () => { + const { b, outcome } = await measure({ views: [container(true)] }); + expect(outcome).toBe('admitted'); + await closedOnBothDoors(b); + }); +}); diff --git a/packages/runtime/src/app-plugin.ts b/packages/runtime/src/app-plugin.ts index 08013432c3e..8035825a016 100644 --- a/packages/runtime/src/app-plugin.ts +++ b/packages/runtime/src/app-plugin.ts @@ -520,7 +520,7 @@ export class AppPlugin implements Plugin { // register an app". `manifest`/`functions` are envelope-level // wrappers and don't count. const APP_CATEGORY_KEYS = [ - 'objects', 'views', 'apps', 'pages', 'dashboards', 'reports', + 'objects', 'views', 'forms', 'apps', 'pages', 'dashboards', 'reports', 'flows', 'workflows', 'triggers', 'agents', 'tools', 'skills', 'aiContexts', 'actions', 'permissions', 'positions', 'translations', 'sharingRules', 'data', 'emailTemplates', diff --git a/packages/spec/api-surface-signatures.json b/packages/spec/api-surface-signatures.json index 5dacefab969..7255869acaa 100644 --- a/packages/spec/api-surface-signatures.json +++ b/packages/spec/api-surface-signatures.json @@ -9,6 +9,7 @@ "defineDatasource": "sha256:5f4aec18b148c77b", "defineEmailTemplateDefinition": "sha256:c1d86a5f074ed7ff", "defineFlow": "sha256:54b60bb867083f61", + "defineForm": "sha256:4442488ff945c139", "defineHook": "sha256:8de712350ec58845", "defineJob": "sha256:e0e927ebb165d48d", "defineMapping": "sha256:c9458652cca717da", diff --git a/packages/spec/api-surface/root.json b/packages/spec/api-surface/root.json index 26a13c500b8..5ae86b2dc59 100644 --- a/packages/spec/api-surface/root.json +++ b/packages/spec/api-surface/root.json @@ -157,6 +157,7 @@ "defineDatasource (function)", "defineEmailTemplateDefinition (function)", "defineFlow (function)", + "defineForm (function)", "defineHook (function)", "defineJob (function)", "defineMapping (function)", diff --git a/packages/spec/api-surface/system.json b/packages/spec/api-surface/system.json index 16e1d3e81f4..85cbf2f8d87 100644 --- a/packages/spec/api-surface/system.json +++ b/packages/spec/api-surface/system.json @@ -280,6 +280,7 @@ "FlowScreenFieldOptionLike (interface)", "FlowScreenLike (interface)", "FlowTerminalMessageKey (type)", + "FormLike (interface)", "GCounter (type)", "GCounterSchema (const)", "GlobalFilterLike (interface)", @@ -950,6 +951,7 @@ "translateDashboard (function)", "translateDataset (function)", "translateFlow (function)", + "translateForm (function)", "translateMapping (function)", "translateMetadataDocument (function)", "translateObject (function)", diff --git a/packages/spec/api-surface/ui.json b/packages/spec/api-surface/ui.json index 2d49dd2e894..d74335e9139 100644 --- a/packages/spec/api-surface/ui.json +++ b/packages/spec/api-surface/ui.json @@ -219,11 +219,15 @@ "FieldWidgetPropsParsed (type)", "FieldWidgetPropsSchema (const)", "FilterCondition (type)", + "Form (type)", "FormButtonConfig (type)", "FormButtonConfigSchema (const)", "FormField (type)", "FormFieldInput (type)", "FormFieldSchema (const)", + "FormIntakeLayer (interface)", + "FormParsed (type)", + "FormSchema (const)", "FormSection (type)", "FormSectionParsed (type)", "FormSectionSchema (const)", @@ -233,6 +237,7 @@ "FormView (type)", "FormViewParsed (type)", "FormViewSchema (const)", + "FormWithdrawal (interface)", "GalleryConfig (type)", "GalleryConfigParsed (type)", "GalleryConfigSchema (const)", @@ -360,6 +365,7 @@ "PAGE_TYPE_ROADMAP (const)", "PRINTABLE_PAGE_COMPONENT_TYPES (const)", "PRINT_REFUSED_PAGE_COMPONENT_TYPES (const)", + "PROJECTED_FORM_SOURCE_KEY (const)", "Page (type)", "PageAccordionProps (const)", "PageCardProps (const)", @@ -396,6 +402,7 @@ "PaginationConfig (type)", "PaginationConfigParsed (type)", "PaginationConfigSchema (const)", + "ProjectedFormItem (interface)", "QueryInput (type)", "REACT_BLOCKS (const)", "REACT_OVERLAY_SHADOWS (const)", @@ -475,6 +482,7 @@ "TreeConfig (type)", "TreeConfigSchema (const)", "UNMAPPED_COLUMN_SUMMARIES (const)", + "UnreadableFormBody (interface)", "UrlNavItem (type)", "UrlNavItemParsed (type)", "UrlNavItemSchema (const)", @@ -509,6 +517,7 @@ "ViewFilterRule (type)", "ViewFilterRuleParsed (type)", "ViewFilterRuleSchema (const)", + "ViewFormProjection (interface)", "ViewItem (type)", "ViewItemName (type)", "ViewItemNameSchema (const)", @@ -558,6 +567,7 @@ "checkDashboardWidgetChartMeasureArity (function)", "checkDashboardWidgetMetricMeasureArity (function)", "checkDashboardWidgetStageOrder (function)", + "checkFormItemNamePrefix (function)", "checkGlobalFilterDateDefaultValue (function)", "checkListViewCalendarVisualization (function)", "checkListViewChartBinding (function)", @@ -580,6 +590,7 @@ "defineAction (function)", "defineApp (function)", "defineDataset (function)", + "defineForm (function)", "defineList (function)", "defineMetadataForm (function)", "definePage (function)", @@ -592,6 +603,8 @@ "expandViewContainer (function)", "expandViewContainerWithDiagnostics (function)", "expressionBindableTextKeysFor (function)", + "formExplicitlyWithdraws (function)", + "formIntakeLayer (function)", "hasReservedComponentNamespace (function)", "isActionParamValuePresent (function)", "isAggregatedViewContainer (function)", @@ -609,9 +622,13 @@ "normalizeFilterOperator (function)", "normalizeInlineAction (function)", "objectNavTargetExclusivity (function)", + "oldShapeFormWithdrawals (function)", + "openFormAt (function)", "pageComponentSlotPositions (function)", "pageForm (const)", "partitionAssembledViewArtifacts (function)", + "projectViewForms (function)", + "projectedFormsOf (function)", "publicFormSlug (function)", "reactBlockTagFor (function)", "reportForm (const)", diff --git a/packages/spec/authorable-defaults/ui.json b/packages/spec/authorable-defaults/ui.json index 93d86a4c716..04a602c355c 100644 --- a/packages/spec/authorable-defaults/ui.json +++ b/packages/spec/authorable-defaults/ui.json @@ -40,6 +40,7 @@ "ui/ElementTextInputProps:required = false", "ui/ElementTextProps:align = \"left\"", "ui/ElementTextProps:variant = \"body\"", + "ui/Form:type = \"simple\"", "ui/FormField:span = \"auto\"", "ui/FormSection:collapsed = false", "ui/FormSection:collapsible = false", diff --git a/packages/spec/authorable-surface/system.json b/packages/spec/authorable-surface/system.json index a674725026c..5385c4aacbe 100644 --- a/packages/spec/authorable-surface/system.json +++ b/packages/spec/authorable-surface/system.json @@ -921,6 +921,7 @@ "system/PlatformTranslationData:dashboards", "system/PlatformTranslationData:datasets", "system/PlatformTranslationData:flows", + "system/PlatformTranslationData:forms", "system/PlatformTranslationData:globalActions", "system/PlatformTranslationData:hooks", "system/PlatformTranslationData:mappings", @@ -1062,6 +1063,7 @@ "system/ServedTranslationData:dashboards", "system/ServedTranslationData:datasets", "system/ServedTranslationData:flows", + "system/ServedTranslationData:forms", "system/ServedTranslationData:globalActions", "system/ServedTranslationData:hooks", "system/ServedTranslationData:mappings", @@ -1372,6 +1374,7 @@ "system/TranslationData:dashboards", "system/TranslationData:datasets", "system/TranslationData:flows", + "system/TranslationData:forms", "system/TranslationData:globalActions", "system/TranslationData:hooks", "system/TranslationData:mappings", @@ -1403,6 +1406,7 @@ "system/TranslationItem:dashboards", "system/TranslationItem:datasets", "system/TranslationItem:flows", + "system/TranslationItem:forms", "system/TranslationItem:globalActions", "system/TranslationItem:hooks", "system/TranslationItem:label", diff --git a/packages/spec/authorable-surface/ui.json b/packages/spec/authorable-surface/ui.json index a2eb1f182f8..9d5f664dd72 100644 --- a/packages/spec/authorable-surface/ui.json +++ b/packages/spec/authorable-surface/ui.json @@ -536,6 +536,40 @@ "ui/EmptyState:link", "ui/EmptyState:message", "ui/EmptyState:title", + "ui/Form:_lock", + "ui/Form:_lockDocsUrl", + "ui/Form:_lockReason", + "ui/Form:_lockSource", + "ui/Form:_packageId", + "ui/Form:_packageVersion", + "ui/Form:_provenance", + "ui/Form:allowSkip", + "ui/Form:buttons", + "ui/Form:columns", + "ui/Form:defaultTab", + "ui/Form:defaults", + "ui/Form:description", + "ui/Form:drawerSide [RETIRED]", + "ui/Form:drawerWidth [RETIRED]", + "ui/Form:groups", + "ui/Form:label", + "ui/Form:layout", + "ui/Form:modalSize", + "ui/Form:name", + "ui/Form:object", + "ui/Form:overrides", + "ui/Form:protection", + "ui/Form:sections", + "ui/Form:sharing", + "ui/Form:showStepIndicator", + "ui/Form:splitDirection [RETIRED]", + "ui/Form:splitResizable [RETIRED]", + "ui/Form:splitSize [RETIRED]", + "ui/Form:subforms", + "ui/Form:submitBehavior", + "ui/Form:tabPosition", + "ui/Form:title", + "ui/Form:type", "ui/FormButtonConfig:label", "ui/FormButtonConfig:show", "ui/FormField:colSpan", diff --git a/packages/spec/declaration-map/ui.json b/packages/spec/declaration-map/ui.json index 758905e105e..7ba7afb043e 100644 --- a/packages/spec/declaration-map/ui.json +++ b/packages/spec/declaration-map/ui.json @@ -133,11 +133,13 @@ "EmptyStateSchema": "ui/EmptyState", "ExpressionBindableTextKey": "ui/ExpressionBindableTextKey", "ExpressionBindableTextKeySchema": "ui/ExpressionBindableTextKey", + "Form": "ui/Form", "FormButtonConfig": "ui/FormButtonConfig", "FormButtonConfigSchema": "ui/FormButtonConfig", "FormField": "ui/FormField", "FormFieldBaseSchema": "ui/FormField", "FormFieldSchema": "ui/FormField", + "FormSchema": "ui/Form", "FormSection": "ui/FormSection", "FormSectionSchema": "ui/FormSection", "FormSelectOption": "ui/FormSelectOption", diff --git a/packages/spec/dropped-refinements.baseline.json b/packages/spec/dropped-refinements.baseline.json index 1dbc51d97f3..6276a80c1dc 100644 --- a/packages/spec/dropped-refinements.baseline.json +++ b/packages/spec/dropped-refinements.baseline.json @@ -146,6 +146,9 @@ "manifest.flows.element.errorHandling", "manifest.flows.element.nodes.element.in.waitEventConfig", "manifest.flows.element.variables.element", + "manifest.forms.element", + "manifest.forms.element.sections.element", + "manifest.forms.element.submitBehavior.options[1].url", "manifest.hooks.element", "manifest.hooks.element.object", "manifest.hooks.element.refusals.valueType", @@ -194,8 +197,6 @@ "manifest.translations.element.valueType.flows.valueType.screens.valueType.title", "manifest.translations.element.valueType.flows.valueType.successMessage", "manifest.views.element.form", - "manifest.views.element.form.sections.element", - "manifest.views.element.form.submitBehavior.options[1].url", "manifest.views.element.list", "manifest.views.element.list.bulkActionDefs.element", "manifest.views.element.list.emptyState.link.url", @@ -340,6 +341,9 @@ "data.options[1].manifest.flows.element.errorHandling", "data.options[1].manifest.flows.element.nodes.element.in.waitEventConfig", "data.options[1].manifest.flows.element.variables.element", + "data.options[1].manifest.forms.element", + "data.options[1].manifest.forms.element.sections.element", + "data.options[1].manifest.forms.element.submitBehavior.options[1].url", "data.options[1].manifest.hooks.element", "data.options[1].manifest.hooks.element.object", "data.options[1].manifest.hooks.element.refusals.valueType", @@ -381,8 +385,6 @@ "data.options[1].manifest.translations.element.valueType.flows.valueType.errorMessage", "data.options[1].manifest.translations.element.valueType.flows.valueType.successMessage", "data.options[1].manifest.views.element.form", - "data.options[1].manifest.views.element.form.sections.element", - "data.options[1].manifest.views.element.form.submitBehavior.options[1].url", "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", @@ -514,6 +516,9 @@ "options[1].manifest.flows.element.errorHandling", "options[1].manifest.flows.element.nodes.element.in.waitEventConfig", "options[1].manifest.flows.element.variables.element", + "options[1].manifest.forms.element", + "options[1].manifest.forms.element.sections.element", + "options[1].manifest.forms.element.submitBehavior.options[1].url", "options[1].manifest.hooks.element", "options[1].manifest.hooks.element.object", "options[1].manifest.hooks.element.refusals.valueType", @@ -559,8 +564,6 @@ "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.form.sections.element", - "options[1].manifest.views.element.form.submitBehavior.options[1].url", "options[1].manifest.views.element.list", "options[1].manifest.views.element.list.bulkActionDefs.element", "options[1].manifest.views.element.list.emptyState.link.url", @@ -616,6 +619,9 @@ "data.packages.element.options[1].manifest.flows.element.errorHandling", "data.packages.element.options[1].manifest.flows.element.nodes.element.in.waitEventConfig", "data.packages.element.options[1].manifest.flows.element.variables.element", + "data.packages.element.options[1].manifest.forms.element", + "data.packages.element.options[1].manifest.forms.element.sections.element", + "data.packages.element.options[1].manifest.forms.element.submitBehavior.options[1].url", "data.packages.element.options[1].manifest.hooks.element", "data.packages.element.options[1].manifest.hooks.element.object", "data.packages.element.options[1].manifest.hooks.element.refusals.valueType", @@ -657,8 +663,6 @@ "data.packages.element.options[1].manifest.translations.element.valueType.flows.valueType.errorMessage", "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.form.sections.element", - "data.packages.element.options[1].manifest.views.element.form.submitBehavior.options[1].url", "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.filter.element", @@ -1937,6 +1941,14 @@ "link.url" ] }, + "ui/Form": { + "sites": [ + "", + "sections.element", + "subforms.element.columns.element", + "submitBehavior.options[1].url" + ] + }, "ui/FormSection": { "sites": [ "" diff --git a/packages/spec/export-origins/root.json b/packages/spec/export-origins/root.json index ee1b9fc59f8..14a1c341671 100644 --- a/packages/spec/export-origins/root.json +++ b/packages/spec/export-origins/root.json @@ -156,6 +156,7 @@ "defineDatasource": "src/data/datasource.zod.ts#defineDatasource (function)", "defineEmailTemplateDefinition": "src/system/email-template.zod.ts#defineEmailTemplateDefinition (function)", "defineFlow": "src/automation/flow.zod.ts#defineFlow (function)", + "defineForm": "src/ui/view.zod.ts#defineForm (function)", "defineHook": "src/data/hook.zod.ts#defineHook (function)", "defineJob": "src/system/job.zod.ts#defineJob (function)", "defineMapping": "src/data/mapping.zod.ts#defineMapping (function)", diff --git a/packages/spec/export-origins/system.json b/packages/spec/export-origins/system.json index d787d751fe0..aaf3d260cfa 100644 --- a/packages/spec/export-origins/system.json +++ b/packages/spec/export-origins/system.json @@ -272,6 +272,7 @@ "FlowScreenFieldOptionLike": "src/system/i18n-resolver.ts#FlowScreenFieldOptionLike (interface)", "FlowScreenLike": "src/system/i18n-resolver.ts#FlowScreenLike (interface)", "FlowTerminalMessageKey": "src/system/i18n-resolver.ts#FlowTerminalMessageKey (type)", + "FormLike": "src/system/i18n-resolver.ts#FormLike (interface)", "GCounter": "src/system/collaboration.zod.ts#GCounter (type)", "GCounterSchema": "src/system/collaboration.zod.ts#GCounterSchema (const)", "GlobalFilterLike": "src/system/i18n-resolver.ts#GlobalFilterLike (interface)", @@ -910,6 +911,7 @@ "translateDashboard": "src/system/i18n-resolver.ts#translateDashboard (function)", "translateDataset": "src/system/i18n-resolver.ts#translateDataset (function)", "translateFlow": "src/system/i18n-resolver.ts#translateFlow (function)", + "translateForm": "src/system/i18n-resolver.ts#translateForm (function)", "translateMapping": "src/system/i18n-resolver.ts#translateMapping (function)", "translateMetadataDocument": "src/system/i18n-resolver.ts#translateMetadataDocument (function)", "translateObject": "src/system/i18n-resolver.ts#translateObject (function)", diff --git a/packages/spec/export-origins/ui.json b/packages/spec/export-origins/ui.json index 075b60a9285..d5d706f9a4d 100644 --- a/packages/spec/export-origins/ui.json +++ b/packages/spec/export-origins/ui.json @@ -213,11 +213,15 @@ "FieldWidgetPropsParsed": "src/ui/widget.zod.ts#FieldWidgetPropsParsed (type)", "FieldWidgetPropsSchema": "src/ui/widget.zod.ts#FieldWidgetPropsSchema (const)", "FilterCondition": "src/data/filter.zod.ts#FilterCondition (type)", + "Form": "src/ui/view.zod.ts#Form (type)", "FormButtonConfig": "src/ui/view.zod.ts#FormButtonConfig (type)", "FormButtonConfigSchema": "src/ui/view.zod.ts#FormButtonConfigSchema (const)", "FormField": "src/ui/view.zod.ts#FormField (type)", "FormFieldInput": "src/ui/view.zod.ts#FormFieldInput (type)", "FormFieldSchema": "src/ui/view.zod.ts#FormFieldSchema (const)", + "FormIntakeLayer": "src/ui/form-intake-layer.ts#FormIntakeLayer (interface)", + "FormParsed": "src/ui/view.zod.ts#FormParsed (type)", + "FormSchema": "src/ui/view.zod.ts#FormSchema (const)", "FormSection": "src/ui/view.zod.ts#FormSection (type)", "FormSectionParsed": "src/ui/view.zod.ts#FormSectionParsed (type)", "FormSectionSchema": "src/ui/view.zod.ts#FormSectionSchema (const)", @@ -227,6 +231,7 @@ "FormView": "src/ui/view.zod.ts#FormView (type)", "FormViewParsed": "src/ui/view.zod.ts#FormViewParsed (type)", "FormViewSchema": "src/ui/view.zod.ts#FormViewSchema (const)", + "FormWithdrawal": "src/ui/anonymous-form-intake.ts#FormWithdrawal (interface)", "GalleryConfig": "src/ui/view.zod.ts#GalleryConfig (type)", "GalleryConfigParsed": "src/ui/view.zod.ts#GalleryConfigParsed (type)", "GalleryConfigSchema": "src/ui/view.zod.ts#GalleryConfigSchema (const)", @@ -354,6 +359,7 @@ "PAGE_TYPE_ROADMAP": "src/ui/page.zod.ts#PAGE_TYPE_ROADMAP (const)", "PRINTABLE_PAGE_COMPONENT_TYPES": "src/ui/page.zod.ts#PRINTABLE_PAGE_COMPONENT_TYPES (const)", "PRINT_REFUSED_PAGE_COMPONENT_TYPES": "src/ui/page.zod.ts#PRINT_REFUSED_PAGE_COMPONENT_TYPES (const)", + "PROJECTED_FORM_SOURCE_KEY": "src/ui/view.zod.ts#PROJECTED_FORM_SOURCE_KEY (const)", "Page": "src/ui/page.zod.ts#Page (type)", "PageAccordionProps": "src/ui/component.zod.ts#PageAccordionProps (const)", "PageCardProps": "src/ui/component.zod.ts#PageCardProps (const)", @@ -388,6 +394,7 @@ "PaginationConfig": "src/ui/view.zod.ts#PaginationConfig (type)", "PaginationConfigParsed": "src/ui/view.zod.ts#PaginationConfigParsed (type)", "PaginationConfigSchema": "src/ui/view.zod.ts#PaginationConfigSchema (const)", + "ProjectedFormItem": "src/ui/view.zod.ts#ProjectedFormItem (interface)", "QueryInput": "src/data/query.zod.ts#QueryInput (type)", "REACT_BLOCKS": "src/ui/react-blocks.ts#REACT_BLOCKS (const)", "REACT_OVERLAY_SHADOWS": "src/ui/react-blocks.ts#REACT_OVERLAY_SHADOWS (const)", @@ -458,6 +465,7 @@ "TreeConfig": "src/ui/view.zod.ts#TreeConfig (type)", "TreeConfigSchema": "src/ui/view.zod.ts#TreeConfigSchema (const)", "UNMAPPED_COLUMN_SUMMARIES": "src/ui/view-grouping-query.ts#UNMAPPED_COLUMN_SUMMARIES (const)", + "UnreadableFormBody": "src/ui/form-intake-layer.ts#UnreadableFormBody (interface)", "UrlNavItem": "src/ui/app.zod.ts#UrlNavItem (type)", "UrlNavItemParsed": "src/ui/app.zod.ts#UrlNavItemParsed (type)", "UrlNavItemSchema": "src/ui/app.zod.ts#UrlNavItemSchema (const)", @@ -492,6 +500,7 @@ "ViewFilterRule": "src/ui/view.zod.ts#ViewFilterRule (type)", "ViewFilterRuleParsed": "src/ui/view.zod.ts#ViewFilterRuleParsed (type)", "ViewFilterRuleSchema": "src/ui/view.zod.ts#ViewFilterRuleSchema (const)", + "ViewFormProjection": "src/ui/view.zod.ts#ViewFormProjection (interface)", "ViewItem": "src/ui/view.zod.ts#ViewItem (type)", "ViewItemName": "src/ui/view.zod.ts#ViewItemName (type)", "ViewItemNameSchema": "src/ui/view.zod.ts#ViewItemNameSchema (const)", @@ -541,6 +550,7 @@ "checkDashboardWidgetChartMeasureArity": "src/ui/dashboard.zod.ts#checkDashboardWidgetChartMeasureArity (function)", "checkDashboardWidgetMetricMeasureArity": "src/ui/dashboard.zod.ts#checkDashboardWidgetMetricMeasureArity (function)", "checkDashboardWidgetStageOrder": "src/ui/dashboard.zod.ts#checkDashboardWidgetStageOrder (function)", + "checkFormItemNamePrefix": "src/ui/view.zod.ts#checkFormItemNamePrefix (function)", "checkGlobalFilterDateDefaultValue": "src/ui/dashboard.zod.ts#checkGlobalFilterDateDefaultValue (function)", "checkListViewCalendarVisualization": "src/ui/view.zod.ts#checkListViewCalendarVisualization (function)", "checkListViewChartBinding": "src/ui/view.zod.ts#checkListViewChartBinding (function)", @@ -563,6 +573,7 @@ "defineAction": "src/ui/action.zod.ts#defineAction (function)", "defineApp": "src/ui/app.zod.ts#defineApp (function)", "defineDataset": "src/ui/dataset.zod.ts#defineDataset (function)", + "defineForm": "src/ui/view.zod.ts#defineForm (function)", "defineList": "src/ui/view.zod.ts#defineList (function)", "defineMetadataForm": "src/ui/view.zod.ts#defineMetadataForm (function)", "definePage": "src/ui/page.zod.ts#definePage (function)", @@ -575,6 +586,8 @@ "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)", + "formExplicitlyWithdraws": "src/ui/anonymous-form-intake.ts#formExplicitlyWithdraws (function)", + "formIntakeLayer": "src/ui/form-intake-layer.ts#formIntakeLayer (function)", "hasReservedComponentNamespace": "src/ui/component-type-vocabulary.ts#hasReservedComponentNamespace (function)", "isActionParamValuePresent": "src/ui/action-params.zod.ts#isActionParamValuePresent (function)", "isAggregatedViewContainer": "src/ui/view.zod.ts#isAggregatedViewContainer (function)", @@ -592,9 +605,13 @@ "normalizeFilterOperator": "src/ui/view.zod.ts#normalizeFilterOperator (function)", "normalizeInlineAction": "src/ui/action.zod.ts#normalizeInlineAction (function)", "objectNavTargetExclusivity": "src/ui/app.zod.ts#objectNavTargetExclusivity (function)", + "oldShapeFormWithdrawals": "src/ui/old-shape-form-withdrawals.ts#oldShapeFormWithdrawals (function)", + "openFormAt": "src/ui/form-intake-layer.ts#openFormAt (function)", "pageComponentSlotPositions": "src/ui/component.zod.ts#pageComponentSlotPositions (function)", "pageForm": "src/ui/page.metadata-form.ts#pageForm (const)", "partitionAssembledViewArtifacts": "src/ui/assembled-views.zod.ts#partitionAssembledViewArtifacts (function)", + "projectViewForms": "src/ui/view.zod.ts#projectViewForms (function)", + "projectedFormsOf": "src/ui/view.zod.ts#projectedFormsOf (function)", "publicFormSlug": "src/ui/anonymous-form-intake.ts#publicFormSlug (function)", "reactBlockTagFor": "src/ui/react-blocks.ts#reactBlockTagFor (function)", "reportForm": "src/ui/report.metadata-form.ts#reportForm (const)", diff --git a/packages/spec/json-schema.manifest/ui.json b/packages/spec/json-schema.manifest/ui.json index 3a43042256a..90275f60ec6 100644 --- a/packages/spec/json-schema.manifest/ui.json +++ b/packages/spec/json-schema.manifest/ui.json @@ -73,6 +73,7 @@ "ui/ElementTextProps", "ui/EmptyState", "ui/ExpressionBindableTextKey", + "ui/Form", "ui/FormButtonConfig", "ui/FormField", "ui/FormSection", diff --git a/packages/spec/liveness/README.md b/packages/spec/liveness/README.md index 397e78e2cfa..451989aa369 100644 --- a/packages/spec/liveness/README.md +++ b/packages/spec/liveness/README.md @@ -893,7 +893,7 @@ The governed set is `GOVERNED` at the top of `check-liveness.mts`. To add a type RecordDetailView had been gating the History tab on it the whole time (#2707). 4. Add the type to `GOVERNED`; confirm the gate is green. -## Current state — 45 governed types (complete registry coverage) +## Current state — 46 governed types (complete registry coverage) > **This heading is now checked** (#7257). `check:liveness` reconciles the table > against `GOVERNED` in both directions — a governed type with no row fails, a row @@ -1028,6 +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`). | The `dead` set across types is the enforce-or-remove worklist (ADR-0049); a `dead` row warns its authors at compile time by its verdict alone, with no `authorWarn` diff --git a/packages/spec/liveness/form.json b/packages/spec/liveness/form.json new file mode 100644 index 00000000000..826c39814ce --- /dev/null +++ b/packages/spec/liveness/form.json @@ -0,0 +1,162 @@ +{ + "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.", + "props": { + "name": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidence": "packages/metadata-protocol/src/protocol-form-reads.ts#readEffectiveForms (keys the effective `form` read by name, the address the override, the withdrawal and the action target name); packages/spec/src/ui/form-intake-layer.ts#openFormAt (a form withdrawn by name is not served)", + "note": "ADR-0159 D3: `OBJECT.KEY`, its prefix equal to `object` (checkFormItemNamePrefix)." + }, + "object": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidence": "packages/spec/src/ui/form-intake-layer.ts#openFormAt (the door's match carries `object`, and the submit runs as `publicFormGrant` on exactly that object); packages/lint/src/validate-form-items.ts#validateFormObjectBindings", + "note": "ADR-0159 D2: the form's one binding; `data` is refused by name." + }, + "label": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidence": "packages/rest/src/form-routes.ts#resolveFormBySlug (`servedLabel` is the `form` item's label); packages/spec/src/system/i18n-resolver.ts#translateForm (`forms.NAME.label`)" + }, + "type": { + "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." + }, + "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." + }, + "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." + }, + "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)." + }, + "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." + }, + "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." + }, + "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." + }, + "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)." + }, + "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." + }, + "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." + }, + "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." + }, + "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." + }, + "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`)." + }, + "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`." + }, + "modalSize": { + "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. objectui: ModalForm.tsx reads `modalSize`. Until #36425 the console's New / Edit record dialog copied it from the object's internal form view whatever the form's `type` (#27155); #36425 retired that read (the dialog takes no layout from a form view), and a named or public form opens on a full page (FormPage), not a dialog. RE-AUDIT OWED: no form-view reader of this key is named here after #36425; the verdict is left to the ledger's owner (reported on #36425), not flipped by that change." + }, + "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]." + }, + "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." + }, + "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)." + }, + "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": "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." + }, + "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." + }, + "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." + }, + "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." + }, + "protection": null, + "_lock": null, + "_lockReason": null, + "_lockSource": null, + "_provenance": null, + "_packageId": null, + "_packageVersion": null, + "_lockDocsUrl": null, + "overrides": { + "status": "planned", + "verifiedAt": "2026-10-31", + "note": "PLANNED RECORD (ADR-0146 D2, the spec card N-08): the override declaration `overrides: { package, basedOn }`, one field set (`OverrideDeclarationFields`, packages/spec/src/kernel/override-declaration.zod.ts) spread on the thirteen types `OVERRIDE_TYPE_CLASSIFICATION` classifies `overridable`. CARRIED today, measured: it survives the metadata save's schema parse, `defineStack()` and `GET /packages/:id/export` (packages/spec/src/kernel/override-declaration.test.ts; packages/runtime/src/domains/packages-export-override-declaration.test.ts). ACTED ON by nothing yet: the write gate that admits a declared override from the paired `.custom` and refuses an undeclared same-named item, and the effective read that serves the declared document over the base's, are later cards of ADR-0146's Rollout (P1). Flip to `live` on the commit that lands the reader, citing it.", + "children": { + "package": { + "status": "planned", + "verifiedAt": "2026-10-31", + "note": "Planned with its container `overrides` (see that row): the base package id the declaring item replaces an item of. The pair predicate the write gate will read is `isCustomizationPairOf` (packages/spec/src/kernel/customization-package.ts). The schema refuses a `.custom` id here at parse." + }, + "basedOn": { + "status": "planned", + "verifiedAt": "2026-10-31", + "note": "Planned with its container `overrides` (see that row). RECORDED, NEVER JUDGED by contract (ADR-0146 D2, 'Decided here' item 2): no door compares it with the installed base, produces an upgrade diff from it, or refuses on it. Its whole reading is a person's (Studio's override chip, the export); it stays `planned` until that reader lands, and must never gain a gate." + } + } + } + } +} diff --git a/packages/spec/liveness/state-counts/form.md b/packages/spec/liveness/state-counts/form.md new file mode 100644 index 00000000000..b5ef615f19b --- /dev/null +++ b/packages/spec/liveness/state-counts/form.md @@ -0,0 +1,15 @@ + + + +# `form` — liveness counts (generated) + +This type's row of the liveness state table, computed by the gate that enforces +it (`scripts/liveness/check-liveness.mts --json`, `types..byStatus`). Its +Notes prose is the `form` row of [the ledger README](../README.md), which +also states the counting method. One file per governed type, and no total is +committed anywhere: `check:liveness` sums the shards when it reads them. +**Never hand-patch a number here** — fix the ledger or the schema and regenerate. + +| Type | live | exp | elsewhere | dead | planned | classified | +|---|---|---|---|---|---|---| +| `form` | 28 | 0 | 0 | 5 | 2 | 35 | diff --git a/packages/spec/liveness/state-counts/translation.md b/packages/spec/liveness/state-counts/translation.md index 88dbc018bff..63d0e58fe0b 100644 --- a/packages/spec/liveness/state-counts/translation.md +++ b/packages/spec/liveness/state-counts/translation.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `translation` | 48 | 0 | 0 | 0 | 2 | 50 | +| `translation` | 53 | 0 | 0 | 0 | 2 | 55 | diff --git a/packages/spec/liveness/translation.json b/packages/spec/liveness/translation.json index c2a11ac9d69..dd247ce3736 100644 --- a/packages/spec/liveness/translation.json +++ b/packages/spec/liveness/translation.json @@ -152,6 +152,46 @@ "evidence": "packages/spec/src/system/i18n-resolver.ts#lookupPageAttr (`pages..` — label/description/title/subtitle; an omitted title keeps the authored header title, the label standing in only where the header authors none or restates the page label); packages/spec/src/system/i18n-resolver.ts#lookupPageComponentCopy (`pages..components.` — header copy keyed by page name because page:header instances carry no stable id)", "note": "translatePage: label/description/title/subtitle (an omitted title keeps the authored header title, the label standing in only where the header authors none or restates the page label; header copy keyed by page name because page:header instances carry no stable id). 2026-08-28: RE-ANCHORED (commit 8f10a79f7) and REPOINTED — `:636` had rotted onto `function lookupAppAttr`, the APP group's reader, ~226 lines above the page ones. Re-closed by hand against 8cb96ec41." }, + "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.", + "children": { + "label": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidence": "packages/spec/src/system/i18n-resolver.ts#translateForm (`forms..label` only — `_views..label` is never read: a view's label names the view, not the form)" + }, + "description": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidence": "packages/spec/src/system/i18n-resolver.ts#translateForm (`forms..description`)" + }, + "title": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidence": "packages/spec/src/system/i18n-resolver.ts#translateForm (`forms..title`, then the `_views..title` tail)" + }, + "submitBehavior": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidence": "packages/spec/src/system/i18n-resolver.ts#translateForm (`forms..submitBehavior.{title,message}`, then the `_views..submitBehavior` tail, via translateFormSubmitBehavior)", + "children": { + "title": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidence": "packages/spec/src/system/i18n-resolver.ts#translateFormSubmitBehavior (the thank-you panel's `title`, read off `forms..submitBehavior.title` first, then the `_views..submitBehavior.title` tail)" + }, + "message": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidence": "packages/spec/src/system/i18n-resolver.ts#translateFormSubmitBehavior (the thank-you panel's `message`, read off `forms..submitBehavior.message` first, then the `_views..submitBehavior.message` tail)" + } + } + } + } + }, "flows": { "status": "live", "verifiedAt": "2026-10-05", diff --git a/packages/spec/liveness/view.json b/packages/spec/liveness/view.json index 2e899ec7ce3..2ce7067416a 100644 --- a/packages/spec/liveness/view.json +++ b/packages/spec/liveness/view.json @@ -383,7 +383,7 @@ "sharing": { "status": "live", "verifiedAt": "2026-08-28", - "evidence": "packages/rest/src/form-routes.ts#findPublicFormView (`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)", + "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": { diff --git a/packages/spec/scripts/liveness/check-liveness.mts b/packages/spec/scripts/liveness/check-liveness.mts index 83bcba14bbe..cec5729e489 100644 --- a/packages/spec/scripts/liveness/check-liveness.mts +++ b/packages/spec/scripts/liveness/check-liveness.mts @@ -279,7 +279,7 @@ const ledgerRoot = ledgerRootArg // Governed metadata types, rolled out highest-frequency / highest-risk first. // (`query` is not a metadata type — see SPEC_ONLY_SCHEMAS below.) -const GOVERNED = ['object', 'field', 'flow', 'action', 'hook', 'permission', 'position', 'agent', 'tool', 'skill', 'dataset', 'page', 'view', 'report', 'dashboard', 'webhook', 'query', 'datasource', 'app', 'book', 'doc', 'email_template', 'job', 'mapping', 'picklist', 'seed', 'translation', 'validation', 'api', 'capability', 'qa', 'manifest', 'crud_endpoints', 'metadata_endpoints', 'batch_endpoints', 'route_generation', 'rest_api', 'realtime_subscription', 'sharing_rule', 'connector', 'analytics_cube', 'queue', 'assignment_rule', 'template_manifest', 'ai_context']; +const GOVERNED = ['object', 'field', 'flow', 'action', 'hook', 'permission', 'position', 'agent', 'tool', 'skill', 'dataset', 'page', 'view', 'report', 'dashboard', 'webhook', 'query', 'datasource', 'app', 'book', 'doc', 'email_template', 'job', 'mapping', 'picklist', 'seed', 'translation', 'validation', 'api', 'capability', 'qa', 'manifest', 'crud_endpoints', 'metadata_endpoints', 'batch_endpoints', 'route_generation', 'rest_api', 'realtime_subscription', 'sharing_rule', 'connector', 'analytics_cube', 'queue', 'assignment_rule', 'template_manifest', 'ai_context', 'form']; // Authorable metadata types that are NOT yet governed — the coverage ratchet. // diff --git a/packages/spec/scripts/liveness/undrilled-containers.baseline.json b/packages/spec/scripts/liveness/undrilled-containers.baseline.json index e10a38260ff..28b887127dc 100644 --- a/packages/spec/scripts/liveness/undrilled-containers.baseline.json +++ b/packages/spec/scripts/liveness/undrilled-containers.baseline.json @@ -92,6 +92,11 @@ "flow/nodes.inputSchema", "flow/nodes.position", "flow/nodes.waitEventConfig", + "form/buttons", + "form/groups", + "form/sections", + "form/sharing", + "form/subforms", "hook/retryPolicy", "job/retryPolicy", "manifest/contributes.kinds", diff --git a/packages/spec/src/api/error-code-ledger.zod.ts b/packages/spec/src/api/error-code-ledger.zod.ts index 0384070c612..7352ad15f4a 100644 --- a/packages/spec/src/api/error-code-ledger.zod.ts +++ b/packages/spec/src/api/error-code-ledger.zod.ts @@ -244,6 +244,10 @@ export const ERROR_CODE_LEDGER = { // ledger is door-agnostic. 'FIELD_VISIBILITY_UNRESOLVED', 'FORBIDDEN', + // [ADR-0159 ruled question 3 = A] The public address clash: a `form` write + // that would leave the form open on a `/forms/SLUG` another form holds + // (`formAddressClashRefusal`, `@objectstack/metadata-protocol`), 409. + 'FORM_ADDRESS_TAKEN', 'FORM_NOT_FOUND', 'FORM_RESOLVE_FAILED', 'IMPORT_JOB_CREATE_FAILED', diff --git a/packages/spec/src/index.ts b/packages/spec/src/index.ts index dcf2f4c2b8b..57b18cd7332 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, defineMetadataForm, defineViewItem, isAggregatedViewContainer, expandViewContainer, expandViewContainerWithDiagnostics } from './ui/view.zod'; +export { defineView, defineForm, defineMetadataForm, defineViewItem, isAggregatedViewContainer, expandViewContainer, 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/kernel/customization-package.ts b/packages/spec/src/kernel/customization-package.ts index 7942d49fbd0..a8bd0cbd004 100644 --- a/packages/spec/src/kernel/customization-package.ts +++ b/packages/spec/src/kernel/customization-package.ts @@ -322,6 +322,9 @@ export const OVERRIDE_TYPE_CLASSIFICATION = { translation: listed, email_template: listed, page: listed, + // [ADR-0159 D4] `form` is `view`'s form half: overridable on the terms a form + // `view` item is today, so a declared override switches an installed form off. + form: listed, app: listed, dataset: listed, doc: listed, diff --git a/packages/spec/src/kernel/metadata-plugin.zod.ts b/packages/spec/src/kernel/metadata-plugin.zod.ts index 76dc493b5ae..18920d07d22 100644 --- a/packages/spec/src/kernel/metadata-plugin.zod.ts +++ b/packages/spec/src/kernel/metadata-plugin.zod.ts @@ -96,6 +96,7 @@ export const MetadataTypeSchema = lazySchema(() => z.enum([ // UI Protocol 'view', // List/form views (ViewSchema) + 'form', // Data-entry forms bound to one object (FormSchema, ADR-0159) — the anonymous intake reads them 'page', // Standalone pages (PageSchema) 'dashboard', // Dashboard layouts (DashboardSchema) 'app', // Application shell (AppSchema) @@ -964,6 +965,10 @@ export const DEFAULT_METADATA_TYPE_REGISTRY: MetadataTypeRegistryEntryParsed[] = // MATERIALIZED into `sys_metadata` (DB-only provenance), which rides the // `allowRuntimeCreate` tier, not this flag. { type: 'view', label: 'View', filePatterns: ['**/*.view.ts', '**/*.view.yml', '**/*.view.json'], supportsOverlay: true, allowEnvironmentOverlay: true, allowRuntimeCreate: true, supportsVersioning: true, executionPinned: false, loadOrder: 50, domain: 'ui' }, + // [ADR-0159 D1] `form` carries page's flags exactly: overlayable per org but not + // per environment (the ruled scope set is `{global, org, user}`), runtime- + // creatable, versioned, unpinned, loaded with the UI tier. + { type: 'form', label: 'Form', filePatterns: ['**/*.form.ts', '**/*.form.yml', '**/*.form.json'], supportsOverlay: true, allowEnvironmentOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, executionPinned: false, loadOrder: 50, domain: 'ui' }, { type: 'page', label: 'Page', filePatterns: ['**/*.page.ts', '**/*.page.yml'], supportsOverlay: true, allowEnvironmentOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, executionPinned: false, loadOrder: 50, domain: 'ui' }, { type: 'dashboard', label: 'Dashboard', filePatterns: ['**/*.dashboard.ts', '**/*.dashboard.yml', '**/*.dashboard.json'], supportsOverlay: true, allowEnvironmentOverlay: true, allowRuntimeCreate: true, supportsVersioning: true, executionPinned: false, loadOrder: 60, domain: 'ui' }, { type: 'app', label: 'Application', filePatterns: ['**/*.app.ts', '**/*.app.yml', '**/*.app.json'], supportsOverlay: true, allowEnvironmentOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, executionPinned: false, loadOrder: 70, domain: 'ui' }, diff --git a/packages/spec/src/kernel/metadata-type-schemas.ts b/packages/spec/src/kernel/metadata-type-schemas.ts index 7cfd721ba44..af23d5d308a 100644 --- a/packages/spec/src/kernel/metadata-type-schemas.ts +++ b/packages/spec/src/kernel/metadata-type-schemas.ts @@ -36,7 +36,7 @@ import { SeedSchema } from '../data/seed.zod'; import { MappingSchema } from '../data/mapping.zod'; import { PicklistSchema } from '../data/picklist.zod'; -import { ViewMetadataSchema } from '../ui/view.zod'; +import { ViewMetadataSchema, FormSchema } from '../ui/view.zod'; import { PageSchema } from '../ui/page.zod'; import { DashboardSchema } from '../ui/dashboard.zod'; import { AppSchema } from '../ui/app.zod'; @@ -113,6 +113,7 @@ const BUILTIN_METADATA_TYPE_SCHEMAS: Partial> = // served by no read path. Every consumer of this entry — saveMetaItem's 422 // gate and the read-time diagnostics badge — inherits that refusal here. view: ViewMetadataSchema, + form: FormSchema, // ADR-0159: the authored `form` item; projected old shapes are never parsed by it (D5) page: PageSchema, dashboard: DashboardSchema, app: AppSchema, diff --git a/packages/spec/src/meta-spelling/manifest-collection-spelling.ts b/packages/spec/src/meta-spelling/manifest-collection-spelling.ts index 94f13897443..0fbac088b12 100644 --- a/packages/spec/src/meta-spelling/manifest-collection-spelling.ts +++ b/packages/spec/src/meta-spelling/manifest-collection-spelling.ts @@ -59,6 +59,7 @@ export const PLURAL_TO_SINGULAR: Record = { objects: 'object', apps: 'app', + forms: 'form', pages: 'page', dashboards: 'dashboard', reports: 'report', diff --git a/packages/spec/src/meta-spelling/meta-url-data.generated.ts b/packages/spec/src/meta-spelling/meta-url-data.generated.ts index 0cb6496a7e5..4f8ff6ce435 100644 --- a/packages/spec/src/meta-spelling/meta-url-data.generated.ts +++ b/packages/spec/src/meta-spelling/meta-url-data.generated.ts @@ -19,6 +19,7 @@ export const META_URL_TO_SINGULAR: Readonly> = Object.freeze({ "objects": "object", "apps": "app", + "forms": "form", "pages": "page", "dashboards": "dashboard", "reports": "report", @@ -74,6 +75,7 @@ export const REGISTRY_DECLARED_META_TYPES: ReadonlyArray = Object.freeze "picklist", "mapping", "view", + "form", "page", "dashboard", "app", diff --git a/packages/spec/src/migrations/entries/semantic/18.form-type-define-form-and-packageless-list-at-form-name.ts b/packages/spec/src/migrations/entries/semantic/18.form-type-define-form-and-packageless-list-at-form-name.ts new file mode 100644 index 00000000000..9eb3c4cda51 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.form-type-define-form-and-packageless-list-at-form-name.ts @@ -0,0 +1,35 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// The ADR-0087 registration of card ② of ADR-0159 (the `form` metadata type): +// its two breaks together, as the record's own consequences paragraph asks +// (one marker for the export break of ruled question 1 and the refusal of +// D5). Neither has a source the chain rewrites: the export is a TS name, and +// the refused save is a runtime write whose fix is another key or another +// binding, chosen by the administrator. +export const entry: SemanticMigration = { + id: 'form-type-define-form-and-packageless-list-at-form-name', + surface: + '`defineForm` (function) on `@objectstack/spec` and `@objectstack/spec/ui`, which now builds a `form` ' + + 'metadata item; and a package-less `view` write (save, publish of a draft, rollback) that would store a ' + + 'LIST — an item, or a container\'s expansion — at a name a read-only package authors as a `form` item', + replacement: + '`defineForm({ name: \'OBJECT.KEY\', object, …form body })` builds a `form` item (ADR-0159 D2); the Studio ' + + 'helper that held the name is `defineMetadataForm` since the previous entry. A list at a form\'s name is ' + + 'saved under another key, or into an app of the environment\'s own: a list and a form of one name are two ' + + 'items, and a package-less list there would be read over the package\'s form', + reason: + 'ADR-0159 makes `form` a metadata type of its own (ruled question 1 = A gives it the factory name), and D5 ' + + 'reads a stored `view` row that stands over a package\'s form as the form it replaces. A package-less row ' + + 'is in every package\'s served-row order, so a list stored there at a form\'s name would leave nothing ' + + 'served for that name from the package. Some such saves are admitted today: several packages ship the ' + + 'name, the base has no pair, a re-save of a row its pair already holds, a container that overlays the ' + + 'package\'s own. The refusal bites for a name from the release in which a package authors it as a `form` ' + + 'item (`400 VALIDATION_ERROR`, naming the package)', + acceptanceCriteria: + 'Every `defineForm` call builds a `form` item that parses under `FormSchema` (its name `OBJECT.KEY`, its ' + + 'body at the top level, no `data`); a Studio metadata-editing form is built with `defineMetadataForm`. No ' + + 'package-less `view` row stores a list at a name a read-only package authors as a `form` item; the same ' + + 'list under another key, or in an app of the environment\'s own, saves as before.', +}; diff --git a/packages/spec/src/stack.zod.ts b/packages/spec/src/stack.zod.ts index 717d193aae1..8e2ced22ff5 100644 --- a/packages/spec/src/stack.zod.ts +++ b/packages/spec/src/stack.zod.ts @@ -63,7 +63,7 @@ import { SeedSchema } from './data/seed.zod'; // UI Protocol import { AppSchema } from './ui/app.zod'; -import { ViewSchema, isAggregatedViewContainer, expandViewContainer } from './ui/view.zod'; +import { ViewSchema, FormSchema, isAggregatedViewContainer, expandViewContainer } from './ui/view.zod'; import { deriveViewContainerObject } from './ui/view-container-object'; import { defaultRecordPageObject } from './ui/default-record-page'; import { PageSchema } from './ui/page.zod'; @@ -909,6 +909,7 @@ const STACK_DEFINITION_COLLECTIONS_SHAPE = { + '(standalone ViewItems, flattened overlays) — written by package export and artifact ' + 'factories, refused in authored stack sources.', ), + forms: z.array(FormSchema).optional().describe('Data-entry forms, one object each (ADR-0159): `defineForm` items named `OBJECT.KEY`'), pages: z.array(PageSchema).optional().describe('Custom Pages'), dashboards: z.array(DashboardSchema).optional().describe('Dashboards'), reports: z.array(ReportSchema).optional().describe('Analytics Reports'), @@ -1674,6 +1675,7 @@ export const COMPOSE_KEY_DISPOSITIONS = Object.freeze({ // manifests are not `composeStacks` inputs today; if two ever were, their // non-container view artifacts would concatenate like every other collection. viewItems: 'concat', + forms: 'concat', pages: 'concat', dashboards: 'concat', reports: 'concat', @@ -3397,6 +3399,7 @@ const SAME_STACK_ENTRY_IDENTITY = Object.freeze({ "one's configuration.", remedy: RENAME_OR_MERGE, }, + forms: lastWinsByName('Form', 'forms'), pages: lastWinsByName('Page', 'pages'), dashboards: lastWinsByName('Dashboard', 'dashboards'), reports: lastWinsByName('Report', 'reports'), diff --git a/packages/spec/src/system/i18n-resolver.form-item.test.ts b/packages/spec/src/system/i18n-resolver.form-item.test.ts new file mode 100644 index 00000000000..f3a2ee139e6 --- /dev/null +++ b/packages/spec/src/system/i18n-resolver.form-item.test.ts @@ -0,0 +1,80 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [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). + */ + +import { describe, expect, it } from 'vitest'; +import { translateForm, translateMetadataDocument } from './i18n-resolver'; +import { TranslationDataSchema, type TranslationBundle } from './translation.zod'; + +const clone = (v: T): T => JSON.parse(JSON.stringify(v)); + +const FORM = { + name: 'crm_lead.web_to_lead', + object: 'crm_lead', + label: 'Web to lead', + description: 'The public lead form', + title: 'Contact us', + submitBehavior: { kind: 'thank-you', title: 'Thanks!', message: 'We will be in touch.' }, + sections: [{ fields: [{ field: 'name' }] }], +}; + +const ZH_FORMS = { + forms: { + 'crm_lead.web_to_lead': { + label: '网页线索', + description: '公开的线索表单', + title: '联系我们', + submitBehavior: { title: '谢谢!' }, + }, + }, +}; +const ZH_VIEWS_ONLY = { + objects: { + crm_lead: { + _views: { web_to_lead: { label: 'MUST-NOT-APPLY', title: '旧地址标题', submitBehavior: { message: '旧地址消息' } } }, + }, + }, +}; + +describe('translateForm — the `forms` family, `_views` tails as fallback', () => { + 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); + }); + + it('reads `forms.NAME` for every translatable string', () => { + const bundle: TranslationBundle = { 'zh-CN': ZH_FORMS as any }; + const out = translateMetadataDocument('form', clone(FORM), bundle, { locale: 'zh-CN' }) as any; + expect(out).toMatchObject({ + label: '网页线索', + description: '公开的线索表单', + title: '联系我们', + submitBehavior: { title: '谢谢!', message: 'We will be in touch.' }, + }); + }); + + it('falls back to the `_views.KEY` tails for title and submitBehavior, never for the label', () => { + 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('旧地址消息'); + expect(out.label).toBe('Web to lead'); + }); + + it('`forms.NAME` wins over the `_views` tail when both are present', () => { + const bundle: TranslationBundle = { 'zh-CN': { ...ZH_VIEWS_ONLY, ...ZH_FORMS } as any }; + const out = translateForm(clone(FORM), bundle, { locale: 'zh-CN' }) as any; + expect(out.title).toBe('联系我们'); + }); + + it('CONTROL: no key leaves the authored strings, and the document unchanged', () => { + const doc = clone(FORM); + expect(translateForm(doc, { 'zh-CN': {} as any }, { locale: 'zh-CN' })).toBe(doc); + }); +}); diff --git a/packages/spec/src/system/i18n-resolver.ts b/packages/spec/src/system/i18n-resolver.ts index ab9c0c75753..f774cee9970 100644 --- a/packages/spec/src/system/i18n-resolver.ts +++ b/packages/spec/src/system/i18n-resolver.ts @@ -1943,6 +1943,97 @@ export function translateView( }; } +/** Minimal `form` item shape consumed by {@link translateForm}. */ +export interface FormLike { + name: string; + object: string; + label?: string; + description?: string; + title?: string; + sections?: unknown; + submitBehavior?: unknown; + [key: string]: any; +} + +/** One string off `forms.` (a path below it), across the locale chain. */ +function lookupFormText( + bundle: TranslationBundle | undefined, + formName: string, + path: readonly string[], + opts: ResolveOptions | undefined, +): string | undefined { + if (!bundle) return undefined; + for (const code of localeChain(opts)) { + let node: any = (pickData(bundle, code) as { forms?: Record } | undefined)?.forms?.[formName]; + for (const key of path) node = node?.[key]; + if (typeof node === 'string' && node.length > 0) return node; + } + return undefined; +} + +/** + * [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 + * copy keeps `objects.._sections.
` as its object-level + * default ({@link translateFormSections}). The override rule is the view's: + * a string authored on top of the packaged form keeps its text against the + * catalog (ADR-0029 D9.2a, {@link valueOverridesPackagedBase}). + */ +export function translateForm( + form: T, + bundle: TranslationBundle | undefined, + opts?: TranslateDocumentOptions, +): T { + if (typeof form.name !== 'string' || typeof form.object !== 'string') return form; + const base = asRecord(opts?.packagedBase); + 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; + return lookupFormText(catalogFor(catalogs, valueOverridesPackagedBase(base, attr, value)), name, [attr], opts); + }; + const label = own('label'); + const description = own('description'); + 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; + } + const submitBehavior = translateFormSubmitBehavior( + form.submitBehavior, + catalogs, + (catalog, attr) => lookupFormText(catalog, name, ['submitBehavior', attr], opts) + ?? lookupSubmitBehaviorText(catalog, objectName, key, attr, opts), + base, + ); + const sections = catalogs.unchanged + ? translateFormSections(form.sections, catalogs, formSectionObjectName(form, objectName), opts, base) + : form.sections; + if (label === undefined && description === undefined && title === form.title + && submitBehavior === form.submitBehavior && sections === form.sections) { + return form; + } + return { + ...form, + ...(label !== undefined ? { label } : {}), + ...(description !== undefined ? { description } : {}), + ...(title !== form.title ? { title } : {}), + ...(submitBehavior !== form.submitBehavior ? { submitBehavior } : {}), + ...(sections !== form.sections ? { sections } : {}), + }; +} + /** * Apply the active locale to an action metadata document by overwriting * `label`, `description`, `confirmText`, `successMessage`, `disabledReason`, @@ -2063,6 +2154,9 @@ const METADATA_DOCUMENT_TRANSLATORS: Record< // mapping by label from `GET /meta/mapping`, so registering here is the // whole wiring. mapping: translateMapping, + // [ADR-0159 D8] A `form` item: `forms.` first, its old-shape `_views` + // tails as the declared fallback. + form: translateForm, }; /** diff --git a/packages/spec/src/system/translation.zod.ts b/packages/spec/src/system/translation.zod.ts index 033cc6ecb9d..e209541c9b1 100644 --- a/packages/spec/src/system/translation.zod.ts +++ b/packages/spec/src/system/translation.zod.ts @@ -1100,9 +1100,9 @@ const PER_APP_SETTINGS_PLATFORM_ONLY = + '(`@objectstack/service-settings`\'s `settingsBuiltinTranslations`, typed ' + '`PlatformTranslationData`); a key it does not translate falls back to the manifest\'s own ' + 'literal, so correct it there rather than filling the gap from an application. For an ' - + 'application\'s own copy use the seventeen groups this bundle does declare, in the order it ' + + 'application\'s own copy use the eighteen groups this bundle does declare, in the order it ' + "declares them — 'objects', 'picklists', 'apps', 'messages', 'globalActions', 'dashboards', " - + "'datasets', 'reports', 'pages', 'flows', 'hooks', 'positions', 'permissions', 'books', " + + "'datasets', 'reports', 'pages', 'forms', 'flows', 'hooks', 'positions', 'permissions', 'books', " + "'mappings', 'metadataForms', 'settingsCommon'. " + "Note the last one: 'settingsCommon' IS " + 'on this face, so the Settings UI shell strings an application may translate (the source ' @@ -1145,7 +1145,7 @@ const ITEM_SETTINGS_PLATFORM_ONLY = + '(`@objectstack/service-settings`\'s `settingsBuiltinTranslations`, typed ' + '`PlatformTranslationData`); a key it does not translate falls back to the manifest\'s own ' + 'literal, so correct it there rather than overriding it from an application. For an ' - + 'application\'s own copy use the groups this item does declare — the same seventeen a per-app ' + + 'application\'s own copy use the groups this item does declare — the same eighteen a per-app ' + "bundle declares, 'settingsCommon' among them: the Settings UI shell strings an application " + 'may translate (the source badges, under `settingsCommon.sourceLabels`) are NOT what is being ' + "refused here — only the per-namespace manifest copy under 'settings' is. " @@ -1184,12 +1184,12 @@ const ITEM_TRANSLATION_KEY_GUIDANCE: Record = { */ /** * The translation groups an APPLICATION may author, as a shape rather than a - * schema. Seventeen groups — the eighteenth, `settings`, is platform-only and lives in + * schema. Eighteen groups — the nineteenth, `settings`, is platform-only and lives in * {@link platformSettingsShape}. * * Three schemas need exactly these keys: {@link TranslationDataSchema} (one - * entry of a per-app file-authored bundle — these seventeen and no more), - * {@link PlatformTranslationDataSchema} (these seventeen plus `settings`) and + * entry of a per-app file-authored bundle — these eighteen and no more), + * {@link PlatformTranslationDataSchema} (these eighteen plus `settings`) and * {@link TranslationItemSchema} (the registered `translation` metadata type — * the per-app face plus `locale`, its identity keys and the ADR-0010 * envelope; it carried the platform face's `settings` too until #19620). The item used to @@ -1807,6 +1807,36 @@ const appTranslationDataShape = () => ({ })).optional().describe('Per-component copy keyed by component id (`PageComponentSchema.id`)'), })).optional().describe('Page translations keyed by page name'), + /** + * [ADR-0159 D8] `form` item translations keyed by the form's name + * (`Form.name`, `OBJECT.KEY`). + * + * Convention: + * forms..label + * forms..description + * forms..title + * forms..submitBehavior.title (a `thank-you` panel) + * forms..submitBehavior.message + * + * The translator reads `forms.NAME` first; the form tails a form defined in + * a view had under `objects.OBJECT._views.KEY` (`title`, `submitBehavior`) + * are the declared fallback, so a bundle written for the old shape keeps + * translating the same form. `label` and `description` under `_views.KEY` + * are a view's, not form tails: they are neither moved nor read as a + * fallback. Section copy keeps `objects.OBJECT._sections.SECTION` as its + * object-level default. + */ + forms: z.record(z.string(), strictObject({ + surface: 'this form translation', + history: TRANSLATION_HISTORY, + aliases: { name: 'label', heading: 'title' }, + }, { + label: z.string().optional().describe('Translated form label'), + description: z.string().optional().describe('Translated form description'), + title: z.string().optional().describe('Translated form heading (overlays the form\'s `title`)'), + submitBehavior: submitBehaviorTranslationSchema('this form submit behavior translation').optional().describe("Translated thank-you panel copy — overlays the form's `submitBehavior` `title` / `message` when its `kind` is `'thank-you'`"), + })).optional().describe('Form translations keyed by form name (ADR-0159 D8)'), + /** * Screen-flow translations keyed by flow name (`Flow.name`). * @@ -2730,10 +2760,10 @@ const platformSettingsShape = () => ({ * One locale of a PER-APP translation bundle — `stack.translations`, and * everything {@link defineTranslationBundle} builds. * - * Seventeen groups: every group the platform bundle declares EXCEPT `settings`, + * Eighteen groups: every group the platform bundle declares EXCEPT `settings`, * which is platform-only and is refused here by name with * {@link PER_APP_SETTINGS_PLATFORM_ONLY} as the remedy. See - * {@link PlatformTranslationDataSchema} for the eighteen-group face and for why + * {@link PlatformTranslationDataSchema} for the nineteen-group face and for why * the two are separate namespaces. */ export const TranslationDataSchema = lazySchema(() => strictObject({ @@ -2744,7 +2774,7 @@ export const TranslationDataSchema = lazySchema(() => strictObject({ // `settings`, and an alias prescribing a key the shape rejects is a // suggestion the author cannot take (the `alias-integrity` audit judges // exactly that). Both spellings are answered by `guidance` above instead. - aliases: { object: 'objects', fields: 'objects', app: 'apps', page: 'pages', dashboard: 'dashboards', dataset: 'datasets', report: 'reports', picklist: 'picklists', flow: 'flows', hook: 'hooks', position: 'positions', permission: 'permissions', permissionSets: 'permissions', book: 'books', mapping: 'mappings', message: 'messages', strings: 'messages', labels: 'messages', actions: 'globalActions' }, + aliases: { object: 'objects', fields: 'objects', app: 'apps', page: 'pages', form: 'forms', dashboard: 'dashboards', dataset: 'datasets', report: 'reports', picklist: 'picklists', flow: 'flows', hook: 'hooks', position: 'positions', permission: 'permissions', permissionSets: 'permissions', book: 'books', mapping: 'mappings', message: 'messages', strings: 'messages', labels: 'messages', actions: 'globalActions' }, // `locale` lives on the ITEM, not on a bundle entry (the bundle keys ARE the // locales). Naming it keeps the suggestion useful for an author who moved a // `translation` item into a bundle and left the field behind. @@ -2754,7 +2784,7 @@ export const TranslationDataSchema = lazySchema(() => strictObject({ export type TranslationData = z.input; /** - * One locale of a PLATFORM translation bundle — the eighteen groups, `settings` + * One locale of a PLATFORM translation bundle — the nineteen groups, `settings` * included. * * The platform's own bundles are code, not authored metadata @@ -2789,7 +2819,7 @@ export const PlatformTranslationDataSchema = lazySchema(() => strictObject({ surface: 'this locale of the platform translation bundle', history: TRANSLATION_HISTORY, guidance: TRANSLATION_KEY_GUIDANCE, - aliases: { object: 'objects', fields: 'objects', app: 'apps', page: 'pages', dashboard: 'dashboards', dataset: 'datasets', report: 'reports', picklist: 'picklists', flow: 'flows', hook: 'hooks', position: 'positions', permission: 'permissions', permissionSets: 'permissions', book: 'books', mapping: 'mappings', setting: 'settings', message: 'messages', strings: 'messages', labels: 'messages', actions: 'globalActions' }, + aliases: { object: 'objects', fields: 'objects', app: 'apps', page: 'pages', form: 'forms', dashboard: 'dashboards', dataset: 'datasets', report: 'reports', picklist: 'picklists', flow: 'flows', hook: 'hooks', position: 'positions', permission: 'permissions', permissionSets: 'permissions', book: 'books', mapping: 'mappings', setting: 'settings', message: 'messages', strings: 'messages', labels: 'messages', actions: 'globalActions' }, extraKeys: ['locale'], }, { ...appTranslationDataShape(), @@ -2998,7 +3028,7 @@ export type TranslationConfig = z.input; * to whoever — or whatever — authored it. * * `settings` is NOT on this door (#19620, ruling batch #210 item 2 letter B): - * the item takes the PER-APP face, the same seventeen groups as + * the item takes the PER-APP face, the same eighteen groups as * {@link TranslationDataSchema}, and refuses `settings` (and the singular * `setting`) by name with {@link ITEM_SETTINGS_PLATFORM_ONLY} as the remedy. * The file door and the item door are two authoring surfaces for one app @@ -3037,7 +3067,7 @@ export const TranslationItemSchema = lazySchema(() => strictObject({ // this door no longer declares `settings`, and an alias prescribing a key // the shape rejects is a suggestion the author cannot take. Both spellings // are answered by `guidance` above instead. - aliases: { object: 'objects', app: 'apps', page: 'pages', dataset: 'datasets', report: 'reports', picklist: 'picklists', flow: 'flows', hook: 'hooks', position: 'positions', permission: 'permissions', permissionSets: 'permissions', book: 'books', mapping: 'mappings', message: 'messages', strings: 'messages', labels: 'messages', actions: 'globalActions', lang: 'locale', language: 'locale' }, + aliases: { object: 'objects', app: 'apps', page: 'pages', form: 'forms', dataset: 'datasets', report: 'reports', picklist: 'picklists', flow: 'flows', hook: 'hooks', position: 'positions', permission: 'permissions', permissionSets: 'permissions', book: 'books', mapping: 'mappings', message: 'messages', strings: 'messages', labels: 'messages', actions: 'globalActions', lang: 'locale', language: 'locale' }, }, { ...appTranslationDataShape(), locale: LocaleSchema.describe('BCP-47 locale this item translates (e.g. "zh-CN")'), diff --git a/packages/spec/src/ui/anonymous-form-intake.ts b/packages/spec/src/ui/anonymous-form-intake.ts index 64898008b49..d4bf389b212 100644 --- a/packages/spec/src/ui/anonymous-form-intake.ts +++ b/packages/spec/src/ui/anonymous-form-intake.ts @@ -232,3 +232,25 @@ export function anonymousFormIntakeWithdrawnIn( } return false; } + +/** One withdrawal a layer holds: the served name it closes, and the slug its body names. */ +export interface FormWithdrawal { + name: string; + slug: string; +} + +/** + * The slug a form body EXPLICITLY withdraws: its `sharing` keeps a non-empty + * `publicLink` and sets `enabled === false` or `allowAnonymous === false`. + * Absent switches are not a withdrawal; a cleared link withdraws nothing (the + * rule `anonymousFormIntakeWithdrawnIn` applies to a `view` body). + */ +export function formExplicitlyWithdraws(form: unknown): string | undefined { + const sharing = (form as { sharing?: unknown } | null)?.sharing; + if (!sharing || typeof sharing !== 'object') return undefined; + const s = sharing as Record; + if (typeof s.publicLink !== 'string' || !s.publicLink) return undefined; + if (s.enabled !== false && s.allowAnonymous !== false) return undefined; + return publicFormSlug(s.publicLink); +} + diff --git a/packages/spec/src/ui/form-intake-layer.ts b/packages/spec/src/ui/form-intake-layer.ts new file mode 100644 index 00000000000..b9e1c00bb57 --- /dev/null +++ b/packages/spec/src/ui/form-intake-layer.ts @@ -0,0 +1,110 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { anonymousFormIntakeSlug, formExplicitlyWithdraws, type FormWithdrawal } from './anonymous-form-intake'; +import { projectViewForms } from './view.zod'; +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. + * + * - **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 + * `sharing` keeps a `publicLink` and sets `enabled` or `allowAnonymous` to + * `false`) closes the form, whatever slug either side declares. A + * definition under another name is a different form: the slug match + * decides no case in this layer. + * - **An unreadable body closes the links it names** (rule 7): a body the + * projection cannot turn into items closes every `sharing.publicLink` slug + * it names, and the caller says so once at `error`. + * - A withdrawal in one package closes the name's form in every package (a + * known limit that fails closed, as before). + */ + +/** A body the projection cannot read, and the links it closes (rule 7). */ +export interface UnreadableFormBody { + /** The stored row: its type, name and package (`undefined`: package-less). */ + type: 'view' | 'form'; + name: string; + packageId?: string; + reason: string; + /** The slugs it names, each closed. */ + links: string[]; +} + +/** The judged layer: the names withdrawn, and the slugs closed by unreadable bodies. */ +export interface FormIntakeLayer { + withdrawn: ReadonlyMap; + closedLinks: ReadonlyMap; +} + +const nameOf = (item: unknown): string | undefined => { + const name = (item as { name?: unknown } | null)?.name; + return typeof name === 'string' && name !== '' ? name : 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). + */ +export function formIntakeLayer(input: { + forms: ReadonlyArray; + views: ReadonlyArray; + unreadable?: ReadonlyArray; +}): FormIntakeLayer { + const withdrawn = new Map(); + const closedLinks = new Map(); + for (const form of input.forms) { + const name = nameOf(form); + const slug = formExplicitlyWithdraws(form); + if (name !== undefined && slug !== undefined && !withdrawn.has(name)) withdrawn.set(name, { name, slug }); + } + for (const view of input.views) { + for (const w of oldShapeFormWithdrawals(view)) if (!withdrawn.has(w.name)) withdrawn.set(w.name, w); + const projection = projectViewForms(view); + if (projection.unreadable !== undefined) { + const pkg = (view as { _packageId?: unknown } | null)?._packageId; + const body: UnreadableFormBody = { + type: 'view', + name: nameOf(view) ?? '', + ...(typeof pkg === 'string' && pkg !== '' ? { packageId: pkg } : {}), + reason: projection.unreadable.reason, + links: projection.unreadable.links, + }; + for (const link of body.links) if (!closedLinks.has(link)) closedLinks.set(link, body); + } + } + for (const body of input.unreadable ?? []) { + for (const link of body.links) if (!closedLinks.has(link)) closedLinks.set(link, body); + } + return { withdrawn, closedLinks }; +} + +/** The open form the doors serve at `slug`: the first candidate the layer does not close. */ +export function openFormAt( + forms: ReadonlyArray, + layer: FormIntakeLayer, + slug: string, +): { form: Record; object: string } | null { + if (layer.closedLinks.has(slug)) return null; + for (const item of forms) { + if (!item || typeof item !== 'object') continue; + const form = item as Record; + if (anonymousFormIntakeSlug(form.sharing) !== slug) continue; + const name = nameOf(form); + if (name === undefined || layer.withdrawn.has(name)) continue; + const object = typeof form.object === 'string' && form.object ? form.object : undefined; + if (object === undefined) continue; + return { form, object }; + } + return null; +} diff --git a/packages/spec/src/ui/form-item.test.ts b/packages/spec/src/ui/form-item.test.ts new file mode 100644 index 00000000000..5ad2c4741da --- /dev/null +++ b/packages/spec/src/ui/form-item.test.ts @@ -0,0 +1,162 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0159 card ② items 1, 4 and 6] The `form` metadata type at the spec + * layer: the authored item's schema (derived from `FormViewSchema` by + * reference, the name's prefix equal to its object, `data` and the view-item + * keys refused by name), THE projection of the three old `view` shapes, and + * the intake layer the anonymous doors judge withdrawal and closed links by. + */ + +import { describe, expect, it } from 'vitest'; +import { + FormSchema, + FormViewSchema, + PROJECTED_FORM_SOURCE_KEY, + defineForm, + projectViewForms, + projectedFormsOf, +} from './view.zod'; +import { formExplicitlyWithdraws } from './anonymous-form-intake'; +import { formIntakeLayer, openFormAt } from './form-intake-layer'; +import { oldShapeFormWithdrawals } from './old-shape-form-withdrawals'; + +const OPEN = { enabled: true, allowAnonymous: true, publicLink: '/forms/contact-us' }; +const SECTIONS = [{ fields: [{ field: 'name' }, { field: 'email' }] }]; +const authored = (over: Record = {}) => ({ + name: 'crm_lead.web_to_lead', + object: 'crm_lead', + type: 'simple', + sections: SECTIONS, + sharing: OPEN, + ...over, +}); +const issuesOf = (value: unknown) => { + const r = FormSchema.safeParse(value); + return r.success ? [] : r.error.issues.map((i) => ({ path: i.path.join('.'), message: i.message })); +}; + +describe('[ADR-0159 D2, D3] FormSchema — the authored `form` item', () => { + it('parses a form whose name is OBJECT.KEY, its body at the top level', () => { + const parsed = defineForm(authored() as Parameters[0]); + expect(parsed.name).toBe('crm_lead.web_to_lead'); + expect(parsed.object).toBe('crm_lead'); + expect(parsed.sharing?.publicLink).toBe('/forms/contact-us'); + }); + + it('derives every body key from FormViewSchema by reference, less `data`', () => { + const body = Object.keys(FormViewSchema.shape).filter((k) => k !== 'data'); + const shape = (FormSchema as any).shape ?? (FormSchema as any)._def?.schema?.shape; + // The authored item accepts each body key of the form view (none is transcribed). + for (const key of body) expect(issuesOf(authored({ [key]: undefined })).filter((i) => i.path === key)).toEqual([]); + expect(shape === undefined || !('data' in shape)).toBe(true); + }); + + it('refuses a name whose prefix is not its object, with the rename', () => { + const issues = issuesOf(authored({ name: 'crm_contact.web_to_lead' })); + expect(issues).toHaveLength(1); + expect(issues[0].path).toBe('name'); + expect(issues[0].message).toContain("Rename it 'crm_lead.web_to_lead'"); + }); + + it.each(['data', 'viewKind', 'config', 'isDefault', 'order', 'scope'])('refuses `%s` by name', (key) => { + const issues = issuesOf(authored({ [key]: key === 'data' ? { provider: 'object', object: 'crm_lead' } : 'form' })); + expect(issues.length).toBeGreaterThan(0); + expect(issues.map((i) => i.message).join(' ')).toContain(`\`${key}\``); + }); + + it('applies the form view\'s cross-field rules (one Zod source)', () => { + // A tabbed form with no sections is refused by the view rules, so it is by the item. + const view = FormViewSchema.safeParse({ type: 'tabbed' }); + const item = FormSchema.safeParse(authored({ type: 'tabbed', sections: undefined })); + expect(item.success).toBe(view.success); + }); +}); + +describe('[ADR-0159 D5] projectViewForms — THE projection of the three old shapes', () => { + it('projects a container\'s `form` and each `formViews` entry under the names the expansion serves', () => { + const { forms, lists } = projectViewForms({ + name: 'crm_lead', + list: { type: 'grid', columns: ['name'] }, + form: { type: 'simple', sections: SECTIONS }, + formViews: { contact: { type: 'simple', sections: SECTIONS, sharing: OPEN } }, + }); + expect(forms.map((f) => [f.name, f.object])).toEqual([['crm_lead.contact', 'crm_lead'], ['crm_lead.form', 'crm_lead']]); + expect(forms[0].sharing).toEqual(OPEN); + expect(forms[0][PROJECTED_FORM_SOURCE_KEY]).toBe('view'); + expect(lists.length).toBeGreaterThan(0); + }); + + it('projects a `viewKind: \'form\'` item under its own name, the body lifted unchanged', () => { + const config = { type: 'simple', data: { provider: 'object', object: 'crm_lead' }, sections: SECTIONS, sharing: OPEN }; + const { forms, lists } = projectViewForms({ name: 'contact_us', viewKind: 'form', label: 'Contact', config }); + expect(lists).toEqual([]); + expect(forms).toHaveLength(1); + // Never parsed by FormSchema: the name keeps no OBJECT prefix and `data` stays. + expect(forms[0]).toMatchObject({ name: 'contact_us', object: 'crm_lead', label: 'Contact', data: config.data }); + }); + + it('carries the view item\'s own requiredPermissions onto the projected form', () => { + const { forms } = projectViewForms({ + name: 'contact_us', viewKind: 'form', requiredPermissions: ['crm.read'], + config: { data: { provider: 'object', object: 'crm_lead' }, sections: SECTIONS }, + }); + expect(forms[0].requiredPermissions).toEqual(['crm.read']); + }); + + it('reads a list item as a list, never a form', () => { + expect(projectViewForms({ name: 'all_leads', viewKind: 'list', config: { columns: ['name'] } })).toEqual({ forms: [], lists: ['all_leads'] }); + }); + + it.each([ + ['a container `formViews` that is not an object', { name: 'crm_lead', form: { sharing: OPEN }, formViews: 'x' }], + ['a `formViews` entry that is not an object', { name: 'crm_lead', form: { sharing: OPEN }, formViews: { a: 3 } }], + ['a `viewKind: \'form\'` item with no config', { name: 'contact_us', viewKind: 'form', sharing: OPEN }], + ])('reads %s as unreadable, with the links it names (rule 7)', (_label, body) => { + const projection = projectViewForms(body); + expect(projection.forms).toEqual([]); + expect(projection.unreadable?.links).toEqual(['contact-us']); + }); + + it('projectedFormsOf keeps the first body that projects a name, containers first', () => { + const item = { name: 'crm_lead.contact', viewKind: 'form', config: { data: { provider: 'object', object: 'crm_lead' }, title: 'item' } }; + const container = { name: 'crm_lead', formViews: { contact: { title: 'container' } } }; + const forms = projectedFormsOf([item, container]); + expect(forms.map((f) => [f.name, f.title])).toEqual([['crm_lead.contact', 'container']]); + }); +}); + +describe('[ADR-0159 D6] the intake layer — withdrawal by name, closed links', () => { + it('formExplicitlyWithdraws reads a kept link with an explicit off switch', () => { + expect(formExplicitlyWithdraws({ sharing: { ...OPEN, enabled: false } })).toBe('contact-us'); + expect(formExplicitlyWithdraws({ sharing: { ...OPEN, allowAnonymous: false } })).toBe('contact-us'); + expect(formExplicitlyWithdraws({ sharing: OPEN })).toBeUndefined(); + expect(formExplicitlyWithdraws({ sharing: { enabled: false } })).toBeUndefined(); + }); + + it('oldShapeFormWithdrawals reads through the projection', () => { + expect(oldShapeFormWithdrawals({ name: 'crm_lead', formViews: { contact: { sharing: { ...OPEN, enabled: false } } } })) + .toEqual([{ name: 'crm_lead.contact', slug: 'contact-us' }]); + }); + + it('a form withdrawn by name in any body is not served at its address', () => { + const form = { ...authored(), name: 'crm_lead.web_to_lead' }; + const layer = formIntakeLayer({ forms: [{ ...form, sharing: { ...OPEN, enabled: false } }], views: [] }); + expect(openFormAt([form], layer, 'contact-us')).toBeNull(); + expect(openFormAt([form], formIntakeLayer({ forms: [form], views: [] }), 'contact-us')).toMatchObject({ object: 'crm_lead' }); + }); + + it('identity is the whole item\'s name: a withdrawal of another name sharing the slug does not close this form (rule 6)', () => { + const form = authored(); + const other = { ...authored(), name: 'crm_lead.other', sharing: { ...OPEN, enabled: false } }; + expect(openFormAt([form], formIntakeLayer({ forms: [other], views: [] }), 'contact-us')).toMatchObject({ form }); + }); + + it('an unreadable stored body closes the links it names (rule 7)', () => { + const layer = formIntakeLayer({ forms: [], views: [{ name: 'contact_us', viewKind: 'form', sharing: OPEN, _packageId: 'com.acme' }] }); + expect(layer.closedLinks.get('contact-us')).toMatchObject({ type: 'view', name: 'contact_us', packageId: 'com.acme' }); + expect(openFormAt([authored()], layer, 'contact-us')).toBeNull(); + const reported = formIntakeLayer({ forms: [], views: [], unreadable: [{ type: 'view', name: 'x', reason: 'r', links: ['contact-us'] }] }); + expect(openFormAt([authored()], reported, 'contact-us')).toBeNull(); + }); +}); diff --git a/packages/spec/src/ui/index.ts b/packages/spec/src/ui/index.ts index 54ac93501b5..0fbce5a429f 100644 --- a/packages/spec/src/ui/index.ts +++ b/packages/spec/src/ui/index.ts @@ -95,6 +95,8 @@ export * from './sharing.zod'; // read these bindings through `@objectstack/metadata-core`, which re-exports // them, and a console imports them from here instead of re-reading the keys. export * from './anonymous-form-intake'; +export * from './old-shape-form-withdrawals'; +export * from './form-intake-layer'; // --------------------------------------------------------------------------- // RETIRED in v17 (#4988, ADR-0049 enforce-or-remove): the five interaction diff --git a/packages/spec/src/ui/old-shape-form-withdrawals.ts b/packages/spec/src/ui/old-shape-form-withdrawals.ts new file mode 100644 index 00000000000..e3e8bd090d4 --- /dev/null +++ b/packages/spec/src/ui/old-shape-form-withdrawals.ts @@ -0,0 +1,32 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { projectViewForms } from './view.zod'; +import { formExplicitlyWithdraws, type FormWithdrawal } from './anonymous-form-intake'; + +/** + * [ADR-0159 D6 rule 10, D7; ruled question 4 = A] THE reader of a withdrawal + * held in an OLD-SHAPE body: the forms a stored `view` body (a container's + * `form`, a `formViews` entry, a `viewKind: 'form'` item) explicitly + * withdraws, read through THE projection ({@link projectViewForms}), each under + * the name it is served as. + * + * ⛔ ADR-0159: exempt from the ADR-0087 age-out; leaves only by a release + * whose upgrade precheck refuses a deployment still holding an old-shape form + * row. A permission boundary: an old-shape row that withdraws a public form + * keeps it withdrawn after the form's source moves to `forms:`, and no + * withdrawn public form may re-open. It is not registered as an ADR-0087 + * conversion-layer entry, so no retirement clock starts on it; the upgrade + * precheck is card ⑤'s (major 19). + * + * A body the projection cannot turn into items withdraws nothing BY NAME + * here: its links are closed by the two-type layer (D6 rule 7, + * `formIntakeLayer`), which reads {@link projectViewForms}' `unreadable`. + */ +export function oldShapeFormWithdrawals(body: unknown): FormWithdrawal[] { + const out: FormWithdrawal[] = []; + for (const form of projectViewForms(body).forms) { + const withdrawal = formExplicitlyWithdraws(form); + if (withdrawal !== undefined) out.push({ name: form.name, slug: withdrawal }); + } + return out; +} diff --git a/packages/spec/src/ui/view.zod.ts b/packages/spec/src/ui/view.zod.ts index d3af2c19eed..b1084359d81 100644 --- a/packages/spec/src/ui/view.zod.ts +++ b/packages/spec/src/ui/view.zod.ts @@ -90,6 +90,8 @@ import { lazySchema } from '../shared/lazy-schema'; // This file's shared refusal history (#4001), declared outside it since #21229 // so the export options block it shares with the `object-grid` row keeps it. import { VIEW_HISTORY } from './view-history'; +import { anonymousFormObjectName, publicFormSlug } from './anonymous-form-intake'; +import { deriveViewContainerObject } from './view-container-object'; // [#21229] The export options block — its format enum, the retired-`'pdf'` // prescription and the five-member object — declared once, outside the `ui` // barrel: the `object-grid` page-component row takes the object by identity. @@ -5390,6 +5392,147 @@ const FORM_VIEW_LAYOUT_RETIRED: ReadonlyMap = new Map([ + '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.'], ]); +/** + * The cross-field rules of a form body: the section, wizard-step and + * field-predicate checks {@link FormViewSchema} runs. A named function so the + * `form` metadata type ({@link FormSchema}, ADR-0159 D2), whose body IS a form + * view's, attaches this same binding instead of a copy. + */ +function checkFormViewBody(view: any, ctx: z.RefinementCtx): void { + // Section-level checks. `.extend()` keeps this refinement (zod 4 attaches + // refinements to the schema), so the flattened runtime-overlay variant in + // ViewMetadataSchema enforces it too. [#27155] The split-only `pane` check + // that used to open this loop is gone: `pane` is a `retiredKey()` tombstone + // now, refused on every form type at the section itself. + // + // ⚠️ This refinement runs BEFORE the `.overwrite()` fold — see + // {@link foldFormGroupsIntoSections} — so every check here must keep + // reading BOTH buckets (`sections` AND the legacy `groups` alias). + for (const [key, sections] of [['sections', view.sections], ['groups', view.groups]] as const) { + sections?.forEach((section, index) => { + // The `features.*` scope-root exclusion (ruled 2026-08-27, objectui#6262 + // — see {@link checkFormViewPredicateFeaturesRoot}): every predicate + // this form view carries — section-level, field-level at any depth, + // per-option — is refused when it names the root that is unbound on the + // standalone form routes. Runs on every form `type`. + const sectionRefusal = checkFormViewPredicateFeaturesRoot(section?.visibleWhen); + if (sectionRefusal) { + ctx.addIssue({ code: 'custom', path: [key, index, 'visibleWhen'], message: sectionRefusal }); + } + section?.fields?.forEach((field, fieldIndex) => { + refineFormFieldFeaturesRoot(field, [key, index, 'fields', fieldIndex], ctx); + }); + // [#13704] Wizard steps carry no predicate slot and do not collapse — + // objectui#6237's ruled `FormSectionConfig` split ("WizardForm steps = + // No"), upgraded from a renderer fact to a parse refusal (#13622 D2/T2, + // ruled 2026-08-31). Breadth is ruled NARROW: exactly this step-key + // family — no per-type presentation-key matrix. + // + // Post-parse observability decides the spellings checked here: the + // retired `visibleOn` never reaches this refinement (its tombstone on + // `FormSectionSchema` refuses it at the section, #23543 F4), so the + // canonical key is the one spelling to check. `collapsible` / + // `collapsed` carry `.default(false)`, so an authored `false` is + // indistinguishable from the default here — and needs no refusal: it + // declares exactly the behavior a wizard delivers. Only `true` declares + // behavior a wizard step does not have. + if (view.type === 'wizard' && section != null) { + if (section.visibleWhen != null) { + ctx.addIssue({ + code: 'custom', + path: [key, index, 'visibleWhen'], + message: + '`visibleWhen` on a wizard step is refused: wizard steps carry no predicate slot ' + + '— steps are entered in array order behind the step gate, ' + + 'never conditionally. Put the predicate on the fields inside the step, or use a ' + + '`simple`/`tabbed` form for section-level visibility.', + }); + } + for (const collapseKey of ['collapsible', 'collapsed'] as const) { + if (section[collapseKey] === true) { + ctx.addIssue({ + code: 'custom', + path: [key, index, collapseKey], + message: + `\`${collapseKey}\` on a wizard step is refused: wizard steps do not collapse — ` + + 'the wizard shows exactly the current step. Remove the key; collapsible ' + + 'grouping belongs to `simple`/`tabbed` sections.', + }); + } + } + // [#13855] The field-group REFERENCE form is refused on a wizard step + // for the same reason the two refusals above exist, one layer back: a + // `fieldGroups` entry carries `visibleWhen` and `collapse`, and + // `deriveFieldGroupLayout` passes both through to the derived section. + // Accepting `group` here would hand a wizard step exactly the predicate + // and collapse state #13704 just finished refusing — reached through + // the object's declaration instead of the step's own keys, so the + // refusals above would report clean while the behaviour arrived anyway. + // The section schema cannot see the group (that is cross-schema), so + // the honest answer at parse is to refuse the reference on this form + // type, not to guess what the group declares. + // + // Deliberately the CONSERVATIVE direction: a wizard step whose group + // declares neither key is legal metadata this refuses today, and + // allowing it later (once the renderer half lands and a ruling covers a + // derived predicate on a step) is additive. + if (section.group != null) { + ctx.addIssue({ + code: 'custom', + path: [key, index, 'group'], + message: + '`group` on a wizard step is refused: a field group carries `visibleWhen` and ' + + '`collapse`, and `deriveFieldGroupLayout` passes both through to the section it ' + + 'derives — neither of which a wizard step has a slot for (steps are entered in ' + + 'array order behind the step gate, and the wizard shows exactly the current step). ' + + 'Enumerate the step with `fields: [...]`, or use a `simple`/`tabbed` form to ' + + 'inherit the group.', + }); + } + } + }); + } + // [#13704] A wizard must declare its steps (#13622 D7, ruled 2026-08-31). + // Before this refusal, `type: 'wizard'` with absent/empty `sections` + // silently fell back to plain simple rendering (objectui RecordFormPage's + // conditional spread + ObjectForm's `sections?.length` guard) — the + // 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` = + // `.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 + // by the base view, is its load-bearing round-trip shape (#7025 pins that + // membership; moving it needs its own ruling, per #7741's precedent). The + // extension's required `viewKind` is the structural marker of that door: on + // THIS strict shape the key can never be present (unknown keys are refused + // before acceptance), so reading it distinguishes the doors mechanically. + // The step-KEY refusals above run on every door on purpose — they fire only + // on a key the author wrote, which is never a partial-overlay artifact. + if (view.type === 'wizard' && typeof (view as { viewKind?: unknown }).viewKind !== 'string') { + // Mirror `foldFormGroupsIntoSections`' precedence exactly (`sections` + // wins even when empty), and report at the bucket the author wrote — + // canonical `sections` when neither bucket is present. + const steps = view.sections !== undefined ? view.sections : view.groups; + if (steps === undefined || steps.length === 0) { + const authoredKey = + view.sections !== undefined ? 'sections' : view.groups !== undefined ? 'groups' : 'sections'; + ctx.addIssue({ + code: 'custom', + path: [authoredKey], + message: + "A `type: 'wizard'` form view must declare its steps: `" + + authoredKey + '` is ' + (steps === undefined ? 'absent' : 'empty') + + ', and the wizard would silently render as a plain simple form. Declare at least one ' + + 'step — `sections: [{ label, fields: [...] }]`; sections ARE the steps, in array order.', + }); + } + } +} + /** * Form View Schema * Defines the layout for creating or editing a single record. @@ -5740,140 +5883,7 @@ export const FormViewSchema = lazySchema(() => strictObject({ defaults: z.record(z.string(), z.unknown()).optional() .describe('Initial field values for create-mode forms (folded into ObjectUI ObjectForm initial values;).'), -}).superRefine((view, ctx) => { - // Section-level checks. `.extend()` keeps this refinement (zod 4 attaches - // refinements to the schema), so the flattened runtime-overlay variant in - // ViewMetadataSchema enforces it too. [#27155] The split-only `pane` check - // that used to open this loop is gone: `pane` is a `retiredKey()` tombstone - // now, refused on every form type at the section itself. - // - // ⚠️ This refinement runs BEFORE the `.overwrite()` fold — see - // {@link foldFormGroupsIntoSections} — so every check here must keep - // reading BOTH buckets (`sections` AND the legacy `groups` alias). - for (const [key, sections] of [['sections', view.sections], ['groups', view.groups]] as const) { - sections?.forEach((section, index) => { - // The `features.*` scope-root exclusion (ruled 2026-08-27, objectui#6262 - // — see {@link checkFormViewPredicateFeaturesRoot}): every predicate - // this form view carries — section-level, field-level at any depth, - // per-option — is refused when it names the root that is unbound on the - // standalone form routes. Runs on every form `type`. - const sectionRefusal = checkFormViewPredicateFeaturesRoot(section?.visibleWhen); - if (sectionRefusal) { - ctx.addIssue({ code: 'custom', path: [key, index, 'visibleWhen'], message: sectionRefusal }); - } - section?.fields?.forEach((field, fieldIndex) => { - refineFormFieldFeaturesRoot(field, [key, index, 'fields', fieldIndex], ctx); - }); - // [#13704] Wizard steps carry no predicate slot and do not collapse — - // objectui#6237's ruled `FormSectionConfig` split ("WizardForm steps = - // No"), upgraded from a renderer fact to a parse refusal (#13622 D2/T2, - // ruled 2026-08-31). Breadth is ruled NARROW: exactly this step-key - // family — no per-type presentation-key matrix. - // - // Post-parse observability decides the spellings checked here: the - // retired `visibleOn` never reaches this refinement (its tombstone on - // `FormSectionSchema` refuses it at the section, #23543 F4), so the - // canonical key is the one spelling to check. `collapsible` / - // `collapsed` carry `.default(false)`, so an authored `false` is - // indistinguishable from the default here — and needs no refusal: it - // declares exactly the behavior a wizard delivers. Only `true` declares - // behavior a wizard step does not have. - if (view.type === 'wizard' && section != null) { - if (section.visibleWhen != null) { - ctx.addIssue({ - code: 'custom', - path: [key, index, 'visibleWhen'], - message: - '`visibleWhen` on a wizard step is refused: wizard steps carry no predicate slot ' - + '— steps are entered in array order behind the step gate, ' - + 'never conditionally. Put the predicate on the fields inside the step, or use a ' - + '`simple`/`tabbed` form for section-level visibility.', - }); - } - for (const collapseKey of ['collapsible', 'collapsed'] as const) { - if (section[collapseKey] === true) { - ctx.addIssue({ - code: 'custom', - path: [key, index, collapseKey], - message: - `\`${collapseKey}\` on a wizard step is refused: wizard steps do not collapse — ` - + 'the wizard shows exactly the current step. Remove the key; collapsible ' - + 'grouping belongs to `simple`/`tabbed` sections.', - }); - } - } - // [#13855] The field-group REFERENCE form is refused on a wizard step - // for the same reason the two refusals above exist, one layer back: a - // `fieldGroups` entry carries `visibleWhen` and `collapse`, and - // `deriveFieldGroupLayout` passes both through to the derived section. - // Accepting `group` here would hand a wizard step exactly the predicate - // and collapse state #13704 just finished refusing — reached through - // the object's declaration instead of the step's own keys, so the - // refusals above would report clean while the behaviour arrived anyway. - // The section schema cannot see the group (that is cross-schema), so - // the honest answer at parse is to refuse the reference on this form - // type, not to guess what the group declares. - // - // Deliberately the CONSERVATIVE direction: a wizard step whose group - // declares neither key is legal metadata this refuses today, and - // allowing it later (once the renderer half lands and a ruling covers a - // derived predicate on a step) is additive. - if (section.group != null) { - ctx.addIssue({ - code: 'custom', - path: [key, index, 'group'], - message: - '`group` on a wizard step is refused: a field group carries `visibleWhen` and ' - + '`collapse`, and `deriveFieldGroupLayout` passes both through to the section it ' - + 'derives — neither of which a wizard step has a slot for (steps are entered in ' - + 'array order behind the step gate, and the wizard shows exactly the current step). ' - + 'Enumerate the step with `fields: [...]`, or use a `simple`/`tabbed` form to ' - + 'inherit the group.', - }); - } - } - }); - } - // [#13704] A wizard must declare its steps (#13622 D7, ruled 2026-08-31). - // Before this refusal, `type: 'wizard'` with absent/empty `sections` - // silently fell back to plain simple rendering (objectui RecordFormPage's - // conditional spread + ObjectForm's `sections?.length` guard) — the - // 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` = - // `.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 - // by the base view, is its load-bearing round-trip shape (#7025 pins that - // membership; moving it needs its own ruling, per #7741's precedent). The - // extension's required `viewKind` is the structural marker of that door: on - // THIS strict shape the key can never be present (unknown keys are refused - // before acceptance), so reading it distinguishes the doors mechanically. - // The step-KEY refusals above run on every door on purpose — they fire only - // on a key the author wrote, which is never a partial-overlay artifact. - if (view.type === 'wizard' && typeof (view as { viewKind?: unknown }).viewKind !== 'string') { - // Mirror `foldFormGroupsIntoSections`' precedence exactly (`sections` - // wins even when empty), and report at the bucket the author wrote — - // canonical `sections` when neither bucket is present. - const steps = view.sections !== undefined ? view.sections : view.groups; - if (steps === undefined || steps.length === 0) { - const authoredKey = - view.sections !== undefined ? 'sections' : view.groups !== undefined ? 'groups' : 'sections'; - ctx.addIssue({ - code: 'custom', - path: [authoredKey], - message: - "A `type: 'wizard'` form view must declare its steps: `" - + authoredKey + '` is ' + (steps === undefined ? 'absent' : 'empty') - + ', and the wizard would silently render as a plain simple form. Declare at least one ' - + 'step — `sections: [{ label, fields: [...] }]`; sections ARE the steps, in array order.', - }); - } - } -}).overwrite(foldFormGroupsIntoSections)); +}).superRefine(checkFormViewBody).overwrite(foldFormGroupsIntoSections)); /** * Object-scoped user filters (ADR-0047 amendment, framework #2679 / objectui #2338). @@ -6685,6 +6695,138 @@ export function defineViewItem(config: z.input): ViewItem return ViewItemSchema.parse(config); } +// ─────────────────────────────────────────────────────────────────────────── +// The `form` metadata type (ADR-0159) +// ─────────────────────────────────────────────────────────────────────────── + +/** + * [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 + * (`data.provider: 'schema'`) is a Studio metadata form + * ({@link defineMetadataForm}), not a `form` item. + */ +const FORM_ITEM_DATA_REFUSED = + 'A form item is bound with `object`, never with `data` (ADR-0159 D2): remove `data` and set `object` to the ' + + 'object the form submits into; the name\'s prefix is that object (`OBJECT.KEY`). A form bound to a JSON ' + + 'Schema is a Studio metadata form (`defineMetadataForm`), not a `form` item.'; + +/** [ADR-0159 D2] The view-item keys a `form` item does not carry, each with what to do instead. */ +const FORM_ITEM_GUIDANCE = { + data: FORM_ITEM_DATA_REFUSED, + viewKind: 'A form item has no `viewKind`: the `form` type is the discriminator (ADR-0159 D2). Remove the key.', + config: 'A form item carries its body at the top level, not under `config` (ADR-0159 D2, question 5): move ' + + 'the keys of `config` up beside `name` and `object`.', + isDefault: 'A form item has no `isDefault`: the object\'s record create and edit form is its `fieldGroups`, ' + + 'never a `form` item (ADR-0159 D1). Remove the key.', + order: 'A form item has no `order`: forms are not in the view switcher (ADR-0159 D2). Remove the key.', + scope: 'A form item has no `scope`: the registry\'s provenance already says package or runtime (ADR-0159 D2). ' + + 'Remove the key.', +} as const; + +/** + * [ADR-0159 D3] The part of a `form` item's name before its last segment must + * equal its `object`: `crm_lead.web_to_lead` is a form of `crm_lead`. The view + * item never enforced it; the `form` type does from its first release. Applied + * to AUTHORED items only: a form the projection reads out of an old shape + * ({@link projectViewForms}) is served under the name it is served under today + * and is never parsed by {@link FormSchema} (ADR-0159 D5). + */ +export function checkFormItemNamePrefix( + form: { name?: unknown; object?: unknown }, + ctx: z.RefinementCtx, +): void { + if (typeof form.name !== 'string' || typeof form.object !== 'string') return; + const cut = form.name.lastIndexOf('.'); + if (cut <= 0) return; // the name grammar refuses a name with no dot + const prefix = form.name.slice(0, cut); + if (prefix === form.object) return; + ctx.addIssue({ + code: 'custom', + path: ['name'], + message: + `The form name '${form.name}' names the object '${prefix}', but the form is bound to '${form.object}' ` + + '(ADR-0159 D3): a form is named `OBJECT.KEY` after the object it submits into. Rename it ' + + `'${form.object}.${form.name.slice(cut + 1)}', or bind it to '${prefix}'.`, + }); +} + +/** + * [ADR-0159 D2] The body keys of a `form` item: every key of + * {@link FormViewSchema}'s shape BY REFERENCE (never transcribed), less + * `data`, which a `form` item does not author (the object binding is + * `object`). + */ +function formItemBodyShape() { + const { data: _data, ...body } = FormViewSchema.shape; + return body; +} + +/** + * [ADR-0159 D2] A `form` metadata item: a named form with a consumer — a public + * form (it declares `sharing.publicLink`) or a form an action of + * `type: 'form'` opens. Its name is `OBJECT.KEY`, the name the form is served + * under (D3); it is bound to one object by `object`; and its body is a form + * view's, at the top level (ruled question 5: no `config` wrapper). + * + * - One Zod source: the body keys are {@link FormViewSchema}'s shape, by + * reference, and its cross-field rules are the same binding + * (`checkFormViewBody`, then the `groups` fold). + * - Not carried over from the view item: `viewKind`, `config`, `isDefault`, + * `order` and `scope` — each refused by name with its prescription. + * - `data` is refused by name: bind the form with `object`. + * - `object` must name an object the package can reference; that is judged + * where a view's object is judged (`os validate`, publish), not here. + * + * A record create or edit form is NOT a `form` item (ADR-0159 D1): it is the + * object's `fieldGroups`. + */ +export const FormSchema = lazySchema(() => strictObject({ + surface: 'this form', + history: VIEW_HISTORY, + guidance: FORM_ITEM_GUIDANCE, +}, { + name: ViewItemNameSchema.describe('The form\'s name, `OBJECT.KEY` (ADR-0159 D3): the name it is served under, the target of an action of `type: \'form\'`, and the key a declared override names. The part before the last segment is the form\'s `object`.'), + object: SnakeCaseIdentifierSchema.describe('The object the form submits into — its one binding (ADR-0159 D2). It must name an object the package can reference.'), + label: I18nLabelSchema.optional().describe('The form\'s name in lists (Setup, Studio). When absent a surface shows `title`, then the name.'), + ...formItemBodyShape(), + protection: ProtectionSchema.optional().describe('Package author protection block — lock policy for this form.'), + // ADR-0010 — runtime protection envelope (internal — set by the loader). + ...MetadataProtectionFields, + // ADR-0146 D2 / ADR-0159 D4 — the override declaration (authored; travels with the item). + ...OverrideDeclarationFields, +}) + .superRefine(checkFormViewBody) + .superRefine(checkFormItemNamePrefix) + .overwrite(foldFormGroupsIntoSections)); + +/** A `form` metadata item as authored (ADR-0159). */ +export type Form = z.input; +/** Post-parse shape of {@link Form} — defaults applied, the `groups` alias folded. */ +export type FormParsed = z.infer; + +/** + * Type-safe factory for a `form` metadata item (ADR-0159, ruled question 1 = A): + * the item a stack lists under `forms: [...]`, one per `*.form.ts` module. + * Validates at authoring time. + * + * @example + * ```ts + * export const webToLead = defineForm({ + * name: 'crm_lead.web_to_lead', + * object: 'crm_lead', + * label: 'Web to lead', + * title: 'Contact us', + * sections: [{ fields: [{ field: 'name' }, { field: 'email' }] }], + * sharing: { enabled: true, allowAnonymous: true, publicLink: '/forms/contact-us' }, + * }); + * ``` + */ +export function defineForm(config: z.input): FormParsed { + return FormSchema.parse(config); +} + // ─────────────────────────────────────────────────────────────────────────── // Canonical persisted-`view`-body schema (the runtime metadata-type schema) // ─────────────────────────────────────────────────────────────────────────── @@ -8221,6 +8363,190 @@ export function expandViewContainer(object: string, container: any): ExpandedVie return expandViewContainerWithDiagnostics(object, container).items; } +// ─────────────────────────────────────────────────────────────────────────── +// [ADR-0159 D5] The projection of the three old form shapes into `form` items +// ─────────────────────────────────────────────────────────────────────────── + +/** + * The read-envelope mark of a `form` item the projection read out of an old + * shape ({@link projectViewForms}): a surface can say "defined in a view" and + * offer the move (ADR-0159 D5). It names the shape: `'view'`. + */ +export const PROJECTED_FORM_SOURCE_KEY = '_formDefinedIn' as const; + +/** One `form` item a `view` body carries (ADR-0159 D5). */ +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}). */ + 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; +} + +/** What one `view` body carries, as the `form` type reads it (ADR-0159 D5, D6 rule 7). */ +export interface ViewFormProjection { + /** The form items the body carries, under the names they are served as today, in scan order. */ + forms: ProjectedFormItem[]; + /** The names the body writes a LIST at — an item, or a container's expansion. A list is not a form (D3). */ + lists: string[]; + /** + * Set when the body carries form content the projection cannot turn into + * items (D6 rule 7): a `form` or `formViews` that is not an object, a + * `formViews` entry that is not one, a `viewKind: 'form'` item with no + * `config` object, or a container whose expansion throws. `links` are the + * `sharing.publicLink` values the content names, normalised to slugs: a + * reader treats each as withdrawn. + */ + unreadable?: { reason: string; links: string[] }; +} + +/** The `view`-item keys that travel onto a projected `form` item beside its body. */ +const PROJECTED_ITEM_KEYS = ['label', 'overrides', 'protection', '_lock', '_lockReason', '_lockSource', '_packageId', '_packageVersion', '_provenance'] as const; + +/** Every `sharing.publicLink` slug a value names, at any depth (rule 7's "the links it names"). */ +function namedPublicLinks(value: unknown, out: Set = new Set(), depth = 0): string[] { + if (depth > 12 || value === null || typeof value !== 'object') return [...out]; + if (Array.isArray(value)) { + for (const v of value) namedPublicLinks(v, out, depth + 1); + return [...out]; + } + const rec = value as Record; + const sharing = rec.sharing; + if (sharing && typeof sharing === 'object' && typeof (sharing as Record).publicLink === 'string') { + const link = (sharing as Record).publicLink as string; + if (link) out.add(publicFormSlug(link)); + } + for (const [k, v] of Object.entries(rec)) if (k !== 'sharing') namedPublicLinks(v, out, depth + 1); + return [...out]; +} + +function projectedItem( + name: string, + object: string, + body: Record, + carrier: Record, +): ProjectedFormItem { + const item: ProjectedFormItem = { ...body, name, object }; + for (const key of PROJECTED_ITEM_KEYS) { + if (carrier[key] !== undefined && item[key] === undefined) item[key] = carrier[key]; + } + // A view item's own audience gate travels with it: a caller refused the + // form at `/meta/view/NAME` is refused it at `/meta/form/NAME` (card ② item 2). + const own = Array.isArray(carrier.requiredPermissions) ? carrier.requiredPermissions : []; + if (own.length > 0) { + const inner = Array.isArray(body.requiredPermissions) ? body.requiredPermissions : []; + item.requiredPermissions = [...new Set([...own, ...inner])]; + } + item[PROJECTED_FORM_SOURCE_KEY] = 'view'; + return item; +} + +/** + * [ADR-0159 D5] THE projection: turn one `view` body into the `form` items it + * carries — the container's `form`, each `formViews` entry, and a + * `viewKind: 'form'` item's `config` — and the names it writes a list at. + * + * It is the ONLY reader of the old shapes for form content: the loader, the + * stored-row read, the anonymous doors, the withdrawal judgement and the lint + * call it, and none re-reads `formViews` by hand. + * + * - 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 + * ({@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 + * refusals (`data` by name, the name's prefix equal to `object`) are not + * applied to it, because the view item never enforced them (D3) and nothing an + * author wrote stops loading. + * - A body it cannot turn into items at all is `unreadable` (D6 rule 7), with + * the links it names; never an item that fails an authored-`form` refusal. + * + * Pure: no I/O, no registry, no module-load work. + */ +export function projectViewForms(body: unknown, options: { object?: string } = {}): ViewFormProjection { + const out: ViewFormProjection = { forms: [], lists: [] }; + if (!body || typeof body !== 'object' || Array.isArray(body)) return out; + const v = body as Record; + const unreadable = (reason: string, content: unknown): ViewFormProjection => ({ + forms: [], + lists: out.lists, + unreadable: { reason, links: namedPublicLinks(content) }, + }); + if (isAggregatedViewContainer(v)) { + if (v.form !== undefined && v.form !== null && (typeof v.form !== 'object' || Array.isArray(v.form))) { + return unreadable('the container\'s `form` is not an object', { form: v.form, formViews: v.formViews }); + } + if (v.formViews !== undefined && v.formViews !== null) { + if (typeof v.formViews !== 'object' || Array.isArray(v.formViews)) { + return unreadable('the container\'s `formViews` is not an object', { form: v.form, formViews: v.formViews }); + } + for (const [key, entry] of Object.entries(v.formViews)) { + if (!entry || typeof entry !== 'object' || Array.isArray(entry)) { + return unreadable(`the container's \`formViews.${key}\` is not an object`, { form: v.form, formViews: v.formViews }); + } + } + } + // The object the loaders and the runtime door expand the container under + // (`deriveViewContainerObject`), so the projected names are the served ones. + const object = deriveViewContainerObject(v) ?? options.object; + if (object === undefined) return unreadable('the container names no object', { form: v.form, formViews: v.formViews }); + let expanded: ExpandedViewItem[]; + try { + expanded = expandViewContainerWithDiagnostics(object, v).items; + } catch (err) { + return unreadable(`the container cannot be expanded (${err instanceof Error ? err.message : String(err)})`, { form: v.form, formViews: v.formViews }); + } + for (const item of expanded) { + if (item.viewKind !== 'form') { + out.lists.push(item.name); + continue; + } + 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 + // `data.object`, else the object the container expands under. + out.forms.push(projectedItem(item.name, anonymousFormObjectName({ object: item.object }, config) ?? item.object, config, carrier)); + } + return out; + } + const name = typeof v.name === 'string' && v.name ? v.name : undefined; + if (v.viewKind === 'form') { + if (!v.config || typeof v.config !== 'object' || Array.isArray(v.config)) { + return unreadable('a `viewKind: \'form\'` item carries no `config` object', v); + } + if (name === undefined) return unreadable('a `viewKind: \'form\'` item names no `name`', v.config); + const object = anonymousFormObjectName(v, v.config); + if (typeof object !== 'string' || !object) return unreadable('a `viewKind: \'form\'` item names no object', v.config); + out.forms.push(projectedItem(name, object, v.config as Record, v)); + return out; + } + if (name !== undefined) out.lists.push(name); + return out; +} + +/** + * [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. + */ +export function projectedFormsOf(bodies: ReadonlyArray): ProjectedFormItem[] { + const seen = new Set(); + const out: ProjectedFormItem[] = []; + const ordered = [...bodies].sort((a, b) => Number(!isAggregatedViewContainer(a)) - Number(!isAggregatedViewContainer(b))); + for (const body of ordered) { + for (const form of projectViewForms(body).forms) { + if (seen.has(form.name)) continue; + seen.add(form.name); + out.push(form); + } + } + return out; +} + /** * Type-safe factory for a standalone {@link FormView} bound to a JSON Schema * rather than to an ObjectQL object. diff --git a/scripts/adr-anchors/packages__rest__src__form-routes.ts.json b/scripts/adr-anchors/packages__rest__src__form-routes.ts.json index e594edbdb92..a839e52753f 100644 --- a/scripts/adr-anchors/packages__rest__src__form-routes.ts.json +++ b/scripts/adr-anchors/packages__rest__src__form-routes.ts.json @@ -3,7 +3,8 @@ "adrs": [ "ADR-0131", "ADR-0056", - "ADR-0112" + "ADR-0112", + "ADR-0159" ], - "invariant": "The public (anonymous) form REST doors, moved here whole from `rest-server.ts` (#23050 slice 11): `GET {base}/forms/:slug` and `POST {base}/forms/:slug/submit`, mounted once per base, both reading the form through ONE resolution. ADR-0131 — the metadata an anonymous form request reads is the environment's, as every metadata read is: the view list the doors judge (a withdrawal in any body of a view name closing its form) and the object schema the resolve door narrows are both the environment's, never an organization's (its D6). ADR-0056 — the doors bypass `enforceAuth` because their authorization is DERIVED from the form's own declaration (Option A): the submit runs as `publicFormGrant`, scoped to exactly the form's target object, and writes only the fields the form's sections declare, never a server-managed anchor; a form that declares no fields publishes nothing and accepts nothing. ADR-0112 — that refusal answers the standard catalog's generic 400 code, never a minted synonym. A door that reads another layer's metadata, accepts an undeclared key or an anchor, or authorizes by anything but the form's declaration is the drift these records forbid; the bodies' own comments carry each citation." + "invariant": "The public (anonymous) form REST doors, moved here whole from `rest-server.ts` (#23050 slice 11): `GET {base}/forms/:slug` and `POST {base}/forms/:slug/submit`, mounted once per base, both reading the form through ONE resolution. ADR-0131 — the metadata an anonymous form request reads is the environment's, as every metadata read is: the view list the doors judge (a withdrawal in any body of a view name closing its form) and the object schema the resolve door narrows are both the environment's, never an organization's (its D6). ADR-0056 — the doors bypass `enforceAuth` because their authorization is DERIVED from the form's own declaration (Option A): the submit runs as `publicFormGrant`, scoped to exactly the form's target object, and writes only the fields the form's sections declare, never a server-managed anchor; a form that declares no fields publishes nothing and accepts nothing. ADR-0112 — that refusal answers the standard catalog's generic 400 code, never a minted synonym. A door that reads another layer's metadata, accepts an undeclared key or an anchor, or authorizes by anything but the form's declaration is the drift these records forbid; the bodies' own comments carry each citation. ADR-0159 — since card ② the doors read a form over BOTH types: the candidates are the effective `form` read (authored `form` items and the projection of the three old `view` shapes, resolved over both types so a stored row that replaces its base's body keeps closing the address), judged against the effective lists and the per-package layers of both `form` and `view`, old shapes projected first; narrowing only, in both directions; identity is the served name and the whole item; a stored body the projection cannot read closes the links it names (rule 7). A door that reads one type alone, or lets a slug match decide a withdrawal, can re-open a withdrawn public form." } diff --git a/scripts/adr-anchors/packages__spec__src__ui__old-shape-form-withdrawals.ts.json b/scripts/adr-anchors/packages__spec__src__ui__old-shape-form-withdrawals.ts.json new file mode 100644 index 00000000000..5a8177dcfb2 --- /dev/null +++ b/scripts/adr-anchors/packages__spec__src__ui__old-shape-form-withdrawals.ts.json @@ -0,0 +1,8 @@ +{ + "file": "packages/spec/src/ui/old-shape-form-withdrawals.ts", + "adrs": [ + "ADR-0159", + "ADR-0087" + ], + "invariant": "ADR-0159 D6 rule 10, D7 (ruled question 4 = A): THE reader of a withdrawal held in an old-shape `view` body (a container's `form`, a `formViews` entry, a `viewKind: 'form'` item), read through the projection under the name each form is served as. It is exempt from the ADR-0087 age-out and leaves only by a release whose upgrade precheck refuses a deployment still holding an old-shape form row: a permission boundary, since no withdrawn public form may re-open. It is not an ADR-0087 conversion-layer entry, so no retirement clock starts on it; removing or narrowing it re-opens forms an old-shape row withdrew." +} From a1bd3fee2392f6556217b5bb2231079333a9e91d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 01:11:35 +0000 Subject: [PATCH 02/29] =?UTF-8?q?fix(37086):=20gate=20findings=20=E2=80=94?= =?UTF-8?q?=20collection-map=20waivers,=20restore-door=20delegation,=20cli?= =?UTF-8?q?=20i18n=20bucket,=20provenance=20row,=20checklist=20waiver,=20t?= =?UTF-8?q?ranscript=20counts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- content/docs/deployment/cli.mdx | 2 +- content/docs/deployment/validating-metadata.mdx | 2 +- .../docs/getting-started/build-with-claude-code.mdx | 2 +- content/docs/ui/react-pages.mdx | 2 +- docs/qa/platform-checklist/coverage.json | 3 +++ packages/cli/src/utils/i18n-coverage.ts | 4 ++++ packages/metadata-protocol/src/protocol.ts | 11 ++++++----- .../rest/src/public-form-two-type-withdrawal.test.ts | 9 ++++++--- packages/spec/src/api/error-code-ledger.zod.ts | 6 ++++++ scripts/check-stack-collection-maps.mjs | 12 ++++++++++-- 10 files changed, 39 insertions(+), 14 deletions(-) diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 919d3d6285e..770b56bd0fb 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -937,7 +937,7 @@ os compile --json # JSON output for CI pipelines → Normalizing stack definition... → Lowering inline handlers... → Validating protocol compliance... - → Running author-time rules (79)... + → Running author-time rules (81)... → Checking that every required capability has a provider installable in this edition... → Collecting package docs (ADR-0046)... 0 collected → Writing artifact... diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index 9b70c57abe8..72f77750452 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -867,7 +867,7 @@ A clean run walks the registry and reports timing: Config: /path/to/support-desk/objectstack.config.ts Load time: 21ms → Validating against ObjectStack Protocol... - → Running author-time rules (79)... + → Running author-time rules (81)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/content/docs/getting-started/build-with-claude-code.mdx b/content/docs/getting-started/build-with-claude-code.mdx index 7f53195af9e..f9ad115e2a9 100644 --- a/content/docs/getting-started/build-with-claude-code.mdx +++ b/content/docs/getting-started/build-with-claude-code.mdx @@ -311,7 +311,7 @@ visible: 'status != "resolved"' ◆ Validate ──────────────────────────────────────── → Validating against ObjectStack Protocol... - → Running author-time rules (79)... + → Running author-time rules (81)... ✗ Author-time rules failed (1 issue) • stack · action 'resolve_ticket' visible: bare reference `status` — a diff --git a/content/docs/ui/react-pages.mdx b/content/docs/ui/react-pages.mdx index 2c196df8b2e..6315fde8a9c 100644 --- a/content/docs/ui/react-pages.mdx +++ b/content/docs/ui/react-pages.mdx @@ -404,7 +404,7 @@ objectstack validate ──────────────────────────────────────── → Loading configuration... → Validating against ObjectStack Protocol... - → Running author-time rules (79)... + → Running author-time rules (81)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/docs/qa/platform-checklist/coverage.json b/docs/qa/platform-checklist/coverage.json index 7efe788388d..50757cb7493 100644 --- a/docs/qa/platform-checklist/coverage.json +++ b/docs/qa/platform-checklist/coverage.json @@ -415,6 +415,9 @@ "studio-authoring.validation-rules-authoring" ] }, + "form": { + "waived": "WAIVED 2026-11-26 — the kind is new (ADR-0159 card ②, #37086) and no checklist item has been run against an authored `form` item yet. What exists: no app this checklist drives authors `forms:` (the showcase's contact-us form is an old `view` shape, which the anonymous doors now read through the one projection, so access-security.public-form-intake keeps driving the same door and the same answers); the type's own rules are pinned below the checklist — FormSchema, the projection and the intake layer in packages/spec/src/ui/form-item.test.ts, the two-type withdrawal, FORM_ADDRESS_TAKEN, the old-shape row removal and the package-less list refusal on both doors in packages/rest/src/public-form-two-type-withdrawal.test.ts, and the authoring rules in packages/lint/src/validate-form-items.test.ts. WHAT RETIRES THIS WAIVER — the showcase moves its contact-us form to `forms:` (card ③, #37087) or a scratch package authors one; an item then drives GET /forms/:slug and its submit for an authored form, a view override that withdraws it, and the 409 for a second form left open on the address, and the same edit replaces this waiver with `items` naming it." + }, "view": { "items": [ "records-forms.view-type-gallery", diff --git a/packages/cli/src/utils/i18n-coverage.ts b/packages/cli/src/utils/i18n-coverage.ts index 4907eac0fc9..427966f034f 100644 --- a/packages/cli/src/utils/i18n-coverage.ts +++ b/packages/cli/src/utils/i18n-coverage.ts @@ -72,6 +72,7 @@ export interface CoverageIssue { | 'report' | 'picklist' | 'page' + | 'form' | 'flow' | 'hook' | 'position' @@ -358,6 +359,8 @@ const COVERAGE_SOURCE: Record // it, so it keeps its own bucket and reports as `i18n/missing-picklist`. picklist: 'picklist', page: 'page', + // A `form` item's copy (`forms..label`, `.title`, the thank-you tails, ADR-0159) — its own bucket, reported as `i18n/missing-form`. + form: 'form', // Flow copy (every flow's `flows..label`, `flows..screens..title` / // `.description` (#22507), and the per-field `label` / `placeholder` / // option labels), the terminal @@ -415,6 +418,7 @@ const SOURCE_NOUN: Record = { report: 'Report', picklist: 'Picklist', page: 'Page', + form: 'Form', flow: 'Flow', hook: 'Hook', position: 'Position', diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 1856228b5ee..fb287bd7bf9 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -1591,6 +1591,11 @@ export class ObjectStackProtocolImplementation implements return restoredBodyDerivation.call(host, type); } + /** [ADR-0159 card ② item 5] {@link packagelessListOverFormRefusal}, asked of a restored body against its binding. */ + private listOverFormRefusal(type: string, item: unknown, name: string, binding: string | null): Error | undefined { + return packagelessListOverFormRefusal(protocolHost(this), type, item, name, binding); + } + /** * [#21470] What a restore passes to `repo.restoreVersion` as * `deriveRestoredBody`: the divergent `name` refusal FIRST, then @@ -1626,11 +1631,7 @@ export class ObjectStackProtocolImplementation implements private restoredBodyWriter(type: string, name: string, binding: string | null, source: string): (historyBody: unknown) => Promise { // [#25467 cut 8] The body moved to `protocol-authoring-gate.ts` (see `AuthoringGateHost`). const host: ThisParameterType = { - listOverFormRefusal: (t, item, n, binding) => packagelessListOverFormRefusal({ - expandRuntimeViewContainer: (...a) => this.expandRuntimeViewContainer(...a), - isWritablePackage: (...a) => this.isWritablePackage(...a), - shippedArtifactsOf: (...a) => this.shippedArtifactsOf(...a), - }, t, item, n, binding), + listOverFormRefusal: (...a) => this.listOverFormRefusal(...a), objectExtensionItemRefusal: (...a) => this.objectExtensionItemRefusal(...a), refuseRestoredBodyTheSaveDoorRefuses: (...a) => this.refuseRestoredBodyTheSaveDoorRefuses(...a), restoredBodyDerivation: (...a) => this.restoredBodyDerivation(...a), diff --git a/packages/rest/src/public-form-two-type-withdrawal.test.ts b/packages/rest/src/public-form-two-type-withdrawal.test.ts index 72c92cd5fbc..9592f06cb08 100644 --- a/packages/rest/src/public-form-two-type-withdrawal.test.ts +++ b/packages/rest/src/public-form-two-type-withdrawal.test.ts @@ -128,7 +128,7 @@ async function boot(ships: { forms?: unknown[]; views?: unknown[] }) { await submit.handler({ params: { 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 any)) as unknown[]).length; + 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', @@ -155,7 +155,7 @@ async function boot(ships: { forms?: unknown[]; views?: unknown[] }) { 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 } } as any); + }, { context: { isSystem: true } }); }; return { engine, protocol, get, post, records, install, saveInto, saveBeforeTheGate, seedRow }; } @@ -187,12 +187,15 @@ describe('[ADR-0159 D6] the form doors read both types: a withdrawal in either c const savedWritable = process.env.OS_METADATA_WRITABLE; beforeAll(() => { delete process.env.OS_METADATA_WRITABLE; + // Pin 6 reads the boot report off console.error, so the REST log level is declared (check:rest-log-spy-declared). + vi.stubEnv('OS_REST_LOG', 'info'); }); beforeEach(() => { ObjectStackProtocolImplementation.resetEnvWritableCache(); resetEnvWritableMetadataTypes(); }); afterAll(async () => { + vi.unstubAllEnvs(); if (savedWritable === undefined) delete process.env.OS_METADATA_WRITABLE; else process.env.OS_METADATA_WRITABLE = savedWritable; ObjectStackProtocolImplementation.resetEnvWritableCache(); @@ -363,7 +366,7 @@ describe('[ADR-0159 D5] the `form` writes: the old-shape row goes with the save; }; /** The pair's ACTIVE stored `view` rows of the name, read off the store itself. */ const storedViews = async (b: Booted, name = NAME) => { - const rows = (await b.engine.find('sys_metadata', { where: { type: 'view', name, package_id: PAIR, state: 'active' } }, { context: { isSystem: true } } as any)) as any[]; + const rows = (await b.engine.find('sys_metadata', { where: { type: 'view', name, package_id: PAIR, state: 'active' } }, { context: { isSystem: true } })) as any[]; return rows.map((r) => (typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata)); }; diff --git a/packages/spec/src/api/error-code-ledger.zod.ts b/packages/spec/src/api/error-code-ledger.zod.ts index 7352ad15f4a..5fcb9932f9b 100644 --- a/packages/spec/src/api/error-code-ledger.zod.ts +++ b/packages/spec/src/api/error-code-ledger.zod.ts @@ -738,6 +738,12 @@ export const ERROR_CODE_LEDGER = { // string is spelled in each). Served by the `/meta` write doors through // `errorFromThrown`. 'DEFAULT_RECORD_PAGE_CONFLICT', + // [ADR-0159 ruled question 3 = A] The public address clash: the `form` + // save, draft promotion and restore doors refuse a `form` write that would + // leave the form open on a `/forms/SLUG` another form holds, naming both, + // 409 (`formAddressClashRefusal`, protocol-form-writes.ts). Served by the + // `/meta` write doors through `errorFromThrown`. + 'FORM_ADDRESS_TAKEN', // [#24001] The flow save door's 409 for a refused conversion rename came // out with its last producer (this header's "Retiring a code"): protocol // 18 reserved the old HTTP-callout node types, so no live owner can diff --git a/scripts/check-stack-collection-maps.mjs b/scripts/check-stack-collection-maps.mjs index 0264484f156..e8c8f56edd6 100644 --- a/scripts/check-stack-collection-maps.mjs +++ b/scripts/check-stack-collection-maps.mjs @@ -502,6 +502,14 @@ const SITES = [ + 'identity is the target object), ObjectExtensionSchema and PicklistExtensionSchema key by ' + '`extend`, SeedSchema keys by `object`, and TranslationBundleSchema is itself a record.', }, + { + direction: 'missing', + keys: ['forms'], + reason: + 'not offered yet (ADR-0159 card ②): a `form` item is named `OBJECT.KEY` and is checked against its ' + + '`object` (the name\'s prefix must equal it), so a map key standing in for the name would carry a ' + + 'second spelling of that identity; the array form is the one the record and its conversion write.', + }, { direction: 'missing', keys: ['datasourceMapping', 'capabilities', 'docs', 'books', 'tools', 'skills', 'aiContexts', 'picklists'], @@ -561,7 +569,7 @@ const SITES = [ 'datasources', 'datasourceMapping', 'objectExtensions', 'apps', 'jobs', 'emailTemplates', 'docs', 'books', 'positions', 'capabilities', 'sharingRules', 'webhooks', 'tools', 'skills', 'aiContexts', 'hooks', 'mappings', 'analyticsCubes', 'connectors', 'data', 'picklists', 'picklistExtensions', - 'queues', 'assignmentRules', + 'queues', 'assignmentRules', 'forms', ], reason: 'DRIFT in the opposite direction, under the same acceptance constraint: ADDING a member widens ' @@ -755,7 +763,7 @@ const SITES = [ 'views', 'pages', 'dashboards', 'reports', 'datasets', 'actions', 'flows', 'jobs', 'emailTemplates', 'docs', 'books', 'apis', 'webhooks', 'agents', 'tools', 'skills', 'aiContexts', 'hooks', 'mappings', 'analyticsCubes', 'connectors', 'data', 'picklists', 'picklistExtensions', - 'queues', 'assignmentRules', + 'queues', 'assignmentRules', 'forms', ], reason: 'DELIBERATE — a four-collection SUBSET, not an enumeration of the collection set. This block ' From d7eb41bd70e21bf44a8a934b3d871d80e969e37d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 01:36:24 +0000 Subject: [PATCH 03/29] =?UTF-8?q?fix(37086):=20i18n=20for=20the=20form=20t?= =?UTF-8?q?ype=20=E2=80=94=20platform-objects=20form=20label=20bundles,=20?= =?UTF-8?q?showcase=20feedback=20form=20zh-CN,=20walk-parity=20fixture=20m?= =?UTF-8?q?ember;=20typed=20form-body=20refinement=20params?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .../app-showcase/src/system/translations/index.ts | 13 +++++++++++++ .../translations/ar.metadata-forms.generated.ts | 3 +++ .../translations/de.metadata-forms.generated.ts | 3 +++ .../translations/en.metadata-forms.generated.ts | 3 +++ .../translations/es-ES.metadata-forms.generated.ts | 3 +++ .../translations/fr.metadata-forms.generated.ts | 3 +++ .../translations/ja-JP.metadata-forms.generated.ts | 3 +++ .../translations/ko.metadata-forms.generated.ts | 3 +++ .../translations/pt-BR.metadata-forms.generated.ts | 3 +++ .../translations/ru.metadata-forms.generated.ts | 3 +++ .../translations/zh-CN.metadata-forms.generated.ts | 3 +++ .../zh-Hant.metadata-forms.generated.ts | 3 +++ packages/spec/src/ui/view.zod.ts | 4 ++-- .../i18n-walk-parity/every-group.stack.json | 11 +++++++++++ 14 files changed, 59 insertions(+), 2 deletions(-) diff --git a/examples/app-showcase/src/system/translations/index.ts b/examples/app-showcase/src/system/translations/index.ts index a5f7d4b905e..848cd5c6be8 100644 --- a/examples/app-showcase/src/system/translations/index.ts +++ b/examples/app-showcase/src/system/translations/index.ts @@ -907,6 +907,8 @@ export const ShowcaseTranslationBundle = { // (#8231). _sections: { tell_us_about_yourself: { label: '介绍一下您自己' }, + // The authored `form` item's section (`ui/forms/feedback.form.ts`). + feedback: { label: '您的反馈' }, }, }, // Object, fields and `kind` options as well as the views below: the @@ -1374,6 +1376,17 @@ export const ShowcaseTranslationBundle = { // page heading: each reads the word its sidebar entry already uses // (`apps.showcase_app.navigation`), so the heading matches the link that // opened it. + // [ADR-0159 D8] The showcase's authored `form` item (`forms.`), + // src/ui/forms/feedback.form.ts — read before any `_views` tail. + forms: { + 'showcase_inquiry.feedback': { + label: '提交反馈', + submitBehavior: { + title: '感谢您', + message: '您的反馈已送达展示团队。', + }, + }, + }, pages: { showcase_capability_map: { label: '能力地图' }, showcase_my_work: { label: '我的工作', subtitle: '你的待办队列、团队产出,以及需要关注的事项。' }, diff --git a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index 43316d31730..a2e358d2899 100644 --- a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts @@ -1469,6 +1469,9 @@ export const arMetadataForms: NonNullable = { } } }, + form: { + label: "نموذج" + }, page: { label: "الصفحة", sections: { diff --git a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index 2418140afd6..d26d558358a 100644 --- a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts @@ -1469,6 +1469,9 @@ export const deMetadataForms: NonNullable = { } } }, + form: { + label: "Formular" + }, page: { label: "Seite", sections: { diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index 44c4749a0ef..a96edd8e260 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -1469,6 +1469,9 @@ export const enMetadataForms: NonNullable = { } } }, + form: { + label: "Form" + }, page: { label: "Page", sections: { diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index bb66aea373d..efa7a09b85f 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -1469,6 +1469,9 @@ export const esESMetadataForms: NonNullable = } } }, + form: { + label: "Formulario" + }, page: { label: "Página", sections: { diff --git a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts index 06130d95ac2..0d9163516a2 100644 --- a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts @@ -1469,6 +1469,9 @@ export const frMetadataForms: NonNullable = { } } }, + form: { + label: "Formulaire" + }, page: { label: "Page", sections: { diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index 23261e71d45..ada32e03400 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -1469,6 +1469,9 @@ export const jaJPMetadataForms: NonNullable = } } }, + form: { + label: "フォーム" + }, page: { label: "ページ", sections: { diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index 700890fea29..550164a9c44 100644 --- a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts @@ -1469,6 +1469,9 @@ export const koMetadataForms: NonNullable = { } } }, + form: { + label: "양식" + }, page: { label: "페이지", sections: { diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index 473a97654d0..67d549be4f9 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts @@ -1469,6 +1469,9 @@ export const ptBRMetadataForms: NonNullable = } } }, + form: { + label: "Formulário" + }, page: { label: "Página", sections: { diff --git a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index 62e6b87e23e..726a7532fa7 100644 --- a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts @@ -1469,6 +1469,9 @@ export const ruMetadataForms: NonNullable = { } } }, + form: { + label: "Форма" + }, page: { label: "Страница", sections: { diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index dee1da3bbb2..af99725c86f 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -1469,6 +1469,9 @@ export const zhCNMetadataForms: NonNullable = } } }, + form: { + label: "表单" + }, page: { label: "页面", sections: { diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index b1851fb0e28..a5da9043dc2 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts @@ -1469,6 +1469,9 @@ export const zhHantMetadataForms: NonNullable } } }, + form: { + label: "表單" + }, page: { label: "頁面", sections: { diff --git a/packages/spec/src/ui/view.zod.ts b/packages/spec/src/ui/view.zod.ts index b1084359d81..1ccbde73475 100644 --- a/packages/spec/src/ui/view.zod.ts +++ b/packages/spec/src/ui/view.zod.ts @@ -5409,7 +5409,7 @@ function checkFormViewBody(view: any, ctx: z.RefinementCtx): void { // {@link foldFormGroupsIntoSections} — so every check here must keep // reading BOTH buckets (`sections` AND the legacy `groups` alias). for (const [key, sections] of [['sections', view.sections], ['groups', view.groups]] as const) { - sections?.forEach((section, index) => { + sections?.forEach((section: any, index: number) => { // The `features.*` scope-root exclusion (ruled 2026-08-27, objectui#6262 // — see {@link checkFormViewPredicateFeaturesRoot}): every predicate // this form view carries — section-level, field-level at any depth, @@ -5419,7 +5419,7 @@ function checkFormViewBody(view: any, ctx: z.RefinementCtx): void { if (sectionRefusal) { ctx.addIssue({ code: 'custom', path: [key, index, 'visibleWhen'], message: sectionRefusal }); } - section?.fields?.forEach((field, fieldIndex) => { + section?.fields?.forEach((field: any, fieldIndex: number) => { refineFormFieldFeaturesRoot(field, [key, index, 'fields', fieldIndex], ctx); }); // [#13704] Wizard steps carry no predicate slot and do not collapse — diff --git a/scripts/fixtures/i18n-walk-parity/every-group.stack.json b/scripts/fixtures/i18n-walk-parity/every-group.stack.json index 6036bfeaefb..9a9dcf4916b 100644 --- a/scripts/fixtures/i18n-walk-parity/every-group.stack.json +++ b/scripts/fixtures/i18n-walk-parity/every-group.stack.json @@ -154,6 +154,17 @@ } ], + "forms": [ + { + "name": "parity_object.parity_form", + "object": "parity_object", + "label": "Parity Form", + "type": "simple", + "sections": [{ "fields": [{ "field": "name" }] }], + "submitBehavior": { "kind": "thank-you", "title": "Thanks", "message": "Received." } + } + ], + "flows": [ { "name": "parity_flow", From 196b3a16fe635180b79b207b9004d477903c2138 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 02:25:20 +0000 Subject: [PATCH 04/29] =?UTF-8?q?fix(37086):=20package=20tests=20=E2=80=94?= =?UTF-8?q?=20form=20doors=20project=20old=20shapes=20from=20a=20protocol?= =?UTF-8?q?=20serving=20no=20form=20item,=20one=20registry=20heal=20for=20?= =?UTF-8?q?old-shape=20removals,=20the=20by-name=20form=20read=20keeps=20t?= =?UTF-8?q?he=20generic=20answer=20unless=20resolved=20across=20types,=20c?= =?UTF-8?q?ensus=20and=20enumeration=20pins?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .changeset/37086-form-metadata-type.md | 2 +- packages/lint/src/index.ts | 13 ++++++ .../src/reference-integrity-suite.test.ts | 2 + .../lint/src/reference-integrity-suite.ts | 2 +- packages/metadata-protocol/src/plugin.ts | 12 ----- .../src/protocol-diff-delete-load.ts | 13 +----- .../src/protocol-form-writes.ts | 22 ++++++++++ .../src/protocol-history-and-publish.ts | 13 +----- .../src/protocol-meta-item-reads.ts | 44 ++++++++++++------- .../metadata-protocol/src/protocol-save.ts | 13 +----- .../protocol.legacy-overlay-delete.test.ts | 3 +- ...ct-registry-write-through-spelling.test.ts | 10 +++-- ...iew-expansion-reconcile-call-sites.test.ts | 39 ++++++++++++++-- .../package-scoped-exact-qualifier.test.ts | 8 ++-- ...rite-summary-recompute-other-doors.test.ts | 4 +- packages/rest/src/form-routes.ts | 28 ++++++++---- .../rest/src/public-form-file-field.test.ts | 4 ++ .../public-form-intake-availability.test.ts | 3 +- .../src/public-form-option-subset.test.ts | 4 ++ .../rest/src/public-form-required.test.ts | 4 ++ ...route-hook-refusal-sentence.ledger.test.ts | 5 ++- .../spec/dropped-refinements.baseline.json | 4 +- .../src/kernel/collection-item-owner-stamp.ts | 2 +- .../src/kernel/metadata-create-seeds.test.ts | 5 +++ .../kernel/metadata-credential-fields.test.ts | 4 ++ .../src/kernel/override-declaration.test.ts | 5 ++- 26 files changed, 178 insertions(+), 90 deletions(-) diff --git a/.changeset/37086-form-metadata-type.md b/.changeset/37086-form-metadata-type.md index f3fb12b7d60..92b4432a611 100644 --- a/.changeset/37086-form-metadata-type.md +++ b/.changeset/37086-form-metadata-type.md @@ -27,7 +27,7 @@ ADR-0159 makes a public form a `form` item: `name` (`OBJECT.KEY`, the name it is What lands with the type: - `@objectstack/spec`: `FormSchema`, `defineForm`, the registry row (`*.form.ts|yml|json`, overlay-capable, no environment overlay), `form` in the customization package's listed types, the stack's `forms` collection, the `forms` translation family (`forms.NAME` first, the `_views.KEY` title and thank-you tails as the fallback, `_views.KEY.label` never read), the projection `projectViewForms`, the intake layer `formIntakeLayer` / `openFormAt`, and the error code `FORM_ADDRESS_TAKEN`. -- `@objectstack/metadata-protocol`: the effective `form` read resolves a form over both types in the one served-row order (a stored `view` row over a package's form keeps replacing it when the package moves to `forms:`); a `form` save, reset or delete at a package removes that package's old-shape row of the name in the same transaction (form content only — a list of the name is untouched); a `form` left open on a public address another form holds is refused with `409 FORM_ADDRESS_TAKEN`, naming both (a switched-off form that keeps its link still holds the address; a save that leaves the form closed is never refused); the override gate accepts a `form` override over a base that ships the form as an old shape; a stored body whose form content cannot be read is reported once at boot, at `error`, naming the row, the links it closes and the repair save. +- `@objectstack/metadata-protocol`: the effective `form` read resolves a form over both types in the one served-row order (a stored `view` row over a package's form keeps replacing it when the package moves to `forms:`); a `form` save, reset or delete at a package removes that package's old-shape row of the name in the same transaction (form content only — a list of the name is untouched); a `form` left open on a public address another form holds is refused with `409 FORM_ADDRESS_TAKEN`, naming both (a switched-off form that keeps its link still holds the address; a save that leaves the form closed is never refused); the override gate accepts a `form` override over a base that ships the form as an old shape; a stored body whose form content cannot be read closes the links it names and is reported once per process, at `error`, the first time the form doors read it, naming the row, the links it closes and the repair save. - `@objectstack/rest`: `GET /forms/:slug` and its submit read candidates from the effective `form` read and judge withdrawal across `form` and `view`, effective and per-package, old shapes projected first — narrowing only, in both directions; a body that cannot be read closes the links it names. `/meta/form/NAME` refuses whom `/meta/view/NAME` refuses. `GET /meta/view` answers as before. - `@objectstack/lint`: `form-public-address-taken` (gating), `form-consumer-less` (advisory, never for an `overrides` item), `form-object-outside-closure` / `form-object-unknown`; the i18n walk emits `forms.NAME.*` keys and no `_views` tail for a `form` item. No new advisory for an old shape. - `@objectstack/metadata`, `@objectstack/metadata-core`, `@objectstack/objectql`, `@objectstack/runtime`, `@objectstack/cli`: the `forms` collection is loaded, typed, registered and counted for i18n coverage like every other. diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 8880a48921c..2a9e5b3f977 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -319,6 +319,19 @@ export { FORM_VIEW_INTERNAL_NOT_LOADED, } from './validate-internal-form-views.js'; export type { InternalFormViewFinding } from './validate-internal-form-views.js'; +// [ADR-0159 card ②] The `form` type's authoring rules: the public-address +// refusal (gating), the consumer-less advisory and the object binding. +export { + stackForms, + validateFormConsumers, + validateFormObjectBindings, + validateFormPublicAddresses, + FORM_CONSUMER_LESS, + FORM_OBJECT_OUTSIDE_CLOSURE, + FORM_OBJECT_UNKNOWN, + FORM_PUBLIC_ADDRESS_TAKEN, +} from './validate-form-items.js'; +export type { FormItemFinding, FormObjectBindingOptions, StackForm } from './validate-form-items.js'; // A form open to anonymous intake that declares a file field (ruling C on #25572). export { validatePublicFormFileFields, PUBLIC_FORM_FILE_FIELD } from './validate-public-form-file-fields.js'; diff --git a/packages/lint/src/reference-integrity-suite.test.ts b/packages/lint/src/reference-integrity-suite.test.ts index 249acb0456e..8ea57a88785 100644 --- a/packages/lint/src/reference-integrity-suite.test.ts +++ b/packages/lint/src/reference-integrity-suite.test.ts @@ -25,6 +25,8 @@ describe('reference-integrity suite — membership', () => { // field-naming position the two members above do not own. Placed beside // them because the three walk the identical rungs. 'validateListViewFieldRefs', + // [ADR-0159 D2] A `form` item's `object`, judged where a list view's is. + 'validateFormObjectBindings', // [#15254] The object-level half of the same sweep: the field-name lists // an object writes about its OWN fields. Placed beside the list-view // members because it completes the object's field surface — and because diff --git a/packages/lint/src/reference-integrity-suite.ts b/packages/lint/src/reference-integrity-suite.ts index 2f5371f3b20..e9058b4acae 100644 --- a/packages/lint/src/reference-integrity-suite.ts +++ b/packages/lint/src/reference-integrity-suite.ts @@ -426,7 +426,7 @@ export const REFERENCE_INTEGRITY_RULES: readonly ReferenceIntegrityRule[] = [ // the stated closure, or against the whole collection of a runtime write. { name: 'validateFormObjectBindings', - runtimeTypes: ['form'], + runtimeTypes: ['flow', 'form'], run: (stack, ctx) => validateFormObjectBindings( stack, diff --git a/packages/metadata-protocol/src/plugin.ts b/packages/metadata-protocol/src/plugin.ts index 4b60842e0e5..4d8c704b705 100644 --- a/packages/metadata-protocol/src/plugin.ts +++ b/packages/metadata-protocol/src/plugin.ts @@ -476,18 +476,6 @@ export function assembleMetadataProtocol( plans?.register?.(createRecordedBySentinelPlan()); }); - // [ADR-0159 D6 rule 7] A stored `view` body the `form` projection - // cannot read closes the public links it names on both anonymous - // doors; the boot says so once at `error`, naming the row, the - // links and the repair save. Reads only; never fails a bootstrap. - (ctx as any)?.hook?.('kernel:ready', async () => { - try { - await protocolShim.getUnreadableFormBodies(); - } catch { - // An unreadable store is the doors' own question per request. - } - }); - // NO `analytics` fallback rides here anymore (#3891 / #3878). The // degraded shim this assembly used to register dropped the request's // ExecutionContext (aggregates ran without RLS/tenant predicates) diff --git a/packages/metadata-protocol/src/protocol-diff-delete-load.ts b/packages/metadata-protocol/src/protocol-diff-delete-load.ts index 394bcf043d8..edc81638073 100644 --- a/packages/metadata-protocol/src/protocol-diff-delete-load.ts +++ b/packages/metadata-protocol/src/protocol-diff-delete-load.ts @@ -23,7 +23,7 @@ * not move. */ -import { applyOldShapeFormRowRemovals, type OldShapeFormRowRemoval } from './protocol-form-writes.js'; +import { applyOldShapeFormRowRemovals, healOldShapeFormRowRemovals, type OldShapeFormRowRemoval } from './protocol-form-writes.js'; import { overlayMemberWhere } from './migrations/overlay-index.js'; import { historyRowsOfMember, @@ -937,16 +937,7 @@ export class ProtocolDiffDeleteLoadFacet { packageId, ...memberOption(member), })); - for (const removal of removedOldShapeRows) { - if (removal.kind === 'delete') { - await host.restoreArtifactRegistryView('view', removal.row.name, null, removal.row.packageId); - } else { - await host.applyRegistryWriteThrough({ - type: 'view', name: removal.row.name, item: removal.body, - packageId: removal.row.packageId, organizationId: null, - }); - } - } + await healOldShapeFormRowRemovals(host, removedOldShapeRows); // Heal the registry: drop the overlay's runtime shadow so the // packaged artifact is visible again (all kernels), and on diff --git a/packages/metadata-protocol/src/protocol-form-writes.ts b/packages/metadata-protocol/src/protocol-form-writes.ts index 04c6e48374e..055eeef9ba9 100644 --- a/packages/metadata-protocol/src/protocol-form-writes.ts +++ b/packages/metadata-protocol/src/protocol-form-writes.ts @@ -257,3 +257,25 @@ export async function applyOldShapeFormRowRemovals( } return removals; } + +/** + * [ADR-0159 D5] The registry heal of each old-shape row a `form` write removed + * or re-saved ({@link applyOldShapeFormRowRemovals}), run after the commit by + * every door that removes them: a deleted row's name is restored to what the + * store still serves, a re-saved container is written through as stored. + */ +export async function healOldShapeFormRowRemovals( + host: Pick, + removals: readonly OldShapeFormRowRemoval[], +): Promise { + for (const removal of removals) { + if (removal.kind === 'delete') { + await host.restoreArtifactRegistryView('view', removal.row.name, null, removal.row.packageId); + } else { + await host.applyRegistryWriteThrough({ + type: 'view', name: removal.row.name, item: removal.body, + packageId: removal.row.packageId, organizationId: null, + }); + } + } +} diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index 07259a12217..8e0ee006844 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -23,7 +23,7 @@ * not move. */ -import { applyOldShapeFormRowRemovals, packagelessListOverFormRefusal, type OldShapeFormRowRemoval } from './protocol-form-writes.js'; +import { applyOldShapeFormRowRemovals, healOldShapeFormRowRemovals, packagelessListOverFormRefusal, type OldShapeFormRowRemoval } from './protocol-form-writes.js'; import { stampHtmlPageRequires } from './runtime-authoring-gate.js'; import type { RuntimeAuthoringIssue, RuntimePendingDeclarations } from './runtime-authoring-gate.js'; import { DraftConflictError, packagelessAddressAmbiguityRefusal } from './sys-metadata-repository.js'; @@ -1423,16 +1423,7 @@ export class ProtocolHistoryAndPublishFacet { // [#22877] …of the member that was judged. ...memberOption(request.member), })); - for (const removal of removedOldShapeRows) { - if (removal.kind === 'delete') { - await host.restoreArtifactRegistryView('view', removal.row.name, null, removal.row.packageId); - } else { - await host.applyRegistryWriteThrough({ - type: 'view', name: removal.row.name, item: removal.body, - packageId: removal.row.packageId, organizationId: null, - }); - } - } + await healOldShapeFormRowRemovals(host, removedOldShapeRows); return { singularType, advisories: runtimeAdvisories, diff --git a/packages/metadata-protocol/src/protocol-meta-item-reads.ts b/packages/metadata-protocol/src/protocol-meta-item-reads.ts index 059878f2e01..8dd44b2847f 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-reads.ts @@ -51,6 +51,7 @@ import { import { packagelessContentPackage } from './protocol-environment-rows.js'; import type { ProtocolHost } from './protocol-host.js'; import { readEffectiveForms, type FormReadHost } from './protocol-form-reads.js'; +import { PROJECTED_FORM_SOURCE_KEY } from '@objectstack/spec/ui'; import { admitExactQualifier, declinedCopyReplaced, @@ -673,33 +674,44 @@ export async function getMetaItem(host: Pick & FormReadHost, request: { type: string; name: string; packageId?: string; member?: string; userTextLocales?: readonly string[] }, ): Promise { const generic: any = await host.readMetaItemFace(request, 'served'); - const listed = await readEffectiveForms(host, { + const listedAt = (packageId: string | undefined) => readEffectiveForms(host, { type: 'form', names: [request.name], - ...(request.packageId !== undefined ? { packageId: request.packageId } : {}), + ...(packageId !== undefined ? { packageId } : {}), }, 'served'); + const listed = await listedAt(request.packageId); const pkgOf = (item: unknown): unknown => (item as { _packageId?: unknown } | null)?._packageId; + const fromView = (item: unknown): boolean => (item as Record | null)?.[PROJECTED_FORM_SOURCE_KEY] === 'view'; + const envelope = generic && typeof generic === 'object' ? generic : { type: 'form', name: request.name }; const genericItem = generic?.item; - const served = listed.find((item) => genericItem !== undefined && pkgOf(item) === pkgOf(genericItem)) ?? listed[0]; - if (served === undefined) { - if (generic === null || typeof generic !== 'object') return generic; - const { item: _item, ...rest } = generic; - return rest; - } - return { ...(generic && typeof generic === 'object' ? generic : { type: 'form', name: request.name }), item: served }; + if (genericItem === undefined) return listed.length > 0 ? { ...envelope, item: listed[0] } : generic; + const matching = listed.find((item) => pkgOf(item) === pkgOf(genericItem)); + const projected = (matching !== undefined && fromView(matching) ? matching : undefined) + ?? (request.packageId !== undefined ? listed.find(fromView) : undefined); + if (projected !== undefined) return { ...envelope, item: projected }; + if (matching !== undefined || listed.length > 0) return generic; + if (request.packageId !== undefined && (await listedAt(undefined)).some((item) => pkgOf(item) === pkgOf(genericItem))) return generic; + const { item: _item, ...rest } = envelope; + return rest; } /** The body of `ObjectStackProtocolImplementation#getMetaItemForExecution`; the method's docblock there is its contract. */ diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index 2f53e61780f..b6f0bc3573c 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -23,7 +23,7 @@ * not move. */ -import { applyOldShapeFormRowRemovals, formAddressClashRefusal, packagelessListOverFormRefusal, type OldShapeFormRowRemoval } from './protocol-form-writes.js'; +import { applyOldShapeFormRowRemovals, healOldShapeFormRowRemovals, formAddressClashRefusal, packagelessListOverFormRefusal, type OldShapeFormRowRemoval } from './protocol-form-writes.js'; import { MetadataAuthoringSurfaceSchema } from '@objectstack/spec/api'; import { stampHtmlPageRequires } from './runtime-authoring-gate.js'; import { SysMetadataRepository, actionCustomizationHoldersOf, actionHeldOnlyOnOtherObjects, actionRowsBindingObjectOf, isPackageBoundRow, packagelessAddressAmbiguityRefusal } from './sys-metadata-repository.js'; @@ -2347,16 +2347,7 @@ export class ProtocolSaveFacet { })); // [ADR-0159 D5] The registry heal of each old-shape row the write // removed or re-saved, after the commit. - for (const removal of removedOldShapeRows) { - if (removal.kind === 'delete') { - await host.restoreArtifactRegistryView('view', removal.row.name, null, removal.row.packageId); - } else { - await host.applyRegistryWriteThrough({ - type: 'view', name: removal.row.name, item: removal.body, - packageId: removal.row.packageId, organizationId: null, - }); - } - } + await healOldShapeFormRowRemovals(host, removedOldShapeRows); // Persistence succeeded — NOW it's safe to mutate the // in-memory registry. If put() had thrown, the registry // would still reflect the prior state. Drafts are NOT diff --git a/packages/metadata-protocol/src/protocol.legacy-overlay-delete.test.ts b/packages/metadata-protocol/src/protocol.legacy-overlay-delete.test.ts index d1691bdaf66..ccb6b869f5d 100644 --- a/packages/metadata-protocol/src/protocol.legacy-overlay-delete.test.ts +++ b/packages/metadata-protocol/src/protocol.legacy-overlay-delete.test.ts @@ -275,8 +275,9 @@ describe('#6960 — the registry is the tier boundary, and it is DATA', () => { */ it('names the rolled-back overlayable tier exactly as the registry declares it', () => { // [ADR-0160 D1] `ai_context` registers like `skill`, overlay allowed, so it joins the tier. + // [ADR-0159 D2] So does `form`: overlay-capable through a package's pair, no environment overlay. expect([...ROLLED_BACK_OVERLAYABLE_TYPES]).toEqual([ - 'ai_context', 'app', 'book', 'dataset', 'page', 'permission', 'position', 'skill', 'tool', + 'ai_context', 'app', 'book', 'dataset', 'form', 'page', 'permission', 'position', 'skill', 'tool', ]); // The six commit ee58392e1 named, all present. for (const t of ['permission', 'position', 'page', 'app', 'dataset', 'book']) { diff --git a/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts b/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts index 0f2122eb254..c0d10f85ca2 100644 --- a/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts +++ b/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts @@ -38,7 +38,7 @@ // The trace, measured on `origin/main` — all four routes fold at the producer // --------------------------------------------------------------------------- // `applyObjectRegistryMutation` has exactly ONE caller -// (`applyRegistryWriteThrough`), which has exactly SEVEN: +// (`applyRegistryWriteThrough`), which has exactly EIGHT: // // 1. `saveMetaItem` passes `singularTypeForRepo`, and the method // already ran `canonicalizeMetaRequestType`. @@ -74,6 +74,10 @@ // still stored after a delete (another // package's, or the package-less one), so the // registry keeps serving what the store serves. +// 8. `healOldShapeFormRowRemovals` (ADR-0159 D5) passes the literal +// `'view'`: it heals the old-shape `view` row a +// `form` save, publish or delete re-saved, so no +// stored spelling reaches it. // // Both fold maps resolve the plural — `PLURAL_TO_SINGULAR.objects === 'object'` // and `canonicalMetaUrlType('objects') === 'object'` — so no route can deliver @@ -606,9 +610,9 @@ describe('[#8862] the `applyRegistryWriteThrough` caller set stays closed', () = const sources = [source, ...SPLIT_MODULES.map((file) => readFileSync(fileURLToPath(new URL(`./${file}`, import.meta.url)), 'utf8'))]; const sitesOf = (pattern: RegExp) => sources.flatMap((text) => text.match(pattern) ?? []); - it('has exactly seven call sites, all traced in this file’s header', () => { + it('has exactly eight call sites, all traced in this file’s header', () => { const callSites = sitesOf(/\b(?:this|host)\.applyRegistryWriteThrough\(/g); - expect(callSites).toHaveLength(7); + expect(callSites).toHaveLength(8); }); it('`applyObjectRegistryMutation` is reached only through the write-through', () => { diff --git a/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts b/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts index 4f73e596010..d40967ba011 100644 --- a/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts +++ b/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts @@ -152,7 +152,13 @@ type Route = /** The write-through or the heal is called after the write, in the same member, before its next write. */ | { readonly sameMember: 'applyRegistryWriteThrough' | 'restoreArtifactRegistryView' } /** The member hands the row to its callers, and each of them calls `then`, which calls the write-through. */ - | { readonly handedTo: 'callers'; readonly then: 'runPublishSideEffects' }; + | { readonly handedTo: 'callers'; readonly then: 'runPublishSideEffects' } + /** + * [ADR-0159 D5] A module function that writes inside its caller's + * transaction and hands the rows it wrote back: each caller calls `then` + * after the commit, and `then` both writes through and heals. + */ + | { readonly handedTo: 'module callers'; readonly then: 'healOldShapeFormRowRemovals' }; // [#28355] A door's write lives in its `…Unaudited` body; the public door of the same name // only wraps it with the refusal audit, so the member is the body's name. @@ -172,6 +178,10 @@ const WRITES: ReadonlyArray<{ readonly member: string; readonly verb: string; re { member: 'undoLandedPromotions', verb: 'repo.restoreVersion(', route: { sameMember: 'restoreArtifactRegistryView' } }, { member: 'undoLandedPromotions', verb: 'repo.delete(', route: { sameMember: 'restoreArtifactRegistryView' } }, { member: 'undoLandedPromotions', verb: 'repo.put(', route: { sameMember: 'restoreArtifactRegistryView' } }, + // [ADR-0159 D5] A `form` save, publish or delete removes (or re-saves) the old-shape `view` row of + // its name in the same transaction; each door heals the registry from the rows handed back. + { member: 'applyOldShapeFormRowRemovals', verb: 'repo.delete(', route: { handedTo: 'module callers', then: 'healOldShapeFormRowRemovals' } }, + { member: 'applyOldShapeFormRowRemovals', verb: 'repo.put(', route: { handedTo: 'module callers', then: 'healOldShapeFormRowRemovals' } }, ]; /** The verb as `WRITES` spells it: no whitespace after its open paren, [#29985] the class as `this`. */ @@ -206,7 +216,7 @@ describe('[#23198] every stored-row write in protocol.ts and its modules reaches it('a write handed to its callers reaches the write-through in each of them', () => { for (const row of WRITES) { - if (!('handedTo' in row.route)) continue; + if (!('handedTo' in row.route) || row.route.handedTo !== 'callers') continue; const callers = codeMatches(new RegExp(`\\b${SELF}\\.${row.member}\\(`)); expect(callers.length, `${row.member}: its callers`).toBeGreaterThan(0); for (const call of callers) { @@ -219,6 +229,25 @@ describe('[#23198] every stored-row write in protocol.ts and its modules reaches } }); + it('[ADR-0159 D5] a write handed to its module callers is healed in each of them, after the call', () => { + const rows = WRITES.filter((row) => 'handedTo' in row.route && row.route.handedTo === 'module callers'); + expect(rows.length, 'the module-handed writes').toBeGreaterThan(0); + for (const row of rows) { + const then = (row.route as { then: string }).then; + const callers = codeMatches(new RegExp(`(? call.member !== row.member); + expect(callers.length, `${row.member}: its callers`).toBeGreaterThan(0); + for (const call of callers) { + const { end } = memberAt(call.scanned, call.offset); + const heals = codeMatches(new RegExp(`(? scanned === call.scanned && offset > call.offset && offset < end); + expect(heals.length, `${call.member}: ${row.member} → ${then}`).toBeGreaterThan(0); + } + const body = bodyOf(then); + expect(body).toMatch(new RegExp(`\\b${SELF}\\.applyRegistryWriteThrough\\(`)); + expect(body).toMatch(new RegExp(`\\b${SELF}\\.restoreArtifactRegistryView\\(`)); + } + }); + it('a repository is bound under the one spelling the census reads', () => { // A repository bound under any other name would write past the census. const ACQUIRE = new RegExp(`\\b${SELF}\\.getOverlayRepo\\(\\)|new SysMetadataRepository\\(`); @@ -252,7 +281,11 @@ describe('[#29985] the census reads the modules the split moved bodies to', () = expect(codeMatches(STORED_ROW_WRITE) .filter(({ scanned }) => scanned !== HOST && !isCodemodModule(scanned)) .map(({ scanned, member }) => `${scanned.file}: ${member}`)) - .toEqual(['protocol-packageless-overlay-migration.ts: migratePackagelessOverlays']); + .toEqual([ + 'protocol-form-writes.ts: applyOldShapeFormRowRemovals', + 'protocol-form-writes.ts: applyOldShapeFormRowRemovals', + 'protocol-packageless-overlay-migration.ts: migratePackagelessOverlays', + ]); }); }); diff --git a/packages/objectql/src/package-scoped-exact-qualifier.test.ts b/packages/objectql/src/package-scoped-exact-qualifier.test.ts index d7dd635b159..200997e1a0b 100644 --- a/packages/objectql/src/package-scoped-exact-qualifier.test.ts +++ b/packages/objectql/src/package-scoped-exact-qualifier.test.ts @@ -873,7 +873,7 @@ describe('[#34040] the exact read never serves the service\'s copy of another pa expect([...COVERED].sort()).toEqual([...UNWIRED_COVERED_TYPES].sort()); expect([...OUTSIDE].sort()).toEqual( // [ADR-0150 addendum 2026-11-25] `ai_context` left this list: the registry reads it by `(package, name)`. - ['capability', 'datasource', 'doc', 'external_catalog', 'field', 'object', 'object_extension', 'position', 'seed', 'translation', 'view'], + ['capability', 'datasource', 'doc', 'external_catalog', 'field', 'form', 'object', 'object_extension', 'position', 'seed', 'translation', 'view'], ); }); @@ -964,8 +964,8 @@ describe('[#34247] the exact read of a name the package holds no item of is refu const itemAt = async (served: ObjectStackProtocolImplementation, type: string, packageId: string) => (await served.getMetaItem({ type, name: 'shared', packageId }))?.item as { label?: string } | undefined; - it('the family: the eight types the #34040 pin fixes (`ai_context` is read by package since ADR-0150\'s 2026-11-25 addendum)', () => { - expect([...OUTSIDE_PINNED].sort()).toEqual(['datasource', 'doc', 'external_catalog', 'field', 'object_extension', 'seed', 'translation', 'view']); + it('the family: the nine types the #34040 pin fixes (`form` joins with ADR-0159) (`ai_context` is read by package since ADR-0150\'s 2026-11-25 addendum)', () => { + expect([...OUTSIDE_PINNED].sort()).toEqual(['datasource', 'doc', 'external_catalog', 'field', 'form', 'object_extension', 'seed', 'translation', 'view']); }); it.each(OUTSIDE_PINNED.flatMap((type) => [[type, [A, B]], [type, [B, A]]] as const))( @@ -1101,7 +1101,7 @@ describe('[#34041] the read naming no package serves the one enabled holder besi it('the enumeration: every type the registry does not read by package is pinned below, one-holder, or judged elsewhere', () => { expect([...TWO_HOLDER].sort()).toEqual( // [ADR-0150 addendum 2026-11-25] `ai_context` left this list: the registry reads it by `(package, name)`. - ['assignment_rule', 'datasource', 'doc', 'external_catalog', 'field', 'hook', 'job', 'object_extension', 'queue', 'seed', 'sharing_rule', 'translation', 'view'], + ['assignment_rule', 'datasource', 'doc', 'external_catalog', 'field', 'form', 'hook', 'job', 'object_extension', 'queue', 'seed', 'sharing_rule', 'translation', 'view'], ); }); diff --git a/packages/rest/src/data-write-summary-recompute-other-doors.test.ts b/packages/rest/src/data-write-summary-recompute-other-doors.test.ts index 93c26bbec19..1fbb4c2b042 100644 --- a/packages/rest/src/data-write-summary-recompute-other-doors.test.ts +++ b/packages/rest/src/data-write-summary-recompute-other-doors.test.ts @@ -138,9 +138,11 @@ beforeAll(async () => { const protocol = new Proxy(real as any, { get(target, prop, receiver) { if (prop === 'getMetaItemsPerPackage') return async () => []; + // [ADR-0159] No stored body and no `form` item: the door reads FORM_VIEW through the projection. + if (prop === 'getUnreadableFormBodies') return async () => []; if (prop === 'getMetaItems') { // The engine holds the objects; this harness registers no metadata service. - return async (req: any) => (req?.type === 'view' ? [FORM_VIEW] : req?.type === 'object' ? [CHILD_OBJECT, PARENT_OBJECT] : target.getMetaItems(req)); + return async (req: any) => (req?.type === 'view' ? [FORM_VIEW] : req?.type === 'form' ? [] : req?.type === 'object' ? [CHILD_OBJECT, PARENT_OBJECT] : target.getMetaItems(req)); } const v = Reflect.get(target, prop, receiver); return typeof v === 'function' ? v.bind(target) : v; diff --git a/packages/rest/src/form-routes.ts b/packages/rest/src/form-routes.ts index ae0737b5bfd..fcc7ff88f78 100644 --- a/packages/rest/src/form-routes.ts +++ b/packages/rest/src/form-routes.ts @@ -80,6 +80,8 @@ import { PROJECTED_FORM_SOURCE_KEY, formIntakeLayer, openFormAt, + projectViewForms, + projectedFormsOf, thankYouRecordFieldNames, type FormIntakeLayer, type UnreadableFormBody, @@ -159,12 +161,6 @@ function thankYouAnswerFields( return kept > 0 ? fields : undefined; } -/** - * Register the public (anonymous) form endpoints — - * `RestServer#registerFormEndpoints`' body, called by that method with the - * server as `this`. The method's own docblock, which the published declaration - * carries, names the two routes and what authorizes them. - */ /** * [ADR-0159 D2] The body of a `form` item the doors serve as the form: the * item without its envelope (its identity, its label — served beside the form @@ -182,6 +178,12 @@ function formBodyOf(item: unknown): any { return body; } +/** + * Register the public (anonymous) form endpoints — + * `RestServer#registerFormEndpoints`' body, called by that method with the + * server as `this`. The method's own docblock, which the published declaration + * carries, names the two routes and what authorizes them. + */ export function registerFormEndpoints(this: FormRouteHost, basePath: string): void { const isScoped = basePath.includes('/environments/:environmentId'); @@ -243,7 +245,10 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo if (item?.[PROJECTED_FORM_SOURCE_KEY] === 'view') { const pkg = item?._packageId ?? undefined; for (const view of views ?? []) { - if (!view || typeof view !== 'object' || view.name !== item.name) continue; + 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; @@ -302,7 +307,14 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo : []); const formsRequest: TransportScopedMetaRequest = { ...viewsRequest, type: 'form' }; const views = listOf(await p.getMetaItems(viewsRequest)); - const forms = typeof (p as any).getMetaItems === 'function' ? listOf(await p.getMetaItems(formsRequest)) : []; + // [ADR-0159 D5] The candidates are the effective `form` read, which + // projects the old shapes itself. A protocol that serves no `form` + // item at all (one older than the type) serves its forms only as old + // shapes, and the doors read them through THE same projection; where + // the protocol serves the type, an empty `form` read is the same + // projection of the same `view` read, so nothing is added. + const servedForms = listOf(await p.getMetaItems(formsRequest)); + const forms = servedForms.length > 0 ? servedForms : projectedFormsOf(views); // [#28409] The per-package layers, where the protocol serves them: a // server-only extension, feature-detected like the other extensions // the doors read. A protocol without it serves no narrower list than diff --git a/packages/rest/src/public-form-file-field.test.ts b/packages/rest/src/public-form-file-field.test.ts index 484451022b1..c2f457825ac 100644 --- a/packages/rest/src/public-form-file-field.test.ts +++ b/packages/rest/src/public-form-file-field.test.ts @@ -112,6 +112,8 @@ describe('[#25572] POST /forms/:slug/submit: an anonymous submission carries no const protocol: any = new ObjectStackProtocolImplementation(engine as any); const realGetMetaItems = protocol.getMetaItems.bind(protocol); protocol.getMetaItems = async (request: any) => { + // [ADR-0159 D5] No `form` item is injected: the doors read the injected old shape through the projection. + if (request?.type === 'form') return []; if (request?.type === 'view') return [FORM]; if (request?.type === 'object') return [SUPPLIER]; return realGetMetaItems(request); @@ -119,6 +121,8 @@ describe('[#25572] POST /forms/:slug/submit: an anonymous submission carries no // [#28409] The doors judge withdrawal against the effective list beside // the per-package layer: the injected list is that whole layer here. protocol.getMetaItemsPerPackage = async (request: any) => (request?.type === 'view' ? [FORM] : []); + // [ADR-0159 D6 rule 7] No stored body here: the store is not provisioned, the injected lists are the layer. + protocol.getUnreadableFormBodies = async () => []; const realCreateData = protocol.createData.bind(protocol); createData = vi.fn(realCreateData); protocol.createData = createData; diff --git a/packages/rest/src/public-form-intake-availability.test.ts b/packages/rest/src/public-form-intake-availability.test.ts index 489496bcd59..1458cba00b8 100644 --- a/packages/rest/src/public-form-intake-availability.test.ts +++ b/packages/rest/src/public-form-intake-availability.test.ts @@ -177,7 +177,8 @@ describe('[#21476] a public form that cannot take intake on this posture is not // file field carrying a value is refused), which reads it whenever a // declared field carries a value. None for the predicate: a predicate // that read the object on this posture would be a second object read. - expect(s.getMetaItems.mock.calls.map(([r]) => r.type)).toEqual(['view', 'object']); + // [ADR-0159 D5] Beside it, the env-wide `form` read the candidates come from. + expect(s.getMetaItems.mock.calls.map(([r]) => r.type)).toEqual(['view', 'form', 'object']); }); it('CONTROL: a degraded walled request reads the posture IN FORCE (single) — accepted', async () => { diff --git a/packages/rest/src/public-form-option-subset.test.ts b/packages/rest/src/public-form-option-subset.test.ts index 831e9c7d31a..d9fd6a9cd7e 100644 --- a/packages/rest/src/public-form-option-subset.test.ts +++ b/packages/rest/src/public-form-option-subset.test.ts @@ -171,6 +171,8 @@ describe('[#27606] POST /forms/:slug/submit: a form row\'s `options` subset is e const protocol: any = new ObjectStackProtocolImplementation(engine as any); const realGetMetaItems = protocol.getMetaItems.bind(protocol); protocol.getMetaItems = async (request: any) => { + // [ADR-0159 D5] No `form` item is injected: the doors read the injected old shape through the projection. + if (request?.type === 'form') return []; if (request?.type === 'view') return [FORM, WIDE_FORM, LOOSE_FORM]; if (request?.type === 'object') return [CASE]; return realGetMetaItems(request); @@ -178,6 +180,8 @@ describe('[#27606] POST /forms/:slug/submit: a form row\'s `options` subset is e // [#28409] The doors judge withdrawal against the effective list beside // the per-package layer: the injected list is that whole layer here. protocol.getMetaItemsPerPackage = async (request: any) => (request?.type === 'view' ? [FORM, WIDE_FORM, LOOSE_FORM] : []); + // [ADR-0159 D6 rule 7] No stored body here: the store is not provisioned, the injected lists are the layer. + protocol.getUnreadableFormBodies = async () => []; const realCreateData = protocol.createData.bind(protocol); createData = vi.fn(realCreateData); protocol.createData = createData; diff --git a/packages/rest/src/public-form-required.test.ts b/packages/rest/src/public-form-required.test.ts index 6b08e05b93b..7ba06ad5192 100644 --- a/packages/rest/src/public-form-required.test.ts +++ b/packages/rest/src/public-form-required.test.ts @@ -134,6 +134,8 @@ describe('[#24131] POST /forms/:slug/submit enforces the form\'s own `required`' const protocol: any = new ObjectStackProtocolImplementation(engine as any); const realGetMetaItems = protocol.getMetaItems.bind(protocol); protocol.getMetaItems = async (request: any) => { + // [ADR-0159 D5] No `form` item is injected: the doors read the injected old shape through the projection. + if (request?.type === 'form') return []; if (request?.type === 'view') return [FORM]; if (request?.type === 'object') return [LEAD]; return realGetMetaItems(request); @@ -141,6 +143,8 @@ describe('[#24131] POST /forms/:slug/submit enforces the form\'s own `required`' // [#28409] The doors judge withdrawal against the effective list beside // the per-package layer: the injected list is that whole layer here. protocol.getMetaItemsPerPackage = async (request: any) => (request?.type === 'view' ? [FORM] : []); + // [ADR-0159 D6 rule 7] No stored body here: the store is not provisioned, the injected lists are the layer. + protocol.getUnreadableFormBodies = async () => []; const rest = new RestServer(mockServer() as any, protocol, { api: { requireAuth: false } } as any); rest.registerRoutes(); const submit = rest.getRoutes().find((r: any) => r.method === 'POST' && r.path === '/api/v1/forms/:slug/submit'); diff --git a/packages/rest/src/rest-write-route-hook-refusal-sentence.ledger.test.ts b/packages/rest/src/rest-write-route-hook-refusal-sentence.ledger.test.ts index 217f16ad60e..a254b724e84 100644 --- a/packages/rest/src/rest-write-route-hook-refusal-sentence.ledger.test.ts +++ b/packages/rest/src/rest-write-route-hook-refusal-sentence.ledger.test.ts @@ -129,9 +129,12 @@ const UNIT_CODE_FIELDS = { const READS: Record = { getDiscovery: async () => ({ version: 'v0', routes: {} }), getMetaTypes: async () => [], - getMetaItems: async (req: { type?: string }) => (req?.type === 'view' ? [FORM_VIEW] : [SCHEMA]), + // [ADR-0159 D5] No `form` item: the form door reads FORM_VIEW through the projection. + getMetaItems: async (req: { type?: string }) => (req?.type === 'view' ? [FORM_VIEW] : req?.type === 'form' ? [] : [SCHEMA]), // [#28409] The form doors' withdrawal layer beside the effective list. getMetaItemsPerPackage: async (req: { type?: string }) => (req?.type === 'view' ? [FORM_VIEW] : []), + // [ADR-0159 D6 rule 7] No stored body the projection cannot read. + getUnreadableFormBodies: async () => [], getMetaItem: async () => SCHEMA, findData: async () => ({ records: [] }), getData: async () => ({ record: { id: 'r1' } }), diff --git a/packages/spec/dropped-refinements.baseline.json b/packages/spec/dropped-refinements.baseline.json index 6276a80c1dc..0a06c1b6b50 100644 --- a/packages/spec/dropped-refinements.baseline.json +++ b/packages/spec/dropped-refinements.baseline.json @@ -2,8 +2,8 @@ "description": "Shrink-only ledger of every PUBLISHED JSON Schema that is STILL WIDER than the Zod type it was generated from, because a rule written as `.refine()` reaches the runtime and not the file (#18670). `z.toJSONSchema()` has no arm for a `custom` check: a plain record, the same record with a `.refine()`, and the same record with an ABORTING `.refine()` all project byte-identically (measured on zod 4.4.3, the version packages/spec resolves). So a document one of these files ACCEPTS can still be refused at parse time, and an author -- or an AI -- validating against packages/spec/json-schema/** finds out a release later. Each `sites` path is a position under that schema at which a refinement is dropped; the same paths are written onto the artifact itself as `x-dropped-refinements`. Item 2 closed the first patterns: a refinement DECLARED through the closed list in src/shared/refinement-projection.ts is emitted into the published file, reads `projected` rather than `dropped`, and its row LEAVES this ledger in the same PR -- which is why the ledger shrinks and never grows on a repair. Every refinement outside that closed list stays here, and adding an arm to the list is a public-contract decision, not a refactor. Hand-edited on purpose and with no `gen:` script: a generator would let a new gap be admitted by running a command instead of by a decision, which is the silence this ledger exists to end. Adding, removing or moving a site fails packages/spec/scripts/build-schemas.ts until the line moves with it, and the failure prints the corrected entry in full. ⛔ Do not delete or weaken a refinement to shorten this file -- the runtime rule is correct; it is the projection that is silent, and the remedy is to teach the closed list a NAMED pattern, never to drop the rule.", "measured": { "zod": "4.4.3", - "publishedSchemasWithDroppedRefinements": 276, - "droppedRefinementSites": 1188, + "publishedSchemasWithDroppedRefinements": 277, + "droppedRefinementSites": 1196, "refinementSitesThatDidProject": 728, "refinementSitesWithNoJsonFormToCompare": 0 }, diff --git a/packages/spec/src/kernel/collection-item-owner-stamp.ts b/packages/spec/src/kernel/collection-item-owner-stamp.ts index a839c430748..d9e76c10ea2 100644 --- a/packages/spec/src/kernel/collection-item-owner-stamp.ts +++ b/packages/spec/src/kernel/collection-item-owner-stamp.ts @@ -100,7 +100,7 @@ export interface CollectionItemOwnerStampRefusal { export const OWNER_STAMP_JUDGED_COLLECTIONS = Object.freeze([ 'objects', 'apps', 'picklists', - 'actions', 'views', 'pages', 'dashboards', 'reports', 'datasets', + 'actions', 'views', 'forms', 'pages', 'dashboards', 'reports', 'datasets', 'flows', 'webhooks', 'jobs', 'positions', 'permissions', 'capabilities', 'sharingRules', 'queues', 'assignmentRules', diff --git a/packages/spec/src/kernel/metadata-create-seeds.test.ts b/packages/spec/src/kernel/metadata-create-seeds.test.ts index b93b2159c3b..3f43d014ad9 100644 --- a/packages/spec/src/kernel/metadata-create-seeds.test.ts +++ b/packages/spec/src/kernel/metadata-create-seeds.test.ts @@ -91,6 +91,11 @@ describe('metadata create seeds validate against their spec schemas', () => { // (merge question 11). Same category as `sharing_rule`. 'queue', 'assignment_rule', + // [ADR-0159 card ②] `form` is runtime-creatable (a `/meta/form` save) but + // Studio has no form designer for it yet: the console keeps reading forms + // from `view` until card ③ (#37087), which brings the designer and its + // seed. Deferred work, named here so it is not a silent gap. + 'form', ]); const seeded = new Set(listMetadataCreateSeedTypes()); const missing = listMetadataTypeSchemaTypes().filter((t) => !seeded.has(t) && !KNOWN_UNSEEDED.has(t)); diff --git a/packages/spec/src/kernel/metadata-credential-fields.test.ts b/packages/spec/src/kernel/metadata-credential-fields.test.ts index a5870988144..0cd7640eb45 100644 --- a/packages/spec/src/kernel/metadata-credential-fields.test.ts +++ b/packages/spec/src/kernel/metadata-credential-fields.test.ts @@ -50,6 +50,10 @@ const NOT_A_CREDENTIAL: Readonly> = { 'datasource:external.connector': 'the NAME of a declared connector instance (snake_case, pattern-checked); the credential it lends stays on ' + 'that instance, referenced by its own `auth.credentialRef` (ADR-0015 amendment D7)', + 'form:sharing.password': + 'the form view\'s own `SharingConfigSchema.password`, carried onto the `form` item by reference (ADR-0159 D2) and ' + + 'served unmarked on every `view` form slot today; marking it changes what both types serve, so it is decided once ' + + 'for the shared schema (named in the #37086 report), not for one of its two carriers', }; const CREDENTIAL_WORDS = new Set([ diff --git a/packages/spec/src/kernel/override-declaration.test.ts b/packages/spec/src/kernel/override-declaration.test.ts index 45eb8895d2f..5a39ca3ba02 100644 --- a/packages/spec/src/kernel/override-declaration.test.ts +++ b/packages/spec/src/kernel/override-declaration.test.ts @@ -103,6 +103,7 @@ const EXTRA_FIXTURES: Partial>> = { app: { name: 'crm', label: 'CRM', navigation: [] }, doc: { name: 'crm_lead_guide', content: '# Lead Guide' }, book: { name: 'crm_guide', groups: [{ key: 'start', label: 'Start', include: 'crm_*' }] }, + form: { name: 'crm_lead.web_to_lead', object: 'crm_lead', type: 'simple', sections: [{ fields: [{ field: 'name' }] }] }, }; function fixtureFor(type: MetadataType): Record { @@ -123,10 +124,10 @@ const LIST_OVERLAY = { }; describe('the stored body — every overridable type carries `overrides` through its metadata schema', () => { - it('the overridable list is the thirteen types ADR-0146 D2 names', () => { + it('the overridable list is the thirteen types ADR-0146 D2 names, and `form` (ADR-0159 D2)', () => { expect([...OVERRIDABLE_METADATA_TYPES].sort()).toEqual([ 'action', 'app', 'book', 'dashboard', 'dataset', 'doc', 'email_template', - 'flow', 'mapping', 'page', 'report', 'translation', 'view', + 'flow', 'form', 'mapping', 'page', 'report', 'translation', 'view', ]); }); From d649e85a4f70c5a0bc639bc9cb8324e5a33d1b8f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 03:31:19 +0000 Subject: [PATCH 05/29] test(form): census cells and ratchets for the form type MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The owner-stamp fixture tables, the meta list/item census, the CLI schema-gate classification and the metadata-form catalog ratchets each gain the form type (ADR-0159 card ②, #37086). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .../test/metadata-type-schema-gate.test.ts | 3 +++ .../owner-stamp-residual-build-boot.test.ts | 1 + .../bare-type-display-echo-decisions.test.ts | 19 +++++++++++-------- ...ect-lifecycle-panel-echo-decisions.test.ts | 4 +++- .../meta-list-projection-parity.test.ts | 10 ++++++++++ .../stack-collection-item-owner-stamp.test.ts | 1 + 6 files changed, 29 insertions(+), 9 deletions(-) diff --git a/packages/cli/test/metadata-type-schema-gate.test.ts b/packages/cli/test/metadata-type-schema-gate.test.ts index 2e2c0ae5be7..3050986f6ea 100644 --- a/packages/cli/test/metadata-type-schema-gate.test.ts +++ b/packages/cli/test/metadata-type-schema-gate.test.ts @@ -110,6 +110,9 @@ const GATED_AT: Readonly> = { skill: 'skills', // [ADR-0160 D1] `ai_context`: CLOSED from its first day, authored at `aiContexts:`. ai_context: 'aiContexts', + // [ADR-0159 card ②] `form`: CLOSED from its first day (`FormSchema` is a + // `strictObject`), authored at `forms:` as a flat array of that same shape. + form: 'forms', // [#5384] `api` GRADUATED here from NOT_YET_CLOSED — the deliberate ratchet // step this file's own note asked for. `ApiEndpointSchema` is `strictObject` // as of #5384, so the stack's `apis:` array and the registry schema now reject diff --git a/packages/metadata/src/owner-stamp-residual-build-boot.test.ts b/packages/metadata/src/owner-stamp-residual-build-boot.test.ts index 4ff53ca2d24..a410d41091f 100644 --- a/packages/metadata/src/owner-stamp-residual-build-boot.test.ts +++ b/packages/metadata/src/owner-stamp-residual-build-boot.test.ts @@ -73,6 +73,7 @@ const JUDGED_FIXTURES: Record { - it('⭐ the registry and the catalog describe the same 33 metadata types', () => { + it('⭐ the registry and the catalog describe the same 34 metadata types', () => { // The ratchet's anchor. The catalog is GENERATED from this registry, so a // new metadata type arrives in both at once — which is what makes the bare // class below pick up a future unauthored display pair without anybody @@ -807,7 +807,9 @@ describe('#19403 round 7 — the population, DERIVED from the registry and a sha // description, authored in the three locales on arrival. // 32 → 33: `ai_context` joined it (ADR-0160 D1, #37140), bare with a label // and no description, authored in the three locales on arrival. - expect(REGISTRY_TYPES.length).toBe(33); + // 33 → 34: `form` joined it (ADR-0159 card ②, #37086), bare with a label + // and no description (no designer until card ③), authored on arrival. + expect(REGISTRY_TYPES.length).toBe(34); expect([...REGISTRY_TYPES].sort()).toEqual(Object.keys(enMetadataForms as Record).sort()); }); @@ -815,16 +817,17 @@ describe('#19403 round 7 — the population, DERIVED from the registry and a sha // Lit. // 16 / 17 → 15 / 18: `ai_context` gained its form (ADR-0160 D1 clause 2, // #37143), so it is a panel type now. - expect(BARE_TYPES.length).toBe(15); + // 15 → 16: `form` joined bare (ADR-0159 card ②, #37086). + expect(BARE_TYPES.length).toBe(16); expect(PANEL_TYPES.length).toBe(18); expect(BARE_TYPES.length + PANEL_TYPES.length).toBe(REGISTRY_TYPES.length); for (const type of ['seed', 'mapping', 'api', 'doc', 'book', 'capability', 'picklist', 'sharing_rule', 'queue', 'assignment_rule', 'object_extension']) { expect(BARE_TYPES, `${type} is bare`).toContain(type); } for (const type of AUTHORED_BARE_TYPES) expect(BARE_TYPES, `${type} is bare`).toContain(type); - // 26 leaves: fifteen labels, and a description on the eleven that carry one. - expect(BARE_LEAVES.length).toBe(26); - expect(BARE_LEAVES.filter((l) => l.prop === 'label').length).toBe(15); + // 27 leaves: sixteen labels, and a description on the eleven that carry one. + expect(BARE_LEAVES.length).toBe(27); + expect(BARE_LEAVES.filter((l) => l.prop === 'label').length).toBe(16); expect(BARE_LEAVES.filter((l) => l.prop === 'description').length).toBe(11); expect(BARE_LEAVES.every((l) => ['label', 'description'].includes(l.prop))).toBe(true); }); @@ -906,13 +909,13 @@ describe('#19403 round 7 — the population, DERIVED from the registry and a sha expect(flagged.length).toBe(BARE_LEAVES.length); }); - it('⭐ this class is now DONE — zero of its 26 leaves echoes in all three locales', () => { + it('⭐ this class is now DONE — zero of its 27 leaves echoes in all three locales', () => { const echoing = BARE_LEAVES.filter((l) => TRANSLATED_LOCALES.every(([, forms]) => forms[l.type]?.[l.prop] === l.en), ); expect(echoing.map((l) => `${l.type}.${l.prop}`)).toEqual([]); // Lit — and it really walked the class, which a zero alone would not show. - expect(BARE_LEAVES.length).toBe(26); + expect(BARE_LEAVES.length).toBe(27); }); }); diff --git a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts index 3d95976b4ae..2e90a34941d 100644 --- a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts @@ -1331,7 +1331,9 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // children — three row labels, authored in all three locales. // 837 since #37143: the `ai_context` form (ADR-0160 D1 clause 2) — two // section labels and seven row labels, authored in all three locales. - expect(translated.length, `${locale} positive control`).toBe(837); + // 838 since #37086: the `form` type's own label (ADR-0159 card ②), + // authored in all three locales. + expect(translated.length, `${locale} positive control`).toBe(838); } // ⭐ DARK — the blindness, executable. On a synthetic two-locale catalog the // all-three predicate returns 0 while the per-locale one returns 1, so the diff --git a/packages/runtime/src/domains/meta-list-projection-parity.test.ts b/packages/runtime/src/domains/meta-list-projection-parity.test.ts index e9b6662f7f1..9ea53946260 100644 --- a/packages/runtime/src/domains/meta-list-projection-parity.test.ts +++ b/packages/runtime/src/domains/meta-list-projection-parity.test.ts @@ -181,6 +181,8 @@ const STORE: Record = { permission: [{ name: 'crm_sales_user', label: 'Sales user', objects: {} }], // [#25788] Translated by `translateReport` — a cell of the translatable-type axis. report: [{ name: 'opps_by_stage', label: 'Opportunities by Stage', type: 'summary', dataset: 'pipeline', values: ['amount'] }], + // [#37086] Translated by the `forms` family (ADR-0159) — a cell of the translatable-type axis. + form: [{ name: 'lead.web_intake', label: 'Web intake', object: 'lead', type: 'simple', sections: [{ fields: [{ field: 'company' }] }] }], }; /** @@ -234,6 +236,8 @@ const BUNDLE: Record = { books: { help_center: { label: '帮助中心', groups: { start: { label: '开始' } } } }, // A named import mapping's label. mappings: { lead_feed: { label: '线索导入' } }, + // A form's label (ADR-0159). + forms: { 'lead.web_intake': { label: '网页登记' } }, }, }; @@ -572,6 +576,7 @@ const TYPE_CELLS: readonly string[] = [ 'app', 'apps', 'view', 'views', 'doc', 'docs', 'book', 'books', 'api', 'apis', 'object', 'objects', 'dashboard', 'dashboards', 'page', 'action', 'dataset', 'picklist', 'flow', 'position', 'positions', 'permission', 'permissions', 'report', 'reports', 'mapping', 'mappings', + 'form', 'forms', // [#20408] A segment that names no metadata type: `RestServer` refuses it // (`refuseUnknownMetaListType`) rather than listing an empty collection. 'totally_invented_type', @@ -772,6 +777,9 @@ describe('[#20320] row A: the reference moves — each probe changes RestServer\ expect(zhMappings.items?.find((m: any) => m.name === 'lead_feed')?.label).toBe('线索导入'); const enMappings = await read('/meta/mapping', {}, { 'accept-language': 'en-US' }); expect(enMappings.items?.find((m: any) => m.name === 'lead_feed')?.label).toBe('Lead feed'); + // [#37086] So is a form (ADR-0159). + const zhForms = await read('/meta/forms', {}, { 'accept-language': 'zh-CN' }); + expect(zhForms.items?.find((f: any) => f.name === 'lead.web_intake')?.label).toBe('网页登记'); }); }); @@ -946,6 +954,7 @@ const ITEM_CELLS: readonly string[] = [ '/meta/page/home', '/meta/action/close_case', '/meta/dataset/pipeline', '/meta/picklist/industry', '/meta/flow/on_lead', '/meta/api/crm_served', '/meta/position/sales_rep', '/meta/permission/crm_sales_user', '/meta/report/opps_by_stage', '/meta/mapping/lead_feed', '/meta/mappings/lead_feed', + '/meta/form/lead.web_intake', '/meta/forms/lead.web_intake', ]; const ITEM_TYPE_AXIS = new Set(ITEM_CELLS.map((c) => singular(c.split('/')[2]))); const ITEM_CALLERS = ['holder', 'non-holder', 'builder', 'author'] as const satisfies readonly CallerName[]; @@ -1098,6 +1107,7 @@ describe('[#20408] the item read: the reference moves — each probe changes Res expect((await read('/meta/report/opps_by_stage', {}, { 'accept-language': 'zh-CN' })).item?.label).toBe('各阶段商机'); expect((await read('/meta/book/help_center', {}, { 'accept-language': 'zh-CN' })).item?.groups?.[0]?.label).toBe('开始'); expect((await read('/meta/mapping/lead_feed', {}, { 'accept-language': 'zh-CN' })).item?.label).toBe('线索导入'); + expect((await read('/meta/form/lead.web_intake', {}, { 'accept-language': 'zh-CN' })).item?.label).toBe('网页登记'); const zhDoc = await read('/meta/doc/crm_intro', { locale: 'zh-CN' }); expect(zhDoc.item?.label).toBe('入门'); expect(text(zhDoc)).not.toContain('"translations"'); diff --git a/packages/spec/src/stack-collection-item-owner-stamp.test.ts b/packages/spec/src/stack-collection-item-owner-stamp.test.ts index a5b4a1aca15..5f14f905f0c 100644 --- a/packages/spec/src/stack-collection-item-owner-stamp.test.ts +++ b/packages/spec/src/stack-collection-item-owner-stamp.test.ts @@ -217,6 +217,7 @@ const JUDGED_FIXTURES: Record Date: Thu, 26 Nov 2026 03:35:11 +0000 Subject: [PATCH 06/29] chore(changeset): name platform-objects, whose bundles ship the form label Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .changeset/37086-form-metadata-type.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.changeset/37086-form-metadata-type.md b/.changeset/37086-form-metadata-type.md index 92b4432a611..e2c8159ab17 100644 --- a/.changeset/37086-form-metadata-type.md +++ b/.changeset/37086-form-metadata-type.md @@ -8,6 +8,7 @@ '@objectstack/objectql': minor '@objectstack/runtime': minor '@objectstack/cli': minor +'@objectstack/platform-objects': minor --- feat(spec)!: `form` is a metadata type of its own — `defineForm`, `*.form.ts` and a stack's `forms:` — and the anonymous form doors read a form over both types (ADR-0159 card ②) @@ -17,6 +18,8 @@ Metadata-protocol: narrowed ADR-0159 makes a public form a `form` item: `name` (`OBJECT.KEY`, the name it is served under), `object` (its one binding) and a form view's body at the top level, its keys taken from `FormViewSchema` by reference. A stack lists them under `forms:`, one per `*.form.ts` module built with `defineForm`. The three old `view` shapes that carry a form (a container's `form`, a `formViews` entry, a `viewKind: 'form'` item) keep loading and serving exactly as before: one projection reads them as `form` items, under the names they are served as today, and nothing an author wrote stops loading. +`@objectstack/platform-objects` ships the `form` type's display label in its metadata-form bundles, translated in every bundled locale. + **BREAKING** (the protocol is narrowed, and a published export changes meaning): From 0c972e7a096922508ff6fc9230222a2f880ca875 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 03:38:14 +0000 Subject: [PATCH 07/29] fix(lint): a form item's named sections are _sections anchors of its object translateForm reads a form item's section headings at objects.._sections., so translation-target-unknown must accept those keys. The showcase feedback form's zh-CN section heading tripped it in the dogfood build. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .../validate-translation-references.test.ts | 14 +++++ .../src/validate-translation-references.ts | 63 +++++++++++-------- 2 files changed, 52 insertions(+), 25 deletions(-) diff --git a/packages/lint/src/validate-translation-references.test.ts b/packages/lint/src/validate-translation-references.test.ts index 627fce2fcbe..f7c2ee78d1f 100644 --- a/packages/lint/src/validate-translation-references.test.ts +++ b/packages/lint/src/validate-translation-references.test.ts @@ -189,6 +189,20 @@ describe('validateTranslationReferences — orphan keys', () => { expect(findings).toEqual([]); }); + it('[ADR-0159 card ②] a `form` item\'s named section is a `_sections` anchor of the object it binds to', () => { + // `translateForm` reads a form item's section headings at + // `objects.._sections.`, as it reads a form view's. + const stackWithForm = (sectionKey: string) => ({ + ...leadStack([{ 'zh-CN': { objects: { crm_lead: { label: '线索', _sections: { [sectionKey]: { label: '反馈', fields: { name: { label: '称呼' } } } } } } } }]), + forms: [{ name: 'crm_lead.feedback', object: 'crm_lead', type: 'simple', sections: [{ name: 'feedback', fields: [{ field: 'name' }] }] }], + }); + expect(validateTranslationReferences(stackWithForm('feedback'))).toEqual([]); + // CONTROL: the same stack keyed to a section nothing declares is still reported. + expect(validateTranslationReferences(stackWithForm('feedbacks')).map((f) => f.path)).toEqual([ + 'translations[0]["zh-CN"].objects.crm_lead._sections.feedbacks', + ]); + }); + it('flags an unresolved view / action / section by name', () => { const findings = validateTranslationReferences( leadStack([ diff --git a/packages/lint/src/validate-translation-references.ts b/packages/lint/src/validate-translation-references.ts index fb0fb0c3d6a..d814f2d011c 100644 --- a/packages/lint/src/validate-translation-references.ts +++ b/packages/lint/src/validate-translation-references.ts @@ -717,6 +717,35 @@ function emptyFacts(): ObjectFacts { * of anchors is now a list of call sites, not four copies of a loop that can * drift apart one at a time. */ +/** + * Register the `_sections` names one form-ish container declares, under the + * object it binds to. + * + * Form sections carry an OPTIONAL `name` that exists purely for the + * `_sections` lookup (`ui/view.zod.ts`: "Stable section identifier for i18n + * lookup"). A section without one cannot be translated at all, so it + * contributes nothing here. A form view's container and a `form` item + * (ADR-0159) both feed it: `translateForm` reads a form item's section + * headings at `objects.._sections.`, as a form view's are read. + */ +function addFormSections(container: AnyRec, binding: string | undefined, factsFor: (objectName: string) => ObjectFacts): void { + if (!binding) return; + for (const section of recordsOf(container.sections)) { + const sectionName = strName(section.name); + if (!sectionName) continue; + const facts = factsFor(binding); + facts.sections.add(sectionName); + // A section's entry objects are the `_sections..fields` keys; a + // bare field-name entry authors no copy, so it addresses nothing. + let entries = facts.sectionEntries.get(sectionName); + if (!entries) facts.sectionEntries.set(sectionName, (entries = new Set())); + for (const entry of recordsOf(section.fields)) { + const field = strName(entry.field); + if (field) entries.add(field); + } + } +} + function collectViewRecord(view: AnyRec, factsFor: (objectName: string) => ObjectFacts): void { const recordObject = viewObjectName(view); const bindingOf = (container: AnyRec): string | undefined => @@ -729,31 +758,8 @@ function collectViewRecord(view: AnyRec, factsFor: (objectName: string) => Objec if (objectName && name) factsFor(objectName).forms.add(name); }; - /** - * Register the `_sections` names one form-ish container declares. - * - * Form sections carry an OPTIONAL `name` that exists purely for the - * `_sections` lookup (`ui/view.zod.ts`: "Stable section identifier for i18n - * lookup"). A section without one cannot be translated at all, so it - * contributes nothing here. - */ - const addSections = (container: AnyRec, binding: string | undefined) => { - if (!binding) return; - for (const section of recordsOf(container.sections)) { - const sectionName = strName(section.name); - if (!sectionName) continue; - const facts = factsFor(binding); - facts.sections.add(sectionName); - // A section's entry objects are the `_sections..fields` keys; a - // bare field-name entry authors no copy, so it addresses nothing. - let entries = facts.sectionEntries.get(sectionName); - if (!entries) facts.sectionEntries.set(sectionName, (entries = new Set())); - for (const entry of recordsOf(section.fields)) { - const field = strName(entry.field); - if (field) entries.add(field); - } - } - }; + const addSections = (container: AnyRec, binding: string | undefined) => + addFormSections(container, binding, factsFor); const listBinding = isRec(view.list) ? bindingOf(view.list) : undefined; if (isRec(view.list)) addView(listBinding, defaultListViewKey(listBinding, view)); @@ -1463,6 +1469,13 @@ function buildUniverse(stack: AnyRec): Universe { for (const view of [...recordsOf(stack.views), ...artifactProvidedRecords(stack, 'views')]) { collectViewRecord(view, factsFor); } + // [ADR-0159 card ②] A `form` item's named sections are `_sections` facts of + // the object it binds to (its one `object`), the same anchor a form view's + // sections are. Its own label, title and panel live in the `forms` family, + // keyed by its name, so it contributes no `_views` fact. + for (const form of [...recordsOf(stack.forms), ...artifactProvidedRecords(stack, 'forms')]) { + addFormSections(form, strName(form.object), factsFor); + } // ── Pages: `record:details` sections are the other `_sections` anchor, and // `interfaceConfig.userFilters.tabs` is the ONE `_tabs` anchor ── From 9d212c36d1367a5bf3bbd9b1516081538827d54a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 04:35:45 +0000 Subject: [PATCH 08/29] fix(ui,rest): the form type in the Studio and console tables CI read MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - TranslationPreview draws the forms group, with its strings and fixtures. - Pending changes count a drafted form in every pack. - The console loader namespaces a served forms group. - Studio's directory and menu leave form out until card ③ brings its designer, placement and ADR-0084 row. - The types censuses: spec FormSchema is a name collision with the form node, and checkFormItemNamePrefix judges a schema objectui does not mirror. - rest: the unused withdrawal import goes, and the intake test pays the objectql load at collection. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- packages/rest/src/form-routes.ts | 9 +++++---- .../public-form-intake-availability.test.ts | 3 +++ .../src/preview/DraftChangesPanel.tsx | 2 ++ .../views/metadata-admin/directoryScope.ts | 8 ++++++-- ...anslationPreview.categories-11765.test.tsx | 1 + .../previews/TranslationPreview.tsx | 3 +++ .../adminPreviews.i18n-10862-s2.test.tsx | 3 ++- ui/packages/i18n/src/locales/ar.ts | 7 +++++++ ui/packages/i18n/src/locales/de.ts | 3 +++ ui/packages/i18n/src/locales/en.ts | 3 +++ ui/packages/i18n/src/locales/es.ts | 4 ++++ ui/packages/i18n/src/locales/fr.ts | 4 ++++ ui/packages/i18n/src/locales/ja.ts | 3 +++ ui/packages/i18n/src/locales/ko.ts | 3 +++ ui/packages/i18n/src/locales/pt-BR.ts | 4 ++++ ui/packages/i18n/src/locales/ru.ts | 5 +++++ ui/packages/i18n/src/locales/zh-Hans.ts | 3 +++ ui/packages/i18n/src/locales/zh-Hant.ts | 3 +++ ui/packages/i18n/src/namespaces/studio/en.ts | 1 + ui/packages/i18n/src/namespaces/studio/zh.ts | 1 + .../i18n/src/utils/spec-translations.ts | 4 ++++ .../spec-object-refinements-7715.test.ts | 17 ++++++++++++++--- .../src/__tests__/zod-mirror-parity.test.ts | 19 ++++++++++++++++++- 23 files changed, 102 insertions(+), 11 deletions(-) diff --git a/packages/rest/src/form-routes.ts b/packages/rest/src/form-routes.ts index fcc7ff88f78..37fe93505ae 100644 --- a/packages/rest/src/form-routes.ts +++ b/packages/rest/src/form-routes.ts @@ -59,9 +59,11 @@ * envelope `TransportScopedMetaRequest` is imported from * `meta-collection-routes.ts`, where slice 13a moved it on from `ui-routes.ts` * (slice 10's home for it), and the data doors' `ServerScopedDataRequest` from - * `data-action-routes.ts`, where slice 1 moved it. `anonymousFormIntakeWithdrawnIn`, + * `data-action-routes.ts`, where slice 1 moved it. * `PUBLIC_FORM_SERVER_MANAGED_FIELDS` and `isExpectedRouteError`, which only - * this body read, are imported here instead of there. No export was added + * this body read, are imported here instead of there (and so was + * `anonymousFormIntakeWithdrawnIn`, until ADR-0159 card ② judged withdrawal + * through `formIntakeLayer`). No export was added * anywhere, and the published surface does not move. */ @@ -69,7 +71,6 @@ import { anonymousFormIntakeCandidates, anonymousFormIntakePosture, anonymousFormIntakeUnavailability, - anonymousFormIntakeWithdrawnIn, anonymousFormObjectName, } from '@objectstack/metadata-core'; import { isEmptyForRequired, isMissing } from '@objectstack/core'; @@ -205,7 +206,7 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo // document under its override (the hard requirement ruled on #28238, // option 3). A candidate is served only when no body of its view name // in that layer explicitly withdraws the same form - // (`anonymousFormIntakeWithdrawnIn`: matched by slot or by slug, the + // (then `anonymousFormIntakeWithdrawnIn`: matched by slot or by slug, the // link kept with a switch set to `false`), so a withdrawal in one // package closes the name's form in every package (a known limit that // fails closed). Another view publishing the same slug is a different diff --git a/packages/rest/src/public-form-intake-availability.test.ts b/packages/rest/src/public-form-intake-availability.test.ts index 1458cba00b8..db3be38aaae 100644 --- a/packages/rest/src/public-form-intake-availability.test.ts +++ b/packages/rest/src/public-form-intake-availability.test.ts @@ -15,6 +15,9 @@ import { RestServer } from './rest-server'; // [#10126] Pay the first transform of these dist-resolved workspace deps at // MODULE LOAD rather than inside a clocked `it()` body. import '@objectstack/spec/ui'; +// …and `@objectstack/objectql`, which `rest-server.ts`'s meta-object routes reach +// through a dynamic import inside a handler (`check:test-source-alias`). +import '@objectstack/objectql'; const ORG = 'org_alpha'; const SLUG = 'contact-us'; diff --git a/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx b/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx index c5c177446e0..551f386d56d 100644 --- a/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx +++ b/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx @@ -908,6 +908,8 @@ const TYPE_COUNT: Readonly strin t('preview.changes.typeCount.ai_context', { count, defaultValue: '{{count}} AI context packs' }), datasource: (t, count) => t('preview.changes.typeCount.datasource', { count, defaultValue: '{{count}} datasources' }), + // objectstack#37086 — a `form` item (ADR-0159 card ②) drafts and publishes like a view. + form: (t, count) => t('preview.changes.typeCount.form', { count, defaultValue: '{{count}} forms' }), }; /** The types {@link TYPE_COUNT} names, for the test that holds it to the spec's registry. */ diff --git a/ui/packages/app-shell/src/views/metadata-admin/directoryScope.ts b/ui/packages/app-shell/src/views/metadata-admin/directoryScope.ts index 7f3dea98fc5..e62307771ea 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/directoryScope.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/directoryScope.ts @@ -10,9 +10,13 @@ import { ENVIRONMENT_AREA_TYPES } from './metadataAreaHost.js'; /** * Types never listed. `field` is edited inside its object; `package` is the - * scope container itself, with its own management surface. + * scope container itself, with its own management surface. `form` (ADR-0159 + * card ②, objectstack#37086) has no designer, menu placement or ADR-0084 row + * yet: card ③ (objectstack#37087) brings all three and takes it off this set. + * Its forms are still served and judged; only Studio's directory and menu + * leave the type out. */ -export const HIDDEN_DIRECTORY_TYPES: ReadonlySet = new Set(['field', 'package']); +export const HIDDEN_DIRECTORY_TYPES: ReadonlySet = new Set(['field', 'package', 'form']); /** * The served type entries a directory lists, in served order: diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/TranslationPreview.categories-11765.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/TranslationPreview.categories-11765.test.tsx index b58983a49ce..ff9cb2778f2 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/TranslationPreview.categories-11765.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/TranslationPreview.categories-11765.test.tsx @@ -68,6 +68,7 @@ const ONE_ENTRY: Record; key: string; ro row: () => keys(2), }, pages: { data: { home: { label: 'Accueil' } }, key: 'home', row: () => keys(1) }, + forms: { data: { 'lead.web_intake': { label: 'Inscription web' } }, key: 'lead.web_intake', row: () => keys(1) }, flows: { data: { onboarding: { label: 'Intégration' } }, key: 'onboarding', row: () => keys(1) }, hooks: { data: { credit_guard: { refusals: { CREDIT_LIMIT: { message: 'Limite de crédit dépassée.' } } } }, diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/TranslationPreview.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/TranslationPreview.tsx index 245c95e8824..056593e8be8 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/TranslationPreview.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/TranslationPreview.tsx @@ -38,6 +38,7 @@ import { Database, FileInput, FileText, + FormInput, Gauge, Globe2, LayoutDashboard, @@ -100,6 +101,8 @@ const CATEGORY_DEFS = { datasets: { label: 'engine.translationPreview.category.datasets', icon: Database, flat: false }, reports: { label: 'engine.translationPreview.category.reports', icon: BarChart3, flat: false }, pages: { label: 'engine.translationPreview.category.pages', icon: PanelsTopLeft, flat: false }, + // [ADR-0159 card ②] A `form` item's label, title and thank-you panel. + forms: { label: 'engine.translationPreview.category.forms', icon: FormInput, flat: false }, flows: { label: 'engine.translationPreview.category.flows', icon: Workflow, flat: false }, hooks: { label: 'engine.translationPreview.category.hooks', icon: Webhook, flat: false }, positions: { label: 'engine.translationPreview.category.positions', icon: Users, flat: false }, diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/adminPreviews.i18n-10862-s2.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/adminPreviews.i18n-10862-s2.test.tsx index c25c2387c93..77fdb843bda 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/adminPreviews.i18n-10862-s2.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/adminPreviews.i18n-10862-s2.test.tsx @@ -469,6 +469,7 @@ describe('TranslationPreview reads the designer locale (objectui#10862)', () => { key: 'engine.translationPreview.category.datasets' }, { key: 'engine.translationPreview.category.reports' }, { key: 'engine.translationPreview.category.pages' }, + { key: 'engine.translationPreview.category.forms' }, { key: 'engine.translationPreview.category.flows' }, { key: 'engine.translationPreview.category.hooks' }, { key: 'engine.translationPreview.category.positions' }, @@ -482,7 +483,7 @@ describe('TranslationPreview reads the designer locale (objectui#10862)', () => { key: 'engine.translationPreview.keyCountOne', vars: { count: 1 } }, ]); // The bundle's own locale is author data, not the designer's language. - expectAsWritten(['French', 'fr-FR', 'account', '"Un"', '2/17 (12%)']); + expectAsWritten(['French', 'fr-FR', 'account', '"Un"', '2/18 (11%)']); }); } }); diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 040ffe0ca80..ed12b88cfb3 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -5940,6 +5940,13 @@ const ar = { ai_context_few: 'حزم سياق الذكاء الاصطناعي {{count}}', ai_context_many: 'حزم سياق الذكاء الاصطناعي {{count}}', ai_context_other: 'حزم سياق الذكاء الاصطناعي {{count}}', + form: 'نماذج {{count}}', + form_zero: 'نماذج {{count}}', + form_one: 'نموذج {{count}}', + form_two: 'نماذج {{count}}', + form_few: 'نماذج {{count}}', + form_many: 'نماذج {{count}}', + form_other: 'نماذج {{count}}', datasource: 'مصادر بيانات {{count}}', datasource_zero: 'مصادر بيانات {{count}}', datasource_one: 'مصدر بيانات {{count}}', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index b581fe53706..22c4e04d343 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -5338,6 +5338,9 @@ const de = { ai_context: '{{count}} KI-Kontextpakete', ai_context_one: '{{count}} KI-Kontextpaket', ai_context_other: '{{count}} KI-Kontextpakete', + form: '{{count}} Formulare', + form_one: '{{count}} Formular', + form_other: '{{count}} Formulare', datasource: '{{count}} Datenquellen', datasource_one: '{{count}} Datenquelle', datasource_other: '{{count}} Datenquellen', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index e4a76084830..d821fceaf95 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -4913,6 +4913,9 @@ const en = { ai_context: '{{count}} AI context packs', ai_context_one: '{{count}} AI context pack', ai_context_other: '{{count}} AI context packs', + form: '{{count}} forms', + form_one: '{{count}} form', + form_other: '{{count}} forms', datasource: '{{count}} datasources', datasource_one: '{{count}} datasource', datasource_other: '{{count}} datasources', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index c879e9508ec..be90d5ca793 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -5489,6 +5489,10 @@ const es = { ai_context_one: '{{count}} paquete de contexto de IA', ai_context_many: '{{count}} de paquetes de contexto de IA', ai_context_other: '{{count}} paquetes de contexto de IA', + form: '{{count}} formularios', + form_one: '{{count}} formulario', + form_many: '{{count}} de formularios', + form_other: '{{count}} formularios', datasource: '{{count}} orígenes de datos', datasource_one: '{{count}} origen de datos', datasource_many: '{{count}} de orígenes de datos', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 5bf4039eab7..ad44d013f8c 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -5485,6 +5485,10 @@ const fr = { ai_context_one: '{{count}} pack de contexte IA', ai_context_many: '{{count}} de packs de contexte IA', ai_context_other: '{{count}} packs de contexte IA', + form: '{{count}} formulaires', + form_one: '{{count}} formulaire', + form_many: '{{count}} de formulaires', + form_other: '{{count}} formulaires', datasource: '{{count}} sources de données', datasource_one: '{{count}} source de données', datasource_many: '{{count}} de sources de données', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 5b689d2ef4e..2cbdc4a527b 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -5340,6 +5340,9 @@ const ja = { ai_context: 'AI コンテキストパック {{count}}', ai_context_one: 'AI コンテキストパック {{count}}', ai_context_other: 'AI コンテキストパック {{count}}', + form: 'フォーム {{count}}', + form_one: 'フォーム {{count}}', + form_other: 'フォーム {{count}}', datasource: 'データソース {{count}}', datasource_one: 'データソース {{count}}', datasource_other: 'データソース {{count}}', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 6d159da8f17..b652f1da934 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -5337,6 +5337,9 @@ const ko = { ai_context: 'AI 컨텍스트 팩 {{count}}', ai_context_one: 'AI 컨텍스트 팩 {{count}}', ai_context_other: 'AI 컨텍스트 팩 {{count}}', + form: '양식 {{count}}', + form_one: '양식 {{count}}', + form_other: '양식 {{count}}', datasource: '데이터 소스 {{count}}', datasource_one: '데이터 소스 {{count}}', datasource_other: '데이터 소스 {{count}}', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 09c1cc0730a..ab2547d364a 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -5484,6 +5484,10 @@ const pt = { ai_context_one: '{{count}} pacote de contexto de IA', ai_context_many: '{{count}} de pacotes de contexto de IA', ai_context_other: '{{count}} pacotes de contexto de IA', + form: '{{count}} formulários', + form_one: '{{count}} formulário', + form_many: '{{count}} de formulários', + form_other: '{{count}} formulários', datasource: '{{count}} fontes de dados', datasource_one: '{{count}} fonte de dados', datasource_many: '{{count}} de fontes de dados', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index c1281b7a05c..8e0837af71a 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -5649,6 +5649,11 @@ const ru = { ai_context_few: 'Пакеты контекста ИИ: {{count}}', ai_context_many: 'Пакеты контекста ИИ: {{count}}', ai_context_other: 'Пакеты контекста ИИ: {{count}}', + form: 'Формы: {{count}}', + form_one: 'Форма: {{count}}', + form_few: 'Формы: {{count}}', + form_many: 'Форм: {{count}}', + form_other: 'Формы: {{count}}', datasource: 'Источники данных: {{count}}', datasource_one: 'Источник данных: {{count}}', datasource_few: 'Источники данных: {{count}}', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 832015de466..34806a93164 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -4273,6 +4273,9 @@ const zh = { ai_context: 'AI 上下文包 {{count}}', ai_context_one: 'AI 上下文包 {{count}}', ai_context_other: 'AI 上下文包 {{count}}', + form: '表单 {{count}}', + form_one: '表单 {{count}}', + form_other: '表单 {{count}}', datasource: '数据源 {{count}}', datasource_one: '数据源 {{count}}', datasource_other: '数据源 {{count}}', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index d397fc1bf28..50c1d6e4086 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -4273,6 +4273,9 @@ const zhHant = { ai_context: 'AI 上下文包 {{count}}', ai_context_one: 'AI 上下文包 {{count}}', ai_context_other: 'AI 上下文包 {{count}}', + form: '表單 {{count}}', + form_one: '表單 {{count}}', + form_other: '表單 {{count}}', datasource: '資料來源 {{count}}', datasource_one: '資料來源 {{count}}', datasource_other: '資料來源 {{count}}', diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index aa327874e67..48bafc52553 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -4784,6 +4784,7 @@ const STUDIO_EN: Record = { 'engine.translationPreview.category.dashboards': 'Dashboards', 'engine.translationPreview.category.datasets': 'Datasets', 'engine.translationPreview.category.reports': 'Reports', + 'engine.translationPreview.category.forms': 'Forms', 'engine.translationPreview.category.pages': 'Pages', 'engine.translationPreview.category.flows': 'Flows', 'engine.translationPreview.category.hooks': 'Hooks', diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index 17376aba138..c251304291b 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -4296,6 +4296,7 @@ const STUDIO_ZH: Record = { 'engine.translationPreview.category.dashboards': '仪表盘', 'engine.translationPreview.category.datasets': '数据集', 'engine.translationPreview.category.reports': '报表', + 'engine.translationPreview.category.forms': '表单', 'engine.translationPreview.category.pages': '页面', 'engine.translationPreview.category.flows': '流程', 'engine.translationPreview.category.hooks': '钩子', diff --git a/ui/packages/i18n/src/utils/spec-translations.ts b/ui/packages/i18n/src/utils/spec-translations.ts index 623bc5c5ffd..70398a5196e 100644 --- a/ui/packages/i18n/src/utils/spec-translations.ts +++ b/ui/packages/i18n/src/utils/spec-translations.ts @@ -118,6 +118,10 @@ const SPEC_TRANSLATION_GROUPS = [ // objectstack #34939 serves `mappings` (a named import mapping's label, the // name the import wizard offers it by), copied through onto `app` the same way. 'mappings', + // objectstack #37086 serves `forms` (a `form` item's label, title and + // thank-you panel, ADR-0159 card ②). Nothing on this side reads it yet, but + // a payload carrying it is namespaced like any other group. + 'forms', ] as const; function isPlainObject(value: unknown): value is Record { diff --git a/ui/packages/types/src/__tests__/spec-object-refinements-7715.test.ts b/ui/packages/types/src/__tests__/spec-object-refinements-7715.test.ts index fc8fdb2c5b6..cf9b0c46904 100644 --- a/ui/packages/types/src/__tests__/spec-object-refinements-7715.test.ts +++ b/ui/packages/types/src/__tests__/spec-object-refinements-7715.test.ts @@ -480,6 +480,17 @@ const SITES = [ */ const CARRIED_ELSEWHERE = ['checkGlobalFilterDateDefaultValue'] as const; +/** + * Exported checks of a spec schema objectui has NO mirror of, so no site can + * attach them. `checkFormItemNamePrefix` judges the `form` METADATA ITEM + * (ADR-0159 card ②, objectstack#37086): the name `OBJECT.KEY` against its + * `object`. A renderer meets a form only as the body `@objectstack/rest`'s form + * doors serve, already parsed server-side, never as an authored node. Counted + * only where the installed spec exports it, as the census reads a spec built + * from either tree. + */ +const NOT_MIRRORED = ['checkFormItemNamePrefix'] as const; + /** * Every `check*` FUNCTION `@objectstack/spec/ui` exports, name → binding, read * at RUN time from the entry point's own module namespace. @@ -535,7 +546,7 @@ const PAGE_SITE = 'SpecPageFields → PageNodeSchema (layout.zod.ts)'; * Any OTHER unnamed check still reddens the census below, by name. */ async function specChecksRemovedOnMain(): Promise { - const named = new Set([...SITES.flatMap((s) => [...s.attached, ...s.notAttachable]), ...CARRIED_ELSEWHERE]); + const named = new Set([...SITES.flatMap((s) => [...s.attached, ...s.notAttachable]), ...CARRIED_ELSEWHERE, ...NOT_MIRRORED]); const page = { kind: 'slotted', slots: { details: [{ type: 'object-grid', properties: { data: { provider: 'api', read: { url: '/api/rows' } } } }] } }; const removed: string[] = []; for (const [name, binding] of await specUiChecks()) { @@ -559,12 +570,12 @@ describe('objectui#7715 — census: the spec\'s object-level checks at the six d }); }); - it('every `check*` the spec exports is named by exactly one site, carried elsewhere, or removed on objectstack `main`', async () => { + it('every `check*` the spec exports is named by exactly one site, carried elsewhere, of a schema objectui does not mirror, or removed on objectstack `main`', async () => { const checks = await specUiChecks(); const removedOnMain = await specChecksRemovedOnMain(); // At most the one judge objectstack#23784 removed; zero once objectui installs a spec without it. expect(removedOnMain.length).toBeLessThanOrEqual(1); - const named = [...SITES.flatMap((s) => [...s.attached, ...s.notAttachable]), ...CARRIED_ELSEWHERE, ...removedOnMain].sort(); + const named = [...SITES.flatMap((s) => [...s.attached, ...s.notAttachable]), ...CARRIED_ELSEWHERE, ...NOT_MIRRORED.filter((name) => checks.has(name)), ...removedOnMain].sort(); expect([...checks.keys()].sort()).toEqual(named); for (const [name, binding] of checks) expect(typeof binding, name).toBe('function'); }); diff --git a/ui/packages/types/src/__tests__/zod-mirror-parity.test.ts b/ui/packages/types/src/__tests__/zod-mirror-parity.test.ts index 300d91e3f1b..20583bd8b69 100644 --- a/ui/packages/types/src/__tests__/zod-mirror-parity.test.ts +++ b/ui/packages/types/src/__tests__/zod-mirror-parity.test.ts @@ -5819,6 +5819,16 @@ function typeLiteralOf(shape: Record): string | undefined { return values.length === 1 && typeof values[0] === 'string' ? values[0] : undefined; } +/** + * Barrel names the spec exports for an UNRELATED schema, so the same-name rule + * (1) above would pair two layers that never meet. Each is skipped on its + * `spec#NAME` side only: a `ComponentPropsMap` row still pairs it by its `type`. + */ +const SPEC_NAME_COLLISIONS: Readonly> = { + FormSchema: + "objectui's `FormSchema` is the `form` component node; the spec's (ADR-0159 card ②, objectstack#37086) is the `form` METADATA ITEM — `name` `OBJECT.KEY`, one `object` — which reaches a renderer only through `@objectstack/rest`'s form doors, never as a node", +}; + /** Every derived spec pair, with the keys its spec side declares and the mirror side does not. */ function measureSpecOnlyKeys(): { pairs: string[]; specOnly: string[] } { const spec: Record = { ...SpecData, ...SpecUi }; @@ -5831,7 +5841,7 @@ function measureSpecOnlyKeys(): { pairs: string[]; specOnly: string[] } { if (!mirrorShape) continue; const literal = typeLiteralOf(mirrorShape); const sides: [string, unknown][] = []; - if (name in spec) sides.push([`spec#${name}`, spec[name]]); + if (name in spec && !(name in SPEC_NAME_COLLISIONS)) sides.push([`spec#${name}`, spec[name]]); if (literal !== undefined && literal in rows) sides.push([`ComponentPropsMap['${literal}']`, rows[literal]]); const bag = objectOf(mirrorShape.properties); const mirrored = new Set([...Object.keys(mirrorShape), ...(bag ? Object.keys(bag) : [])]); @@ -5867,6 +5877,13 @@ otherwise add a SPEC_ONLY_KEY_ROWS row saying what happens to it.`).toEqual([]); expect(bare.map(([key]) => key), 'a row without its reason is an oversight').toEqual([]); }); + it('every name collision is still a collision, and says why', () => { + const spec: Record = { ...SpecData, ...SpecUi }; + const stale = Object.keys(SPEC_NAME_COLLISIONS).filter((name) => !(name in spec) || !(name in ZodBarrel)); + expect(stale, 'a collision row for a name one side no longer exports — delete it').toEqual([]); + expect(Object.values(SPEC_NAME_COLLISIONS).every((why) => why.trim().length >= 40)).toBe(true); + }); + it('the pairing can see both kinds of pair (non-vacuity)', () => { // A broken reader finds no pair and the first case passes while checking nothing. const { pairs } = measureSpecOnlyKeys(); From d536707958bb7adfe501ab216b79d5d7b126def3 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 04:36:53 +0000 Subject: [PATCH 09/29] chore(changeset): the console strings for the form type Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .changeset/37086-form-type-console-strings.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 .changeset/37086-form-type-console-strings.md diff --git a/.changeset/37086-form-type-console-strings.md b/.changeset/37086-form-type-console-strings.md new file mode 100644 index 00000000000..b64c7b506dd --- /dev/null +++ b/.changeset/37086-form-type-console-strings.md @@ -0,0 +1,11 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +fix(console): the console reads the new `form` type — Studio's translation preview, the pending-changes count and the served `forms` translation group + +Clause-②: no +Metadata-protocol: none + +ADR-0159 card ② (#37086) makes `form` a metadata type of its own with a `forms` translation group. The Studio translation preview now draws a Forms card (en "Forms", zh 表单), the pending-changes summary counts a drafted form as "1 form" / "2 forms" in every bundled locale, and the console's language loader recognises a served document that carries only `forms`. Studio's directory and left menu do not list the `form` type yet: card ③ (#37087) brings its designer and its menu placement. From 2da1058a88d005d39621375b23a4e50c80223df2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 05:10:31 +0000 Subject: [PATCH 10/29] chore(ui): the types FormSchema is a different concept from the spec's form item Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- ui/scripts/check-spec-symbol-derivation.mjs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/ui/scripts/check-spec-symbol-derivation.mjs b/ui/scripts/check-spec-symbol-derivation.mjs index c3295007bc8..9d0a2b8018d 100644 --- a/ui/scripts/check-spec-symbol-derivation.mjs +++ b/ui/scripts/check-spec-symbol-derivation.mjs @@ -578,6 +578,17 @@ const ALLOW = { "in its error output instead of suggesting a lossy rename.", issue: 4115, }, + "@object-ui/types:FormSchema": { + reason: + "Different concepts under one name (objectstack#37086): this is the `form` COMPONENT " + + "node (`type: 'form'`, a field list a page renders), and the spec's FormSchema, added by " + + "ADR-0159 card ②, is the `form` METADATA ITEM (`name` `OBJECT.KEY`, one `object`) that " + + "a renderer meets only as the body `@objectstack/rest`'s form doors serve. Not derivable: " + + "the item carries no node `type` and the node no item `name`. The mirror census skips the " + + "same-name pair by the same reasoning (`SPEC_NAME_COLLISIONS` in zod-mirror-parity.test.ts), " + + "and the node keeps its `ComponentPropsMap['form']` pairing there.", + issue: 37086, + }, "@object-ui/types:SelectOptionSchema": { reason: "Spec-derived dialect (objectui#3090): spec keys flow in by reference via " + From 6103f74f0003948531c2499ba9f23ab8d911e27a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 05:22:58 +0000 Subject: [PATCH 11/29] docs(skills): the platform skill lists forms among the stack's top-level keys The enumeration row only (check:skill-top-level-keys); the prose, examples and evals are #37105's. The token ceiling moves by the row's measured +2 (6149 -> 6151), the standing enumeration-row case: ruling A on #32584 (record 6819475461), made standing by #32673 letter A (record 6840575378). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- scripts/check-skills-token-ratchet.mjs | 14 +++++++++++++- skills/objectstack-platform/SKILL.md | 2 +- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index 58e34b3d88c..2f420375d31 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -870,7 +870,19 @@ export const CEILINGS = new Map([ // are absorbed and the ceiling moves 6148 -> 6149 (+1). Pinned AT the // measurement. // ceil(($(wc -c < skills/objectstack-platform/SKILL.md) - 20) / 4) == ceil(24594 / 4) - ['skills/objectstack-platform/SKILL.md', 6149], + // 6149 -> 6151 (card #37086): the enumeration row for the new `forms` stack + // key (ADR-0159 card ②) — `forms` joins the top-level key list, which + // `check:skill-top-level-keys` holds exhaustive over + // `ObjectStackDefinitionSchema`. The standing enumeration-row case: ruling A + // on #32584 (record 6819475461), made standing by #32673 letter A (record + // 6840575378). Raised by the row's own measured delta and by no more; + // nothing else in the file is cut and nothing rides along (its prose, + // examples and evals are #37105's). Arithmetic in priced bytes (stamp line + // excluded): on the base the text was 24594 bytes (6149 tokens, headroom 0); + // the row adds 9 bytes, so the LANDED priced text is 24603 bytes -> 6151 + // tokens: the ceiling moves 6149 -> 6151 (+2). Pinned AT the measurement. + // ceil(($(wc -c < skills/objectstack-platform/SKILL.md) - 20) / 4) == ceil(24603 / 4) + ['skills/objectstack-platform/SKILL.md', 6151], // `skills/objectstack-pm-dispatch/SKILL.md` (9708) and its // `rules/dev-template.md` (1838) left this table on 2026-09-10 with the files: // the maintainer deleted the published PM skill whole (verbatim: diff --git a/skills/objectstack-platform/SKILL.md b/skills/objectstack-platform/SKILL.md index e2c0cc2be43..202a13e1e02 100644 --- a/skills/objectstack-platform/SKILL.md +++ b/skills/objectstack-platform/SKILL.md @@ -32,7 +32,7 @@ metadata: `defineStack()` accepts an `ObjectStackDefinitionInput` whose top-level keys are `manifest`, `packages`, `objects`, `objectExtensions`, `picklists`, -`picklistExtensions`, `views`, `apps`, `pages`, `dashboards`, `reports`, +`picklistExtensions`, `views`, `forms`, `apps`, `pages`, `dashboards`, `reports`, `datasets`, `actions`, `flows`, `jobs`, `emailTemplates`, `docs`, `books`, `positions`, `permissions`, `capabilities`, `sharingRules`, `queues`, `assignmentRules`, `apis`, `webhooks`, `api`, `server`, From 97341d57da84d7143c7990ef72a82fff0e8b77ef Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 05:55:46 +0000 Subject: [PATCH 12/29] docs: CLI transcripts count 82 author-time rules on the merged tree Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- content/docs/deployment/cli.mdx | 2 +- content/docs/deployment/validating-metadata.mdx | 2 +- content/docs/getting-started/build-with-claude-code.mdx | 2 +- content/docs/ui/react-pages.mdx | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 997923bb601..5e887692ac9 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -937,7 +937,7 @@ os compile --json # JSON output for CI pipelines → Normalizing stack definition... → Lowering inline handlers... → Validating protocol compliance... - → Running author-time rules (81)... + → Running author-time rules (82)... → Checking that every required capability has a provider installable in this edition... → Collecting package docs (ADR-0046)... 0 collected → Writing artifact... diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index 72f77750452..7144f4b179f 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -867,7 +867,7 @@ A clean run walks the registry and reports timing: Config: /path/to/support-desk/objectstack.config.ts Load time: 21ms → Validating against ObjectStack Protocol... - → Running author-time rules (81)... + → Running author-time rules (82)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/content/docs/getting-started/build-with-claude-code.mdx b/content/docs/getting-started/build-with-claude-code.mdx index f9ad115e2a9..c6f1b6bf791 100644 --- a/content/docs/getting-started/build-with-claude-code.mdx +++ b/content/docs/getting-started/build-with-claude-code.mdx @@ -311,7 +311,7 @@ visible: 'status != "resolved"' ◆ Validate ──────────────────────────────────────── → Validating against ObjectStack Protocol... - → Running author-time rules (81)... + → Running author-time rules (82)... ✗ Author-time rules failed (1 issue) • stack · action 'resolve_ticket' visible: bare reference `status` — a diff --git a/content/docs/ui/react-pages.mdx b/content/docs/ui/react-pages.mdx index 6315fde8a9c..833444c4f49 100644 --- a/content/docs/ui/react-pages.mdx +++ b/content/docs/ui/react-pages.mdx @@ -404,7 +404,7 @@ objectstack validate ──────────────────────────────────────── → Loading configuration... → Validating against ObjectStack Protocol... - → Running author-time rules (81)... + → Running author-time rules (82)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... From 995bbce917d90c59d06f29f3d1a924fed83f35aa Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:01:18 +0000 Subject: [PATCH 13/29] fix(metadata-protocol,rest): judge the address clash at publish and restore; one candidate read at the form doors formTypeWriteRefusal asks the package-less list refusal and the public address clash together, at draft promotion and in the restore writer, so the three doors the ledger names all refuse FORM_ADDRESS_TAKEN. The form doors read their candidates from the effective form read alone; the test doubles serve that read as the protocol does for an old-shape fixture, through projectedFormsOf. The effective form read pushes names down, resolves a package-less stored form row at an old-shape address in the served-row order (one definition per address), and the by-name read resolves the name once. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .../src/protocol-authoring-gate.ts | 27 ++++--- .../src/protocol-form-reads.ts | 74 ++++++++++++++++++- .../src/protocol-form-writes.ts | 22 ++++++ .../src/protocol-history-and-publish.ts | 22 +++--- .../src/protocol-meta-item-reads.ts | 15 ++-- .../src/protocol-meta-list-reads.ts | 31 +++++--- packages/metadata-protocol/src/protocol.ts | 10 +-- ...rite-summary-recompute-other-doors.test.ts | 4 +- packages/rest/src/form-routes.ts | 14 ++-- .../rest/src/public-form-file-field.test.ts | 5 +- .../public-form-intake-availability.test.ts | 4 +- .../src/public-form-option-subset.test.ts | 5 +- .../rest/src/public-form-required.test.ts | 5 +- .../src/public-form-routes.stored-row.test.ts | 2 + packages/rest/src/public-form-routes.test.ts | 4 +- .../rest/src/public-form-section-i18n.test.ts | 4 +- .../src/public-form-submit-answer.test.ts | 4 +- .../rest/src/public-form-title-i18n.test.ts | 3 +- .../rest/src/public-form-withdrawal.test.ts | 10 +-- ...route-hook-refusal-sentence.ledger.test.ts | 3 +- 20 files changed, 193 insertions(+), 75 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index 52d2ea1bd8d..64eef5c1272 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -102,11 +102,12 @@ export interface AuthoringGateHost { unknownPicklistBindingSaveRefusal: ObjectStackProtocolImplementation['unknownPicklistBindingSaveRefusal']; seedExternalIdSaveRefusal: ObjectStackProtocolImplementation['seedExternalIdSaveRefusal']; /** - * [ADR-0159 card ② item 5] The save door's package-less list-over-form - * refusal ({@link packagelessListOverFormRefusal}), asked of a restored - * body against the binding it is restored into. + * [ADR-0159 card ② items 5 and 7] The save door's two `form`-type + * refusals ({@link formTypeWriteRefusal}: the package-less list over a + * form, and the public address clash), asked of a restored body against + * the binding it is restored into. */ - listOverFormRefusal: (type: string, item: unknown, name: string, binding: string | null) => Error | undefined; + formRestoreRefusal: (type: string, item: unknown, name: string, binding: string | null) => Promise; /** [#34776] The automation engine's sealed node-type vocabulary ({@link sealedFlowNodeTypeVocabulary}). */ sealedFlowNodeTypeVocabulary: () => readonly string[] | undefined; } @@ -121,7 +122,7 @@ export function restoredBodyDerivation( /** The body of `ObjectStackProtocolImplementation#restoredBodyWriter`; the method's docblock there is its contract. */ export function restoredBodyWriter( - this: Pick, + this: Pick, type: string, name: string, binding: string | null, source: string): (historyBody: unknown) => Promise { const derive = this.restoredBodyDerivation(type); return async (historyBody) => { @@ -135,13 +136,15 @@ export function restoredBodyWriter( // [#28574] An `object_extension` version against its address, on the same binding. const extensionRefusal = this.objectExtensionItemRefusal(type, historyBody, name, binding); if (extensionRefusal) throw extensionRefusal; - // [ADR-0159 card ② item 5] …and a package-less view whose restored - // body would store a list at the name a read-only package authors as a - // `form`: the save door refuses that body (`VALIDATION_ERROR`, 400), - // so a rollback or a revert restoring it is refused with the same - // sentence before anything is written. - const listOverForm = this.listOverFormRefusal(type, historyBody, name, binding); - if (listOverForm) throw listOverForm; + // [ADR-0159 card ② items 5 and 7] …and the save door's two `form`-type + // refusals: a package-less view whose restored body would store a list + // at the name a read-only package authors as a `form` + // (`VALIDATION_ERROR`, 400), and a `form` version that would be left + // open on a public address another form holds (`FORM_ADDRESS_TAKEN`, + // 409). A rollback or a revert restoring either is refused with the + // save door's sentence before anything is written. + const formRefusal = await this.formRestoreRefusal(type, historyBody, name, binding); + if (formRefusal) throw formRefusal; await this.refuseRestoredBodyTheSaveDoorRefuses(type, name, historyBody, binding, source); // [#37013] A restore is never the platform's registration: the body is // written without the platform's mark, read where the store reads it. diff --git a/packages/metadata-protocol/src/protocol-form-reads.ts b/packages/metadata-protocol/src/protocol-form-reads.ts index 80c9c7c8d4c..2305840bbff 100644 --- a/packages/metadata-protocol/src/protocol-form-reads.ts +++ b/packages/metadata-protocol/src/protocol-form-reads.ts @@ -196,9 +196,40 @@ export async function readEffectiveForms( request: { type: string; packageId?: string; names?: readonly string[]; previewDrafts?: boolean }, audience: 'served' | 'execution', ): Promise { + return (await readEffectiveFormList(host, request, audience)).items; +} + +/** + * {@link readEffectiveForms}, with the envelope of the generic `form` list it + * read (`type`, the served decorations): the list faces answer it without a + * second generic read. + * + * - **`names` is pushed down** into both generic reads (`GetMetaItemsRequest.names`, + * kept once every source is merged): every reading below judges an item by + * its own name, and a projected form carries the name of the `view` item it + * is read from, so the named items resolve exactly as the whole list would. + * The stored rows of step 3 are read whole: a container row's `name` is not + * the name its expansion writes, so no row predicate can select them by the + * form's name. + * - **`packageId` is NOT pushed down**, and is applied to the resolved list: + * the effective `form` read is resolved per address over both types, and a + * list scoped to a package reads another address than its own. Step 1 + * re-keys a declared `form` override onto its base's address from the + * base's projected `view` item, which a list scoped to the pair never holds, + * and a `view` list scoped to a package seats the package-less rows in that + * package's slots (#21817), which would be projected as the package's own + * forms ahead of the served-row order step 3 asks. Filtered after, the + * answer at `packageId` is the item the unscoped resolution serves there. + */ +export async function readEffectiveFormList( + host: FormReadHost, + request: { type: string; packageId?: string; names?: readonly string[]; previewDrafts?: boolean }, + audience: 'served' | 'execution', +): Promise<{ type: string; items: unknown[] } & Record> { const { packageId: scope, names, ...rest } = request; - const unscoped = { ...rest, type: 'form' }; - const generic = (await host.readFlattenedMetaItems(unscoped, audience)).items as unknown[]; + const unscoped = { ...rest, type: 'form', ...(names !== undefined ? { names } : {}) }; + const genericList = await host.readFlattenedMetaItems(unscoped, audience) as { items: unknown[] } & Record; + const generic = genericList.items; const views = (await host.readFlattenedMetaItems({ ...unscoped, type: 'view' }, audience)).items as unknown[]; const installed = installedManifestsOfEngine(host.engine); @@ -255,9 +286,27 @@ export async function readEffectiveForms( let places: StoredFormPlace[] | undefined; const placesOf = async (): Promise => (places ??= await storedFormPlaces(host)); + // [D5, one address holds one definition] A package's address that still + // authors its form as an old shape is resolved by the `view` merge (step + // 2), and a package-less stored `form` row of the name is in that + // address's served-row order too. Such a row is judged at each of those + // addresses below, before it is listed on its own. + const projectedAddressesOf = new Map(); + for (const key of projectedOrder) { + const pkg = packageOf(projected.get(key)); + const name = String(projected.get(key)!.name); + if (pkg === undefined || genericByKey.has(key) || leftView(pkg, name)) continue; + projectedAddressesOf.set(name, [...(projectedAddressesOf.get(name) ?? []), pkg]); + } + const packagelessFormRows = new Map(); + for (const [key, item] of genericByKey) { const name = String((item as { name?: unknown }).name); const pkg = packageOf(item); + if (pkg === undefined && projectedAddressesOf.has(name)) { + packagelessFormRows.set(name, { key, item }); + continue; + } if (!leftView(pkg, name)) { put(key, item); continue; @@ -279,6 +328,7 @@ export async function readEffectiveForms( // Step 2's items, where no generic item holds the same address. An // authored item shadows a projected one of the same package and name. const genericNames = new Set([...genericByKey.values()].map((item) => String((item as { name?: unknown }).name))); + const standingIn = new Set(); for (const key of projectedOrder) { if (genericByKey.has(key)) continue; const item = projected.get(key)!; @@ -289,16 +339,34 @@ export async function readEffectiveForms( // A package-less projection stands in for the addresses of the name // that step 1 resolved (they read it as a candidate): never listed twice. if (pkg === undefined && genericNames.has(name)) continue; + // [D5] A package-less stored `form` row of the name: the served-row + // order at this address decides between it and the `view` row the + // projection read. A stored `form` row wins over a stored `view` row at + // the same place, so where the order picks it the address serves its + // body, under the address's envelope, and the projection is not served. + const packageless = pkg !== undefined ? packagelessFormRows.get(name) : undefined; + if (packageless !== undefined) { + const served = servedFormHolding(await placesOf(), name, pkg!, installed); + if (served?.place.type === 'form' && served.place.packageId === undefined) { + put(key, { ...(packageless.item as object), _packageId: pkg }); + standingIn.add(name); + continue; + } + } 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. + for (const [name, { key, item }] of packagelessFormRows) if (!standingIn.has(name)) put(key, item); let items = order.map((key) => out.get(key)); if (scope !== undefined) items = items.filter((item) => packageOf(item) === scope); + // The read pushed `names` down; a projection names only what its item names, kept exact here. if (names !== undefined) { const wanted = new Set(names); items = items.filter((item) => wanted.has(String((item as { name?: unknown }).name))); } - return items; + return { ...genericList, type: 'form', items }; } /** The rows {@link readUnreadableFormBodies} has reported, so each is said once per process. */ diff --git a/packages/metadata-protocol/src/protocol-form-writes.ts b/packages/metadata-protocol/src/protocol-form-writes.ts index 055eeef9ba9..187a768e645 100644 --- a/packages/metadata-protocol/src/protocol-form-writes.ts +++ b/packages/metadata-protocol/src/protocol-form-writes.ts @@ -157,6 +157,28 @@ export async function formAddressClashRefusal( return err; } +/** + * [ADR-0159 card ② items 5 and 7] The two `form`-type write refusals, asked + * together by the doors that write a body the save door did not judge at its + * own moment: the publish of a draft (`promoteDraftForPublish`) and the + * restore writer (`restoredBodyWriter`). Each asks the save door's own + * predicate with its own envelope: {@link packagelessListOverFormRefusal} + * (`400 VALIDATION_ERROR`) and {@link formAddressClashRefusal} + * (`409 FORM_ADDRESS_TAKEN`), so a draft saved before a holder took the + * address, and a version restored onto it, leave no two open forms on one + * address (ruled question 3 = A). + */ +export async function formTypeWriteRefusal( + host: FormReadHost & Pick, + type: string, + item: unknown, + name: string, + packageId: string | null | undefined, +): Promise { + return packagelessListOverFormRefusal(host, type, item, name, packageId) + ?? await formAddressClashRefusal(host, type, item, name, packageId); +} + /** One write the `form` door makes to the old-shape row carrying a form at its address. */ export type OldShapeFormRowRemoval = | { readonly kind: 'delete'; readonly row: { readonly name: string; readonly packageId: string | null } } diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index 2aada6b1e66..3def2e34ca2 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -23,7 +23,7 @@ * not move. */ -import { applyOldShapeFormRowRemovals, healOldShapeFormRowRemovals, packagelessListOverFormRefusal, type OldShapeFormRowRemoval } from './protocol-form-writes.js'; +import { applyOldShapeFormRowRemovals, formTypeWriteRefusal, healOldShapeFormRowRemovals, type OldShapeFormRowRemoval } from './protocol-form-writes.js'; import { stampHtmlPageRequires } from './runtime-authoring-gate.js'; import type { RuntimeAuthoringIssue, RuntimePendingDeclarations } from './runtime-authoring-gate.js'; import { DraftConflictError, packagelessAddressAmbiguityRefusal } from './sys-metadata-repository.js'; @@ -675,7 +675,7 @@ export class ProtocolHistoryAndPublishFacet { * `recordPendingDenialAudit`, rethrow. Skip it and the refusal is silent * again — the pre-#7748 state, not merely a worse one. */ - static async promoteDraftForPublish(host: Pick, request: { + static async promoteDraftForPublish(host: Pick, request: { type: string; name: string; actor?: string; message?: string; /** * [#8907] ADR-0048 — the package binding of the draft being promoted, @@ -1196,17 +1196,19 @@ export class ProtocolHistoryAndPublishFacet { ); if (nameCollision) throw nameCollision; } - // [ADR-0159 card ② item 5] …and a package-less view draft that would - // store a list at the name a read-only package authors as a `form`: - // the save door refuses that body (`VALIDATION_ERROR`, 400), and a - // draft saved before the gate is refused here with the same sentence - // before `repo.promoteDraft` writes. See - // {@link packagelessListOverFormRefusal}. + // [ADR-0159 card ② items 5 and 7] …and the save door's two `form`-type + // refusals, judged again on the draft's body and the package it is + // promoted into before `repo.promoteDraft` writes: a package-less view + // draft that would store a list at the name a read-only package + // authors as a `form` (`VALIDATION_ERROR`, 400), and a `form` draft + // left open on a public address another form has taken since the + // draft was saved (`FORM_ADDRESS_TAKEN`, 409). See + // {@link formTypeWriteRefusal}. if (draftForGate) { - const listOverForm = packagelessListOverFormRefusal( + const formRefusal = await formTypeWriteRefusal( host, singularType, draftForGate.body, request.name, promoteInto, ); - if (listOverForm) throw listOverForm; + if (formRefusal) throw formRefusal; } // [#28905, ADR-0146 D1, D11] …and the promotion INTO the read-only // base itself, of an item of one of the five overlay types it ships: diff --git a/packages/metadata-protocol/src/protocol-meta-item-reads.ts b/packages/metadata-protocol/src/protocol-meta-item-reads.ts index 8dd44b2847f..e409d542465 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-reads.ts @@ -693,13 +693,14 @@ async function readEffectiveFormItem( request: { type: string; name: string; packageId?: string; member?: string; userTextLocales?: readonly string[] }, ): Promise { const generic: any = await host.readMetaItemFace(request, 'served'); - const listedAt = (packageId: string | undefined) => readEffectiveForms(host, { - type: 'form', - names: [request.name], - ...(packageId !== undefined ? { packageId } : {}), - }, 'served'); - const listed = await listedAt(request.packageId); + // ONE effective read of the name, unscoped: the list scoped to a package + // is the same resolution filtered to that address (`readEffectiveFormList`), + // so the address's answer and every address's are both read off it. + const everywhere = await readEffectiveForms(host, { type: 'form', names: [request.name] }, 'served'); const pkgOf = (item: unknown): unknown => (item as { _packageId?: unknown } | null)?._packageId; + const listed = request.packageId === undefined + ? everywhere + : everywhere.filter((item) => pkgOf(item) === request.packageId); const fromView = (item: unknown): boolean => (item as Record | null)?.[PROJECTED_FORM_SOURCE_KEY] === 'view'; const envelope = generic && typeof generic === 'object' ? generic : { type: 'form', name: request.name }; const genericItem = generic?.item; @@ -709,7 +710,7 @@ async function readEffectiveFormItem( ?? (request.packageId !== undefined ? listed.find(fromView) : undefined); if (projected !== undefined) return { ...envelope, item: projected }; if (matching !== undefined || listed.length > 0) return generic; - if (request.packageId !== undefined && (await listedAt(undefined)).some((item) => pkgOf(item) === pkgOf(genericItem))) return generic; + if (request.packageId !== undefined && everywhere.some((item) => pkgOf(item) === pkgOf(genericItem))) return generic; const { item: _item, ...rest } = envelope; return rest; } diff --git a/packages/metadata-protocol/src/protocol-meta-list-reads.ts b/packages/metadata-protocol/src/protocol-meta-list-reads.ts index 35b51582a7c..22b8789c59d 100644 --- a/packages/metadata-protocol/src/protocol-meta-list-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-list-reads.ts @@ -34,7 +34,7 @@ import { } from './protocol-authoring-refusals.js'; import { shippingPackageIds } from './protocol-environment-rows.js'; import type { ProtocolHost } from './protocol-host.js'; -import { readEffectiveForms, type FormReadHost } from './protocol-form-reads.js'; +import { readEffectiveFormList, type FormReadHost } from './protocol-form-reads.js'; import { canonicalizeMetaRequestType } from './protocol-meta-type-schema.js'; import { mergePackageAwareOverlay, servedViewExpansion, withoutServedRowName } from './protocol-overlay-merge.js'; import { @@ -60,6 +60,22 @@ import { pairMemberWithheldAt, } from './protocol-exact-qualifier.js'; +/** + * [ADR-0159 D5] The `form` list face: the items {@link readEffectiveFormList} + * resolves, in the envelope of the generic list of the same request. Unscoped, + * that is the envelope the resolution itself read; a list scoped to a package + * takes the scoped generic list's envelope, as before. + */ +async function effectiveFormList( + host: FormReadHost, + request: { type: string; packageId?: string; names?: readonly string[]; previewDrafts?: boolean }, + audience: 'served' | 'execution', +) { + const resolved = await readEffectiveFormList(host, request, audience); + if (request.packageId === undefined) return resolved; + return { ...(await host.readFlattenedMetaItems(request, audience)), items: resolved.items }; +} + /** The body of `ObjectStackProtocolImplementation#getMetaItems`; the method's docblock there is its contract. */ export async function getMetaItems(host: FormReadHost, request: { type: string; packageId?: string; names?: readonly string[]; previewDrafts?: boolean }) { // #4432 — CANONICAL TYPE KEY. See {@link canonicalMetaType}. This one @@ -73,11 +89,9 @@ export async function getMetaItems(host: FormReadHost, request: { type: string; // each face's boundary, so the shared body only ever sees the canonical // key. const canonical = canonicalizeMetaRequestType(request); - // [ADR-0159 D5] The `form` list is resolved over both types. - if (canonical.type === 'form') { - const list = await host.readFlattenedMetaItems(canonical, 'served'); - return { ...list, items: await readEffectiveForms(host, canonical, 'served') }; - } + // [ADR-0159 D5] The `form` list is resolved over both types, in one + // generic read where the list names no package (`readEffectiveFormList`). + if (canonical.type === 'form') return effectiveFormList(host, canonical, 'served'); return host.readFlattenedMetaItems(canonical, 'served'); } @@ -85,10 +99,7 @@ export async function getMetaItems(host: FormReadHost, request: { type: string; export async function getMetaItemsForExecution(host: FormReadHost, request: { type: string; packageId?: string; previewDrafts?: boolean }) { // The same #4432 fold {@link getMetaItems} applies, for the same reason. const canonical = canonicalizeMetaRequestType(request); - if (canonical.type === 'form') { - const list = await host.readFlattenedMetaItems(canonical, 'execution'); - return { ...list, items: await readEffectiveForms(host, canonical, 'execution') }; - } + if (canonical.type === 'form') return effectiveFormList(host, canonical, 'execution'); return host.readFlattenedMetaItems(canonical, 'execution'); } diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 3d1c4321de7..9a0ea42b661 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -1,6 +1,6 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. -import { packagelessListOverFormRefusal } from './protocol-form-writes.js'; +import { formTypeWriteRefusal } from './protocol-form-writes.js'; import { readUnreadableFormBodies } from './protocol-form-reads.js'; import type { UnreadableFormBody } from '@objectstack/spec/ui'; import type { @@ -1591,9 +1591,9 @@ export class ObjectStackProtocolImplementation implements return restoredBodyDerivation.call(host, type); } - /** [ADR-0159 card ② item 5] {@link packagelessListOverFormRefusal}, asked of a restored body against its binding. */ - private listOverFormRefusal(type: string, item: unknown, name: string, binding: string | null): Error | undefined { - return packagelessListOverFormRefusal(protocolHost(this), type, item, name, binding); + /** [ADR-0159 card ② items 5 and 7] {@link formTypeWriteRefusal}, asked of a restored body against its binding. */ + private formRestoreRefusal(type: string, item: unknown, name: string, binding: string | null): Promise { + return formTypeWriteRefusal(protocolHost(this), type, item, name, binding); } /** @@ -1631,7 +1631,7 @@ export class ObjectStackProtocolImplementation implements private restoredBodyWriter(type: string, name: string, binding: string | null, source: string): (historyBody: unknown) => Promise { // [#25467 cut 8] The body moved to `protocol-authoring-gate.ts` (see `AuthoringGateHost`). const host: ThisParameterType = { - listOverFormRefusal: (...a) => this.listOverFormRefusal(...a), + formRestoreRefusal: (...a) => this.formRestoreRefusal(...a), objectExtensionItemRefusal: (...a) => this.objectExtensionItemRefusal(...a), refuseRestoredBodyTheSaveDoorRefuses: (...a) => this.refuseRestoredBodyTheSaveDoorRefuses(...a), restoredBodyDerivation: (...a) => this.restoredBodyDerivation(...a), diff --git a/packages/rest/src/data-write-summary-recompute-other-doors.test.ts b/packages/rest/src/data-write-summary-recompute-other-doors.test.ts index 1fbb4c2b042..40d5cb4e8c2 100644 --- a/packages/rest/src/data-write-summary-recompute-other-doors.test.ts +++ b/packages/rest/src/data-write-summary-recompute-other-doors.test.ts @@ -47,7 +47,7 @@ import { RestServer } from './rest-server'; import { installDefaultOrganization } from './default-organization.testkit.js'; // [#10126] Pay the first transform of this dist-resolved workspace dep at module load. -import '@objectstack/spec/ui'; +import { projectedFormsOf } from '@objectstack/spec/ui'; const PARENT = 'qsf_parent'; const CHILD = 'qsf_child'; @@ -142,7 +142,7 @@ beforeAll(async () => { if (prop === 'getUnreadableFormBodies') return async () => []; if (prop === 'getMetaItems') { // The engine holds the objects; this harness registers no metadata service. - return async (req: any) => (req?.type === 'view' ? [FORM_VIEW] : req?.type === 'form' ? [] : req?.type === 'object' ? [CHILD_OBJECT, PARENT_OBJECT] : target.getMetaItems(req)); + return async (req: any) => (req?.type === 'view' ? [FORM_VIEW] : req?.type === 'form' ? projectedFormsOf([FORM_VIEW]) : req?.type === 'object' ? [CHILD_OBJECT, PARENT_OBJECT] : target.getMetaItems(req)); } const v = Reflect.get(target, prop, receiver); return typeof v === 'function' ? v.bind(target) : v; diff --git a/packages/rest/src/form-routes.ts b/packages/rest/src/form-routes.ts index 37fe93505ae..4f64d109447 100644 --- a/packages/rest/src/form-routes.ts +++ b/packages/rest/src/form-routes.ts @@ -82,7 +82,6 @@ import { formIntakeLayer, openFormAt, projectViewForms, - projectedFormsOf, thankYouRecordFieldNames, type FormIntakeLayer, type UnreadableFormBody, @@ -308,14 +307,11 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo : []); const formsRequest: TransportScopedMetaRequest = { ...viewsRequest, type: 'form' }; const views = listOf(await p.getMetaItems(viewsRequest)); - // [ADR-0159 D5] The candidates are the effective `form` read, which - // projects the old shapes itself. A protocol that serves no `form` - // item at all (one older than the type) serves its forms only as old - // shapes, and the doors read them through THE same projection; where - // the protocol serves the type, an empty `form` read is the same - // projection of the same `view` read, so nothing is added. - const servedForms = listOf(await p.getMetaItems(formsRequest)); - const forms = servedForms.length > 0 ? servedForms : projectedFormsOf(views); + // [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 + // `form` item serves no candidate. + const forms = listOf(await p.getMetaItems(formsRequest)); // [#28409] The per-package layers, where the protocol serves them: a // server-only extension, feature-detected like the other extensions // the doors read. A protocol without it serves no narrower list than diff --git a/packages/rest/src/public-form-file-field.test.ts b/packages/rest/src/public-form-file-field.test.ts index c2f457825ac..d4ce7771ec2 100644 --- a/packages/rest/src/public-form-file-field.test.ts +++ b/packages/rest/src/public-form-file-field.test.ts @@ -28,6 +28,7 @@ */ import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import { projectedFormsOf } from '@objectstack/spec/ui'; import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; @@ -112,8 +113,8 @@ describe('[#25572] POST /forms/:slug/submit: an anonymous submission carries no const protocol: any = new ObjectStackProtocolImplementation(engine as any); const realGetMetaItems = protocol.getMetaItems.bind(protocol); protocol.getMetaItems = async (request: any) => { - // [ADR-0159 D5] No `form` item is injected: the doors read the injected old shape through the projection. - if (request?.type === 'form') return []; + // [ADR-0159 D5] The `form` read, as the protocol serves it for the injected old shape: its projection. + if (request?.type === 'form') return projectedFormsOf([FORM]); if (request?.type === 'view') return [FORM]; if (request?.type === 'object') return [SUPPLIER]; return realGetMetaItems(request); diff --git a/packages/rest/src/public-form-intake-availability.test.ts b/packages/rest/src/public-form-intake-availability.test.ts index db3be38aaae..55fa54e60a0 100644 --- a/packages/rest/src/public-form-intake-availability.test.ts +++ b/packages/rest/src/public-form-intake-availability.test.ts @@ -14,7 +14,7 @@ import { RestServer } from './rest-server'; // [#10126] Pay the first transform of these dist-resolved workspace deps at // MODULE LOAD rather than inside a clocked `it()` body. -import '@objectstack/spec/ui'; +import { projectedFormsOf } from '@objectstack/spec/ui'; // …and `@objectstack/objectql`, which `rest-server.ts`'s meta-object routes reach // through a dynamic import inside a handler (`check:test-source-alias`). import '@objectstack/objectql'; @@ -73,6 +73,8 @@ function build(setup: Setup) { const createData = vi.fn().mockResolvedValue({ object: 'inquiry', id: 'rec_1', record: {} }); const getMetaItems = vi.fn(async (req: { type: string }) => { if (req.type === 'view') return [formView(setup.allowAnonymous ?? true)]; + // [ADR-0159 D5] The `form` read, as the protocol serves it for an old-shape-only fixture: the projection of the views. + if (req.type === 'form') return projectedFormsOf([formView(setup.allowAnonymous ?? true)]); if (req.type === 'object') return [inquiryObject(setup.tenancyDisabled ?? false)]; return []; }); diff --git a/packages/rest/src/public-form-option-subset.test.ts b/packages/rest/src/public-form-option-subset.test.ts index d9fd6a9cd7e..5a9aa476045 100644 --- a/packages/rest/src/public-form-option-subset.test.ts +++ b/packages/rest/src/public-form-option-subset.test.ts @@ -31,6 +31,7 @@ */ import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import { projectedFormsOf } from '@objectstack/spec/ui'; import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; @@ -171,8 +172,8 @@ describe('[#27606] POST /forms/:slug/submit: a form row\'s `options` subset is e const protocol: any = new ObjectStackProtocolImplementation(engine as any); const realGetMetaItems = protocol.getMetaItems.bind(protocol); protocol.getMetaItems = async (request: any) => { - // [ADR-0159 D5] No `form` item is injected: the doors read the injected old shape through the projection. - if (request?.type === 'form') return []; + // [ADR-0159 D5] The `form` read, as the protocol serves it for the injected old shape: its projection. + if (request?.type === 'form') return projectedFormsOf([FORM, WIDE_FORM, LOOSE_FORM]); if (request?.type === 'view') return [FORM, WIDE_FORM, LOOSE_FORM]; if (request?.type === 'object') return [CASE]; return realGetMetaItems(request); diff --git a/packages/rest/src/public-form-required.test.ts b/packages/rest/src/public-form-required.test.ts index 7ba06ad5192..a217af3aff0 100644 --- a/packages/rest/src/public-form-required.test.ts +++ b/packages/rest/src/public-form-required.test.ts @@ -30,6 +30,7 @@ */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { projectedFormsOf } from '@objectstack/spec/ui'; import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; @@ -134,8 +135,8 @@ describe('[#24131] POST /forms/:slug/submit enforces the form\'s own `required`' const protocol: any = new ObjectStackProtocolImplementation(engine as any); const realGetMetaItems = protocol.getMetaItems.bind(protocol); protocol.getMetaItems = async (request: any) => { - // [ADR-0159 D5] No `form` item is injected: the doors read the injected old shape through the projection. - if (request?.type === 'form') return []; + // [ADR-0159 D5] The `form` read, as the protocol serves it for the injected old shape: its projection. + if (request?.type === 'form') return projectedFormsOf([FORM]); if (request?.type === 'view') return [FORM]; if (request?.type === 'object') return [LEAD]; return realGetMetaItems(request); diff --git a/packages/rest/src/public-form-routes.stored-row.test.ts b/packages/rest/src/public-form-routes.stored-row.test.ts index 8e3694c795e..81b66e3dba8 100644 --- a/packages/rest/src/public-form-routes.stored-row.test.ts +++ b/packages/rest/src/public-form-routes.stored-row.test.ts @@ -64,6 +64,7 @@ import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protoco // it reports TS7006 — one broken extension reading as two type errors in this // package's TEST_DEBT re-measure. import { RestServer } from './rest-server.js'; +import { projectedFormsOf } from '@objectstack/spec/ui'; // ─── the real save path ────────────────────────────────────────────────────── @@ -172,6 +173,7 @@ function routesOver(storedView: any) { getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '' } }), getMetaTypes: vi.fn().mockResolvedValue([]), getMetaItems: vi.fn(async ({ type }: { type: string }) => { + if (type === 'form') return projectedFormsOf([storedView]); if (type === 'view') return [storedView]; if (type === 'object') return [leadObject]; return []; diff --git a/packages/rest/src/public-form-routes.test.ts b/packages/rest/src/public-form-routes.test.ts index ce781877cac..cd1b8d73026 100644 --- a/packages/rest/src/public-form-routes.test.ts +++ b/packages/rest/src/public-form-routes.test.ts @@ -22,7 +22,7 @@ import { RestServer } from './rest-server'; // hook -- both of which vitest clocks, while collection is clocked against nothing. See // `scripts/check-test-source-alias.mjs` (the clocked-window rule) and #10115 / PR #10120, // where the same shape cost 30 ejected merge-queue builds in one night. -import '@objectstack/spec/ui'; +import { projectedFormsOf } from '@objectstack/spec/ui'; function mockServer() { return { @@ -93,6 +93,7 @@ function buildServer(sections: any[] | undefined, object: any = ticketObject) { getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '' } }), getMetaTypes: vi.fn().mockResolvedValue([]), getMetaItems: vi.fn(async ({ type }: { type: string }) => { + if (type === 'form') return projectedFormsOf([formView(sections)]); if (type === 'view') return [formView(sections)]; if (type === 'object') return [object]; return []; @@ -473,6 +474,7 @@ describe('[#21180] GET /forms/:slug/lookup/:field is gone — it answers what an getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '' } }), getMetaTypes: vi.fn().mockResolvedValue([]), getMetaItems: vi.fn(async ({ type }: { type: string }) => { + if (type === 'form') return projectedFormsOf([formView([{ fields: ['subject', 'owner_id'] }])]); if (type === 'view') return [formView([{ fields: ['subject', 'owner_id'] }])]; if (type === 'object') return [ticketObject]; return []; diff --git a/packages/rest/src/public-form-section-i18n.test.ts b/packages/rest/src/public-form-section-i18n.test.ts index c55a496cb19..56ded0e343f 100644 --- a/packages/rest/src/public-form-section-i18n.test.ts +++ b/packages/rest/src/public-form-section-i18n.test.ts @@ -28,7 +28,7 @@ import { describe, it, expect, vi } from 'vitest'; import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; import { SchemaRegistry } from '@objectstack/objectql'; -import { expandViewContainer } from '@objectstack/spec/ui'; +import { expandViewContainer, projectedFormsOf } from '@objectstack/spec/ui'; import { RestServer } from './rest-server'; // [#10126] Pay the first transform of the dist-resolved workspace dep the @@ -153,6 +153,7 @@ function buildServer(view: Record, packagedView?: Record { + if (type === 'form') return projectedFormsOf([view]); if (type === 'view') return [view]; if (type === 'object') return [ticketObject]; return []; @@ -412,6 +413,7 @@ describe('[#33952] GET /forms/:slug — a field label a code package\'s fieldPat getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '' } }), getMetaTypes: vi.fn().mockResolvedValue([]), getMetaItems: vi.fn(async ({ type }: { type: string }) => { + if (type === 'form') return projectedFormsOf([formView()]); if (type === 'view') return [formView()]; if (type === 'object') return [patchedTicket]; return []; diff --git a/packages/rest/src/public-form-submit-answer.test.ts b/packages/rest/src/public-form-submit-answer.test.ts index 4d28a52d19a..729af0b48f7 100644 --- a/packages/rest/src/public-form-submit-answer.test.ts +++ b/packages/rest/src/public-form-submit-answer.test.ts @@ -33,7 +33,7 @@ import { REST_ROUTE_LEDGER } from './rest-route-ledger'; // [#10126] Pay the first transform of this dist-resolved workspace dep at MODULE // LOAD, as `public-form-routes.test.ts` does for the same routes. -import '@objectstack/spec/ui'; +import { projectedFormsOf } from '@objectstack/spec/ui'; const CREATED_ID = 'rec_answer_1'; /** Synthetic values the stored row carries. None may reach the anonymous caller. */ @@ -88,6 +88,7 @@ function protocolDouble() { getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '' } }), getMetaTypes: vi.fn().mockResolvedValue([]), getMetaItems: vi.fn(async ({ type }: { type: string }) => { + if (type === 'form') return projectedFormsOf([formView()]); if (type === 'view') return [formView()]; if (type === 'object') return [requestObject]; return []; @@ -198,6 +199,7 @@ function tokenProtocol(opts: { getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '' } }), getMetaTypes: vi.fn().mockResolvedValue([]), getMetaItems: vi.fn(async ({ type }: { type: string }) => { + if (type === 'form') return projectedFormsOf([view]); if (type === 'view') return [view]; if (type === 'object') return [object]; return []; diff --git a/packages/rest/src/public-form-title-i18n.test.ts b/packages/rest/src/public-form-title-i18n.test.ts index 462be014dab..6e30c8ea0b1 100644 --- a/packages/rest/src/public-form-title-i18n.test.ts +++ b/packages/rest/src/public-form-title-i18n.test.ts @@ -24,7 +24,7 @@ import { describe, it, expect, vi } from 'vitest'; import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; import { SchemaRegistry } from '@objectstack/objectql'; -import { expandViewContainer } from '@objectstack/spec/ui'; +import { expandViewContainer, projectedFormsOf } from '@objectstack/spec/ui'; import { RestServer } from './rest-server'; // [#10126] Pay the first transform of the dist-resolved workspace dep the @@ -160,6 +160,7 @@ function overDouble(view: Record) { getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '' } }), getMetaTypes: vi.fn().mockResolvedValue([]), getMetaItems: vi.fn(async ({ type }: { type: string }) => { + if (type === 'form') return projectedFormsOf([view]); if (type === 'view') return [view]; if (type === 'object') return [ticketObject]; return []; diff --git a/packages/rest/src/public-form-withdrawal.test.ts b/packages/rest/src/public-form-withdrawal.test.ts index 352c9097d59..aa605e2a405 100644 --- a/packages/rest/src/public-form-withdrawal.test.ts +++ b/packages/rest/src/public-form-withdrawal.test.ts @@ -31,7 +31,7 @@ import { RestServer } from './rest-server'; // [#10126] Pay the first transform of these dist-resolved workspace deps at // MODULE LOAD rather than inside a clocked `it()` body. -import '@objectstack/spec/ui'; +import { projectedFormsOf } from '@objectstack/spec/ui'; const ORG = 'org_alpha'; @@ -98,10 +98,10 @@ interface Setup { function build(setup: Setup) { const createData = vi.fn().mockResolvedValue({ object: 'inquiry', id: 'rec_1', record: {} }); const getMetaItems = vi.fn(async (req: Record & { type: string }) => { - if (req.type === 'view') { - if (setup.envWideViews) return setup.envWideViews; - return [formView(setup.envWide, setup.sharing), ...(setup.extraViews ?? [])]; - } + const views = () => setup.envWideViews ?? [formView(setup.envWide, setup.sharing), ...(setup.extraViews ?? [])]; + if (req.type === 'view') return views(); + // [ADR-0159 D5] The `form` read, as the protocol serves it for an old-shape-only fixture: the projection of the views. + if (req.type === 'form') return projectedFormsOf(views()); if (req.type === 'object') return [inquiryObject]; return []; }); diff --git a/packages/rest/src/rest-write-route-hook-refusal-sentence.ledger.test.ts b/packages/rest/src/rest-write-route-hook-refusal-sentence.ledger.test.ts index a254b724e84..a0a75e2fddb 100644 --- a/packages/rest/src/rest-write-route-hook-refusal-sentence.ledger.test.ts +++ b/packages/rest/src/rest-write-route-hook-refusal-sentence.ledger.test.ts @@ -66,6 +66,7 @@ import { REST_ROUTE_LEDGER } from './rest-route-ledger.js'; import { sandboxFaultAnswer } from './error-response.js'; import { isSandboxOwnFault } from '@objectstack/types'; import { assertEngineUpdateDispatch } from '@objectstack/metadata-core'; +import { projectedFormsOf } from '@objectstack/spec/ui'; const SENTENCE = 'Locked rows cannot be changed here.'; const WRAPPER = `hook 'mz_guard' threw: Error: ${SENTENCE}`; @@ -130,7 +131,7 @@ const READS: Record = { getDiscovery: async () => ({ version: 'v0', routes: {} }), getMetaTypes: async () => [], // [ADR-0159 D5] No `form` item: the form door reads FORM_VIEW through the projection. - getMetaItems: async (req: { type?: string }) => (req?.type === 'view' ? [FORM_VIEW] : req?.type === 'form' ? [] : [SCHEMA]), + getMetaItems: async (req: { type?: string }) => (req?.type === 'view' ? [FORM_VIEW] : req?.type === 'form' ? projectedFormsOf([FORM_VIEW]) : [SCHEMA]), // [#28409] The form doors' withdrawal layer beside the effective list. getMetaItemsPerPackage: async (req: { type?: string }) => (req?.type === 'view' ? [FORM_VIEW] : []), // [ADR-0159 D6 rule 7] No stored body the projection cannot read. From e934757eca4965848537aecd5f60b4b9236073c1 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:08:31 +0000 Subject: [PATCH 14/29] test(rest): pin the form half of the layer, served rows, the closed reading, the bound and the form write doors Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .../public-form-two-type-withdrawal.test.ts | 341 ++++++++++++++++++ 1 file changed, 341 insertions(+) diff --git a/packages/rest/src/public-form-two-type-withdrawal.test.ts b/packages/rest/src/public-form-two-type-withdrawal.test.ts index 9592f06cb08..22f5123718b 100644 --- a/packages/rest/src/public-form-two-type-withdrawal.test.ts +++ b/packages/rest/src/public-form-two-type-withdrawal.test.ts @@ -468,3 +468,344 @@ describe('[ADR-0159 D7-b, measure first] does a write door admit a declared over await closedOnBothDoors(b); }); }); + +/** The pair's (or `packageId`'s) ACTIVE stored rows of `type` at `name`, as the store holds them: metadata bytes and checksum. */ +async function rawRows(b: Booted, type: string, name: string, packageId: string | null) { + const rows = (await b.engine.find('sys_metadata', { where: { type, name, state: 'active' } }, { context: { isSystem: true } })) as any[]; + return rows + .filter((r) => (r.package_id ?? null) === packageId) + .map((r) => ({ metadata: typeof r.metadata === 'string' ? r.metadata : JSON.stringify(r.metadata), checksum: r.checksum })); +} + +/** The newest version the history holds for `(type, name)` at `packageId`. */ +async function newestVersion(b: Booted, type: string, name: string): Promise { + const history: any = await b.protocol.historyMetaItem({ type, name }); + return Math.max(...(history.events as any[]).map((e) => Number(e.version)).filter((v) => Number.isFinite(v))); +} + +const LIST = { name: NAME, object: OBJECT, viewKind: 'list', label: 'A list', config: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } } }; +/** A container on {@link OBJECT} whose bare `list` expands to `.`. */ +const listContainer = (name: string) => ({ name, object: OBJECT, list: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } } }); + +describe('[ADR-0159 D6, D5] the `form` half of the layer, served rows only, and the closed reading', () => { + const engines: ObjectQL[] = []; + afterAll(async () => { + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + const booted = async (ships: { forms?: unknown[]; views?: unknown[] }): Promise => { + const b = await boot(ships); + engines.push(b.engine); + return b; + }; + const servedAt = async (b: Booted) => ((await b.protocol.getMetaItems({ type: 'form' })).items as any[]) + .filter((f) => f?.name === NAME) + .map((f) => [f._packageId ?? null, f.sharing?.allowAnonymous ?? null]); + + it('pin 2b — the `form` half alone: the base authors the form switched off with its link kept, and a dependent\'s old-shape row of the name stands open on that link (ablate: the `form` half of the layer)', async () => { + const b = await booted({ forms: [formItem(false)] }); + await b.install(DEPENDENT); + await b.saveBeforeTheGate('view', DEPENDENT, viewItem(true)); + // The premise: the open old shape is a candidate, and the only body that + // withdraws the name is the base's `form` item: no `view` body does. + expect(await servedAt(b)).toEqual(expect.arrayContaining([[BASE, false], [DEPENDENT, true]])); + const views = ((await b.protocol.getMetaItems({ type: 'view' })).items as any[]).filter((v) => v?.name === NAME); + expect(views.map((v) => v.config?.sharing?.allowAnonymous)).toEqual([true]); + await closedOnBothDoors(b); + }); + + it('pin 2b, twin — a package-less old-shape row open over the base\'s switched-off `form` item: the base\'s own document still withdraws it', async () => { + const b = await booted({ forms: [formItem(false)] }); + await b.seedRow('view', NAME, null, viewItem(true)); + await closedOnBothDoors(b); + }); + + it('served rows only — a writable package\'s own list beside a package-less open old shape of the name: 404 before and after (ablate: project every stored `view` row)', async () => { + const b = await booted({}); + await b.install(DEPENDENT); + await b.saveInto('view', DEPENDENT, LIST); + await b.seedRow('view', NAME, null, viewItem(true)); + await closedOnBothDoors(b); + }); + + it('served rows only, at the address — a read-only package\'s open `form` item under a package-less row whose form has no link: 404 before and after a list of the name is saved beside it (ablate: take the served rows from the effective `view` list)', async () => { + const b = await booted({ forms: [formItem(true)] }); + await b.seedRow('view', NAME, null, viewItem(null)); + await closedOnBothDoors(b); + await b.install(DEPENDENT); + await b.saveInto('view', DEPENDENT, LIST); + await b.install(PAIR); + await b.saveInto('view', PAIR, LIST); + await closedOnBothDoors(b); + }); + + it('the closed reading — a stored package-less list at the name keeps both doors at 404 at the package\'s address (ablate: fall through to the package\'s source `form` item)', async () => { + const b = await booted({ forms: [formItem(true)] }); + await openOnBothDoors(b); + await b.seedRow('view', NAME, null, LIST); + await closedOnBothDoors(b); + }); + + it('the closed reading — so does a stored package-less container whose expansion writes a list at the name', async () => { + const ALL = `${OBJECT}.all`; + const b = await booted({ forms: [{ ...formItem(true), name: ALL }] }); + await openOnBothDoors(b); + await b.seedRow('view', 'all', null, listContainer('all')); + await closedOnBothDoors(b); + }); +}); + +describe('[ADR-0159 D5, card ② item 5] the bound: a package-less list at the form\'s name is refused, the saves beside it are admitted', () => { + const engines: ObjectQL[] = []; + afterAll(async () => { + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + const booted = async (ships: { forms?: unknown[]; views?: unknown[] }): Promise => { + const b = await boot(ships); + engines.push(b.engine); + return b; + }; + const ALL = `${OBJECT}.all`; + const refused = async (p: Promise) => { + const err: any = await p.then(() => undefined, (e: any) => e); + expect(err, 'refused').toBeDefined(); + expect([err.status, err.code]).toEqual([400, 'VALIDATION_ERROR']); + }; + + it('refused where the base\'s pair cannot be ensured too; the list saved into an app of the environment\'s own and into the pair as its own item saves; after all of them the doors serve the package\'s form (ablate: the bound; the expansion half)', async () => { + const b = await booted({ forms: [formItem(true), { ...formItem(true, {}, OTHER_SLUG), name: ALL }] }); + await refused(b.protocol.saveMetaItem({ type: 'view', name: NAME, mode: 'draft', item: LIST })); + await refused(b.protocol.saveMetaItem({ type: 'view', name: 'all', mode: 'draft', item: listContainer('all') })); + // Another package holds the namespace the pair would take: the ensure door refuses to form it. + await b.protocol.installPackage({ manifest: { id: 'com.default.squatter37086', name: 'squatter', version: '0.1.0', type: 'app', namespace: 'ftt_custom' } }); + const ensured = await b.protocol.ensureCustomizationPackage({ basePackageId: BASE }).then(() => 'ensured', (e: any) => e.status); + expect(ensured).not.toBe('ensured'); + await refused(b.protocol.saveMetaItem({ type: 'view', name: NAME, mode: 'draft', item: LIST })); + await refused(b.protocol.saveMetaItem({ type: 'view', name: 'all', mode: 'draft', item: listContainer('all') })); + expect(await rawRows(b, 'view', NAME, null)).toEqual([]); + expect(await rawRows(b, 'view', 'all', null)).toEqual([]); + await openOnBothDoors(b); + await openOnBothDoors(b, OTHER_SLUG); + }); + + it('…and with the pair ensurable: the list into an app of the environment\'s own and into the pair as its own item saves, and the doors still serve the package\'s form', async () => { + const b = await booted({ forms: [formItem(true)] }); + await b.install(DEPENDENT); + await expect(b.saveInto('view', DEPENDENT, LIST)).resolves.toBeUndefined(); + await b.install(PAIR); + await expect(b.saveInto('view', PAIR, LIST)).resolves.toBeUndefined(); + await refused(b.protocol.saveMetaItem({ type: 'view', name: NAME, mode: 'draft', item: LIST })); + await openOnBothDoors(b); + }); +}); + +describe('[ADR-0159 D5, D6 rule 9, card ② items 2, 5 and 7] the `form` write doors', () => { + const engines: ObjectQL[] = []; + afterAll(async () => { + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + const booted = async (ships: { forms?: unknown[]; views?: unknown[] }): Promise => { + const b = await boot(ships); + engines.push(b.engine); + return b; + }; + const SECOND = `${OBJECT}.second`; + const THIRD = `${OBJECT}.third`; + const failure = (p: Promise) => p.then(() => undefined, (e: any) => e); + + it('rule 9 — an organization-scoped `form` save is refused as the same `view` save is, the withdrawal held in the other type, and nothing is written', async () => { + // A form withdrawn in `form`, an organization-scoped `view` save that would leave it open… + const a = await booted({ forms: [formItem(false)] }); + const viewErr = await failure(a.protocol.saveMetaItem({ type: 'view', name: NAME, mode: 'draft', item: viewItem(true), organizationId: 'org_a' } as any)); + expect([viewErr?.status, viewErr?.code]).toEqual([403, 'NOT_OVERRIDABLE']); + // …and the mirror: withdrawn in an old shape, an organization-scoped `form` save. + const b = await booted({ views: [container(false)] }); + const formErr = await failure(b.protocol.saveMetaItem({ type: 'form', name: NAME, mode: 'draft', item: formItem(true), organizationId: 'org_a' } as any)); + expect([formErr?.status, formErr?.code]).toEqual([403, 'NOT_OVERRIDABLE']); + expect(await rawRows(a, 'view', NAME, null)).toEqual([]); + expect((await b.engine.find('sys_metadata', { where: { type: 'form' } }, { context: { isSystem: true } }) as any[]).length).toBe(0); + await closedOnBothDoors(a); + await closedOnBothDoors(b); + }); + + it('a `form` override of a name the base ships in neither type is refused `declared_package_ships_no_such_item` (ablate: the projection half of the gate\'s "ships" read; the CONTROL below is then refused)', async () => { + const b = await booted({ views: [container(true)] }); + await b.install(PAIR); + const verdicts: any[] = []; + const real = b.protocol.overrideWriteVerdict.bind(b.protocol); + b.protocol.overrideWriteVerdict = (...a: any[]) => { const v = real(...a); verdicts.push(v); return v; }; + const NOWHERE = `${OBJECT}.nowhere`; + const err = await failure(b.protocol.saveMetaItem({ type: 'form', name: NOWHERE, packageId: PAIR, mode: 'draft', item: { ...formItem(null, overrides), name: NOWHERE } })); + expect([err?.status, err?.code]).toEqual([403, 'NOT_OVERRIDABLE']); + expect(verdicts.map((v) => v.rule)).toContain('declared_package_ships_no_such_item'); + // CONTROL: the same override of the name the base ships as an old shape is admitted. + verdicts.length = 0; + await expect(b.saveInto('form', PAIR, formItem(false, overrides))).resolves.toBeUndefined(); + expect(verdicts.map((v) => v.verdict)).toContain('admit'); + await closedOnBothDoors(b); + }); + + it('an old-shape `view` write on a taken slug still saves as before', async () => { + const b = await booted({ forms: [formItem(true)] }); + await b.install(DEPENDENT); + await expect(b.saveInto('view', DEPENDENT, viewItem(true, { name: SECOND }, SLUG), SECOND)).resolves.toBeUndefined(); + expect((await rawRows(b, 'view', SECOND, DEPENDENT)).length).toBe(1); + }); + + it('publish — a `form` draft left open on an address another form took after the draft was saved is refused 409 FORM_ADDRESS_TAKEN, naming both forms, and nothing is promoted', async () => { + const b = await booted({}); + await b.install(PAIR); + await b.protocol.saveMetaItem({ type: 'form', name: SECOND, packageId: PAIR, mode: 'draft', item: { ...formItem(true), name: SECOND } }); + await b.saveInto('form', PAIR, { ...formItem(true), name: THIRD }, THIRD); + const err = await failure(b.protocol.publishMetaItem({ type: 'form', name: SECOND, packageId: PAIR })); + expect([err?.status, err?.code]).toEqual([409, 'FORM_ADDRESS_TAKEN']); + expect(String(err.message)).toContain(SECOND); + expect(String(err.message)).toContain(THIRD); + expect(await rawRows(b, 'form', SECOND, PAIR)).toEqual([]); + }); + + it('publish CONTROL — the same draft, its address free, is promoted', async () => { + const b = await booted({}); + await b.install(PAIR); + await b.protocol.saveMetaItem({ type: 'form', name: SECOND, packageId: PAIR, mode: 'draft', item: { ...formItem(true), name: SECOND } }); + await expect(b.protocol.publishMetaItem({ type: 'form', name: SECOND, packageId: PAIR })).resolves.toBeDefined(); + expect((await rawRows(b, 'form', SECOND, PAIR)).length).toBe(1); + await openOnBothDoors(b); + }); + + it('restore — a rollback to a version open on an address another form holds now is refused 409 FORM_ADDRESS_TAKEN, and the row stays as it is; CONTROL: the address free, it is restored', async () => { + const run = async (holderTakesIt: boolean) => { + const b = await booted({}); + await b.install(PAIR); + await b.saveInto('form', PAIR, { ...formItem(true), name: SECOND }, SECOND); + const openVersion = await newestVersion(b, 'form', SECOND); + await b.saveInto('form', PAIR, { ...formItem(null), name: SECOND }, SECOND); + if (holderTakesIt) await b.saveInto('form', PAIR, { ...formItem(true), name: THIRD }, THIRD); + const before = await rawRows(b, 'form', SECOND, PAIR); + const outcome = await b.protocol.rollbackMetaItem({ type: 'form', name: SECOND, toVersion: openVersion }) + .then(() => 'restored', (e: any) => e); + return { b, outcome, before }; + }; + const taken = await run(true); + expect([taken.outcome?.status, taken.outcome?.code]).toEqual([409, 'FORM_ADDRESS_TAKEN']); + expect(String(taken.outcome.message)).toContain(THIRD); + expect(await rawRows(taken.b, 'form', SECOND, PAIR)).toEqual(taken.before); + const free = await run(false); + expect(free.outcome).toBe('restored'); + await openOnBothDoors(free.b); + }); +}); + +describe('[ADR-0159 D5] a `form` save, reset and delete: the old-shape row of the address goes in the same transaction, a list of the name stays byte-equal', () => { + const engines: ObjectQL[] = []; + afterAll(async () => { + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + const booted = async (ships: { forms?: unknown[]; views?: unknown[] }): Promise => { + const b = await boot(ships); + engines.push(b.engine); + return b; + }; + const failure = (p: Promise) => p.then(() => undefined, (e: any) => e); + + it('a list row of the name stays byte-equal across the `form` draft save, its publish and its reset (ablate: the form-content test of the old-shape row removal)', async () => { + const b = await booted({ forms: [formItem(true)] }); + await b.install(PAIR); + await b.saveInto('view', PAIR, LIST); + const list = await rawRows(b, 'view', NAME, PAIR); + expect(list.length).toBe(1); + await b.protocol.saveMetaItem({ type: 'form', name: NAME, packageId: PAIR, mode: 'draft', item: formItem(false, overrides) }); + expect(await rawRows(b, 'view', NAME, PAIR)).toEqual(list); + await b.protocol.publishMetaItem({ type: 'form', name: NAME, packageId: PAIR }); + expect(await rawRows(b, 'view', NAME, PAIR)).toEqual(list); + const reset: any = await b.protocol.deleteMetaItem({ type: 'form', name: NAME, packageId: PAIR }); + expect(reset.success).toBe(true); + expect(await rawRows(b, 'form', NAME, PAIR)).toEqual([]); + expect(await rawRows(b, 'view', NAME, PAIR)).toEqual(list); + }); + + it('…and across the `form` delete of an override whose base ships the form as an old shape', async () => { + const b = await booted({ views: [container(true)] }); + await b.install(PAIR); + await b.saveBeforeTheGate('view', PAIR, LIST); + const list = await rawRows(b, 'view', NAME, PAIR); + await b.saveInto('form', PAIR, formItem(false, overrides)); + expect(await rawRows(b, 'view', NAME, PAIR)).toEqual(list); + await b.protocol.deleteMetaItem({ type: 'form', name: NAME, packageId: PAIR }); + expect(await rawRows(b, 'form', NAME, PAIR)).toEqual([]); + expect(await rawRows(b, 'view', NAME, PAIR)).toEqual(list); + }); + + it('a `form` reset at the pair removes the pair\'s old-shape row of the name', async () => { + const b = await booted({ forms: [formItem(true)] }); + await b.install(PAIR); + await b.saveInto('form', PAIR, formItem(false, overrides)); + await b.saveBeforeTheGate('view', PAIR, viewItem(false, overrides)); + expect((await rawRows(b, 'view', NAME, PAIR)).length).toBe(1); + await b.protocol.deleteMetaItem({ type: 'form', name: NAME, packageId: PAIR }); + expect(await rawRows(b, 'form', NAME, PAIR)).toEqual([]); + expect(await rawRows(b, 'view', NAME, PAIR)).toEqual([]); + await openOnBothDoors(b); + }); + + it('a `form` delete at the pair removes the pair\'s old-shape row of the name', async () => { + const b = await booted({ views: [container(true)] }); + await b.install(PAIR); + await b.saveInto('form', PAIR, formItem(false, overrides)); + await b.saveInto('view', PAIR, viewItem(false, overrides)); + expect((await rawRows(b, 'view', NAME, PAIR)).length).toBe(1); + await b.protocol.deleteMetaItem({ type: 'form', name: NAME, packageId: PAIR }); + expect(await rawRows(b, 'form', NAME, PAIR)).toEqual([]); + expect(await rawRows(b, 'view', NAME, PAIR)).toEqual([]); + await openOnBothDoors(b); + }); + + it('a stored container is re-saved without the member, its lists byte-equal', async () => { + const b = await booted({ forms: [formItem(true)] }); + await b.install(PAIR); + const stored = { name: 'intake', object: OBJECT, list: { type: 'grid', columns: ['name', 'email'], data: { provider: 'object', object: OBJECT } }, formViews: { contact: { ...body(false), data: { provider: 'object', object: OBJECT } } } }; + await b.saveBeforeTheGate('view', PAIR, stored, 'intake'); + const [before] = await rawRows(b, 'view', 'intake', PAIR); + expect(JSON.parse(before.metadata).formViews?.contact).toBeDefined(); + await b.saveInto('form', PAIR, formItem(false, overrides)); + const [after] = await rawRows(b, 'view', 'intake', PAIR); + expect(after).toBeDefined(); + const was = JSON.parse(before.metadata); + const now = JSON.parse(after.metadata); + expect(now.formViews).toBeUndefined(); + expect(JSON.stringify(now.list)).toBe(JSON.stringify(was.list)); + }); + + it('a `form` write that fails leaves both rows as they were', async () => { + const b = await booted({ views: [container(true)] }); + await b.install(PAIR); + await b.saveInto('view', PAIR, viewItem(true, overrides)); + const view = await rawRows(b, 'view', NAME, PAIR); + await b.protocol.saveMetaItem({ type: 'form', name: NAME, packageId: PAIR, mode: 'draft', item: formItem(false, overrides) }); + // The old-shape row's removal, the second write of the transaction, fails. + const realRepo = b.protocol.getOverlayRepo.bind(b.protocol); + b.protocol.getOverlayRepo = (...a: any[]) => { + const repo = realRepo(...a); + return new Proxy(repo, { + get(target, prop, receiver) { + if (prop === 'delete') { + return async (ref: any, ...rest: any[]) => { + if (ref?.type === 'view') throw new Error('the old-shape removal failed'); + return target.delete(ref, ...rest); + }; + } + const value = Reflect.get(target, prop, receiver); + return typeof value === 'function' ? value.bind(target) : value; + }, + }); + }; + let err: any; + try { + err = await failure(b.protocol.publishMetaItem({ type: 'form', name: NAME, packageId: PAIR })); + } finally { + b.protocol.getOverlayRepo = realRepo; + } + expect(String(err?.message)).toContain('the old-shape removal failed'); + expect(await rawRows(b, 'form', NAME, PAIR)).toEqual([]); + expect(await rawRows(b, 'view', NAME, PAIR)).toEqual(view); + }); +}); From db4d24e16b8436c1f042926a7e6bd15850616fab Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:13:27 +0000 Subject: [PATCH 15/29] fix(rest,metadata-protocol): the form read gate on the cached plain read, and a form override's own text over its base's catalog The cached plain read of GET /meta/:type/:name judges a form through the per-caller read gate, as it judges a view, so a caller refused a form's document at /meta/view/NAME is refused it at /meta/form/NAME. A form gets a packaged-base accessor (getPackagedFormBase: the base's authored form, else the form its old shape carries through the projection), so an override's changed text outranks the base's catalog on /meta/form and on the public door (ADR-0029 D9.2a). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .../src/protocol-discovery-and-bases.ts | 19 +++- packages/metadata-protocol/src/protocol.ts | 5 + ...hboard-view-i18n-explicit-override.test.ts | 5 +- packages/rest/src/meta-item-read-gate.ts | 3 + packages/rest/src/meta-item-read-routes.ts | 11 ++- .../public-form-two-type-withdrawal.test.ts | 95 ++++++++++++++++++- 6 files changed, 127 insertions(+), 11 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-discovery-and-bases.ts b/packages/metadata-protocol/src/protocol-discovery-and-bases.ts index 8fdb2e46311..a7c7c574312 100644 --- a/packages/metadata-protocol/src/protocol-discovery-and-bases.ts +++ b/packages/metadata-protocol/src/protocol-discovery-and-bases.ts @@ -76,6 +76,7 @@ import type { ApiRoutes, CapabilityDescriptor, ServiceInfo, WellKnownCapabilitie // `DiscoverySchema` "System Identity" field — never a literal again. import { resolveDiscoveryVersion } from './discovery-version.js'; import { CORE_SERVICE_PROVIDER, serviceUnavailableMessage } from '@objectstack/spec/system'; +import { projectViewForms } from '@objectstack/spec/ui'; import { SERVICE_CONFIG } from './protocol-discovery-services.js'; import type { ProtocolHost } from './protocol-host.js'; import { servedOverrideBaseOf } from './served-override.js'; @@ -86,7 +87,7 @@ import type { ObjectStackProtocolImplementation } from './protocol.js'; * answers: the artifact item IS the packaged declaration for each (none has an * extension fold, unlike the object). */ -export type PackagedArtifactBaseType = 'dashboard' | 'view' | 'report' | 'page' | 'dataset' | 'app' | 'book' | 'mapping'; +export type PackagedArtifactBaseType = 'dashboard' | 'view' | 'report' | 'page' | 'dataset' | 'app' | 'book' | 'mapping' | 'form'; export class ProtocolDiscoveryAndBasesFacet { /** The body of `ObjectStackProtocolImplementation#getProjectId`; the method's docblock there is its contract. */ @@ -932,6 +933,22 @@ export class ProtocolDiscoveryAndBasesFacet { return host.packagedArtifactBase('mapping', name); } + /** + * The body of `ObjectStackProtocolImplementation#getPackagedFormBase`; the + * method's docblock there is its contract. [ADR-0159 D5, ADR-0029 D9.2a] + * The base's authored `form` item, else the form its old shape carries at + * the name, read through THE projection: until card ④ a `form` override's + * base still ships most first-party forms as an old shape, and the text the + * override changed outranks that base's catalog either way. + */ + static getPackagedFormBase(host: Pick, name: string): unknown { + const authored = host.packagedArtifactBase('form', name); + if (authored !== undefined && authored !== null) return authored; + const view = host.packagedArtifactBase('view', name); + if (view === undefined || view === null) return undefined; + return projectViewForms(view).forms.find((form) => form.name === name); + } + /** The body of `ObjectStackProtocolImplementation#servedOverrideBaseOf`; the method's docblock there is its contract. */ static servedOverrideBaseOf(type: string, document: unknown): string | undefined { return servedOverrideBaseOf(type, document); diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 9a0ea42b661..0b2b200c63f 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -3055,6 +3055,11 @@ export class ObjectStackProtocolImplementation implements return ProtocolDiscoveryAndBasesFacet.getPackagedMappingBase(protocolHost(this), name); } + /** Contract: the shared docblock on {@link getPackagedPageBase}; [ADR-0159 D5] an old-shape base's form is its projection. */ + getPackagedFormBase(name: string): unknown { + return ProtocolDiscoveryAndBasesFacet.getPackagedFormBase(protocolHost(this), name); + } + /** * [#30062, ADR-0146 D2] The base package a SERVED metadata document is the * declared override of, or `undefined` when it is none — read off the diff --git a/packages/rest/src/meta-dashboard-view-i18n-explicit-override.test.ts b/packages/rest/src/meta-dashboard-view-i18n-explicit-override.test.ts index f1d1282e04b..53b4c11d672 100644 --- a/packages/rest/src/meta-dashboard-view-i18n-explicit-override.test.ts +++ b/packages/rest/src/meta-dashboard-view-i18n-explicit-override.test.ts @@ -302,6 +302,8 @@ describe('#20730 §1 packagedObjectBaseOf — one per-type packaged-base resolve getPackagedBookBase: vi.fn((name: string) => ({ kind: 'book', name })), // An import mapping is an ADR-0146 D2 listed overridable type as well. getPackagedMappingBase: vi.fn((name: string) => ({ kind: 'mapping', name })), + // [ADR-0159] A `form` override replaces its base's form (an authored item or an old shape's projection). + getPackagedFormBase: vi.fn((name: string) => ({ kind: 'form', name })), }); it('asks each type its own accessor, handing the served name through unchanged', () => { @@ -322,7 +324,8 @@ describe('#20730 §1 packagedObjectBaseOf — one per-type packaged-base resolve expect(packagedObjectBaseOf(p, 'app', 'crm')).toEqual({ kind: 'app', name: 'crm' }); expect(packagedObjectBaseOf(p, 'book', 'crm_manual')).toEqual({ kind: 'book', name: 'crm_manual' }); expect(packagedObjectBaseOf(p, 'mapping', 'crm_lead_feed')).toEqual({ kind: 'mapping', name: 'crm_lead_feed' }); - for (const accessor of ['getPackagedPageBase', 'getPackagedDatasetBase', 'getPackagedAppBase', 'getPackagedBookBase', 'getPackagedMappingBase'] as const) { + expect(packagedObjectBaseOf(p, 'form', 'crm_lead.web_to_lead')).toEqual({ kind: 'form', name: 'crm_lead.web_to_lead' }); + for (const accessor of ['getPackagedPageBase', 'getPackagedDatasetBase', 'getPackagedAppBase', 'getPackagedBookBase', 'getPackagedMappingBase', 'getPackagedFormBase'] as const) { expect(p[accessor], accessor).toHaveBeenCalledTimes(1); } }); diff --git a/packages/rest/src/meta-item-read-gate.ts b/packages/rest/src/meta-item-read-gate.ts index 0bfde0bdf4e..fc63e35c675 100644 --- a/packages/rest/src/meta-item-read-gate.ts +++ b/packages/rest/src/meta-item-read-gate.ts @@ -3442,6 +3442,9 @@ const PACKAGED_BASE_ACCESSORS: ReadonlyMap = new Map 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; }, @@ -90,7 +93,7 @@ function makeRes() { interface Answer { status: number; body: any } -async function boot(ships: { forms?: unknown[]; views?: unknown[] }) { +async function boot(ships: { forms?: unknown[]; views?: unknown[] }, opts: { i18n?: unknown } = {}) { const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any); const engine = new ObjectQL(); engine.registerDriver(driver, true); @@ -109,7 +112,12 @@ async function boot(ships: { forms?: unknown[]; views?: unknown[] }) { } 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); + const rest = new RestServer( + mockServer() as any, protocol, { api: { requireAuth: false } } as any, + undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, + // i18nServiceProvider — the 14th constructor argument. + opts.i18n !== undefined ? async () => opts.i18n as any : undefined, + ); rest.registerRoutes(); const route = (method: string, path: string) => { const found = rest.getRoutes().find((r: any) => r.method === method && r.path === path); @@ -118,9 +126,9 @@ async function boot(ships: { forms?: unknown[]; views?: unknown[] }) { }; const resolve = route('GET', '/api/v1/forms/:slug'); const submit = route('POST', '/api/v1/forms/:slug/submit'); - const get = async (slug = SLUG): Promise => { + const get = async (slug = SLUG, headers: Record = {}): Promise => { const res = makeRes(); - await resolve.handler({ params: { slug }, query: {}, headers: {} } as any, res); + await resolve.handler({ params: { slug }, query: {}, headers } as any, res); return { status: res._status ?? 200, body: res._json }; }; const post = async (slug = SLUG): Promise => { @@ -157,7 +165,15 @@ async function boot(ships: { forms?: unknown[]; views?: unknown[] }) { version: 1, created_at: now, updated_at: now, }, { context: { isSystem: true } }); }; - return { engine, protocol, get, post, records, install, saveInto, saveBeforeTheGate, seedRow }; + /** `GET /api/v1/meta/:type/:name` as `caller` (`systemPermissions`), or anonymous-free when `caller` is omitted. */ + const meta = async (type: string, name: string, caller?: { systemPermissions: string[] }, headers: Record = {}): Promise => { + (rest as any).resolveExecCtx = async () => (caller ? { userId: 'u_reader', ...caller } : undefined); + const item = route('GET', '/api/v1/meta/:type/:name'); + const res = makeRes(); + await item.handler({ method: 'GET', path: `/api/v1/meta/${type}/${name}`, params: { type, name }, query: {}, body: {}, headers } as any, res); + return { status: res._status ?? 200, body: res._json }; + }; + return { engine, protocol, rest, get, post, records, install, saveInto, saveBeforeTheGate, seedRow, meta }; } type Booted = Awaited>; @@ -809,3 +825,72 @@ describe('[ADR-0159 D5] a `form` save, reset and delete: the old-shape row of th expect(await rawRows(b, 'view', NAME, PAIR)).toEqual(view); }); }); + +describe('[ADR-0159 card ② item 2, D5, ADR-0029 D9.2a] the `/meta/form` read: its audience, one definition per address, the override\'s own text', () => { + const engines: ObjectQL[] = []; + afterAll(async () => { + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + const booted = async (ships: { forms?: unknown[]; views?: unknown[] }, opts: { i18n?: unknown } = {}): Promise => { + const b = await boot(ships, opts); + engines.push(b.engine); + return b; + }; + const CAP = 'ftt.legal_desk'; + const holder = { systemPermissions: [CAP] }; + const stranger = { systemPermissions: [] as string[] }; + + it('a caller refused a form\'s document at `/api/v1/meta/view/NAME` is refused it at `/api/v1/meta/form/NAME`; its holder is served both', async () => { + // A view item's own audience gate travels with the form it projects. On + // this tree only a row at rest carries one on a form (the `view` write + // door refuses an item-level `requiredPermissions`, and a form body + // declares none), so the row is seeded as stored. + const b = await booted({}); + await b.seedRow('view', NAME, null, viewItem(true, { requiredPermissions: [CAP] })); + const view = await b.meta('view', NAME, stranger); + const form = await b.meta('form', NAME, stranger); + expect(view.status, JSON.stringify(view.body)).toBe(403); + expect([form.status, form.body?.error?.code ?? form.body?.code]).toEqual([view.status, view.body?.error?.code ?? view.body?.code]); + expect(JSON.stringify(form.body)).not.toContain('Contact us'); + // CONTROL: the holder reads both. + expect((await b.meta('view', NAME, holder)).status).toBe(200); + const served = await b.meta('form', NAME, holder); + expect(served.status, JSON.stringify(served.body)).toBe(200); + expect(JSON.stringify(served.body)).toContain('Contact us'); + }); + + it('one definition per address: a package-less stored `form` row over a base that ships the form as an old shape is listed once, at the base\'s address, with the row\'s body (D5 served-row order)', async () => { + const b = await booted({ views: [container(true)] }); + await b.seedRow('form', NAME, null, formItem(false, { label: 'Package-less row' })); + const listed = ((await b.protocol.getMetaItems({ type: 'form' })).items as any[]).filter((f) => f?.name === NAME); + expect(listed.map((f) => [f._packageId, f.label, f._formDefinedIn ?? null])).toEqual([[BASE, 'Package-less row', null]]); + const byName: any = await b.protocol.getMetaItem({ type: 'form', name: NAME }); + expect(byName.item?.label).toBe('Package-less row'); + // Fail-closed as before: the row switches the form off. + await closedOnBothDoors(b); + }); + + it('an override\'s own changed text outranks the base\'s catalog on `/meta/form` and on the public door; text it kept is translated (ablate: the `form` row of PACKAGED_BASE_ACCESSORS)', async () => { + const BUNDLE: Record = { + en: {}, + de: { forms: { [NAME]: { title: 'Kontaktieren Sie uns' } } }, + }; + const i18n = { getLocales: () => ['en', 'de'], getTranslations: (l: string) => BUNDLE[l], getDefaultLocale: () => 'en' }; + const de = { 'accept-language': 'de' }; + const b = await booted({ forms: [formItem(true, { title: 'Contact us' })] }, { i18n }); + // CONTROL: the base's own title is translated. + expect((await b.get(SLUG, de)).body?.form?.title).toBe('Kontaktieren Sie uns'); + await b.install(PAIR); + await b.saveInto('form', PAIR, formItem(true, { ...overrides, title: 'Write to us' })); + const door = await b.get(SLUG, de); + expect(door.status, JSON.stringify(door.body)).toBe(200); + expect(door.body?.form?.title).toBe('Write to us'); + const read = await b.meta('form', NAME, stranger, de); + expect(read.status, JSON.stringify(read.body)).toBe(200); + expect(JSON.stringify(read.body)).toContain('Write to us'); + expect(JSON.stringify(read.body)).not.toContain('Kontaktieren Sie uns'); + // An override that keeps the base's title is served the translation. + await b.saveInto('form', PAIR, formItem(true, { ...overrides, title: 'Contact us' })); + expect((await b.get(SLUG, de)).body?.form?.title).toBe('Kontaktieren Sie uns'); + }); +}); From 89858b3f947f2349361fa6b24d9cad747f2a69dc Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:26:37 +0000 Subject: [PATCH 16/29] feat(spec): forms.NAME.sections, read before the object-level _sections default ADR-0159 D8 gives a form its own section copy: forms.NAME.sections.SECTION.{label,description} and .fields.FIELD.{label,placeholder,helpText}. translateForm reads that node first, key by key, across the locale chain, and objects.OBJECT._sections.SECTION stays the object-level default that field groups share on purpose. A view is not a form: translateView never reads the forms family. The section shape is one factory for both faces, so they cannot drift; the ledger drills the new branch and the generated references follow. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- content/docs/references/api/protocol.mdx | 2 +- .../docs/references/system/translation.mdx | 12 ++- .../spec/liveness/state-counts/translation.md | 2 +- packages/spec/liveness/translation.json | 40 ++++++++++ .../system/i18n-resolver.form-item.test.ts | 78 +++++++++++++++++++ packages/spec/src/system/i18n-resolver.ts | 33 ++++++-- packages/spec/src/system/translation.zod.ts | 69 ++++++++++------ 7 files changed, 201 insertions(+), 35 deletions(-) diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index f2bb8313904..bf506815d7c 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -1944,7 +1944,7 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **datasets** | `Record; measures?: Record }>` | optional | Analytics dataset translations keyed by dataset name | | **reports** | `Record }>` | optional | Report translations keyed by report name | | **pages** | `Record` | optional | Page translations keyed by page name | -| **forms** | `Record` | optional | Form translations keyed by form name (ADR-0159 D8) | +| **forms** | `Record` | optional | Form translations keyed by form name (ADR-0159 D8) | | **flows** | `Record; … }>` | optional | Screen-flow translations keyed by flow name | | **hooks** | `Record; texts?: Record }>` | optional | Hook translations keyed by hook name | | **positions** | `Record` | optional | Position translations keyed by position name | diff --git a/content/docs/references/system/translation.mdx b/content/docs/references/system/translation.mdx index 8b9fe046694..7549172c623 100644 --- a/content/docs/references/system/translation.mdx +++ b/content/docs/references/system/translation.mdx @@ -198,7 +198,7 @@ Platform translation data — the per-app groups plus the platform-only `setting | **datasets** | `Record; measures?: Record }>` | optional | Analytics dataset translations keyed by dataset name | | **reports** | `Record }>` | optional | Report translations keyed by report name | | **pages** | `Record` | optional | Page translations keyed by page name | -| **forms** | `Record` | optional | Form translations keyed by form name (ADR-0159 D8) | +| **forms** | `Record` | optional | Form translations keyed by form name (ADR-0159 D8) | | **flows** | `Record; … }>` | optional | Screen-flow translations keyed by flow name | | **hooks** | `Record; texts?: Record }>` | optional | Hook translations keyed by hook name | | **positions** | `Record` | optional | Position translations keyed by position name | @@ -304,6 +304,7 @@ Translation data for a single object | **description** | `string` | optional | Translated form description | | **title** | `string` | optional | Translated form heading (overlays the form's `title`) | | **submitBehavior** | `{ title?: string; message?: string }` | optional | Translated thank-you panel copy — overlays the form's `submitBehavior` `title` / `message` when its `kind` is `'thank-you'` | +| **sections** | `Record }>` | optional | The form's own section copy keyed by section name; a key absent here reads `objects.OBJECT._sections.SECTION` | ### Nested Shape: `PlatformTranslationData.flows[string]` @@ -400,7 +401,7 @@ Served translation data — the platform groups the browser reads, without the s | **datasets** | `Record; measures?: Record }>` | optional | Analytics dataset translations keyed by dataset name | | **reports** | `Record }>` | optional | Report translations keyed by report name | | **pages** | `Record` | optional | Page translations keyed by page name | -| **forms** | `Record` | optional | Form translations keyed by form name (ADR-0159 D8) | +| **forms** | `Record` | optional | Form translations keyed by form name (ADR-0159 D8) | | **flows** | `Record; … }>` | optional | Screen-flow translations keyed by flow name | | **hooks** | `Record; texts?: Record }>` | optional | Hook translations keyed by hook name | | **positions** | `Record` | optional | Position translations keyed by position name | @@ -505,6 +506,7 @@ Translation data for a single object | **description** | `string` | optional | Translated form description | | **title** | `string` | optional | Translated form heading (overlays the form's `title`) | | **submitBehavior** | `{ title?: string; message?: string }` | optional | Translated thank-you panel copy — overlays the form's `submitBehavior` `title` / `message` when its `kind` is `'thank-you'` | +| **sections** | `Record }>` | optional | The form's own section copy keyed by section name; a key absent here reads `objects.OBJECT._sections.SECTION` | ### Nested Shape: `ServedTranslationData.flows[string]` @@ -664,7 +666,7 @@ Per-app translation data for objects, apps, and UI messages | **datasets** | `Record; measures?: Record }>` | optional | Analytics dataset translations keyed by dataset name | | **reports** | `Record }>` | optional | Report translations keyed by report name | | **pages** | `Record` | optional | Page translations keyed by page name | -| **forms** | `Record` | optional | Form translations keyed by form name (ADR-0159 D8) | +| **forms** | `Record` | optional | Form translations keyed by form name (ADR-0159 D8) | | **flows** | `Record; … }>` | optional | Screen-flow translations keyed by flow name | | **hooks** | `Record; texts?: Record }>` | optional | Hook translations keyed by hook name | | **positions** | `Record` | optional | Position translations keyed by position name | @@ -769,6 +771,7 @@ Translation data for a single object | **description** | `string` | optional | Translated form description | | **title** | `string` | optional | Translated form heading (overlays the form's `title`) | | **submitBehavior** | `{ title?: string; message?: string }` | optional | Translated thank-you panel copy — overlays the form's `submitBehavior` `title` / `message` when its `kind` is `'thank-you'` | +| **sections** | `Record }>` | optional | The form's own section copy keyed by section name; a key absent here reads `objects.OBJECT._sections.SECTION` | ### Nested Shape: `TranslationData.flows[string]` @@ -886,7 +889,7 @@ One locale of translations — the `translation` metadata type | **datasets** | `Record; measures?: Record }>` | optional | Analytics dataset translations keyed by dataset name | | **reports** | `Record }>` | optional | Report translations keyed by report name | | **pages** | `Record` | optional | Page translations keyed by page name | -| **forms** | `Record` | optional | Form translations keyed by form name (ADR-0159 D8) | +| **forms** | `Record` | optional | Form translations keyed by form name (ADR-0159 D8) | | **flows** | `Record; … }>` | optional | Screen-flow translations keyed by flow name | | **hooks** | `Record; texts?: Record }>` | optional | Hook translations keyed by hook name | | **positions** | `Record` | optional | Position translations keyed by position name | @@ -1002,6 +1005,7 @@ Translation data for a single object | **description** | `string` | optional | Translated form description | | **title** | `string` | optional | Translated form heading (overlays the form's `title`) | | **submitBehavior** | `{ title?: string; message?: string }` | optional | Translated thank-you panel copy — overlays the form's `submitBehavior` `title` / `message` when its `kind` is `'thank-you'` | +| **sections** | `Record }>` | optional | The form's own section copy keyed by section name; a key absent here reads `objects.OBJECT._sections.SECTION` | ### Nested Shape: `TranslationItem.flows[string]` diff --git a/packages/spec/liveness/state-counts/translation.md b/packages/spec/liveness/state-counts/translation.md index 63d0e58fe0b..282a7af5f82 100644 --- a/packages/spec/liveness/state-counts/translation.md +++ b/packages/spec/liveness/state-counts/translation.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `translation` | 53 | 0 | 0 | 0 | 2 | 55 | +| `translation` | 58 | 0 | 0 | 0 | 2 | 60 | diff --git a/packages/spec/liveness/translation.json b/packages/spec/liveness/translation.json index dd247ce3736..30d129a46a2 100644 --- a/packages/spec/liveness/translation.json +++ b/packages/spec/liveness/translation.json @@ -189,6 +189,46 @@ "evidence": "packages/spec/src/system/i18n-resolver.ts#translateFormSubmitBehavior (the thank-you panel's `message`, read off `forms..submitBehavior.message` first, then the `_views..submitBehavior.message` tail)" } } + }, + "sections": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidence": "packages/spec/src/system/i18n-resolver.ts#lookupSectionText (`forms..sections.
.{label,description}` read first when translateForm passes the form's name, then `objects.._sections.
`); packages/spec/src/system/i18n-resolver.ts#lookupSectionEntryText (`forms..sections.
.fields..{label,placeholder,helpText}` first, then the `_sections` entry)", + "note": "ADR-0159 D8: the form's own section copy, key by key over the object-level `_sections` default that field groups share on purpose. The extractor scaffolds the `_sections` default only (packages/lint/src/i18n-walk.ts#walkForms emits no `forms..sections` key): a form-specific section string is an author's override of the shared default, not a key every form owes.", + "children": { + "label": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidence": "packages/spec/src/system/i18n-resolver.ts#lookupSectionText (`forms..sections.
.label`, then `_sections.
.label`)" + }, + "description": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidence": "packages/spec/src/system/i18n-resolver.ts#lookupSectionText (`forms..sections.
.description`, then `_sections.
.description`)" + }, + "fields": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidence": "packages/spec/src/system/i18n-resolver.ts#lookupSectionEntryText (`forms..sections.
.fields..*`, keyed by the entry's own `field`)", + "children": { + "label": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidence": "packages/spec/src/system/i18n-resolver.ts#lookupSectionEntryText (`forms..sections.
.fields..label`, then the `_sections` entry's)" + }, + "placeholder": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidence": "packages/spec/src/system/i18n-resolver.ts#lookupSectionEntryText (`forms..sections.
.fields..placeholder`, then the `_sections` entry's)" + }, + "helpText": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidence": "packages/spec/src/system/i18n-resolver.ts#lookupSectionEntryText (`forms..sections.
.fields..helpText`, then the `_sections` entry's)" + } + } + } + } } } }, 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 f3a2ee139e6..4372c56175c 100644 --- a/packages/spec/src/system/i18n-resolver.form-item.test.ts +++ b/packages/spec/src/system/i18n-resolver.form-item.test.ts @@ -78,3 +78,81 @@ describe('translateForm — the `forms` family, `_views` tails as fallback', () expect(translateForm(doc, { 'zh-CN': {} as any }, { locale: 'zh-CN' })).toBe(doc); }); }); + +/** + * [ADR-0159 D8] `forms.NAME.sections.SECTION`: a form's own section copy is + * read first, key by key, and `objects.OBJECT._sections.SECTION` is the + * object-level default for any key the form's node does not carry. + */ +describe('translateForm — `forms.NAME.sections` first, `_sections` as the object-level default', () => { + const SECTIONED = { + name: 'crm_lead.web_to_lead', + object: 'crm_lead', + sections: [{ + name: 'about', + label: 'About you', + description: 'Who you are', + fields: [{ field: 'email', label: 'Work email', placeholder: 'you@example.com', helpText: 'We never share it' }], + }], + }; + const OWN = { + forms: { + 'crm_lead.web_to_lead': { + sections: { about: { label: '关于您', fields: { email: { label: '工作邮箱', helpText: '我们不会分享' } } } }, + }, + }, + }; + const OBJECT_DEFAULT = { + objects: { + crm_lead: { + _sections: { + about: { + label: '对象级标签', description: '对象级描述', + fields: { email: { label: '对象级邮箱', placeholder: '对象级占位' } }, + }, + }, + }, + }, + }; + + it('composes a legal pack: `forms.NAME.sections` parses', () => { + const parsed = TranslationDataSchema.safeParse(OWN); + expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); + }); + + it('REFUSES an unknown key under `forms.NAME.sections.SECTION`, as `_sections` does', () => { + const parsed = TranslationDataSchema.safeParse({ + forms: { 'crm_lead.web_to_lead': { sections: { about: { lable: 'x' } } } }, + }); + expect(parsed.success).toBe(false); + }); + + it('reads the form\'s own section node first, and `_sections` for each key it lacks', () => { + const bundle: TranslationBundle = { 'zh-CN': { ...OBJECT_DEFAULT, ...OWN } as any }; + const out = translateForm(clone(SECTIONED), bundle, { locale: 'zh-CN' }) as any; + expect(out.sections[0]).toMatchObject({ + label: '关于您', + description: '对象级描述', + fields: [{ field: 'email', label: '工作邮箱', placeholder: '对象级占位', helpText: '我们不会分享' }], + }); + }); + + it('CONTROL: with no `forms.NAME.sections` node, `_sections` translates the section as before', () => { + const bundle: TranslationBundle = { 'zh-CN': OBJECT_DEFAULT as any }; + const out = translateForm(clone(SECTIONED), bundle, { locale: 'zh-CN' }) as any; + expect(out.sections[0]).toMatchObject({ + label: '对象级标签', + description: '对象级描述', + fields: [{ field: 'email', label: '对象级邮箱', placeholder: '对象级占位', helpText: 'We never share it' }], + }); + }); + + it('CONTROL: a view is not a form — `translateView` never reads `forms.NAME.sections`', () => { + const view = { + name: 'crm_lead.web_to_lead', object: 'crm_lead', viewKind: 'form', + config: { type: 'simple', sections: clone(SECTIONED.sections) }, + }; + const out = translateMetadataDocument('view', view, { 'zh-CN': OWN as any }, { locale: 'zh-CN' }) as any; + expect(out.config.sections[0].label).toBe('About you'); + }); +}); diff --git a/packages/spec/src/system/i18n-resolver.ts b/packages/spec/src/system/i18n-resolver.ts index f774cee9970..35e16727757 100644 --- a/packages/spec/src/system/i18n-resolver.ts +++ b/packages/spec/src/system/i18n-resolver.ts @@ -1456,6 +1456,11 @@ function translateBulkActionDefs( * One string off a form section's `objects.._sections.
` node, * across the locale chain — `undefined` when no locale carries it, and the * caller then leaves the authored value in place. + * + * A `form` item passes its `formName`: its own + * `forms.
.sections.
` node is read first, across the whole + * locale chain, and `_sections` is the object-level default after it + * (ADR-0159 D8), the order {@link translateForm} reads `title` in. */ function lookupSectionText( bundle: TranslationBundle | undefined, @@ -1463,8 +1468,13 @@ function lookupSectionText( sectionName: string, attr: 'label' | 'description', opts: ResolveOptions | undefined, + formName?: string, ): string | undefined { if (!bundle) return undefined; + if (formName !== undefined) { + const own = lookupFormText(bundle, formName, ['sections', sectionName, attr], opts); + if (own !== undefined) return own; + } for (const code of localeChain(opts)) { const candidate = pickData(bundle, code)?.objects?.[objectName]?._sections?.[sectionName]?.[attr]; if (typeof candidate === 'string' && candidate.length > 0) return candidate; @@ -1476,7 +1486,9 @@ function lookupSectionText( * One string off a form section entry's * `objects.._sections.
.fields.` node, across the * locale chain — `undefined` when no locale carries it, and the caller then - * leaves the authored value in place. + * leaves the authored value in place. A `form` item's `formName` reads + * `forms..sections.
.fields.` first, as + * {@link lookupSectionText} does. */ function lookupSectionEntryText( bundle: TranslationBundle | undefined, @@ -1485,8 +1497,13 @@ function lookupSectionEntryText( fieldName: string, attr: FormSectionEntryAttr, opts: ResolveOptions | undefined, + formName?: string, ): string | undefined { if (!bundle) return undefined; + if (formName !== undefined) { + const own = lookupFormText(bundle, formName, ['sections', sectionName, 'fields', fieldName, attr], opts); + if (own !== undefined) return own; + } for (const code of localeChain(opts)) { const candidate = pickData(bundle, code)?.objects?.[objectName]?._sections?.[sectionName] ?.fields?.[fieldName]?.[attr]; @@ -1560,6 +1577,7 @@ function translateFormSections( objectName: string, opts: ResolveOptions | undefined, packagedConfig: Record | undefined, + formName?: string, ): unknown { if (!Array.isArray(sections)) return sections; let changed = false; @@ -1573,7 +1591,7 @@ function translateFormSections( ? undefined : lookupSectionText( catalogFor(catalogs, valueOverridesPackagedBase(packagedSection, attr, authored)), - objectName, sectionName, attr, opts, + objectName, sectionName, attr, opts, formName, ); const label = text('label', section.label); @@ -1585,6 +1603,7 @@ function translateFormSections( sectionName, opts, packagedSection, + formName, ); if (label === undefined && description === undefined && fields === section.fields) return raw; changed = true; @@ -1622,6 +1641,7 @@ function translateFormSectionEntries( sectionName: string, opts: ResolveOptions | undefined, packagedSection: Record | undefined, + formName?: string, ): unknown { if (!Array.isArray(entries)) return entries; let changed = false; @@ -1635,7 +1655,7 @@ function translateFormSectionEntries( ? undefined : lookupSectionEntryText( catalogFor(catalogs, valueOverridesPackagedBase(packagedEntry, attr, entry[attr])), - objectName, sectionName, fieldName, attr, opts, + objectName, sectionName, fieldName, attr, opts, formName, ); const label = text('label'); @@ -1980,8 +2000,9 @@ function lookupFormText( * 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 - * copy keeps `objects.._sections.
` as its object-level - * default ({@link translateFormSections}). The override rule is the view's: + * 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: * a string authored on top of the packaged form keeps its text against the * catalog (ADR-0029 D9.2a, {@link valueOverridesPackagedBase}). */ @@ -2018,7 +2039,7 @@ export function translateForm( base, ); const sections = catalogs.unchanged - ? translateFormSections(form.sections, catalogs, formSectionObjectName(form, objectName), opts, base) + ? translateFormSections(form.sections, catalogs, formSectionObjectName(form, objectName), opts, base, name) : form.sections; if (label === undefined && description === undefined && title === form.title && submitBehavior === form.submitBehavior && sections === form.sections) { diff --git a/packages/spec/src/system/translation.zod.ts b/packages/spec/src/system/translation.zod.ts index e209541c9b1..cee9a58e90b 100644 --- a/packages/spec/src/system/translation.zod.ts +++ b/packages/spec/src/system/translation.zod.ts @@ -554,6 +554,38 @@ const submitBehaviorTranslationSchema = (surface: string) => strictObject({ message: z.string().optional().describe('Translated thank-you panel message (overlays `submitBehavior.message`)'), }); +/** + * The copy of one named form section: its `label`, `description` and, under + * `fields`, the `label` / `placeholder` / `helpText` each entry authors, keyed + * by the entry's own `field`. Two faces carry it: the object-level default at + * `objects.._sections.
` (shared with field groups and record + * pages on purpose) and a form's own `forms..sections.
` + * (ADR-0159 D8), which the translator reads first. Built by a factory for + * {@link actionTranslationSchema}'s reason: the two cannot drift, and + * `surface` says which of the two a rejected key was written on. + */ +const sectionTranslationSchema = (surface: string, entrySurface: string) => strictObject({ + surface, + history: TRANSLATION_HISTORY, + aliases: { name: 'label', title: 'label', heading: 'label', entries: 'fields' }, +}, { + label: z.string().optional().describe('Translated section label'), + description: z.string().optional().describe('Translated section description'), + fields: z.record(z.string(), strictObject({ + surface: entrySurface, + history: TRANSLATION_HISTORY, + // `helpText` is the spelling a form section entry declares + // (`FormFieldSchema.helpText`); `help` is the FIELD translation's, one + // level up at `objects..fields.`. Neighbouring-surface + // borrowing, which edit distance reads as a legitimate word. + aliases: { help: 'helpText', hint: 'helpText', tooltip: 'helpText', name: 'label', title: 'label' }, + }, { + label: z.string().optional().describe('Translated entry label (overlays the section entry\'s `label` override)'), + placeholder: z.string().optional().describe('Translated entry placeholder (overlays the section entry\'s `placeholder` override)'), + helpText: z.string().optional().describe('Translated entry help text (overlays the section entry\'s `helpText` override)'), + })).optional().describe('Form section entry translations keyed by the entry\'s `field`'), +}); + export const ObjectTranslationDataSchema = lazySchema(() => strictObject({ surface: 'this object translation', history: TRANSLATION_HISTORY, @@ -814,27 +846,8 @@ export const ObjectTranslationDataSchema = lazySchema(() => strictObject({ * none of the three keeps the object field's own copy, translated at * `objects..fields.`. */ - _sections: z.record(z.string(), strictObject({ - surface: 'this section translation', - history: TRANSLATION_HISTORY, - aliases: { name: 'label', title: 'label', heading: 'label', entries: 'fields' }, - }, { - label: z.string().optional().describe('Translated section label'), - description: z.string().optional().describe('Translated section description'), - fields: z.record(z.string(), strictObject({ - surface: 'this form section entry translation', - history: TRANSLATION_HISTORY, - // `helpText` is the spelling a form section entry declares - // (`FormFieldSchema.helpText`); `help` is the FIELD translation's, one - // level up at `objects..fields.`. Neighbouring-surface - // borrowing, which edit distance reads as a legitimate word. - aliases: { help: 'helpText', hint: 'helpText', tooltip: 'helpText', name: 'label', title: 'label' }, - }, { - label: z.string().optional().describe('Translated entry label (overlays the section entry\'s `label` override)'), - placeholder: z.string().optional().describe('Translated entry placeholder (overlays the section entry\'s `placeholder` override)'), - helpText: z.string().optional().describe('Translated entry help text (overlays the section entry\'s `helpText` override)'), - })).optional().describe('Form section entry translations keyed by the entry\'s `field`'), - })).optional().describe('Section translations keyed by section name'), + _sections: z.record(z.string(), sectionTranslationSchema('this section translation', 'this form section entry translation')) + .optional().describe('Section translations keyed by section name'), /** * Filter-preset tab translations keyed by tab name (`ViewTabSchema.name`). @@ -1817,14 +1830,22 @@ const appTranslationDataShape = () => ({ * forms..title * forms..submitBehavior.title (a `thank-you` panel) * forms..submitBehavior.message + * forms..sections..label + * forms..sections..description + * forms..sections..fields..label + * forms..sections..fields..placeholder + * forms..sections..fields..helpText * * The translator reads `forms.NAME` first; the form tails a form defined in * a view had under `objects.OBJECT._views.KEY` (`title`, `submitBehavior`) * are the declared fallback, so a bundle written for the old shape keeps * translating the same form. `label` and `description` under `_views.KEY` * are a view's, not form tails: they are neither moved nor read as a - * fallback. Section copy keeps `objects.OBJECT._sections.SECTION` as its - * object-level default. + * fallback. A section with no key under `forms.NAME.sections` reads + * `objects.OBJECT._sections.SECTION`, its object-level default: field + * groups and forms of one object share section names on purpose, so that + * is not a legacy fallback, and an entry key the form's section lacks falls + * back the same way, one key at a time. */ forms: z.record(z.string(), strictObject({ surface: 'this form translation', @@ -1835,6 +1856,8 @@ const appTranslationDataShape = () => ({ description: z.string().optional().describe('Translated form description'), title: z.string().optional().describe('Translated form heading (overlays the form\'s `title`)'), submitBehavior: submitBehaviorTranslationSchema('this form submit behavior translation').optional().describe("Translated thank-you panel copy — overlays the form's `submitBehavior` `title` / `message` when its `kind` is `'thank-you'`"), + sections: z.record(z.string(), sectionTranslationSchema('this form section translation', 'this form section entry translation')) + .optional().describe("The form's own section copy keyed by section name; a key absent here reads `objects.OBJECT._sections.SECTION`"), })).optional().describe('Form translations keyed by form name (ADR-0159 D8)'), /** From 7185b8a64edabb204c636293b6509b2b016c7e93 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:32:06 +0000 Subject: [PATCH 17/29] test(rest): hold the old shapes and the CRM's public form to answers taken before the form type form-old-shape-before.json was captured on PR A's head (the rename-only tree, cb854ea4d) by a throwaway test that booted the same stacks the pins boot here, and never committed: GET /api/v1/meta/view over a container default form, a formViews entry and a stored viewKind form; a formViews entry whose data.object names another object, on both doors; and the CRM's GET /forms/contact-us. Each is compared as the wire serializes it, with the save clock written as TIME. The CRM pin reads two examples/app-crm files, declared as rest test:repo inputs; the four form route tests the form-read doubles edited pay the objectql transform at module top. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- packages/rest/src/form-old-shape-before.json | 287 ++++++++++++++++++ .../public-form-app-crm-byte-equal.test.ts | 68 +++++ .../src/public-form-routes.stored-row.test.ts | 5 + packages/rest/src/public-form-routes.test.ts | 5 + .../src/public-form-submit-answer.test.ts | 5 + .../public-form-two-type-withdrawal.test.ts | 78 ++++- .../rest/src/public-form-withdrawal.test.ts | 5 + packages/rest/vitest.repo-tests.json | 1 + scripts/cross-package-test-inputs.mjs | 8 + turbo.json | 2 + 10 files changed, 461 insertions(+), 3 deletions(-) create mode 100644 packages/rest/src/form-old-shape-before.json create mode 100644 packages/rest/src/public-form-app-crm-byte-equal.test.ts diff --git a/packages/rest/src/form-old-shape-before.json b/packages/rest/src/form-old-shape-before.json new file mode 100644 index 00000000000..30e843c0c08 --- /dev/null +++ b/packages/rest/src/form-old-shape-before.json @@ -0,0 +1,287 @@ +{ + "meta-view-list": { + "status": 200, + "body": { + "type": "view", + "items": [ + { + "name": "ftt_inquiry.contact", + "object": "ftt_inquiry", + "viewKind": "form", + "config": { + "type": "simple", + "sections": [ + { + "fields": [ + "name", + "email" + ] + } + ], + "sharing": { + "enabled": true, + "allowAnonymous": true, + "publicLink": "/forms/contact-37086" + }, + "data": { + "provider": "object", + "object": "ftt_inquiry" + } + }, + "order": 0, + "scope": "package", + "_packageId": "com.example.forms37086", + "_packageVersion": "1.0.0", + "_provenance": "package", + "_diagnostics": { + "valid": true + } + }, + { + "name": "ftt_inquiry.form", + "object": "ftt_inquiry", + "viewKind": "form", + "config": { + "type": "simple", + "sections": [ + { + "fields": [ + "name" + ] + } + ], + "sharing": { + "enabled": true, + "allowAnonymous": true, + "publicLink": "/forms/whole-37086" + }, + "data": { + "provider": "object", + "object": "ftt_inquiry" + } + }, + "order": 1, + "scope": "package", + "isDefault": true, + "_packageId": "com.example.forms37086", + "_packageVersion": "1.0.0", + "_provenance": "package", + "_diagnostics": { + "valid": true + } + }, + { + "name": "ftt_inquiry.standalone", + "object": "ftt_inquiry", + "viewKind": "form", + "label": "Contact us", + "config": { + "type": "simple", + "sections": [ + { + "fields": [ + "name", + "email" + ] + } + ], + "sharing": { + "enabled": true, + "allowAnonymous": true, + "publicLink": "/forms/standalone-37086" + }, + "data": { + "provider": "object", + "object": "ftt_inquiry" + } + }, + "_diagnostics": { + "valid": true + } + } + ], + "changedAt": { + "ftt_inquiry.standalone": "2026-11-26T07:19:38.576Z" + } + } + }, + "data-object-resolve": { + "status": 200, + "body": { + "slug": "contact-37086", + "object": "ftt_lead", + "form": { + "type": "simple", + "sections": [ + { + "fields": [ + "name", + "email" + ] + } + ], + "sharing": { + "enabled": true, + "allowAnonymous": true, + "publicLink": "/forms/contact-37086" + }, + "data": { + "provider": "object", + "object": "ftt_lead" + } + }, + "objectSchema": { + "name": "ftt_lead", + "label": "Lead", + "fields": { + "name": { + "name": "name", + "type": "text", + "label": "Name" + }, + "email": { + "name": "email", + "type": "text", + "label": "Email" + } + } + } + } + }, + "data-object-submit": { + "status": 400, + "body": { + "error": "Organization is required", + "code": "VALIDATION_FAILED", + "fields": [ + { + "field": "organization_id", + "code": "required", + "message": "Organization is required", + "label": "Organization" + } + ] + } + }, + "crm-resolve": { + "status": 200, + "body": { + "slug": "contact-us", + "object": "crm_lead", + "form": { + "type": "simple", + "data": { + "provider": "object", + "object": "crm_lead" + }, + "sections": [ + { + "name": "contact_us", + "label": "Contact us", + "collapsible": false, + "collapsed": false, + "columns": 1, + "fields": [ + { + "field": "name", + "required": true, + "span": "auto" + }, + { + "field": "company", + "span": "auto" + }, + { + "field": "email", + "required": true, + "span": "auto" + }, + { + "field": "phone", + "span": "auto" + }, + { + "field": "title", + "span": "auto" + } + ] + } + ], + "sharing": { + "enabled": true, + "publicLink": "/forms/contact-us", + "allowAnonymous": true + } + }, + "objectSchema": { + "name": "crm_lead", + "label": "Lead", + "fields": { + "name": { + "label": "Lead Name", + "type": "text", + "required": true, + "searchable": true, + "multiple": false, + "unique": false, + "maxLength": 200, + "hidden": false, + "readonly": false, + "sortable": true, + "externalId": false + }, + "email": { + "label": "Email", + "type": "email", + "required": false, + "searchable": true, + "multiple": false, + "unique": false, + "hidden": false, + "readonly": false, + "sortable": true, + "externalId": false + }, + "phone": { + "label": "Phone", + "type": "phone", + "required": false, + "searchable": false, + "multiple": false, + "unique": false, + "hidden": false, + "readonly": false, + "sortable": true, + "externalId": false + }, + "company": { + "label": "Company", + "type": "text", + "required": false, + "searchable": true, + "multiple": false, + "unique": false, + "maxLength": 200, + "hidden": false, + "readonly": false, + "sortable": true, + "externalId": false + }, + "title": { + "label": "Title", + "type": "text", + "required": false, + "searchable": false, + "multiple": false, + "unique": false, + "maxLength": 120, + "hidden": false, + "readonly": false, + "sortable": true, + "externalId": false + } + } + } + } + } +} diff --git a/packages/rest/src/public-form-app-crm-byte-equal.test.ts b/packages/rest/src/public-form-app-crm-byte-equal.test.ts new file mode 100644 index 00000000000..4d1ec849128 --- /dev/null +++ b/packages/rest/src/public-form-app-crm-byte-equal.test.ts @@ -0,0 +1,68 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0159 D5, card ② "Done when"] The public form of `examples/app-crm` + * (`/forms/contact-us`, the lead container's `formViews.web_to_lead`) answers + * at its address as it did before the `form` type, byte-equal on the resolve + * door. The fixture `form-old-shape-before.json` (`crm-resolve`) was taken by + * the same boot against the rename-only head `cb854ea4d`, which serves no + * `form` type, and is never regenerated from this tree. + * + * It reads the example's own sources, so it runs in the `repo` project + * (`vitest.repo-tests.json`), a separate file from the door harness + * (`public-form-two-type-withdrawal.test.ts`) for that reason only. + */ +import { afterAll, describe, expect, it } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { SysMetadataAuditObject, SysMetadataCommitObject, SysMetadataHistoryObject, SysMetadataObject } from '@objectstack/metadata-core'; +import { RestServer } from './rest-server'; +import * as CRM_OBJECTS from '../../../examples/app-crm/src/objects/index'; +import { LeadViews } from '../../../examples/app-crm/src/views/lead.view'; + +const BEFORE = JSON.parse(readFileSync(new URL('./form-old-shape-before.json', import.meta.url), 'utf8')); + +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, end: () => res, + status: (code: number) => { res._status = code; return res; }, + json: (b: unknown) => { res._json = b; return res; }, + }; + return res; +} + +describe('[ADR-0159 D5] examples/app-crm: the public form answers byte-equal on the resolve door', () => { + const engines: ObjectQL[] = []; + afterAll(async () => { + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + + it('GET /api/v1/forms/contact-us answers the fixture taken before the type, and the form is also read as a `form` item', async () => { + 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: 'com.example.crm', name: 'crm', version: '1.0.0', namespace: 'crm', objects: Object.values(CRM_OBJECTS), views: [LeadViews] } 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 resolve = rest.getRoutes().find((r: any) => r.method === 'GET' && r.path === '/api/v1/forms/:slug')!; + const res = makeRes(); + await resolve.handler({ params: { slug: 'contact-us' }, query: {}, headers: {} } as any, res); + // Byte-equal: the answer as the wire serializes it, key order included. + expect(JSON.stringify({ status: res._status ?? 200, body: res._json })).toBe(JSON.stringify(BEFORE['crm-resolve'])); + const forms = ((await protocol.getMetaItems({ type: 'form' })).items as any[]).filter((f) => f?.sharing?.publicLink === '/forms/contact-us'); + expect(forms.map((f) => [f.name, f._formDefinedIn])).toEqual([['crm_lead.web_to_lead', 'view']]); + }); +}); diff --git a/packages/rest/src/public-form-routes.stored-row.test.ts b/packages/rest/src/public-form-routes.stored-row.test.ts index 81b66e3dba8..d5247cf434b 100644 --- a/packages/rest/src/public-form-routes.stored-row.test.ts +++ b/packages/rest/src/public-form-routes.stored-row.test.ts @@ -66,6 +66,11 @@ import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protoco import { RestServer } from './rest-server.js'; import { projectedFormsOf } from '@objectstack/spec/ui'; +// Pay the first transform of `@objectstack/objectql`, which the route source +// reaches through a dynamic `import()`, at MODULE LOAD rather than inside a +// clocked `it()` body (`scripts/check-test-source-alias.mjs`). +import '@objectstack/objectql'; + // ─── the real save path ────────────────────────────────────────────────────── /** The slice of the engine the `sys_metadata` write path touches. */ diff --git a/packages/rest/src/public-form-routes.test.ts b/packages/rest/src/public-form-routes.test.ts index cd1b8d73026..749106be3b8 100644 --- a/packages/rest/src/public-form-routes.test.ts +++ b/packages/rest/src/public-form-routes.test.ts @@ -24,6 +24,11 @@ import { RestServer } from './rest-server'; // where the same shape cost 30 ejected merge-queue builds in one night. import { projectedFormsOf } from '@objectstack/spec/ui'; +// Pay the first transform of `@objectstack/objectql`, which the route source +// reaches through a dynamic `import()`, at MODULE LOAD rather than inside a +// clocked `it()` body (`scripts/check-test-source-alias.mjs`). +import '@objectstack/objectql'; + function mockServer() { return { get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), patch: vi.fn(), diff --git a/packages/rest/src/public-form-submit-answer.test.ts b/packages/rest/src/public-form-submit-answer.test.ts index 729af0b48f7..7399948f821 100644 --- a/packages/rest/src/public-form-submit-answer.test.ts +++ b/packages/rest/src/public-form-submit-answer.test.ts @@ -35,6 +35,11 @@ import { REST_ROUTE_LEDGER } from './rest-route-ledger'; // LOAD, as `public-form-routes.test.ts` does for the same routes. import { projectedFormsOf } from '@objectstack/spec/ui'; +// Pay the first transform of `@objectstack/objectql`, which the route source +// reaches through a dynamic `import()`, at MODULE LOAD rather than inside a +// clocked `it()` body (`scripts/check-test-source-alias.mjs`). +import '@objectstack/objectql'; + const CREATED_ID = 'rec_answer_1'; /** Synthetic values the stored row carries. None may reach the anonymous caller. */ const DERIVED = 'SYNTH-DERIVED-FROM-EXISTING-7311'; diff --git a/packages/rest/src/public-form-two-type-withdrawal.test.ts b/packages/rest/src/public-form-two-type-withdrawal.test.ts index a71e6826065..f2ee78c63a1 100644 --- a/packages/rest/src/public-form-two-type-withdrawal.test.ts +++ b/packages/rest/src/public-form-two-type-withdrawal.test.ts @@ -30,6 +30,7 @@ import { SysMetadataObject, hashSpec, } from '@objectstack/metadata-core'; +import { readFileSync } from 'node:fs'; import { RestServer } from './rest-server'; const BASE = 'com.example.forms37086'; @@ -93,7 +94,7 @@ function makeRes() { interface Answer { status: number; body: any } -async function boot(ships: { forms?: unknown[]; views?: unknown[] }, opts: { i18n?: unknown } = {}) { +async function boot(ships: { forms?: unknown[]; views?: unknown[]; objects?: unknown[] }, opts: { i18n?: unknown } = {}) { const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any); const engine = new ObjectQL(); engine.registerDriver(driver, true); @@ -106,7 +107,7 @@ async function boot(ships: { forms?: unknown[]; views?: unknown[] }, opts: { i18 name: 'forms37086', version: '1.0.0', namespace: 'ftt', - objects: [INQUIRY], + objects: [INQUIRY, ...(ships.objects ?? [])], ...(ships.forms ? { forms: ships.forms } : {}), ...(ships.views ? { views: ships.views } : {}), } as any); @@ -173,7 +174,15 @@ async function boot(ships: { forms?: unknown[]; views?: unknown[] }, opts: { i18 await item.handler({ method: 'GET', path: `/api/v1/meta/${type}/${name}`, params: { type, name }, query: {}, body: {}, headers } as any, res); return { status: res._status ?? 200, body: res._json }; }; - return { engine, protocol, rest, get, post, records, install, saveInto, saveBeforeTheGate, seedRow, meta }; + /** `GET /api/v1/meta/:type` as a caller who holds no capability. */ + const metaList = async (type: string): Promise => { + (rest as any).resolveExecCtx = async () => ({ userId: 'u_reader', systemPermissions: [] }); + const list = route('GET', '/api/v1/meta/:type'); + const res = makeRes(); + await list.handler({ method: 'GET', path: `/api/v1/meta/${type}`, params: { type }, query: {}, body: {}, headers: {} } as any, res); + return { status: res._status ?? 200, body: res._json }; + }; + return { engine, protocol, rest, get, post, records, install, saveInto, saveBeforeTheGate, seedRow, meta, metaList }; } type Booted = Awaited>; @@ -894,3 +903,66 @@ describe('[ADR-0159 card ② item 2, D5, ADR-0029 D9.2a] the `/meta/form` read: expect((await b.get(SLUG, de)).body?.form?.title).toBe('Kontaktieren Sie uns'); }); }); + +/** + * [ADR-0159 D5, card ② "Done when"] What the old shapes serve, held byte-equal + * with a fixture TAKEN BEFORE the `form` type: `form-old-shape-before.json` was + * written by these same fixtures run against the tree under this change (the + * rename-only head `cb854ea4d`, which serves no `form` type), and is never + * regenerated from this tree. + */ +const BEFORE: Record = JSON.parse(readFileSync(new URL('./form-old-shape-before.json', import.meta.url), 'utf8')); +/** + * An answer as the wire carries it: a JSON round trip (an `undefined` member is + * not on the wire), with each `changedAt` stamp written as `TIME` — the clock + * a row was saved at is the one value two runs cannot share. The keys stay: + * which items carry a stamp is part of the answer. + */ +const wire = (answer: unknown): unknown => JSON.parse(JSON.stringify(answer), function (key, value) { + return key !== 'changedAt' || value === null || typeof value !== 'object' + ? value + : Object.fromEntries(Object.keys(value).map((name) => [name, 'TIME'])); +}); +const LEAD = { name: 'ftt_lead', label: 'Lead', fields: { name: { name: 'name', type: 'text' as const, label: 'Name' }, email: { name: 'email', type: 'text' as const, label: 'Email' } } }; +/** The three old shapes: a container's `form`, a `formViews` entry, and (stored) a `viewKind: 'form'` item. */ +const threeShapes = () => ({ + views: [{ + object: OBJECT, + form: { type: 'simple', sections: [{ fields: ['name'] }], sharing: sharing(true, 'whole-37086'), data: { provider: 'object', object: OBJECT } }, + formViews: { contact: { ...body(true), data: { provider: 'object', object: OBJECT } } }, + }], +}); +const STANDALONE = `${OBJECT}.standalone`; +/** A container on {@link OBJECT} whose `formViews` entry binds ANOTHER object through `data.object`. */ +const otherObjectForm = () => ({ + objects: [LEAD], + views: [{ object: OBJECT, formViews: { contact: { ...body(true), data: { provider: 'object', object: 'ftt_lead' } } } }], +}); + +describe('[ADR-0159 D5] the old shapes answer what they answered before the type (fixture taken before the change)', () => { + const engines: ObjectQL[] = []; + afterAll(async () => { + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + + it('a stack that authors the three old shapes: `GET /api/v1/meta/view` answers exactly the fixture, and each form is also served as a `form` item of the same name', async () => { + const b = await boot(threeShapes()); + engines.push(b.engine); + await b.saveInto('view', undefined, { ...viewItem(true, {}, 'standalone-37086'), name: STANDALONE }, STANDALONE); + const list = await b.metaList('view'); + expect(JSON.stringify(wire(list))).toBe(JSON.stringify(wire(BEFORE['meta-view-list']))); + const forms = ((await b.protocol.getMetaItems({ type: 'form' })).items as any[]).map((f) => [f.name, f._formDefinedIn]).sort(); + const viewForms = ((list.body?.items ?? list.body?.data?.items ?? list.body) as any[]) + .filter((v) => v?.viewKind === 'form').map((v) => [v.name, 'view']).sort(); + expect(viewForms.length).toBeGreaterThanOrEqual(3); + expect(forms).toEqual(viewForms); + }); + + it('an old-shape form whose `data.object` differs from its container\'s object answers both doors as before, byte-equal on the resolve door (ablate: parse projected items with FormSchema)', async () => { + const b = await boot(otherObjectForm()); + engines.push(b.engine); + expect(JSON.stringify(wire(await b.get()))).toBe(JSON.stringify(wire(BEFORE['data-object-resolve']))); + const submitted = await b.post(); + expect([submitted.status, submitted.body?.code]).toEqual([BEFORE['data-object-submit'].status, BEFORE['data-object-submit'].body?.code]); + }); +}); diff --git a/packages/rest/src/public-form-withdrawal.test.ts b/packages/rest/src/public-form-withdrawal.test.ts index aa605e2a405..3f391456c7f 100644 --- a/packages/rest/src/public-form-withdrawal.test.ts +++ b/packages/rest/src/public-form-withdrawal.test.ts @@ -33,6 +33,11 @@ import { RestServer } from './rest-server'; // MODULE LOAD rather than inside a clocked `it()` body. import { projectedFormsOf } from '@objectstack/spec/ui'; +// Pay the first transform of `@objectstack/objectql`, which the route source +// reaches through a dynamic `import()`, at MODULE LOAD rather than inside a +// clocked `it()` body (`scripts/check-test-source-alias.mjs`). +import '@objectstack/objectql'; + const ORG = 'org_alpha'; function mockServer() { diff --git a/packages/rest/vitest.repo-tests.json b/packages/rest/vitest.repo-tests.json index 79903bbca41..d0635bed148 100644 --- a/packages/rest/vitest.repo-tests.json +++ b/packages/rest/vitest.repo-tests.json @@ -3,5 +3,6 @@ "src/error-response-sandbox-arm-message.test.ts", "src/error-response-structured-arm-door-parity.test.ts", "src/meta-state-route-doc-spelling.test.ts", + "src/public-form-app-crm-byte-equal.test.ts", "src/rest-server-canonical-query-ast.test.ts" ] diff --git a/scripts/cross-package-test-inputs.mjs b/scripts/cross-package-test-inputs.mjs index f8af81272de..e421b777734 100644 --- a/scripts/cross-package-test-inputs.mjs +++ b/scripts/cross-package-test-inputs.mjs @@ -1498,11 +1498,19 @@ export const CROSS_PACKAGE_TEST_INPUTS = { // scanned them in this package (`rest-server-canonical-query-ast.test.ts`; // the three `error-response-*` arm-derivation tests) now read them there, // each bound to one relative literal. + // + // The two `examples/app-crm` files are ADR-0159 card ②'s byte-equal pin + // (`public-form-app-crm-byte-equal.test.ts`): it boots the CRM's lead + // object and its lead views, the container whose `formViews` entry is the + // first-party public form, and holds `GET /forms/contact-us` to the answer + // taken before the `form` type. An edit to either file can move that answer. globs: [ 'content/docs/protocol/objectql/state-machine.mdx', 'skills/objectstack-automation/SKILL.md', 'packages/types/src/data-error-classification.ts', 'packages/core/src/utils/import-runner.ts', + 'examples/app-crm/src/objects/index.ts', + 'examples/app-crm/src/views/lead.view.ts', 'content/**', 'docs/**', 'skills/**', diff --git a/turbo.json b/turbo.json index 49ca3cabbf4..de4a7960ff8 100644 --- a/turbo.json +++ b/turbo.json @@ -874,6 +874,8 @@ "$TURBO_ROOT$/skills/objectstack-automation/SKILL.md", "$TURBO_ROOT$/packages/types/src/data-error-classification.ts", "$TURBO_ROOT$/packages/core/src/utils/import-runner.ts", + "$TURBO_ROOT$/examples/app-crm/src/objects/index.ts", + "$TURBO_ROOT$/examples/app-crm/src/views/lead.view.ts", "$TURBO_ROOT$/content/**", "$TURBO_ROOT$/docs/**", "$TURBO_ROOT$/skills/**" From 08b199ebfa325707b536073661e4bd621483f216 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:33:37 +0000 Subject: [PATCH 18/29] =?UTF-8?q?docs(qa):=20the=20form=20waiver=20names?= =?UTF-8?q?=20the=20showcase's=20authored=20form=20and=20card=20=E2=91=A3?= =?UTF-8?q?=20as=20the=20contact-us=20mover?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- docs/qa/platform-checklist/coverage.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/qa/platform-checklist/coverage.json b/docs/qa/platform-checklist/coverage.json index 50757cb7493..1bdaa73a61e 100644 --- a/docs/qa/platform-checklist/coverage.json +++ b/docs/qa/platform-checklist/coverage.json @@ -416,7 +416,7 @@ ] }, "form": { - "waived": "WAIVED 2026-11-26 — the kind is new (ADR-0159 card ②, #37086) and no checklist item has been run against an authored `form` item yet. What exists: no app this checklist drives authors `forms:` (the showcase's contact-us form is an old `view` shape, which the anonymous doors now read through the one projection, so access-security.public-form-intake keeps driving the same door and the same answers); the type's own rules are pinned below the checklist — FormSchema, the projection and the intake layer in packages/spec/src/ui/form-item.test.ts, the two-type withdrawal, FORM_ADDRESS_TAKEN, the old-shape row removal and the package-less list refusal on both doors in packages/rest/src/public-form-two-type-withdrawal.test.ts, and the authoring rules in packages/lint/src/validate-form-items.test.ts. WHAT RETIRES THIS WAIVER — the showcase moves its contact-us form to `forms:` (card ③, #37087) or a scratch package authors one; an item then drives GET /forms/:slug and its submit for an authored form, a view override that withdraws it, and the 409 for a second form left open on the address, and the same edit replaces this waiver with `items` naming it." + "waived": "WAIVED 2026-11-26 — the kind is new (ADR-0159 card ②, #37086) and no checklist item has been run against an authored `form` item yet. What exists: the showcase authors one `form` item, `forms: [FeedbackForm]` (examples/app-showcase/src/ui/forms/feedback.form.ts, public at /forms/showcase-feedback, an address no other form holds); its contact-us form is still an old `view` shape (examples/app-showcase/src/ui/views/inquiry.view.ts), which the anonymous doors read through the one projection, so access-security.public-form-intake keeps driving the same door and the same answers. The type's own rules are pinned below the checklist — FormSchema, the projection and the intake layer in packages/spec/src/ui/form-item.test.ts, the two-type withdrawal, FORM_ADDRESS_TAKEN on save, publish and restore, the old-shape row removal and the package-less list refusal on both doors in packages/rest/src/public-form-two-type-withdrawal.test.ts, and the authoring rules in packages/lint/src/validate-form-items.test.ts. WHAT RETIRES THIS WAIVER — an item that drives GET /forms/showcase-feedback and its submit for the authored form, a `form` override that withdraws it, and the 409 for a second form left open on the address; the same edit replaces this waiver with `items` naming it. Card ④ (#37088: the examples, their translation keys and the docs move to `forms:`) moves the contact-us form, after which access-security.public-form-intake drives an authored form too." }, "view": { "items": [ From b1a299432035dbd755d74281c74f80564280b66c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:36:55 +0000 Subject: [PATCH 19/29] docs(spec,scripts): the form sharing ledger row cites the form doors, the registry row says what overlays a form, and the cross-type resolution has an anchor Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- packages/spec/liveness/form.json | 4 ++-- packages/spec/src/kernel/metadata-plugin.zod.ts | 10 +++++++--- ...metadata-protocol__src__protocol-form-reads.ts.json | 7 +++++++ 3 files changed, 16 insertions(+), 5 deletions(-) create mode 100644 scripts/adr-anchors/packages__metadata-protocol__src__protocol-form-reads.ts.json diff --git a/packages/spec/liveness/form.json b/packages/spec/liveness/form.json index 826c39814ce..d2de6de7188 100644 --- a/packages/spec/liveness/form.json +++ b/packages/spec/liveness/form.json @@ -117,8 +117,8 @@ }, "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)", + "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." }, "submitBehavior": { diff --git a/packages/spec/src/kernel/metadata-plugin.zod.ts b/packages/spec/src/kernel/metadata-plugin.zod.ts index 18920d07d22..b3f8c82af66 100644 --- a/packages/spec/src/kernel/metadata-plugin.zod.ts +++ b/packages/spec/src/kernel/metadata-plugin.zod.ts @@ -965,9 +965,13 @@ export const DEFAULT_METADATA_TYPE_REGISTRY: MetadataTypeRegistryEntryParsed[] = // MATERIALIZED into `sys_metadata` (DB-only provenance), which rides the // `allowRuntimeCreate` tier, not this flag. { type: 'view', label: 'View', filePatterns: ['**/*.view.ts', '**/*.view.yml', '**/*.view.json'], supportsOverlay: true, allowEnvironmentOverlay: true, allowRuntimeCreate: true, supportsVersioning: true, executionPinned: false, loadOrder: 50, domain: 'ui' }, - // [ADR-0159 D1] `form` carries page's flags exactly: overlayable per org but not - // per environment (the ruled scope set is `{global, org, user}`), runtime- - // creatable, versioned, unpinned, loaded with the UI tier. + // [ADR-0159 D1] `form` carries page's flags exactly. An environment does not + // overlay a packaged form in place (`allowEnvironmentOverlay: false`, the + // ADR-0005 default for a new type): it customizes one through the override + // package (ADR-0146 D2), where `form: listed`. No organization layer exists + // to write either: an organization-scoped write is refused for every type + // (ADR-0131 D6). Runtime-creatable, versioned, unpinned, loaded with the UI + // tier. { type: 'form', label: 'Form', filePatterns: ['**/*.form.ts', '**/*.form.yml', '**/*.form.json'], supportsOverlay: true, allowEnvironmentOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, executionPinned: false, loadOrder: 50, domain: 'ui' }, { type: 'page', label: 'Page', filePatterns: ['**/*.page.ts', '**/*.page.yml'], supportsOverlay: true, allowEnvironmentOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, executionPinned: false, loadOrder: 50, domain: 'ui' }, { type: 'dashboard', label: 'Dashboard', filePatterns: ['**/*.dashboard.ts', '**/*.dashboard.yml', '**/*.dashboard.json'], supportsOverlay: true, allowEnvironmentOverlay: true, allowRuntimeCreate: true, supportsVersioning: true, executionPinned: false, loadOrder: 60, domain: 'ui' }, diff --git a/scripts/adr-anchors/packages__metadata-protocol__src__protocol-form-reads.ts.json b/scripts/adr-anchors/packages__metadata-protocol__src__protocol-form-reads.ts.json new file mode 100644 index 00000000000..e605ba1929f --- /dev/null +++ b/scripts/adr-anchors/packages__metadata-protocol__src__protocol-form-reads.ts.json @@ -0,0 +1,7 @@ +{ + "file": "packages/metadata-protocol/src/protocol-form-reads.ts", + "adrs": [ + "ADR-0159" + ], + "invariant": "ADR-0159 D5, D6 rule 11: THE cross-type resolution of the effective `form` read. A package's form is resolved over both types in the one served-row order (`servedOverlayRowCandidates`): the stored `view` row that order picks at the package's address is served, as the `form` item it projects, over the package's source `form` item of that name, and a stored `form` row at the same place wins over it; a stored `view` row that carries no form at a form's name serves none (the closed reading), and only a row the order serves is projected, never every stored `view` row. Reading the `form` type alone re-opens a form a stored old-shape row withdrew or replaced; reading every stored row serves a form no layer serves. The public doors, `GET /api/v1/meta/form` and the by-name read all answer from this one resolution." +} From 67af96fb676e6e2064098f83227d2aa3fab4c6c2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 08:11:05 +0000 Subject: [PATCH 20/29] fix(scripts,rest): the examples coupling gate asks the task that runs the file; the CRM pin loads the example by path check-examples-live-imports read only a package's `#test` inputs, so a repo-project file (hashed on `#test:repo`, #16466) read as invisible even with its inputs declared. It now asks the task its package's vitest.repo-tests.json assigns the file, with three self-test cases read off rest's own split. The CRM byte-equal pin loads the two example sources through `new URL(...)`: a static import put them in rest's tsconfig.test.json zone, whose rootDir is packages/. The form changeset names the publish and restore refusals and the forms.NAME.sections keys. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .changeset/37086-form-metadata-type.md | 4 +- .../public-form-app-crm-byte-equal.test.ts | 11 +++- scripts/check-examples-live-imports.mjs | 55 ++++++++++++++++++- 3 files changed, 63 insertions(+), 7 deletions(-) diff --git a/.changeset/37086-form-metadata-type.md b/.changeset/37086-form-metadata-type.md index e2c8159ab17..25296140873 100644 --- a/.changeset/37086-form-metadata-type.md +++ b/.changeset/37086-form-metadata-type.md @@ -29,8 +29,8 @@ ADR-0159 makes a public form a `form` item: `name` (`OBJECT.KEY`, the name it is What lands with the type: -- `@objectstack/spec`: `FormSchema`, `defineForm`, the registry row (`*.form.ts|yml|json`, overlay-capable, no environment overlay), `form` in the customization package's listed types, the stack's `forms` collection, the `forms` translation family (`forms.NAME` first, the `_views.KEY` title and thank-you tails as the fallback, `_views.KEY.label` never read), the projection `projectViewForms`, the intake layer `formIntakeLayer` / `openFormAt`, and the error code `FORM_ADDRESS_TAKEN`. -- `@objectstack/metadata-protocol`: the effective `form` read resolves a form over both types in the one served-row order (a stored `view` row over a package's form keeps replacing it when the package moves to `forms:`); a `form` save, reset or delete at a package removes that package's old-shape row of the name in the same transaction (form content only — a list of the name is untouched); a `form` left open on a public address another form holds is refused with `409 FORM_ADDRESS_TAKEN`, naming both (a switched-off form that keeps its link still holds the address; a save that leaves the form closed is never refused); the override gate accepts a `form` override over a base that ships the form as an old shape; a stored body whose form content cannot be read closes the links it names and is reported once per process, at `error`, the first time the form doors read it, naming the row, the links it closes and the repair save. +- `@objectstack/spec`: `FormSchema`, `defineForm`, the registry row (`*.form.ts|yml|json`, overlay-capable, no environment overlay), `form` in the customization package's listed types, the stack's `forms` collection, the `forms` translation family (`forms.NAME` first, the `_views.KEY` title and thank-you tails as the fallback, `_views.KEY.label` never read; a form's own section copy at `forms.NAME.sections.SECTION`, with `objects.OBJECT._sections.SECTION` as its object-level default), the projection `projectViewForms`, the intake layer `formIntakeLayer` / `openFormAt`, and the error code `FORM_ADDRESS_TAKEN`. +- `@objectstack/metadata-protocol`: the effective `form` read resolves a form over both types in the one served-row order (a stored `view` row over a package's form keeps replacing it when the package moves to `forms:`); a `form` save, reset or delete at a package removes that package's old-shape row of the name in the same transaction (form content only — a list of the name is untouched); a `form` left open on a public address another form holds is refused with `409 FORM_ADDRESS_TAKEN`, naming both, on the save, on the publish of a draft whose address another form took after it was saved, and on a rollback to a version open on a held address (a switched-off form that keeps its link still holds the address; a write that leaves the form closed is never refused); the override gate accepts a `form` override over a base that ships the form as an old shape; a stored body whose form content cannot be read closes the links it names and is reported once per process, at `error`, the first time the form doors read it, naming the row, the links it closes and the repair save. - `@objectstack/rest`: `GET /forms/:slug` and its submit read candidates from the effective `form` read and judge withdrawal across `form` and `view`, effective and per-package, old shapes projected first — narrowing only, in both directions; a body that cannot be read closes the links it names. `/meta/form/NAME` refuses whom `/meta/view/NAME` refuses. `GET /meta/view` answers as before. - `@objectstack/lint`: `form-public-address-taken` (gating), `form-consumer-less` (advisory, never for an `overrides` item), `form-object-outside-closure` / `form-object-unknown`; the i18n walk emits `forms.NAME.*` keys and no `_views` tail for a `form` item. No new advisory for an old shape. - `@objectstack/metadata`, `@objectstack/metadata-core`, `@objectstack/objectql`, `@objectstack/runtime`, `@objectstack/cli`: the `forms` collection is loaded, typed, registered and counted for i18n coverage like every other. diff --git a/packages/rest/src/public-form-app-crm-byte-equal.test.ts b/packages/rest/src/public-form-app-crm-byte-equal.test.ts index 4d1ec849128..2bcd907268c 100644 --- a/packages/rest/src/public-form-app-crm-byte-equal.test.ts +++ b/packages/rest/src/public-form-app-crm-byte-equal.test.ts @@ -14,13 +14,20 @@ */ import { afterAll, describe, expect, it } from 'vitest'; import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; import { SysMetadataAuditObject, SysMetadataCommitObject, SysMetadataHistoryObject, SysMetadataObject } from '@objectstack/metadata-core'; import { RestServer } from './rest-server'; -import * as CRM_OBJECTS from '../../../examples/app-crm/src/objects/index'; -import { LeadViews } from '../../../examples/app-crm/src/views/lead.view'; + +// The example's two sources, loaded by path: a static import would put them in +// this package's `tsconfig.test.json` zone, whose `rootDir` is `packages/`. +// Both are declared as `@objectstack/rest#test:repo` inputs in the cross-package test-input registry. +const CRM_OBJECTS_SOURCE = new URL('../../../examples/app-crm/src/objects/index.ts', import.meta.url); +const CRM_LEAD_VIEWS_SOURCE = new URL('../../../examples/app-crm/src/views/lead.view.ts', import.meta.url); +const CRM_OBJECTS: Record = await import(fileURLToPath(CRM_OBJECTS_SOURCE)); +const { LeadViews } = (await import(fileURLToPath(CRM_LEAD_VIEWS_SOURCE))) as { LeadViews: unknown }; const BEFORE = JSON.parse(readFileSync(new URL('./form-old-shape-before.json', import.meta.url), 'utf8')); diff --git a/scripts/check-examples-live-imports.mjs b/scripts/check-examples-live-imports.mjs index 41333736df1..eb0a2abf5e2 100644 --- a/scripts/check-examples-live-imports.mjs +++ b/scripts/check-examples-live-imports.mjs @@ -412,6 +412,12 @@ function owningPackage(fileAbs) { * Packages whose `#test` task declares an `examples/...` input glob in * turbo.json, mapped to those globs in repo-relative form (the `$TURBO_ROOT$/` * prefix stripped) so they can be matched against a coupling target. + * + * A package that splits its suite into two vitest projects (#16466) runs the + * files its `vitest.repo-tests.json` lists under `#test:repo` instead: those + * globs are keyed `#test:repo`, and {@link declaredGlobsFor} asks the + * task that actually runs the file. A `#test` glob never covers a repo-project + * file, nor the reverse: each task hashes its own inputs. */ function packagesWithExampleInputs() { const declared = new Map(); @@ -423,15 +429,34 @@ function packagesWithExampleInputs() { } const tasks = turbo.tasks ?? turbo.pipeline ?? {}; for (const [taskId, cfg] of Object.entries(tasks)) { - if (!taskId.endsWith('#test')) continue; + const repoTask = taskId.endsWith('#test:repo'); + if (!taskId.endsWith('#test') && !repoTask) continue; const globs = (cfg?.inputs ?? []) .filter((g) => typeof g === 'string' && g.includes('examples/')) .map((g) => g.replace(/^\$TURBO_ROOT\$\//, '')); - if (globs.length) declared.set(taskId.slice(0, -'#test'.length), globs); + if (globs.length) declared.set(repoTask ? taskId : taskId.slice(0, -'#test'.length), globs); } return declared; } +/** Whether `fileAbs` is listed in its package's `vitest.repo-tests.json`, so `#test:repo` runs it. */ +function inRepoProject(pkgDir, fileAbs) { + try { + const listed = JSON.parse(readFileSync(join(REPO_ROOT, pkgDir, 'vitest.repo-tests.json'), 'utf8')); + const own = posix.normalize(relative(join(REPO_ROOT, pkgDir), fileAbs).split(sep).join('/')); + return Array.isArray(listed) && listed.some((entry) => typeof entry === 'string' && posix.normalize(entry) === own); + } catch { + return false; + } +} + +/** The `examples/` input globs of the turbo task that runs this test file. */ +function declaredGlobsFor(exampleInputs, pkg, fileAbs) { + const name = pkg?.manifest?.name ?? '(unknown)'; + if (pkg?.dir !== undefined && inRepoProject(pkg.dir, fileAbs)) return exampleInputs.get(`${name}#test:repo`) ?? []; + return exampleInputs.get(name) ?? []; +} + /** * Does one declared input glob cover this coupling target? * @@ -533,7 +558,7 @@ function collect() { // Only the by-path couplings need an input glob: a by-package-name coupling // on a declared edge is already reachable through the dependency graph. - const declaredGlobs = exampleInputs.get(pkgName) ?? []; + const declaredGlobs = declaredGlobsFor(exampleInputs, pkg, abs); const uncoveredTargets = uncoveredTargetsOf(byPath, abs, declaredGlobs); let visibility; @@ -869,6 +894,30 @@ function selfTest() { Object.values(INVISIBLE_COUPLINGS).every((e) => (e.note ?? '').trim().length >= 40), ], + // ── the task that runs the file: a repo-project file is hashed on `#test:repo` ── + // + // Read off rest's own split (#16466): the first file its + // `vitest.repo-tests.json` lists is asked of the `#test:repo` globs, and a + // file it does not list of the `#test` globs, never the other task's. + ...(() => { + const restDir = 'packages/rest'; + let listed = []; + try { + listed = JSON.parse(readFileSync(join(REPO_ROOT, restDir, 'vitest.repo-tests.json'), 'utf8')); + } catch { + listed = []; + } + const pkg = { dir: restDir, manifest: { name: '@objectstack/rest' } }; + const inputs = new Map([['@objectstack/rest', ['examples/a/**']], ['@objectstack/rest#test:repo', ['examples/b/**']]]); + const repoFile = join(REPO_ROOT, restDir, String(listed[0] ?? '')); + const localFile = join(REPO_ROOT, restDir, 'src/__not-listed__.test.ts'); + return [ + ['rest lists at least one repo-project file', listed.length > 0 && inRepoProject(restDir, repoFile)], + ['a listed file is asked of the #test:repo globs', declaredGlobsFor(inputs, pkg, repoFile).join() === 'examples/b/**'], + ['an unlisted file is asked of the #test globs', declaredGlobsFor(inputs, pkg, localFile).join() === 'examples/a/**'], + ]; + })(), + // ── input-glob coverage: the check that lets a radius be NARROW safely ── // // Pinned because a false positive here is silent and total: a coupling From 7ffc21f52c687f6f47f2b8661e1b58e97b3a7932 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 12:59:32 +0000 Subject: [PATCH 21/29] fix(metadata-protocol): the undo of a refused publish and a commit revert put back the old-shape rows a form write removed Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .../src/protocol-form-writes.ts | 69 +++++++++++++++++-- .../src/protocol-history-and-publish.ts | 47 +++++++++++-- packages/metadata-protocol/src/protocol.ts | 4 +- ...iew-expansion-reconcile-call-sites.test.ts | 2 + 4 files changed, 106 insertions(+), 16 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-form-writes.ts b/packages/metadata-protocol/src/protocol-form-writes.ts index 187a768e645..061ae4c3043 100644 --- a/packages/metadata-protocol/src/protocol-form-writes.ts +++ b/packages/metadata-protocol/src/protocol-form-writes.ts @@ -11,7 +11,9 @@ * open public address another form already holds. * - {@link oldShapeFormRowRemovals} — what a `form` save, reset or delete at * `(package, name)` removes of the old-shape row that carries that form at - * that address, in the same transaction. + * that address, in the same transaction; and + * {@link restoreOldShapeFormRowRemovals}, which puts those rows back when + * the write that removed them is undone. * * Each judges bodies through THE projection ({@link projectViewForms}), never * by re-reading `formViews` by hand. @@ -184,6 +186,16 @@ export type OldShapeFormRowRemoval = | { readonly kind: 'delete'; readonly row: { readonly name: string; readonly packageId: string | null } } | { readonly kind: 'resave'; readonly row: { readonly name: string; readonly packageId: string | null }; readonly body: Record }; +/** + * [ADR-0159 D5] An {@link OldShapeFormRowRemoval} as it was applied: with the + * history version the row stood at before the write (the stored row's + * `version`, `null` when the row carried none), so a door that undoes the + * `form` write puts the row back at that version + * ({@link restoreOldShapeFormRowRemovals}), and a package commit records it as + * a row the publish edited (the commit's revert restores it). + */ +export type AppliedOldShapeFormRowRemoval = OldShapeFormRowRemoval & { readonly replacedVersion: number | null }; + /** * [ADR-0159 D5, card ② item 5] What a `form` save, reset or delete at * `(packageId, name)` does to the stored old-shape row that carries that form @@ -244,22 +256,27 @@ export function oldShapeFormRowRemovals( * that carries the form, through the repository the `form` write wrote with. * Called INSIDE the `form` write's transaction, so a `form` write that fails * leaves both rows as they were (the repository's own `withTxn` joins the - * ambient one, ADR-0067 D2). Returns the rows it changed, for the registry - * heal the caller runs once the transaction has committed. + * ambient one, ADR-0067 D2). Returns the rows it changed, each with the + * version it replaced, for the registry heal the caller runs once the + * transaction has committed, and for the undo of that write. */ export async function applyOldShapeFormRowRemovals( host: Pick, args: { name: string; packageId: string | null; actor: string | null; source: string }, -): Promise { +): Promise { const rows = await host.readActiveOverlayRows({ type: 'view' }); - const at: Array<{ name: string; data: unknown; hash: string | null }> = []; + const at: Array<{ name: string; data: unknown; hash: string | null; version: number | null }> = []; for (const row of rows) { if (((row?.package_id ?? null) || null) !== (args.packageId || null)) continue; const entry = host.storedOverlayEntries({ type: 'view' }, [row])[0]; if (entry === undefined) continue; - at.push({ name: entry.name, data: entry.data, hash: typeof row?.checksum === 'string' ? row.checksum : null }); + at.push({ + name: entry.name, data: entry.data, hash: typeof row?.checksum === 'string' ? row.checksum : null, + version: typeof row?.version === 'number' ? row.version : null, + }); } - const removals = oldShapeFormRowRemovals(at, args.name, args.packageId); + const removals: AppliedOldShapeFormRowRemoval[] = oldShapeFormRowRemovals(at, args.name, args.packageId) + .map((removal) => ({ ...removal, replacedVersion: at.find((row) => row.name === removal.row.name)?.version ?? null })); if (removals.length === 0) return removals; const repo = host.getOverlayRepo(); for (const removal of removals) { @@ -301,3 +318,41 @@ export async function healOldShapeFormRowRemovals( } } } + +/** + * [ADR-0159 D5, ADR-0067 D2] Put back each old-shape row a `form` write removed + * or re-saved ({@link applyOldShapeFormRowRemovals}), when that write is undone + * by hand: a refused package publish on a runtime that cannot roll back + * (`undoLandedPromotions`). Newest first, each row is restored to the version + * it stood at before the write, written again when it was deleted, under the + * package it was bound to, and the registry is healed from what the store then + * serves. The removal and its undo are one pair: the old-shape row stands + * again exactly as it stood, whatever it held (a form, or that form switched + * off), so the undone write leaves the address answering what it answered + * before. + * + * Throws on the first row it cannot put back (no recorded version, or the + * store's refusal), so the caller reports the item as not undone. + */ +export async function restoreOldShapeFormRowRemovals( + host: Pick, + repo: Pick, 'restoreVersion'>, + removals: readonly AppliedOldShapeFormRowRemoval[], + options: { actor: string | null; source: string; message: string }, +): Promise { + for (const removal of [...removals].reverse()) { + if (removal.replacedVersion === null) { + throw new Error( + `the old-shape view row '${removal.row.name}' the form write ${removal.kind === 'delete' ? 'removed' : 're-saved'} ` + + 'was recorded at no version, so it cannot be put back', + ); + } + const ref = { type: 'view', name: removal.row.name, org: 'env' } as Parameters[0]; + await repo.restoreVersion(ref, removal.replacedVersion, { + ...options, + intent: host.isArtifactBacked('view', removal.row.name) ? 'override-artifact' : 'runtime-only', + packageId: removal.row.packageId, + }); + await host.restoreArtifactRegistryView('view', removal.row.name, null, removal.row.packageId); + } +} diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index 3def2e34ca2..f9e6b206ec2 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -23,7 +23,7 @@ * not move. */ -import { applyOldShapeFormRowRemovals, formTypeWriteRefusal, healOldShapeFormRowRemovals, type OldShapeFormRowRemoval } from './protocol-form-writes.js'; +import { applyOldShapeFormRowRemovals, formTypeWriteRefusal, healOldShapeFormRowRemovals, restoreOldShapeFormRowRemovals, type AppliedOldShapeFormRowRemoval } from './protocol-form-writes.js'; import { stampHtmlPageRequires } from './runtime-authoring-gate.js'; import type { RuntimeAuthoringIssue, RuntimePendingDeclarations } from './runtime-authoring-gate.js'; import { DraftConflictError, packagelessAddressAmbiguityRefusal } from './sys-metadata-repository.js'; @@ -85,6 +85,12 @@ type LandedPromotion = { version: string; /** The draft row the promotion consumed. */ promotedDraft?: { body: unknown; hash: string }; + /** + * [ADR-0159 D5] The old-shape `view` rows a `form` promotion removed or + * re-saved at its address, each with the version it replaced: the undo + * puts them back before it undoes the promotion itself. + */ + removedOldShapeRows?: readonly AppliedOldShapeFormRowRemoval[]; }; /** @@ -108,7 +114,10 @@ function unwrittenPromotionError(type: string, name: string): Error { * moves an ADR-0067 D3 revert makes, read off the same pre-publish capture) — * and the draft row the promotion consumed is put back as the pending draft, * byte for byte, so its hash and its version token are the ones the author - * holds. + * holds. [ADR-0159 D5] A `form` promotion also removed (or re-saved) the + * old-shape `view` row of its address; that row is put back first, at the + * version it stood at ({@link restoreOldShapeFormRowRemovals}), so an undo + * that stops part-way never leaves the address without it. * * Each undo step appends its own history event, as a revert does: history is * append-only (D3), so the log records that the publish happened and was @@ -152,6 +161,9 @@ async function undoLandedPromotions(host: Pick 0) { + await restoreOldShapeFormRowRemovals(host, args.repo, item.removedOldShapeRows, { actor, source, message }); + } if (!item.promotedDraft) { throw new Error(`the draft ${item.d.type}/${item.d.name} consumed was not captured, so it cannot be put back`); } @@ -777,8 +789,13 @@ export class ProtocolHistoryAndPublishFacet { * discipline — per the maintainer's ruling, no parallel top-level map. */ advisories: RuntimeAuthoringIssue[]; - /** What `repo.promoteDraft` wrote. Absent exactly when `judgeOnly` was stated. */ - result?: { version: string; seq: number; item: MetadataItem; packageId: string | null }; + /** + * What `repo.promoteDraft` wrote. Absent exactly when `judgeOnly` + * was stated. [ADR-0159 D5] For a `form`, also the old-shape rows + * the same transaction removed or re-saved, each with the version + * it replaced (absent when it changed none). + */ + result?: { version: string; seq: number; item: MetadataItem; packageId: string | null; removedOldShapeRows?: readonly AppliedOldShapeFormRowRemoval[] }; /** * [#32369] What a judge-only call judged: the draft body the * promotion would make active and the package it would write it @@ -1456,7 +1473,7 @@ export class ProtocolHistoryAndPublishFacet { // same transaction, as the published save does // ({@link applyOldShapeFormRowRemovals}); the registry is healed // after the commit. ⛔ Form content only. - let removedOldShapeRows: OldShapeFormRowRemoval[] = []; + let removedOldShapeRows: AppliedOldShapeFormRowRemoval[] = []; const promoteFormAware = async (promote: () => Promise): Promise => { if (singularType !== 'form' || request.judgeOnly) return promote(); const run = async () => { @@ -1508,7 +1525,7 @@ export class ProtocolHistoryAndPublishFacet { return { singularType, advisories: runtimeAdvisories, - result, + result: removedOldShapeRows.length > 0 ? { ...result, removedOldShapeRows } : result, ...(draftForGate ? { promotedDraft: { body: draftForGate.body, hash: draftForGate.hash } } : {}), }; } catch (err: any) { @@ -2372,6 +2389,7 @@ export class ProtocolHistoryAndPublishFacet { seq: result.seq, advisories, ...(promotedDraft ? { promotedDraft } : {}), + ...(result.removedOldShapeRows?.length ? { removedOldShapeRows: result.removedOldShapeRows } : {}), }); if (typeof result.seq === 'number') publishedSeqs.push(result.seq); } catch (e: unknown) { @@ -2411,13 +2429,28 @@ export class ProtocolHistoryAndPublishFacet { // [#22877] Keyed by member too: two members of one name // are two plan items. const promotedKeys = new Set(promoted.map((p) => commitPlanKey(p.d))); + const committedItems = commitItems.filter((it) => promotedKeys.has(commitPlanKey(it))); + // [ADR-0159 D5, ADR-0067 D3] …and every old-shape `view` row a + // `form` promotion removed or re-saved: a row this publish + // edited, recorded at the version it stood at before the + // publish (the first removal of it; a row the batch also + // promotes keeps its own pre-publish capture), so the + // commit's revert restores it as it restores any edited row. + for (const p of promoted) { + for (const removal of p.removedOldShapeRows ?? []) { + const item: CommitPlanItem = { + type: 'view', name: removal.row.name, existedBefore: true, prevVersion: removal.replacedVersion, + }; + if (!committedItems.some((it) => commitPlanKey(it) === commitPlanKey(item))) committedItems.push(item); + } + } commit = await this.recordPackageCommit({ packageId: request.packageId, operation: 'apply', ...(request.message ? { message: request.message } : {}), ...(request.actor ? { actor: request.actor } : {}), ...(request.aiModel ? { aiModel: request.aiModel } : {}), - items: commitItems.filter((it) => promotedKeys.has(commitPlanKey(it))), + items: committedItems, ...(publishedSeqs.length ? { eventSeqStart: Math.min(...publishedSeqs), eventSeqEnd: Math.max(...publishedSeqs) } : {}), diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 0b2b200c63f..86ea7e5f781 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -9825,8 +9825,8 @@ export class ObjectStackProtocolImplementation implements * discipline — per the maintainer's ruling, no parallel top-level map. */ advisories: RuntimeAuthoringIssue[]; - /** What the promotion wrote. Absent exactly when `judgeOnly` was stated. */ - result?: { version: string; seq: number; item: MetadataItem; packageId: string | null }; + /** What the promotion wrote (with a `form`'s removed old-shape rows). Absent exactly when `judgeOnly` was stated. */ + result?: { version: string; seq: number; item: MetadataItem; packageId: string | null; removedOldShapeRows?: readonly import('./protocol-form-writes.js').AppliedOldShapeFormRowRemoval[] }; /** [#32396] The draft row the promotion consumed. Absent when nothing was written. */ promotedDraft?: { body: unknown; hash: string }; /** [#32369] What a judge-only call judged: the draft body and the package it would go live in. */ diff --git a/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts b/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts index d40967ba011..a41e56ff08d 100644 --- a/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts +++ b/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts @@ -182,6 +182,8 @@ const WRITES: ReadonlyArray<{ readonly member: string; readonly verb: string; re // its name in the same transaction; each door heals the registry from the rows handed back. { member: 'applyOldShapeFormRowRemovals', verb: 'repo.delete(', route: { handedTo: 'module callers', then: 'healOldShapeFormRowRemovals' } }, { member: 'applyOldShapeFormRowRemovals', verb: 'repo.put(', route: { handedTo: 'module callers', then: 'healOldShapeFormRowRemovals' } }, + // [ADR-0159 D5] …and the undo of that write on a runtime that cannot roll back puts each row back, healed. + { member: 'restoreOldShapeFormRowRemovals', verb: 'repo.restoreVersion(', route: { sameMember: 'restoreArtifactRegistryView' } }, ]; /** The verb as `WRITES` spells it: no whitespace after its open paren, [#29985] the class as `this`. */ From 7b0f2f8c77502d44bdb4639f8f3f6d22d0e75524 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:02:22 +0000 Subject: [PATCH 22/29] test(rest): the undo of a refused package publish and a commit revert leave the old-shape row as it was, on an engine that cannot roll back Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .../public-form-two-type-withdrawal.test.ts | 106 +++++++++++++++++- 1 file changed, 104 insertions(+), 2 deletions(-) diff --git a/packages/rest/src/public-form-two-type-withdrawal.test.ts b/packages/rest/src/public-form-two-type-withdrawal.test.ts index f2ee78c63a1..645f7a754df 100644 --- a/packages/rest/src/public-form-two-type-withdrawal.test.ts +++ b/packages/rest/src/public-form-two-type-withdrawal.test.ts @@ -94,8 +94,22 @@ function makeRes() { interface Answer { status: number; body: any } -async function boot(ships: { forms?: unknown[]; views?: unknown[]; objects?: unknown[] }, opts: { i18n?: unknown } = {}) { - const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any); +/** + * A store that cannot roll a transaction back: a `SqlDriver` that declares + * `supports.transactionsUnsupported`, the shape the remote Turso transport + * takes (as `rest-batch-no-rollback-driver.test.ts` builds it). `ObjectQL` + * then runs a transaction's callback with no transaction, and + * `engineCanRollBack` answers no. + */ +class NoRollbackSqlDriver extends SqlDriver { + override get supports() { + return { ...super.supports, transactionsUnsupported: true }; + } +} + +async function boot(ships: { forms?: unknown[]; views?: unknown[]; objects?: unknown[] }, opts: { i18n?: unknown; canRollBack?: boolean } = {}) { + const driverOptions = { client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any; + const driver = opts.canRollBack === false ? new NoRollbackSqlDriver(driverOptions) : new SqlDriver(driverOptions); const engine = new ObjectQL(); engine.registerDriver(driver, true); await engine.init(); @@ -966,3 +980,91 @@ describe('[ADR-0159 D5] the old shapes answer what they answered before the type expect([submitted.status, submitted.body?.code]).toEqual([BEFORE['data-object-submit'].status, BEFORE['data-object-submit'].body?.code]); }); }); + +describe('[ADR-0159 D5, ADR-0067 D2 and D3] the undo of a `form` publish puts back the old-shape row the publish removed', () => { + const engines: ObjectQL[] = []; + afterAll(async () => { + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + const SECOND = `${OBJECT}.second`; + const NEW_SLUG = 'renamed-37086'; + /** + * The base ships the form in an old-shape container, open on {@link SLUG}; the pair + * stores its own old-shape row of the name with the form switched off. + */ + const pairWithItsOwnOldShapeRow = async (canRollBack: boolean): Promise => { + const b = await boot({ views: [container(true)] }, { canRollBack }); + engines.push(b.engine); + expect(engineCanRollBackOf(b)).toBe(canRollBack); + await b.install(PAIR); + await b.saveInto('view', PAIR, viewItem(false, overrides)); + await closedOnBothDoors(b); + return b; + }; + const engineCanRollBackOf = (b: Booted) => (b.protocol as any).engine?.getDriverByName?.((b.protocol as any).engine?.getDefaultDriverName?.())?.supports?.transactionsUnsupported !== true; + /** Two `form` drafts in the pair: the form of the name on {@link NEW_SLUG}, and a second form on `secondSlug`. */ + const twoFormDrafts = async (b: Booted, secondSlug: string) => { + await b.protocol.saveMetaItem({ type: 'form', name: NAME, packageId: PAIR, mode: 'draft', item: formItem(true, overrides, NEW_SLUG) }); + await b.protocol.saveMetaItem({ type: 'form', name: SECOND, packageId: PAIR, mode: 'draft', item: { ...formItem(true, {}, secondSlug), name: SECOND } }); + }; + + it('a package publish refused part-way on an engine that cannot roll back leaves the old-shape row as it was (ablate: the restore of the removed rows in the undo)', async () => { + const b = await pairWithItsOwnOldShapeRow(false); + const before = await rawRows(b, 'view', NAME, PAIR); + expect(before.length).toBe(1); + // Both drafts take the same new link: each passes the judging pass, and the + // second is refused once the first holds the link, after its promotion. + await twoFormDrafts(b, NEW_SLUG); + const answer: any = await b.protocol.publishPackageDrafts({ packageId: PAIR }); + expect(answer.success).toBe(false); + expect(answer.failed.map((f: any) => [f.name, f.code])).toContainEqual([SECOND, 'FORM_ADDRESS_TAKEN']); + expect(await rawRows(b, 'form', NAME, PAIR)).toEqual([]); + expect(await rawRows(b, 'view', NAME, PAIR)).toEqual(before); + await closedOnBothDoors(b); + await closedOnBothDoors(b, NEW_SLUG); + }); + + it('CONTROL: the same package publish with the second form on another link is published, and the form\'s promotion removes the old-shape row', async () => { + const b = await pairWithItsOwnOldShapeRow(false); + await twoFormDrafts(b, OTHER_SLUG); + const answer: any = await b.protocol.publishPackageDrafts({ packageId: PAIR }); + expect(answer.success, JSON.stringify(answer.failed)).toBe(true); + expect(await rawRows(b, 'view', NAME, PAIR)).toEqual([]); + expect((await rawRows(b, 'form', NAME, PAIR)).length).toBe(1); + await openOnBothDoors(b, NEW_SLUG); + }); + + for (const canRollBack of [false, true]) { + it(`a commit revert puts back the old-shape row the commit's \`form\` publish removed, at its version (${canRollBack ? 'an engine that can roll back' : 'an engine that cannot roll back'}; ablate: the removed rows in the commit plan)`, async () => { + const b = await pairWithItsOwnOldShapeRow(canRollBack); + const before = await rawRows(b, 'view', NAME, PAIR); + await b.protocol.saveMetaItem({ type: 'form', name: NAME, packageId: PAIR, mode: 'draft', item: formItem(false, overrides) }); + const published: any = await b.protocol.publishPackageDrafts({ packageId: PAIR }); + expect(published.success, JSON.stringify(published.failed)).toBe(true); + expect(await rawRows(b, 'view', NAME, PAIR)).toEqual([]); + const reverted: any = await b.protocol.revertCommit({ commitId: published.commitId, packageId: PAIR }); + expect(reverted.failed).toEqual([]); + expect(reverted.reverted).toEqual(expect.arrayContaining([ + { type: 'form', name: NAME, action: 'removed' }, + { type: 'view', name: NAME, action: 'restored' }, + ])); + expect(await rawRows(b, 'form', NAME, PAIR)).toEqual([]); + expect((await rawRows(b, 'view', NAME, PAIR)).map((r) => r.metadata)).toEqual(before.map((r) => r.metadata)); + await closedOnBothDoors(b); + }); + } + + it('CONTROL: the revert of a `form` publish that removed no old-shape row removes the form and restores nothing else', async () => { + const b = await boot({ views: [container(true)] }, { canRollBack: false }); + engines.push(b.engine); + await b.install(PAIR); + await b.protocol.saveMetaItem({ type: 'form', name: NAME, packageId: PAIR, mode: 'draft', item: formItem(false, overrides) }); + const published: any = await b.protocol.publishPackageDrafts({ packageId: PAIR }); + expect(published.success, JSON.stringify(published.failed)).toBe(true); + await closedOnBothDoors(b); + const reverted: any = await b.protocol.revertCommit({ commitId: published.commitId, packageId: PAIR }); + expect(reverted.reverted).toEqual([{ type: 'form', name: NAME, action: 'removed' }]); + expect(await rawRows(b, 'view', NAME, PAIR)).toEqual([]); + await openOnBothDoors(b); + }); +}); From 8ccb511ce47fbba589b076e6739b53d634f0efbd Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:15:50 +0000 Subject: [PATCH 23/29] fix(lint,cli): a form item's section copy is extracted, covered and judged at its own forms node, the object-level slot its default Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- packages/cli/src/utils/i18n-bundle-extract.ts | 7 ++ packages/cli/src/utils/i18n-coverage.ts | 12 +++- .../i18n-form-section-entry-coverage.test.ts | 68 +++++++++++++++++++ packages/lint/src/i18n-walk.ts | 65 ++++++++++++++---- .../validate-translation-references.test.ts | 22 ++++++ .../src/validate-translation-references.ts | 62 +++++++++++++++++ 6 files changed, 223 insertions(+), 13 deletions(-) diff --git a/packages/cli/src/utils/i18n-bundle-extract.ts b/packages/cli/src/utils/i18n-bundle-extract.ts index c632d6935ab..ab76a828266 100644 --- a/packages/cli/src/utils/i18n-bundle-extract.ts +++ b/packages/cli/src/utils/i18n-bundle-extract.ts @@ -217,6 +217,13 @@ export function extractTranslations(config: any, opts: ExtractOptions = {}): Ext const existingValue = lookupDeep(existing[locale], entry.path); if (existingValue !== undefined && existingValue !== '') { value = String(existingValue); + } else if (entry.fallbackPath !== undefined) { + // [ADR-0159 D8] A translation at the address the translator falls + // back to already translates the string: no value is scaffolded at + // the first address, where an empty or `[TODO]` one would be read + // ahead of it. + const fallbackValue = lookupDeep(existing[locale], entry.fallbackPath); + if (fallbackValue !== undefined && fallbackValue !== '') continue; } } if (value === undefined) { diff --git a/packages/cli/src/utils/i18n-coverage.ts b/packages/cli/src/utils/i18n-coverage.ts index 427966f034f..0ffd7b84ee9 100644 --- a/packages/cli/src/utils/i18n-coverage.ts +++ b/packages/cli/src/utils/i18n-coverage.ts @@ -295,6 +295,12 @@ interface ExpectedKey { source: CoverageIssue['source']; /** Lookup path expressed as an array of segments. */ path: string[]; + /** + * [ADR-0159 D8] The address the translator reads when a bundle has no value + * at {@link path} (the walker's `ExpectedEntry.fallbackPath`): a value there + * translates the string too. + */ + fallbackPath?: string[]; /** Friendly display key (joined with dots). */ displayKey: string; /** Description shown in the issue message when the key is missing. */ @@ -517,6 +523,7 @@ function collectExpectedKeys(config: any): ExpectedKey[] { return { source, path: entry.path, + ...(entry.fallbackPath ? { fallbackPath: entry.fallbackPath } : {}), displayKey: entry.path.join('.'), context: describeEntry(entry, source), inline: entry.inline, @@ -735,7 +742,8 @@ export function computeI18nCoverage(config: any, opts: CoverageOptions = {}): Co (key) => key.inline !== undefined || inlineLocaleAny(key.inlineLocales) !== undefined - || authoredInBundle(key.path), + || authoredInBundle(key.path) + || (key.fallbackPath !== undefined && authoredInBundle(key.fallbackPath)), ); // The platform baseline is dropped from the POPULATION, not from the issue @@ -772,7 +780,9 @@ export function computeI18nCoverage(config: any, opts: CoverageOptions = {}): Co // text a reader of the default locale sees, so `inlineLocaleAny` // stands in for `inline` when the author wrote a map instead of a // string. + // [ADR-0159 D8] 1b. The address the translator falls back to. const value = lookupKey(data, key.path) + ?? (key.fallbackPath !== undefined ? lookupKey(data, key.fallbackPath) : undefined) ?? inlineLocaleText(key.inlineLocales, locale) ?? (locale === defaultLocale ? (key.inline ?? inlineLocaleAny(key.inlineLocales)) : undefined); if (value !== undefined) { diff --git a/packages/cli/test/i18n-form-section-entry-coverage.test.ts b/packages/cli/test/i18n-form-section-entry-coverage.test.ts index 3807c9082ba..935bf580bba 100644 --- a/packages/cli/test/i18n-form-section-entry-coverage.test.ts +++ b/packages/cli/test/i18n-form-section-entry-coverage.test.ts @@ -121,3 +121,71 @@ describe('i18n walker — a form section entry\'s copy, `_sections.
.fie expect(covered).toEqual([]); }); }); + +// [ADR-0159 D8] An authored `form` item's section copy is read at the form's +// own node, `forms..sections.
…`, and at the object-level +// default `objects.._sections.
…` for each key the node lacks. +describe('i18n walker — a `form` item\'s sections, `forms..sections.
…`', () => { + const FORM = 'crm_case.intake'; + const formConfig = (translations: unknown[] = []) => ({ + i18n: { defaultLocale: 'en', supportedLocales: ['en', 'zh-CN'] }, + objects: [{ + name: 'crm_case', + label: 'Case', + fields: { subject: { type: 'text', label: 'Subject' }, contact_name: { type: 'text', label: 'Contact name' } }, + }], + forms: [{ + name: FORM, + object: 'crm_case', + type: 'simple', + sections: [ + { name: 'about', label: 'About you', description: 'Who is asking', fields: [{ field: 'contact_name', label: 'Your name', helpText: 'As on your ID' }, 'subject'] }, + { label: 'Nameless', fields: ['subject'] }, + ], + }], + translations, + }); + const formKeys = (config: any) => collectExpectedEntries(config) + .map((e) => e.path.join('.')) + .filter((p) => p.startsWith(`forms.${FORM}.sections.`) || p.includes('._sections.')); + const zhMissing = (translations: unknown[]) => computeI18nCoverage(formConfig(translations)).issues + .filter((i) => i.locale === 'zh-CN' && (i.key.includes('.sections.') || i.key.includes('._sections.'))) + .map((i) => i.key) + .sort(); + + it('emits each named section\'s authored copy at the form\'s own node, with the object-level slot as its fallback', () => { + expect(formKeys(formConfig()).sort()).toEqual([ + `forms.${FORM}.sections.about.description`, + `forms.${FORM}.sections.about.fields.contact_name.helpText`, + `forms.${FORM}.sections.about.fields.contact_name.label`, + `forms.${FORM}.sections.about.label`, + ]); + const label = collectExpectedEntries(formConfig()).find((e) => e.path.join('.') === `forms.${FORM}.sections.about.label`); + expect(label?.fallbackPath?.join('.')).toBe('objects.crm_case._sections.about.label'); + }); + + it('the coverage gate counts the section translated at either address, and reports it untranslated at neither', () => { + expect(zhMissing([{ 'zh-CN': { objects: { crm_case: { label: '工单' } } } }])).toEqual([ + `forms.${FORM}.sections.about.description`, + `forms.${FORM}.sections.about.fields.contact_name.helpText`, + `forms.${FORM}.sections.about.fields.contact_name.label`, + `forms.${FORM}.sections.about.label`, + ]); + const atTheFormsNode = { label: '关于您', description: '提问者', fields: { contact_name: { label: '您的姓名', helpText: '与证件一致' } } }; + expect(zhMissing([{ 'zh-CN': { objects: { crm_case: { label: '工单' } }, forms: { [FORM]: { sections: { about: atTheFormsNode } } } } }])).toEqual([]); + expect(zhMissing([{ 'zh-CN': { objects: { crm_case: { label: '工单', _sections: { about: atTheFormsNode } } } } }])).toEqual([]); + }); + + it('`os i18n extract` writes the form\'s own node, and no translated-locale value over a translation the object-level slot holds', () => { + const en: any = extractTranslations(formConfig(), { locales: ['en'] }).bundles.en; + expect(en?.forms?.[FORM]?.sections?.about?.label).toBe('About you'); + expect(en?.objects?.crm_case?._sections).toBeUndefined(); + const zh: any = extractTranslations( + formConfig([{ 'zh-CN': { objects: { crm_case: { _sections: { about: { label: '关于您' } } } } } }]), + { locales: ['zh-CN'], fill: 'todo' }, + ).bundles['zh-CN']; + expect(zh?.forms?.[FORM]?.sections?.about?.label).toBeUndefined(); + // CONTROL: a key the object-level slot does not hold is scaffolded at the form's node. + expect(zh?.forms?.[FORM]?.sections?.about?.description).toBe('[TODO] Who is asking'); + }); +}); diff --git a/packages/lint/src/i18n-walk.ts b/packages/lint/src/i18n-walk.ts index 2c79a816de8..cd46652b302 100644 --- a/packages/lint/src/i18n-walk.ts +++ b/packages/lint/src/i18n-walk.ts @@ -128,6 +128,11 @@ * pages..components..items..label (a `page:tabs` item label) * pages..components..submitBehavior.title / .message * (an `object-form`'s thank-you panel) + * forms..label / .description / .title (an authored `form` item, ADR-0159 D8) + * forms..submitBehavior.title / .message + * forms..sections.
.label / .description + * forms..sections.
.fields..{label,placeholder,helpText} + * (each read before `objects.._sections.…`) * flows..label * flows..screens..title (#7646 / #11287) * flows..screens..description (#22507) @@ -201,6 +206,18 @@ import { walkPageComponents } from './page-walk.js'; export interface ExpectedEntry { /** Lookup path expressed as an array of segments. */ path: string[]; + /** + * [ADR-0159 D8] The address the translator reads when a bundle has no value + * at {@link path}: a `form` item's section copy is read at + * `forms..sections.
…` first and at the object-level default + * `objects.._sections.
…` for each key the form's node + * lacks. A bundle that carries either has translated the string, so the + * coverage gate counts it covered, and `os i18n extract` scaffolds no + * translated-locale value over one the default already holds. + * + * Unset (every other entry): {@link path} is the one address. + */ + fallbackPath?: string[]; /** * Value `os i18n extract` seeds the default-locale skeleton with — the * English literal on the schema, or the fallback the renderer displays when @@ -555,7 +572,7 @@ function pushViewEmptyState(out: ExpectedEntry[], viewPath: string[], view: any, pushEntry(out, [...viewPath, 'emptyState', 'message'], emptyState.message, 'view', { objectName }); } -type EntryScope = Pick; +type EntryScope = Pick; /** Narrow to a usable source string; an empty string is not authored text. */ function inlineText(value: unknown): string | undefined { @@ -1244,15 +1261,10 @@ function walkObjectSections(config: any, out: ExpectedEntry[]): void { } } - // (b) [ADR-0159 D8] authored `form` items' sections, keyed under the - // object they bind (the object-level default the translator keeps). - const forms: any[] = Array.isArray(config?.forms) ? config.forms : []; - for (const form of forms) { - if (!form || typeof form !== 'object') continue; - const formObject = viewObjectName(form) ?? (typeof form.object === 'string' ? form.object : undefined); - addSectionList(index, form.sections, formObject); - addSectionEntries(entries, form.sections, formObject); - } + // (b) [ADR-0159 D8] An authored `form` item's sections are NOT walked here: + // their copy is keyed at the form's own node (`forms..sections.…`, + // {@link walkForms}), with this object-level slot as the default each key + // falls back to. // (b) authored page sections — a record page's `record:details`. // @@ -2237,8 +2249,15 @@ function walkMappings(config: any, out: ExpectedEntry[]): void { * authored `form` item — the address `translateForm` reads first. ⛔ No * `objects.._views.` tail is emitted for an authored `form`: that * address is the old shapes' fallback, read, never scaffolded for the new - * type. Section copy stays the object's (`objects.._sections.…`), - * walked with the object's sections. + * type. + * + * Section copy is the form's own too: `forms..sections.
.{label, + * description}` and `.fields..{label, placeholder, helpText}`, for a + * named section and the copy it authors (`translateForm` translates authored + * copy only), each with the object-level default + * `objects.._sections.
…` as its {@link ExpectedEntry.fallbackPath}: + * D8 keeps that slot live, shared with field groups, so a bundle that + * translates the section there has translated the form's too. */ function walkForms(config: any, out: ExpectedEntry[]): void { const forms: any[] = Array.isArray(config?.forms) ? config.forms : []; @@ -2251,6 +2270,28 @@ function walkForms(config: any, out: ExpectedEntry[]): void { pushOptional(out, ['forms', name, 'description'], form.description, 'form', extra); pushOptional(out, ['forms', name, 'title'], form.title, 'form', extra); pushThankYouPanel(out, ['forms', name], form.submitBehavior, 'form', extra); + const objectName = typeof form.object === 'string' && form.object ? form.object : undefined; + for (const raw of Array.isArray(form.sections) ? form.sections : []) { + if (!raw || typeof raw !== 'object') continue; + const section = raw as Record; + if (typeof section.name !== 'string' || section.name.length === 0) continue; + const at = (tail: string[]) => ({ + ...extra, + ...(objectName ? { fallbackPath: ['objects', objectName, '_sections', section.name as string, ...tail] } : {}), + }); + for (const attr of ['label', 'description'] as const) { + pushOptional(out, ['forms', name, 'sections', section.name, attr], section[attr], 'form', at([attr])); + } + for (const entryRaw of Array.isArray(section.fields) ? section.fields : []) { + if (!entryRaw || typeof entryRaw !== 'object') continue; + const entry = entryRaw as Record; + if (typeof entry.field !== 'string' || entry.field.length === 0) continue; + for (const attr of SECTION_ENTRY_ATTRS) { + pushEntry(out, ['forms', name, 'sections', section.name, 'fields', entry.field, attr], entry[attr], 'form', + at(['fields', entry.field, attr])); + } + } + } } } diff --git a/packages/lint/src/validate-translation-references.test.ts b/packages/lint/src/validate-translation-references.test.ts index f7c2ee78d1f..7e5f6b1fd99 100644 --- a/packages/lint/src/validate-translation-references.test.ts +++ b/packages/lint/src/validate-translation-references.test.ts @@ -203,6 +203,28 @@ describe('validateTranslationReferences — orphan keys', () => { ]); }); + it('[ADR-0159 D8] a `form` item\'s own `forms..sections` node is judged against the sections it names and their entries', () => { + const FORM = 'crm_lead.feedback'; + const stackWithFormNode = (formKey: string, sectionKey: string, fieldKey: string) => ({ + ...leadStack([{ 'zh-CN': { + objects: { crm_lead: { label: '线索' } }, + forms: { [formKey]: { label: '反馈', sections: { [sectionKey]: { label: '反馈', fields: { [fieldKey]: { label: '称呼' } } } } } }, + } }]), + forms: [{ name: FORM, object: 'crm_lead', type: 'simple', sections: [{ name: 'feedback', fields: [{ field: 'name' }, 'status'] }] }], + }); + const paths = (stack: unknown) => validateTranslationReferences(stack as any).map((f) => [f.rule, f.path]); + expect(paths(stackWithFormNode(FORM, 'feedback', 'name'))).toEqual([]); + expect(paths(stackWithFormNode(FORM, 'feedbacks', 'name'))).toEqual([ + [TRANSLATION_TARGET_UNKNOWN, `translations[0]["zh-CN"].forms["${FORM}"].sections.feedbacks`], + ]); + // An entry the section does not declare as an entry object: a bare field name authors no copy. + expect(paths(stackWithFormNode(FORM, 'feedback', 'status'))).toEqual([ + [TRANSLATION_TARGET_UNKNOWN, `translations[0]["zh-CN"].forms["${FORM}"].sections.feedback.fields.status`], + ]); + // CONTROL: the node of a form the stack does not author is not judged here. + expect(paths(stackWithFormNode('crm_lead.elsewhere', 'feedbacks', 'status'))).toEqual([]); + }); + it('flags an unresolved view / action / section by name', () => { const findings = validateTranslationReferences( leadStack([ diff --git a/packages/lint/src/validate-translation-references.ts b/packages/lint/src/validate-translation-references.ts index d814f2d011c..756a131d85f 100644 --- a/packages/lint/src/validate-translation-references.ts +++ b/packages/lint/src/validate-translation-references.ts @@ -599,6 +599,12 @@ interface Universe { */ contributedOnlyApps: Set; dashboards: Map; actions: Set }>; + /** + * [ADR-0159 D8] Authored `form` item name → its named sections → the `field` + * of each entry object the section declares: what a + * `forms..sections.
[.fields.]` key may name. + */ + forms: Map>>; /** Flow name (`Flow.name`) → its screen nodes and their declared fields. */ flows: Map; /** @@ -1473,8 +1479,25 @@ function buildUniverse(stack: AnyRec): Universe { // the object it binds to (its one `object`), the same anchor a form view's // sections are. Its own label, title and panel live in the `forms` family, // keyed by its name, so it contributes no `_views` fact. + // [ADR-0159 D8] …and the form's own `forms..sections` node, read + // before that default: the same sections and entries, keyed by the form. + const forms = new Map>>(); for (const form of [...recordsOf(stack.forms), ...artifactProvidedRecords(stack, 'forms')]) { addFormSections(form, strName(form.object), factsFor); + const formName = strName(form.name); + if (!formName) continue; + let sections = forms.get(formName); + if (!sections) forms.set(formName, (sections = new Map())); + for (const section of recordsOf(form.sections)) { + const sectionName = strName(section.name); + if (!sectionName) continue; + let entries = sections.get(sectionName); + if (!entries) sections.set(sectionName, (entries = new Set())); + for (const entry of recordsOf(section.fields)) { + const field = strName(entry.field); + if (field) entries.add(field); + } + } } // ── Pages: `record:details` sections are the other `_sections` anchor, and @@ -1922,6 +1945,7 @@ function buildUniverse(stack: AnyRec): Universe { apps, contributedOnlyApps, dashboards, + forms, flows, hooks, hookTexts, @@ -2355,6 +2379,44 @@ export function validateTranslationReferences(stack: AnyRec): TranslationRefFind } } + // ── [ADR-0159 D8] forms..sections.
[.fields.] ── + // + // Only the `sections` branch is judged: a section the form names and an + // entry `field` that section declares are the targets `translateForm` + // reads there. A form this stack does not author is skipped, as a page + // is (no rung judges `forms.` itself yet). + for (const [formName, rawForm] of Object.entries(asRecord(rawData.forms))) { + const form = universe.forms.get(formName); + if (!form || !isRec(rawForm)) continue; + const formPath = `${base}.forms${memberPath(formName)}`; + for (const [sectionName, rawSection] of Object.entries(asRecord(rawForm.sections))) { + const entries = form.get(sectionName); + if (!entries) { + orphan( + `${inLocale} · form "${formName}" · section "${sectionName}"`, + `${formPath}.sections.${sectionName}`, + `Translations are keyed to section "${sectionName}", which form "${formName}" does not ` + + `declare, so nothing reads them.` + + suggest(sectionName, form.keys()), + `Key the section by its \`name\` in the form's \`sections\`, or drop the translation.`, + ); + continue; + } + for (const fieldName of Object.keys(asRecord(asRecord(rawSection).fields))) { + if (entries.has(fieldName)) continue; + orphan( + `${inLocale} · form "${formName}" · section "${sectionName}" · entry "${fieldName}"`, + `${formPath}.sections.${sectionName}.fields.${fieldName}`, + `Translations are keyed to entry "${fieldName}" of section "${sectionName}", which form ` + + `"${formName}" does not declare in that section, so nothing reads them.` + + suggest(fieldName, entries), + `Key the entry by its \`field\` under the section's \`name\`, or drop the translation. A ` + + `bare field name authors no copy: translate the field itself at \`objects.OBJECT.fields.FIELD\`.`, + ); + } + } + } + // ── pages..components..items. / .submitBehavior ── // // Only the `items` and `submitBehavior` members are judged here: they From 95cb02acf127a457b04748f69261748342ba4c0a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:23:55 +0000 Subject: [PATCH 24/29] test(cli): the form item section coverage pin reads the form's own keys Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- packages/cli/test/i18n-form-section-entry-coverage.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/cli/test/i18n-form-section-entry-coverage.test.ts b/packages/cli/test/i18n-form-section-entry-coverage.test.ts index 935bf580bba..b5210a9b72c 100644 --- a/packages/cli/test/i18n-form-section-entry-coverage.test.ts +++ b/packages/cli/test/i18n-form-section-entry-coverage.test.ts @@ -149,7 +149,7 @@ describe('i18n walker — a `form` item\'s sections, `forms..sections. e.path.join('.')) .filter((p) => p.startsWith(`forms.${FORM}.sections.`) || p.includes('._sections.')); const zhMissing = (translations: unknown[]) => computeI18nCoverage(formConfig(translations)).issues - .filter((i) => i.locale === 'zh-CN' && (i.key.includes('.sections.') || i.key.includes('._sections.'))) + .filter((i) => i.locale === 'zh-CN' && (i.key.startsWith(`forms.${FORM}.`) || i.key.includes('._sections.'))) .map((i) => i.key) .sort(); From 7e3b3d2438e455d2ab735c4dfd2764189e68a68d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:27:03 +0000 Subject: [PATCH 25/29] docs(changeset): the form type's entry names the undo of the old-shape row removal and the forms sections translation family in lint and cli Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .changeset/37086-form-metadata-type.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.changeset/37086-form-metadata-type.md b/.changeset/37086-form-metadata-type.md index 25296140873..54b545b0a9c 100644 --- a/.changeset/37086-form-metadata-type.md +++ b/.changeset/37086-form-metadata-type.md @@ -30,7 +30,7 @@ ADR-0159 makes a public form a `form` item: `name` (`OBJECT.KEY`, the name it is What lands with the type: - `@objectstack/spec`: `FormSchema`, `defineForm`, the registry row (`*.form.ts|yml|json`, overlay-capable, no environment overlay), `form` in the customization package's listed types, the stack's `forms` collection, the `forms` translation family (`forms.NAME` first, the `_views.KEY` title and thank-you tails as the fallback, `_views.KEY.label` never read; a form's own section copy at `forms.NAME.sections.SECTION`, with `objects.OBJECT._sections.SECTION` as its object-level default), the projection `projectViewForms`, the intake layer `formIntakeLayer` / `openFormAt`, and the error code `FORM_ADDRESS_TAKEN`. -- `@objectstack/metadata-protocol`: the effective `form` read resolves a form over both types in the one served-row order (a stored `view` row over a package's form keeps replacing it when the package moves to `forms:`); a `form` save, reset or delete at a package removes that package's old-shape row of the name in the same transaction (form content only — a list of the name is untouched); a `form` left open on a public address another form holds is refused with `409 FORM_ADDRESS_TAKEN`, naming both, on the save, on the publish of a draft whose address another form took after it was saved, and on a rollback to a version open on a held address (a switched-off form that keeps its link still holds the address; a write that leaves the form closed is never refused); the override gate accepts a `form` override over a base that ships the form as an old shape; a stored body whose form content cannot be read closes the links it names and is reported once per process, at `error`, the first time the form doors read it, naming the row, the links it closes and the repair save. +- `@objectstack/metadata-protocol`: the effective `form` read resolves a form over both types in the one served-row order (a stored `view` row over a package's form keeps replacing it when the package moves to `forms:`); a `form` save, reset or delete at a package removes that package's old-shape row of the name in the same transaction (form content only — a list of the name is untouched), and the undo of that write puts the row back: a package commit records the row as one its publish edited, so the commit's revert restores it, and a refused package publish undone on a runtime that cannot roll back restores it at its version; a `form` left open on a public address another form holds is refused with `409 FORM_ADDRESS_TAKEN`, naming both, on the save, on the publish of a draft whose address another form took after it was saved, and on a rollback to a version open on a held address (a switched-off form that keeps its link still holds the address; a write that leaves the form closed is never refused); the override gate accepts a `form` override over a base that ships the form as an old shape; a stored body whose form content cannot be read closes the links it names and is reported once per process, at `error`, the first time the form doors read it, naming the row, the links it closes and the repair save. - `@objectstack/rest`: `GET /forms/:slug` and its submit read candidates from the effective `form` read and judge withdrawal across `form` and `view`, effective and per-package, old shapes projected first — narrowing only, in both directions; a body that cannot be read closes the links it names. `/meta/form/NAME` refuses whom `/meta/view/NAME` refuses. `GET /meta/view` answers as before. -- `@objectstack/lint`: `form-public-address-taken` (gating), `form-consumer-less` (advisory, never for an `overrides` item), `form-object-outside-closure` / `form-object-unknown`; the i18n walk emits `forms.NAME.*` keys and no `_views` tail for a `form` item. No new advisory for an old shape. -- `@objectstack/metadata`, `@objectstack/metadata-core`, `@objectstack/objectql`, `@objectstack/runtime`, `@objectstack/cli`: the `forms` collection is loaded, typed, registered and counted for i18n coverage like every other. +- `@objectstack/lint`: `form-public-address-taken` (gating), `form-consumer-less` (advisory, never for an `overrides` item), `form-object-outside-closure` / `form-object-unknown`; the i18n walk emits `forms.NAME.*` keys and no `_views` tail for a `form` item, a form's section copy at `forms.NAME.sections.SECTION` with `objects.OBJECT._sections.SECTION` as the address it falls back to; the translation reference lint judges a `forms.NAME.sections` key against the form's named sections and their entries. No new advisory for an old shape. +- `@objectstack/metadata`, `@objectstack/metadata-core`, `@objectstack/objectql`, `@objectstack/runtime`, `@objectstack/cli`: the `forms` collection is loaded, typed, registered and counted for i18n coverage like every other; in `@objectstack/cli` a key translated at the address the walk names as its fallback is covered, and `os i18n extract` scaffolds no translated-locale value over one. From d2049502a0869129f8bce283753f6b04e40539ae Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:53:25 +0000 Subject: [PATCH 26/29] test(metadata-protocol): the stored-row write census lists the old-shape row restore among the hand-series module writers Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .../src/protocol.view-expansion-reconcile-call-sites.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts b/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts index a41e56ff08d..7e9e34a47bb 100644 --- a/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts +++ b/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts @@ -286,6 +286,7 @@ describe('[#29985] the census reads the modules the split moved bodies to', () = .toEqual([ 'protocol-form-writes.ts: applyOldShapeFormRowRemovals', 'protocol-form-writes.ts: applyOldShapeFormRowRemovals', + 'protocol-form-writes.ts: restoreOldShapeFormRowRemovals', 'protocol-packageless-overlay-migration.ts: migratePackagelessOverlays', ]); }); From 6bea26c97141261678ad0c538bc82e0f176c3cab Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:26:20 +0000 Subject: [PATCH 27/29] fix(metadata-protocol): a rolled-back transaction retires the overlay cache it filled A read inside a transaction can cache that transaction's own uncommitted sys_metadata rows at the generation its earlier writes already moved; a driver rollback undoes the rows below the middleware seam, so nothing moved the generation again and the entry stood until the TTL. Every transaction the protocol opens (the package publish batch, the form-aware publish, save and delete, the repository's write unit, the atomic data batch) now goes through retireOverlayCacheOnRollback, which advances the generation when the transaction fails after moving it. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .changeset/37086-form-metadata-type.md | 2 +- .../src/meta-overlay-cache.ts | 42 +++++++++++++++++++ .../src/protocol-batch-data.ts | 5 ++- .../src/protocol-diff-delete-load.ts | 3 +- .../src/protocol-history-and-publish.ts | 5 ++- .../metadata-protocol/src/protocol-save.ts | 3 +- .../src/sys-metadata-repository.ts | 4 +- 7 files changed, 56 insertions(+), 8 deletions(-) diff --git a/.changeset/37086-form-metadata-type.md b/.changeset/37086-form-metadata-type.md index 54b545b0a9c..0f7ab462082 100644 --- a/.changeset/37086-form-metadata-type.md +++ b/.changeset/37086-form-metadata-type.md @@ -30,7 +30,7 @@ ADR-0159 makes a public form a `form` item: `name` (`OBJECT.KEY`, the name it is What lands with the type: - `@objectstack/spec`: `FormSchema`, `defineForm`, the registry row (`*.form.ts|yml|json`, overlay-capable, no environment overlay), `form` in the customization package's listed types, the stack's `forms` collection, the `forms` translation family (`forms.NAME` first, the `_views.KEY` title and thank-you tails as the fallback, `_views.KEY.label` never read; a form's own section copy at `forms.NAME.sections.SECTION`, with `objects.OBJECT._sections.SECTION` as its object-level default), the projection `projectViewForms`, the intake layer `formIntakeLayer` / `openFormAt`, and the error code `FORM_ADDRESS_TAKEN`. -- `@objectstack/metadata-protocol`: the effective `form` read resolves a form over both types in the one served-row order (a stored `view` row over a package's form keeps replacing it when the package moves to `forms:`); a `form` save, reset or delete at a package removes that package's old-shape row of the name in the same transaction (form content only — a list of the name is untouched), and the undo of that write puts the row back: a package commit records the row as one its publish edited, so the commit's revert restores it, and a refused package publish undone on a runtime that cannot roll back restores it at its version; a `form` left open on a public address another form holds is refused with `409 FORM_ADDRESS_TAKEN`, naming both, on the save, on the publish of a draft whose address another form took after it was saved, and on a rollback to a version open on a held address (a switched-off form that keeps its link still holds the address; a write that leaves the form closed is never refused); the override gate accepts a `form` override over a base that ships the form as an old shape; a stored body whose form content cannot be read closes the links it names and is reported once per process, at `error`, the first time the form doors read it, naming the row, the links it closes and the repair save. +- `@objectstack/metadata-protocol`: the effective `form` read resolves a form over both types in the one served-row order (a stored `view` row over a package's form keeps replacing it when the package moves to `forms:`); a `form` save, reset or delete at a package removes that package's old-shape row of the name in the same transaction (form content only — a list of the name is untouched), and the undo of that write puts the row back: a package commit records the row as one its publish edited, so the commit's revert restores it, and a refused package publish undone on a runtime that cannot roll back restores it at its version; a `form` left open on a public address another form holds is refused with `409 FORM_ADDRESS_TAKEN`, naming both, on the save, on the publish of a draft whose address another form took after it was saved, and on a rollback to a version open on a held address (a switched-off form that keeps its link still holds the address; a write that leaves the form closed is never refused); the override gate accepts a `form` override over a base that ships the form as an old shape; a stored body whose form content cannot be read closes the links it names and is reported once per process, at `error`, the first time the form doors read it, naming the row, the links it closes and the repair save; and a transaction the protocol opens that rolls back after writing metadata rows retires the overlay read cache, so a read after a refused package publish answers the store as the rollback left it. - `@objectstack/rest`: `GET /forms/:slug` and its submit read candidates from the effective `form` read and judge withdrawal across `form` and `view`, effective and per-package, old shapes projected first — narrowing only, in both directions; a body that cannot be read closes the links it names. `/meta/form/NAME` refuses whom `/meta/view/NAME` refuses. `GET /meta/view` answers as before. - `@objectstack/lint`: `form-public-address-taken` (gating), `form-consumer-less` (advisory, never for an `overrides` item), `form-object-outside-closure` / `form-object-unknown`; the i18n walk emits `forms.NAME.*` keys and no `_views` tail for a `form` item, a form's section copy at `forms.NAME.sections.SECTION` with `objects.OBJECT._sections.SECTION` as the address it falls back to; the translation reference lint judges a `forms.NAME.sections` key against the form's named sections and their entries. No new advisory for an old shape. - `@objectstack/metadata`, `@objectstack/metadata-core`, `@objectstack/objectql`, `@objectstack/runtime`, `@objectstack/cli`: the `forms` collection is loaded, typed, registered and counted for i18n coverage like every other; in `@objectstack/cli` a key translated at the address the walk names as its fallback is covered, and `os i18n extract` scaffolds no translated-locale value over one. diff --git a/packages/metadata-protocol/src/meta-overlay-cache.ts b/packages/metadata-protocol/src/meta-overlay-cache.ts index 565a72ea1e2..a1647f3bb18 100644 --- a/packages/metadata-protocol/src/meta-overlay-cache.ts +++ b/packages/metadata-protocol/src/meta-overlay-cache.ts @@ -104,6 +104,10 @@ * bumped this cache, so a read landing inside the residue window fed the * untimed registry a row this cache should already have retired — see * `protocol.datasource-delete-prolongation.test.ts` for the measurement. + * 4. **A rolled-back transaction** ({@link retireOverlayCacheOnRollback}): + * a read inside a transaction can cache rows it then rolls back, below + * the seam ①. Every transaction this package opens retires the cache when + * it fails after moving the generation. * * ⚠️ **`metadata.changed` is NOT a trigger here, and #11633 §4's expectation * that it would be does not survive measurement.** That channel is published by @@ -405,6 +409,44 @@ export function retireMetaOverlayCache(engine: unknown): number | undefined { return advance(state); } +/** + * [ADR-0067 D2] Open a transaction — `open` is the call to + * `engine.transaction(...)` — and, when it does not commit, retire every row + * set this engine holds if the generation moved while it was open. + * + * A read made INSIDE a transaction reads that transaction's own uncommitted + * rows, and stamps them with the generation its earlier writes already moved + * (each write advances it as it settles, inside the transaction). A rollback + * then undoes the rows in the driver, below the middleware seam, so nothing + * advances the generation again, and the entry would be served until the TTL + * as the committed answer — to every reader, the registry hydration of + * `getMetaItems` included, which has no expiry of its own. Retiring here makes + * such an entry dead the moment the rejection reaches the protocol, before + * the caller that opened the transaction reads or answers anything. + * + * Why at the rollback and not at the fill: the engine keeps its ambient + * transaction private, so a read cannot tell that it runs inside one. Every + * transaction this package opens is opened through here; one that JOINED an + * outer transaction (ADR-0067 D2) retires on its own failure, and again when + * the outer one fails, where that one is this package's too. + * + * Retires only when the generation moved, so a transaction that wrote no + * `sys_metadata` row — whose reads could cache nothing uncommitted — costs the + * cache nothing. A commit retires nothing: what was read inside it is what + * committed. The error is rethrown as it came. + */ +export async function retireOverlayCacheOnRollback(engine: unknown, open: () => Promise): Promise { + const covered = engine !== null && typeof engine === 'object'; + const opened = covered ? overlayWriteStates.get(engine)?.gen : undefined; + try { + return await open(); + } catch (e) { + const state = covered ? overlayWriteStates.get(engine) : undefined; + if (state && state.gen !== opened) advance(state); + throw e; + } +} + /** * [#34554] The wall-clock time the current generation began * ({@link readOverlayCacheGeneration}): every row set this engine holds was diff --git a/packages/metadata-protocol/src/protocol-batch-data.ts b/packages/metadata-protocol/src/protocol-batch-data.ts index 58d2df65bac..87fe1852764 100644 --- a/packages/metadata-protocol/src/protocol-batch-data.ts +++ b/packages/metadata-protocol/src/protocol-batch-data.ts @@ -52,6 +52,7 @@ import type { DroppedFieldsEvent, EngineQueryOptionsParsed } from '@objectstack/ import type { ISecurityService } from '@objectstack/spec/contracts'; import { engineCanRollBack, recordNotFoundError } from '@objectstack/core'; import { omitInternalFieldsFromWriteResponse } from './write-response-internal-fields.js'; +import { retireOverlayCacheOnRollback } from './meta-overlay-cache.js'; import { staleSummaryAnswerLines, staleSummaryRefusalOrThrow, withEarnedAnswer, type SummaryRecomputeRefusal } from '@objectstack/types'; /** @@ -281,14 +282,14 @@ export async function runAtomicBatch( const ABORT = new Error('atomic batch aborted — rolled back'); let aborted: BatchDataLoopOutcome | undefined; try { - return await engineTx(async (trxCtx: any) => { + return await retireOverlayCacheOnRollback(this.engine, () => engineTx(async (trxCtx: any) => { const outcome = await runLoop(trxCtx); if (outcome.failed > 0) { aborted = outcome; throw ABORT; } return onCommit(outcome); - }, context); + }, context)); } catch (err) { if (err === ABORT && aborted) { return onRollback(aborted); diff --git a/packages/metadata-protocol/src/protocol-diff-delete-load.ts b/packages/metadata-protocol/src/protocol-diff-delete-load.ts index edc81638073..105892f8e92 100644 --- a/packages/metadata-protocol/src/protocol-diff-delete-load.ts +++ b/packages/metadata-protocol/src/protocol-diff-delete-load.ts @@ -69,6 +69,7 @@ import type { RuntimeAuthoringIssue } from './runtime-authoring-gate.js'; import type { ProtocolHost } from './protocol-host.js'; import { packagelessHolderRefusal, packagelessRowHeldBaseAddress } from './protocol-save.js'; import { isPlatformOrigin } from '@objectstack/metadata'; +import { retireOverlayCacheOnRollback } from './meta-overlay-cache.js'; /** * [#33308] The row slot a `sys_metadata` row is: its bound package, or `null` @@ -913,7 +914,7 @@ export class ProtocolDiffDeleteLoadFacet { }); return removed; }; - return typeof host.engine?.transaction === 'function' ? host.engine.transaction(run) : run(); + return typeof host.engine?.transaction === 'function' ? retireOverlayCacheOnRollback(host.engine, () => host.engine.transaction!(run)) : run(); }; const result = await deleteFormAware(() => repo.delete(ref, { parentVersion, diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index f9e6b206ec2..a5234b7dd7d 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -69,6 +69,7 @@ import { historySlotOf, refusePackageSelectorOutsideSlottedTypes } from './proto import { captureStoredExpressionChange, fillStoredExpressionChange, type StoredExpressionFillCapture } from './protocol-stored-expression-fill.js'; import { OBJECT_REGISTRY_REFUSED, reportObjectRegistryRefusal } from './protocol-registry-hydration.js'; import { OBJECT_EXTENSION_TYPE, registrableObjectExtension } from './protocol-object-extension-item.js'; +import { retireOverlayCacheOnRollback } from './meta-overlay-cache.js'; /** * [#32396] A promotion a package publish wrote: what {@link undoLandedPromotions} @@ -1486,7 +1487,7 @@ export class ProtocolHistoryAndPublishFacet { }); return promoted; }; - return typeof host.engine?.transaction === 'function' ? host.engine.transaction(run) : run(); + return typeof host.engine?.transaction === 'function' ? retireOverlayCacheOnRollback(host.engine, () => host.engine.transaction!(run)) : run(); }; const result = await promoteFormAware(() => repo.promoteDraft(ref, { deriveActiveBody: (draftBody) => stampHtmlPageRequires(singularType, draftBody, sduiManifest), @@ -2266,7 +2267,7 @@ export class ProtocolHistoryAndPublishFacet { ? this.engine.transaction.bind(this.engine) : undefined; const inTxn: (cb: () => Promise) => Promise = - engineTx ? (cb) => engineTx(() => cb()) : (cb) => cb(); + engineTx ? (cb) => retireOverlayCacheOnRollback(this.engine, () => engineTx(() => cb())) : (cb) => cb(); /** The promotion request for one draft: Phase 0 judges it, Phase 1 writes it. */ const promotionRequest = (d: (typeof ordered)[number]) => ({ registryQuestion: PROMOTION_REGISTRY_QUESTION['package-publish'], diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index b6f0bc3573c..d84a3f71385 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -97,6 +97,7 @@ import { installedManifestsOfEngine } from './installed-manifests.js'; import { packageScopedRefusalOf } from './protocol-meta-item-reads.js'; import { pairsOf } from '@objectstack/metadata-core'; import { BatchRowHealError, canJudgeBatchObjects, isBatchObjectType, readActiveBatchRow, settleBatchObjectRows, undoBatchRowWrite, undoOutcomeForLog, type WrittenBatchRow } from './batch-object-registration.js'; +import { retireOverlayCacheOnRollback } from './meta-overlay-cache.js'; export class ProtocolSaveFacet { /** @@ -2320,7 +2321,7 @@ export class ProtocolSaveFacet { }); return written; }; - return typeof host.engine?.transaction === 'function' ? host.engine.transaction(run) : run(); + return typeof host.engine?.transaction === 'function' ? retireOverlayCacheOnRollback(host.engine, () => host.engine.transaction!(run)) : run(); }; try { const result = await putFormAware(() => repo.put(ref, request.item, { diff --git a/packages/metadata-protocol/src/sys-metadata-repository.ts b/packages/metadata-protocol/src/sys-metadata-repository.ts index 89b850ce07f..227ab11393c 100644 --- a/packages/metadata-protocol/src/sys-metadata-repository.ts +++ b/packages/metadata-protocol/src/sys-metadata-repository.ts @@ -102,6 +102,7 @@ import type { MetadataAuthoringClient, MetadataAuthoringSurface } from '@objects // [#24395] The draft save's per-key provenance — the diff, the keep rule and // the stored form, one module the strict draft read reads it back through. import { draftChangedPaths, mergeDraftChanges, storedDraftChanges, type DraftChangeStamp } from './draft-changes.js'; +import { retireOverlayCacheOnRollback } from './meta-overlay-cache.js'; /** * Canonicalise a driver-materialised timestamp into the ISO-8601 string the @@ -886,7 +887,8 @@ export class SysMetadataRepository implements MetadataRepository { */ private async withTxn(cb: (ctx: any) => Promise): Promise { if (typeof this.engine.transaction === 'function') { - return this.engine.transaction(cb); + // ADR-0067 D2: a rollback retires the overlay rows read inside it. + return retireOverlayCacheOnRollback(this.engine, () => this.engine.transaction!(cb)); } return cb(undefined); } From c75ea6281cd7418af82eeb6de9cf927027ff77a6 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:26:20 +0000 Subject: [PATCH 28/29] test(metadata-protocol, rest): a package publish refused part-way on an engine that can roll back leaves nothing of the batch served Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .../src/meta-overlay-cache.test.ts | 61 ++++++++++++++ .../public-form-two-type-withdrawal.test.ts | 81 +++++++++++++++++++ 2 files changed, 142 insertions(+) diff --git a/packages/metadata-protocol/src/meta-overlay-cache.test.ts b/packages/metadata-protocol/src/meta-overlay-cache.test.ts index 542867b67cd..a4a8bfea398 100644 --- a/packages/metadata-protocol/src/meta-overlay-cache.test.ts +++ b/packages/metadata-protocol/src/meta-overlay-cache.test.ts @@ -88,7 +88,9 @@ import { META_OVERLAY_CACHE_DEFAULT_TTL_MS, metaOverlayCacheEntryCount, metaOverlayCacheTtlMs, + readOverlayCacheGeneration, readWriteEpoch, + retireOverlayCacheOnRollback, } from './meta-overlay-cache.js'; interface StoredRow { @@ -792,3 +794,62 @@ describe('[#10757 leg 6] §10 a write to any OTHER object does not retire the ov expect(h.finds.length).toBe(perCall); }); }); + +describe('[ADR-0067 D2] §11 a transaction that rolls back retires the rows read inside it', () => { + /** + * One transaction over the harness: a `sys_metadata` insert of `gamma` + * through the seam, a read inside it (which caches the uncommitted row), + * then the callback's outcome; a failure undoes the insert BELOW the seam, + * as a driver rollback does, and rethrows. + */ + const transaction = (h: ReturnType, rows: StoredRow[], fail: Error | null, write = true) => + retireOverlayCacheOnRollback(h.engine, async () => { + if (write) await h.writeTo('sys_metadata', () => rows.push(storedRow('object', 'gamma')), 'insert'); + const inside = await h.protocol.getMetaItems({ type: 'object' }); + if (fail) { + if (write) rows.pop(); + throw fail; + } + return inside; + }); + const names = (answer: { items: unknown[] }) => (answer.items as Array<{ name?: string }>).map((i) => i.name); + + it('rolled back: the generation moves, the next read misses and serves the committed rows, the error is rethrown as it came', async () => { + const rows = clone(OVERLAY_ROWS); + const h = makeHarness(rows); + await h.protocol.getMetaItems({ type: 'object' }); + const refused = new Error('refused part-way'); + let generationInside: number | undefined; + await expect(retireOverlayCacheOnRollback(h.engine, async () => { + await h.writeTo('sys_metadata', () => rows.push(storedRow('object', 'gamma')), 'insert'); + expect(names(await h.protocol.getMetaItems({ type: 'object' }))).toContain('gamma'); + generationInside = readOverlayCacheGeneration(h.engine); + rows.pop(); + throw refused; + })).rejects.toBe(refused); + expect(readOverlayCacheGeneration(h.engine)).toBe(generationInside! + 1); + const perCall = h.finds.length; + expect(names(await h.protocol.getMetaItems({ type: 'object' }))).not.toContain('gamma'); + expect(h.finds.length).toBeGreaterThan(perCall); + }); + + it('CONTROL: committed, the row read inside it keeps serving with zero reads', async () => { + const rows = clone(OVERLAY_ROWS); + const h = makeHarness(rows); + await transaction(h, rows, null); + const perCall = h.finds.length; + expect(names(await h.protocol.getMetaItems({ type: 'object' }))).toContain('gamma'); + expect(h.finds.length).toBe(perCall); + }); + + it('CONTROL: a failed transaction that wrote no `sys_metadata` row retires nothing', async () => { + const rows = clone(OVERLAY_ROWS); + const h = makeHarness(rows); + await h.protocol.getMetaItems({ type: 'object' }); // first sight: wires the seam before the transaction opens + const refused = new Error('refused'); + await expect(transaction(h, rows, refused, false)).rejects.toBe(refused); + const perCall = h.finds.length; + await h.protocol.getMetaItems({ type: 'object' }); + expect(h.finds.length).toBe(perCall); + }); +}); diff --git a/packages/rest/src/public-form-two-type-withdrawal.test.ts b/packages/rest/src/public-form-two-type-withdrawal.test.ts index 645f7a754df..7f4746bacaa 100644 --- a/packages/rest/src/public-form-two-type-withdrawal.test.ts +++ b/packages/rest/src/public-form-two-type-withdrawal.test.ts @@ -1068,3 +1068,84 @@ describe('[ADR-0159 D5, ADR-0067 D2 and D3] the undo of a `form` publish puts ba await openOnBothDoors(b); }); }); + +describe('[ADR-0067 D2] a package publish refused part-way on an engine that can roll back leaves nothing of the batch served', () => { + const engines: ObjectQL[] = []; + beforeAll(() => { + // The overlay read cache ON, at its shipped default bound: the rows a + // refused batch read while it was open must not outlive its rollback. + vi.stubEnv('OS_METADATA_OVERLAY_CACHE_TTL_MS', '30000'); + }); + afterAll(async () => { + vi.unstubAllEnvs(); + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + const SECOND = `${OBJECT}.second`; + const NEW_SLUG = 'renamed-37086-rb'; + /** + * An engine that CAN roll back. The base ships the form in an old-shape + * container, open on {@link SLUG}; the pair stores its own old-shape row of + * the name with the form switched off. + */ + const pairOverTheBase = async (): Promise => { + const b = await boot({ views: [container(true)] }); + engines.push(b.engine); + await b.install(PAIR); + await b.saveInto('view', PAIR, viewItem(false, overrides)); + await closedOnBothDoors(b); + return b; + }; + /** What the store and the meta doors answer for the name, compared before and after the publish. */ + const standing = async (b: Booted) => ({ + view: await rawRows(b, 'view', NAME, PAIR), + form: await rawRows(b, 'form', NAME, PAIR), + metaView: await b.meta('view', NAME), + metaForm: await b.meta('form', NAME), + }); + + const THIRD = `${OBJECT}.third`; + /** A `form` draft in the pair: `name` open on `slug`. */ + const draft = (b: Booted, name: string, slug: string) => b.protocol.saveMetaItem({ + type: 'form', name, packageId: PAIR, mode: 'draft', + item: name === NAME ? formItem(true, overrides, slug) : { ...formItem(true, {}, slug), name }, + }); + const variants = [ + { + // The first form opens a new link; the second, saved on the same link + // while it was free, is refused once the first holds it. + intent: 'a new public link', slug: NEW_SLUG, + others: [SECOND], + refused: [[NAME, 'BATCH_ABORTED'], [SECOND, 'FORM_ADDRESS_TAKEN']], + }, + { + // The first form re-opens the address the pair's switched-off row holds; + // the batch is refused later, at a third form, once the second holds + // the link they were both saved on. + intent: 'the address the pair\'s switched-off row holds', slug: SLUG, + others: [SECOND, THIRD], + refused: [[NAME, 'BATCH_ABORTED'], [SECOND, 'BATCH_ABORTED'], [THIRD, 'FORM_ADDRESS_TAKEN']], + }, + ] as const; + + for (const { intent, slug, others, refused } of variants) { + it(`refused part-way, a batch whose first form opens ${intent} leaves both doors at 404 there and the meta reads unchanged`, async () => { + const b = await pairOverTheBase(); + await draft(b, NAME, slug); + for (const name of others) await draft(b, name, NEW_SLUG); + const before = await standing(b); + const answer: any = await b.protocol.publishPackageDrafts({ packageId: PAIR }); + expect(answer.success).toBe(false); + expect(answer.failed.map((f: any) => [f.name, f.code])).toEqual(refused); + await closedOnBothDoors(b, slug); + expect(await standing(b)).toEqual(before); + }); + + it(`CONTROL: the first form published alone opens ${intent} on both doors`, async () => { + const b = await pairOverTheBase(); + await draft(b, NAME, slug); + const answer: any = await b.protocol.publishPackageDrafts({ packageId: PAIR }); + expect(answer.success, JSON.stringify(answer.failed)).toBe(true); + await openOnBothDoors(b, slug); + }); + } +}); From 049639046792e69c77f32b0d4bb615633a826884 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:37:53 +0000 Subject: [PATCH 29/29] test(metadata-protocol): the overlay cache pins pay the protocol's lazy lint load at collection Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- packages/metadata-protocol/src/meta-overlay-cache.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/metadata-protocol/src/meta-overlay-cache.test.ts b/packages/metadata-protocol/src/meta-overlay-cache.test.ts index a4a8bfea398..be0d7a2e534 100644 --- a/packages/metadata-protocol/src/meta-overlay-cache.test.ts +++ b/packages/metadata-protocol/src/meta-overlay-cache.test.ts @@ -82,6 +82,8 @@ */ import { describe, expect, it } from 'vitest'; +// check:test-source-alias — the protocol's lazy `@objectstack/lint` load is paid at collection, not in a case's window. +import '@objectstack/lint'; import { ObjectStackProtocolImplementation } from './protocol.js'; import { bumpWriteEpoch,