From fb088dfb371ba66dfa58e707358d33a568093a67 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 23:20:02 +0000 Subject: [PATCH 01/50] refactor(spec)!: rename the Studio helper defineForm to defineMetadataForm and its modules to *.metadata-form.ts ADR-0159 question 1 (ruled A): the name defineForm and the *.form.ts suffix go to the new `form` metadata type. This commit is the rename and the suffix move alone (the card's PR A): 18 modules renamed, import specifiers swept by both spellings, the i18n surface constant, the gate self-test and fixtures, comments and path citations re-pointed, lint text re-worded, the generated spec artifacts regenerated, and the semantic ADR-0087 entry registered. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .../37086-define-metadata-form-rename.md | 21 ++++++++++ content/docs/protocol/objectui/layout-dsl.mdx | 2 +- content/docs/references/ui/view.mdx | 4 +- .../areas/studio-authoring.json | 4 +- packages/cli/src/commands/i18n/extract.ts | 2 +- packages/cli/src/utils/config.ts | 2 +- packages/cli/src/utils/i18n-bundle-extract.ts | 2 +- .../cli/test/i18n-duplicate-demand.test.ts | 2 +- ...8n-extract-metadata-forms-flag.e2e.test.ts | 2 +- packages/lint/src/i18n-walk.ts | 4 +- .../lint/src/lint-liveness-properties.test.ts | 2 +- packages/lint/src/predicate-rhs-position.ts | 2 +- packages/lint/src/rule-explanations.ts | 2 +- packages/lint/src/validate-expressions.ts | 8 ++-- .../src/validate-predicate-path-refs.test.ts | 28 ++++++------- .../lint/src/validate-predicate-path-refs.ts | 14 +++---- .../validate-visibility-predicates.test.ts | 24 +++++------ .../src/validate-visibility-predicates.ts | 12 +++--- packages/lint/src/view-walk.ts | 2 +- .../src/protocol-meta-type-schema.ts | 4 +- .../dashboard-header-children.test.ts | 8 ++-- .../field-panel-echo-decisions.test.ts | 4 +- ...-collapsed-sections-echo-decisions.test.ts | 4 +- ...ect-lifecycle-panel-echo-decisions.test.ts | 2 +- .../repeater-row-properties.test.ts | 6 +-- .../report-form-echo-decisions.test.ts | 2 +- .../view-composite-children.test.ts | 2 +- packages/platform-objects/src/plugin.ts | 2 +- packages/spec/api-surface-signatures.json | 2 +- packages/spec/api-surface/root.json | 2 +- packages/spec/api-surface/ui.json | 2 +- packages/spec/export-origins/ai.json | 8 ++-- packages/spec/export-origins/automation.json | 2 +- packages/spec/export-origins/data.json | 6 +-- packages/spec/export-origins/identity.json | 2 +- packages/spec/export-origins/root.json | 2 +- packages/spec/export-origins/security.json | 2 +- packages/spec/export-origins/system.json | 2 +- packages/spec/export-origins/ui.json | 16 ++++---- packages/spec/liveness/README.md | 4 +- packages/spec/liveness/action.json | 4 +- packages/spec/liveness/field.json | 4 +- packages/spec/liveness/view.json | 6 +-- .../scripts/pure-schema-construction.test.ts | 16 ++++---- .../{agent.form.ts => agent.metadata-form.ts} | 4 +- ...st.ts => ai-context.metadata-form.test.ts} | 2 +- ...xt.form.ts => ai-context.metadata-form.ts} | 8 ++-- packages/spec/src/ai/index.ts | 8 ++-- .../{skill.form.ts => skill.metadata-form.ts} | 4 +- .../{tool.form.ts => tool.metadata-form.ts} | 4 +- .../{flow.form.ts => flow.metadata-form.ts} | 4 +- packages/spec/src/automation/index.ts | 2 +- packages/spec/src/data/authoring-key-lint.ts | 2 +- .../data/field-currency-scale-refused.test.ts | 6 +-- packages/spec/src/data/field-due-like.test.ts | 4 +- ...field-form-external-id-not-offered.test.ts | 2 +- .../field-form-reference-name-visible.test.ts | 2 +- .../src/data/field-mail-association.test.ts | 4 +- .../field-rows-option-description.test.ts | 6 +-- .../{field.form.ts => field.metadata-form.ts} | 26 ++++++------ packages/spec/src/data/field.zod.ts | 2 +- .../data/form-delete-behavior-options.test.ts | 10 ++--- .../src/data/form-return-type-options.test.ts | 10 ++--- packages/spec/src/data/hook-refusals.test.ts | 2 +- .../{hook.form.ts => hook.metadata-form.ts} | 4 +- packages/spec/src/data/index.ts | 6 +-- ...object.form.ts => object.metadata-form.ts} | 14 +++---- packages/spec/src/identity/index.ts | 2 +- ...tion.form.ts => position.metadata-form.ts} | 4 +- packages/spec/src/index.ts | 2 +- .../src/kernel/repeater-item-titles.test.ts | 36 ++++++++-------- ...dio-helper-renamed-define-metadata-form.ts | 33 +++++++++++++++ packages/spec/src/security/index.ts | 2 +- .../permission-form-label-first.test.ts | 2 +- ...rmission-set-managed-by-retirement.test.ts | 2 +- ...on.form.ts => permission.metadata-form.ts} | 4 +- ...orm.ts => email-template.metadata-form.ts} | 4 +- packages/spec/src/system/i18n-resolver.ts | 2 +- packages/spec/src/system/index.ts | 2 +- .../metadata-form-declared-rows.pin.test.ts | 8 ++-- .../spec/src/system/metadata-form-registry.ts | 6 +-- .../metadata-form-zod-reconciliation.test.ts | 12 +++--- ...action.form.ts => action.metadata-form.ts} | 12 +++--- .../ui/add-record-config-retirement.test.ts | 4 +- .../ui/{app.form.ts => app.metadata-form.ts} | 4 +- ...hboard-form-business-wording-36816.test.ts | 2 +- ...ard.form.ts => dashboard.metadata-form.ts} | 4 +- packages/spec/src/ui/dashboard.test.ts | 2 +- packages/spec/src/ui/dashboard.zod.ts | 2 +- ...taset.form.ts => dataset.metadata-form.ts} | 4 +- .../src/ui/form-option-enum-derive.test.ts | 34 +++++++-------- packages/spec/src/ui/index.ts | 14 +++---- .../src/ui/navigation-mode-retirement.test.ts | 2 +- .../{page.form.ts => page.metadata-form.ts} | 4 +- .../ui/report-form-composite-children.test.ts | 2 +- ...rt-form-default-range-labels-36835.test.ts | 4 +- .../ui/report-joined-block-dataset.test.ts | 2 +- ...report.form.ts => report.metadata-form.ts} | 4 +- .../ui/view-form-composite-children.test.ts | 2 +- .../spec/src/ui/view-form-pagination.test.ts | 2 +- ...-list-filterable-fields-retirement.test.ts | 2 +- .../src/ui/view-list-tabs-retirement.test.ts | 2 +- .../{view.form.ts => view.metadata-form.ts} | 4 +- packages/spec/src/ui/view.test.ts | 10 ++--- packages/spec/src/ui/view.zod.ts | 41 +++++++++++-------- packages/spec/tsup.config.ts | 6 +-- scripts/check-i18n-bundles.mjs | 6 +-- scripts/i18n-bundle-surface.mjs | 27 +++++++----- scripts/pm/dispatch-gates.data.mjs | 8 ++-- scripts/pm/dispatch-gates.self-test.mjs | 21 +++++----- scripts/pm/landing-k.mjs | 2 +- ...orm.groupSectionReachability-8725.test.tsx | 2 +- .../SchemaForm.optionVisibleWhen.test.tsx | 2 +- .../SchemaForm.pageVisibility.test.tsx | 2 +- .../src/views/metadata-admin/SchemaForm.tsx | 2 +- .../src/views/metadata-admin/form-spec.ts | 2 +- .../inspectors/ObjectFieldInspector.tsx | 2 +- .../metadata-admin/metadata-form-zh-cn.ts | 4 +- .../src/views/metadata-admin/predicate.ts | 2 +- .../src/views/metadata-admin/widgets.tsx | 2 +- 120 files changed, 414 insertions(+), 349 deletions(-) create mode 100644 .changeset/37086-define-metadata-form-rename.md rename packages/spec/src/ai/{agent.form.ts => agent.metadata-form.ts} (97%) rename packages/spec/src/ai/{ai-context.form.test.ts => ai-context.metadata-form.test.ts} (96%) rename packages/spec/src/ai/{ai-context.form.ts => ai-context.metadata-form.ts} (94%) rename packages/spec/src/ai/{skill.form.ts => skill.metadata-form.ts} (96%) rename packages/spec/src/ai/{tool.form.ts => tool.metadata-form.ts} (94%) rename packages/spec/src/automation/{flow.form.ts => flow.metadata-form.ts} (98%) rename packages/spec/src/data/{field.form.ts => field.metadata-form.ts} (98%) rename packages/spec/src/data/{hook.form.ts => hook.metadata-form.ts} (98%) rename packages/spec/src/data/{object.form.ts => object.metadata-form.ts} (99%) rename packages/spec/src/identity/{position.form.ts => position.metadata-form.ts} (95%) create mode 100644 packages/spec/src/migrations/entries/semantic/18.define-form-studio-helper-renamed-define-metadata-form.ts rename packages/spec/src/security/{permission.form.ts => permission.metadata-form.ts} (98%) rename packages/spec/src/system/{email-template.form.ts => email-template.metadata-form.ts} (96%) rename packages/spec/src/ui/{action.form.ts => action.metadata-form.ts} (98%) rename packages/spec/src/ui/{app.form.ts => app.metadata-form.ts} (98%) rename packages/spec/src/ui/{dashboard.form.ts => dashboard.metadata-form.ts} (98%) rename packages/spec/src/ui/{dataset.form.ts => dataset.metadata-form.ts} (98%) rename packages/spec/src/ui/{page.form.ts => page.metadata-form.ts} (99%) rename packages/spec/src/ui/{report.form.ts => report.metadata-form.ts} (99%) rename packages/spec/src/ui/{view.form.ts => view.metadata-form.ts} (99%) diff --git a/.changeset/37086-define-metadata-form-rename.md b/.changeset/37086-define-metadata-form-rename.md new file mode 100644 index 00000000000..b73c84f9827 --- /dev/null +++ b/.changeset/37086-define-metadata-form-rename.md @@ -0,0 +1,21 @@ +--- +'@objectstack/spec': patch +'@objectstack/lint': patch +--- + +refactor(spec)!: the Studio metadata-form helper `defineForm` is renamed `defineMetadataForm`, and its modules move from `*.form.ts` to `*.metadata-form.ts`, so the name and the suffix are free for the `form` metadata type (ADR-0159) + +Clause-②: yes (narrowing) +Metadata-protocol: none + +ADR-0159 makes `form` a metadata type of its own, and the maintainer ruled that its factory is `defineForm` (question 1, option A). The helper that held the name builds something else: a schema-bound form for Studio's metadata editors (`data.provider: 'schema'`). It is renamed after the translation family its forms feed (`metadataForms`), with the same argument and the same result, and its 18 modules under `packages/spec/src` are renamed with it. `defineForm` is absent from `@objectstack/spec` until the `form` type lands with it, in the same major; it never has two meanings. Nothing a metadata author writes changes: no stack, no stored row and no spec key names the helper, which is why the protocol line is `none`. + + + +**BREAKING** (a published export is renamed), shipped as `patch`: the change is not to the metadata protocol (`Metadata-protocol: none`). + +- **FROM:** `import { defineForm } from '@objectstack/spec'` (or `@objectstack/spec/ui`), `defineForm({ schemaId, … })` in a `NAME.form.ts` module. +- **TO:** `import { defineMetadataForm } from '@objectstack/spec'` (or `@objectstack/spec/ui`), `defineMetadataForm({ schemaId, … })` in a `NAME.metadata-form.ts` module. +- **The fix:** rename the import and the call; rename a module that builds one to `*.metadata-form.ts`. The compiler names every call site (`TS2305` / `TS2724`). +- **Outside use, read before the rename:** no import or call of `defineForm` in any public repository of the organization, nor in the cloud repository. +- `@objectstack/lint`: the explanation of `visibility-root-mislayered` and the `data`-root message of the field-rule check name the Studio modules by their new suffix (`*.metadata-form.ts`); what each rule reports is unchanged. diff --git a/content/docs/protocol/objectui/layout-dsl.mdx b/content/docs/protocol/objectui/layout-dsl.mdx index 93166737927..1df028612d4 100644 --- a/content/docs/protocol/objectui/layout-dsl.mdx +++ b/content/docs/protocol/objectui/layout-dsl.mdx @@ -929,7 +929,7 @@ The predicate's **binding root** is set by the layer, not the key: | Page components (`*.page.ts`) | `record` + `current_user` (plus `page.`) | | Runtime record form **fields** (`*.view.ts`) | `record` + `previous` + `current_user` (objectui#6010) | | Runtime record form **sections** (`*.view.ts`) | `record` + `previous` + `current_user` (objectui#6110 + #6111) | -| Metadata-editing forms (`*.form.ts`) | `data` — the row under edit | +| Metadata-editing forms (`*.metadata-form.ts`) | `data` — the row under edit | The two form rows were one row until objectui#6010 bound the host predicate scope on the SDUI form renderer's authored-predicate call sites — at that point only the diff --git a/content/docs/references/ui/view.mdx b/content/docs/references/ui/view.mdx index 0cab105f67b..b2559b43a93 100644 --- a/content/docs/references/ui/view.mdx +++ b/content/docs/references/ui/view.mdx @@ -206,7 +206,7 @@ Column footer summary configuration | :--- | :--- | :--- | :--- | | **field** | `string` | ✅ | Field name (snake_case) | | **type** | `Enum<'text' \| 'textarea' \| 'email' \| 'url' \| 'phone' \| 'password' \| 'secret' \| 'markdown' \| 'html' \| 'richtext' \| 'number' \| 'currency' \| 'percent' \| 'date' \| … +35 more>` | optional | Field type (auto-infers widget if omitted) | -| **options** | `{ label: string; value: string; description?: string; color?: string; … }[]` | optional | Options for select/multiselect/radio/checkboxes fields (per-option `default` is not accepted here — declare the pre-selected choice on the object definition). On a metadata form (schema-bound, built by `defineForm`), an enum-typed row may list its members here, to give them human labels or to offer a deliberate subset. An option `value` is a lowercase system identifier, so a row whose members cannot be spelled as option values (a hyphen, a capital) omits `options`: the control derives the members from the served JSON Schema, and their meanings go in `helpText`. | +| **options** | `{ label: string; value: string; description?: string; color?: string; … }[]` | optional | Options for select/multiselect/radio/checkboxes fields (per-option `default` is not accepted here — declare the pre-selected choice on the object definition). On a metadata form (schema-bound, built by `defineMetadataForm`), an enum-typed row may list its members here, to give them human labels or to offer a deliberate subset. An option `value` is a lowercase system identifier, so a row whose members cannot be spelled as option values (a hyphen, a capital) omits `options`: the control derives the members from the served JSON Schema, and their meanings go in `helpText`. | | **reference** | `string` | optional | Target object name for lookup/master_detail fields | | **publicPicker** | `never` | optional | [REMOVED] `view.form.sections[].fields[].publicPicker` was removed in @objectstack/spec 17.6.0 (ADR-0087 D2) — an anonymous public form no longer offers record search: lookup, `master_detail` and `user` fields are always left off the anonymous rendering, and the anonymous record-search route (`GET /forms/:slug/lookup/:field`) no longer exists. Delete the key (the whole `publicPicker` block). To let a visitor choose from a fixed list, use a `select` field with static `options`; to let them pick an existing record, put the form behind sign-in. 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. | | **maxLength** | `integer` | optional | Maximum character length (positive integer; for text/textarea/email/url/phone) | @@ -336,7 +336,7 @@ Form-view select option — the object-field option shape minus the per-option ` | :--- | :--- | :--- | :--- | | **field** | `string` | ✅ | Field name (snake_case) | | **type** | `Enum<'text' \| 'textarea' \| 'email' \| 'url' \| 'phone' \| 'password' \| 'secret' \| …>` | optional | Field type (auto-infers widget if omitted) | -| **options** | `{ label: string; value: string; description?: string; color?: string; … }[]` | optional | Options for select/multiselect/radio/checkboxes fields (per-option `default` is not accepted here — declare the pre-selected choice on the object definition). On a metadata form (schema-bound, built by `defineForm`), an enum-typed row may list its members here, to give them human labels or to offer a deliberate subset. An option `value` is a lowercase system identifier, so a row whose members cannot be spelled as option values (a hyphen, a capital) omits `options`: the control derives the members from the served JSON Schema, and their meanings go in `helpText`. | +| **options** | `{ label: string; value: string; description?: string; color?: string; … }[]` | optional | Options for select/multiselect/radio/checkboxes fields (per-option `default` is not accepted here — declare the pre-selected choice on the object definition). On a metadata form (schema-bound, built by `defineMetadataForm`), an enum-typed row may list its members here, to give them human labels or to offer a deliberate subset. An option `value` is a lowercase system identifier, so a row whose members cannot be spelled as option values (a hyphen, a capital) omits `options`: the control derives the members from the served JSON Schema, and their meanings go in `helpText`. | | **reference** | `string` | optional | Target object name for lookup/master_detail fields | | **publicPicker** | `never` | optional | [REMOVED] `view.form.sections[].fields[].publicPicker` was removed in @objectstack/spec 17.6.0 (ADR-0087 D2) — an anonymous public form no longer offers record search: lookup, `master_detail` and `user` fields are always left off the anonymous rendering, and the anonymous record-search route (`GET /forms/:slug/lookup/:field`) no longer exists. Delete the key (the whole `publicPicker` block). To let a visitor choose from a fixed list, use a `select` field with static `options`; to let them pick an existing record, put the form behind sign-in. 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. | | **maxLength** | `integer` | optional | Maximum character length (positive integer; for text/textarea/email/url/phone) | diff --git a/docs/qa/platform-checklist/areas/studio-authoring.json b/docs/qa/platform-checklist/areas/studio-authoring.json index 0c931f2b410..021bd28a2e9 100644 --- a/docs/qa/platform-checklist/areas/studio-authoring.json +++ b/docs/qa/platform-checklist/areas/studio-authoring.json @@ -5653,7 +5653,7 @@ { "clause": "Studio's dataset form offers Synonyms and Description on the measure row, with the help text that states the limits", "oracle": "dom", - "verify": "the measure row shows Synonyms holding 'bill count' and '账单数', and Description holding the sentence; the Synonyms help text says 'At most 20, each at most 60 characters'. Studio draws them in DatasetDefaultInspector's row Advanced fold through DatasetMemberVocabulary (ui/packages/app-shell/src/views/metadata-admin/inspectors/DatasetMemberVocabulary.tsx, data-testid dataset-measures-synonyms / dataset-measures-description), which takes its label and help copy from the spec form (packages/spec/src/ui/dataset.form.ts#datasetForm)", + "verify": "the measure row shows Synonyms holding 'bill count' and '账单数', and Description holding the sentence; the Synonyms help text says 'At most 20, each at most 60 characters'. Studio draws them in DatasetDefaultInspector's row Advanced fold through DatasetMemberVocabulary (ui/packages/app-shell/src/views/metadata-admin/inspectors/DatasetMemberVocabulary.tsx, data-testid dataset-measures-synonyms / dataset-measures-description), which takes its label and help copy from the spec form (packages/spec/src/ui/dataset.metadata-form.ts#datasetForm)", "evidence": "a screenshot of the measure row" } ], @@ -5673,7 +5673,7 @@ "packages/spec/src/ui/dataset.zod.ts#normalizeDatasetTerm", "packages/spec/src/ui/dataset.zod.ts#DatasetMemberSynonymsSchema", "packages/spec/src/ui/dataset.zod.ts#checkDatasetVocabulary", - "packages/spec/src/ui/dataset.form.ts#datasetForm" + "packages/spec/src/ui/dataset.metadata-form.ts#datasetForm" ], "history": [ { diff --git a/packages/cli/src/commands/i18n/extract.ts b/packages/cli/src/commands/i18n/extract.ts index 04eb00e34b5..c66cdc0ee25 100644 --- a/packages/cli/src/commands/i18n/extract.ts +++ b/packages/cli/src/commands/i18n/extract.ts @@ -451,7 +451,7 @@ export default class I18nExtract extends Command { * `@objectstack/platform-objects` owns. Those records are unreadable here * (no `metadataForms` bundle exists in this package for them to be about), * and they would move all three of this package's companions every time an - * unrelated `*.form.ts` in `packages/spec` changed — the same cross-package + * unrelated `*.metadata-form.ts` in `packages/spec` changed — the same cross-package * coupling ADR-0029 D8 and each package's `bundle-ownership.test.ts` exist * to keep out of its committed bundles. * diff --git a/packages/cli/src/utils/config.ts b/packages/cli/src/utils/config.ts index 326000f39c0..f41cd8ed7ac 100644 --- a/packages/cli/src/utils/config.ts +++ b/packages/cli/src/utils/config.ts @@ -594,7 +594,7 @@ const AUTHORED_SOURCE_PRELUDE: readonly string[] = [ * * - **A source that loads today evaluates identically.** The real helper * runs, so every value the module builds is the value it builds today, with - * each helper's defaults and transforms (`defineForm` moves `schemaId` into + * each helper's defaults and transforms (`defineMetadataForm` moves `schemaId` into * `data`, …). The one difference is which value the chain starts from: an * accepted `defineStack` call's ARGUMENT, not its result (see "An accepted * `defineStack` call" below). diff --git a/packages/cli/src/utils/i18n-bundle-extract.ts b/packages/cli/src/utils/i18n-bundle-extract.ts index d836afc8c50..c632d6935ab 100644 --- a/packages/cli/src/utils/i18n-bundle-extract.ts +++ b/packages/cli/src/utils/i18n-bundle-extract.ts @@ -561,7 +561,7 @@ export function renderSourceHashModule( * digests of the Studio metadata-form baseline `@objectstack/platform-objects` * owns — unreadable in that package (no `metadataForms` bundle exists there for * them to be about) and re-written in all three of its companions every time an - * unrelated `*.form.ts` in `packages/spec` moved. That is the cross-package + * unrelated `*.metadata-form.ts` in `packages/spec` moved. That is the cross-package * coupling ADR-0029 D8 and each package's `bundle-ownership.test.ts` keep out of * the committed bundles; the companion is not exempt from it. * diff --git a/packages/cli/test/i18n-duplicate-demand.test.ts b/packages/cli/test/i18n-duplicate-demand.test.ts index a37b9066eba..7187c2fcd27 100644 --- a/packages/cli/test/i18n-duplicate-demand.test.ts +++ b/packages/cli/test/i18n-duplicate-demand.test.ts @@ -29,7 +29,7 @@ * reference, measured on all three baselined example configs — so both * action branches emit `objects.OBJECT._actions.ACTION.*`. * - Two declarations, one form field. `deleteBehavior` is declared twice in - * each of `field.form.ts` / `object.form.ts`, gated on `visibleWhen`; both + * each of `field.metadata-form.ts` / `object.metadata-form.ts`, gated on `visibleWhen`; both * render into one key. Config-independent — it duplicates six entries on an * EMPTY config, and it never reaches `os lint`'s report, which hides the * `metadataForms` bucket unless `--include-platform` is passed. A diff --git a/packages/cli/test/i18n-extract-metadata-forms-flag.e2e.test.ts b/packages/cli/test/i18n-extract-metadata-forms-flag.e2e.test.ts index 5b2c023d2ca..b904b4de977 100644 --- a/packages/cli/test/i18n-extract-metadata-forms-flag.e2e.test.ts +++ b/packages/cli/test/i18n-extract-metadata-forms-flag.e2e.test.ts @@ -39,7 +39,7 @@ * invisible to `toContain`, and a duplicate is half of what this closes. * * ⛔ Not asserted: the exact baseline key count. It is registry-driven and - * moves with every `*.form.ts` in `packages/spec`; pinning it here would make + * moves with every `*.metadata-form.ts` in `packages/spec`; pinning it here would make * this file fail for reasons that have nothing to do with the flags. What is * pinned is the INVARIANT — the baseline is in the companion or nowhere, and * never in two places at once. diff --git a/packages/lint/src/i18n-walk.ts b/packages/lint/src/i18n-walk.ts index 839003b0f47..71d67f76614 100644 --- a/packages/lint/src/i18n-walk.ts +++ b/packages/lint/src/i18n-walk.ts @@ -1933,8 +1933,8 @@ export function collectExpectedEntries( * actions to the object (`obj.actions`) *and* to the top-level `actions` * list — measured to be the SAME object reference, not a copy — so the two * action branches above both emit `objects.._actions..*`. - * - **Two declarations, one form field.** `field.form.ts` and - * `object.form.ts` each declare `deleteBehavior` twice, gated on + * - **Two declarations, one form field.** `field.metadata-form.ts` and + * `object.metadata-form.ts` each declare `deleteBehavior` twice, gated on * `visibleWhen` (`lookup` vs `master_detail`). Both variants render into * the same key, because {@link walkFormField} keys on the field path. * Config-independent: it duplicates six entries on *every* config, diff --git a/packages/lint/src/lint-liveness-properties.test.ts b/packages/lint/src/lint-liveness-properties.test.ts index 74be56ffb0a..39f2cdf693d 100644 --- a/packages/lint/src/lint-liveness-properties.test.ts +++ b/packages/lint/src/lint-liveness-properties.test.ts @@ -283,7 +283,7 @@ describe('lintLivenessProperties', () => { // sweep (tombstones refuse them at parse); their rows stay `dead`, so handed // an unparsed stack the rule grades them dead (#16094 — see the flow pin // above). form.data is the sweep's one CORRECTION: the removal attempt broke - // the build — defineForm writes data.provider='schema' on every metadata + // the build — defineMetadataForm writes data.provider='schema' on every metadata // form — so its ledger entry flipped to live and it must stay silent. // // #25767: `list.responsive` / `form.defaultSort` were ≤16.x retirements, so diff --git a/packages/lint/src/predicate-rhs-position.ts b/packages/lint/src/predicate-rhs-position.ts index 067488b7a65..0e4a2f0510e 100644 --- a/packages/lint/src/predicate-rhs-position.ts +++ b/packages/lint/src/predicate-rhs-position.ts @@ -154,7 +154,7 @@ function isRec(v: unknown): v is AnyRec { /** * The `schemaId` a form view resolves its row shape from, or `undefined` when * the view is not schema-bound. Read off `ViewDataSourceSchema`'s `schema` - * member (`view.zod.ts:151-161`) — the shape `defineForm` writes. + * member (`view.zod.ts:151-161`) — the shape `defineMetadataForm` writes. * * Shared rather than duplicated: it is the test for "the metadata-admin * evaluator renders this", which is the precondition BOTH the rule that diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 34b8b040634..167dfcb23b0 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -1200,7 +1200,7 @@ const VISIBILITY_ROOT_MISLAYERED_EXPLANATION: RuleExplanation = { paragraphs: [ 'ADR-0089 D3 binds a different root on each layer. A runtime view or page surface binds the live ' + 'record as `record`, plus `current_user` (and page state as `page.VAR` on a page component); a ' + - 'metadata-editing form — a `*.form.ts` module or a schema-bound form view — binds the row under ' + + 'metadata-editing form — a `*.metadata-form.ts` module or a schema-bound form view — binds the row under ' + 'edit as `data`.', 'A predicate rooted at the other layer\'s namespace never matches, and the element renders ' + 'unconditionally. The rule is a warning rather than an error because the root is at least a ' + diff --git a/packages/lint/src/validate-expressions.ts b/packages/lint/src/validate-expressions.ts index 47d488876b0..48066b1fd10 100644 --- a/packages/lint/src/validate-expressions.ts +++ b/packages/lint/src/validate-expressions.ts @@ -999,7 +999,7 @@ function rulePredicates(rule: AnyRec, path: string, depth = 0, keyPrefix = ''): * - `data.status == 'x'` — `data` is the LEGAL root of this very * `visibleWhen` key on a METADATA form (`view.zod.ts`: "Root: `record` … * in runtime forms, or `data` in metadata forms"). Two form kinds, one key - * name, different roots — and the repo's own `*.form.ts` files are full of + * name, different roots — and the repo's own `*.metadata-form.ts` files are full of * the `data` spelling for an author to copy. * * A denylist cannot track `SCOPE_ROOTS`: every root added there is unreported @@ -1339,7 +1339,7 @@ const FIELD_RULE_SLOT_CONSEQUENCE: Record = { 'the predicate no longer merely faults — and BOTH of its outcomes are wrong, in opposite ' + 'directions. Under a host that publishes a predicate scope the renderer RESOLVES it ' + // `sectionFields` is spelled WITHOUT its `.ts` extension for the same - // reason the `*.form` spelling below is: this is a STRING literal, and + // reason the `*.metadata-form` spelling below is: this is a STRING literal, and // #5017's receiver scan strips comments but not strings, so `sectionFields.ts` // inside the message registers `sectionFields` as a read receiver of this // rule. Measured — it went red on the first run, exactly as the sibling did. @@ -1448,11 +1448,11 @@ export function fieldRuleRootIssue( `but only in the renderer, so moving a server-enforced object rule there swaps a loud ` + `error for a silent enforcement gap; it is not a fourth answer.` : root === 'data' - // The `*.form` spelling is deliberately not `*.form.ts`: this is a + // The `*.metadata-form` spelling is deliberately not `*.metadata-form.ts`: this is a // STRING literal, and #5017's receiver scan strips comments but not // strings, so `form.ts` inside the message registers `form` as a read // receiver of this rule. Measured — it went red on the first run. - ? `\`data\` is the root of a METADATA form (a \`*.form\` module — the metadata row ` + + ? `\`data\` is the root of a METADATA form (a \`*.metadata-form\` module — the metadata row ` + `being edited); ` + `this is an OBJECT field, whose runtime form binds the row as \`record\` — one key name, ` + `two form kinds, two roots. Rewrite \`data.\` as \`record.\`.` diff --git a/packages/lint/src/validate-predicate-path-refs.test.ts b/packages/lint/src/validate-predicate-path-refs.test.ts index 14bb87b5229..08ea135c4ad 100644 --- a/packages/lint/src/validate-predicate-path-refs.test.ts +++ b/packages/lint/src/validate-predicate-path-refs.test.ts @@ -9,7 +9,7 @@ * metadata forms this repo actually SHIPS (`METADATA_FORM_REGISTRY`), which is * both the corpus count the widening discipline requires before an `error`-level * gate may land, and the reverse verification — restoring #6254's pre-fix - * `object.form.ts` spellings must turn the count from 0 to the number of + * `object.metadata-form.ts` spellings must turn the count from 0 to the number of * `data.type`-rooted predicates that form ships today (17; #6254 itself * measured 16, and #11410 added the second `deleteBehavior` declaration). */ @@ -78,7 +78,7 @@ const explanationOf = (rule: string): string => explainRule(rule)?.paragraphs.jo const resolveSchema = (schemaId: string) => (schemaId === 'demo' ? DemoSchema : undefined); const run = (stack: Record) => validatePredicatePathRefs(stack, { resolveSchema }); -/** A `defineForm`-shaped view: the bare FormView with a schema data source. */ +/** A `defineMetadataForm`-shaped view: the bare FormView with a schema data source. */ const form = (sections: unknown[], schemaId = 'demo') => ({ views: [{ name: 'demo_form', data: { provider: 'schema', schemaId }, sections }], }); @@ -511,7 +511,7 @@ describe('registry wiring', () => { // // `METADATA_FORM_REGISTRY` is the whole population of `data.`-rooted predicates // this repo ships (17 forms; 48 predicates, all `visibleWhen`). Every entry is a -// `defineForm` output, i.e. exactly the bare FormView shape `formViewSites` +// `defineMetadataForm` output, i.e. exactly the bare FormView shape `formViewSites` // walks as its `self` rung — so the corpus is fed through the rule's PRODUCTION // entry point, not through a parallel walker written for the test. // @@ -566,7 +566,7 @@ describe('#7010 corpus — shipped METADATA_FORM_REGISTRY', () => { }; corrupt(corrupted.views); // The count tracks the CORPUS, not an issue: 49 after #13216 added - // a `page` section to `view.form.ts` — the surface block for the new `page` + // a `page` section to `view.metadata-form.ts` — the surface block for the new `page` // view type, gated by `visibleWhen: "data.type == 'page'"` exactly as every // other surface block is — so the walk has one more predicate to reach. // It was 51 after objectui#6140 (maintainer ruling 2026-08-25, Option A) @@ -586,7 +586,7 @@ describe('#7010 corpus — shipped METADATA_FORM_REGISTRY', () => { // removed. Earlier measurements stay what they were: history, not the census. // It is 52 today, and this one is a REMOVAL: #17063 retired the // `type: 'page'` list-view mount under ADR-0049 enforce-or-remove, and - // `view.form.ts`'s `page` section — the single `pageName` input gated + // `view.metadata-form.ts`'s `page` section — the single `pageName` input gated // `data.type == 'page'` — went with the key it configured. A form input for // an unwritable key is the false-compliant UI half of a retirement, so the // census falls by exactly one. @@ -611,11 +611,11 @@ describe('#7010 corpus — shipped METADATA_FORM_REGISTRY', () => { // accepts each key whatever the sibling value is, but only some field // types, page kinds or action operations ever read it, and offering a knob // the runtime does not deliver is what Prime Directive #10 forbids. Fifteen - // are `field.form.ts` rows mirrored from the same key's row in the object + // are `field.metadata-form.ts` rows mirrored from the same key's row in the object // designer's quick-add grid, so the two surfaces cannot disagree about when // a knob applies; the other four are `page :: source`, `action :: openIn`, // `action :: newTabUrl` and `action :: undoable`. - // Measured rather than inferred from the delta: the shipped `*.form.ts` + // Measured rather than inferred from the delta: the shipped `*.metadata-form.ts` // corpus was differenced against the merge base `5ce3705052` by // `
::::`. Exactly nineteen entries were added and NONE // was removed — `field :: ackPlaintextMasking | allowCreate | @@ -651,13 +651,13 @@ describe('#7010 corpus — shipped METADATA_FORM_REGISTRY', () => { // It is 83 today, an ADDITION of ONE: the field form's `useGrouping` row, // offered once the key was enforced, carries `scale`'s gate — the key is a // display hint for `number` fields only. Measured, not inferred: the - // shipped `*.form.ts` corpus differenced against the merge base + // shipped `*.metadata-form.ts` corpus differenced against the merge base // `d78a0bda07` adds exactly `field :: useGrouping :: data.type == 'number'` // and removes none. // It is 85 today, an ADDITION of TWO: #21863 offered the action form's // `outcomeMessages` and `onSuccess` rows, each gated on the two action types // whose parse accepts the key. Measured, not inferred: the shipped - // `*.form.ts` corpus differenced against the merge base `607463d736` by + // `*.metadata-form.ts` corpus differenced against the merge base `607463d736` by // `::::`, 83 → 85, adds exactly // `action :: outcomeMessages` and `action :: onSuccess`, both // `data.type == 'api' || data.type == 'script'`, and removes none. The two @@ -666,7 +666,7 @@ describe('#7010 corpus — shipped METADATA_FORM_REGISTRY', () => { // `dueLike` and `settledWhen` rows, the deadline semantic. These two are // PARSE gates, not meaningfulness gates: `FieldSchema` refuses both keys off // `date` / `datetime`, and `settledWhen` without `dueLike: true`. Measured, - // not inferred: the shipped `*.form.ts` corpus differenced against the + // not inferred: the shipped `*.metadata-form.ts` corpus differenced against the // merge base `dee7692f0b` by `::::`, 85 → 87, adds // exactly `field :: dueLike :: data.type in ['date','datetime']` and // `field :: settledWhen :: data.type in ['date','datetime'] && data.dueLike @@ -676,7 +676,7 @@ describe('#7010 corpus — shipped METADATA_FORM_REGISTRY', () => { // It is 88 today, an ADDITION of ONE: #22870 offered the field form's // `mailAssociation` row, a PARSE gate like the deadline pair (`FieldSchema` // refuses the key off `email`). Measured, not inferred: the shipped - // `*.form.ts` corpus differenced against the merge base `018b077fb` by + // `*.metadata-form.ts` corpus differenced against the merge base `018b077fb` by // `::::`, 87 → 88, adds exactly // `field :: mailAssociation :: data.type == 'email'` and removes none. It // does reach the literal-comparison census below. @@ -784,7 +784,7 @@ describe('#7010 corpus — shipped METADATA_FORM_REGISTRY', () => { // note above) — exactly the #11566 (PR #11989) respell of the sibling // `maxLength` row, which took the measurement from 47 to 44. Earlier // measurements stay what they were — history, not the census. It was 42 - // when #13216's `page` section in `view.form.ts` carried a + // when #13216's `page` section in `view.metadata-form.ts` carried a // `data.type == 'page'` gate; it is 41 today because #17063 retired that // section with the `type: 'page'` mount it configured (ADR-0049 // enforce-or-remove), taking that one `==` literal comparison with it. The @@ -850,7 +850,7 @@ describe('#7010 corpus — shipped METADATA_FORM_REGISTRY', () => { it('catches the pre-#6254 bare spellings when they are restored (reverse verification)', () => { // The reverse direction is RED-on-restore: #6254 rewrote 16 predicates in - // `object.form.ts` from `type ...` to `data.type ...`. Restoring the bare + // `object.metadata-form.ts` from `type ...` to `data.type ...`. Restoring the bare // spelling on a deep copy of the shipped `object` form must produce one // `predicate-path-unrooted` finding per `data.type`-rooted predicate the // form ships — the class the issue measured, and the class this rule exists @@ -881,7 +881,7 @@ describe('#7010 corpus — shipped METADATA_FORM_REGISTRY', () => { } if (!node || typeof node !== 'object') return; const rec = node as Record; - // `defineForm` PARSES, so a shipped predicate is the post-parse + // `defineMetadataForm` PARSES, so a shipped predicate is the post-parse // `{ dialect, source }` envelope, not the raw string the source file spells. const predicate = rec.visibleWhen; const source = typeof predicate === 'string' ? predicate diff --git a/packages/lint/src/validate-predicate-path-refs.ts b/packages/lint/src/validate-predicate-path-refs.ts index bd2a70c367a..e46a78c451c 100644 --- a/packages/lint/src/validate-predicate-path-refs.ts +++ b/packages/lint/src/validate-predicate-path-refs.ts @@ -29,8 +29,8 @@ * through the one door the family's own gates leave open. * * The gap is not hypothetical on this exact surface. #6254 measured 16 - * predicates in `packages/spec/src/data/object.form.ts` written as BARE - * identifiers (`type == 'formula'`) where the sibling `field.form.ts` wrote + * predicates in `packages/spec/src/data/object.metadata-form.ts` written as BARE + * identifiers (`type == 'formula'`) where the sibling `field.metadata-form.ts` wrote * `data.type` — and stated, in as many words, why the #6128 gate structurally * could not catch them: `type` is an identifier **CEL itself declares** (it * denotes a type value), so the strict-environment checker reports a type @@ -41,7 +41,7 @@ * This rule does not have that blind spot, because it never asks CEL what * resolves. It asks the **target schema** — a closed, enumerable key set — and * CEL's own type-name vocabulary has no bearing on whether `type` is a key of - * `FieldSchema`. Measured: restoring #6254's pre-fix `object.form.ts` makes this + * `FieldSchema`. Measured: restoring #6254's pre-fix `object.metadata-form.ts` makes this * rule report exactly those 16 sites (see the reverse-verification test). * * ## Scope: the `data.*` layer only, and why that is a decision @@ -50,7 +50,7 @@ * set the rule can enumerate, where "absent" really means "cannot resolve". That * is true for exactly one of the two binding layers ADR-0089 D3 names: * - * - **metadata-editing forms** (`data`, a `defineForm` whose data source is + * - **metadata-editing forms** (`data`, a `defineMetadataForm` whose data source is * `{ provider: 'schema', schemaId }` — `view.zod.ts:151-161`). The row under * edit is an instance of a metadata type, and its shape is a Zod schema this * package can read key by key through the canonical @@ -113,7 +113,7 @@ * A sub-field of a `type: 'record'` / `repeater` / `composite` entry is rendered * with its own activation: objectui's metadata SchemaForm evaluates it as * `evaluatePredicate(spec.visibleOn, { data: row })` (its own runtime slot, - * which the form fills from the spec's `visibleWhen`). So inside `object.form.ts`'s + * which the form fills from the spec's `visibleWhen`). So inside `object.metadata-form.ts`'s * `fields` repeater, `data.type` means *this row's* `type` — `FieldSchema.type`, * not `ObjectSchema.type` (which does not exist). `view.zod.ts:1647-1657` states * both halves: the root is still spelled `data` at every depth, and the object it @@ -795,7 +795,7 @@ function walkFields( * declare (#7010). * * Walks `views[]` through the shared {@link formViewSites} ladder — the entry - * itself (the bare `defineForm` shape every `*.form.ts` uses), the container's + * itself (the bare `defineMetadataForm` shape every `*.metadata-form.ts` uses), the container's * default `form`, and each `formViews.` — and judges only the sites whose * data source is `{ provider: 'schema', schemaId }`, resolving `schemaId` * through `opts.resolveSchema` (the canonical metadata-type registry by @@ -807,7 +807,7 @@ function walkFields( * build on them. The corpus measurement behind that severity is on the PR for * #7010: over the shipped `METADATA_FORM_REGISTRY` (17 forms, 46 predicates) the * count is **0** for both, and 16 for `predicate-path-unrooted` once #6254's - * pre-fix `object.form.ts` is restored. + * pre-fix `object.metadata-form.ts` is restored. * * The third rule, `predicate-rhs-path-shaped` (#7659), asks a different question * about the same predicates — whether a `==` / `!=` RIGHT-hand side is diff --git a/packages/lint/src/validate-visibility-predicates.test.ts b/packages/lint/src/validate-visibility-predicates.test.ts index eaaa9f1c7f0..45c8650bb3e 100644 --- a/packages/lint/src/validate-visibility-predicates.test.ts +++ b/packages/lint/src/validate-visibility-predicates.test.ts @@ -302,7 +302,7 @@ describe('the layer a site declares for itself (#7815)', () => { }); it('`opts.layer` still governs every site that declares no data source', () => { - // The file-aware caller's contract is unchanged: a `*.form.ts` whose form + // The file-aware caller's contract is unchanged: a `*.metadata-form.ts` whose form // carries no `data: { provider: 'schema' }` is still only reachable through // the option, and a page component always is. expect(validateVisibilityPredicates(runtimeForm("data.type == 'grid'"), { layer: 'metadata' })) @@ -519,7 +519,7 @@ describe('visibility-bare-identifier (#6128 / #5149 requirement 3)', () => { expect(bareFindings(stack).map((f) => f.path)).toEqual(['views[0].form.sections[0]']); }); - it('a bare form view whose `sections` sit at the top (the `defineForm` shape)', () => { + it('a bare form view whose `sections` sit at the top (the `defineMetadataForm` shape)', () => { const stack = { views: [{ name: 'v', sections: [{ visibleWhen: 'approved', fields: [] }] }] }; expect(bareFindings(stack).map((f) => f.path)).toEqual(['views[0].sections[0]']); }); @@ -1543,7 +1543,7 @@ describe('visibility-predicate-over-budget (#7217)', () => { }); it('speaks the LAYER\'s binding root in its remedy', () => { - // A `*.form.ts` author binds `data`, so a `record.`-flavoured example would + // A `*.metadata-form.ts` author binds `data`, so a `record.`-flavoured example would // be a second wrong prescription in a rule whose whole point is that the // prescription must be followable. const metadata = overBudgetFindings(formStack(OVER_AST_NODES), { layer: 'metadata' }); @@ -1570,7 +1570,7 @@ describe('visibility-predicate-over-budget (#7217)', () => { // (`authoring-rules.ts` → `validateVisibilityPredicates(stack)`, no options): // a form view declaring `data: { provider: 'schema', schemaId }` is judged // there on its own say-so. That door's audience is a Studio / REST `/meta` / -// MCP author who has no `*.form.ts` to open, so a message that justified the +// MCP author who has no `*.metadata-form.ts` to open, so a message that justified the // layer by naming that file prescribed correctly and then explained itself // somewhere the reader cannot go. // @@ -1588,8 +1588,8 @@ describe('emitted prose names the surface, not a source file (#8042)', () => { }], }); - /** Any `*.view.ts` / `*.page.ts` / `*.form.ts` spelling, in any position. */ - const SOURCE_FILENAME = /\.(form|view|page)\.ts/; + /** Any `*.view.ts` / `*.page.ts` / `*.metadata-form.ts` spelling, in any position. */ + const SOURCE_FILENAME = /[.-](form|view|page)\.ts/; it('the mis-layered advisory explains the metadata layer without naming a file', () => { const f = validateVisibilityPredicates(publishedForm("record.type == 'grid'")) @@ -1617,7 +1617,7 @@ describe('emitted prose names the surface, not a source file (#8042)', () => { it('the RUNTIME arm is file-free too — the mirror sentence carried the same defect', () => { // A view or page published through Studio has no `*.view.ts` either, and - // this arm explained the forbidden `data.` root by naming `*.form.ts`. Same + // this arm explained the forbidden `data.` root by naming `*.metadata-form.ts`. Same // class, other direction; fixing only the graded arm would have left half // the sentence pointing at a file. const f = validateVisibilityPredicates(formStack("data.type == 'grid'"))[0]; @@ -1659,7 +1659,7 @@ describe('emitted prose names the surface, not a source file (#8042)', () => { it('the file-aware caller reads the SAME prose — this changed strings, not a code path', () => { // `MISLAYER_BY_LAYER` is keyed by LAYER, not by how the layer was decided, // so a caller passing `opts.layer = 'metadata'` (the file-aware caller, - // linting a real `*.form.ts`) reads exactly what the published-through- + // linting a real `*.metadata-form.ts`) reads exactly what the published-through- // Studio author reads. Pinned because the tempting shape of this fix — fork // the wording by caller and give the file-aware one its filename back — is // two messages for one condition, which #5240 rules out. @@ -1676,15 +1676,15 @@ describe('emitted prose names the surface, not a source file (#8042)', () => { it('the file-aware CALLER contract keeps its filename — this was not a find-and-replace', () => { // The discrimination that IS the card. What was wrong is prose addressed to // an AUTHOR who may hold no file; `opts.layer` is addressed to a CALLER that - // is linting one, where `*.form.ts` is both accurate and the useful word. A + // is linting one, where `*.metadata-form.ts` is both accurate and the useful word. A // blanket strip would have deleted that too, and would pass every assertion // above — this is the one that notices. const source = readFileSync( join(dirname(fileURLToPath(import.meta.url)), 'validate-visibility-predicates.ts'), 'utf8', ); - expect(source).toContain('a file-aware caller linting a `*.form.ts` does'); - expect(source).toContain('when linting a `*.form.ts` metadata-editing form'); + expect(source).toContain('a file-aware caller linting a `*.metadata-form.ts` does'); + expect(source).toContain('when linting a `*.metadata-form.ts` metadata-editing form'); }); }); @@ -1901,7 +1901,7 @@ describe('[#22161] one-line verdicts — the rule ids this file shortened', () = // What each verdict stopped saying, which `os explain RULE_ID` now prints. const MOVED: Record = { - [VISIBILITY_ROOT_MISLAYERED]: ['ADR-0089', '`*.form.ts`', '`page.VAR`'], + [VISIBILITY_ROOT_MISLAYERED]: ['ADR-0089', '`*.metadata-form.ts`', '`page.VAR`'], [VISIBILITY_PREDICATE_OVER_BUDGET]: ['falls OPEN', 'settled behaviour', 'SIZE fault', '`maxListElements` is 64'], [VISIBILITY_PREDICATE_SYNTAX]: ['falls OPEN', 'settled behaviour', 'ADR-0032', '`===`'], [VISIBILITY_PREDICATE_UNKNOWN_FUNCTION]: ['`throwOnError: true`', 'falls CLOSED', '`console.warn`', 'CEL_STDLIB_FUNCTIONS'], diff --git a/packages/lint/src/validate-visibility-predicates.ts b/packages/lint/src/validate-visibility-predicates.ts index e4fe792e009..7f15e891a4d 100644 --- a/packages/lint/src/validate-visibility-predicates.ts +++ b/packages/lint/src/validate-visibility-predicates.ts @@ -87,11 +87,11 @@ * predicate here is a wrong-layer paste that silently never matches; and * - **metadata-editing** forms — the row under edit — bind `data`, so a * `record.`-rooted predicate there is the same bug in the other direction. - * That surface is reached two ways: a `*.form.ts` module, and a form view + * That surface is reached two ways: a `*.metadata-form.ts` module, and a form view * declaring `data: { provider: 'schema', schemaId }`, which is judged here on * its own say-so whatever the caller passes (#7815). Only the first has a * file, which is why the EMITTED prose names the surface and never a filename - * (#8042) — the `*.form.ts` mentions that remain below are the ones addressed + * (#8042) — the `*.metadata-form.ts` mentions that remain below are the ones addressed * to a file-aware CALLER of this function, where the filename is the point. * The layer is read off the METADATA where the metadata declares it, and taken * from the caller (`opts.layer`, default `'runtime'`) only where it does not — @@ -606,7 +606,7 @@ export type VisibilitySeverity = 'error' | 'warning'; /** * Which binding environment the linted surface belongs to (ADR-0089 §Context): * - `runtime` — `*.view.ts` / `*.page.ts`; binds `record` + `current_user` (+ `page`). - * - `metadata` — metadata-editing forms (a `*.form.ts` module, or a form view + * - `metadata` — metadata-editing forms (a `*.metadata-form.ts` module, or a form view * declaring `data: { provider: 'schema', schemaId }`); binds `data` (the row * under edit). */ @@ -623,7 +623,7 @@ export interface VisibilityOptions { * row under edit as `data` — so such a site is judged at `'metadata'` * regardless of this option (#7815; see the module note §Which layer a site is * on). Pass `'metadata'` to cover the forms that do not carry that data source - * either, which is what a file-aware caller linting a `*.form.ts` does. + * either, which is what a file-aware caller linting a `*.metadata-form.ts` does. */ layer?: VisibilityLayer; } @@ -1331,7 +1331,7 @@ function rhsChainRoots(node: unknown, out: Set = new Set()): Set * The root an author on this layer should have written. Runtime view/page * surfaces bind the live record as `record`; a metadata-editing form binds the * row under edit as `data` (ADR-0089 D3, §Context) — whether that form was - * authored as a `*.form.ts` module or published as a schema-bound form view. + * authored as a `*.metadata-form.ts` module or published as a schema-bound form view. */ const CANONICAL_ROOT_BY_LAYER: Record = { runtime: 'record', @@ -1667,7 +1667,7 @@ function isFieldObject(entry: unknown): entry is AnyRec { * The binding-root check is layer-directional (ADR-0089 D3). A form view that * declares `data: { provider: 'schema', schemaId }` is judged at `metadata` on * its own say-so (#7815); for every other site pass `opts.layer = 'metadata'` - * when linting a `*.form.ts` metadata-editing form (so a `record.`-rooted + * when linting a `*.metadata-form.ts` metadata-editing form (so a `record.`-rooted * predicate is flagged), or leave it at the `'runtime'` default for `*.view.ts` / * `*.page.ts` surfaces (so a `data.`-rooted predicate is flagged). The syntax and * bare-identifier checks are layer-agnostic — but the ROOT their hints prescribe diff --git a/packages/lint/src/view-walk.ts b/packages/lint/src/view-walk.ts index 421ed01b383..5f24e2efd30 100644 --- a/packages/lint/src/view-walk.ts +++ b/packages/lint/src/view-walk.ts @@ -35,7 +35,7 @@ * down. * - **A bare FORM VIEW** (`FormViewSchema`, `view.zod.ts:1599`), whose * `sections` (`:1649`) and `groups` (`:1650`, the legacy alias) sit at the - * top. This is the `defineForm` shape the `*.form.ts` metadata-editing forms + * top. This is the `defineMetadataForm` shape the `*.metadata-form.ts` metadata-editing forms * use. * * | rung | `kind` | why it is walked | diff --git a/packages/metadata-protocol/src/protocol-meta-type-schema.ts b/packages/metadata-protocol/src/protocol-meta-type-schema.ts index da71b122af2..7e9037ee3c8 100644 --- a/packages/metadata-protocol/src/protocol-meta-type-schema.ts +++ b/packages/metadata-protocol/src/protocol-meta-type-schema.ts @@ -405,7 +405,7 @@ function toJsonSchemaSafe(schema: z.ZodTypeAny, typeLabel?: string): Record> = { // display order. The SchemaForm engine recognises // `additionalProperties` as a Record and dispatches to // the `record` form-field renderer (ADR-0007). The form - // layout in `object.form.ts` declares `type: 'record'` + // layout in `object.metadata-form.ts` declares `type: 'record'` // so the inner `additionalProperties` schema is used to // shape each value. type: 'object', diff --git a/packages/platform-objects/src/apps/translations/dashboard-header-children.test.ts b/packages/platform-objects/src/apps/translations/dashboard-header-children.test.ts index f37560257a0..c397ed53266 100644 --- a/packages/platform-objects/src/apps/translations/dashboard-header-children.test.ts +++ b/packages/platform-objects/src/apps/translations/dashboard-header-children.test.ts @@ -4,7 +4,7 @@ // children and the `header.actions[]` ROW properties, in every locale. // // Before this pin the four generated catalogs carried `header` alone: the -// extractor walks a form field's DECLARED `fields`, `dashboard.form.ts` +// extractor walks a form field's DECLARED `fields`, `dashboard.metadata-form.ts` // declared none under `header`, so no `header.` key was ever emitted // and the only localisation of those three children was a private overlay in // objectui. The row properties had no channel at all — a repeater's column @@ -50,7 +50,7 @@ const HEADER_CHILDREN = ['header.showTitle', 'header.showDescription', 'header.a const ROW_PROPERTIES = ['label', 'actionUrl', 'actionType', 'icon']; const ROW_KEYS = ROW_PROPERTIES.map((p) => `header.actions.${p}`); -/** The `actions` repeater as `dashboard.form.ts` declares it, children included. */ +/** The `actions` repeater as `dashboard.metadata-form.ts` declares it, children included. */ function declaredActionsRepeater(): any { for (const section of (dashboardForm as any).sections ?? []) { for (const field of section.fields ?? []) { @@ -83,7 +83,7 @@ describe('#16458 — dashboard header children and row properties in every catal it('en: each row-property leaf is the form\'s declared label, the English name the panel reads', () => { const repeater = declaredActionsRepeater(); - expect(repeater, 'dashboard.form.ts declares header.actions with children').toBeDefined(); + expect(repeater, 'dashboard.metadata-form.ts declares header.actions with children').toBeDefined(); const declared = new Map( (repeater.fields as any[]).map((f) => [String(f.field), String(f.label)]), ); @@ -115,7 +115,7 @@ describe('#16458 — dashboard header children and row properties in every catal // #14478) and is now a `retiredKey` tombstone — authoring it is a parse error // (`packages/spec/src/ui/dashboard.test.ts` pins the refusal). The live // authorable key is `refreshIntervalSeconds`, which is what these catalogs and -// `dashboard.form.ts` already name. +// `dashboard.metadata-form.ts` already name. // // The card's reading came from a substring: `refreshInterval` "occurs" in // `dashboard.zod.ts` only inside `refreshIntervalSeconds`, in the rename diff --git a/packages/platform-objects/src/apps/translations/field-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/field-panel-echo-decisions.test.ts index 280c7c7ccbe..785c71e9910 100644 --- a/packages/platform-objects/src/apps/translations/field-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/field-panel-echo-decisions.test.ts @@ -50,7 +50,7 @@ // otherwise beside it. // // The remaining four keys have no twin at all — `relatedListFilter` (#19085 -// added it to `field.form.ts` only) and three of the five `summaryOperations` +// added it to `field.metadata-form.ts` only) and three of the five `summaryOperations` // row properties — and are decided from their own helpText and their schema. // // ## The #19430 trap, met and checked AT THE SCHEMA before a word was rendered @@ -220,7 +220,7 @@ const DECISIONS: readonly Decision[] = [ en: 'Related List Filter', verdict: ALL_TRANSLATE, reason: - 'THE ONE LABEL IN THIS FAMILY WITH NO SAME-STRING PRECEDENT: `Related List` returns zero hits across BOTH catalogs, and there is no twin (#19085 added this row to field.form.ts alone). Decided instead by composing this catalog\'s own authored renderings of its two parts — `Related` is 关联 / 関連 / relacionad- (sys_email.fields.related_object.label is 关联对象 / 関連オブジェクト / Objeto relacionado) and `Filter` is 筛选 / フィルター / Filtro (four authored precedents). ⚠️ Recorded as a LITERAL rendering, not an expansion: unlike round 3\'s `include`, the English compound already names its content, so nothing had to be added to make the label answer "filter what?".', + 'THE ONE LABEL IN THIS FAMILY WITH NO SAME-STRING PRECEDENT: `Related List` returns zero hits across BOTH catalogs, and there is no twin (#19085 added this row to field.metadata-form.ts alone). Decided instead by composing this catalog\'s own authored renderings of its two parts — `Related` is 关联 / 関連 / relacionad- (sys_email.fields.related_object.label is 关联对象 / 関連オブジェクト / Objeto relacionado) and `Filter` is 筛选 / フィルター / Filtro (four authored precedents). ⚠️ Recorded as a LITERAL rendering, not an expansion: unlike round 3\'s `include`, the English compound already names its content, so nothing had to be added to make the label answer "filter what?".', }, { scope: 'fields', diff --git a/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts index 9c6c19cfc66..54a8a7cf6bf 100644 --- a/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts @@ -18,7 +18,7 @@ // over a spec-side source that MANUFACTURES the leaves". This round keeps it // there, with the source that actually manufactures these eleven: // -// `objectForm` (`packages/spec/src/data/object.form.ts`), crossed with ONE +// `objectForm` (`packages/spec/src/data/object.metadata-form.ts`), crossed with ONE // predicate read off the form's own shape: a section is IN when it ships // `collapsed: true`. Two of the four qualify — `capabilities` and `advanced` // — and the walk takes every field they declare, recursively through the @@ -83,7 +83,7 @@ // three renderings is either of them. // // ⛔ And the English is NOT fixed here. It would be an edit to -// `packages/spec/src/data/object.form.ts`, outside this round's file surface, +// `packages/spec/src/data/object.metadata-form.ts`, outside this round's file surface, // and it is a SEPARATE act with its own reason that does ⛔ not discharge the // translation. It is reported as a finding, not folded in. // 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 f70ef6712b1..3d95976b4ae 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 @@ -1147,7 +1147,7 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // `bodyExtra` — authored in all three locales. // 623 since #20301: // the list view's own `tabs` is a retired key, and its form repeater left - // `view.form.ts` with it — the repeater's own label and its nine row labels + // `view.metadata-form.ts` with it — the repeater's own label and its nine row labels // (`name`, `label`, `icon`, `view`, `filter`, `order`, `pinned`, // `isDefault`, `visible`), ten leaves authored in all three locales, out of // the catalog. diff --git a/packages/platform-objects/src/apps/translations/repeater-row-properties.test.ts b/packages/platform-objects/src/apps/translations/repeater-row-properties.test.ts index d6d4d18df00..0df0769632a 100644 --- a/packages/platform-objects/src/apps/translations/repeater-row-properties.test.ts +++ b/packages/platform-objects/src/apps/translations/repeater-row-properties.test.ts @@ -29,9 +29,9 @@ // The population is DERIVED from the forms, not listed here, so a repeater // enumerated tomorrow is red on the day it lands rather than a month later. // `view.columns` / `view.sort` / `view.tabs` joined it with #19955: #17507 -// titled their item schemas, and `view.form.ts` now enumerates their children. +// titled their item schemas, and `view.metadata-form.ts` now enumerates their children. // `view.tabs` left it again with #20301: the list view's own `tabs` is a -// retired key, and its repeater left `view.form.ts` with it. +// retired key, and its repeater left `view.metadata-form.ts` with it. import { describe, it, expect } from 'vitest'; @@ -75,7 +75,7 @@ const LOCALES = [ { name: 'ko', forms: koMetadataForms as Record }, ]; -/** Every `*.form.ts` the spec package exports, by its export name. */ +/** Every `*.metadata-form.ts` the spec package exports, by its export name. */ const FORMS: ReadonlyArray = [ ['actionForm', actionForm], ['agentForm', agentForm], diff --git a/packages/platform-objects/src/apps/translations/report-form-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/report-form-echo-decisions.test.ts index bd56cd51695..8959194c328 100644 --- a/packages/platform-objects/src/apps/translations/report-form-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/report-form-echo-decisions.test.ts @@ -37,7 +37,7 @@ // ## The population — DERIVED from `reportForm`, ⛔ not from the catalog's keys // // The source that MANUFACTURES these leaves is `reportForm` -// (`packages/spec/src/ui/report.form.ts`), walked exactly as the CLI extractor +// (`packages/spec/src/ui/report.metadata-form.ts`), walked exactly as the CLI extractor // walks it (`walkMetadataForms` / `walkFormField` in // `packages/cli/src/utils/i18n-extract.ts`): every section's `label` and // `description`, then every field it declares, recursively, with the same diff --git a/packages/platform-objects/src/apps/translations/view-composite-children.test.ts b/packages/platform-objects/src/apps/translations/view-composite-children.test.ts index 9f88f1b71fd..cbad5f6a938 100644 --- a/packages/platform-objects/src/apps/translations/view-composite-children.test.ts +++ b/packages/platform-objects/src/apps/translations/view-composite-children.test.ts @@ -3,7 +3,7 @@ // #30267 — the catalogs name every child the view form declares under its // composites, and zh-CN carries its own text for each of them. // -// `view.form.ts` used to declare `selection`, `pagination`, `userFilters`, +// `view.metadata-form.ts` used to declare `selection`, `pagination`, `userFilters`, // `appearance`, `userActions`, `navigation` and `sharing` as composites with // no children. `os i18n extract` walks a form field's DECLARED `fields` only, // so none of those rows had a `metadataForms.view.fields['.']` diff --git a/packages/platform-objects/src/plugin.ts b/packages/platform-objects/src/plugin.ts index 75d128b792e..f194038da69 100644 --- a/packages/platform-objects/src/plugin.ts +++ b/packages/platform-objects/src/plugin.ts @@ -167,7 +167,7 @@ import { SEED_SETTLEMENT_SERVICE } from '@objectstack/spec/contracts'; * ledger is simply absent — every flag reader answers "not verified", the * safe posture — secret-field writes fail closed (throw, never cleartext), * and without an i18n service the UI falls back to the inline literals - * carried on each App / Dashboard / `*.form.ts` schema. + * carried on each App / Dashboard / `*.metadata-form.ts` schema. * * Structurally typed against `@objectstack/core`'s `Plugin` contract so * this package does not need to depend on the kernel at compile time. diff --git a/packages/spec/api-surface-signatures.json b/packages/spec/api-surface-signatures.json index 1d8462c6d1e..5dacefab969 100644 --- a/packages/spec/api-surface-signatures.json +++ b/packages/spec/api-surface-signatures.json @@ -9,10 +9,10 @@ "defineDatasource": "sha256:5f4aec18b148c77b", "defineEmailTemplateDefinition": "sha256:c1d86a5f074ed7ff", "defineFlow": "sha256:54b60bb867083f61", - "defineForm": "sha256:8d5aab9ae1a79219", "defineHook": "sha256:8de712350ec58845", "defineJob": "sha256:e0e927ebb165d48d", "defineMapping": "sha256:c9458652cca717da", + "defineMetadataForm": "sha256:8d5aab9ae1a79219", "defineObjectExtension": "sha256:3b4099069f01adfb", "definePage": "sha256:770a5cdb49ceba18", "definePermissionSet": "sha256:78d05bdfde46dc0d", diff --git a/packages/spec/api-surface/root.json b/packages/spec/api-surface/root.json index afb534e821f..26a13c500b8 100644 --- a/packages/spec/api-surface/root.json +++ b/packages/spec/api-surface/root.json @@ -157,10 +157,10 @@ "defineDatasource (function)", "defineEmailTemplateDefinition (function)", "defineFlow (function)", - "defineForm (function)", "defineHook (function)", "defineJob (function)", "defineMapping (function)", + "defineMetadataForm (function)", "defineObjectExtension (function)", "definePage (function)", "definePermissionSet (function)", diff --git a/packages/spec/api-surface/ui.json b/packages/spec/api-surface/ui.json index 2c045b605a3..2d49dd2e894 100644 --- a/packages/spec/api-surface/ui.json +++ b/packages/spec/api-surface/ui.json @@ -580,8 +580,8 @@ "defineAction (function)", "defineApp (function)", "defineDataset (function)", - "defineForm (function)", "defineList (function)", + "defineMetadataForm (function)", "definePage (function)", "defineReport (function)", "defineView (function)", diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json index b1d78d10a4f..a620ec57d20 100644 --- a/packages/spec/export-origins/ai.json +++ b/packages/spec/export-origins/ai.json @@ -269,8 +269,8 @@ "VectorStoreProvider": "src/ai/embedding.zod.ts#VectorStoreProvider (type)", "VectorStoreProviderSchema": "src/ai/embedding.zod.ts#VectorStoreProviderSchema (const)", "VectorStoreSchema": "src/ai/embedding.zod.ts#VectorStoreSchema (const)", - "agentForm": "src/ai/agent.form.ts#agentForm (const)", - "aiContextForm": "src/ai/ai-context.form.ts#aiContextForm (const)", + "agentForm": "src/ai/agent.metadata-form.ts#agentForm (const)", + "aiContextForm": "src/ai/ai-context.metadata-form.ts#aiContextForm (const)", "defineAgent": "src/ai/agent.zod.ts#defineAgent (function)", "defineSkill": "src/ai/skill.zod.ts#defineSkill (function)", "defineSolutionBlueprint": "src/ai/solution-blueprint.zod.ts#defineSolutionBlueprint (function)", @@ -279,7 +279,7 @@ "getDatasetToolJsonSchemas": "src/ai/dataset-tools.zod.ts#getDatasetToolJsonSchemas (function)", "getRecordContextToolJsonSchemas": "src/ai/record-context-tools.zod.ts#getRecordContextToolJsonSchemas (function)", "scopesToAgentPermissionSets": "src/ai/mcp.zod.ts#scopesToAgentPermissionSets (function)", - "skillForm": "src/ai/skill.form.ts#skillForm (const)", - "toolForm": "src/ai/tool.form.ts#toolForm (const)" + "skillForm": "src/ai/skill.metadata-form.ts#skillForm (const)", + "toolForm": "src/ai/tool.metadata-form.ts#toolForm (const)" } } diff --git a/packages/spec/export-origins/automation.json b/packages/spec/export-origins/automation.json index f9cc34198ec..77641ef150b 100644 --- a/packages/spec/export-origins/automation.json +++ b/packages/spec/export-origins/automation.json @@ -341,7 +341,7 @@ "findRegionEntry": "src/automation/control-flow.zod.ts#findRegionEntry (function)", "flowDecisionEdgeBranch": "src/automation/flow-altitude.ts#flowDecisionEdgeBranch (function)", "flowFilterOperands": "src/automation/flow-node-expression-paths.ts#flowFilterOperands (function)", - "flowForm": "src/automation/flow.form.ts#flowForm (const)", + "flowForm": "src/automation/flow.metadata-form.ts#flowForm (const)", "flowNodeConfigRefusals": "src/automation/flow-node-config-refusals.ts#flowNodeConfigRefusals (function)", "flowNodeExpressionBlock": "src/automation/flow-node-expression-paths.ts#flowNodeExpressionBlock (function)", "flowNodeTextSlotSources": "src/automation/flow-text-slot-template.ts#flowNodeTextSlotSources (function)", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index a5867cd7a04..2fea0d8ae71 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -1050,7 +1050,7 @@ "extensionArrangementKeys": "src/data/field-customization.ts#extensionArrangementKeys (function)", "externalBindingDatasourceRefusal": "src/data/external-binding-datasource.ts#externalBindingDatasourceRefusal (function)", "externalColumnMapTargets": "src/data/injected-system-column-provenance.ts#externalColumnMapTargets (function)", - "fieldForm": "src/data/field.form.ts#fieldForm (const)", + "fieldForm": "src/data/field.metadata-form.ts#fieldForm (const)", "fieldGroupBodyTableRefusal": "src/data/related-list-body-table.ts#fieldGroupBodyTableRefusal (function)", "fieldGroupsPlaceRelationship": "src/data/related-list-body-table.ts#fieldGroupsPlaceRelationship (function)", "filterOperatorFieldTypeFit": "src/data/filter-operator-field-type-fit.ts#filterOperatorFieldTypeFit (function)", @@ -1075,7 +1075,7 @@ "hasDanglingLikeEscape": "src/data/filter.zod.ts#hasDanglingLikeEscape (function)", "hasDynamicTokens": "src/data/autonumber-format.ts#hasDynamicTokens (function)", "hasNulInLikePattern": "src/data/filter.zod.ts#hasNulInLikePattern (function)", - "hookForm": "src/data/hook.form.ts#hookForm (const)", + "hookForm": "src/data/hook.metadata-form.ts#hookForm (const)", "hookRefusalCodesThrownIn": "src/data/hook-refusal-codes.ts#hookRefusalCodesThrownIn (function)", "hookRefusalReasonsThrownIn": "src/data/hook-refusal-codes.ts#hookRefusalReasonsThrownIn (function)", "hookRefusalsWithoutSandboxedBody": "src/data/hook-refusal-codes.ts#hookRefusalsWithoutSandboxedBody (function)", @@ -1159,7 +1159,7 @@ "numberComparandFieldVerdict": "src/data/filter-number-comparand-declared-type.ts#numberComparandFieldVerdict (function)", "numberComparandRefusalMessage": "src/data/filter-number-comparand-declared-type.ts#numberComparandRefusalMessage (function)", "numericColumnFor": "src/data/numeric-column-representation.ts#numericColumnFor (function)", - "objectForm": "src/data/object.form.ts#objectForm (const)", + "objectForm": "src/data/object.metadata-form.ts#objectForm (const)", "objectTitleCompleteness": "src/data/display-name.ts#objectTitleCompleteness (function)", "parseAutonumberFormat": "src/data/autonumber-format.ts#parseAutonumberFormat (function)", "parseDateMacroParam": "src/data/date-macros.zod.ts#parseDateMacroParam (function)", diff --git a/packages/spec/export-origins/identity.json b/packages/spec/export-origins/identity.json index 71c80f88053..25b59ca2ec5 100644 --- a/packages/spec/export-origins/identity.json +++ b/packages/spec/export-origins/identity.json @@ -119,6 +119,6 @@ "lowerRequiresMembershipReach": "src/identity/membership-reach.ts#lowerRequiresMembershipReach (function)", "mapMembershipRole": "src/identity/eval-user.zod.ts#mapMembershipRole (function)", "membershipReachPredicate": "src/identity/membership-reach.ts#membershipReachPredicate (function)", - "positionForm": "src/identity/position.form.ts#positionForm (const)" + "positionForm": "src/identity/position.metadata-form.ts#positionForm (const)" } } diff --git a/packages/spec/export-origins/root.json b/packages/spec/export-origins/root.json index 45d0a473375..ee1b9fc59f8 100644 --- a/packages/spec/export-origins/root.json +++ b/packages/spec/export-origins/root.json @@ -156,10 +156,10 @@ "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)", + "defineMetadataForm": "src/ui/view.zod.ts#defineMetadataForm (function)", "defineObjectExtension": "src/data/object.zod.ts#defineObjectExtension (function)", "definePage": "src/ui/page.zod.ts#definePage (function)", "definePermissionSet": "src/security/permission.zod.ts#definePermissionSet (function)", diff --git a/packages/spec/export-origins/security.json b/packages/spec/export-origins/security.json index df0ec7ebd50..e4799523612 100644 --- a/packages/spec/export-origins/security.json +++ b/packages/spec/export-origins/security.json @@ -111,7 +111,7 @@ "judgePermissionSetOwnerBinding": "src/security/permission-set-owner-binding.ts#judgePermissionSetOwnerBinding (function)", "normalizeTenancyPosture": "src/security/tenancy-posture.ts#normalizeTenancyPosture (function)", "objectPermissionGrants": "src/security/permission.zod.ts#objectPermissionGrants (function)", - "permissionForm": "src/security/permission.form.ts#permissionForm (const)", + "permissionForm": "src/security/permission.metadata-form.ts#permissionForm (const)", "postureEnforcesWall": "src/security/tenancy-posture.ts#postureEnforcesWall (function)", "postureStampsOrganization": "src/security/tenancy-posture.ts#postureStampsOrganization (function)", "postureUsesUnionScope": "src/security/tenancy-posture.ts#postureUsesUnionScope (function)", diff --git a/packages/spec/export-origins/system.json b/packages/spec/export-origins/system.json index e638da027a2..d787d751fe0 100644 --- a/packages/spec/export-origins/system.json +++ b/packages/spec/export-origins/system.json @@ -831,7 +831,7 @@ "defineTranslationBundle": "src/system/translation.zod.ts#defineTranslationBundle (function)", "deriveImplicitPackageBook": "src/system/book.zod.ts#deriveImplicitPackageBook (function)", "docAudienceAllows": "src/system/book.zod.ts#docAudienceAllows (function)", - "emailTemplateForm": "src/system/email-template.form.ts#emailTemplateForm (const)", + "emailTemplateForm": "src/system/email-template.metadata-form.ts#emailTemplateForm (const)", "flowNoticeMessageKey": "src/system/i18n-resolver.ts#flowNoticeMessageKey (function)", "flowRecordFieldTextKey": "src/system/i18n-resolver.ts#flowRecordFieldTextKey (function)", "flowRefusalMessageKey": "src/system/i18n-resolver.ts#flowRefusalMessageKey (function)", diff --git a/packages/spec/export-origins/ui.json b/packages/spec/export-origins/ui.json index 16278e9e5be..075b60a9285 100644 --- a/packages/spec/export-origins/ui.json +++ b/packages/spec/export-origins/ui.json @@ -525,13 +525,13 @@ "WidgetColorVariant": "src/ui/dashboard.zod.ts#WidgetColorVariant (type)", "WidgetColorVariantSchema": "src/ui/dashboard.zod.ts#WidgetColorVariantSchema (const)", "actionConfirmTemplateRoots": "src/ui/action-copy-template.ts#actionConfirmTemplateRoots (function)", - "actionForm": "src/ui/action.form.ts#actionForm (const)", + "actionForm": "src/ui/action.metadata-form.ts#actionForm (const)", "anonymousFormIntakeCandidates": "src/ui/anonymous-form-intake.ts#anonymousFormIntakeCandidates (function)", "anonymousFormIntakeSlug": "src/ui/anonymous-form-intake.ts#anonymousFormIntakeSlug (function)", "anonymousFormIntakeSlugs": "src/ui/anonymous-form-intake.ts#anonymousFormIntakeSlugs (function)", "anonymousFormIntakeWithdrawnIn": "src/ui/anonymous-form-intake.ts#anonymousFormIntakeWithdrawnIn (function)", "anonymousFormObjectName": "src/ui/anonymous-form-intake.ts#anonymousFormObjectName (function)", - "appForm": "src/ui/app.form.ts#appForm (const)", + "appForm": "src/ui/app.metadata-form.ts#appForm (const)", "bulkConfirmTemplateRoots": "src/ui/bulk-action.zod.ts#bulkConfirmTemplateRoots (function)", "chartAggregateCategoryKey": "src/ui/chart-aggregate.ts#chartAggregateCategoryKey (function)", "chartAggregateResultKeys": "src/ui/chart-aggregate.ts#chartAggregateResultKeys (function)", @@ -557,14 +557,14 @@ "columnSummaryNodeFunctions": "src/ui/view-grouping-query.ts#columnSummaryNodeFunctions (function)", "compileListViewGroupQuery": "src/ui/view-grouping-query.ts#compileListViewGroupQuery (function)", "compileListViewGroupRowsQuery": "src/ui/view-grouping-query.ts#compileListViewGroupRowsQuery (function)", - "dashboardForm": "src/ui/dashboard.form.ts#dashboardForm (const)", - "datasetForm": "src/ui/dataset.form.ts#datasetForm (const)", + "dashboardForm": "src/ui/dashboard.metadata-form.ts#dashboardForm (const)", + "datasetForm": "src/ui/dataset.metadata-form.ts#datasetForm (const)", "defaultRecordPageObject": "src/ui/default-record-page.ts#defaultRecordPageObject (function)", "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)", "defineReport": "src/ui/report.zod.ts#defineReport (function)", "defineView": "src/ui/view.zod.ts#defineView (function)", @@ -593,17 +593,17 @@ "normalizeInlineAction": "src/ui/action.zod.ts#normalizeInlineAction (function)", "objectNavTargetExclusivity": "src/ui/app.zod.ts#objectNavTargetExclusivity (function)", "pageComponentSlotPositions": "src/ui/component.zod.ts#pageComponentSlotPositions (function)", - "pageForm": "src/ui/page.form.ts#pageForm (const)", + "pageForm": "src/ui/page.metadata-form.ts#pageForm (const)", "partitionAssembledViewArtifacts": "src/ui/assembled-views.zod.ts#partitionAssembledViewArtifacts (function)", "publicFormSlug": "src/ui/anonymous-form-intake.ts#publicFormSlug (function)", "reactBlockTagFor": "src/ui/react-blocks.ts#reactBlockTagFor (function)", - "reportForm": "src/ui/report.form.ts#reportForm (const)", + "reportForm": "src/ui/report.metadata-form.ts#reportForm (const)", "reportSelectionOrder": "src/ui/report.zod.ts#reportSelectionOrder (function)", "resolveI18nLabel": "src/ui/i18n-label-resolver.ts#resolveI18nLabel (function)", "selectViewMetadataBranch": "src/ui/view.zod.ts#selectViewMetadataBranch (function)", "stripViewConsoleDecorations": "src/ui/view.zod.ts#stripViewConsoleDecorations (function)", "thankYouRecordFieldNames": "src/ui/view.zod.ts#thankYouRecordFieldNames (function)", "validateActionParams": "src/ui/action-params.zod.ts#validateActionParams (function)", - "viewForm": "src/ui/view.form.ts#viewForm (const)" + "viewForm": "src/ui/view.metadata-form.ts#viewForm (const)" } } diff --git a/packages/spec/liveness/README.md b/packages/spec/liveness/README.md index bbb338affa9..397e78e2cfa 100644 --- a/packages/spec/liveness/README.md +++ b/packages/spec/liveness/README.md @@ -369,7 +369,7 @@ a `live-elsewhere` entry does cite is held to the full scanned-status standard > all thirteen are behavioural keys. `live` means **authoring the property changes runtime behaviour**. A Studio -`*.form.ts` input or a `metadata-admin/previews/*Preview.tsx` panel merely +`*.metadata-form.ts` input or a `metadata-admin/previews/*Preview.tsx` panel merely *echoes back what the author typed* — it proves the property round-trips, never that anything acts on it. A 2026-06 sweep that "missed objectui" over-corrected and marked **13 properties `live` citing only a preview renderer**; of those, @@ -995,7 +995,7 @@ marker where the Notes cell goes, never a guess at what belongs there. | skill | `permissions` REMOVED 2026-07 (#3704); `triggerPhrases` REMOVED 2026-07-30 (#3896 close-out sweep — phrases were never matched; activation is `triggerConditions` + the agent's `skills[]` + /skill-name pinning) | | dataset | `measures.certified` (declared-but-unenforced governance flag) REMOVED in 16.0 (#2377) | | page | live, plus the one dead tombstone below. The `print` declaration (#22158, 2026-10-08: the container, its eight keys and the four `margins` sides) was declared spec-first by card ① of the #8346 ruling (B′) — its REFUSALS live (the parse's `checkPagePrintComposition`, lint's `validatePrintPageBlocks`), its keys `planned` with `authorWarn` on the container — and flipped `live` 2026-10-16 (#23710) once card ②, the console's print rendering, reached the `.objectui-sha` pin: `PageRenderer` mounts objectui's `buildPagePrintStylesheet`, which reads every key. `authorWarn` went with the flip, so an author who writes `print` is no longer told the layout is not applied. Its earlier `planned` row, `requires`, flipped `live` 2026-10-02 (#20871): the save door refuses an html page whose written list disagrees with its source and stores the derived one, and boot hydration reports a stored page whose list names a plugin the deployment's SDUI manifest does not carry. Dead `assignedProfiles` REMOVED 2026-09-12 (ADR-0090 D2 + ADR-0049 — a per-page audience list named for the concept D2 deleted, with zero readers in either repo, so the page was open to everyone who could reach it). The row stays because `retiredKey` keeps the key in the walked shape (the `rls.priority` precedent). Its prior `live` verdict is the #12516 class twice over: the objectui bridge it cited never existed (lit control — two sibling objectui citations in the same file resolve), and the entry carried no `verifiedAt`, so nothing ever re-asked | -| view | list/form drilled via `children` (#2998 Track B); list.{responsive,performance} + form.{defaultSort,aria} REMOVED 2026-07-30 (#3896 close-out sweep — list aria/data stay live); **form.data was that sweep's one CORRECTION** — the removal attempt broke the build (`defineForm` writes `data.provider='schema'` onto every metadata form, `metadata-protocol` serves it), so it stands `live` with re-verified evidence; form.{buttons,defaults} live (framework#1894 / #2998); audit-era DEAD lines superseded by re-verification. **The dead set is six, not the four removals above**: #4534 (the last #4001 batch, batch 6e) declared three CONTAINER-level keys this row had never classified — `name` and `label`, both `dead`, and `object`, `live`. All three are properties of the `views: [...]` *container*, not of a view: `name` is dead because authoring it changes nothing — an authored value restates the key the container already registers under or contradicts it — and `label` is container display metadata with no reader. Neither is `authorWarn`'d and both are deliberately KEPT — the metadata door itself stamps the save name into every saved view body (`normalizeViewMetadata`) and its overlay paths key on that copy, so tombstoning `name` would reject the platform's own saves (re-measured 2026-10-02, #20301 stage 2: the earlier attribution to artifact-shipped containers and the metadata-validation sweep was the door's stamp misread; neither carries one). `object` is the container's object binding, and it was *stripped on every parse* until #4534 declared it. Separately, the level-2 dead residue (userActions.buttons, tabs[].order; addRecord.mode/formView until their #24692 removal) is noted on parents and is **not** in the counts — one drill level only **#9340**: `list.map` declared — the eighth visualization block (`ListMapConfigSchema`), keys mirroring objectui plugin-map's documented read set. FLIPPED `planned` → `live` 2026-08-24 (#11442): objectui#5908 landed `resolveListMapConfig`, which merges the view-level `map` block over the legacy `options.map` bag before `ListView.tsx`'s `case 'map'` forwards it into `ObjectMap`, with the same merged config also feeding the visualization-switcher's capability gate so a view binding coordinates only in the spec block is no longer filtered out of `allowedVisualizations` either (objectui#5042) **#22611** (2026-10-10): `list.requiredPermissions` is this type's only `planned` row (the `list.map` precedent above flipped `live`) — the audience gate (a list of capabilities, all required), declared spec-first under the ruling of record 6095014058, letter A, with `authorWarn` and an `authorHint` because no server reads it until the `/meta` read gate applies it (#22639, the carrier). The warning reaches a container's `list` only: the lint flattens one level of `children`, so a named `listViews` entry is not walked, and the key's describe carries the not-enforced clause for that door | +| view | list/form drilled via `children` (#2998 Track B); list.{responsive,performance} + form.{defaultSort,aria} REMOVED 2026-07-30 (#3896 close-out sweep — list aria/data stay live); **form.data was that sweep's one CORRECTION** — the removal attempt broke the build (`defineMetadataForm` writes `data.provider='schema'` onto every metadata form, `metadata-protocol` serves it), so it stands `live` with re-verified evidence; form.{buttons,defaults} live (framework#1894 / #2998); audit-era DEAD lines superseded by re-verification. **The dead set is six, not the four removals above**: #4534 (the last #4001 batch, batch 6e) declared three CONTAINER-level keys this row had never classified — `name` and `label`, both `dead`, and `object`, `live`. All three are properties of the `views: [...]` *container*, not of a view: `name` is dead because authoring it changes nothing — an authored value restates the key the container already registers under or contradicts it — and `label` is container display metadata with no reader. Neither is `authorWarn`'d and both are deliberately KEPT — the metadata door itself stamps the save name into every saved view body (`normalizeViewMetadata`) and its overlay paths key on that copy, so tombstoning `name` would reject the platform's own saves (re-measured 2026-10-02, #20301 stage 2: the earlier attribution to artifact-shipped containers and the metadata-validation sweep was the door's stamp misread; neither carries one). `object` is the container's object binding, and it was *stripped on every parse* until #4534 declared it. Separately, the level-2 dead residue (userActions.buttons, tabs[].order; addRecord.mode/formView until their #24692 removal) is noted on parents and is **not** in the counts — one drill level only **#9340**: `list.map` declared — the eighth visualization block (`ListMapConfigSchema`), keys mirroring objectui plugin-map's documented read set. FLIPPED `planned` → `live` 2026-08-24 (#11442): objectui#5908 landed `resolveListMapConfig`, which merges the view-level `map` block over the legacy `options.map` bag before `ListView.tsx`'s `case 'map'` forwards it into `ObjectMap`, with the same merged config also feeding the visualization-switcher's capability gate so a view binding coordinates only in the spec block is no longer filtered out of `allowedVisualizations` either (objectui#5042) **#22611** (2026-10-10): `list.requiredPermissions` is this type's only `planned` row (the `list.map` precedent above flipped `live`) — the audience gate (a list of capabilities, all required), declared spec-first under the ruling of record 6095014058, letter A, with `authorWarn` and an `authorHint` because no server reads it until the `/meta` read gate applies it (#22639, the carrier). The warning reaches a container's `list` only: the lint flattens one level of `children`, so a named `listViews` entry is not walked, and the key's describe carries the not-enforced clause for that door | | report | dataset-bound (ADR-0021); the aria/performance LEDGER entries were stale — the keys left the schema in the report-liveness close-out; deleted 2026-07-30 as hygiene. Audit-era `chart` DEAD superseded (framework#1890 / #3441) — live on non-joined reports only: a `joined` report's container `chart` is refused and `blocks[].chart` was removed (#20161, 2026-09-27; nothing drew either) | | dashboard | ADR-0021 dataset widgets (#3251; DashboardWidgetSchema `.strict()`); `aria`/`performance` (and widget `performance` + PerformanceConfigSchema) REMOVED 2026-07-30 (#3896 close-out sweep — no renderer applied any of them); audit-era `globalFilters`/`dateRange` DEAD superseded (framework#2501) **#4956**: `widgets` DRILLED — the row jumps 20 → 41 classified because all 22 widget-level keys enter the count at once. They had never been classified at all: the entry carried one blanket `live` plus a `note` asserting they were classified "in the DashboardWidgetSchema subtree", and no such subtree existed in any of the 28 ledger files. That gap, not any evidence, is what carried `widgets[].responsive` through the #3896 sweep that removed both its sibling `widgets[].performance` and its literal namesake `view.responsive` — `view` is drilled, so `list.responsive` got asked and went out. New dead 6 = `responsive` (retired #4876/#4995, tombstone keeps the row) + `colorVariant` + `actionUrl`/`actionType`/`actionIcon` + `aria`. The action trio is the sharpest: no renderer draws a per-widget action button at all (every `actionUrl` read in DashboardRenderer is scoped to `header.actions[]`), yet `validate-dashboard-action-refs.ts` enforces reference integrity on it and its docblock calls it "the per-widget button" — a lint guarding an affordance that does not exist. `requiresService` is the counter-example worth remembering: dead by every objectui measurement, and LIVE server-side (`filterDashboardForUser`, ADR-0057 D10) — judging a widget key from the renderer repo alone would have retired an enforced gate. `compareTo` is `live` on ONE path only (inline object-provider charts); on the ADR-0021 dataset path the string arms are dropped and `{ offset }` throws in the executor. **#6774** moves the row 33/8 → 34/7: `colorVariant` CORRECTED dead → live 2026-08-09, the enforce leg of #5010 ruling B landing from the renderer side (objectui#3359 / PR objectui#3799, absorbed by pin `09987b68`). Worth reading beside `requiresService` above, because it is the same lesson from the other end — that row warns against judging a widget key from the renderer repo alone, and this one is a `dead` verdict that was correct in this repo AND correct in the renderer repo on the day it was measured, and stopped being either when a cross-repo decision was implemented. A ledger row is a claim with a timestamp; `verifiedAt` is what makes the claim re-askable. It also empties the dashboard warn set, so the author-side lint now says nothing about any widget key — `dashboard` stays in the lint's TYPE_COLLECTIONS all the same (the `webhook`/`email_template` resolved state). **#17385** DRILLS `widgets.chartConfig` — 14 per-key verdicts where the row had carried one blanket `live`, re-measured against `.objectui-sha` pin `53ded82bf7a4`: 12 live (the nine chrome keys `chartConfigPresentation` lowers, plus `xAxis`/`yAxis`/`series`, whose PRESENTATION merges onto the derived bindings while `ChartAxis.field` and `ChartSeries.name` are dropped so membership stays with the dataset) and dead 2 — `type`, which parses and does nothing because the widget's own `type` owns the chart family, and `aria`, which has no reader on either face. Both are pinned as NEGATIVES in objectui, which is what makes them re-askable rather than merely asserted. ⚠️ The drill made SIX containers one level further down visible for the first time (`xAxis`/`yAxis`/`series`/`annotations`/`interaction`/`aria`, 39 child keys); they are RECORDED, not drilled — fanning this row's verdicts down over them would manufacture verdicts, and the evidence work is a separate measurement. Note the cell's previous last stated position (`34/7`) had already drifted one `dead` behind the generated artifact before this change; the counts columns are generated and are the authority **#22611** (2026-10-10): `requiredPermissions` is this type's only `planned` row — the audience gate (a list of capabilities, all required) shared word for word with the list view's, declared spec-first under the ruling of record 6095014058, letter A, with `authorWarn` and an `authorHint` because no server reads it until the `/meta` read gate applies it (#22639, the carrier) | | query | **not a metadata type** — the REQUEST surface (`QuerySchema`: client SDK QueryBuilder output; the `POST /data/:object/query` body), governed via `SPEC_ONLY_SCHEMAS` (#4286). The gate resolves 1 experimental at the depth this ledger drills; the 7 marker-experimental search affordances sit one level deeper, below what this ledger declares (the walk recurses since #17424, but only where a `children` map is written, and none is written here) — resolved from `[EXPERIMENTAL — not enforced]` describe markers, not ledger entries (search `fuzzy`/`operator`/`boost`/`minScore`/`language`/`highlight` + `aggregations[].filter` — declared engine affordances no executor receives). The #4286 sweep closed out same-release: `having` ENFORCED 2026-07-31 (engine-side post-aggregation filter, both paths; was finding 1); dead 4 = the tombstoned removals `joins`/`windowFunctions`/`cursor`/`distinct` — REMOVED 2026-07-31 (retiredKey keeps each in the walked shape so the rows stay; protocol-17 semantic migrations; the JoinNode + WindowFunctionNode clusters and the `QueryBuilder.cursor()`/`.distinct()` producers deleted with their keys; `distinct`'s mis-wired REST count suppression deleted too — finding 2). **#6815** adds the 5th dead: `aggregations[].distinct` REMOVED 2026-08-09 (live → dead, `-1` live). It is the one member of this ledger the #4286 sweep could not have caught with the question it asked — that sweep looked for keys NO executor reads, and this one had a reader: the objectql in-memory fallback deduplicated before applying the function while all five other faces (driver-sql, driver-turso, driver-mongodb, driver-memory, service-analytics' `AGGREGATE_SQL`) ignored it, so one query answered two plausible NUMBERS depending on which backend served it. The lesson for the next audit is the question, not the key: a per-key `live` verdict is only as good as the count of faces it was measured across, and this row's 2026-07-31 evidence (`in-memory-aggregation.ts:167,204-206`) was TRUE and still the wrong verdict. `count_distinct` is the surviving spelling (enforce leg, #6409) | diff --git a/packages/spec/liveness/action.json b/packages/spec/liveness/action.json index e8cc93ab71e..e022b76ad70 100644 --- a/packages/spec/liveness/action.json +++ b/packages/spec/liveness/action.json @@ -21,14 +21,14 @@ "verifiedAt": "2026-10-31", "evidenceScope": "in-repo", "evidence": "ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx#paramCollectionHandler and ui/packages/app-shell/src/views/RecordDetailView.tsx#paramCollectionHandler (the two param-collection handlers: the bundle's `objects.{o}._actions.{a}.submitText`, or `globalActions.{a}.submitText` for an object-less action, through `actionSubmitText`, then the authored `I18nLabel` collapsed to the active language); ui/packages/app-shell/src/views/ActionParamDialog.tsx (draws it on the submit button, `actionDialog.confirm` when absent, `actionDialog.uploading` while a file uploads); ui/packages/components/src/renderers/action/action-button.tsx, ui/packages/components/src/renderers/action/action-icon.tsx, ui/packages/components/src/renderers/action/action-group.tsx, ui/packages/components/src/renderers/action/action-menu.tsx (the four action renderers forward it to the runner); ui/packages/core/src/actions/ActionRunner.ts#ActionDef (the key derived from the spec); packages/spec/src/system/i18n-resolver.ts#translateAction (the served overlay); packages/lint/src/validate-translation-references.ts#checkActionSubmitText (a translation under an action with no `params` is refused)", - "note": "LIVE since #28158 (the console half of #27944). An action that collects `params` names its own submit verb (\"Send\", \"Log Call\"): the param dialog's submit button draws the translated or authored `submitText` and falls back to \"Confirm\" when the action declares none. While a file param uploads, the button says \"Uploading…\" either way. The Studio action form offers the key (`action.form.ts`). `authorWarn` / `authorHint` were dropped in the same edit (a warned `live` row reds this gate)." + "note": "LIVE since #28158 (the console half of #27944). An action that collects `params` names its own submit verb (\"Send\", \"Log Call\"): the param dialog's submit button draws the translated or authored `submitText` and falls back to \"Confirm\" when the action declares none. While a file param uploads, the button says \"Uploading…\" either way. The Studio action form offers the key (`action.metadata-form.ts`). `authorWarn` / `authorHint` were dropped in the same edit (a warned `live` row reds this gate)." }, "cancelText": { "status": "live", "verifiedAt": "2026-11-02", "evidenceScope": "in-repo", "evidence": "ui/packages/react/src/hooks/useActionTextLocalizer.ts (the confirm path: the bundle's `objects.{o}._actions.{a}.cancelText`, or `globalActions.{a}.cancelText` for an object-less action, through `actionCancelText`, then the authored `I18nLabel` collapsed to the active language, only when the action declares one); ui/packages/core/src/actions/ActionRunner.ts#confirmOptions (hands the resolved string to the confirm handler as `options.cancelText`) and ui/packages/core/src/actions/ActionRunner.ts#ActionDef (the key derived from the spec); ui/packages/app-shell/src/views/ActionConfirmDialog.tsx (draws `options.cancelText` over `actionConfirm.cancel`); ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx#paramCollectionHandler and ui/packages/app-shell/src/views/RecordDetailView.tsx#paramCollectionHandler (the param path, resolved the same way); ui/packages/app-shell/src/views/ActionParamDialog.tsx (draws it on the dismiss button, `actionDialog.cancel` when absent); ui/packages/components/src/renderers/action/action-button.tsx, ui/packages/components/src/renderers/action/action-icon.tsx, ui/packages/components/src/renderers/action/action-group.tsx, ui/packages/components/src/renderers/action/action-menu.tsx (the four action renderers forward it to the runner); packages/spec/src/system/i18n-resolver.ts#translateAction (the served overlay); packages/lint/src/validate-translation-references.ts#checkActionCancelText (a translation under an action that opens neither dialog is refused)", - "note": "LIVE since #28879 (the console half of #28519). An action that asks first or collects `params` names its dialog's dismiss button (\"Keep invitation\" beside \"Cancel Invitation\"): the confirm dialog and the param dialog draw the translated or authored `cancelText` and fall back to \"Cancel\" when the action declares none. `sys_invitation`'s `cancel_invitation` is the first consumer. The Studio action form offers the key (`action.form.ts`). `authorWarn` / `authorHint` were dropped in the same edit (a warned `live` row reds this gate)." + "note": "LIVE since #28879 (the console half of #28519). An action that asks first or collects `params` names its dialog's dismiss button (\"Keep invitation\" beside \"Cancel Invitation\"): the confirm dialog and the param dialog draw the translated or authored `cancelText` and fall back to \"Cancel\" when the action declares none. `sys_invitation`'s `cancel_invitation` is the first consumer. The Studio action form offers the key (`action.metadata-form.ts`). `authorWarn` / `authorHint` were dropped in the same edit (a warned `live` row reds this gate)." }, "objectName": { "status": "live", diff --git a/packages/spec/liveness/field.json b/packages/spec/liveness/field.json index 97663e07f5c..a664813d348 100644 --- a/packages/spec/liveness/field.json +++ b/packages/spec/liveness/field.json @@ -444,7 +444,7 @@ "status": "dead", "verifiedAt": "2026-10-27", "evidenceScope": "in-repo", - "evidence": "no reader: at 1c632311, outside packages/spec, nothing under packages/** or ui/** reads a field's `externalId`. The protocol still parses it (`FieldSchema` keeps the key; not a retirement), and no Studio surface offers it (#26674): the field metadata form has no row for it (packages/spec/src/data/field.form.ts, a recorded root omission), and neither the designer's field drawer (ui/packages/plugin-designer/src/FieldDesigner.tsx) nor the field inspector (ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx#ObjectFieldInspector) has a control for it. The `ui/` mentions only carry a stored value through a save: those two surfaces, ui/packages/plugin-designer/src/MetadataFieldsPage.tsx, and ui/packages/app-shell/src/services/MetadataService.ts, which copies it into a field summary. None is a preview: no `registerMetadataPreview('field', …)` exists, and no registered preview (ui/packages/app-shell/src/views/metadata-admin/previews/, `object` included) reads `externalId`. Every upsert matches on something else: a seed dataset's `externalId` (packages/metadata-protocol/src/seed-loader.ts, `name` by default) or an import mapping's `upsertKey` (packages/rest/src/import-prepare.ts)", + "evidence": "no reader: at 1c632311, outside packages/spec, nothing under packages/** or ui/** reads a field's `externalId`. The protocol still parses it (`FieldSchema` keeps the key; not a retirement), and no Studio surface offers it (#26674): the field metadata form has no row for it (packages/spec/src/data/field.metadata-form.ts, a recorded root omission), and neither the designer's field drawer (ui/packages/plugin-designer/src/FieldDesigner.tsx) nor the field inspector (ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx#ObjectFieldInspector) has a control for it. The `ui/` mentions only carry a stored value through a save: those two surfaces, ui/packages/plugin-designer/src/MetadataFieldsPage.tsx, and ui/packages/app-shell/src/services/MetadataService.ts, which copies it into a field summary. None is a preview: no `registerMetadataPreview('field', …)` exists, and no registered preview (ui/packages/app-shell/src/views/metadata-admin/previews/, `object` included) reads `externalId`. Every upsert matches on something else: a seed dataset's `externalId` (packages/metadata-protocol/src/seed-loader.ts, `name` by default) or an import mapping's `upsertKey` (packages/rest/src/import-prepare.ts)", "note": "RE-GRADED live -> dead 2026-10-27 (#25753, follow-up F23 of #25712). The `live` grade rested on objectui console `metadataConverters.ts` (:125, commit not pinned), which objectui dc14bcb deleted for having zero importers; the re-measure above found no other reader. A boolean `default(false)`, so the author lint warns only on an authored `true`. Owed enforce-or-remove (ADR-0049).", "authorHint": "Remove it: no upsert reads a field's `externalId`. To match seed records on this field, name it in the seed dataset's `externalId`; for an import, in the mapping's `upsertKey`." }, @@ -595,7 +595,7 @@ "verifiedAt": "2026-09-20", "evidenceScope": "in-repo", "evidence": "ui/packages/app-shell/src/utils/deriveRelatedLists.ts#deriveRelatedLists:319 puts the authored value on the derived descriptor as `filter`, gated by the same file's #isDeclaredFilter predicate — the declared-vs-absent discrimination its relatedListTitle / relatedListColumns siblings do, with no alias accepted and no shape coerced; ui/packages/app-shell/src/views/RecordDetailView.tsx#synthParts:3160 destructures that descriptor key as `declaredFilter` (:3121) and writes it onto the synthesized `record:related_list` node, the same `filter` slot the component-level input already lowers, so RelatedList AND-composes it with { [referenceField]: parentId } and the tab strip's count probe composes the same pair — measured objectui @53ded82bf7, which is this repo's `.objectui-sha` pin, so both pointers were read AT THE PIN this repo builds against rather than on objectui main", - "note": "[#8704] Contract-first spec half (maintainer ruling 2026-08-15, 「接受全部建议。」 item 3): the declarative default filter the auto-derived related list AND-composes with { [referenceField]: parentId }, badge-count parity included — both clauses normative in the key's describe()/JSDoc and pinned in field.test.ts. Reuses FilterConditionSchema, so the #8793 bare-preset schema door judges it at parse (pinned at this position) and the engine FILTER doors (#8296 formula refusal etc.) judge the composed query at run time. Seeded `planned` + authorWarn per enforce-or-mark, the app.navigation runAction (#4848) shape rather than the useGrouping one, and that seeding wrote its own flip condition: 「Flip to `live` (and drop authorWarn) with a deriveRelatedLists/RecordDetailView evidence pointer when objectui#4664 lands.」 **FLIPPED `planned` → `live` 2026-09-20 (#19187), and the condition was re-measured rather than relayed**: objectui#4664 landed as objectui d796c8dde (objectui PR #6946, 2026-08-31) and `git merge-base --is-ancestor d796c8dde 53ded82bf7` exits 0, so the consumer is inside the console this repo pins — the #10068 discipline (read both pointers at the pin, never at objectui main) one row over. What the flip drops is not bookkeeping: the authorHint it carried told an author 「the auto-derived related list does not apply this filter yet」 about a key the pinned console applies, and `packages/lint`'s ledger-driven advisory repeated that sentence at every compile, steering authors off a working key. The sentence is recorded rather than deleted because it was TRUE from #8704 until the pin absorbed d796c8dde — a `planned` row falsifies by its consumer landing, which is the one direction no citation check can see (the pointer never rots; there was no pointer). The form hint's face today (packages/spec/src/data/field.form.ts; moved out of spec source, #23434): objectui @b9814b334 packages/app-shell/src/views/metadata-admin/SchemaForm.tsx#resolveFieldFace lands the `filter-condition` hint on `{ kind: 'raw-json', hint }`, past both structural fallbacks, because objectui @b9814b334 packages/app-shell/src/views/metadata-admin/widgets.tsx#WIDGETS registers no `filter-condition`; re-read 2026-10-15, first cited sha-less." + "note": "[#8704] Contract-first spec half (maintainer ruling 2026-08-15, 「接受全部建议。」 item 3): the declarative default filter the auto-derived related list AND-composes with { [referenceField]: parentId }, badge-count parity included — both clauses normative in the key's describe()/JSDoc and pinned in field.test.ts. Reuses FilterConditionSchema, so the #8793 bare-preset schema door judges it at parse (pinned at this position) and the engine FILTER doors (#8296 formula refusal etc.) judge the composed query at run time. Seeded `planned` + authorWarn per enforce-or-mark, the app.navigation runAction (#4848) shape rather than the useGrouping one, and that seeding wrote its own flip condition: 「Flip to `live` (and drop authorWarn) with a deriveRelatedLists/RecordDetailView evidence pointer when objectui#4664 lands.」 **FLIPPED `planned` → `live` 2026-09-20 (#19187), and the condition was re-measured rather than relayed**: objectui#4664 landed as objectui d796c8dde (objectui PR #6946, 2026-08-31) and `git merge-base --is-ancestor d796c8dde 53ded82bf7` exits 0, so the consumer is inside the console this repo pins — the #10068 discipline (read both pointers at the pin, never at objectui main) one row over. What the flip drops is not bookkeeping: the authorHint it carried told an author 「the auto-derived related list does not apply this filter yet」 about a key the pinned console applies, and `packages/lint`'s ledger-driven advisory repeated that sentence at every compile, steering authors off a working key. The sentence is recorded rather than deleted because it was TRUE from #8704 until the pin absorbed d796c8dde — a `planned` row falsifies by its consumer landing, which is the one direction no citation check can see (the pointer never rots; there was no pointer). The form hint's face today (packages/spec/src/data/field.metadata-form.ts; moved out of spec source, #23434): objectui @b9814b334 packages/app-shell/src/views/metadata-admin/SchemaForm.tsx#resolveFieldFace lands the `filter-condition` hint on `{ kind: 'raw-json', hint }`, past both structural fallbacks, because objectui @b9814b334 packages/app-shell/src/views/metadata-admin/widgets.tsx#WIDGETS registers no `filter-condition`; re-read 2026-10-15, first cited sha-less." }, "trackHistory": { "status": "live", diff --git a/packages/spec/liveness/view.json b/packages/spec/liveness/view.json index 9f3e11ab537..2e899ec7ce3 100644 --- a/packages/spec/liveness/view.json +++ b/packages/spec/liveness/view.json @@ -281,8 +281,8 @@ "data": { "status": "live", "verifiedAt": "2026-07-30", - "evidence": "packages/spec/src/ui/view.zod.ts defineForm (writes data.provider=schema + schemaId onto every metadata form); packages/metadata-protocol/src/protocol.ts:1580,1598 (serves schemaId with the form to the metadata-admin pipeline)", - "note": "CORRECTED 2026-07-30: the #3896 sweep attempted removal on the prior dead verdict and the build itself refuted it — defineForm authors the key on every *.form.ts. The record-form provider VALUES (object/value) may still lack readers; that is a value-subset audit, not a key removal. 2026-10-13: the `api` value is RETIRED on the union itself (see `list.data`'s retirement record) — a form's `data` no longer admits a request block; a submit-to-endpoint is not a view concern." + "evidence": "packages/spec/src/ui/view.zod.ts defineMetadataForm (writes data.provider=schema + schemaId onto every metadata form); packages/metadata-protocol/src/protocol.ts:1580,1598 (serves schemaId with the form to the metadata-admin pipeline)", + "note": "CORRECTED 2026-07-30: the #3896 sweep attempted removal on the prior dead verdict and the build itself refuted it — defineMetadataForm authors the key on every *.metadata-form.ts. The record-form provider VALUES (object/value) may still lack readers; that is a value-subset audit, not a key removal. 2026-10-13: the `api` value is RETIRED on the union itself (see `list.data`'s retirement record) — a form's `data` no longer admits a request block; a submit-to-endpoint is not a view concern." }, "type": { "status": "live", @@ -371,7 +371,7 @@ "verifiedAt": "2026-08-09", "evidenceScope": "in-repo", "evidence": "packages/spec/src/ui/view.zod.ts (foldFormGroupsIntoSections + the .overwrite on FormViewSchema — the PRODUCER fold, #6926: groups-only folds onto sections, sections wins when both are present, and groups is absent from every parsed form); ui/packages/plugin-form/src/ObjectForm.tsx (:129-142 at objectui @7b3e048) (objectui @7b3e048 — the pre-existing boundary folds, now redundant for parsed forms and retiring in a later cross-repo lap)", - "note": "WHERE THE FOLD LIVES: at the producer, as of #6926 — a `.overwrite()` on FormViewSchema, inherited by every parse door (ViewSchema.form/.formViews.*, both ViewItemSchema form arms, and ViewMetadataSchema's container AND flattened form-overlay members, which picks it up through .extend()). Before #6926 the alias was declared but folded NOWHERE in this repo: it was honored one boundary downstream in objectui (alias-at-one-boundary, objectui#2545, after a groups-only spec rendered nothing), while the framework's REST public-form routes read `sections` only — so the same authored form rendered in the console and degraded on GET /forms/:slug, POST /forms/:slug/submit and GET /forms/:slug/lookup/:field. That omission is what let #6926 be filed reading a live key as dead; it is recorded here so the next reader cannot repeat it. STILL NOT FOLDED (measured 2026-08-09, #6926): a RUNTIME-saved sys_metadata row — saveMetaItem validates through ViewMetadataSchema and then deliberately discards parsed.data to keep Studio round-trip keys, and the read replays the ADR-0087 stored-row conversion chain, which is not a zod parse. Code-authored views (defineView/defineForm → registry) DO reach REST folded. Pre-parse consumers still read the authored key and are right to: packages/lint's view rules walk authored sources. Audit L24 drift resolved by alias-at-one-boundary; superseded by the producer fold. 2026-10-26 (#25712, objectui merged into this repo as ui/): the spec-bridge clause (`form-view.ts:169`) was dropped, not repointed: objectui#6632 retired the spec-bridge. ObjectForm's line range is kept as the @7b3e048 reading; it does not match today's file." + "note": "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", diff --git a/packages/spec/scripts/pure-schema-construction.test.ts b/packages/spec/scripts/pure-schema-construction.test.ts index b28641605ef..b2121adf712 100644 --- a/packages/spec/scripts/pure-schema-construction.test.ts +++ b/packages/spec/scripts/pure-schema-construction.test.ts @@ -81,13 +81,13 @@ const FIXTURE = [ 'const strictObject = (shape: object): object => ({ ...shape });', 'const z = { strictObject };', "export const single = 'measured: `z.strictObject(DashboardWidgetSchema.shape)` accepts it';", - 'export const double = "lazySchema(fn) and defineForm(cfg)";', + 'export const double = "lazySchema(fn) and defineMetadataForm(cfg)";', 'export const template = `a strictObject({}) mention in template text`;', 'export const substituted = `${lazySchema(() => \'x\')} then lazySchema( in text`;', 'export const regex = /strictObject(\\w+)/.source;', '/** JSDoc naming strictObject(shape) and lazySchema(fn) */', 'export const trailing = 1; /* strictObject(x) */ // lazySchema(y)', - 'export function defineForm(cfg: object): object { return cfg; }', + 'export function defineMetadataForm(cfg: object): object { return cfg; }', 'export const called = strictObject({ a: 1 });', 'export const member = z.strictObject({ b: 1 });', '', @@ -103,7 +103,7 @@ describe('a fixture quoting every marked name survives the build byte-identical' const built = (await import(pathToFileURL(file).href)) as Record; expect(built.single).toBe('measured: `z.strictObject(DashboardWidgetSchema.shape)` accepts it'); - expect(built.double).toBe('lazySchema(fn) and defineForm(cfg)'); + expect(built.double).toBe('lazySchema(fn) and defineMetadataForm(cfg)'); expect(built.template).toBe('a strictObject({}) mention in template text'); expect(built.substituted).toBe('x then lazySchema( in text'); expect(built.regex).toBe('strictObject(\\w+)'); @@ -155,12 +155,12 @@ describe('annotatePureCalls — where the annotation goes', () => { it('touches nothing that is not a call', () => { const text = [ "const a = 'strictObject(';", - 'const b = `lazySchema(${x}) defineForm(`;', + 'const b = `lazySchema(${x}) defineMetadataForm(`;', '/** @example lazySchema(() => z.object({})) */', '// strictObject(shape)', - 'const c = 1; /* defineForm(cfg) */', + 'const c = 1; /* defineMetadataForm(cfg) */', 'const d = /lazySchema(x)/;', - 'export function defineForm(cfg: object) { return cfg; }', + 'export function defineMetadataForm(cfg: object) { return cfg; }', '', ].join('\n'); expect(annotatePureCalls(text, 'a.ts')).toBe(text); @@ -170,7 +170,7 @@ describe('annotatePureCalls — where the annotation goes', () => { const text = [ 'const A = lazySchema(() => z.object({}));', 'const B = strictObject({ a: z.string() });', - 'const C = defineForm({ schemaId: "x" });', + 'const C = defineMetadataForm({ schemaId: "x" });', 'const D = z.strictObject({});', 'const E = `${lazySchema(() => 1)} lazySchema(`;', 'const F = lazySchema(() => shape);', @@ -181,7 +181,7 @@ describe('annotatePureCalls — where the annotation goes', () => { [ `const A = ${PURE}lazySchema(() => z.object({}));`, `const B = ${PURE}strictObject({ a: z.string() });`, - `const C = ${PURE}defineForm({ schemaId: "x" });`, + `const C = ${PURE}defineMetadataForm({ schemaId: "x" });`, `const D = ${PURE}z.strictObject({});`, `const E = \`\${${PURE}lazySchema(() => 1)} lazySchema(\`;`, `const F = ${PURE}lazySchema(() => shape);`, diff --git a/packages/spec/src/ai/agent.form.ts b/packages/spec/src/ai/agent.metadata-form.ts similarity index 97% rename from packages/spec/src/ai/agent.form.ts rename to packages/spec/src/ai/agent.metadata-form.ts index dc10c33bdb7..0c5c5686024 100644 --- a/packages/spec/src/ai/agent.form.ts +++ b/packages/spec/src/ai/agent.metadata-form.ts @@ -1,13 +1,13 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. -import { defineForm } from '../ui/view.zod'; +import { defineMetadataForm } from '../ui/view.zod'; /** * Agent Metadata Form * * Form layout for creating/editing AI agent metadata definitions. */ -export const agentForm = defineForm({ +export const agentForm = defineMetadataForm({ schemaId: 'agent', type: 'simple', sections: [ diff --git a/packages/spec/src/ai/ai-context.form.test.ts b/packages/spec/src/ai/ai-context.metadata-form.test.ts similarity index 96% rename from packages/spec/src/ai/ai-context.form.test.ts rename to packages/spec/src/ai/ai-context.metadata-form.test.ts index 35fcf7db268..ce55bc9300d 100644 --- a/packages/spec/src/ai/ai-context.form.test.ts +++ b/packages/spec/src/ai/ai-context.metadata-form.test.ts @@ -10,7 +10,7 @@ import { describe, it, expect } from 'vitest'; -import { aiContextForm } from './ai-context.form'; +import { aiContextForm } from './ai-context.metadata-form'; import { METADATA_FORM_REGISTRY } from '../system/metadata-form-registry'; type Row = { field?: string; widget?: string; dependsOn?: string; required?: boolean; fields?: Row[] }; diff --git a/packages/spec/src/ai/ai-context.form.ts b/packages/spec/src/ai/ai-context.metadata-form.ts similarity index 94% rename from packages/spec/src/ai/ai-context.form.ts rename to packages/spec/src/ai/ai-context.metadata-form.ts index cf06d86e062..0a0626f4447 100644 --- a/packages/spec/src/ai/ai-context.form.ts +++ b/packages/spec/src/ai/ai-context.metadata-form.ts @@ -1,6 +1,6 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -import { defineForm } from '../ui/view.zod'; +import { defineMetadataForm } from '../ui/view.zod'; import { AI_CONTEXT_BODY_FIELD_TYPES, AI_CONTEXT_MAX_FIELDS, AI_CONTEXT_MAX_RELATED, AI_CONTEXT_MAX_RELATED_FIELDS } from './ai-context.zod'; /** @@ -12,8 +12,8 @@ import { AI_CONTEXT_BODY_FIELD_TYPES, AI_CONTEXT_MAX_FIELDS, AI_CONTEXT_MAX_RELA * Every field picker is scoped by the pack's own root: * * - `fields` is the generic `field-multi` block with `dependsOn: 'object'` - * (the `page.form.ts` precedent): it offers the root object's fields. - * - `related` is the `related-list-entries` block (the `object.form.ts` + * (the `page.metadata-form.ts` precedent): it offers the root object's fields. + * - `related` is the `related-list-entries` block (the `object.metadata-form.ts` * precedent). Under a pack its entries are `{ object, field?, fields? }`, * so the block offers the relationships that point at the root and, for * each entry, that child object's fields as its columns. @@ -24,7 +24,7 @@ import { AI_CONTEXT_BODY_FIELD_TYPES, AI_CONTEXT_MAX_FIELDS, AI_CONTEXT_MAX_RELA * the pack is saved (`validateAiContext` on the runtime publish door) and by * `os validate`; the bounds are refused by `AiContextSchema` at parse. */ -export const aiContextForm = defineForm({ +export const aiContextForm = defineMetadataForm({ schemaId: 'ai_context', type: 'simple', sections: [ diff --git a/packages/spec/src/ai/index.ts b/packages/spec/src/ai/index.ts index 4c23c418f45..edce7e36c46 100644 --- a/packages/spec/src/ai/index.ts +++ b/packages/spec/src/ai/index.ts @@ -27,12 +27,12 @@ */ export * from './agent.zod'; -export { agentForm } from './agent.form'; +export { agentForm } from './agent.metadata-form'; export * from './tool.zod'; -export { toolForm } from './tool.form'; +export { toolForm } from './tool.metadata-form'; export * from './skill.zod'; -export { skillForm } from './skill.form'; -export { aiContextForm } from './ai-context.form'; +export { skillForm } from './skill.metadata-form'; +export { aiContextForm } from './ai-context.metadata-form'; export * from './conversation.zod'; export * from './model-registry.zod'; export * from './embedding.zod'; diff --git a/packages/spec/src/ai/skill.form.ts b/packages/spec/src/ai/skill.metadata-form.ts similarity index 96% rename from packages/spec/src/ai/skill.form.ts rename to packages/spec/src/ai/skill.metadata-form.ts index 4bbd92086c0..f22d79cb1c5 100644 --- a/packages/spec/src/ai/skill.form.ts +++ b/packages/spec/src/ai/skill.metadata-form.ts @@ -1,13 +1,13 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. -import { defineForm } from '../ui/view.zod'; +import { defineMetadataForm } from '../ui/view.zod'; /** * Skill Metadata Form * * Form layout for creating/editing AI skill metadata definitions. */ -export const skillForm = defineForm({ +export const skillForm = defineMetadataForm({ schemaId: 'skill', type: 'simple', sections: [ diff --git a/packages/spec/src/ai/tool.form.ts b/packages/spec/src/ai/tool.metadata-form.ts similarity index 94% rename from packages/spec/src/ai/tool.form.ts rename to packages/spec/src/ai/tool.metadata-form.ts index 815b0435126..54c3a861da2 100644 --- a/packages/spec/src/ai/tool.form.ts +++ b/packages/spec/src/ai/tool.metadata-form.ts @@ -1,6 +1,6 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. -import { defineForm } from '../ui/view.zod'; +import { defineMetadataForm } from '../ui/view.zod'; /** * Tool Metadata Form @@ -15,7 +15,7 @@ import { defineForm } from '../ui/view.zod'; * compliance — the same "advertising the failure mode" objectui#2962 removed * from the sharing-criteria builder. */ -export const toolForm = defineForm({ +export const toolForm = defineMetadataForm({ schemaId: 'tool', type: 'simple', sections: [ diff --git a/packages/spec/src/automation/flow.form.ts b/packages/spec/src/automation/flow.metadata-form.ts similarity index 98% rename from packages/spec/src/automation/flow.form.ts rename to packages/spec/src/automation/flow.metadata-form.ts index 649ed53a917..51d670409b4 100644 --- a/packages/spec/src/automation/flow.form.ts +++ b/packages/spec/src/automation/flow.metadata-form.ts @@ -1,13 +1,13 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. -import { defineForm } from '../ui/view.zod'; +import { defineMetadataForm } from '../ui/view.zod'; /** * Flow Metadata Form * * Form layout for creating/editing visual flow metadata definitions. */ -export const flowForm = defineForm({ +export const flowForm = defineMetadataForm({ schemaId: 'flow', type: 'simple', sections: [ diff --git a/packages/spec/src/automation/index.ts b/packages/spec/src/automation/index.ts index 9903ffd4fc6..e5e66b53e93 100644 --- a/packages/spec/src/automation/index.ts +++ b/packages/spec/src/automation/index.ts @@ -21,7 +21,7 @@ export * from './io-node-config.zod'; export * from './builtin-node-config.zod'; export * from './schemaless-node-config.zod'; export * from './flow-function.zod'; -export { flowForm } from './flow.form'; +export { flowForm } from './flow.metadata-form'; export * from './execution.zod'; export * from './webhook.zod'; export * from './approval.zod'; diff --git a/packages/spec/src/data/authoring-key-lint.ts b/packages/spec/src/data/authoring-key-lint.ts index a6522383093..d0bc066681f 100644 --- a/packages/spec/src/data/authoring-key-lint.ts +++ b/packages/spec/src/data/authoring-key-lint.ts @@ -86,7 +86,7 @@ const EMBEDDED_JSON_TYPED_LIST = * Semantic near-misses on `FieldSchema` — a different **word** for the same * intent, or a key that was retired outright. * - * Every entry here was found in the wild. The rename half is what `object.form.ts` + * Every entry here was found in the wild. The rename half is what `object.metadata-form.ts` * had drifted into by #4120; the retired half is the `auditTrail` / `dataQuality` * / `encryptionConfig` family pruned in 2026-06 plus the field-level `index` flag * removed in the 16.x line (#2377). Edit distance cannot reach most of these diff --git a/packages/spec/src/data/field-currency-scale-refused.test.ts b/packages/spec/src/data/field-currency-scale-refused.test.ts index 123b3e15b3f..d0027d8517b 100644 --- a/packages/spec/src/data/field-currency-scale-refused.test.ts +++ b/packages/spec/src/data/field-currency-scale-refused.test.ts @@ -16,7 +16,7 @@ * change. The write seam drops `currency` from its enforced set in the same * change (pinned in that package's `record-validator.test.ts`); this file pins * the authoring half: the parse door, and the OFFER beside it. The object - * designer's quick-add grid (`object.form.ts`, the registered `object` form) + * designer's quick-add grid (`object.metadata-form.ts`, the registered `object` form) * showed its `scale` input on currency rows until the at-tier review of this * change caught it; a door that refuses a key a registered form still offers is * the offer-vs-door shape the retirement exists to remove, so the last block @@ -31,7 +31,7 @@ import { describe, expect, it } from 'vitest'; import { Field, FieldSchema } from './field.zod'; import { ObjectSchema } from './object.zod'; -import { objectForm } from './object.form'; +import { objectForm } from './object.metadata-form'; import { METADATA_FORM_REGISTRY } from '../system/metadata-form-registry'; type Issue = { code: string; path: PropertyKey[]; message: string }; @@ -155,7 +155,7 @@ describe('CONTROLS: what the refusal must leave alone', () => { type FormRow = Record; -/** `defineForm` stores a predicate as `{ dialect, source }`; accept the bare string too. */ +/** `defineMetadataForm` stores a predicate as `{ dialect, source }`; accept the bare string too. */ function predicateSource(row: FormRow): string | undefined { const raw = row.visibleWhen; if (raw == null) return undefined; diff --git a/packages/spec/src/data/field-due-like.test.ts b/packages/spec/src/data/field-due-like.test.ts index 5635c6590b8..620deb264e2 100644 --- a/packages/spec/src/data/field-due-like.test.ts +++ b/packages/spec/src/data/field-due-like.test.ts @@ -26,7 +26,7 @@ import { describe, it, expect } from 'vitest'; import { FieldSchema } from './field.zod'; -import { fieldForm } from './field.form'; +import { fieldForm } from './field.metadata-form'; const DEADLINE_TYPES = ['date', 'datetime'] as const; @@ -158,7 +158,7 @@ describe('settledWhen without dueLike: true is refused (ADR-0049: a declared key describe('field.form offers the deadline keys on exactly the types the door accepts', () => { const rows = (fieldForm.sections ?? []).flatMap((s) => s.fields ?? []) as Array<{ field?: string; visibleWhen?: unknown }>; const rowFor = (key: string) => rows.find((r) => r.field === key); - // `defineForm` normalizes a bare predicate string to its `{ dialect, source }` + // `defineMetadataForm` normalizes a bare predicate string to its `{ dialect, source }` // envelope, so the gate is read off `source`. const gateOf = (row: { visibleWhen?: unknown }) => { const v = row.visibleWhen as string | { source?: string } | undefined; diff --git a/packages/spec/src/data/field-form-external-id-not-offered.test.ts b/packages/spec/src/data/field-form-external-id-not-offered.test.ts index dd35fcd3ee7..0111eba9502 100644 --- a/packages/spec/src/data/field-form-external-id-not-offered.test.ts +++ b/packages/spec/src/data/field-form-external-id-not-offered.test.ts @@ -18,7 +18,7 @@ import { fileURLToPath } from 'node:url'; import { describe, it, expect } from 'vitest'; -import { fieldForm } from './field.form'; +import { fieldForm } from './field.metadata-form'; import { FieldSchema } from './field.zod'; const HERE = dirname(fileURLToPath(import.meta.url)); diff --git a/packages/spec/src/data/field-form-reference-name-visible.test.ts b/packages/spec/src/data/field-form-reference-name-visible.test.ts index 512f7b84038..9ddcbea20d6 100644 --- a/packages/spec/src/data/field-form-reference-name-visible.test.ts +++ b/packages/spec/src/data/field-form-reference-name-visible.test.ts @@ -17,7 +17,7 @@ import { describe, it, expect } from 'vitest'; -import { fieldForm } from './field.form'; +import { fieldForm } from './field.metadata-form'; import { FieldSchema, FieldType } from './field.zod'; type Predicate = string | { dialect?: string; source?: string } | undefined; diff --git a/packages/spec/src/data/field-mail-association.test.ts b/packages/spec/src/data/field-mail-association.test.ts index ce0b64219d2..91ed733012d 100644 --- a/packages/spec/src/data/field-mail-association.test.ts +++ b/packages/spec/src/data/field-mail-association.test.ts @@ -25,7 +25,7 @@ import { describe, it, expect } from 'vitest'; import { z } from 'zod'; import { FieldSchema } from './field.zod'; -import { fieldForm } from './field.form'; +import { fieldForm } from './field.metadata-form'; // ========================================================================= // 1. The accepted shape — full parse green, the authored value kept @@ -132,7 +132,7 @@ describe('the JSON-schema projection of FieldSchema carries mailAssociation', () describe('field.form offers mailAssociation on exactly the type the door accepts', () => { const rows = (fieldForm.sections ?? []).flatMap((s) => s.fields ?? []) as Array<{ field?: string; visibleWhen?: unknown }>; - // `defineForm` normalizes a bare predicate string to its `{ dialect, source }` + // `defineMetadataForm` normalizes a bare predicate string to its `{ dialect, source }` // envelope, so the gate is read off `source`. const gateOf = (row: { visibleWhen?: unknown }) => { const v = row.visibleWhen as string | { source?: string } | undefined; diff --git a/packages/spec/src/data/field-rows-option-description.test.ts b/packages/spec/src/data/field-rows-option-description.test.ts index 2021818ccf6..d433334529d 100644 --- a/packages/spec/src/data/field-rows-option-description.test.ts +++ b/packages/spec/src/data/field-rows-option-description.test.ts @@ -33,7 +33,7 @@ * [#13671] Section 3 was added later and is about the OTHER half of the same * offer-vs-door pair this file already documents. The `icon` control in * section 2 used to assert one thing — the door refuses `icon` — while - * `object.form.ts` went on OFFERING an `icon` input, so the file was green + * `object.metadata-form.ts` went on OFFERING an `icon` input, so the file was green * across a live disagreement. Section 3 pins the offer side; the file keeps * its name because the two subjects are one story (`options[]` keys the * authoring form and the publish door must agree about). @@ -42,7 +42,7 @@ import { describe, it, expect } from 'vitest'; import { FieldSchema, SelectOptionSchema } from './field.zod'; -import { objectForm } from './object.form'; +import { objectForm } from './object.metadata-form'; import { FormSelectOptionSchema } from '../ui/view.zod'; // ========================================================================= @@ -228,7 +228,7 @@ describe('SelectOptionSchema accepts `description` — declared because the look * * The `icon` case in section 2 used to stand alone and assert ONE thing: the * publish door refuses `icon`. That was true and is still true — but while it - * held, `object.form.ts`'s options repeater went on OFFERING an `icon` text + * held, `object.metadata-form.ts`'s options repeater went on OFFERING an `icon` text * input labelled "Lucide icon name", so a Studio author was taught a key the * door rejects and found out at the 422. The pin was green across a live * disagreement because it only ever looked at one side of it. diff --git a/packages/spec/src/data/field.form.ts b/packages/spec/src/data/field.metadata-form.ts similarity index 98% rename from packages/spec/src/data/field.form.ts rename to packages/spec/src/data/field.metadata-form.ts index 0fb83eb6764..07b61a1d9c6 100644 --- a/packages/spec/src/data/field.form.ts +++ b/packages/spec/src/data/field.metadata-form.ts @@ -1,13 +1,13 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. -import { defineForm } from '../ui/view.zod'; +import { defineMetadataForm } from '../ui/view.zod'; /** * Field Metadata Form * * Form layout for creating/editing field metadata definitions. */ -export const fieldForm = defineForm({ +export const fieldForm = defineMetadataForm({ schemaId: 'field', type: 'simple', sections: [ @@ -76,7 +76,7 @@ export const fieldForm = defineForm({ { field: 'min', visibleWhen: "data.type == 'number' || data.type == 'currency'", helpText: 'Minimum value' }, { field: 'max', visibleWhen: "data.type == 'number' || data.type == 'currency'", helpText: 'Maximum value' }, // #19992 — the help text follows the key's describe ("Total digits") - // and the object designer's quick-add row (`object.form.ts`): the old + // and the object designer's quick-add row (`object.metadata-form.ts`): the old // "Decimal places (e.g., 2 for $10.50)" taught the one reading the // contract refuses. A currency's decimal places are its CLDR fraction // digits and are declared nowhere. @@ -89,7 +89,7 @@ export const fieldForm = defineForm({ // (the same `z.boolean().optional()` node, no default): the switch // writes nothing until toggled, so an untouched field stays unset and // the renderer decides. It reads off meanwhile, even where the renderer - // groups, and the help text says so in the words of the `object.form.ts` + // groups, and the help text says so in the words of the `object.metadata-form.ts` // `userActions` row. Gated like `scale`, a `number`-only hint. { field: 'useGrouping', visibleWhen: "data.type == 'number'", helpText: 'Digit grouping (thousands separators) in displayed values. Unset: the renderer decides; an untouched switch writes nothing, so it reads off even where the renderer groups. Off: never grouped, e.g. a year or an ID. On: always grouped.' }, // `percentDisplay` is shown once it is enforced, the `useGrouping` @@ -105,7 +105,7 @@ export const fieldForm = defineForm({ ] }, // #19332 G1b (ruling 5861442317, G1) — `currencyConfig` is a strict object // with two keys, and both members of its one enum are spellable option - // values, so it takes the `object.form.ts` `access` / `lifecycle` face: a + // values, so it takes the `object.metadata-form.ts` `access` / `lifecycle` face: a // composite whose sub-rows are DECLARED, so their labels and help text // reach the translation catalogs (a schema-derived sub-field never does). // The schema default (`dynamic`) is a placeholder the renderer never @@ -133,12 +133,12 @@ export const fieldForm = defineForm({ // Every `visibleWhen` below is a MEANINGFULNESS gate, not a parse gate: // `FieldSchema` accepts each key on any type, and each is mirrored from // the key's own contract text and from the same row in the object - // designer's quick-add grid (`object.form.ts`), so the two surfaces + // designer's quick-add grid (`object.metadata-form.ts`), so the two surfaces // cannot disagree about when a knob applies. { field: 'step', visibleWhen: "data.type == 'slider'", helpText: 'Step increment for the slider (default 1). Renderer-only: the write path does not reject a value off the step grid.' }, { field: 'maxSize', visibleWhen: "data.type in ['image','file','avatar','video','audio']", helpText: 'Maximum permitted file size in BYTES (positive integer). Enforced server-side on write against the stored file size — a file with no recorded size cannot fail it.' }, // #19332 G1b — `accept` is `string[]`, not a union, so it takes the - // `app.form.ts` `requiredPermissions` face (`string-tags`, a chip input + // `app.metadata-form.ts` `requiredPermissions` face (`string-tags`, a chip input // over `string[]`). Its gate is `maxSize`'s: both are checked by the same // server-side file-constraint pass, on the same five media types. { field: 'accept', widget: 'string-tags', visibleWhen: "data.type in ['image','file','avatar','video','audio']", helpText: 'Permitted upload types, as MIME types, type/* wildcards or .ext suffixes (e.g. image/*, .pdf). Offered to the file picker and re-checked server-side on write against the stored file. Unset: any type.' }, @@ -202,7 +202,7 @@ export const fieldForm = defineForm({ // Reference field options { field: 'reference', widget: 'ref:object', visibleWhen: "data.type == 'lookup' || data.type == 'master_detail'", helpText: 'Referenced object name' }, // Two declarations of one key, with disjoint `visibleWhen` (#11410) — - // the same split `object.form.ts` carries, and for the same reason: + // the same split `object.metadata-form.ts` carries, and for the same reason: // #9689 made `set_null` on a `master_detail` a parse-time rejection, so // one shared control offered a choice publish refuses. // @@ -307,7 +307,7 @@ export const fieldForm = defineForm({ // #19332 G1b (ruling 5861442317, G1) — the picker's two structured knobs. // // `lookupFilters` is the same key on the same node as the object - // designer's per-field row (`object.form.ts`, `fields.lookupFilters`), so + // designer's per-field row (`object.metadata-form.ts`, `fields.lookupFilters`), so // it copies that row: `json`, no inline `options` (`notIn` carries a // capital, which `FormSelectOptionSchema.value` cannot spell). // @@ -327,7 +327,7 @@ export const fieldForm = defineForm({ { field: 'dependsOn', widget: 'json', visibleWhen: "data.type in ['lookup','master_detail','select','multiselect','radio','checkboxes']", helpText: 'Fields on the same record this field\'s choices depend on: the form holds this field until each is set, and re-evaluates it when one changes. A lookup filters its candidates by them — a name filters the same-named field of the referenced object, {field, param} names a different one. On an option field list the parent field names; the per-option rule lives in each option\'s visibleWhen.' }, { field: 'relatedListTitle', visibleWhen: "data.type in ['lookup','master_detail']", helpText: "Title for this relationship's related list on the parent's detail page." }, // `relatedListColumns` is `string[]` by ruling (an object entry is - // refused at parse), so it takes `string-tags`, the `app.form.ts` + // refused at parse), so it takes `string-tags`, the `app.metadata-form.ts` // `requiredPermissions` face. A field picker is not offered: the names // are the CHILD object's (this field's own object), and no widget here // reads a catalog from the field draft. @@ -344,7 +344,7 @@ export const fieldForm = defineForm({ { field: 'inlineTitle', visibleWhen: "data.type == 'master_detail'", helpText: 'Title for the inline master-detail grid on the parent record.' }, // #19332 (flight G2b of ruling record 5861442317) — the inline grid's // explicit columns, between the grid's title and its total and behind the - // same gate. A repeater with declared sub-rows, the `object.form.ts` + // same gate. A repeater with declared sub-rows, the `object.metadata-form.ts` // `fieldGroups` repeater's face, over a CURATED SUBSET of the twenty // keys `InlineGridColumnSchema` accepts; the reconciliation ledger // records the `subset` row and names what is left out and why. @@ -473,7 +473,7 @@ export const fieldForm = defineForm({ { field: 'searchable', colSpan: 1, helpText: 'Include in global search results' }, { field: 'sortable', colSpan: 1, helpText: 'Allow sorting lists by this field' }, // #19332 G1b — the three field-level predicates. Same keys, same node, as - // the object designer's per-field rows (`object.form.ts`, + // the object designer's per-field rows (`object.metadata-form.ts`, // `fields.visibleWhen` / `readonlyWhen` / `requiredWhen`), so they copy // that row: `type: 'code'`, `language: 'expression'`. { field: 'visibleWhen', type: 'code', language: 'expression', colSpan: 2, helpText: "CEL predicate over the record (e.g. record.type == 'invoice') — the form shows this field only while it is TRUE." }, @@ -483,7 +483,7 @@ export const fieldForm = defineForm({ // object; the runtime FieldMasker enforces it on read AND export. { field: 'maskingRule', colSpan: 2, helpText: "Partial masking: preset ('phone', 'id_card', 'bank_account', 'email', 'name') or {\"keepHead\": n, \"keepTail\": m}. Masked for callers not holding this field's requiredPermissions" }, // #19332 G1b — the capability gate `maskingRule` above already names. - // `string[]`, so the `app.form.ts` `requiredPermissions` face. + // `string[]`, so the `app.metadata-form.ts` `requiredPermissions` face. { field: 'requiredPermissions', widget: 'string-tags', colSpan: 2, helpText: "Capabilities (permission-set systemPermissions) a caller must hold — every one listed — to read or edit this field (ADR-0066 D3). Without them the value is masked on read (partially, when a maskingRule is set) and edits are denied. Empty or unset: no capability gate." }, { field: 'internal', colSpan: 1, helpText: "Never return this field's value on the generic data path: the engine omits the key from find/findOne results and from the create and update response bodies, on the default projection and when a client names the field in ?select=. Storage, filtering and indexing are untouched." }, // [#36290] The off switch is `fieldHistory` (no default); `trackHistory` diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index c346c229c2f..a66cde9cf61 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -390,7 +390,7 @@ export const SelectOptionSchema = lazySchema(() => strictObject({ * produces the same key for fetched options — while this strict shape * refused it at publish, so the search behaviour was real for a key no * author could legally write. The object-definition authoring form - * (`object.form.ts` options repeater) has offered a `description` input all + * (`object.metadata-form.ts` options repeater) has offered a `description` input all * along; this declaration is what makes that offer honest. Per the same * inherited ruling this option shape declares `description` and no cascade * key of its own — `field-rows-option-description.test.ts` pins that diff --git a/packages/spec/src/data/form-delete-behavior-options.test.ts b/packages/spec/src/data/form-delete-behavior-options.test.ts index 6f67d21a1d7..5b278d015ca 100644 --- a/packages/spec/src/data/form-delete-behavior-options.test.ts +++ b/packages/spec/src/data/form-delete-behavior-options.test.ts @@ -14,9 +14,9 @@ * * ## The two forms failed the same way through DIFFERENT option sources * - * - `object.form.ts` declared an inline `options` array carrying all three + * - `object.metadata-form.ts` declared an inline `options` array carrying all three * values, gated by one `visibleWhen` naming both types. - * - `field.form.ts` declared NO `options` at all. That is not a narrower + * - `field.metadata-form.ts` declared NO `options` at all. That is not a narrower * offer — it is the renderer's DERIVED source: with no `fieldSpec.options` * the metadata-admin form falls through to the JSON Schema `enum`, which is * `['set_null','cascade','restrict']` and additionally advertises @@ -64,8 +64,8 @@ import { describe, it, expect } from 'vitest'; import { z } from 'zod'; -import { objectForm } from './object.form'; -import { fieldForm } from './field.form'; +import { objectForm } from './object.metadata-form'; +import { fieldForm } from './field.metadata-form'; import { FieldSchema } from './field.zod'; import { FormViewSchema } from '../ui/view.zod'; @@ -254,7 +254,7 @@ describe('`deleteBehavior` is never offered a value the schema refuses', () => { }); it('is expressible in the form DSL as it stands — no schema extension', () => { - // `defineForm` already parses at module load; re-parsing makes the + // `defineMetadataForm` already parses at module load; re-parsing makes the // claim an assertion rather than an import side effect. If the fix had // needed a key the DSL does not declare, this is where it would fail. const parsed = (FormViewSchema as unknown as z.ZodType).safeParse(form); diff --git a/packages/spec/src/data/form-return-type-options.test.ts b/packages/spec/src/data/form-return-type-options.test.ts index f5860d031ac..c50f4d40346 100644 --- a/packages/spec/src/data/form-return-type-options.test.ts +++ b/packages/spec/src/data/form-return-type-options.test.ts @@ -5,7 +5,7 @@ * schema REFUSES. * * `FieldSchema.returnType` has always been `z.enum(['number','text','boolean', - * 'date'])`. The object designer's quick-add grid (`object.form.ts`, the + * 'date'])`. The object designer's quick-add grid (`object.metadata-form.ts`, the * `fields` repeater) declared an inline `options` list of SIX — the four plus * `datetime` and `currency` — so an author who added a formula field there and * picked either of the extra two wrote a value the parse refuses. The failure @@ -15,7 +15,7 @@ * * The exit is a pull-back, not a decision about what a formula may return. Two * carriers in this package already spelled the accept set correctly — the enum - * itself, and the field designer's own control in `field.form.ts` (four + * itself, and the field designer's own control in `field.metadata-form.ts` (four * members, explicit list). Narrowing the grid makes it three. * * ## Why the four, and not the six @@ -58,8 +58,8 @@ import { describe, it, expect } from 'vitest'; import { z } from 'zod'; -import { objectForm } from './object.form'; -import { fieldForm } from './field.form'; +import { objectForm } from './object.metadata-form'; +import { fieldForm } from './field.metadata-form'; import { FieldSchema } from './field.zod'; import { FormViewSchema } from '../ui/view.zod'; @@ -212,7 +212,7 @@ describe('`returnType` is never offered a value the schema refuses', () => { }); it('is expressible in the form DSL as it stands — no schema extension', () => { - // `defineForm` parses at module load; re-parsing makes the claim an + // `defineMetadataForm` parses at module load; re-parsing makes the claim an // assertion rather than an import side effect. const parsed = (FormViewSchema as unknown as z.ZodType).safeParse(form); expect(parsed.success, JSON.stringify((parsed as { error?: unknown }).error)).toBe(true); diff --git a/packages/spec/src/data/hook-refusals.test.ts b/packages/spec/src/data/hook-refusals.test.ts index 16f1b2f3c0d..7b56fb9b2c4 100644 --- a/packages/spec/src/data/hook-refusals.test.ts +++ b/packages/spec/src/data/hook-refusals.test.ts @@ -14,7 +14,7 @@ import { } from './hook-refusal-codes'; import { hookRefusalMessageKey } from '../system/i18n-resolver'; import { TranslationDataSchema } from '../system/translation.zod'; -import { hookForm } from './hook.form'; +import { hookForm } from './hook.metadata-form'; // #26170 (maintainer ruling 6431311681, letter A): a hook declares its refusal // catalogue, `refusals: { : { message, status? } }`, and its body refuses diff --git a/packages/spec/src/data/hook.form.ts b/packages/spec/src/data/hook.metadata-form.ts similarity index 98% rename from packages/spec/src/data/hook.form.ts rename to packages/spec/src/data/hook.metadata-form.ts index 3b839a76f5c..9ecf13d0a3f 100644 --- a/packages/spec/src/data/hook.form.ts +++ b/packages/spec/src/data/hook.metadata-form.ts @@ -1,6 +1,6 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. -import { defineForm } from '../ui/view.zod'; +import { defineMetadataForm } from '../ui/view.zod'; /** * Form Layout for Hook Metadata Type @@ -12,7 +12,7 @@ import { defineForm } from '../ui/view.zod'; * declared texts (`texts`) sit beside it: a js body or a handler may declare * them, an expression body may not. */ -export const hookForm = defineForm({ +export const hookForm = defineMetadataForm({ schemaId: 'hook', type: 'simple', sections: [ diff --git a/packages/spec/src/data/index.ts b/packages/spec/src/data/index.ts index 93d23cd0e33..06ed74b5450 100644 --- a/packages/spec/src/data/index.ts +++ b/packages/spec/src/data/index.ts @@ -324,9 +324,9 @@ export * from './seed-file.zod'; export * from './seed.zod'; // Form Layouts -export { objectForm } from './object.form'; -export { fieldForm } from './field.form'; -export { hookForm } from './hook.form'; +export { objectForm } from './object.metadata-form'; +export { fieldForm } from './field.metadata-form'; +export { hookForm } from './hook.metadata-form'; // Seed Loader Protocol (Relationship Resolution & Dependency Ordering) export * from './seed-loader.zod'; diff --git a/packages/spec/src/data/object.form.ts b/packages/spec/src/data/object.metadata-form.ts similarity index 99% rename from packages/spec/src/data/object.form.ts rename to packages/spec/src/data/object.metadata-form.ts index dc2c9cb6401..b6c53729871 100644 --- a/packages/spec/src/data/object.form.ts +++ b/packages/spec/src/data/object.metadata-form.ts @@ -1,6 +1,6 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. -import { defineForm } from '../ui/view.zod'; +import { defineMetadataForm } from '../ui/view.zod'; import { ValueDomainSchema, type ValueDomain } from '../shared/value-domain.zod'; /** @@ -24,7 +24,7 @@ const VALUE_DOMAIN_OPTIONS = ValueDomainSchema.options.map((value) => ({ /** * Form Layout for Object Metadata Type */ -export const objectForm = defineForm({ +export const objectForm = defineMetadataForm({ schemaId: 'object', type: 'simple', sections: [ @@ -62,7 +62,7 @@ export const objectForm = defineForm({ { field: 'imageField', type: 'text', colSpan: 1, helpText: 'Field whose value is each record\'s picture, drawn beside the title in the record page header. Must name a field of this object whose type is image or avatar; any other name is refused when the object is saved. Empty: no record picture, and no placeholder is drawn.' }, { field: 'isSystem', type: 'boolean', colSpan: 1, helpText: 'System object (protected from deletion; defaults sharing to public)' }, // #20349 — the object's two own field-name LISTS, beside the `nameField` - // pointer. Free text, the `view.form.ts` `searchableFields` row's face: + // pointer. Free text, the `view.metadata-form.ts` `searchableFields` row's face: // `string-tags` is a chip input over `string[]`, which is exactly this // node. A field picker is not an option here — `field-multi` takes its // catalog from the draft's `object` / `objectName` / `data.object` / @@ -106,7 +106,7 @@ export const objectForm = defineForm({ // `collapse` is absent). // // `fields` is the group's own member list (field names, in display - // order), a `tags` row as `hook.form.ts` gives a list of names; a name + // order), a `tags` row as `hook.metadata-form.ts` gives a list of names; a name // no field declares is skipped by the layout and warned by `os lint`. { field: 'fieldGroups', @@ -392,14 +392,14 @@ export const objectForm = defineForm({ // Formula / summary // `expression`, not `formula` — the key is named for what it holds, // not for the field type that uses it. Shown for every type, as the - // field designer's own row in `field.form.ts` is: `FieldSchema` + // field designer's own row in `field.metadata-form.ts` is: `FieldSchema` // accepts `expression` on any type, and on a non-formula field the // engine computes and stores it on write (`planStoredExpressions`), // so a formula-only row hid a live key on a stored field. { field: 'expression', type: 'code', language: 'expression', helpText: 'CEL expression the field\'s value is computed from. On a formula field: computed on read, no stored column. On any other field: computed by the engine from the row each write stores, and stored, so a client-sent value never stands.' }, // The six members are what `FieldSchema.returnType` declares, and // the same explicit list the field designer's own control carries - // in `field.form.ts` (#19677). This grid additionally offered + // in `field.metadata-form.ts` (#19677). This grid additionally offered // `datetime` and `currency`, so an author who added a formula field // here and picked either wrote a value the parse refuses — the // refusal arriving from the save door, naming a key they never @@ -422,7 +422,7 @@ export const objectForm = defineForm({ visibleWhen: "data.type == 'summary'", fields: [ { field: 'object', type: 'text', required: true, helpText: 'Source child object name' }, - // Not `required`: a `count` saves without it (see field.form.ts). + // Not `required`: a `count` saves without it (see field.metadata-form.ts). { field: 'field', type: 'text', helpText: 'Field on the child object to aggregate (ignored for count)' }, { field: 'function', type: 'select', required: true, helpText: 'Aggregation function', options: [ { label: 'Count', value: 'count' }, { label: 'Sum', value: 'sum' }, { label: 'Avg', value: 'avg' }, diff --git a/packages/spec/src/identity/index.ts b/packages/spec/src/identity/index.ts index 5eb420d93d0..ce3bce1680c 100644 --- a/packages/spec/src/identity/index.ts +++ b/packages/spec/src/identity/index.ts @@ -3,7 +3,7 @@ export * from './identity.zod'; export * from './protocol'; export * from './position.zod'; -export { positionForm } from './position.form'; +export { positionForm } from './position.metadata-form'; export * from './organization.zod'; export * from './scim.zod'; export * from './eval-user.zod'; diff --git a/packages/spec/src/identity/position.form.ts b/packages/spec/src/identity/position.metadata-form.ts similarity index 95% rename from packages/spec/src/identity/position.form.ts rename to packages/spec/src/identity/position.metadata-form.ts index 31fec422b4f..d5412fad0d8 100644 --- a/packages/spec/src/identity/position.form.ts +++ b/packages/spec/src/identity/position.metadata-form.ts @@ -1,6 +1,6 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. -import { defineForm } from '../ui/view.zod'; +import { defineMetadataForm } from '../ui/view.zod'; /** * Position — canonical FormView layout. @@ -10,7 +10,7 @@ import { defineForm } from '../ui/view.zod'; * business units. Single section is enough; the FormView gives the editor * friendly labels and required markers. */ -export const positionForm = defineForm({ +export const positionForm = defineMetadataForm({ schemaId: 'position', type: 'simple', sections: [ diff --git a/packages/spec/src/index.ts b/packages/spec/src/index.ts index 12baa6f68a8..dcf2f4c2b8b 100644 --- a/packages/spec/src/index.ts +++ b/packages/spec/src/index.ts @@ -111,7 +111,7 @@ export type { DefineStackOptions, ComposeStacksOptions, ConflictStrategy, Object export * from './stack.zod'; // DX Helper Functions (re-exported for convenience) -export { defineView, defineForm, defineViewItem, isAggregatedViewContainer, expandViewContainer, expandViewContainerWithDiagnostics } from './ui/view.zod'; +export { defineView, 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/repeater-item-titles.test.ts b/packages/spec/src/kernel/repeater-item-titles.test.ts index 826afb020ab..5af22b2eaf5 100644 --- a/packages/spec/src/kernel/repeater-item-titles.test.ts +++ b/packages/spec/src/kernel/repeater-item-titles.test.ts @@ -16,7 +16,7 @@ // #16458 (PR #17227) titled exactly one repeater, `dashboard.header.actions`. // The class was left silent: the 22nd repeater added next month reproduces the // defect with every gate green. THIS FILE IS THE LOUDNESS. It enumerates every -// repeater declared across every `*.form.ts` in this package, derives each +// repeater declared across every `*.metadata-form.ts` in this package, derives each // one's row schema through the platform's own predicate, and requires every // row property to carry a title — with a shrink-only ledger of the carriers // that are still owed one. @@ -40,25 +40,25 @@ import { z } from 'zod'; import { getMetadataTypeSchema } from './metadata-type-schemas'; -import { skillForm } from '../ai/skill.form'; -import { agentForm } from '../ai/agent.form'; -import { toolForm } from '../ai/tool.form'; -import { flowForm } from '../automation/flow.form'; -import { objectForm } from '../data/object.form'; -import { fieldForm } from '../data/field.form'; -import { hookForm } from '../data/hook.form'; -import { positionForm } from '../identity/position.form'; -import { actionForm } from '../ui/action.form'; -import { appForm } from '../ui/app.form'; -import { dashboardForm } from '../ui/dashboard.form'; -import { datasetForm } from '../ui/dataset.form'; -import { pageForm } from '../ui/page.form'; -import { reportForm } from '../ui/report.form'; -import { viewForm } from '../ui/view.form'; +import { skillForm } from '../ai/skill.metadata-form'; +import { agentForm } from '../ai/agent.metadata-form'; +import { toolForm } from '../ai/tool.metadata-form'; +import { flowForm } from '../automation/flow.metadata-form'; +import { objectForm } from '../data/object.metadata-form'; +import { fieldForm } from '../data/field.metadata-form'; +import { hookForm } from '../data/hook.metadata-form'; +import { positionForm } from '../identity/position.metadata-form'; +import { actionForm } from '../ui/action.metadata-form'; +import { appForm } from '../ui/app.metadata-form'; +import { dashboardForm } from '../ui/dashboard.metadata-form'; +import { datasetForm } from '../ui/dataset.metadata-form'; +import { pageForm } from '../ui/page.metadata-form'; +import { reportForm } from '../ui/report.metadata-form'; +import { viewForm } from '../ui/view.metadata-form'; /** - * Every `*.form.ts` in this package, by its export name. `check:generated` - * does not police this list, so `it('covers every *.form.ts', …)` below reads + * Every `*.metadata-form.ts` in this package, by its export name. `check:generated` + * does not police this list, so `it('covers every *.metadata-form.ts', …)` below reads * the directory listing this file cannot — it asserts the COUNT against the * form exports the domain barrels carry, which is what a new form file moves. */ diff --git a/packages/spec/src/migrations/entries/semantic/18.define-form-studio-helper-renamed-define-metadata-form.ts b/packages/spec/src/migrations/entries/semantic/18.define-form-studio-helper-renamed-define-metadata-form.ts new file mode 100644 index 00000000000..f84c47bf45c --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.define-form-studio-helper-renamed-define-metadata-form.ts @@ -0,0 +1,33 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// A TS/API surface, never stored in stack metadata: the helper builds Studio's +// schema-bound metadata-editing forms, so no authored stack and no stored row +// carries its name and there is no source for the chain to rewrite. This entry +// is the whole ADR-0087 registration of the export rename (ADR-0159, ruled +// question 1 = A, ruling record 7131569242 on #36868). +export const entry: SemanticMigration = { + id: 'define-form-studio-helper-renamed-define-metadata-form', + surface: + '`defineForm` (function) on `@objectstack/spec` and `@objectstack/spec/ui` — the factory of a ' + + 'schema-bound Studio metadata-editing form (`data.provider: \'schema\'`), and the `*.form.ts` file ' + + 'suffix of its modules', + replacement: + '`defineMetadataForm`, with the same argument and the same result (`defineMetadataForm({ schemaId, … })`); ' + + 'a module that builds one is named `NAME.metadata-form.ts`. The name `defineForm` and the `*.form.ts` ' + + 'suffix belong to the `form` metadata type (ADR-0159 D2) and return with that type in the same major, ' + + 'with another meaning: a `form` item is `name` + `object` + a form body, not a schema-bound Studio form', + reason: + 'ADR-0159 adds `form` as a metadata type, and the maintainer ruled that the obvious factory name goes to ' + + 'it (question 1 = A). The Studio helper held that name and the suffix in a meaning the new type does not ' + + 'have, so it is renamed after the translation family its modules feed (`metadataForms`). The outside-use ' + + 'reading before the rename found no import or call of `defineForm` outside objectstack-ai/objectstack, in ' + + 'any public repository of the organization or in the cloud repository. The compiler delivers the break at ' + + 'the call site (TS2305 / TS2724); `os migrate meta` has nothing to visit, because no metadata document ' + + 'names the helper', + acceptanceCriteria: + 'No code imports `defineForm` from `@objectstack/spec` for a schema-bound Studio form: each such call reads ' + + '`defineMetadataForm` and its module is named `*.metadata-form.ts`; the project type-checks; every ' + + 'metadata-editing form parses and refuses exactly as before, because only the name moved.', +}; diff --git a/packages/spec/src/security/index.ts b/packages/spec/src/security/index.ts index 5605b629cdf..b454593574c 100644 --- a/packages/spec/src/security/index.ts +++ b/packages/spec/src/security/index.ts @@ -16,7 +16,7 @@ export * from './permission.zod'; export * from './permission-set-owner-binding'; -export * from './permission.form'; +export * from './permission.metadata-form'; export * from './capabilities'; export * from './high-privilege'; export * from './public-form'; diff --git a/packages/spec/src/security/permission-form-label-first.test.ts b/packages/spec/src/security/permission-form-label-first.test.ts index 02ee2dd0760..19116f1d3ee 100644 --- a/packages/spec/src/security/permission-form-label-first.test.ts +++ b/packages/spec/src/security/permission-form-label-first.test.ts @@ -16,7 +16,7 @@ import { describe, expect, it } from 'vitest'; import { METADATA_FORM_REGISTRY } from '../system/metadata-form-registry'; -import { permissionForm } from './permission.form'; +import { permissionForm } from './permission.metadata-form'; import { PermissionSetSchema } from './permission.zod'; type Row = { field: string; required?: boolean; helpText?: string }; diff --git a/packages/spec/src/security/permission-set-managed-by-retirement.test.ts b/packages/spec/src/security/permission-set-managed-by-retirement.test.ts index 83383ff9698..3ce6607b775 100644 --- a/packages/spec/src/security/permission-set-managed-by-retirement.test.ts +++ b/packages/spec/src/security/permission-set-managed-by-retirement.test.ts @@ -41,7 +41,7 @@ import { applyConversionsToStoredItem } from '../conversions/stored'; import { getMetadataTypeSchema } from '../kernel/metadata-type-schemas'; import { MIGRATIONS_BY_MAJOR, RETIRED_KEYS_BY_MAJOR } from '../migrations/registry'; import { defineStack, ObjectStackDefinitionSchema } from '../stack.zod'; -import { permissionForm } from './permission.form'; +import { permissionForm } from './permission.metadata-form'; import { PermissionSetSchema, type PermissionSet } from './permission.zod'; const KEY = 'managedBy'; diff --git a/packages/spec/src/security/permission.form.ts b/packages/spec/src/security/permission.metadata-form.ts similarity index 98% rename from packages/spec/src/security/permission.form.ts rename to packages/spec/src/security/permission.metadata-form.ts index 0e5fa6918bc..0ea480e0377 100644 --- a/packages/spec/src/security/permission.form.ts +++ b/packages/spec/src/security/permission.metadata-form.ts @@ -1,6 +1,6 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. -import { defineForm } from '../ui/view.zod'; +import { defineMetadataForm } from '../ui/view.zod'; /** * PermissionSet — canonical FormView layout. @@ -20,7 +20,7 @@ import { defineForm } from '../ui/view.zod'; * now — they're typically managed via the dedicated permission matrix * UI on a record-by-record basis, not free-form editing. */ -export const permissionForm = defineForm({ +export const permissionForm = defineMetadataForm({ schemaId: 'permission', type: 'simple', sections: [ diff --git a/packages/spec/src/system/email-template.form.ts b/packages/spec/src/system/email-template.metadata-form.ts similarity index 96% rename from packages/spec/src/system/email-template.form.ts rename to packages/spec/src/system/email-template.metadata-form.ts index 374b9be1ad1..20d103927cd 100644 --- a/packages/spec/src/system/email-template.form.ts +++ b/packages/spec/src/system/email-template.metadata-form.ts @@ -1,6 +1,6 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. -import { defineForm } from '../ui/view.zod'; +import { defineMetadataForm } from '../ui/view.zod'; /** * EmailTemplate — canonical FormView layout. @@ -10,7 +10,7 @@ import { defineForm } from '../ui/view.zod'; * get syntax highlighting for the HTML body; the plain-text body uses * a textarea since it is rarely styled. */ -export const emailTemplateForm = defineForm({ +export const emailTemplateForm = defineMetadataForm({ schemaId: 'email_template', type: 'simple', sections: [ diff --git a/packages/spec/src/system/i18n-resolver.ts b/packages/spec/src/system/i18n-resolver.ts index 1d2f0c95845..ab9c0c75753 100644 --- a/packages/spec/src/system/i18n-resolver.ts +++ b/packages/spec/src/system/i18n-resolver.ts @@ -6322,7 +6322,7 @@ export function resolveMetadataFormLabels>( // measurement is why. This helper takes ANY form-shaped object (`T extends // Record`), and it is exported: its one in-repo caller // (`rest-server.ts` translating `getMetaTypes()` entries) now feeds it - // post-parse forms from `METADATA_FORM_REGISTRY`, all of them `defineForm` + // post-parse forms from `METADATA_FORM_REGISTRY`, all of them `defineMetadataForm` // outputs, so for THAT caller the branch is unreachable — but a stored // `sys_metadata` body still carries the authored key (`saveMetaItem` keeps // the body verbatim and the read replays the ADR-0087 conversion chain, not diff --git a/packages/spec/src/system/index.ts b/packages/spec/src/system/index.ts index fcd0abbdcf2..e6b0a80bf6d 100644 --- a/packages/spec/src/system/index.ts +++ b/packages/spec/src/system/index.ts @@ -75,7 +75,7 @@ export * from './doc.zod'; export * from './book.zod'; export * from './email-config.zod'; export * from './email-template.zod'; -export * from './email-template.form'; +export * from './email-template.metadata-form'; export * from './sms-config.zod'; export * from './push-config.zod'; export * from './push-device.zod'; diff --git a/packages/spec/src/system/metadata-form-declared-rows.pin.test.ts b/packages/spec/src/system/metadata-form-declared-rows.pin.test.ts index 4cd5b8ad431..483467a9070 100644 --- a/packages/spec/src/system/metadata-form-declared-rows.pin.test.ts +++ b/packages/spec/src/system/metadata-form-declared-rows.pin.test.ts @@ -152,7 +152,7 @@ describe('declared keys that now have a form row', () => { // gate, not a parse gate. The related-list derivation only ever reads it // on the child-side FK, so offering it elsewhere would advertise a knob // the runtime does not deliver. - // `defineForm` normalises a predicate into a `{ dialect, source }` + // `defineMetadataForm` normalises a predicate into a `{ dialect, source }` // envelope, so the assertion reads the envelope rather than the string it // was authored as. expect(row.visibleWhen).toEqual({ dialect: 'cel', source: "data.type in ['lookup','master_detail']" }); @@ -225,10 +225,10 @@ describe('object.imageField is offered as a plain text row beside nameField, wit * **A `type: 'code'` row's `language` must name the slot it actually edits** * (#20439). * - * `hook.form.ts`'s `condition` row declared `language: 'javascript'` over + * `hook.metadata-form.ts`'s `condition` row declared `language: 'javascript'` over * `HookSchema.condition`, which is `EvaluatedExpressionInputSchema` — a CEL - * predicate, not a script. Every sibling predicate row (`field.form.ts` / - * `object.form.ts`'s `visibleWhen` / `readonlyWhen` / `requiredWhen`, and the + * predicate, not a script. Every sibling predicate row (`field.metadata-form.ts` / + * `object.metadata-form.ts`'s `visibleWhen` / `readonlyWhen` / `requiredWhen`, and the * formula `expression` row) already declares `language: 'expression'`; a * consumer keyed on the declared language (objectui#10963's `CodeWidget` * fix) cannot otherwise tell this row apart from a real script row diff --git a/packages/spec/src/system/metadata-form-registry.ts b/packages/spec/src/system/metadata-form-registry.ts index 1d58e087ae6..07847a23448 100644 --- a/packages/spec/src/system/metadata-form-registry.ts +++ b/packages/spec/src/system/metadata-form-registry.ts @@ -5,8 +5,8 @@ * metadata configuration UI ("metadata admin" / Studio). * * Each entry maps a metadata-type machine name (singular, e.g. `'agent'`, - * `'flow'`) to the {@link FormView} produced by `defineForm({ schemaId })` - * in the corresponding `*.form.ts`. The registry is consumed by: + * `'flow'`) to the {@link FormView} produced by `defineMetadataForm({ schemaId })` + * in the corresponding `*.metadata-form.ts`. The registry is consumed by: * * - `getMetaTypes()` in `@objectstack/objectql` — surfaces `entry.form` so * the generic SchemaForm renderer can lay each metadata editor out as @@ -46,7 +46,7 @@ import { positionForm } from '../identity'; import { permissionForm } from '../security'; import { agentForm, toolForm, skillForm, aiContextForm } from '../ai'; import { flowForm } from '../automation'; -import { emailTemplateForm } from './email-template.form'; +import { emailTemplateForm } from './email-template.metadata-form'; /** * Frozen map of metadata type → canonical {@link FormView} layout. diff --git a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts index 2ace917522d..13ad40a11e6 100644 --- a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts +++ b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts @@ -3,7 +3,7 @@ /** * **Metadata form ↔ Zod reconciliation** (#3786). * - * Every entry in {@link METADATA_FORM_REGISTRY} is a hand-written `defineForm` + * Every entry in {@link METADATA_FORM_REGISTRY} is a hand-written `defineMetadataForm` * layout that names keys of a Zod schema it never imports. That is the * hand-copied-list shape #3786 was filed about: two descriptions of one key set, * a comment asking the next author to keep them in step, and nothing that fails @@ -198,7 +198,7 @@ const LEDGER: ReadonlyArray = [ key: 'sourceView', why: '@deprecated legacy named-view inheritance, honored at runtime as a fallback but deliberately not offered to new authors — a page defines columns/sort/filterBy directly (ADR-0047 revised)', }, - // #30267 — `view.form.ts` now spells out `userFilters`' children. This walk + // #30267 — `view.metadata-form.ts` now spells out `userFilters`' children. This walk // resolves the block through the view union to the page-shaped // `UserFiltersSchema`; the list arm the view form lays out takes // `ObjectUserFiltersSchema`, which omits these three page-only keys and @@ -228,20 +228,20 @@ const LEDGER: ReadonlyArray = [ kind: 'subset', type: 'object', path: 'fields', - why: "the object editor's inline column grid is a QUICK-ADD surface covering the common authoring keys; the full per-field editor is `field.form.ts` (registered as the `field` metadata type), which is where the long tail of FieldSchema is authored", + why: "the object editor's inline column grid is a QUICK-ADD surface covering the common authoring keys; the full per-field editor is `field.metadata-form.ts` (registered as the `field` metadata type), which is where the long tail of FieldSchema is authored", }, // ── Depth two (#14327): the lists nested inside the `fields` quick-add row ── { kind: 'subset', type: 'object', path: 'fields.options', - why: "one row of the `fields` quick-add grid (the subset entry above), so the same design applies one level down: an option is captured as label / value / color / description, and the long tail — `default`, the per-option `visibleWhen` CEL predicate — is authored in the full per-field editor (`field.form.ts`), whose `options` repeater is schema-derived and so offers every SelectOptionSchema key", + why: "one row of the `fields` quick-add grid (the subset entry above), so the same design applies one level down: an option is captured as label / value / color / description, and the long tail — `default`, the per-option `visibleWhen` CEL predicate — is authored in the full per-field editor (`field.metadata-form.ts`), whose `options` repeater is schema-derived and so offers every SelectOptionSchema key", }, { kind: 'subset', type: 'object', path: 'fields.summaryOperations', - why: "one row of the `fields` quick-add grid (the subset entry above): the roll-up is captured as object / field / function; `relationshipField` (auto-detected unless the child references this object twice) and the `filter` FilterCondition are authored in the full per-field editor (`field.form.ts`), whose own `summaryOperations` composite offers both with their dedicated widgets (`ref:object`, `filter-condition`)", + why: "one row of the `fields` quick-add grid (the subset entry above): the roll-up is captured as object / field / function; `relationshipField` (auto-detected unless the child references this object twice) and the `filter` FilterCondition are authored in the full per-field editor (`field.metadata-form.ts`), whose own `summaryOperations` composite offers both with their dedicated widgets (`ref:object`, `filter-condition`)", }, // ── Depth two (#14327): the lifecycle policy blocks ── { @@ -596,7 +596,7 @@ const LEDGER: ReadonlyArray = [ type: 'object', path: ROOT_PATH, key: 'actions', - why: "authored through its own editor — the `action` type (ruling record 5861442317): each element is that type's own node, the schema `getMetadataTypeSchema('action')` answers and `action.form.ts` edits, and the key's own describe says the list is `auto-populated from top-level actions via objectName`, so an inline editor here would be a second, poorer copy of the action form", + why: "authored through its own editor — the `action` type (ruling record 5861442317): each element is that type's own node, the schema `getMetadataTypeSchema('action')` answers and `action.metadata-form.ts` edits, and the key's own describe says the list is `auto-populated from top-level actions via objectName`, so an inline editor here would be a second, poorer copy of the action form", }, { kind: 'omit', diff --git a/packages/spec/src/ui/action.form.ts b/packages/spec/src/ui/action.metadata-form.ts similarity index 98% rename from packages/spec/src/ui/action.form.ts rename to packages/spec/src/ui/action.metadata-form.ts index 04b4afc2048..330d716e15e 100644 --- a/packages/spec/src/ui/action.form.ts +++ b/packages/spec/src/ui/action.metadata-form.ts @@ -1,13 +1,13 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. -import { defineForm } from './view.zod'; +import { defineMetadataForm } from './view.zod'; /** * Action Metadata Form * * Form layout for creating/editing action metadata definitions. */ -export const actionForm = defineForm({ +export const actionForm = defineMetadataForm({ schemaId: 'action', type: 'simple', sections: [ @@ -47,7 +47,7 @@ export const actionForm = defineForm({ type: 'composite', visibleWhen: "data.type == 'script'", helpText: 'Either an L1 expression or an L2 sandboxed JS body', - // Mirrors hook.form.ts: `body` is a discriminated union + // Mirrors hook.metadata-form.ts: `body` is a discriminated union // (HookBodySchema) on `language`, not a bare string. A flat // `widget: 'code'` fed the whole object to the editor and rendered // "[object Object]". Render the union as language + source (+ the @@ -145,7 +145,7 @@ export const actionForm = defineForm({ ] }, // #19332 G1b (ruling 5861442317, G1) — `patch` is a string-keyed record of // values, so it takes `json`, the hint every structured row carries - // (`object.form.ts` `validations`); the renderer opens the raw JSON + // (`object.metadata-form.ts` `validations`); the renderer opens the raw JSON // editor for a record node. Its gate is `undoable`'s: the parse refuses // `patch` on an action without `operation: 'update'`, so the control is // shown exactly where the value is accepted. @@ -157,7 +157,7 @@ export const actionForm = defineForm({ // served schema and the contract rides the help text. { field: 'execution', helpText: "The bulk dispatch contract this action's body is written for: 'perRecord' sends one dispatch per selected row carrying that row's recordId; 'aggregate' sends ONE dispatch for the whole selection, with every id in params._selectedIds. Omitted, the action is dispatched per record." }, // #19332 G1b — `description` is an I18nLabel (a string, or an inline - // locale map), the node `page.form.ts` `description` carries, so it copies + // locale map), the node `page.metadata-form.ts` `description` carries, so it copies // that row: `widget: 'textarea'`. A passthrough hint, so a stored locale // map resolves to its own branch and opens the raw JSON editor rather // than being read as text. @@ -231,7 +231,7 @@ export const actionForm = defineForm({ // every member IS a row of the reach table the parse step lowers from. { field: 'requiresMembershipReach', helpText: 'The organization endpoint this action calls, so it is offered only to members whose grade reaches that endpoint. It is lowered into the `visible` predicate at parse time and stripped from the output, so no downstream consumer ever sees the key.' }, // #19332 G1b — the RBAC gate, beside the feature gate. `string[]`, so the - // `app.form.ts` `requiredPermissions` face (`string-tags`). + // `app.metadata-form.ts` `requiredPermissions` face (`string-tags`). { field: 'requiredPermissions', widget: 'string-tags', helpText: 'Capabilities (permission-set systemPermissions) a caller must hold — every one listed — to invoke this action (ADR-0066 D4). The platform action door refuses anyone else with 403 on every call it dispatches, the MCP/AI path included, and the button is hidden from them. A type api action\'s endpoint stays directly reachable, so it must still check these capabilities itself; for an api action with an off-origin target the platform checks nothing server-side.' }, // `shortcut` input removed with the key (#3896 close-out) — a form // input for an unenforced capability is the UI half of false compliance. diff --git a/packages/spec/src/ui/add-record-config-retirement.test.ts b/packages/spec/src/ui/add-record-config-retirement.test.ts index 6de51f347af..298fdd9d151 100644 --- a/packages/spec/src/ui/add-record-config-retirement.test.ts +++ b/packages/spec/src/ui/add-record-config-retirement.test.ts @@ -50,9 +50,9 @@ import { applyConversionsToStoredItem } from '../conversions/stored'; import type { ConversionNotice } from '../conversions/types'; import { MIGRATIONS_BY_MAJOR, RETIRED_KEYS_BY_MAJOR } from '../migrations/registry'; import { ComponentPropsMap } from './component.zod'; -import { pageForm } from './page.form'; +import { pageForm } from './page.metadata-form'; import { InterfacePageConfigSchema } from './page.zod'; -import { viewForm } from './view.form'; +import { viewForm } from './view.metadata-form'; import { AddRecordConfigSchema, ListViewSchema, ObjectListViewSchema } from './view.zod'; const STRIP_ID = 'add-record-mode-form-view-removed'; diff --git a/packages/spec/src/ui/app.form.ts b/packages/spec/src/ui/app.metadata-form.ts similarity index 98% rename from packages/spec/src/ui/app.form.ts rename to packages/spec/src/ui/app.metadata-form.ts index 5d0af6fec72..a816d486b2b 100644 --- a/packages/spec/src/ui/app.form.ts +++ b/packages/spec/src/ui/app.metadata-form.ts @@ -18,9 +18,9 @@ * `metadata-form-zod-reconciliation.test.ts` instead of reaching an author. */ -import { defineForm } from './view.zod'; +import { defineMetadataForm } from './view.zod'; -export const appForm = defineForm({ +export const appForm = defineMetadataForm({ schemaId: 'app', type: 'simple', sections: [ diff --git a/packages/spec/src/ui/dashboard-form-business-wording-36816.test.ts b/packages/spec/src/ui/dashboard-form-business-wording-36816.test.ts index 42de09b7975..11c63a04d70 100644 --- a/packages/spec/src/ui/dashboard-form-business-wording-36816.test.ts +++ b/packages/spec/src/ui/dashboard-form-business-wording-36816.test.ts @@ -18,7 +18,7 @@ import { describe, it, expect } from 'vitest'; -import { dashboardForm } from './dashboard.form'; +import { dashboardForm } from './dashboard.metadata-form'; type FormField = { field?: string; helpText?: string; fields?: FormField[] }; diff --git a/packages/spec/src/ui/dashboard.form.ts b/packages/spec/src/ui/dashboard.metadata-form.ts similarity index 98% rename from packages/spec/src/ui/dashboard.form.ts rename to packages/spec/src/ui/dashboard.metadata-form.ts index ba7afb596b7..4675e5fc80f 100644 --- a/packages/spec/src/ui/dashboard.form.ts +++ b/packages/spec/src/ui/dashboard.metadata-form.ts @@ -1,9 +1,9 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. -import { defineForm } from './view.zod'; +import { defineMetadataForm } from './view.zod'; import { defaultPeriodOptions } from './default-period-options'; -export const dashboardForm = defineForm({ +export const dashboardForm = defineMetadataForm({ schemaId: 'dashboard', type: 'simple', sections: [ diff --git a/packages/spec/src/ui/dashboard.test.ts b/packages/spec/src/ui/dashboard.test.ts index 1a2868e127b..47a1f547afb 100644 --- a/packages/spec/src/ui/dashboard.test.ts +++ b/packages/spec/src/ui/dashboard.test.ts @@ -24,7 +24,7 @@ import { import * as ui from './index'; import { readFileSync } from 'node:fs'; import { ChartTypeSchema } from './chart.zod'; -import { dashboardForm } from './dashboard.form'; +import { dashboardForm } from './dashboard.metadata-form'; /** * ADR-0021 single-form: every dashboard widget binds a `dataset` and selects diff --git a/packages/spec/src/ui/dashboard.zod.ts b/packages/spec/src/ui/dashboard.zod.ts index dd608b3e790..f78aaad33ad 100644 --- a/packages/spec/src/ui/dashboard.zod.ts +++ b/packages/spec/src/ui/dashboard.zod.ts @@ -149,7 +149,7 @@ function refuseRecordlessAskAi( * bundle names the same column through * `metadataForms.dashboard.fields['header.actions.'].label`, which * `resolveMetadataFormSchemaTitles` (`system/i18n-resolver.ts`) overlays onto - * the derived schema. `dashboard.form.ts` declares the same four children with + * the derived schema. `dashboard.metadata-form.ts` declares the same four children with * the same labels so the extractor emits those keys; `dashboard.test.ts` pins * the two spellings equal. */ diff --git a/packages/spec/src/ui/dataset.form.ts b/packages/spec/src/ui/dataset.metadata-form.ts similarity index 98% rename from packages/spec/src/ui/dataset.form.ts rename to packages/spec/src/ui/dataset.metadata-form.ts index a07893eaf62..86192ed098e 100644 --- a/packages/spec/src/ui/dataset.form.ts +++ b/packages/spec/src/ui/dataset.metadata-form.ts @@ -1,6 +1,6 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -import { defineForm } from './view.zod'; +import { defineMetadataForm } from './view.zod'; /** * Form layout for the Dataset metadata editor (ADR-0021 analytics semantic layer). @@ -18,7 +18,7 @@ import { defineForm } from './view.zod'; * base object) so a business user can author a dataset without memorising * machine names. Mirrors {@link reportForm} — the sibling analytics editor. */ -export const datasetForm = defineForm({ +export const datasetForm = defineMetadataForm({ schemaId: 'dataset', type: 'simple', sections: [ diff --git a/packages/spec/src/ui/form-option-enum-derive.test.ts b/packages/spec/src/ui/form-option-enum-derive.test.ts index 34d947210d8..7330d68d8a5 100644 --- a/packages/spec/src/ui/form-option-enum-derive.test.ts +++ b/packages/spec/src/ui/form-option-enum-derive.test.ts @@ -9,7 +9,7 @@ * which `FormSelectOptionSchema` reuses by reference. So an enum member that * carries a hyphen or a capital — `object.managedBy`'s `system-data`, * `action.openIn`'s `new-tab`, `action.execution`'s `perRecord` — cannot be - * written as an inline option at all, and `defineForm` throws at module load + * written as an inline option at all, and `defineMetadataForm` throws at module load * when an author tries. The bound stays. The rule, as ruling 乙 records it: an * enum-typed metadata-form row MAY carry an inline `options` list (human * labels, a deliberate subset); a row whose members cannot be spelled as @@ -18,7 +18,7 @@ * * What this file pins is where an author meets that rule: * - * 1. **The wall says what to do.** `defineForm`'s refusal of an unspellable + * 1. **The wall says what to do.** `defineMetadataForm`'s refusal of an unspellable * value still carries the grammar message, and names the derive path — * scoped to a row whose members cannot be spelled — as its remedy. The * firing control reads TODAY's message live — the object face raises the @@ -45,7 +45,7 @@ import { z } from 'zod'; import { SelectOptionSchema } from '../data/field.zod'; import { getMetadataTypeSchema } from '../kernel/metadata-type-schemas'; -import { defineForm, FormFieldSchema, FormSelectOptionSchema } from './view.zod'; +import { defineMetadataForm, FormFieldSchema, FormSelectOptionSchema } from './view.zod'; type Issue = { code: string; path: PropertyKey[]; message: string; errors?: Issue[][] }; @@ -92,7 +92,7 @@ function statesBlanketOmitRule(message: string): boolean { /** Build a one-row metadata form whose row lists a single inline option. */ function formWithOption(value: string, extra: Record = {}) { - return () => defineForm({ + return () => defineMetadataForm({ schemaId: 'action', type: 'simple', sections: [{ label: 'Behavior', fields: [{ field: 'openIn', options: [{ label: 'Option', value, ...extra }] }] }], @@ -101,14 +101,14 @@ function formWithOption(value: string, extra: Record = {}) { /** Build a one-row metadata form over `schemaId` with the given row. */ function formWithRow(schemaId: string, row: Record) { - return () => defineForm({ + return () => defineMetadataForm({ schemaId, type: 'simple', sections: [{ label: 'Section', fields: [row as never] }], }); } -/** This file's own name — the module every `defineForm(...)` call below is made from. */ +/** This file's own name — the module every `defineMetadataForm(...)` call below is made from. */ const THIS_MODULE = 'form-option-enum-derive.test.ts'; /** @@ -120,7 +120,7 @@ const THIS_MODULE = 'form-option-enum-derive.test.ts'; * `toBeInstanceOf(z.ZodError)` passes on it all the same. A string `stack` is * not enough either — zod builds `parsed.error` and a bare * `new z.ZodRealError(...)` with no frame at all — so the stack must also name - * the module that called `defineForm`. + * the module that called `defineMetadataForm`. */ function refusal(build: () => unknown): z.ZodError { let thrown: unknown; @@ -129,14 +129,14 @@ function refusal(build: () => unknown): z.ZodError { } catch (e) { thrown = e; } - expect(thrown, 'expected defineForm to REFUSE at module load').toBeInstanceOf(z.ZodError); + expect(thrown, 'expected defineMetadataForm to REFUSE at module load').toBeInstanceOf(z.ZodError); expect(thrown).toBeInstanceOf(Error); expect(typeof (thrown as Error).stack).toBe('string'); - expect((thrown as Error).stack, 'the stack names no frame in the module that called defineForm').toContain(THIS_MODULE); + expect((thrown as Error).stack, 'the stack names no frame in the module that called defineMetadataForm').toContain(THIS_MODULE); return thrown as z.ZodError; } -/** The issue `defineForm` raised at the row's option value, or a loud failure. */ +/** The issue `defineMetadataForm` raised at the row's option value, or a loud failure. */ function optionValueIssue(build: () => unknown, index = 0) { const thrown = refusal(build); const hit = leaves(thrown.issues as unknown as Issue[]) @@ -179,7 +179,7 @@ const UNSPELLABLE = [ { value: 'x', code: 'too_small', why: 'a single character' }, ] as const; -describe('defineForm: the refusal of an unspellable option value names the derive path', () => { +describe('defineMetadataForm: the refusal of an unspellable option value names the derive path', () => { it.each(UNSPELLABLE)('`$value` ($why) is refused with the remedy', ({ value, code }) => { const issue = optionValueIssue(formWithOption(value)); expect(issue.code).toBe(code); @@ -201,7 +201,7 @@ describe('defineForm: the refusal of an unspellable option value names the deriv it('firing control — both predicates are RED on today\'s message', () => { // The object face raises the grammar issue through the very property schema // the form face shares, and carries no remedy: this is the message - // `defineForm` threw before the ruling was executed. + // `defineMetadataForm` threw before the ruling was executed. for (const { value } of UNSPELLABLE) { const today = objectFaceMessage(value); expect(namesDerivePath(today), today).toBe(false); @@ -213,7 +213,7 @@ describe('defineForm: the refusal of an unspellable option value names the deriv // The two spellings this PR first shipped, held as fixtures ONLY to prove // `statesBlanketOmitRule` can fire — a predicate that is never true would // make every "states no blanket rule" assertion in this file vacuous. - expect(statesBlanketOmitRule('On a metadata form (schema-bound, built by `defineForm`), a row whose key is a spec enum omits `options`: …')).toBe(true); + expect(statesBlanketOmitRule('On a metadata form (schema-bound, built by `defineMetadataForm`), a row whose key is a spec enum omits `options`: …')).toBe(true); expect(statesBlanketOmitRule('When this row edits a spec enum, omit `options`: …')).toBe(true); }); @@ -231,7 +231,7 @@ describe('defineForm: the refusal of an unspellable option value names the deriv }); it('a nested row (composite `fields`) gets the same remedy', () => { - const thrown = refusal(() => defineForm({ + const thrown = refusal(() => defineMetadataForm({ schemaId: 'action', type: 'simple', sections: [{ label: 'Behavior', fields: [{ field: 'outer', fields: [{ field: 'inner', options: [{ label: 'New tab', value: 'new-tab' }] }] }] }], @@ -360,7 +360,7 @@ describe('the verdict did not move — the bound stays', () => { }); it('a spellable inline option still builds', () => { - const form = defineForm({ + const form = defineMetadataForm({ schemaId: 'action', type: 'simple', sections: [{ label: 'Behavior', fields: [{ field: 'mode', options: [{ label: 'Custom', value: 'custom' }] }] }], @@ -377,7 +377,7 @@ describe('the remedy is scoped to a grammar refusal of an inline option value', }); it('an unrelated refusal on the same form is answered without it', () => { - const thrown = refusal(() => defineForm({ schemaId: 'action', type: 'no_such_layout' as never, sections: [] })); + const thrown = refusal(() => defineMetadataForm({ schemaId: 'action', type: 'no_such_layout' as never, sections: [] })); for (const issue of leaves(thrown.issues as unknown as Issue[])) { expect(namesDerivePath(issue.message), issue.message).toBe(false); } @@ -391,7 +391,7 @@ describe('the form field\'s `options` describe states ruling 乙\'s rule', () => const text = served.properties?.options?.description ?? ''; it('permits an inline list on an enum-typed metadata-form row, for human labels or a deliberate subset', () => { - expect(text).toContain('`defineForm`'); + expect(text).toContain('`defineMetadataForm`'); expect(text).toMatch(/enum-typed row may list its members/); expect(text).toContain('human labels'); expect(text).toContain('deliberate subset'); diff --git a/packages/spec/src/ui/index.ts b/packages/spec/src/ui/index.ts index 6a57f625c41..54ac93501b5 100644 --- a/packages/spec/src/ui/index.ts +++ b/packages/spec/src/ui/index.ts @@ -41,13 +41,13 @@ export * from './assembled-views.zod'; export * from './dashboard.zod'; export * from './report.zod'; export * from './dataset.zod'; -export { reportForm } from './report.form'; -export { viewForm } from './view.form'; -export { appForm } from './app.form'; -export { dashboardForm } from './dashboard.form'; -export { datasetForm } from './dataset.form'; -export { actionForm } from './action.form'; -export { pageForm } from './page.form'; +export { reportForm } from './report.metadata-form'; +export { viewForm } from './view.metadata-form'; +export { appForm } from './app.metadata-form'; +export { dashboardForm } from './dashboard.metadata-form'; +export { datasetForm } from './dataset.metadata-form'; +export { actionForm } from './action.metadata-form'; +export { pageForm } from './page.metadata-form'; export * from './action.zod'; // [#24814] The CLOSED scope of an action's copy — `confirmText`, // `successMessage`, `errorMessage` — as the console's runner binds it: the diff --git a/packages/spec/src/ui/navigation-mode-retirement.test.ts b/packages/spec/src/ui/navigation-mode-retirement.test.ts index 7956d5a2db6..209e1483629 100644 --- a/packages/spec/src/ui/navigation-mode-retirement.test.ts +++ b/packages/spec/src/ui/navigation-mode-retirement.test.ts @@ -44,7 +44,7 @@ import type { ConversionNotice } from '../conversions/types'; import { MIGRATIONS_BY_MAJOR } from '../migrations/registry'; import { defineStack } from '../stack.zod'; import { ComponentPropsMap } from './component.zod'; -import { pageForm } from './page.form'; +import { pageForm } from './page.metadata-form'; import { InterfacePageConfigSchema } from './page.zod'; import { ListViewSchema, NavigationConfigSchema, NavigationModeSchema, ObjectListViewSchema } from './view.zod'; diff --git a/packages/spec/src/ui/page.form.ts b/packages/spec/src/ui/page.metadata-form.ts similarity index 99% rename from packages/spec/src/ui/page.form.ts rename to packages/spec/src/ui/page.metadata-form.ts index f87b0789aa5..9992c31baec 100644 --- a/packages/spec/src/ui/page.form.ts +++ b/packages/spec/src/ui/page.metadata-form.ts @@ -1,13 +1,13 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. -import { defineForm } from './view.zod'; +import { defineMetadataForm } from './view.zod'; /** * Page Metadata Form * * Form layout for creating/editing page metadata definitions. */ -export const pageForm = defineForm({ +export const pageForm = defineMetadataForm({ schemaId: 'page', type: 'simple', sections: [ diff --git a/packages/spec/src/ui/report-form-composite-children.test.ts b/packages/spec/src/ui/report-form-composite-children.test.ts index 137b5dc53ef..dc42d50753d 100644 --- a/packages/spec/src/ui/report-form-composite-children.test.ts +++ b/packages/spec/src/ui/report-form-composite-children.test.ts @@ -24,7 +24,7 @@ import { describe, it, expect } from 'vitest'; import { z } from 'zod'; -import { reportForm } from './report.form'; +import { reportForm } from './report.metadata-form'; import { ReportSchema } from './report.zod'; type Node = Record; diff --git a/packages/spec/src/ui/report-form-default-range-labels-36835.test.ts b/packages/spec/src/ui/report-form-default-range-labels-36835.test.ts index aafd2902e6e..15d4224404f 100644 --- a/packages/spec/src/ui/report-form-default-range-labels-36835.test.ts +++ b/packages/spec/src/ui/report-form-default-range-labels-36835.test.ts @@ -17,8 +17,8 @@ import { describe, it, expect } from 'vitest'; -import { reportForm } from './report.form'; -import { dashboardForm } from './dashboard.form'; +import { reportForm } from './report.metadata-form'; +import { dashboardForm } from './dashboard.metadata-form'; import { DATE_RANGE_DEFAULT_RANGES } from './dashboard.zod'; type Option = { label?: unknown; value?: unknown }; diff --git a/packages/spec/src/ui/report-joined-block-dataset.test.ts b/packages/spec/src/ui/report-joined-block-dataset.test.ts index b672138d74c..c569871573e 100644 --- a/packages/spec/src/ui/report-joined-block-dataset.test.ts +++ b/packages/spec/src/ui/report-joined-block-dataset.test.ts @@ -27,7 +27,7 @@ import { describe, expect, it } from 'vitest'; import { getMetadataTypeSchema } from '../kernel/metadata-type-schemas'; import { MIGRATIONS_BY_MAJOR, RETIRED_KEYS_BY_MAJOR } from '../migrations/registry'; import { ObjectStackDefinitionSchema, defineStack } from '../stack.zod'; -import { reportForm } from './report.form'; +import { reportForm } from './report.metadata-form'; import { JoinedReportBlockSchema, ReportSchema, defineReport } from './report.zod'; const ENTRY_ID = 'ui-report-joined-block-dataset-required'; diff --git a/packages/spec/src/ui/report.form.ts b/packages/spec/src/ui/report.metadata-form.ts similarity index 99% rename from packages/spec/src/ui/report.form.ts rename to packages/spec/src/ui/report.metadata-form.ts index 6171fae1267..36f48287579 100644 --- a/packages/spec/src/ui/report.form.ts +++ b/packages/spec/src/ui/report.metadata-form.ts @@ -13,10 +13,10 @@ * form no longer declares those fields. */ -import { defineForm } from './view.zod'; +import { defineMetadataForm } from './view.zod'; import { defaultPeriodOptions } from './default-period-options'; -export const reportForm = defineForm({ +export const reportForm = defineMetadataForm({ schemaId: 'report', type: 'simple', sections: [ diff --git a/packages/spec/src/ui/view-form-composite-children.test.ts b/packages/spec/src/ui/view-form-composite-children.test.ts index 6e19437f4ce..3a53e992c97 100644 --- a/packages/spec/src/ui/view-form-composite-children.test.ts +++ b/packages/spec/src/ui/view-form-composite-children.test.ts @@ -35,7 +35,7 @@ import { describe, it, expect } from 'vitest'; import { z } from 'zod'; -import { viewForm } from './view.form'; +import { viewForm } from './view.metadata-form'; import { ViewSchema } from './view.zod'; type Node = Record; diff --git a/packages/spec/src/ui/view-form-pagination.test.ts b/packages/spec/src/ui/view-form-pagination.test.ts index 50021821f15..b54f7f667c0 100644 --- a/packages/spec/src/ui/view-form-pagination.test.ts +++ b/packages/spec/src/ui/view-form-pagination.test.ts @@ -39,7 +39,7 @@ import { describe, it, expect } from 'vitest'; -import { viewForm } from './view.form'; +import { viewForm } from './view.metadata-form'; import { ListViewSchema } from './view.zod'; type Predicate = string | { dialect?: string; source?: string } | undefined; diff --git a/packages/spec/src/ui/view-list-filterable-fields-retirement.test.ts b/packages/spec/src/ui/view-list-filterable-fields-retirement.test.ts index b95f112362c..17d285717b4 100644 --- a/packages/spec/src/ui/view-list-filterable-fields-retirement.test.ts +++ b/packages/spec/src/ui/view-list-filterable-fields-retirement.test.ts @@ -58,7 +58,7 @@ import { ObjectSchema } from '../data/object.zod'; import { getMetadataTypeSchema } from '../kernel/metadata-type-schemas'; import { MIGRATIONS_BY_MAJOR, RETIRED_KEYS_BY_MAJOR } from '../migrations/registry'; import { ComponentPropsMap } from './component.zod'; -import { viewForm } from './view.form'; +import { viewForm } from './view.metadata-form'; import { ListViewSchema, ObjectListViewSchema, diff --git a/packages/spec/src/ui/view-list-tabs-retirement.test.ts b/packages/spec/src/ui/view-list-tabs-retirement.test.ts index dfc0b4a8694..47eb8929ad4 100644 --- a/packages/spec/src/ui/view-list-tabs-retirement.test.ts +++ b/packages/spec/src/ui/view-list-tabs-retirement.test.ts @@ -49,7 +49,7 @@ import { applyConversionsToStoredItem } from '../conversions/stored'; import { ObjectSchema } from '../data/object.zod'; import { getMetadataTypeSchema } from '../kernel/metadata-type-schemas'; import { MIGRATIONS_BY_MAJOR, RETIRED_KEYS_BY_MAJOR } from '../migrations/registry'; -import { viewForm } from './view.form'; +import { viewForm } from './view.metadata-form'; import { ListViewSchema, ObjectListViewSchema, diff --git a/packages/spec/src/ui/view.form.ts b/packages/spec/src/ui/view.metadata-form.ts similarity index 99% rename from packages/spec/src/ui/view.form.ts rename to packages/spec/src/ui/view.metadata-form.ts index c5b13daf733..da9dabb5953 100644 --- a/packages/spec/src/ui/view.form.ts +++ b/packages/spec/src/ui/view.metadata-form.ts @@ -22,9 +22,9 @@ * cannot go missing from the panel. */ -import { defineForm } from './view.zod'; +import { defineMetadataForm } from './view.zod'; -export const viewForm = defineForm({ +export const viewForm = defineMetadataForm({ schemaId: 'view', type: 'simple', sections: [ diff --git a/packages/spec/src/ui/view.test.ts b/packages/spec/src/ui/view.test.ts index 2691c4101ff..035299981a6 100644 --- a/packages/spec/src/ui/view.test.ts +++ b/packages/spec/src/ui/view.test.ts @@ -41,7 +41,7 @@ import { type ViewData, type HttpRequest, defineView, - defineForm, + defineMetadataForm, ViewItemSchema, ViewMetadataSchema, VIEW_METADATA_MEMBERS, @@ -783,7 +783,7 @@ describe('FormViewSchema', () => { }); // form `data` SURVIVED the #3896 sweep: the removal attempt broke the build - // — defineForm writes data.provider='schema' onto every metadata form — so + // — defineMetadataForm writes data.provider='schema' onto every metadata form — so // the ledger verdict was corrected instead. These pin the surviving shapes. it('accepts form view with object provider', () => { expect(() => FormViewSchema.parse({ @@ -792,7 +792,7 @@ describe('FormViewSchema', () => { sections: [{ fields: ['name'] }], })).not.toThrow(); }); - it('accepts the schema provider defineForm writes', () => { + it('accepts the schema provider defineMetadataForm writes', () => { expect(() => FormViewSchema.parse({ type: 'simple', data: { provider: 'schema', schemaId: 'flow' }, @@ -1119,8 +1119,8 @@ describe('FormViewSchema — the `groups` legacy alias folds onto `sections`', ( expect(view.form?.sections?.map((s) => s.label)).toEqual(['Account']); }); - it('defineForm (the metadata-admin form door)', () => { - const form = defineForm({ schemaId: 'report', type: 'simple', groups: [S('Account')] }); + it('defineMetadataForm (the metadata-admin form door)', () => { + const form = defineMetadataForm({ schemaId: 'report', type: 'simple', groups: [S('Account')] }); expect(has(form, 'groups')).toBe(false); expect(form.sections?.map((s) => s.label)).toEqual(['Account']); }); diff --git a/packages/spec/src/ui/view.zod.ts b/packages/spec/src/ui/view.zod.ts index 50d903c819a..d3af2c19eed 100644 --- a/packages/spec/src/ui/view.zod.ts +++ b/packages/spec/src/ui/view.zod.ts @@ -2021,7 +2021,7 @@ export const ViewTabSchema = lazySchema(() => strictObject({ * Rendering details (widget, options) default to inference from the field * definition on the source object — authors only override when needed. * - * Each property carries a `.meta({ title })` because `view.form.ts` enumerates + * Each property carries a `.meta({ title })` because `view.metadata-form.ts` enumerates * `userFilters.fields` as a repeater: the title is the English column head * Studio reads, and the form's declared row `label` repeats it so the i18n * extractor emits a catalog key per column (#30267). @@ -3979,7 +3979,7 @@ export const MetadataListColumnSchema = lazySchema(() => ListColumnSchema /** * The list layout of a metadata type in Studio: {@link ListViewSchema} narrowed * to its data binding and its columns, the list counterpart of a - * {@link defineForm} layout. Build one with {@link defineList}. + * {@link defineMetadataForm} layout. Build one with {@link defineList}. */ export const MetadataListViewSchema = lazySchema(() => ListViewShapeSchema .pick({ data: true, columns: true }) @@ -4020,7 +4020,7 @@ export const MetadataListViewSchema = lazySchema(() => ListViewShapeSchema * `shared/strict-object.ts` documents. The census that gates this narrowing * (recorded in commit c459da6bc, part of the ruling) measured ZERO occurrences of * `default`/`isDefault`/`selected` inside form-view options across this tree, - * the example apps and the published `*.form.ts` corpus, with the instrument's + * the example apps and the published `*.metadata-form.ts` corpus, with the instrument's * positive control hitting the 40+ enforced object-field usages. * * The protocol-18 conversion `form-view-option-default-removed` strips the key @@ -4233,7 +4233,7 @@ const FormFieldBaseSchema = lazySchema(() => { * shares by reference with the object-field face, so an enum member carrying * a hyphen or a capital (`system-data`, `new-tab`, `perRecord`) cannot be * written as one at all. On a metadata form — schema-bound, built by - * {@link defineForm} — an enum-typed row MAY carry an inline `options` list, + * {@link defineMetadataForm} — an enum-typed row MAY carry an inline `options` list, * for human labels or a deliberate subset (the #19331 `object.ownership` / * `sharingModel` rows and the master_detail `deleteBehavior` rows are the * reference shapes). A row whose members cannot be spelled as option values @@ -4241,10 +4241,10 @@ const FormFieldBaseSchema = lazySchema(() => { * Schema, and their meanings go in `helpText` (the `object.managedBy` / * `action.openIn` / `action.execution` rows are the reference shape). The * describe below states the rule where an author meets it, and - * `defineForm`'s module-load refusal of an unspellable value names the + * `defineMetadataForm`'s module-load refusal of an unspellable value names the * derive path as its remedy. */ - options: z.array(FormSelectOptionSchema).optional().describe('Options for select/multiselect/radio/checkboxes fields (per-option `default` is not accepted here — declare the pre-selected choice on the object definition). On a metadata form (schema-bound, built by `defineForm`), an enum-typed row may list its members here, to give them human labels or to offer a deliberate subset. An option `value` is a lowercase system identifier, so a row whose members cannot be spelled as option values (a hyphen, a capital) omits `options`: the control derives the members from the served JSON Schema, and their meanings go in `helpText`.'), + options: z.array(FormSelectOptionSchema).optional().describe('Options for select/multiselect/radio/checkboxes fields (per-option `default` is not accepted here — declare the pre-selected choice on the object definition). On a metadata form (schema-bound, built by `defineMetadataForm`), an enum-typed row may list its members here, to give them human labels or to offer a deliberate subset. An option `value` is a lowercase system identifier, so a row whose members cannot be spelled as option values (a hyphen, a capital) omits `options`: the control derives the members from the served JSON Schema, and their meanings go in `helpText`.'), /** Reference object for lookup/master_detail fields */ reference: z.string().optional().describe('Target object name for lookup/master_detail fields'), @@ -4365,7 +4365,7 @@ const FormFieldBaseSchema = lazySchema(() => { * (ADR-0089, canonical `*When` name). Binding root depends on the surface: * runtime record forms bind `record` (plus `previous`, the saved record, and * `parent` for master-detail line items); metadata-editing forms - * (`*.form.ts`) bind the row under edit as `data`. + * (`*.metadata-form.ts`) bind the row under edit as `data`. * * ## `current_user` DOES bind here — client-side, and only under a host that * publishes a scope (objectui#6010) @@ -4601,7 +4601,7 @@ export const FormSectionSchema = lazySchema(() => strictObject({ * translation linter (`collectViewRecord`) accepts it and `translateView` * serves it. A section without a `name` has no key there and keeps its * authored text in every locale. - * - **A metadata-editing form** (`defineForm({ schemaId })`): + * - **A metadata-editing form** (`defineMetadataForm({ schemaId })`): * `metadataForms..sections.`, read by * `resolveMetadataFormLabels`. A section without a `name` is looked up * there under a slug of its `label`. @@ -5528,7 +5528,7 @@ export const FormViewSchema = lazySchema(() => strictObject({ /** * Data Source Configuration. NOT removed in the #3896 sweep despite the * ledger's dead verdict — the removal attempt broke the build and thereby - * re-verified the entry: `defineForm` (below) writes + * re-verified the entry: `defineMetadataForm` (below) writes * `data: { provider: 'schema', schemaId }` onto EVERY metadata form, and * `metadata-protocol` serves it to the metadata-admin pipeline. The * record-form provider values (`object`/`value`) may still be unread — that @@ -8225,11 +8225,16 @@ export function expandViewContainer(object: string, container: any): ExpandedVie * Type-safe factory for a standalone {@link FormView} bound to a JSON Schema * rather than to an ObjectQL object. * - * Use this for forms that edit **metadata** (e.g. `report.form.ts`, - * `dashboard.form.ts`), **action inputs**, or **flow screens** — anywhere the + * Use this for forms that edit **metadata** (e.g. `report.metadata-form.ts`, + * `dashboard.metadata-form.ts`), **action inputs**, or **flow screens** — anywhere the * data shape is described by a Zod-derived JSON Schema instead of an Object * field set. * + * Named `defineForm` until ADR-0159 (question 1, ruled A): that name belongs to + * the `form` metadata type's factory, so this Studio helper is + * `defineMetadataForm` and its modules are `*.metadata-form.ts`, after the + * `metadataForms` translation family they feed. + * * The returned FormView is validated at definition time; the runtime form * renderer (`@object-ui/plugin-form`) inspects `data.provider === 'schema'` * and pulls field metadata from the resolved JSON Schema instead of from @@ -8244,7 +8249,7 @@ export function expandViewContainer(object: string, container: any): ExpandedVie * * @example * ```ts - * export const reportForm = defineForm({ + * export const reportForm = defineMetadataForm({ * schemaId: 'report', * type: 'tabbed', * sections: [ @@ -8263,7 +8268,7 @@ export function expandViewContainer(object: string, container: any): ExpandedVie * }); * ``` */ -export function defineForm( +export function defineMetadataForm( config: Omit, 'data'> & { schemaId: string }, ): FormViewParsed { const { schemaId, ...rest } = config; @@ -8273,7 +8278,7 @@ export function defineForm( }); if (parsed.success) return parsed.data; // The refusal stays an `Error` with a stack, so an uncaught module-load throw - // prints its issues and the remedy, with the author's `defineForm(...)` call + // prints its issues and the remedy, with the author's `defineMetadataForm(...)` call // as the first frame. Two traps, both measured on zod 4.6.1: `new z.ZodError` // builds a plain object (no `Error` parent, no `stack`), which node prints as // `ZodError { name, message: [Getter/Setter] }`; and zod builds every @@ -8282,13 +8287,13 @@ export function defineForm( // The error is built from issues that already carry the remedy, so its // lazily computed `message` holds it whenever it is first read. const refusal = new z.ZodRealError(withOptionValueDeriveRemedy(parsed.error.issues)); - z.core.util.captureStackTrace(refusal, defineForm); + z.core.util.captureStackTrace(refusal, defineMetadataForm); throw refusal; } /** * Type-safe factory for a metadata type's Studio list layout — the list - * counterpart of {@link defineForm}. It binds the columns to the type's JSON + * counterpart of {@link defineMetadataForm}. It binds the columns to the type's JSON * Schema (`data.provider === 'schema'`) and validates them against * {@link MetadataListViewSchema} at definition time, so a malformed column * fails at module load. @@ -8320,7 +8325,7 @@ export function defineList( } /** - * [#19678] The remedy {@link defineForm}'s refusal of an unspellable inline + * [#19678] The remedy {@link defineMetadataForm}'s refusal of an unspellable inline * option `value` carries — ruling 乙 (record 5805845085, narrowing ruling * 不动 + 声明): the bound stays, an enum-typed row may still list spellable * members inline, and the wall names the derive path for a row whose members @@ -8332,7 +8337,7 @@ export function defineList( * `form-select-option.test.ts`). That message cannot carry this remedy where it * is declared: the same grammar bounds object-field options and three * object-storage names, and "derive the members from the served JSON Schema" - * is true only on a schema-bound form. `defineForm` is exactly that door — it + * is true only on a schema-bound form. `defineMetadataForm` is exactly that door — it * stamps `data.provider: 'schema'` on every form it builds — so the remedy is * appended here, to the issue that door raises, and nowhere else. */ diff --git a/packages/spec/tsup.config.ts b/packages/spec/tsup.config.ts index e7a5cf1def0..0f24e48ec57 100644 --- a/packages/spec/tsup.config.ts +++ b/packages/spec/tsup.config.ts @@ -20,15 +20,15 @@ type Plugin = NonNullable[number]; * - `lazySchema(fn)` allocates a Proxy, defers `fn` to first use; * - `strictObject(shape, …)` builds a closed zod object (construction only — * the unknown-key error closure runs at parse time, not now); - * - `defineForm(cfg)` parses STATIC author-time data through `FormViewSchema` + * - `defineMetadataForm(cfg)` parses STATIC author-time data through `FormViewSchema` * — pure computation whose only observable effect is a throw on invalid * static input, which this package's own build (`gen:schema` under * OS_EAGER_SCHEMAS) and tests still exercise. */ -const PURE_CONSTRUCTORS: ReadonlySet = new Set(['lazySchema', 'strictObject', 'defineForm']); +const PURE_CONSTRUCTORS: ReadonlySet = new Set(['lazySchema', 'strictObject', 'defineMetadataForm']); /** A file that never names a marked constructor is handed back untouched, unparsed. */ -const NAMES_A_PURE_CONSTRUCTOR = /\b(?:lazySchema|strictObject|defineForm)\b/; +const NAMES_A_PURE_CONSTRUCTOR = /\b(?:lazySchema|strictObject|defineMetadataForm)\b/; const PURE_ANNOTATION = '/* @__PURE__ */ '; diff --git a/scripts/check-i18n-bundles.mjs b/scripts/check-i18n-bundles.mjs index 81af7abacef..2ca32f70aa5 100644 --- a/scripts/check-i18n-bundles.mjs +++ b/scripts/check-i18n-bundles.mjs @@ -160,14 +160,14 @@ const SURFACE_MODULE = 'scripts/i18n-bundle-surface.mjs'; * `metadataForms..label` / `.description` for every entry of * `DEFAULT_METADATA_TYPE_REGISTRY` — including form-less types like * `datasource`/`job`/`translation` — and separately reads - * `METADATA_FORM_REGISTRY` itself (the map, not the `*.form.ts` leaves it + * `METADATA_FORM_REGISTRY` itself (the map, not the `*.metadata-form.ts` leaves it * points at) to decide which types also get section/field labels. Editing * either moves the same `platform-objects` bundles PR #9113 had to - * regenerate — and, unlike the `*.form.ts` leaves, neither carries a filename + * regenerate — and, unlike the `*.metadata-form.ts` leaves, neither carries a filename * SURFACE_MODULE's own convention (`isMetadataFormModulePath`) can see. * * Not folded into SURFACE_MODULE: that module documents the ONE convention it - * enumerates at runtime (the `.form.ts` suffix), and these two files + * enumerates at runtime (the `.metadata-form.ts` suffix), and these two files * deliberately do not carry it — inventing a second filename convention for * exactly two files would be the guess #9144 declined to make. A bare * coupling constant was the option the card measured to have no downside diff --git a/scripts/i18n-bundle-surface.mjs b/scripts/i18n-bundle-surface.mjs index f17fd0194f6..7faab44c022 100644 --- a/scripts/i18n-bundle-surface.mjs +++ b/scripts/i18n-bundle-surface.mjs @@ -41,14 +41,19 @@ * * ## The one convention this module writes down * - * A metadata form module is a file whose name ends `.form.ts`. That is the - * producer's own convention, stated by the registry it feeds — packages/spec/ - * src/system/metadata-form-registry.ts: "the FormView produced by - * defineForm({ schemaId }) in the corresponding *.form.ts". Measured on this - * tree when this module landed: 17 files in the repo carry that suffix, all of - * them under packages/spec/src, and the registry has exactly 17 entries with a - * form — the convention and the population coincide, with nothing left over on - * either side. + * A metadata form module is a file whose name ends `.metadata-form.ts`. That + * is the producer's own convention, stated by the registry it feeds — + * packages/spec/src/system/metadata-form-registry.ts: "the FormView produced + * by defineMetadataForm({ schemaId }) in the corresponding *.metadata-form.ts". + * Measured on this tree when this module landed: 17 files in the repo carried + * the suffix (then `.metadata-form.ts`), all of them under packages/spec/src, and the + * registry had exactly 17 entries with a form — the convention and the + * population coincide, with nothing left over on either side. + * + * The suffix was `.metadata-form.ts` until ADR-0159 (#37086) gave that spelling to the + * `form` metadata type: an app's `lead.form.ts` is a `form` item, not a + * Studio module, so the Studio modules moved to the name of their helper + * (`defineMetadataForm`) and of their translation family (`metadataForms`). * * What it still deliberately does NOT cover, stated so the next reader does * not mistake silence for coverage: the type-level half of the same surface. @@ -58,7 +63,7 @@ * and the registry module itself (packages/spec/src/system/metadata-form- * registry.ts) decides which forms are walked. Editing either moves the same * four bundles, and neither carries a filename this module's ONE convention - * (the `.form.ts` suffix) can see — inventing a second convention for exactly + * (the `.metadata-form.ts` suffix) can see — inventing a second convention for exactly * two files would be a guess, not a discovery. #9144 closed that edge WITHOUT * extending this module: the two module paths are declared as bare coupling * constants directly in check-i18n-bundles.mjs (METADATA_TYPE_REGISTRY_MODULE @@ -93,7 +98,7 @@ export const EXTRACT_CONFIG_FILENAME = 'i18n-extract.config.ts'; export const METADATA_FORMS_OPT_OUT_FLAG = '--no-metadata-forms'; /** The filename suffix of a metadata form module. See the module note. */ -export const METADATA_FORM_MODULE_SUFFIX = '.form.ts'; +export const METADATA_FORM_MODULE_SUFFIX = '.metadata-form.ts'; /** * Does this path name an extract config? The FILENAME plus a `scripts/` @@ -106,7 +111,7 @@ export function isExtractConfigPath(path) { /** * Does this path name a metadata form module? * - * The suffix must be preceded by a name: a file called exactly `.form.ts` is a + * The suffix must be preceded by a name: a file called exactly `.metadata-form.ts` is a * dotted entry every walk here already skips, and accepting it would let the * bare suffix match as a path. */ diff --git a/scripts/pm/dispatch-gates.data.mjs b/scripts/pm/dispatch-gates.data.mjs index 60e8d9f60ee..4755f331adf 100644 --- a/scripts/pm/dispatch-gates.data.mjs +++ b/scripts/pm/dispatch-gates.data.mjs @@ -761,10 +761,10 @@ export const ESCAPABLE_LITERAL_LEDGER_ROWS = Object.freeze([ * zod.ts) supplies `metadataForms..label`/`.description` for EVERY * registry entry, including form-less types, and `METADATA_FORM_REGISTRY` * itself (packages/spec/src/system/metadata-form-registry.ts, the map, not - * the `*.form.ts` leaves it points at) decides which types get section/field + * the `*.metadata-form.ts` leaves it points at) decides which types get section/field * labels at all. Editing either moves the same bundles PR #9113 paid for — - * but unlike the `.form.ts` leaves, neither file carries a filename the - * `.form.ts` convention (or any convention) distinguishes, so a KIND entry + * but unlike the `.metadata-form.ts` leaves, neither file carries a filename the + * `.metadata-form.ts` convention (or any convention) distinguishes, so a KIND entry * here would need to invent one for exactly two files. * * That is not the same shape as the two entries above: this is not a @@ -1081,7 +1081,7 @@ export const CHANGE_KIND_ROWS = [ ], }, { - kind: 'edits a metadata form module (a *.form.ts the Studio form registry collects)', + kind: 'edits a metadata form module (a *.metadata-form.ts the Studio form registry collects)', matches: 'metadata-form-module', gates: [ { diff --git a/scripts/pm/dispatch-gates.self-test.mjs b/scripts/pm/dispatch-gates.self-test.mjs index e6911b85c82..7d00bfbaecf 100644 --- a/scripts/pm/dispatch-gates.self-test.mjs +++ b/scripts/pm/dispatch-gates.self-test.mjs @@ -5751,13 +5751,14 @@ export function selfTest({ tier = 'full' } = {}) { // the metadataForms surface is registry-driven, its source lives in // packages/spec, and packages/spec owns no extract config. Pure judgments // first, then the live tree, then both rendering directions. - t('a form module is one', isMetadataFormModulePath('packages/spec/src/data/object.form.ts')); + t('a form module is one', isMetadataFormModulePath('packages/spec/src/data/object.metadata-form.ts')); t('its sibling schema is not', !isMetadataFormModulePath('packages/spec/src/data/object.zod.ts')); - t('a bare .form.ts with no name is not one', !isMetadataFormModulePath('packages/spec/src/data/.form.ts')); - t('a form module test file is not one', !isMetadataFormModulePath('packages/spec/src/data/object.form.test.ts')); + t('a `form` metadata item source (the ADR-0159 type) is not one', !isMetadataFormModulePath('examples/app-crm/src/forms/lead.form.ts')); + t('a bare .metadata-form.ts with no name is not one', !isMetadataFormModulePath('packages/spec/src/data/.metadata-form.ts')); + t('a form module test file is not one', !isMetadataFormModulePath('packages/spec/src/data/object.metadata-form.test.ts')); - const formMods = ['packages/spec/src/data/object.form.ts', 'packages/spec/src/ui/view.form.ts']; - t('the module itself reaches', reachesMetadataFormModule('packages/spec/src/data/object.form.ts', formMods)); + const formMods = ['packages/spec/src/data/object.metadata-form.ts', 'packages/spec/src/ui/view.metadata-form.ts']; + t('the module itself reaches', reachesMetadataFormModule('packages/spec/src/data/object.metadata-form.ts', formMods)); t('a directory CONTAINING one reaches (a card surface is named before its files exist)', reachesMetadataFormModule('packages/spec/src/ui', formMods)); t('a sibling sharing a name prefix does not', !reachesMetadataFormModule('packages/spec/src/dat', formMods)); t('an unrelated package does not', !reachesMetadataFormModule('packages/objectql/src/engine.ts', formMods)); @@ -5772,7 +5773,7 @@ export function selfTest({ tier = 'full' } = {}) { // The live tree — the half no fixture can prove. const liveForms = metadataFormModulePaths(); - t('the live walk discovers form modules', liveForms.length > 0 && liveForms.every((f) => f.endsWith('.form.ts'))); + t('the live walk discovers form modules', liveForms.length > 0 && liveForms.every((f) => f.endsWith('.metadata-form.ts'))); t('the live walk finds no duplicates', new Set(liveForms).size === liveForms.length); // If this flips, the entry stops firing BY DESIGN (every package opted out of // the shared baseline) — read the entry's deletion criterion before "fixing" it. @@ -5784,7 +5785,7 @@ export function selfTest({ tier = 'full' } = {}) { // rendered delimiters for the reason the entry above states: a bare substring // stays green through a prefix-preserving rename, the one rot the STALE branch // exists to catch. - const formHit = changeKindLines(['packages/spec/src/data/object.form.ts', 'packages/spec/src/data/field.form.ts'], resolved, i18nRows); + const formHit = changeKindLines(['packages/spec/src/data/object.metadata-form.ts', 'packages/spec/src/data/field.metadata-form.ts'], resolved, i18nRows); // The `?? ''` is not defensive noise: reverse-verifying this block by making // every config opt out emptied `formHit`, and the bare index CRASHED the whole // self-test on a TypeError — one stack in place of 180-odd named verdicts. A @@ -5794,14 +5795,14 @@ export function selfTest({ tier = 'full' } = {}) { const formKindLine = formHit[0] ?? ''; t('the measured incident paths now emit the metadata-form section', formHit.length === 2 && formKindLine.includes('metadata form module')); t('that section names check:i18n exactly, runnably', formHit.some((l) => l.includes('- pnpm check:i18n —'))); - t('and it names both incident paths, not just the first', formKindLine.includes('object.form.ts') && formKindLine.includes('field.form.ts')); + t('and it names both incident paths, not just the first', formKindLine.includes('object.metadata-form.ts') && formKindLine.includes('field.metadata-form.ts')); // The over-trigger direction, which the card demanded in its own right: a spec // change that touches no form must NOT be pushed into this gate. Both a schema // beside a real form module and an unrelated package are pinned, because the // first is the one a filename convention could plausibly over-reach into. t('a spec schema next door to a form emits no i18n section', !changeKindLines(['packages/spec/src/data/filter.zod.ts'], resolved).some((l) => l.includes('check:i18n'))); t('an unrelated package still emits no i18n section', !changeKindLines(['packages/rest/src/rest-server.ts'], resolved).some((l) => l.includes('check:i18n'))); - const formStale = changeKindLines(['packages/spec/src/data/object.form.ts'], () => null); + const formStale = changeKindLines(['packages/spec/src/data/object.metadata-form.ts'], () => null); t('an undiscoverable check:i18n renders STALE for this entry too', formStale.filter((l) => l.includes('⚠ check:i18n: STALE')).length === 1); // The measured incident (#8410 / PR #8399), pinned against the REAL workflow @@ -5991,7 +5992,7 @@ export function selfTest({ tier = 'full' } = {}) { const FORM_REGISTRY = 'packages/spec/src/system/metadata-form-registry.ts'; const i18nGateHints = readHints('scripts/check-i18n-bundles.mjs'); t('the i18n gate declares the type-level metadata registry module', covers(i18nGateHints, TYPE_REGISTRY)); - t('the i18n gate declares the form registry module too (not just its *.form.ts leaves)', covers(i18nGateHints, FORM_REGISTRY)); + t('the i18n gate declares the form registry module too (not just its *.metadata-form.ts leaves)', covers(i18nGateHints, FORM_REGISTRY)); const typeRegistryVerdict = classifyEntry({ files: ['scripts/check-i18n-bundles.mjs'], hints: i18nGateHints }, [TYPE_REGISTRY]); const formRegistryVerdict = classifyEntry({ files: ['scripts/check-i18n-bundles.mjs'], hints: i18nGateHints }, [FORM_REGISTRY]); t( diff --git a/scripts/pm/landing-k.mjs b/scripts/pm/landing-k.mjs index 586699eb600..7557b8ec489 100644 --- a/scripts/pm/landing-k.mjs +++ b/scripts/pm/landing-k.mjs @@ -663,7 +663,7 @@ export function selfTest() { t('…and the same pack under a PR off the label surface is clear', [notLabel.exit, notLabel.locale.packs.length, notLabel.locale.label_hits], [EXIT_OK, 1, []]); const known = read(fixture({ files: ['packages/spec/src/ui/view.zod.ts'], git: { added: { [`${BASE}..${MAIN}`]: [`${dir}/zh-CN.metadata-forms.generated.ts`] }, trees } })); t('a file added for a locale the directory already held is no new pack', known.locale.packs, []); - t('the label surface: a form module, spec, an example, a translation file and an extract-config package hit; a script does not', ['packages/spec/src/ui/x.form.ts', 'packages/spec/src/data/field.zod.ts', 'examples/app-todo/objectstack.config.ts', 'packages/x/translations/en.ts', 'packages/platform-objects/src/a.ts', 'scripts/pm/x.mjs'].map((p) => Boolean(labelSurfaceReader(['packages/platform-objects/'])(p))), [true, true, true, true, true, false]); + t('the label surface: a form module, spec, an example, a translation file and an extract-config package hit; a script does not', ['packages/spec/src/ui/x.metadata-form.ts', 'packages/spec/src/data/field.zod.ts', 'examples/app-todo/objectstack.config.ts', 'packages/x/translations/en.ts', 'packages/platform-objects/src/a.ts', 'scripts/pm/x.mjs'].map((p) => Boolean(labelSurfaceReader(['packages/platform-objects/'])(p))), [true, true, true, true, true, false]); t('the locale is the file name up to its first dot', newLocalePacks(['a/translations/ja-JP.source-hashes.generated.ts', 'a/translations/index.ts', 'a/b.ts'], () => []).packs.map((x) => x.locale), ['ja-JP']); const unreadFiles = read(fixture({ files: null, git: { added, trees } })); t('⭐ a new pack with an unread PR file list is exit 3, never a clear leg', [unreadFiles.exit, unreadFiles.gaps.some((g) => g.includes('label leg is unjudged'))], [EXIT_CANT_ANSWER, true]); diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.groupSectionReachability-8725.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.groupSectionReachability-8725.test.tsx index 52cb67bfb35..b14040c58a6 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.groupSectionReachability-8725.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.groupSectionReachability-8725.test.tsx @@ -112,7 +112,7 @@ const SCHEMA_ID = 'demo_type_8725'; /** * A form document spelled the way it ARRIVES from `/meta/types`: plain data - * carrying the `data` binding `defineForm` writes onto every metadata form. + * carrying the `data` binding `defineMetadataForm` writes onto every metadata form. */ function serverForm(sections: unknown[], type = 'simple'): FormViewSpec { return { type, data: { provider: 'schema', schemaId: SCHEMA_ID }, sections } as unknown as FormViewSpec; diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.optionVisibleWhen.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.optionVisibleWhen.test.tsx index f5f2d00af72..177c24bbe70 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.optionVisibleWhen.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.optionVisibleWhen.test.tsx @@ -14,7 +14,7 @@ afterEach(() => { }); /** - * objectui#6247 — a per-option `visibleWhen` written into a `*.form.ts` is + * objectui#6247 — a per-option `visibleWhen` written into a `*.metadata-form.ts` is * honoured by the metadata-admin renderer. * * `SelectOptionSchema` declares `visibleWhen` (ADR-0068 / objectui#2284) and is diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.pageVisibility.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.pageVisibility.test.tsx index 2829454ec66..33f9bd5c4f2 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.pageVisibility.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.pageVisibility.test.tsx @@ -42,7 +42,7 @@ const pageSchema = { }, }; -// FormView mirroring framework PR #1817 (packages/spec/src/ui/page.form.ts). +// FormView mirroring framework PR #1817 (packages/spec/src/ui/page.metadata-form.ts). const pageForm = { type: 'simple' as const, sections: [ diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx index f8fbbf345ca..e841b01bde8 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx @@ -719,7 +719,7 @@ function detectFieldRefWidget( * Detect the icon picker by NAME CONVENTION: a string prop named `icon` (or * `*Icon`) with no enum. Mirrors {@link detectFieldRefWidget} so every metadata * type's icon field renders the searchable Lucide picker instead of a free-text - * input, without each spec `*.form.ts` having to pin `widget: 'icon'`. + * input, without each spec `*.metadata-form.ts` having to pin `widget: 'icon'`. */ function detectIconWidget(name: string, schema: JsonSchema | undefined): string | undefined { if (Array.isArray(schema?.enum)) return undefined; diff --git a/ui/packages/app-shell/src/views/metadata-admin/form-spec.ts b/ui/packages/app-shell/src/views/metadata-admin/form-spec.ts index 1aa563a9c33..c9843e9bc0f 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/form-spec.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/form-spec.ts @@ -123,7 +123,7 @@ export interface FormFieldSpec { * named narrowing — the one element type in this file that the header's * "every key the two layers agree on comes FROM the spec" rule had never * been applied to. `visibleWhen` was among the dropped pair, so an author - * could legally write a per-option predicate into a `*.form.ts`, have it + * could legally write a per-option predicate into a `*.metadata-form.ts`, have it * parse clean against `SelectOptionSchema` (`z.core.$strict`, so the schema * really does declare it), and get a narrowing that this renderer then * ignored: accepted, stored, shipped, inert — ADR-0049's declared≠enforced, diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx index a9c40a53a61..a22ec5fddf0 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx @@ -526,7 +526,7 @@ function offersReferenceNameVisible(type: string): boolean { /** * The `deleteBehavior` values the field panel offers on `type`: the rows the - * generic `field` form draws for the key (`field.form.ts`), so the two + * generic `field` form draws for the key (`field.metadata-form.ts`), so the two * authoring surfaces agree. All three on a `lookup`, and on a `user` field, * where a declared value takes effect when the user is deleted (objectstack#29253) * and declaring nothing keeps the field out of the delete walk. Only diff --git a/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts b/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts index 10a5127ab05..bd9409a5710 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts @@ -351,7 +351,7 @@ export const ZH_CN_SPEC_FORMS: NonNullable = { // The date-grouping sentence lives on the `dateRange.dimension` child below (objectstack#36838). dateRange: { label: '日期范围', helpText: '打开报表时显示的时间段,以及使用者能否自己选择范围' }, exportOptions: { label: '导出选项', helpText: '下载格式(csv、xlsx)与文件名。谁可以下载由数据来源对象上的导出权限决定' }, - // The children `report.form.ts` declares for both composites (objectstack#36447), + // The children `report.metadata-form.ts` declares for both composites (objectstack#36447), // copied from the platform zh-CN bundle like every unmarked row here. 'dateRange.dimension': { label: '日期字段', helpText: '时间段按数据来源里的哪个日期分组筛选;只有一个日期分组时可留空' }, 'dateRange.defaultRange': { label: '默认时间段', helpText: '打开报表时显示的时间段' }, @@ -455,7 +455,7 @@ export const ZH_CN_SPEC_FORMS: NonNullable = { chart: { label: '图表' }, userFilters: { label: '用户筛选器', helpText: '快速筛选栏:控件样式(dropdown / tabs / toggle)+ 暴露的字段或标签页预设' }, // #30267: every composite below now declares its children in - // `view.form.ts`, so each child row is named here (all of them, per + // `view.metadata-form.ts`, so each child row is named here (all of them, per // the ⛔ composite rule at the top of this file). 'userFilters.element': { label: '控件样式', helpText: '对象视图上的筛选控件样式:"dropdown"(按字段取值的筛选标签)。"toggle" 已弃用。"tabs" 仅用于页面——命名预设请使用 `listViews`。' }, 'userFilters.fields': { label: '筛选字段', helpText: '作为快速筛选暴露的字段(dropdown / toggle 控件)' }, diff --git a/ui/packages/app-shell/src/views/metadata-admin/predicate.ts b/ui/packages/app-shell/src/views/metadata-admin/predicate.ts index ed292bdcdbb..2fa44f77a2e 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/predicate.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/predicate.ts @@ -9,7 +9,7 @@ * unified across the platform (ROADMAP M9), swap `evaluatePredicate` * for the real CEL evaluator without touching SchemaForm.tsx. * - * Supported subset (covers everything used in spec `*.form.ts` today): + * Supported subset (covers everything used in spec `*.metadata-form.ts` today): * - `path == 'literal'` string equality * - `path != 'literal'` string inequality * - `path == 123` number equality diff --git a/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx b/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx index 71e8293c608..8b61bcdcccc 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx @@ -3,7 +3,7 @@ /** * Built-in widget renderers for SchemaForm. * - * These cover the common widget hints declared in spec `*.form.ts` + * These cover the common widget hints declared in spec `*.metadata-form.ts` * files (e.g. `widget: 'ref:object'`, `widget: 'master-detail'`). * * Each widget receives `WidgetProps`: From a67a7942cc7be930929dc8b0b938a689bd48d053 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 23:30:29 +0000 Subject: [PATCH 02/50] chore(changeset): name the three packages whose comments the rename re-points Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .changeset/37086-define-metadata-form-rename.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.changeset/37086-define-metadata-form-rename.md b/.changeset/37086-define-metadata-form-rename.md index b73c84f9827..b7710315ded 100644 --- a/.changeset/37086-define-metadata-form-rename.md +++ b/.changeset/37086-define-metadata-form-rename.md @@ -1,6 +1,9 @@ --- '@objectstack/spec': patch '@objectstack/lint': patch +'@objectstack/cli': patch +'@objectstack/metadata-protocol': patch +'@objectstack/platform-objects': patch --- refactor(spec)!: the Studio metadata-form helper `defineForm` is renamed `defineMetadataForm`, and its modules move from `*.form.ts` to `*.metadata-form.ts`, so the name and the suffix are free for the `form` metadata type (ADR-0159) @@ -19,3 +22,4 @@ ADR-0159 makes `form` a metadata type of its own, and the maintainer ruled that - **The fix:** rename the import and the call; rename a module that builds one to `*.metadata-form.ts`. The compiler names every call site (`TS2305` / `TS2724`). - **Outside use, read before the rename:** no import or call of `defineForm` in any public repository of the organization, nor in the cloud repository. - `@objectstack/lint`: the explanation of `visibility-root-mislayered` and the `data`-root message of the field-rule check name the Studio modules by their new suffix (`*.metadata-form.ts`); what each rule reports is unchanged. +- `@objectstack/cli`, `@objectstack/metadata-protocol`, `@objectstack/platform-objects`: comments and docblocks that cite the Studio modules name them by their new file names; no behaviour changes. From d53e5c079cf9e21f550a6b7d0482d0d583470053 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 00:06:52 +0000 Subject: [PATCH 03/50] test(app-shell): pay the lint and formula loads at collection in the three SchemaForm tests the rename edits check:test-source-alias judges the test files a change edits: the three SchemaForm tests reach celAuthoring's dynamic imports of @objectstack/lint and @objectstack/formula, so each now loads them at module top. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .../SchemaForm.groupSectionReachability-8725.test.tsx | 3 +++ .../views/metadata-admin/SchemaForm.optionVisibleWhen.test.tsx | 2 ++ .../views/metadata-admin/SchemaForm.pageVisibility.test.tsx | 3 +++ 3 files changed, 8 insertions(+) diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.groupSectionReachability-8725.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.groupSectionReachability-8725.test.tsx index b14040c58a6..38b86ca7f31 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.groupSectionReachability-8725.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.groupSectionReachability-8725.test.tsx @@ -46,6 +46,9 @@ import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest'; import { render, screen, cleanup } from '@testing-library/react'; import { resolveSectionGroupReferences, sectionEntryName } from '@object-ui/plugin-form'; import { SchemaForm } from './SchemaForm'; +// Paid at module top, during collection (check:test-source-alias): the source under test reaches it through a dynamic import. +import '@objectstack/formula'; +import '@objectstack/lint'; import type { FormSectionSpec, FormViewSpec } from './form-spec'; import type { RichMetadataTypeEntry } from './useMetadata'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.optionVisibleWhen.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.optionVisibleWhen.test.tsx index 177c24bbe70..e98550dc9a9 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.optionVisibleWhen.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.optionVisibleWhen.test.tsx @@ -3,6 +3,8 @@ import { describe, it, expect, afterEach, vi } from 'vitest'; import { render, screen, cleanup, fireEvent, waitFor } from '@testing-library/react'; import { SchemaForm } from './SchemaForm'; +// Paid at module top, during collection (check:test-source-alias): the source under test reaches it through a dynamic import. +import '@objectstack/lint'; import type { FormFieldSpec, FormViewSpec } from './form-spec'; import { WIDGETS, resolveColorWidgetKey } from './widgets'; import { ExpressionProvider } from '../../providers/ExpressionProvider'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.pageVisibility.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.pageVisibility.test.tsx index 33f9bd5c4f2..726bc159ddc 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.pageVisibility.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.pageVisibility.test.tsx @@ -3,6 +3,9 @@ import { describe, it, expect, afterEach } from 'vitest'; import { render, screen, cleanup } from '@testing-library/react'; import { SchemaForm } from './SchemaForm'; +// Paid at module top, during collection (check:test-source-alias): the source under test reaches it through a dynamic import. +import '@objectstack/formula'; +import '@objectstack/lint'; afterEach(cleanup); From 8a3430afdd6ddb45e8dd3efdd648a2951665174f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 00:31:06 +0000 Subject: [PATCH 04/50] 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 05/50] =?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 06/50] =?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 07/50] =?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 08/50] 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 09/50] 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 10/50] 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 d9a02e2150af6d130e85e45087b2af13c3e6f9d6 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 03:38:18 +0000 Subject: [PATCH 11/50] chore(spec): regenerate export-origins after merging main Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- packages/spec/export-origins/ai.json | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json index a620ec57d20..fa303974317 100644 --- a/packages/spec/export-origins/ai.json +++ b/packages/spec/export-origins/ai.json @@ -9,6 +9,10 @@ "AI_CONTEXT_MAX_FIELDS": "src/ai/ai-context.zod.ts#AI_CONTEXT_MAX_FIELDS (const)", "AI_CONTEXT_MAX_RELATED": "src/ai/ai-context.zod.ts#AI_CONTEXT_MAX_RELATED (const)", "AI_CONTEXT_MAX_RELATED_FIELDS": "src/ai/ai-context.zod.ts#AI_CONTEXT_MAX_RELATED_FIELDS (const)", + "AI_CONTEXT_MAX_RELATED_ROWS": "src/ai/ai-context.zod.ts#AI_CONTEXT_MAX_RELATED_ROWS (const)", + "AI_CONTEXT_WHERE_COMBINATORS": "src/ai/ai-context.zod.ts#AI_CONTEXT_WHERE_COMBINATORS (const)", + "AI_CONTEXT_WHERE_MAX_DEPTH": "src/ai/ai-context.zod.ts#AI_CONTEXT_WHERE_MAX_DEPTH (const)", + "AI_CONTEXT_WHERE_OPERATORS": "src/ai/ai-context.zod.ts#AI_CONTEXT_WHERE_OPERATORS (const)", "AI_FACE_NAME_CUT_LENGTH": "src/ai/face-name.ts#AI_FACE_NAME_CUT_LENGTH (const)", "AI_FACE_NAME_HASH_LENGTH": "src/ai/face-name.ts#AI_FACE_NAME_HASH_LENGTH (const)", "AI_FACE_NAME_MAX_LENGTH": "src/ai/face-name.ts#AI_FACE_NAME_MAX_LENGTH (const)", @@ -24,6 +28,9 @@ "AiContextRelated": "src/ai/ai-context.zod.ts#AiContextRelated (type)", "AiContextRelatedParsed": "src/ai/ai-context.zod.ts#AiContextRelatedParsed (type)", "AiContextRelatedSchema": "src/ai/ai-context.zod.ts#AiContextRelatedSchema (const)", + "AiContextRelatedWhere": "src/ai/ai-context.zod.ts#AiContextRelatedWhere (type)", + "AiContextRelatedWhereParsed": "src/ai/ai-context.zod.ts#AiContextRelatedWhereParsed (type)", + "AiContextRelatedWhereSchema": "src/ai/ai-context.zod.ts#AiContextRelatedWhereSchema (const)", "AiContextSchema": "src/ai/ai-context.zod.ts#AiContextSchema (const)", "AiFaceAddress": "src/ai/face-name.ts#AiFaceAddress (interface)", "BUILD_PROGRESS_FRAME_TYPE": "src/ai/build-progress.zod.ts#BUILD_PROGRESS_FRAME_TYPE (const)", @@ -271,6 +278,7 @@ "VectorStoreSchema": "src/ai/embedding.zod.ts#VectorStoreSchema (const)", "agentForm": "src/ai/agent.metadata-form.ts#agentForm (const)", "aiContextForm": "src/ai/ai-context.metadata-form.ts#aiContextForm (const)", + "aiContextWhereFields": "src/ai/ai-context.zod.ts#aiContextWhereFields (function)", "defineAgent": "src/ai/agent.zod.ts#defineAgent (function)", "defineSkill": "src/ai/skill.zod.ts#defineSkill (function)", "defineSolutionBlueprint": "src/ai/solution-blueprint.zod.ts#defineSolutionBlueprint (function)", From 9d212c36d1367a5bf3bbd9b1516081538827d54a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 04:35:45 +0000 Subject: [PATCH 12/50] 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 13/50] 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 14/50] 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 5be6455667ecfa1be7cec2f34f7d26ff6d9260e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 05:18:44 +0000 Subject: [PATCH 15/50] chore(spec): regenerate export-origins after merging main Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- packages/spec/export-origins/ai.json | 11 +++++++++++ packages/spec/export-origins/data.json | 5 +++++ 2 files changed, 16 insertions(+) diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json index fa303974317..e208ba3f218 100644 --- a/packages/spec/export-origins/ai.json +++ b/packages/spec/export-origins/ai.json @@ -58,6 +58,7 @@ "BlueprintViewSchema": "src/ai/solution-blueprint.zod.ts#BlueprintViewSchema (const)", "BlueprintWidgetCondition": "src/ai/solution-blueprint.zod.ts#BlueprintWidgetCondition (type)", "BlueprintWidgetConditionSchema": "src/ai/solution-blueprint.zod.ts#BlueprintWidgetConditionSchema (const)", + "BodyHeading": "src/ai/record-body-anchor.ts#BodyHeading (interface)", "BuildProgressFrame": "src/ai/build-progress.zod.ts#BuildProgressFrame (type)", "BuildProgressFrameSchema": "src/ai/build-progress.zod.ts#BuildProgressFrameSchema (const)", "BuildProgressPhase": "src/ai/build-progress.zod.ts#BuildProgressPhase (type)", @@ -212,6 +213,14 @@ "QueryDatasetInputSchema": "src/ai/dataset-tools.zod.ts#QueryDatasetInputSchema (const)", "QueryDatasetOutput": "src/ai/dataset-tools.zod.ts#QueryDatasetOutput (type)", "QueryDatasetOutputSchema": "src/ai/dataset-tools.zod.ts#QueryDatasetOutputSchema (const)", + "RECORD_CITATIONS_MAX": "src/ai/record-citation.zod.ts#RECORD_CITATIONS_MAX (const)", + "RECORD_CITATIONS_PART_TYPE": "src/ai/record-citation.zod.ts#RECORD_CITATIONS_PART_TYPE (const)", + "RecordCitation": "src/ai/record-citation.zod.ts#RecordCitation (type)", + "RecordCitationParsed": "src/ai/record-citation.zod.ts#RecordCitationParsed (type)", + "RecordCitationSchema": "src/ai/record-citation.zod.ts#RecordCitationSchema (const)", + "RecordCitations": "src/ai/record-citation.zod.ts#RecordCitations (type)", + "RecordCitationsParsed": "src/ai/record-citation.zod.ts#RecordCitationsParsed (type)", + "RecordCitationsSchema": "src/ai/record-citation.zod.ts#RecordCitationsSchema (const)", "RecordContextBody": "src/ai/record-context-tools.zod.ts#RecordContextBody (type)", "RecordContextBodyParsed": "src/ai/record-context-tools.zod.ts#RecordContextBodyParsed (type)", "RecordContextBodySchema": "src/ai/record-context-tools.zod.ts#RecordContextBodySchema (const)", @@ -286,8 +295,10 @@ "deriveAiFaceName": "src/ai/face-name.ts#deriveAiFaceName (function)", "getDatasetToolJsonSchemas": "src/ai/dataset-tools.zod.ts#getDatasetToolJsonSchemas (function)", "getRecordContextToolJsonSchemas": "src/ai/record-context-tools.zod.ts#getRecordContextToolJsonSchemas (function)", + "headingsOf": "src/ai/record-body-anchor.ts#headingsOf (function)", "scopesToAgentPermissionSets": "src/ai/mcp.zod.ts#scopesToAgentPermissionSets (function)", "skillForm": "src/ai/skill.metadata-form.ts#skillForm (const)", + "stripBodyTags": "src/ai/record-body-anchor.ts#stripBodyTags (function)", "toolForm": "src/ai/tool.metadata-form.ts#toolForm (const)" } } diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 2fea0d8ae71..cb0732fd521 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -428,6 +428,7 @@ "HookQuery": "src/data/hook-api.ts#HookQuery (type)", "HookRefusal": "src/data/hook.zod.ts#HookRefusal (type)", "HookRefusalSchema": "src/data/hook.zod.ts#HookRefusalSchema (const)", + "HookRefusalThrownReason": "src/data/hook-refusal-codes.ts#HookRefusalThrownReason (interface)", "HookSchema": "src/data/hook.zod.ts#HookSchema (const)", "HookText": "src/data/hook.zod.ts#HookText (type)", "HookTextReader": "src/data/hook.zod.ts#HookTextReader (type)", @@ -766,6 +767,7 @@ "ReferenceResolutionErrorSchema": "src/data/seed-loader.zod.ts#ReferenceResolutionErrorSchema (const)", "ReferenceResolutionParsed": "src/data/seed-loader.zod.ts#ReferenceResolutionParsed (type)", "ReferenceResolutionSchema": "src/data/seed-loader.zod.ts#ReferenceResolutionSchema (const)", + "RefusalListProblem": "src/data/hook-refusal-codes.ts#RefusalListProblem (type)", "RelatedListEntry": "src/data/object.zod.ts#RelatedListEntry (type)", "RelatedListEntryInput": "src/data/related-list-entry.ts#RelatedListEntryInput (type)", "RelatedListEntryObject": "src/data/related-list-entry.ts#RelatedListEntryObject (interface)", @@ -1139,6 +1141,7 @@ "isTitleEligible": "src/data/display-name.ts#isTitleEligible (function)", "isTransferEligible": "src/data/user-action-transfer.ts#isTransferEligible (function)", "isUnboundedAbove": "src/data/calendar-day.ts#isUnboundedAbove (function)", + "isUndeclaredThrownReason": "src/data/hook-refusal-codes.ts#isUndeclaredThrownReason (function)", "isUniqueDeclared": "src/data/field.zod.ts#isUniqueDeclared (function)", "isVirtualSearchField": "src/data/search-fields.ts#isVirtualSearchField (function)", "judgeImportMappingTarget": "src/data/import-mapping-target.ts#judgeImportMappingTarget (function)", @@ -1245,6 +1248,8 @@ "uniqueNullDistinctDivergence": "src/data/unique-null-distinct-conformance.ts#uniqueNullDistinctDivergence (function)", "unknownImportMappingTargets": "src/data/import-mapping-target.ts#unknownImportMappingTargets (function)", "unprovisionedInjectedColumns": "src/data/injected-system-column-provenance.ts#unprovisionedInjectedColumns (function)", + "unreadableActionRefusalListAtRun": "src/data/hook-refusal-codes.ts#unreadableActionRefusalListAtRun (function)", + "unreadableHookRefusalListAtRun": "src/data/hook-refusal-codes.ts#unreadableHookRefusalListAtRun (function)", "urlCredentialQueryParams": "src/data/driver/common.zod.ts#urlCredentialQueryParams (function)", "urlUserinfoPassword": "src/data/driver/common.zod.ts#urlUserinfoPassword (function)", "urlUserinfoUsername": "src/data/driver/common.zod.ts#urlUserinfoUsername (function)", From 6103f74f0003948531c2499ba9f23ab8d911e27a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 05:22:58 +0000 Subject: [PATCH 16/50] 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 17/50] 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 cb854ea4d065c489e03a0d1b3b5bb9aeb8998626 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 06:51:30 +0000 Subject: [PATCH 18/50] docs(scripts): the i18n bundle surface note names .form.ts as the old Studio suffix Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- scripts/i18n-bundle-surface.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/i18n-bundle-surface.mjs b/scripts/i18n-bundle-surface.mjs index 7faab44c022..b037291f994 100644 --- a/scripts/i18n-bundle-surface.mjs +++ b/scripts/i18n-bundle-surface.mjs @@ -46,11 +46,11 @@ * packages/spec/src/system/metadata-form-registry.ts: "the FormView produced * by defineMetadataForm({ schemaId }) in the corresponding *.metadata-form.ts". * Measured on this tree when this module landed: 17 files in the repo carried - * the suffix (then `.metadata-form.ts`), all of them under packages/spec/src, and the + * the suffix (then `.form.ts`), all of them under packages/spec/src, and the * registry had exactly 17 entries with a form — the convention and the * population coincide, with nothing left over on either side. * - * The suffix was `.metadata-form.ts` until ADR-0159 (#37086) gave that spelling to the + * The suffix was `.form.ts` until ADR-0159 (#37086) gave that spelling to the * `form` metadata type: an app's `lead.form.ts` is a `form` item, not a * Studio module, so the Studio modules moved to the name of their helper * (`defineMetadataForm`) and of their translation family (`metadataForms`). From 995bbce917d90c59d06f29f3d1a924fed83f35aa Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:01:18 +0000 Subject: [PATCH 19/50] 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 20/50] 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 21/50] 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 22/50] 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 23/50] 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 24/50] =?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 25/50] 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 26/50] 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 27/50] 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 28/50] 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 29/50] 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 30/50] 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 31/50] 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 32/50] 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 33/50] 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 34/50] 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 35/50] 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, From 789b8ad7fb1ecfb4a53c493645af346312936835 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 15:25:17 +0000 Subject: [PATCH 36/50] test(rest): the refused-batch pin's comment states the draft as written Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- packages/rest/src/public-form-two-type-withdrawal.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 7f4746bacaa..a4fd17221d9 100644 --- a/packages/rest/src/public-form-two-type-withdrawal.test.ts +++ b/packages/rest/src/public-form-two-type-withdrawal.test.ts @@ -1118,7 +1118,7 @@ describe('[ADR-0067 D2] a package publish refused part-way on an engine that can refused: [[NAME, 'BATCH_ABORTED'], [SECOND, 'FORM_ADDRESS_TAKEN']], }, { - // The first form re-opens the address the pair's switched-off row holds; + // The first form 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, From dee2c2106af72126c7f0116c4ec806db2dc2d40f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 16:18:05 +0000 Subject: [PATCH 37/50] fix(metadata-protocol): a commit revert takes a form back only once the view rows the commit edited stand again Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .../src/protocol-package-commits.ts | 65 ++++++++++++++- .../public-form-two-type-withdrawal.test.ts | 83 +++++++++++++++++++ 2 files changed, 146 insertions(+), 2 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-package-commits.ts b/packages/metadata-protocol/src/protocol-package-commits.ts index b6236849abc..01bffacef06 100644 --- a/packages/metadata-protocol/src/protocol-package-commits.ts +++ b/packages/metadata-protocol/src/protocol-package-commits.ts @@ -118,6 +118,49 @@ function storedGrantObjectKeys(stored: unknown): string[] { return objects && typeof objects === 'object' && !Array.isArray(objects) ? Object.keys(objects) : []; } +/** A plan item's type as the registry keys it: `views` and `view` are one type. */ +const singularPlanType = (item: { type: string }): string => PLURAL_TO_SINGULAR[item.type] ?? item.type; + +/** A `view` row the commit edited (it stood before the commit): the revert restores it. */ +const isEditedViewItem = (item: CommitPlanItem): boolean => singularPlanType(item) === 'view' && item.existedBefore; + +/** + * [ADR-0159 D5, ADR-0067 D3] The order `revertCommit` walks a commit's plan + * in: newest first, with every `form` item walked after every `view` row the + * commit edited. A `form` publish records each old-shape `view` row it + * removed or re-saved as an edited row of the same commit, and the plan does + * not say which form a row carried, so a `form` item is taken back only once + * all of them have been walked ({@link editedViewsNotPutBack}). Every other + * item keeps its place. + */ +export function revertWalkOrder(items: readonly CommitPlanItem[]): CommitPlanItem[] { + const reversed = [...items].reverse(); + let lastEditedView = -1; + reversed.forEach((item, at) => { if (isEditedViewItem(item)) lastEditedView = at; }); + if (lastEditedView < 0) return reversed; + const head = reversed.slice(0, lastEditedView + 1); + return [ + ...head.filter((item) => singularPlanType(item) !== 'form'), + ...head.filter((item) => singularPlanType(item) === 'form'), + ...reversed.slice(lastEditedView + 1), + ]; +} + +/** + * [ADR-0159 D5, ADR-0067 D3] The `view` rows of a commit's plan that the + * commit edited and that this revert has reported in `failed[]`: rows that do + * not stand again as they stood before the commit. While one does, no `form` + * item of the commit is taken back: the form stays as published, so an undo + * never leaves an address with neither the form nor the row that carried it. + */ +export function editedViewsNotPutBack( + items: readonly CommitPlanItem[], + failed: ReadonlyArray<{ type: string; name: string }>, +): string[] { + const edited = new Set(items.filter(isEditedViewItem).map((item) => item.name)); + return [...new Set(failed.filter((f) => singularPlanType(f) === 'view' && edited.has(f.name)).map((f) => f.name))]; +} + export class ProtocolPackageCommitsFacet { /** The body of `ObjectStackProtocolImplementation#revertStoredPackage`; the method's docblock there is its contract. */ static async revertStoredPackage(host: Pick, request: { @@ -1242,8 +1285,26 @@ export class ProtocolPackageCommitsFacet { const advisories: RuntimeAuthoringIssue[] = []; // Reverse apply order so artifacts that depend on others (e.g. a view on - // a new object) are removed before the thing they reference. - for (const it of [...items].reverse()) { + // a new object) are removed before the thing they reference; every + // `form` item after the `view` rows the commit edited (ADR-0159 D5). + for (const it of revertWalkOrder(items)) { + // [ADR-0159 D5, ADR-0067 D3] A `form` item is taken back only once + // every `view` row the commit edited stands again: one that could + // not be put back keeps the form as published, reported here with + // nothing written for it. + const notPutBack = singularPlanType(it) === 'form' ? editedViewsNotPutBack(items, failed) : []; + if (notPutBack.length > 0) { + failed.push({ + type: it.type, + name: it.name, + error: `Commit item '${it.type}/${it.name}' was not reverted: the view row${notPutBack.length > 1 ? 's' : ''} ` + + `${notPutBack.map((n) => `'${n}'`).join(', ')} this commit also edited could not be put back, and a ` + + 'form is taken back only once every view row its commit edited stands again. Nothing was written ' + + 'for it, so it stays as published. Resolve the cause reported for that row, then revert the ' + + 'commit again.', + }); + continue; + } // The version this item restores to, or `null` when it does not take // the restore limb at all — bound ONCE (#9174), because the pre-flight // below and the `else if` further down must never drift apart: a gate 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 a4fd17221d9..1dcc1850a83 100644 --- a/packages/rest/src/public-form-two-type-withdrawal.test.ts +++ b/packages/rest/src/public-form-two-type-withdrawal.test.ts @@ -1054,6 +1054,89 @@ describe('[ADR-0159 D5, ADR-0067 D2 and D3] the undo of a `form` publish puts ba }); } + /** The pair's own old-shape row of the form, switched off: an item of the name, or a container `intake` that expands to it. */ + const OLD_SHAPE_KINDS = [ + { kind: 'an item-shaped row', row: NAME, canRollBack: true, item: () => viewItem(false, overrides) }, + { + kind: 'a re-saved container', row: 'intake', canRollBack: false, + item: () => ({ + name: 'intake', object: OBJECT, + list: { type: 'grid', columns: ['name', 'email'], data: { provider: 'object', object: OBJECT } }, + formViews: { contact: { ...body(false), data: { provider: 'object', object: OBJECT } } }, + }), + }, + ] as const; + /** The pair over the base's open container, its own old-shape row of `kind` stored, and the form switched off published from a package draft. */ + const publishedOverTheOldShape = async (shape: (typeof OLD_SHAPE_KINDS)[number]) => { + const b = await boot({ views: [container(true)] }, { canRollBack: shape.canRollBack }); + engines.push(b.engine); + expect(engineCanRollBackOf(b)).toBe(shape.canRollBack); + await b.install(PAIR); + await b.saveBeforeTheGate('view', PAIR, shape.item(), shape.row); + await closedOnBothDoors(b); + const before = await rawRows(b, 'view', shape.row, PAIR); + expect(before.length).toBe(1); + 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', shape.row, PAIR)).map((r) => r.metadata)).not.toEqual(before.map((r) => r.metadata)); + await closedOnBothDoors(b); + return { b, before, published }; + }; + /** Runs `fn` while the store refuses to restore any `view` version. */ + const withViewRestoreRefused = async (b: Booted, fn: () => Promise): Promise => { + 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 === 'restoreVersion') { + return async (ref: any, ...rest: any[]) => { + if (ref?.type === 'view') throw new Error('the store refused the view restore'); + return target.restoreVersion(ref, ...rest); + }; + } + const value = Reflect.get(target, prop, receiver); + return typeof value === 'function' ? value.bind(target) : value; + }, + }); + }; + try { + return await fn(); + } finally { + b.protocol.getOverlayRepo = realRepo; + } + }; + + for (const shape of OLD_SHAPE_KINDS) { + it(`a commit revert that cannot put back ${shape.kind} its \`form\` publish edited keeps the form as published and lists it in failed[] (ablate: the form item waits for the edited view rows)`, async () => { + const { b, published } = await publishedOverTheOldShape(shape); + const formAfterPublish = await rawRows(b, 'form', NAME, PAIR); + const viewAfterPublish = await rawRows(b, 'view', shape.row, PAIR); + expect(formAfterPublish.length).toBe(1); + const reverted: any = await withViewRestoreRefused(b, () => b.protocol.revertCommit({ commitId: published.commitId, packageId: PAIR })); + expect(reverted.success).toBe(false); + expect(reverted.failed.map((f: any) => [f.type, f.name])).toEqual([['view', shape.row], ['form', NAME]]); + expect(reverted.reverted).toEqual([]); + expect(await rawRows(b, 'form', NAME, PAIR)).toEqual(formAfterPublish); + expect(await rawRows(b, 'view', shape.row, PAIR)).toEqual(viewAfterPublish); + await closedOnBothDoors(b); + }); + + it(`CONTROL: the same revert with the store restoring puts back ${shape.kind} and removes the form`, async () => { + const { b, before, published } = await publishedOverTheOldShape(shape); + const reverted: any = await b.protocol.revertCommit({ commitId: published.commitId, packageId: PAIR }); + expect(reverted.failed).toEqual([]); + expect(reverted.reverted).toEqual([ + { type: 'view', name: shape.row, action: 'restored' }, + { type: 'form', name: NAME, action: 'removed' }, + ]); + expect(await rawRows(b, 'form', NAME, PAIR)).toEqual([]); + expect((await rawRows(b, 'view', shape.row, 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); From 3c769a1747e84ea6453800e658f2efe9c727fe09 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 16:28:29 +0000 Subject: [PATCH 38/50] wip: a form write names a stored row's forms as the form read names them Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .../src/protocol-diff-delete-load.ts | 2 +- .../src/protocol-form-reads.ts | 40 +++++++++++++------ .../src/protocol-form-writes.ts | 37 ++++++++++------- 3 files changed, 52 insertions(+), 27 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-diff-delete-load.ts b/packages/metadata-protocol/src/protocol-diff-delete-load.ts index 105892f8e92..f3fb2e6bdbf 100644 --- a/packages/metadata-protocol/src/protocol-diff-delete-load.ts +++ b/packages/metadata-protocol/src/protocol-diff-delete-load.ts @@ -457,7 +457,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; diff --git a/packages/metadata-protocol/src/protocol-form-reads.ts b/packages/metadata-protocol/src/protocol-form-reads.ts index 2305840bbff..18c5cf91b01 100644 --- a/packages/metadata-protocol/src/protocol-form-reads.ts +++ b/packages/metadata-protocol/src/protocol-form-reads.ts @@ -50,7 +50,7 @@ import { holdsServedOverlayCandidate, servedOverlayRowCandidates } from './proto 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 = +export type StoredHolding = | { readonly kind: 'form'; readonly item: Record } | { readonly kind: 'closed'; readonly reason: 'list' | 'unreadable' }; @@ -111,6 +111,31 @@ async function storedEntries(host: FormReadHost, type: 'form' | 'view'): Promise } } +/** + * [ADR-0159 D5] What one stored `view` row holds per name, under the names + * the read serves them as: an item row through the projection, a stored + * container as the items the runtime door expands it to (the same expansion + * the `view` list serves, {@link FormReadHost.expandStoredViewContainers}). + * So a member of a named container on another package's object is named + * `OBJECT.CONTAINER.KEY`, as the `view` list and the doors serve it. + * + * THE one naming of a stored row's forms: the `form` read + * ({@link storedFormPlaces}) and the `form` write's old-shape row removal + * (`oldShapeFormRowRemovals`) both ask it, so a `form` write removes only + * the old-shape row that carries that same form. + */ +export function storedViewRowHoldings( + host: Pick, + entry: { readonly data: unknown; readonly packageId: string | undefined }, +): Map { + if (!isAggregatedViewContainer(entry.data)) return viewHoldings(entry.data); + const holds = new Map(); + for (const { item } of host.expandStoredViewContainers('view', [entry])) { + for (const [name, holding] of viewHoldings(item)) holds.set(name, holding); + } + return holds; +} + /** Every stored row of both types as a {@link StoredFormPlace}. */ async function storedFormPlaces(host: FormReadHost): Promise { const places: StoredFormPlace[] = []; @@ -123,20 +148,11 @@ async function storedFormPlaces(host: FormReadHost): Promise 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); + places.push({ type: 'view', packageId: entry.packageId, entry, grain: 'item', holds: storedViewRowHoldings(host, entry) }); } for (const container of containers) { const projection = projectViewForms(container.data); - const holds = byContainer.get(container) ?? new Map(); + const holds = storedViewRowHoldings(host, container); // 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; diff --git a/packages/metadata-protocol/src/protocol-form-writes.ts b/packages/metadata-protocol/src/protocol-form-writes.ts index 061ae4c3043..efa21564701 100644 --- a/packages/metadata-protocol/src/protocol-form-writes.ts +++ b/packages/metadata-protocol/src/protocol-form-writes.ts @@ -16,13 +16,14 @@ * the write that removed them is undone. * * Each judges bodies through THE projection ({@link projectViewForms}), never - * by re-reading `formViews` by hand. + * by re-reading `formViews` by hand; the old-shape row removal names a stored + * row's forms as the `form` read names them ({@link storedViewRowHoldings}). */ 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'; +import { readEffectiveForms, storedViewRowHoldings, type FormReadHost, type StoredHolding } 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; @@ -204,30 +205,37 @@ export type AppliedOldShapeFormRowRemoval = OldShapeFormRowRemoval & { readonly * without the member (its lists byte-equal). ⛔ Form content only: a `view` * row that carries a LIST at the name is left untouched. * + * A form write removes only the old-shape row that carries that same form: + * which forms a row carries, and under which names, is `holdingsOf`'s answer, + * the `form` read's own naming ({@link storedViewRowHoldings}); ⛔ never a + * second naming of the members here. A member of another name is never + * removed, whatever its key. + * * `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`. + * (`{ name, data, packageId }`, `packageId` as the stored entry binds it). */ export function oldShapeFormRowRemovals( - rows: ReadonlyArray<{ name: string; data: unknown }>, + rows: ReadonlyArray<{ name: string; data: unknown; packageId: string | undefined }>, name: string, packageId: string | null, + holdingsOf: (entry: { data: unknown; packageId: string | undefined }) => ReadonlyMap, ): OldShapeFormRowRemoval[] { const out: OldShapeFormRowRemoval[] = []; + const carries = (data: unknown, rowPackage: string | undefined): boolean => + holdingsOf({ data, packageId: rowPackage }).get(name)?.kind === 'form'; 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 (!carries(body, row.packageId)) 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); + // Drop exactly the member that carries the form: re-name after each + // candidate removal, so the read's naming decides which one it is. + const without = (patch: Record) => !carries({ ...container, ...patch }, row.packageId); let removed = false; if (container.formViews && typeof container.formViews === 'object' && !Array.isArray(container.formViews)) { for (const key of Object.keys(container.formViews as object)) { @@ -261,21 +269,22 @@ export function oldShapeFormRowRemovals( * transaction has committed, and for the undo of that write. */ export async function applyOldShapeFormRowRemovals( - host: Pick, + 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; version: number | null }> = []; + const at: Array<{ name: string; data: unknown; packageId: string | undefined; 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, + name: entry.name, data: entry.data, packageId: entry.packageId, + hash: typeof row?.checksum === 'string' ? row.checksum : null, version: typeof row?.version === 'number' ? row.version : null, }); } - const removals: AppliedOldShapeFormRowRemoval[] = oldShapeFormRowRemovals(at, args.name, args.packageId) + const removals: AppliedOldShapeFormRowRemoval[] = oldShapeFormRowRemovals(at, args.name, args.packageId, (entry) => storedViewRowHoldings(host, entry)) .map((removal) => ({ ...removal, replacedVersion: at.find((row) => row.name === removal.row.name)?.version ?? null })); if (removals.length === 0) return removals; const repo = host.getOverlayRepo(); From 76ec9b3e4835142c9f598548d9da149fc7f017a7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 16:34:28 +0000 Subject: [PATCH 39/50] test(rest): a form write removes only the old-shape row that carries that form Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .../public-form-two-type-withdrawal.test.ts | 114 ++++++++++++++---- 1 file changed, 91 insertions(+), 23 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 1dcc1850a83..ae2ee81cab8 100644 --- a/packages/rest/src/public-form-two-type-withdrawal.test.ts +++ b/packages/rest/src/public-form-two-type-withdrawal.test.ts @@ -74,6 +74,24 @@ const INQUIRY = { }, }; +/** An object the pair itself ships ({@link pairShipsNote}), and the pair's form of it. */ +const NOTE_OBJECT = 'ftt_note'; +const NOTE_FORM = `${NOTE_OBJECT}.contact`; +const NOTE_SLUG = 'note-37086'; +const NOTE = { name: NOTE_OBJECT, label: 'Note', fields: INQUIRY.fields }; +const noteForm = (open: boolean | null) => ({ name: NOTE_FORM, object: NOTE_OBJECT, label: 'Note', ...body(open, NOTE_SLUG) }); +/** A stored container `intake` on `object`: a list, and `formViews.contact` switched off on `slug`. */ +const intakeContainer = (object: string, slug = SLUG) => ({ + name: 'intake', object, + list: { type: 'grid', columns: ['name', 'email'], data: { provider: 'object', object } }, + formViews: { contact: { ...body(false, slug), data: { provider: 'object', object } } }, +}); +/** The base's container whose `formViews['intake.contact']` is served as `OBJECT.intake.contact`. */ +const intakeMemberContainer = (open: boolean | null) => ({ + object: OBJECT, + formViews: { 'intake.contact': { ...body(open), data: { provider: 'object', object: OBJECT } } }, +}); + function mockServer() { const noop = () => {}; return { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; @@ -200,6 +218,16 @@ async function boot(ships: { forms?: unknown[]; views?: unknown[]; objects?: unk } type Booted = Awaited>; + +/** + * Registers {@link NOTE} as an object the pair ships: a container the pair + * stores on it is on its own package's object, so its members are served as + * `OBJECT.KEY`, the names a `form` item can take. + */ +async function pairShipsNote(b: Booted) { + b.engine.registry.registerObject(NOTE as any, PAIR); + await b.engine.syncSchemas(); +} const answered = (a: Answer) => [a.status, a.body?.code]; /** Both doors refuse with `404 FORM_NOT_FOUND`, and nothing was written. */ @@ -798,14 +826,14 @@ describe('[ADR-0159 D5] a `form` save, reset and delete: the old-shape row of th 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)] }); + it('a stored container is re-saved without the member the `form` write names, its lists byte-equal', async () => { + const b = await booted({}); 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'); + await pairShipsNote(b); + await b.saveBeforeTheGate('view', PAIR, intakeContainer(NOTE_OBJECT, NOTE_SLUG), '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)); + await b.saveInto('form', PAIR, noteForm(false), NOTE_FORM); const [after] = await rawRows(b, 'view', 'intake', PAIR); expect(after).toBeDefined(); const was = JSON.parse(before.metadata); @@ -814,6 +842,41 @@ describe('[ADR-0159 D5] a `form` save, reset and delete: the old-shape row of th expect(JSON.stringify(now.list)).toBe(JSON.stringify(was.list)); }); + it('a `form` write removes only the old-shape row that carries that form: a stored container whose member is served under another name stays as it was across the save, the publish and the reset, and the address stays closed (ablate: the `form` read\'s naming in the old-shape row removal)', async () => { + const b = await booted({ views: [intakeMemberContainer(true)] }); + await b.install(PAIR); + // Stored before the gate: on the base's object the pair's `formViews.contact` + // is served as `OBJECT.intake.contact`, switched off over the base's form of + // that name. + await b.seedRow('view', 'intake', PAIR, intakeContainer(OBJECT)); + await closedOnBothDoors(b); + const before = await rawRows(b, 'view', 'intake', PAIR); + expect(before.length).toBe(1); + // A form of another name, the one the member's key spells under the object alone. + await b.protocol.saveMetaItem({ type: 'form', name: NAME, packageId: PAIR, mode: 'draft', item: formItem(false, {}, OTHER_SLUG) }); + expect(await rawRows(b, 'view', 'intake', PAIR)).toEqual(before); + await b.protocol.publishMetaItem({ type: 'form', name: NAME, packageId: PAIR }); + expect(await rawRows(b, 'view', 'intake', PAIR)).toEqual(before); + await closedOnBothDoors(b); + await closedOnBothDoors(b, OTHER_SLUG); + const reset: any = await b.protocol.deleteMetaItem({ type: 'form', name: NAME, packageId: PAIR }); + expect(reset.success).toBe(true); + expect(await rawRows(b, 'view', 'intake', PAIR)).toEqual(before); + await closedOnBothDoors(b); + }); + + it('CONTROL: the `form` write of the name a stored container\'s member is served under re-saves the container without it, and the form is served as written', async () => { + const b = await booted({}); + await b.install(PAIR); + await pairShipsNote(b); + await b.seedRow('view', 'intake', PAIR, intakeContainer(NOTE_OBJECT, NOTE_SLUG)); + await closedOnBothDoors(b, NOTE_SLUG); + await b.saveInto('form', PAIR, noteForm(true), NOTE_FORM); + const [after] = await rawRows(b, 'view', 'intake', PAIR); + expect(JSON.parse(after.metadata).formViews).toBeUndefined(); + await openOnBothDoors(b, NOTE_SLUG); + }); + it('a `form` write that fails leaves both rows as they were', async () => { const b = await booted({ views: [container(true)] }); await b.install(PAIR); @@ -1054,16 +1117,20 @@ describe('[ADR-0159 D5, ADR-0067 D2 and D3] the undo of a `form` publish puts ba }); } - /** The pair's own old-shape row of the form, switched off: an item of the name, or a container `intake` that expands to it. */ + /** + * The pair's own old-shape row of a form, switched off, and the pair's `form` + * of that name: an item of the name over the base's open container, or a + * container `intake` on the pair's own object whose member is served under + * the form's name. + */ const OLD_SHAPE_KINDS = [ - { kind: 'an item-shaped row', row: NAME, canRollBack: true, item: () => viewItem(false, overrides) }, { - kind: 'a re-saved container', row: 'intake', canRollBack: false, - item: () => ({ - name: 'intake', object: OBJECT, - list: { type: 'grid', columns: ['name', 'email'], data: { provider: 'object', object: OBJECT } }, - formViews: { contact: { ...body(false), data: { provider: 'object', object: OBJECT } } }, - }), + kind: 'an item-shaped row', row: NAME, form: NAME, slug: SLUG, canRollBack: true, ownObject: false, + item: () => viewItem(false, overrides), formBody: () => formItem(false, overrides), + }, + { + kind: 'a re-saved container', row: 'intake', form: NOTE_FORM, slug: NOTE_SLUG, canRollBack: false, ownObject: true, + item: () => intakeContainer(NOTE_OBJECT, NOTE_SLUG), formBody: () => noteForm(false), }, ] as const; /** The pair over the base's open container, its own old-shape row of `kind` stored, and the form switched off published from a package draft. */ @@ -1072,15 +1139,16 @@ describe('[ADR-0159 D5, ADR-0067 D2 and D3] the undo of a `form` publish puts ba engines.push(b.engine); expect(engineCanRollBackOf(b)).toBe(shape.canRollBack); await b.install(PAIR); + if (shape.ownObject) await pairShipsNote(b); await b.saveBeforeTheGate('view', PAIR, shape.item(), shape.row); - await closedOnBothDoors(b); + await closedOnBothDoors(b, shape.slug); const before = await rawRows(b, 'view', shape.row, PAIR); expect(before.length).toBe(1); - await b.protocol.saveMetaItem({ type: 'form', name: NAME, packageId: PAIR, mode: 'draft', item: formItem(false, overrides) }); + await b.protocol.saveMetaItem({ type: 'form', name: shape.form, packageId: PAIR, mode: 'draft', item: shape.formBody() }); const published: any = await b.protocol.publishPackageDrafts({ packageId: PAIR }); expect(published.success, JSON.stringify(published.failed)).toBe(true); expect((await rawRows(b, 'view', shape.row, PAIR)).map((r) => r.metadata)).not.toEqual(before.map((r) => r.metadata)); - await closedOnBothDoors(b); + await closedOnBothDoors(b, shape.slug); return { b, before, published }; }; /** Runs `fn` while the store refuses to restore any `view` version. */ @@ -1111,16 +1179,16 @@ describe('[ADR-0159 D5, ADR-0067 D2 and D3] the undo of a `form` publish puts ba for (const shape of OLD_SHAPE_KINDS) { it(`a commit revert that cannot put back ${shape.kind} its \`form\` publish edited keeps the form as published and lists it in failed[] (ablate: the form item waits for the edited view rows)`, async () => { const { b, published } = await publishedOverTheOldShape(shape); - const formAfterPublish = await rawRows(b, 'form', NAME, PAIR); + const formAfterPublish = await rawRows(b, 'form', shape.form, PAIR); const viewAfterPublish = await rawRows(b, 'view', shape.row, PAIR); expect(formAfterPublish.length).toBe(1); const reverted: any = await withViewRestoreRefused(b, () => b.protocol.revertCommit({ commitId: published.commitId, packageId: PAIR })); expect(reverted.success).toBe(false); - expect(reverted.failed.map((f: any) => [f.type, f.name])).toEqual([['view', shape.row], ['form', NAME]]); + expect(reverted.failed.map((f: any) => [f.type, f.name])).toEqual([['view', shape.row], ['form', shape.form]]); expect(reverted.reverted).toEqual([]); - expect(await rawRows(b, 'form', NAME, PAIR)).toEqual(formAfterPublish); + expect(await rawRows(b, 'form', shape.form, PAIR)).toEqual(formAfterPublish); expect(await rawRows(b, 'view', shape.row, PAIR)).toEqual(viewAfterPublish); - await closedOnBothDoors(b); + await closedOnBothDoors(b, shape.slug); }); it(`CONTROL: the same revert with the store restoring puts back ${shape.kind} and removes the form`, async () => { @@ -1129,11 +1197,11 @@ describe('[ADR-0159 D5, ADR-0067 D2 and D3] the undo of a `form` publish puts ba expect(reverted.failed).toEqual([]); expect(reverted.reverted).toEqual([ { type: 'view', name: shape.row, action: 'restored' }, - { type: 'form', name: NAME, action: 'removed' }, + { type: 'form', name: shape.form, action: 'removed' }, ]); - expect(await rawRows(b, 'form', NAME, PAIR)).toEqual([]); + expect(await rawRows(b, 'form', shape.form, PAIR)).toEqual([]); expect((await rawRows(b, 'view', shape.row, PAIR)).map((r) => r.metadata)).toEqual(before.map((r) => r.metadata)); - await closedOnBothDoors(b); + await closedOnBothDoors(b, shape.slug); }); } From 23d766f6700f266d52677783437d66c15560f912 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 16:38:58 +0000 Subject: [PATCH 40/50] docs(metadata-protocol, rest): comments, titles and the changeset state the rules the doors keep Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .changeset/37086-form-metadata-type.md | 2 +- .../src/meta-overlay-cache.test.ts | 9 ++-- .../src/meta-overlay-cache.ts | 41 ++++++++----------- .../src/sys-metadata-repository.ts | 2 +- .../public-form-two-type-withdrawal.test.ts | 6 +-- 5 files changed, 26 insertions(+), 34 deletions(-) diff --git a/.changeset/37086-form-metadata-type.md b/.changeset/37086-form-metadata-type.md index 0f7ab462082..a3c788b7de8 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; 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/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, in the same transaction, only that package's old-shape row that carries that same form — named as the `form` read serves it (form content only: a list of the name, and a container member served under another name, are untouched); an undo puts back the rows the publish moved, for the revert of a package commit and for a refused package publish on a runtime that cannot roll back alike, and when one view row a commit edited cannot be put back, every form item of that commit is kept as published and each is listed in `failed[]`; 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 after a refused or undone publish the doors and the meta reads answer only committed state. - `@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.test.ts b/packages/metadata-protocol/src/meta-overlay-cache.test.ts index be0d7a2e534..b6ae380fb20 100644 --- a/packages/metadata-protocol/src/meta-overlay-cache.test.ts +++ b/packages/metadata-protocol/src/meta-overlay-cache.test.ts @@ -797,11 +797,10 @@ describe('[#10757 leg 6] §10 a write to any OTHER object does not retire the ov }); }); -describe('[ADR-0067 D2] §11 a transaction that rolls back retires the rows read inside it', () => { +describe('[ADR-0067 D2] §11 after a transaction that does not commit, the reads answer only committed rows', () => { /** * 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, + * through the seam, a read inside it, 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) => @@ -816,7 +815,7 @@ describe('[ADR-0067 D2] §11 a transaction that rolls back retires the rows read }); 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 () => { + it('rolled back: the next read answers the committed rows, and the error is rethrown as it came', async () => { const rows = clone(OVERLAY_ROWS); const h = makeHarness(rows); await h.protocol.getMetaItems({ type: 'object' }); @@ -835,7 +834,7 @@ describe('[ADR-0067 D2] §11 a transaction that rolls back retires the rows read expect(h.finds.length).toBeGreaterThan(perCall); }); - it('CONTROL: committed, the row read inside it keeps serving with zero reads', async () => { + it('CONTROL: committed, the committed row is answered with zero reads', async () => { const rows = clone(OVERLAY_ROWS); const h = makeHarness(rows); await transaction(h, rows, null); diff --git a/packages/metadata-protocol/src/meta-overlay-cache.ts b/packages/metadata-protocol/src/meta-overlay-cache.ts index a1647f3bb18..3fe28ff6785 100644 --- a/packages/metadata-protocol/src/meta-overlay-cache.ts +++ b/packages/metadata-protocol/src/meta-overlay-cache.ts @@ -104,10 +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. + * 4. **A transaction that does not commit** ({@link retireOverlayCacheOnRollback}): + * every transaction this package opens retires the cache when it fails + * after moving the generation, so the reads after it answer only + * committed rows. * * ⚠️ **`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 @@ -414,26 +414,19 @@ export function retireMetaOverlayCache(engine: unknown): number | undefined { * `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. + * The rule: after a transaction this package opened fails, every read answers + * only committed rows — the list and by-name reads and the registry hydration + * of `getMetaItems` alike — from the moment the rejection reaches the + * protocol, before the caller that opened the transaction reads or answers + * anything. + * + * 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 failed transaction that wrote + * no `sys_metadata` row costs the cache nothing. A commit retires nothing. The + * error is rethrown as it came. */ export async function retireOverlayCacheOnRollback(engine: unknown, open: () => Promise): Promise { const covered = engine !== null && typeof engine === 'object'; diff --git a/packages/metadata-protocol/src/sys-metadata-repository.ts b/packages/metadata-protocol/src/sys-metadata-repository.ts index 227ab11393c..382c00d6033 100644 --- a/packages/metadata-protocol/src/sys-metadata-repository.ts +++ b/packages/metadata-protocol/src/sys-metadata-repository.ts @@ -887,7 +887,7 @@ export class SysMetadataRepository implements MetadataRepository { */ private async withTxn(cb: (ctx: any) => Promise): Promise { if (typeof this.engine.transaction === 'function') { - // ADR-0067 D2: a rollback retires the overlay rows read inside it. + // ADR-0067 D2: after a transaction that does not commit, the reads answer only committed rows. return retireOverlayCacheOnRollback(this.engine, () => this.engine.transaction!(cb)); } return cb(undefined); 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 ae2ee81cab8..190e1d1e12d 100644 --- a/packages/rest/src/public-form-two-type-withdrawal.test.ts +++ b/packages/rest/src/public-form-two-type-withdrawal.test.ts @@ -376,7 +376,7 @@ describe('[ADR-0159 D6] the form doors read both types: a withdrawal in either c await closedOnBothDoors(b); }); - it('narrowing only: an open `form` override cannot re-open a form the base\'s old shape withdraws', async () => { + it('narrowing only: a form the base\'s old shape withdraws stays closed under an open `form` override', async () => { const b = await booted({ views: [container(false)] }); await closedOnBothDoors(b); await b.install(PAIR); @@ -1223,8 +1223,8 @@ describe('[ADR-0159 D5, ADR-0067 D2 and D3] the undo of a `form` publish puts ba 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. + // The overlay read cache ON, at its shipped default bound: after a refused + // batch the doors answer only committed state. vi.stubEnv('OS_METADATA_OVERLAY_CACHE_TTL_MS', '30000'); }); afterAll(async () => { From b30d6eb662d5ae4303bdf0ba2b62e09e16bc2182 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 17:51:22 +0000 Subject: [PATCH 41/50] chore(spec): regenerate export-origins and the view reference after merging main The merge deferred three generator-owned artifacts; check:generated --fix rebuilt packages/spec and rewrote exactly the two it proved stale (export-origins/, content/docs/references/ui/view.mdx). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- content/docs/references/ui/view.mdx | 16 ++++++++-------- packages/spec/export-origins/data.json | 2 ++ packages/spec/export-origins/system.json | 1 + 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/content/docs/references/ui/view.mdx b/content/docs/references/ui/view.mdx index b2559b43a93..2da0958bd6a 100644 --- a/content/docs/references/ui/view.mdx +++ b/content/docs/references/ui/view.mdx @@ -107,7 +107,7 @@ Appearance and visualization configuration | **startDateField** | `string` | ✅ | Field providing the event start date/time | | **endDateField** | `string` | optional | Field providing the event end date/time (defaults to a single-day event) | | **titleField** | `string` | optional | Field displayed as the event title. Omit to fall back to the record display name (ADR-0079 resolver chain) | -| **colorField** | `string` | optional | Field to derive each event color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()), else the calendar theme-aware palette color hashed from the value | +| **colorField** | `string` | optional | Field to derive each event color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()) or a Tailwind color utility class (bg-…, text-…), else the default event color: a value that is no color is never turned into one | | **allDayField** | `string` | optional | Field carrying the all-day flag for each event (names a boolean field, not a value): a record whose flag is true is drawn as an all-day band rather than at a clock time, and one whose flag is absent or false is not all-day. Omit to leave the renderer inference in place — an event with no end date draws as all-day | | **initialDate** | `string` | optional | Where the calendar opens: the month, week or day the active view mode shows that holds this date; omit it to open on today. A record anchor: `first_record` opens on the earliest start date (the startDateField value) among the records the view's filter selects, `next_record` on the earliest on or after the viewer's today (a `date` start field compares as a calendar day), and either opens on today when no record qualifies. Or a wrapped date-macro token, resolved each time the calendar opens: `{today}`, `{next_month_start}`, `{current_quarter_start}`, `{3_months_from_now}` (the full vocabulary is `DATE_MACRO_TOKENS` and the parameterised `DATE_MACRO_PARAM_RE` grammar in `@objectstack/spec/data`); a fixed calendar date is not accepted, because it goes stale as time passes. | @@ -548,7 +548,7 @@ Gallery/card view configuration | **titleField** | `string` | ✅ | Field displayed as the task title | | **progressField** | `string` | optional | Field providing the task completion percentage | | **dependenciesField** | `string` | optional | Field listing the task's predecessor (dependency) record ids | -| **colorField** | `string` | optional | Field to derive each bar color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()), else a semantic color token derived from the value | +| **colorField** | `string` | optional | Field to derive each bar color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()), else the default bar color: a value that is no color is never turned into one | | **parentField** | `string` | optional | Field holding the parent task id (builds the summary → step tree) | | **typeField** | `string` | optional | Field whose value maps to task/summary/milestone | | **baselineStartField** | `string` | optional | Baseline (planned) start field | @@ -1056,7 +1056,7 @@ An any-of group: `{ or: [rule, ...] }` matches a record when ANY of its rules ma | **startDateField** | `string` | ✅ | Field providing the event start date/time | | **endDateField** | `string` | optional | Field providing the event end date/time (defaults to a single-day event) | | **titleField** | `string` | optional | Field displayed as the event title. Omit to fall back to the record display name (ADR-0079 resolver chain) | -| **colorField** | `string` | optional | Field to derive each event color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()), else the calendar theme-aware palette color hashed from the value | +| **colorField** | `string` | optional | Field to derive each event color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()) or a Tailwind color utility class (bg-…, text-…), else the default event color: a value that is no color is never turned into one | | **allDayField** | `string` | optional | Field carrying the all-day flag for each event (names a boolean field, not a value): a record whose flag is true is drawn as an all-day band rather than at a clock time, and one whose flag is absent or false is not all-day. Omit to leave the renderer inference in place — an event with no end date draws as all-day | | **initialDate** | `string` | optional | Where the calendar opens: the month, week or day the active view mode shows that holds this date; omit it to open on today. A record anchor: `first_record` opens on the earliest start date (the startDateField value) among the records the view's filter selects, `next_record` on the earliest on or after the viewer's today (a `date` start field compares as a calendar day), and either opens on today when no record qualifies. Or a wrapped date-macro token, resolved each time the calendar opens: `{today}`, `{next_month_start}`, `{current_quarter_start}`, `{3_months_from_now}` (the full vocabulary is `DATE_MACRO_TOKENS` and the parameterised `DATE_MACRO_PARAM_RE` grammar in `@objectstack/spec/data`); a fixed calendar date is not accepted, because it goes stale as time passes. | @@ -1069,7 +1069,7 @@ An any-of group: `{ or: [rule, ...] }` matches a record when ANY of its rules ma | **titleField** | `string` | ✅ | Field displayed as the task title | | **progressField** | `string` | optional | Field providing the task completion percentage | | **dependenciesField** | `string` | optional | Field listing the task's predecessor (dependency) record ids | -| **colorField** | `string` | optional | Field to derive each bar color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()), else a semantic color token derived from the value | +| **colorField** | `string` | optional | Field to derive each bar color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()), else the default bar color: a value that is no color is never turned into one | | **parentField** | `string` | optional | Field holding the parent task id (builds the summary → step tree) | | **typeField** | `string` | optional | Field whose value maps to task/summary/milestone | | **baselineStartField** | `string` | optional | Baseline (planned) start field | @@ -1524,7 +1524,7 @@ An any-of group: `{ or: [rule, ...] }` matches a record when ANY of its rules ma | **startDateField** | `string` | ✅ | Field providing the event start date/time | | **endDateField** | `string` | optional | Field providing the event end date/time (defaults to a single-day event) | | **titleField** | `string` | optional | Field displayed as the event title. Omit to fall back to the record display name (ADR-0079 resolver chain) | -| **colorField** | `string` | optional | Field to derive each event color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()), else the calendar theme-aware palette color hashed from the value | +| **colorField** | `string` | optional | Field to derive each event color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()) or a Tailwind color utility class (bg-…, text-…), else the default event color: a value that is no color is never turned into one | | **allDayField** | `string` | optional | Field carrying the all-day flag for each event (names a boolean field, not a value): a record whose flag is true is drawn as an all-day band rather than at a clock time, and one whose flag is absent or false is not all-day. Omit to leave the renderer inference in place — an event with no end date draws as all-day | | **initialDate** | `string` | optional | Where the calendar opens: the month, week or day the active view mode shows that holds this date; omit it to open on today. A record anchor: `first_record` opens on the earliest start date (the startDateField value) among the records the view's filter selects, `next_record` on the earliest on or after the viewer's today (a `date` start field compares as a calendar day), and either opens on today when no record qualifies. Or a wrapped date-macro token, resolved each time the calendar opens: `{today}`, `{next_month_start}`, `{current_quarter_start}`, `{3_months_from_now}` (the full vocabulary is `DATE_MACRO_TOKENS` and the parameterised `DATE_MACRO_PARAM_RE` grammar in `@objectstack/spec/data`); a fixed calendar date is not accepted, because it goes stale as time passes. | @@ -1537,7 +1537,7 @@ An any-of group: `{ or: [rule, ...] }` matches a record when ANY of its rules ma | **titleField** | `string` | ✅ | Field displayed as the task title | | **progressField** | `string` | optional | Field providing the task completion percentage | | **dependenciesField** | `string` | optional | Field listing the task's predecessor (dependency) record ids | -| **colorField** | `string` | optional | Field to derive each bar color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()), else a semantic color token derived from the value | +| **colorField** | `string` | optional | Field to derive each bar color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()), else the default bar color: a value that is no color is never turned into one | | **parentField** | `string` | optional | Field holding the parent task id (builds the summary → step tree) | | **typeField** | `string` | optional | Field whose value maps to task/summary/milestone | | **baselineStartField** | `string` | optional | Baseline (planned) start field | @@ -2539,7 +2539,7 @@ This schema accepts one of the following structures: | **isPinned** | `boolean` | optional | Console round-trip: the view is pinned in the object's view switcher. Written by the console's pin toggle through the `view` metadata API and read back to draw the pinned group. Stored on the view's row, which has no per-user scope. Not authored. | | **sortOrder** | `integer` | optional | Console round-trip: the view's position among the object's saved views in the switcher, 0-based and counted over saved views only (a code-defined view carries none). Written by the console's drag-reorder and read back to order the tabs. Not authored: `order` is the authored default position. | | **visibility** | `Enum<'private' \| 'team' \| 'organization' \| 'public'>` | optional | Console round-trip: the group the switcher files this view's tab under (private, team, organization or public). Display grouping only, NOT access control: nothing restricts who can list or open the view by this value. No console control sets it; the console carries a stored value forward when it re-saves the row. Not authored. | -| **columnState** | `never` | optional | [REMOVED] `view.columnState` was removed in @objectstack/spec 18.7.0 (ADR-0049 enforce-or-remove) — it held one column order and set of widths on a shared view row; nothing writes it any more, and a stored layout is no longer applied, so every reader sees the view's own column order and widths. The console keeps column widths in each reader's browser and saves a column order into the view itself. Delete the key. To ship a column order, list `columns` in that order (or set `fieldOrder`); to ship a width, set `width` on the column. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +| **columnState** | `never` | optional | [REMOVED] `view.columnState` was removed in @objectstack/spec 19.0.0 (ADR-0049 enforce-or-remove) — it held one column order and set of widths on a shared view row; nothing writes it any more, and a stored layout is no longer applied, so every reader sees the view's own column order and widths. The console keeps column widths in each reader's browser and saves a column order into the view itself. Delete the key. To ship a column order, list `columns` in that order (or set `fieldOrder`); to ship a width, set `width` on the column. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **options** | `never` | optional | Refused: a view item record carries no top-level `options` bag. Its per-kind blocks live under `config` (`config.kanban`, `config.timeline`, …); the legacy `options.KIND` bag belongs to the flattened list overlay only. | ### Nested Shape: `ViewItemWire[viewKind='list'].config` @@ -2639,7 +2639,7 @@ This schema accepts one of the following structures: | **isPinned** | `boolean` | optional | Console round-trip: the view is pinned in the object's view switcher. Written by the console's pin toggle through the `view` metadata API and read back to draw the pinned group. Stored on the view's row, which has no per-user scope. Not authored. | | **sortOrder** | `integer` | optional | Console round-trip: the view's position among the object's saved views in the switcher, 0-based and counted over saved views only (a code-defined view carries none). Written by the console's drag-reorder and read back to order the tabs. Not authored: `order` is the authored default position. | | **visibility** | `Enum<'private' \| 'team' \| 'organization' \| 'public'>` | optional | Console round-trip: the group the switcher files this view's tab under (private, team, organization or public). Display grouping only, NOT access control: nothing restricts who can list or open the view by this value. No console control sets it; the console carries a stored value forward when it re-saves the row. Not authored. | -| **columnState** | `never` | optional | [REMOVED] `view.columnState` was removed in @objectstack/spec 18.7.0 (ADR-0049 enforce-or-remove) — it held one column order and set of widths on a shared view row; nothing writes it any more, and a stored layout is no longer applied, so every reader sees the view's own column order and widths. The console keeps column widths in each reader's browser and saves a column order into the view itself. Delete the key. To ship a column order, list `columns` in that order (or set `fieldOrder`); to ship a width, set `width` on the column. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +| **columnState** | `never` | optional | [REMOVED] `view.columnState` was removed in @objectstack/spec 19.0.0 (ADR-0049 enforce-or-remove) — it held one column order and set of widths on a shared view row; nothing writes it any more, and a stored layout is no longer applied, so every reader sees the view's own column order and widths. The console keeps column widths in each reader's browser and saves a column order into the view itself. Delete the key. To ship a column order, list `columns` in that order (or set `fieldOrder`); to ship a width, set `width` on the column. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **options** | `never` | optional | Refused: a view item record carries no top-level `options` bag. Its per-kind blocks live under `config` (`config.kanban`, `config.timeline`, …); the legacy `options.KIND` bag belongs to the flattened list overlay only. | ### Nested Shape: `ViewItemWire[viewKind='form'].config` diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index cb0732fd521..3378dc1e5e7 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -816,6 +816,7 @@ "STACK_KEY_GUIDANCE": "src/data/authoring-key-lint.ts#STACK_KEY_GUIDANCE (const)", "STACK_RUNTIME_MEMBERS": "src/data/authoring-key-lint.ts#STACK_RUNTIME_MEMBERS (const)", "STANDARD_UNITS": "src/data/standard-units.ts#STANDARD_UNITS (const)", + "STANDARD_UNIT_NAMES": "src/data/standard-units.ts#STANDARD_UNIT_NAMES (const)", "STRING_STORED_COMPARAND_DOOR_FAMILIES": "src/data/filter-string-stored-comparand-declared-type.ts#STRING_STORED_COMPARAND_DOOR_FAMILIES (const)", "STRING_STORED_COMPARAND_DOOR_LIST_OPERATORS": "src/data/filter-string-stored-comparand-declared-type.ts#STRING_STORED_COMPARAND_DOOR_LIST_OPERATORS (const)", "STRING_STORED_COMPARAND_DOOR_SCALAR_OPERATORS": "src/data/filter-string-stored-comparand-declared-type.ts#STRING_STORED_COMPARAND_DOOR_SCALAR_OPERATORS (const)", @@ -1221,6 +1222,7 @@ "resolveUserActionTransfer": "src/data/user-action-transfer.ts#resolveUserActionTransfer (function)", "seedFile": "src/data/seed-file.zod.ts#seedFile (function)", "sequenceWidth": "src/data/autonumber-format.ts#sequenceWidth (function)", + "standardUnitName": "src/data/standard-units.ts#standardUnitName (function)", "standardUnitOf": "src/data/standard-units.ts#standardUnitOf (function)", "storedHomeAmountSourceOf": "src/data/record-currency-path.ts#storedHomeAmountSourceOf (function)", "stringStoredComparandDoorVerdict": "src/data/filter-string-stored-comparand-declared-type.ts#stringStoredComparandDoorVerdict (function)", diff --git a/packages/spec/export-origins/system.json b/packages/spec/export-origins/system.json index d787d751fe0..150791b22ce 100644 --- a/packages/spec/export-origins/system.json +++ b/packages/spec/export-origins/system.json @@ -883,6 +883,7 @@ "resolveMetadataTypeDescription": "src/system/i18n-resolver.ts#resolveMetadataTypeDescription (function)", "resolveMetadataTypeLabel": "src/system/i18n-resolver.ts#resolveMetadataTypeLabel (function)", "resolveObjectFieldLabels": "src/system/i18n-resolver.ts#resolveObjectFieldLabels (function)", + "resolveObjectMilestoneSummary": "src/system/i18n-resolver.ts#resolveObjectMilestoneSummary (function)", "resolveSettingsActionConfirm": "src/system/i18n-resolver.ts#resolveSettingsActionConfirm (function)", "resolveSettingsActionLabel": "src/system/i18n-resolver.ts#resolveSettingsActionLabel (function)", "resolveSettingsActionSuccess": "src/system/i18n-resolver.ts#resolveSettingsActionSuccess (function)", From 62923e91e325bfb54750c212ad95112ca62b45fd Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:05:45 +0000 Subject: [PATCH 42/50] chore(spec): regenerate the spec artifacts after merging the rename branch The merge deferred seven generator-owned artifacts; check:generated --fix rebuilt packages/spec and rewrote the four it proved stale (api-surface/, export-origins/, content/docs/references/**, the strictness-ledger counts: system/ 409 + 1 + 1 = 411, both sides' sites). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .../references/api/package-api-assembled.mdx | 4 ++-- content/docs/references/api/protocol.mdx | 14 +++++++++++++- content/docs/references/system/translation.mdx | 11 +++++++++++ content/docs/references/ui/view.mdx | 16 ++++++++-------- .../system.md | 2 +- packages/spec/api-surface/system.json | 1 + packages/spec/authorable-surface/system.json | 1 + packages/spec/export-origins/system.json | 1 + 8 files changed, 38 insertions(+), 12 deletions(-) diff --git a/content/docs/references/api/package-api-assembled.mdx b/content/docs/references/api/package-api-assembled.mdx index b744b9b6612..b526e58983c 100644 --- a/content/docs/references/api/package-api-assembled.mdx +++ b/content/docs/references/api/package-api-assembled.mdx @@ -138,7 +138,7 @@ Installed package row whose manifest is the assembled package body | **agents** | `{ name: string; label: string; avatar?: string; role: string; … }[]` | optional | AI Agents — platform-internal (ADR-0063 §2): the kernel ships exactly two (ask/build); third parties extend via skills, not agents | | **tools** | `{ name: string; label: string; description: string; parameters: Record; … }[]` | optional | AI Tool metadata records — optional refinement layer, never required: the default path is skills referencing platform tools or materialised action_`` tools (ADR-0109) | | **skills** | `{ name: string; label: string; description?: string; surface?: Enum<'ask' \| 'build' \| 'both'>; … }[]` | optional | AI Skills (reusable capability bundles — the third-party AI extension primitive, ADR-0063) | -| **aiContexts** | `{ name: string; label: string; object: string; fields?: string[]; … }[]` | optional | AI context packs — the material of one record handed to a model, read as the caller by get_record_context (ADR-0160), which is served where `requires` includes `record-context` | +| **aiContexts** | `{ name: string; label: string; object: string; fields?: string[]; … }[]` | optional | AI context packs — the material of one record handed to a model, read as the caller by get_record_context (ADR-0160). A host serves that tool only when it mounts the record-context service: the CLI mounts it where `requires` includes `record-context`, and a host that composes its own kernel lists `RecordContextServicePlugin` in `plugins` | | **hooks** | `{ name: string; label?: string; object: string \| string[]; events: Enum<'beforeFind' \| 'afterFind' \| 'beforeInsert' \| 'afterInsert' \| 'beforeUpdate' \| …>[]; … }[]` | optional | Object Lifecycle Hooks, as a JSON document carries them | | **mappings** | `{ name: string; label?: string; sourceFormat?: Enum<'csv' \| 'json' \| 'xml' \| 'sql'>; targetObject: string; … }[]` | optional | Data Import/Export Mappings | | **analyticsCubes** | `{ name: string; title?: string; description?: string; sql: string; … }[]` | optional | Analytics Semantic Layer Cubes | @@ -390,7 +390,7 @@ This schema accepts one of the following structures: | **agents** | `{ name: string; label: string; avatar?: string; role: string; … }[]` | optional | AI Agents — platform-internal (ADR-0063 §2): the kernel ships exactly two (ask/build); third parties extend via skills, not agents | | **tools** | `{ name: string; label: string; description: string; parameters: Record; … }[]` | optional | AI Tool metadata records — optional refinement layer, never required: the default path is skills referencing platform tools or materialised action_`` tools (ADR-0109) | | **skills** | `{ name: string; label: string; description?: string; surface?: Enum<'ask' \| 'build' \| 'both'>; … }[]` | optional | AI Skills (reusable capability bundles — the third-party AI extension primitive, ADR-0063) | -| **aiContexts** | `{ name: string; label: string; object: string; fields?: string[]; … }[]` | optional | AI context packs — the material of one record handed to a model, read as the caller by get_record_context (ADR-0160), which is served where `requires` includes `record-context` | +| **aiContexts** | `{ name: string; label: string; object: string; fields?: string[]; … }[]` | optional | AI context packs — the material of one record handed to a model, read as the caller by get_record_context (ADR-0160). A host serves that tool only when it mounts the record-context service: the CLI mounts it where `requires` includes `record-context`, and a host that composes its own kernel lists `RecordContextServicePlugin` in `plugins` | | **hooks** | `{ name: string; label?: string; object: string \| string[]; events: Enum<'beforeFind' \| 'afterFind' \| 'beforeInsert' \| 'afterInsert' \| 'beforeUpdate' \| …>[]; … }[]` | optional | Object Lifecycle Hooks, as a JSON document carries them | | **mappings** | `{ name: string; label?: string; sourceFormat?: Enum<'csv' \| 'json' \| 'xml' \| 'sql'>; targetObject: string; … }[]` | optional | Data Import/Export Mappings | | **analyticsCubes** | `{ name: string; title?: string; description?: string; sql: string; … }[]` | optional | Analytics Semantic Layer Cubes | diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index bf506815d7c..b04f5b01148 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -224,7 +224,7 @@ const result = AiAgentCapabilitiesSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **models** | `(string \| { id: string; label: string; default: boolean; costMultiplier?: number })[]` | ✅ | Models this system offers | +| **models** | `(string \| { id: string; label: string; tierLabel?: string; default: boolean; … })[]` | ✅ | Models this system offers | | **defaultModel** | `string` | optional | Default model id, when the service reports one | ### Nested Shape: `AiModelsResponse.models[number]` @@ -233,6 +233,7 @@ const result = AiAgentCapabilitiesSchema.parse(data); | :--- | :--- | :--- | :--- | | **id** | `string` | ✅ | Model id | | **label** | `string` | ✅ | Display label for the picker | +| **tierLabel** | `string` | optional | Display name of the model's tier alone (for example 'Fast'), in the language the response is served in. The closed picker shows it in place of `label`, which may also carry the model's name; the open list keeps `label`. Optional: absent, the picker shows `label` as before. | | **default** | `boolean` | ✅ | Whether this is the environment default | | **costMultiplier** | `number` | optional | Factor by which one message on this model draws on the AI allowance, compared with one message on the environment's default model: 20 means one message here uses as much allowance as 20 on the default. Normalised to the default: the entry with `default: true` carries 1, and every other entry carries its model's cost weight divided by the default model's cost weight. Written by cloud service-ai's GET /api/v1/ai/models; absent when the service reports none, and then nothing is shown for it. | @@ -569,6 +570,7 @@ A write-path strip event: caller-supplied fields legally dropped from the payloa | **message** | `string` | ✅ | Human-readable message — a validation rule's author-written text where one exists. | | **rule** | `string` | optional | The `name` of the ADVISORY validation rule this finding reports. Present only on an advisory rule hit. | | **severity** | `Enum<'warning' \| 'info'>` | optional | The advisory rule's declared severity, `warning` or `info`. Present only on an advisory rule hit. | +| **scope** | `{ field: string; value: string }[]` | optional | The row columns a scoped lookup cell was resolved within, each with the cell the row gave it, in the order the refusal names them. Present only on an import cell error whose `code` is `reference_out_of_scope`: the value matches a record, but none within these columns, so a client can name the scoping column and its cell in its own text instead of parsing `message`. | --- @@ -631,6 +633,7 @@ A write-path strip event: caller-supplied fields legally dropped from the payloa | **message** | `string` | ✅ | Human-readable message — a validation rule's author-written text where one exists. | | **rule** | `string` | optional | The `name` of the ADVISORY validation rule this finding reports. Present only on an advisory rule hit. | | **severity** | `Enum<'warning' \| 'info'>` | optional | The advisory rule's declared severity, `warning` or `info`. Present only on an advisory rule hit. | +| **scope** | `{ field: string; value: string }[]` | optional | The row columns a scoped lookup cell was resolved within, each with the cell the row gave it, in the order the refusal names them. Present only on an import cell error whose `code` is `reference_out_of_scope`: the value matches a record, but none within these columns, so a client can name the scoping column and its cell in its own text instead of parsing `message`. | --- @@ -3384,6 +3387,7 @@ A write-path strip event: caller-supplied fields legally dropped from the payloa | **message** | `string` | ✅ | Human-readable message — a validation rule's author-written text where one exists. | | **rule** | `string` | optional | The `name` of the ADVISORY validation rule this finding reports. Present only on an advisory rule hit. | | **severity** | `Enum<'warning' \| 'info'>` | optional | The advisory rule's declared severity, `warning` or `info`. Present only on an advisory rule hit. | +| **scope** | `{ field: string; value: string }[]` | optional | The row columns a scoped lookup cell was resolved within, each with the cell the row gave it, in the order the refusal names them. Present only on an import cell error whose `code` is `reference_out_of_scope`: the value matches a record, but none within these columns, so a client can name the scoping column and its cell in its own text instead of parsing `message`. | --- @@ -3522,6 +3526,14 @@ A write-path strip event: caller-supplied fields legally dropped from the payloa | **message** | `string` | ✅ | Human-readable message — a validation rule's author-written text where one exists. | | **rule** | `string` | optional | The `name` of the ADVISORY validation rule this finding reports. Present only on an advisory rule hit. | | **severity** | `Enum<'warning' \| 'info'>` | optional | The advisory rule's declared severity, `warning` or `info`. Present only on an advisory rule hit. | +| **scope** | `{ field: string; value: string }[]` | optional | The row columns a scoped lookup cell was resolved within, each with the cell the row gave it, in the order the refusal names them. Present only on an import cell error whose `code` is `reference_out_of_scope`: the value matches a record, but none within these columns, so a client can name the scoping column and its cell in its own text instead of parsing `message`. | + +### Nested Shape: `ValidateDataIssue.scope[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **field** | `string` | ✅ | API name of the row column that scoped the lookup. | +| **value** | `string` | ✅ | The cell the row gave that column, as the importer typed it. | --- diff --git a/content/docs/references/system/translation.mdx b/content/docs/references/system/translation.mdx index 7549172c623..293f2791c8d 100644 --- a/content/docs/references/system/translation.mdx +++ b/content/docs/references/system/translation.mdx @@ -100,6 +100,7 @@ Translation data for a single object | **_tabs** | `Record` | optional | Filter-preset tab translations keyed by tab name | | **_relatedLists** | `Record` | optional | Record-page related list titles keyed by the relatedLists entry list name | | **_validations** | `Record` | optional | Custom validation-rule messages keyed by rule name (`ValidationRuleSchema.name`) | +| **_milestones** | `Record>` | optional | Activity-milestone summary translations keyed by the watched field, then by the value the milestone fires on | ### Nested Shape: `ObjectTranslationData.fields[string]` @@ -169,6 +170,12 @@ Translation data for a single field | :--- | :--- | :--- | :--- | | **message** | `string` | optional | Translated rejection message — overlays the rule's authored `message` on every rejected write | +### Nested Shape: `ObjectTranslationData._milestones[string][string]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **summary** | `string` | optional | Translated milestone summary template — the same `{field}` tokens as the milestone's authored `summary` | + --- @@ -225,6 +232,7 @@ Translation data for a single object | **_tabs** | `Record` | optional | Filter-preset tab translations keyed by tab name | | **_relatedLists** | `Record` | optional | Record-page related list titles keyed by the relatedLists entry list name | | **_validations** | `Record` | optional | Custom validation-rule messages keyed by rule name (`ValidationRuleSchema.name`) | +| **_milestones** | `Record>` | optional | Activity-milestone summary translations keyed by the watched field, then by the value the milestone fires on | ### Nested Shape: `PlatformTranslationData.picklists[string]` @@ -427,6 +435,7 @@ Translation data for a single object | **_tabs** | `Record` | optional | Filter-preset tab translations keyed by tab name | | **_relatedLists** | `Record` | optional | Record-page related list titles keyed by the relatedLists entry list name | | **_validations** | `Record` | optional | Custom validation-rule messages keyed by rule name (`ValidationRuleSchema.name`) | +| **_milestones** | `Record>` | optional | Activity-milestone summary translations keyed by the watched field, then by the value the milestone fires on | ### Nested Shape: `ServedTranslationData.picklists[string]` @@ -692,6 +701,7 @@ Translation data for a single object | **_tabs** | `Record` | optional | Filter-preset tab translations keyed by tab name | | **_relatedLists** | `Record` | optional | Record-page related list titles keyed by the relatedLists entry list name | | **_validations** | `Record` | optional | Custom validation-rule messages keyed by rule name (`ValidationRuleSchema.name`) | +| **_milestones** | `Record>` | optional | Activity-milestone summary translations keyed by the watched field, then by the value the milestone fires on | ### Nested Shape: `TranslationData.picklists[string]` @@ -926,6 +936,7 @@ Translation data for a single object | **_tabs** | `Record` | optional | Filter-preset tab translations keyed by tab name | | **_relatedLists** | `Record` | optional | Record-page related list titles keyed by the relatedLists entry list name | | **_validations** | `Record` | optional | Custom validation-rule messages keyed by rule name (`ValidationRuleSchema.name`) | +| **_milestones** | `Record>` | optional | Activity-milestone summary translations keyed by the watched field, then by the value the milestone fires on | ### Nested Shape: `TranslationItem.picklists[string]` diff --git a/content/docs/references/ui/view.mdx b/content/docs/references/ui/view.mdx index 8d6d9ba868c..a13c131e0b3 100644 --- a/content/docs/references/ui/view.mdx +++ b/content/docs/references/ui/view.mdx @@ -107,7 +107,7 @@ Appearance and visualization configuration | **startDateField** | `string` | ✅ | Field providing the event start date/time | | **endDateField** | `string` | optional | Field providing the event end date/time (defaults to a single-day event) | | **titleField** | `string` | optional | Field displayed as the event title. Omit to fall back to the record display name (ADR-0079 resolver chain) | -| **colorField** | `string` | optional | Field to derive each event color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()), else the calendar theme-aware palette color hashed from the value | +| **colorField** | `string` | optional | Field to derive each event color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()) or a Tailwind color utility class (bg-…, text-…), else the default event color: a value that is no color is never turned into one | | **allDayField** | `string` | optional | Field carrying the all-day flag for each event (names a boolean field, not a value): a record whose flag is true is drawn as an all-day band rather than at a clock time, and one whose flag is absent or false is not all-day. Omit to leave the renderer inference in place — an event with no end date draws as all-day | | **initialDate** | `string` | optional | Where the calendar opens: the month, week or day the active view mode shows that holds this date; omit it to open on today. A record anchor: `first_record` opens on the earliest start date (the startDateField value) among the records the view's filter selects, `next_record` on the earliest on or after the viewer's today (a `date` start field compares as a calendar day), and either opens on today when no record qualifies. Or a wrapped date-macro token, resolved each time the calendar opens: `{today}`, `{next_month_start}`, `{current_quarter_start}`, `{3_months_from_now}` (the full vocabulary is `DATE_MACRO_TOKENS` and the parameterised `DATE_MACRO_PARAM_RE` grammar in `@objectstack/spec/data`); a fixed calendar date is not accepted, because it goes stale as time passes. | @@ -688,7 +688,7 @@ Gallery/card view configuration | **titleField** | `string` | ✅ | Field displayed as the task title | | **progressField** | `string` | optional | Field providing the task completion percentage | | **dependenciesField** | `string` | optional | Field listing the task's predecessor (dependency) record ids | -| **colorField** | `string` | optional | Field to derive each bar color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()), else a semantic color token derived from the value | +| **colorField** | `string` | optional | Field to derive each bar color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()), else the default bar color: a value that is no color is never turned into one | | **parentField** | `string` | optional | Field holding the parent task id (builds the summary → step tree) | | **typeField** | `string` | optional | Field whose value maps to task/summary/milestone | | **baselineStartField** | `string` | optional | Baseline (planned) start field | @@ -1196,7 +1196,7 @@ An any-of group: `{ or: [rule, ...] }` matches a record when ANY of its rules ma | **startDateField** | `string` | ✅ | Field providing the event start date/time | | **endDateField** | `string` | optional | Field providing the event end date/time (defaults to a single-day event) | | **titleField** | `string` | optional | Field displayed as the event title. Omit to fall back to the record display name (ADR-0079 resolver chain) | -| **colorField** | `string` | optional | Field to derive each event color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()), else the calendar theme-aware palette color hashed from the value | +| **colorField** | `string` | optional | Field to derive each event color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()) or a Tailwind color utility class (bg-…, text-…), else the default event color: a value that is no color is never turned into one | | **allDayField** | `string` | optional | Field carrying the all-day flag for each event (names a boolean field, not a value): a record whose flag is true is drawn as an all-day band rather than at a clock time, and one whose flag is absent or false is not all-day. Omit to leave the renderer inference in place — an event with no end date draws as all-day | | **initialDate** | `string` | optional | Where the calendar opens: the month, week or day the active view mode shows that holds this date; omit it to open on today. A record anchor: `first_record` opens on the earliest start date (the startDateField value) among the records the view's filter selects, `next_record` on the earliest on or after the viewer's today (a `date` start field compares as a calendar day), and either opens on today when no record qualifies. Or a wrapped date-macro token, resolved each time the calendar opens: `{today}`, `{next_month_start}`, `{current_quarter_start}`, `{3_months_from_now}` (the full vocabulary is `DATE_MACRO_TOKENS` and the parameterised `DATE_MACRO_PARAM_RE` grammar in `@objectstack/spec/data`); a fixed calendar date is not accepted, because it goes stale as time passes. | @@ -1209,7 +1209,7 @@ An any-of group: `{ or: [rule, ...] }` matches a record when ANY of its rules ma | **titleField** | `string` | ✅ | Field displayed as the task title | | **progressField** | `string` | optional | Field providing the task completion percentage | | **dependenciesField** | `string` | optional | Field listing the task's predecessor (dependency) record ids | -| **colorField** | `string` | optional | Field to derive each bar color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()), else a semantic color token derived from the value | +| **colorField** | `string` | optional | Field to derive each bar color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()), else the default bar color: a value that is no color is never turned into one | | **parentField** | `string` | optional | Field holding the parent task id (builds the summary → step tree) | | **typeField** | `string` | optional | Field whose value maps to task/summary/milestone | | **baselineStartField** | `string` | optional | Baseline (planned) start field | @@ -1664,7 +1664,7 @@ An any-of group: `{ or: [rule, ...] }` matches a record when ANY of its rules ma | **startDateField** | `string` | ✅ | Field providing the event start date/time | | **endDateField** | `string` | optional | Field providing the event end date/time (defaults to a single-day event) | | **titleField** | `string` | optional | Field displayed as the event title. Omit to fall back to the record display name (ADR-0079 resolver chain) | -| **colorField** | `string` | optional | Field to derive each event color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()), else the calendar theme-aware palette color hashed from the value | +| **colorField** | `string` | optional | Field to derive each event color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()) or a Tailwind color utility class (bg-…, text-…), else the default event color: a value that is no color is never turned into one | | **allDayField** | `string` | optional | Field carrying the all-day flag for each event (names a boolean field, not a value): a record whose flag is true is drawn as an all-day band rather than at a clock time, and one whose flag is absent or false is not all-day. Omit to leave the renderer inference in place — an event with no end date draws as all-day | | **initialDate** | `string` | optional | Where the calendar opens: the month, week or day the active view mode shows that holds this date; omit it to open on today. A record anchor: `first_record` opens on the earliest start date (the startDateField value) among the records the view's filter selects, `next_record` on the earliest on or after the viewer's today (a `date` start field compares as a calendar day), and either opens on today when no record qualifies. Or a wrapped date-macro token, resolved each time the calendar opens: `{today}`, `{next_month_start}`, `{current_quarter_start}`, `{3_months_from_now}` (the full vocabulary is `DATE_MACRO_TOKENS` and the parameterised `DATE_MACRO_PARAM_RE` grammar in `@objectstack/spec/data`); a fixed calendar date is not accepted, because it goes stale as time passes. | @@ -1677,7 +1677,7 @@ An any-of group: `{ or: [rule, ...] }` matches a record when ANY of its rules ma | **titleField** | `string` | ✅ | Field displayed as the task title | | **progressField** | `string` | optional | Field providing the task completion percentage | | **dependenciesField** | `string` | optional | Field listing the task's predecessor (dependency) record ids | -| **colorField** | `string` | optional | Field to derive each bar color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()), else a semantic color token derived from the value | +| **colorField** | `string` | optional | Field to derive each bar color from (it names a field, not a color): the option color declared on that field for the record value, else the value itself when it already is a color literal (hex, rgb() or hsl()), else the default bar color: a value that is no color is never turned into one | | **parentField** | `string` | optional | Field holding the parent task id (builds the summary → step tree) | | **typeField** | `string` | optional | Field whose value maps to task/summary/milestone | | **baselineStartField** | `string` | optional | Baseline (planned) start field | @@ -2679,7 +2679,7 @@ This schema accepts one of the following structures: | **isPinned** | `boolean` | optional | Console round-trip: the view is pinned in the object's view switcher. Written by the console's pin toggle through the `view` metadata API and read back to draw the pinned group. Stored on the view's row, which has no per-user scope. Not authored. | | **sortOrder** | `integer` | optional | Console round-trip: the view's position among the object's saved views in the switcher, 0-based and counted over saved views only (a code-defined view carries none). Written by the console's drag-reorder and read back to order the tabs. Not authored: `order` is the authored default position. | | **visibility** | `Enum<'private' \| 'team' \| 'organization' \| 'public'>` | optional | Console round-trip: the group the switcher files this view's tab under (private, team, organization or public). Display grouping only, NOT access control: nothing restricts who can list or open the view by this value. No console control sets it; the console carries a stored value forward when it re-saves the row. Not authored. | -| **columnState** | `never` | optional | [REMOVED] `view.columnState` was removed in @objectstack/spec 18.7.0 (ADR-0049 enforce-or-remove) — it held one column order and set of widths on a shared view row; nothing writes it any more, and a stored layout is no longer applied, so every reader sees the view's own column order and widths. The console keeps column widths in each reader's browser and saves a column order into the view itself. Delete the key. To ship a column order, list `columns` in that order (or set `fieldOrder`); to ship a width, set `width` on the column. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +| **columnState** | `never` | optional | [REMOVED] `view.columnState` was removed in @objectstack/spec 19.0.0 (ADR-0049 enforce-or-remove) — it held one column order and set of widths on a shared view row; nothing writes it any more, and a stored layout is no longer applied, so every reader sees the view's own column order and widths. The console keeps column widths in each reader's browser and saves a column order into the view itself. Delete the key. To ship a column order, list `columns` in that order (or set `fieldOrder`); to ship a width, set `width` on the column. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **options** | `never` | optional | Refused: a view item record carries no top-level `options` bag. Its per-kind blocks live under `config` (`config.kanban`, `config.timeline`, …); the legacy `options.KIND` bag belongs to the flattened list overlay only. | ### Nested Shape: `ViewItemWire[viewKind='list'].config` @@ -2779,7 +2779,7 @@ This schema accepts one of the following structures: | **isPinned** | `boolean` | optional | Console round-trip: the view is pinned in the object's view switcher. Written by the console's pin toggle through the `view` metadata API and read back to draw the pinned group. Stored on the view's row, which has no per-user scope. Not authored. | | **sortOrder** | `integer` | optional | Console round-trip: the view's position among the object's saved views in the switcher, 0-based and counted over saved views only (a code-defined view carries none). Written by the console's drag-reorder and read back to order the tabs. Not authored: `order` is the authored default position. | | **visibility** | `Enum<'private' \| 'team' \| 'organization' \| 'public'>` | optional | Console round-trip: the group the switcher files this view's tab under (private, team, organization or public). Display grouping only, NOT access control: nothing restricts who can list or open the view by this value. No console control sets it; the console carries a stored value forward when it re-saves the row. Not authored. | -| **columnState** | `never` | optional | [REMOVED] `view.columnState` was removed in @objectstack/spec 18.7.0 (ADR-0049 enforce-or-remove) — it held one column order and set of widths on a shared view row; nothing writes it any more, and a stored layout is no longer applied, so every reader sees the view's own column order and widths. The console keeps column widths in each reader's browser and saves a column order into the view itself. Delete the key. To ship a column order, list `columns` in that order (or set `fieldOrder`); to ship a width, set `width` on the column. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +| **columnState** | `never` | optional | [REMOVED] `view.columnState` was removed in @objectstack/spec 19.0.0 (ADR-0049 enforce-or-remove) — it held one column order and set of widths on a shared view row; nothing writes it any more, and a stored layout is no longer applied, so every reader sees the view's own column order and widths. The console keeps column widths in each reader's browser and saves a column order into the view itself. Delete the key. To ship a column order, list `columns` in that order (or set `fieldOrder`); to ship a width, set `width` on the column. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **options** | `never` | optional | Refused: a view item record carries no top-level `options` bag. Its per-kind blocks live under `config` (`config.kanban`, `config.timeline`, …); the legacy `options.KIND` bag belongs to the flattened list overlay only. | ### Nested Shape: `ViewItemWire[viewKind='form'].config` 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 22a10369642..568137a997b 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/` | 410 | +| `system/` | 411 | diff --git a/packages/spec/api-surface/system.json b/packages/spec/api-surface/system.json index 85cbf2f8d87..e9caca98858 100644 --- a/packages/spec/api-surface/system.json +++ b/packages/spec/api-surface/system.json @@ -924,6 +924,7 @@ "resolveMetadataTypeDescription (function)", "resolveMetadataTypeLabel (function)", "resolveObjectFieldLabels (function)", + "resolveObjectMilestoneSummary (function)", "resolveSettingsActionConfirm (function)", "resolveSettingsActionLabel (function)", "resolveSettingsActionSuccess (function)", diff --git a/packages/spec/authorable-surface/system.json b/packages/spec/authorable-surface/system.json index 5385c4aacbe..e7926fe7e42 100644 --- a/packages/spec/authorable-surface/system.json +++ b/packages/spec/authorable-surface/system.json @@ -858,6 +858,7 @@ "system/ObjectStorageConfig:quota", "system/ObjectStorageConfig:scope", "system/ObjectTranslationData:_actions", + "system/ObjectTranslationData:_milestones", "system/ObjectTranslationData:_relatedLists", "system/ObjectTranslationData:_sections", "system/ObjectTranslationData:_tabs", diff --git a/packages/spec/export-origins/system.json b/packages/spec/export-origins/system.json index aaf3d260cfa..12c15578adb 100644 --- a/packages/spec/export-origins/system.json +++ b/packages/spec/export-origins/system.json @@ -884,6 +884,7 @@ "resolveMetadataTypeDescription": "src/system/i18n-resolver.ts#resolveMetadataTypeDescription (function)", "resolveMetadataTypeLabel": "src/system/i18n-resolver.ts#resolveMetadataTypeLabel (function)", "resolveObjectFieldLabels": "src/system/i18n-resolver.ts#resolveObjectFieldLabels (function)", + "resolveObjectMilestoneSummary": "src/system/i18n-resolver.ts#resolveObjectMilestoneSummary (function)", "resolveSettingsActionConfirm": "src/system/i18n-resolver.ts#resolveSettingsActionConfirm (function)", "resolveSettingsActionLabel": "src/system/i18n-resolver.ts#resolveSettingsActionLabel (function)", "resolveSettingsActionSuccess": "src/system/i18n-resolver.ts#resolveSettingsActionSuccess (function)", From c41ed09c9227651ff609aaa010e06b5144444841 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 19:27:49 +0000 Subject: [PATCH 43/50] chore(spec): regenerate export-origins after merging main Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- packages/spec/export-origins/ai.json | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json index e208ba3f218..02ac69d57dc 100644 --- a/packages/spec/export-origins/ai.json +++ b/packages/spec/export-origins/ai.json @@ -297,6 +297,7 @@ "getRecordContextToolJsonSchemas": "src/ai/record-context-tools.zod.ts#getRecordContextToolJsonSchemas (function)", "headingsOf": "src/ai/record-body-anchor.ts#headingsOf (function)", "scopesToAgentPermissionSets": "src/ai/mcp.zod.ts#scopesToAgentPermissionSets (function)", + "skillBindsRecordContextTool": "src/ai/skill.zod.ts#skillBindsRecordContextTool (function)", "skillForm": "src/ai/skill.metadata-form.ts#skillForm (const)", "stripBodyTags": "src/ai/record-body-anchor.ts#stripBodyTags (function)", "toolForm": "src/ai/tool.metadata-form.ts#toolForm (const)" From d1caba774d714b57077cca4e9953e8ee6d2d1799 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 19:39:29 +0000 Subject: [PATCH 44/50] chore(spec): regenerate the references and the strictness ledger after merging the rename branch Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- content/docs/references/api/automation-api.mdx | 1 + .../2026-07-unknown-key-strictness-ledger.counts/system.md | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/content/docs/references/api/automation-api.mdx b/content/docs/references/api/automation-api.mdx index 0982b0d94fd..43303f2d46e 100644 --- a/content/docs/references/api/automation-api.mdx +++ b/content/docs/references/api/automation-api.mdx @@ -1226,6 +1226,7 @@ const result = AutomationApiErrorCode.parse(data); | **error** | `string` | optional | Error message if execution failed | | **durationMs** | `number` | optional | Execution duration in milliseconds | | **code** | `Enum<'PERMISSION_DENIED' \| 'INVALID_SIGNAL' \| 'RUN_NOT_FOUND' \| 'STORE_UNAVAILABLE' \| …>` | optional | Machine-readable failure classification, set alongside `error` when the caller must distinguish WHY it failed. A closed union - the members and their transport mappings are documented on the contract (`AutomationResult.code`, contracts/automation-service.ts). | +| **fields** | `{ field: string; code: Enum<'required' \| 'invalid_type' \| 'invalid_shape' \| 'unknown_field' \| …>; message: string; label?: string; … }[]` | optional | The field-addressed findings behind an `INVALID_SCREEN_INPUT` refusal, one per violated screen field: its `name`, the field-level code it broke and the engine's English line. Set with that code only. A transport serves it as `error.details.fields` | | **status** | `Enum<'completed' \| 'paused' \| 'failed' \| 'stranded' \| 'refused'>` | optional | Lifecycle status. `paused` means the run suspended at a node and can be continued with the resume route. Absent or `completed`/`failed`/`stranded`/`refused` means the run reached a terminal state. `refused` is a first-class refusal: the flow reached an `end` node declaring `outcome: 'refused'` — a successful evaluation that said no, so `success` is true, `successMessage` is absent and the per-record reason is on `refusalMessage`; a runner shows it with Close only. `stranded` is the terminally-failed-but-repairable run: a resume consumed the suspension and a downstream node threw, so the run is recorded as failed and can be re-armed only by an explicit operator verb - never by the resume route, which answers RUN_NOT_FOUND for it. | | **runId** | `string` | optional | Run id - set when `status` is `paused`, so callers can resume it | | **screen** | `{ nodeId: string; title?: string; description?: string; fields: object[]; … }` | optional | The screen to render - set when the run paused at a `screen` node awaiting user input. The client collects values for `screen.fields` and resumes the run with them. | 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 568137a997b..7f70459ac89 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/` | 411 | +| `system/` | 412 | From d5c5b92d5ca5f0ed8cd92dba977965529be3e814 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 19:40:37 +0000 Subject: [PATCH 45/50] fix(metadata-protocol): a held-back form item's revert entry promises no retry A form item a commit revert holds back reports that the form stays as published and points at the view row's own entry for the cause, which may be permanent, instead of telling the caller to revert the commit again. The restore limb's note on the platform-record refusal now says that form items wait for the view rows the commit edited. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- .../metadata-protocol/src/protocol-package-commits.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-package-commits.ts b/packages/metadata-protocol/src/protocol-package-commits.ts index dbba435dc1d..19f859c7f46 100644 --- a/packages/metadata-protocol/src/protocol-package-commits.ts +++ b/packages/metadata-protocol/src/protocol-package-commits.ts @@ -1307,8 +1307,8 @@ export class ProtocolPackageCommitsFacet { error: `Commit item '${it.type}/${it.name}' was not reverted: the view row${notPutBack.length > 1 ? 's' : ''} ` + `${notPutBack.map((n) => `'${n}'`).join(', ')} this commit also edited could not be put back, and a ` + 'form is taken back only once every view row its commit edited stands again. Nothing was written ' - + 'for it, so it stays as published. Resolve the cause reported for that row, then revert the ' - + 'commit again.', + + 'for it, so the form stays as published. The entry for each such row here says why it was ' + + 'not put back.', }); continue; } @@ -1796,7 +1796,9 @@ export class ProtocolPackageCommitsFacet { // [#37130] The platform's own record is never restored: // refused into `failed[]` as {@link rollbackMetaItem} // refuses it, nothing written; the commit's other items - // still revert (ADR-0067 D3). + // still revert (ADR-0067 D3), except its `form` items, + // which wait for every `view` row the commit edited and + // stay as published while one is not put back (ADR-0159 D5). refusePlatformRecord: true, }); rowWritten = `its row was restored to the body of version ${restoreToVersion}`; From 921f5d06052d8e66c7580b96d5c2b268095b9f76 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 19:47:05 +0000 Subject: [PATCH 46/50] refactor(metadata-protocol): keep the protocol facade within its line ceiling after the merge Main's eight new lines in the facade met this branch's additions above the ceiling. The form-body read's docblock points at its facet's contract, and the two spec/ui type imports join the pinned one; nothing else changes. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- packages/metadata-protocol/src/protocol.ts | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 2147464fc7a..be53df79e8a 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -2,7 +2,6 @@ import { formTypeWriteRefusal } from './protocol-form-writes.js'; import { readUnreadableFormBodies } from './protocol-form-reads.js'; -import type { UnreadableFormBody } from '@objectstack/spec/ui'; import type { DataProtocol, FlowRegistration, @@ -84,7 +83,6 @@ import { PLURAL_TO_SINGULAR, unrecognisedMetaTypeRefusal } from '@objectstack/sp // live transport in through `attachMetadataMutationPubSub`. import type { IPubSub } from '@objectstack/spec/contracts'; import type { ConversionNotice, ConversionTodoNotice } from '@objectstack/spec'; -import { type I18nLabel } from '@objectstack/spec/ui'; // [commit ece4dad31] Emitted-specifier pin. This module's inferred public declarations // structurally mention `FormFieldInput` (FormView `sections[].fields`), and // this file imports BOTH `@objectstack/spec` (root, for @@ -100,7 +98,7 @@ import { type I18nLabel } from '@objectstack/spec/ui'; // reference on the narrow `/ui` entry; the export statement is what keeps // no-unused-locals green. index.ts deliberately does not re-export it // (curated entry, unchanged). -import { type FormFieldInput } from '@objectstack/spec/ui'; +import { type FormFieldInput, type I18nLabel, type UnreadableFormBody } from '@objectstack/spec/ui'; export type { FormFieldInput }; import { type TranslationBundle } from '@objectstack/spec/system'; import { @@ -3537,13 +3535,7 @@ 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`. - */ + /** Contract: {@link readUnreadableFormBodies} [ADR-0159 D6 rule 7]; a server-only extension the anonymous form doors feature-detect. */ async getUnreadableFormBodies(): Promise { return readUnreadableFormBodies(protocolHost(this)); } From 20a80b19d16058700b6a44ea91b38be9da771e45 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:04:34 +0000 Subject: [PATCH 47/50] chore(spec): regenerate the protocol and translation references after merging the rename branch Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- content/docs/references/api/protocol.mdx | 10 +++++----- content/docs/references/system/translation.mdx | 6 +++--- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index b04f5b01148..772b888a2b0 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -1323,8 +1323,8 @@ This schema accepts one of the following structures: | **allowPurge** | `never` | optional | [REMOVED] `objects..allowPurge` was removed in @objectstack/spec 17 (ADR-0049): the `purge` ObjectQL operation it claimed to gate did not exist then, so granting the bit delivered nothing (a compliance/GDPR erase the author believed was permission-locked was not). Delete the key. The operation now exists with the recycle bin (ADR-0148), and its grant is spelled `manageRecycleBin` (purge an entry, empty an object's entries, and the permanent delete). 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. | | **allowRestoreOwnDeleted** | `boolean` | optional | Recycle bin: restore the entries of this object the caller deleted. Bounded by read; implied by manageRecycleBin and modifyAllRecords, not by allowDelete. | | **manageRecycleBin** | `boolean` | optional | Recycle bin administration on this object: restore any entry, not only your own, and purge (the permanent delete, purging one entry, emptying the object's entries). Bounded by read; implied by modifyAllRecords. | -| **viewAllRecords** | `boolean` | optional (default: `false`) | View All Data (Bypass Sharing) | -| **modifyAllRecords** | `boolean` | optional (default: `false`) | Modify All Data (Bypass Sharing) — bypasses sharing rules and ownership on the objects record sharing enforces on; on an object with NO owner field sharing abstains, so the platform created_by write floor still applies. Includes delete: an omitted allowDelete parses to true, and an explicit allowDelete: false beside it is refused. | +| **viewAllRecords** | `boolean` | optional (default: `false`) | View All Data (Bypass Sharing): reads every record of the object. Casts no field vote: a field another permission set hides stays hidden; reading every field is viewAllFields. | +| **modifyAllRecords** | `boolean` | optional (default: `false`) | Modify All Data (Bypass Sharing) — bypasses sharing rules and ownership on the objects record sharing enforces on; on an object with NO owner field sharing abstains, so the platform created_by write floor still applies. Includes delete: an omitted allowDelete parses to true, and an explicit allowDelete: false beside it is refused. Casts no field vote: field rows (this set's and others') still hide or lock their fields; reading every field is viewAllFields. | | **viewAllFields** | `boolean` | optional | View All Fields: a read vote on every field of this object, including fields added later. Casts no edit vote: edits come from the default or from explicit editable: true field rows. A field row of the same set beats it, so an own readable: false row keeps the field hidden for this set. Grants no object access and widens no record. Allowed on the '*' entry. | | **readScope** | `Enum<'own' \| 'own_and_reports' \| 'unit' \| 'unit_and_below' \| 'org'>` | optional | [ADR-0057 D1] Read depth: own\|unit\|unit_and_below\|org | | **writeScope** | `Enum<'own' \| 'own_and_reports' \| 'unit' \| 'unit_and_below' \| 'org'>` | optional | [ADR-0057 D1] Write depth: own\|unit\|unit_and_below\|org | @@ -1797,8 +1797,8 @@ One changed key path of the pending draft, and the last write that changed it. | **allowPurge** | `never` | optional | [REMOVED] `objects..allowPurge` was removed in @objectstack/spec 17 (ADR-0049): the `purge` ObjectQL operation it claimed to gate did not exist then, so granting the bit delivered nothing (a compliance/GDPR erase the author believed was permission-locked was not). Delete the key. The operation now exists with the recycle bin (ADR-0148), and its grant is spelled `manageRecycleBin` (purge an entry, empty an object's entries, and the permanent delete). 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. | | **allowRestoreOwnDeleted** | `boolean` | optional | Recycle bin: restore the entries of this object the caller deleted. Bounded by read; implied by manageRecycleBin and modifyAllRecords, not by allowDelete. | | **manageRecycleBin** | `boolean` | optional | Recycle bin administration on this object: restore any entry, not only your own, and purge (the permanent delete, purging one entry, emptying the object's entries). Bounded by read; implied by modifyAllRecords. | -| **viewAllRecords** | `boolean` | optional (default: `false`) | View All Data (Bypass Sharing) | -| **modifyAllRecords** | `boolean` | optional (default: `false`) | Modify All Data (Bypass Sharing) — bypasses sharing rules and ownership on the objects record sharing enforces on; on an object with NO owner field sharing abstains, so the platform created_by write floor still applies. Includes delete: an omitted allowDelete parses to true, and an explicit allowDelete: false beside it is refused. | +| **viewAllRecords** | `boolean` | optional (default: `false`) | View All Data (Bypass Sharing): reads every record of the object. Casts no field vote: a field another permission set hides stays hidden; reading every field is viewAllFields. | +| **modifyAllRecords** | `boolean` | optional (default: `false`) | Modify All Data (Bypass Sharing) — bypasses sharing rules and ownership on the objects record sharing enforces on; on an object with NO owner field sharing abstains, so the platform created_by write floor still applies. Includes delete: an omitted allowDelete parses to true, and an explicit allowDelete: false beside it is refused. Casts no field vote: field rows (this set's and others') still hide or lock their fields; reading every field is viewAllFields. | | **viewAllFields** | `boolean` | optional | View All Fields: a read vote on every field of this object, including fields added later. Casts no edit vote: edits come from the default or from explicit editable: true field rows. A field row of the same set beats it, so an own readable: false row keeps the field hidden for this set. Grants no object access and widens no record. Allowed on the '*' entry. | | **readScope** | `Enum<'own' \| 'own_and_reports' \| 'unit' \| 'unit_and_below' \| 'org'>` | optional | [ADR-0057 D1] Read depth: own\|unit\|unit_and_below\|org | | **writeScope** | `Enum<'own' \| 'own_and_reports' \| 'unit' \| 'unit_and_below' \| 'org'>` | optional | [ADR-0057 D1] Write depth: own\|unit\|unit_and_below\|org | @@ -1809,7 +1809,7 @@ One changed key path of the pending draft, and the last write that changed it. | :--- | :--- | :--- | :--- | | **readable** | `boolean` | optional (default: `true`) | Field read access | | **editable** | `boolean` | optional (default: `false`) | Field edit access | -| **when** | `string` | optional | Row condition narrowing where this entry votes, authored in canonical CEL like `rowLevelSecurity[].using` (a field of this object compared with a literal or a `current_user.*` value using `==`, `!=`, `<`, `<=`, `>`, `>=` or `in`, combined with `&&` / `\|\|`; e.g. status in ["approved", "signing", "active"]). Absent, the entry votes on every row. Present, the entry votes as declared on the rows the condition matches and is ABSENT on every other row, so the most-permissive merge across the caller's sets is unchanged: a set that locks a field only from a stage onward does not lock the rows before it, and a co-held set that says nothing about the field still lifts nothing, unless it holds the super-user bypass on the object (its own entry for the object, otherwise its `'*'` wildcard). Such a set votes on every field of the object, on every row, whatever `when` says: `viewAllRecords` votes `readable: true`, and `modifyAllRecords` votes `readable: true` and `editable: true`, so a row-conditioned lock never binds a Modify All holder. View All never grants an edit. Otherwise union without deny is unchanged. The write gate judges the condition on the stored row BEFORE an update (so a lock on `status in [...]` holds on an approved row even when the write changes `status`) and on the incoming row of an insert, as the caller sent it. It reaches the EDIT vote only — reads are judged row-blind — so `readable: false` beside a `when` is refused at parse time: keep `readable: true` (the default) on a row-conditioned entry. Where no row can be judged (a predicate update with no row address, a stored row the caller cannot read, a condition that does not resolve for the request) the entry is judged as its lock: it contributes no edit grant on that write. Validated like an RLS predicate at authoring and publish time: the fields it names must exist on the entry's object and it may not reach across a relation; a condition that cannot be lowered is refused there, never dropped at runtime. Readers that hold no row (`/auth/me/permissions`, the object-wide field projections, the write preview on an update) report a row-conditioned entry as its lock, so a client never advertises an edit the gate refuses. The record-scoped field projection (`GET /data/{object}/{id}/field-access`, the answer a record's edit form reads) holds the row: it judges the condition on the stored row exactly as the write gate does on an update of that row, so a lock that applies only from a stage onward disables the field only on the rows it names. | +| **when** | `string` | optional | Row condition narrowing where this entry votes, authored in canonical CEL like `rowLevelSecurity[].using` (a field of this object compared with a literal or a `current_user.*` value using `==`, `!=`, `<`, `<=`, `>`, `>=` or `in`, combined with `&&` / `\|\|`; e.g. status in ["approved", "signing", "active"]). Absent, the entry votes on every row. Present, the entry votes as declared on the rows the condition matches and is ABSENT on every other row, so the most-permissive merge across the caller's sets is unchanged: a set that locks a field only from a stage onward does not lock the rows before it, and a co-held set that says nothing about the field still lifts nothing. A set carrying `viewAllFields` on the object (its own entry for the object, otherwise its `'*'` wildcard) votes `readable: true` on every field, on every row, and never an edit, so a row-conditioned lock binds its holders; `viewAllRecords` and `modifyAllRecords` cast no field vote. Otherwise union without deny is unchanged. The write gate judges the condition on the stored row BEFORE an update (so a lock on `status in [...]` holds on an approved row even when the write changes `status`) and on the incoming row of an insert, as the caller sent it. It reaches the EDIT vote only — reads are judged row-blind — so `readable: false` beside a `when` is refused at parse time: keep `readable: true` (the default) on a row-conditioned entry. Where no row can be judged (a predicate update with no row address, a stored row the caller cannot read, a condition that does not resolve for the request) the entry is judged as its lock: it contributes no edit grant on that write. Validated like an RLS predicate at authoring and publish time: the fields it names must exist on the entry's object and it may not reach across a relation; a condition that cannot be lowered is refused there, never dropped at runtime. Readers that hold no row (`/auth/me/permissions`, the object-wide field projections, the write preview on an update) report a row-conditioned entry as its lock, so a client never advertises an edit the gate refuses. The record-scoped field projection (`GET /data/{object}/{id}/field-access`, the answer a record's edit form reads) holds the row: it judges the condition on the stored row exactly as the write gate does on an update of that row, so a lock that applies only from a stage onward disables the field only on the rows it names. | | **rollupSourceUnreadableReason** | `string` | optional | Authoring-time acknowledgement, read only by `os lint` (the runtime does not read it): why holders of this set are meant to read this roll-up `summary` column although the set cannot read the child object, the aggregated child field or a child field the roll-up's `filter` tests (e.g. 'Service staff read account totals but not invoice rows'). Declared on the set's entry for the summary column, it turns that set's `security-rollup-source-unreadable` warning for the column into an `info` note quoting the reason, so `os lint --strict` passes; every other finding is unchanged. The runtime does not read the key, but the entry that carries it is an ordinary declaring entry: it votes `readable: true` in the field merge (only declaring sets vote, and the most permissive vote wins), so on a set that had no entry for the column, adding one to carry the reason restores the column for holders whose other sets mask it. A blank reason is refused, and so is a reason beside `readable: false`, an entry that declares no read to acknowledge. | diff --git a/content/docs/references/system/translation.mdx b/content/docs/references/system/translation.mdx index 293f2791c8d..b54a5f51fe2 100644 --- a/content/docs/references/system/translation.mdx +++ b/content/docs/references/system/translation.mdx @@ -370,7 +370,7 @@ Translation data for a single object | **label** | `string` | optional | Translated metadata-type display label (overrides registry label) | | **description** | `string` | optional | Translated metadata-type description | | **sections** | `Record` | optional | Section translations keyed by section.name | -| **fields** | `Record` | optional | Field translations keyed by field path (dot-notation for nested fields) | +| **fields** | `Record }>` | optional | Field translations keyed by field path (dot-notation for nested fields) | ### Nested Shape: `PlatformTranslationData.settingsCommon` @@ -839,7 +839,7 @@ Translation data for a single object | **label** | `string` | optional | Translated metadata-type display label (overrides registry label) | | **description** | `string` | optional | Translated metadata-type description | | **sections** | `Record` | optional | Section translations keyed by section.name | -| **fields** | `Record` | optional | Field translations keyed by field path (dot-notation for nested fields) | +| **fields** | `Record }>` | optional | Field translations keyed by field path (dot-notation for nested fields) | ### Nested Shape: `TranslationData.settingsCommon` @@ -1074,7 +1074,7 @@ Translation data for a single object | **label** | `string` | optional | Translated metadata-type display label (overrides registry label) | | **description** | `string` | optional | Translated metadata-type description | | **sections** | `Record` | optional | Section translations keyed by section.name | -| **fields** | `Record` | optional | Field translations keyed by field path (dot-notation for nested fields) | +| **fields** | `Record }>` | optional | Field translations keyed by field path (dot-notation for nested fields) | ### Nested Shape: `TranslationItem.settingsCommon` From 4054d58f94187e6e6cbb1ddbc47ecc3fa80d21a8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 03:37:21 +0000 Subject: [PATCH 48/50] chore(spec): regenerate the view reference, the strictness ledger and the authorable surface after merging main Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- content/docs/references/ui/view.mdx | 14 ++++++++++++-- .../ui.md | 12 ++++++------ packages/spec/authorable-surface/ui.json | 1 + 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/content/docs/references/ui/view.mdx b/content/docs/references/ui/view.mdx index a13c131e0b3..ba01fb943a8 100644 --- a/content/docs/references/ui/view.mdx +++ b/content/docs/references/ui/view.mdx @@ -433,7 +433,7 @@ Form-view select option — the object-field option shape minus the per-option ` | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **label** | `string` | ✅ | Display label (human-readable, any case allowed) | -| **value** | `string` | ✅ | Stored value (lowercase machine identifier) | +| **value** | `string` | ✅ | Stored value (lowercase machine identifier, one character or more) | | **description** | `string` | optional | Optional secondary/help text for this option. Lookup option search matches it in addition to the label; renderers may show it as supporting text. | | **color** | `string` | optional | Color code for badges/charts | | **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Per-option visibility predicate (CEL) — option is offered only when TRUE (else omitted). Env: the live `record` plus the host predicate scope, which binds `current_user`. The one VISIBILITY predicate the SERVER also enforces — the rule validator refuses a write of a value whose predicate is false, or cannot be evaluated — so a user-gated CHOICE belongs here. e.g. P`record.country == 'cn'` or P`'admin' in current_user.positions`. On an OBJECT field's option it reads the record's OWN columns: the server never reads a related record there, so a read THROUGH a reference field (`record.account.tier`) would fault and every write picking the option would be refused, and `objectstack validate` refuses it — enforce such a restriction with a `validations[]` `script` rule, whose `condition` is read one hop through a reference. | @@ -516,7 +516,7 @@ Form-view select option — the object-field option shape minus the per-option ` | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **label** | `string` | ✅ | Display label (human-readable, any case allowed) | -| **value** | `string` | ✅ | Stored value (lowercase machine identifier) | +| **value** | `string` | ✅ | Stored value (lowercase machine identifier, one character or more) | | **description** | `string` | optional | Optional secondary/help text for this option. Lookup option search matches it in addition to the label; renderers may show it as supporting text. | | **color** | `string` | optional | Color code for badges/charts | | **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Per-option visibility predicate (CEL) — option is offered only when TRUE (else omitted). Env: the live `record` plus the host predicate scope, which binds `current_user`. The one VISIBILITY predicate the SERVER also enforces — the rule validator refuses a write of a value whose predicate is false, or cannot be evaluated — so a user-gated CHOICE belongs here. e.g. P`record.country == 'cn'` or P`'admin' in current_user.positions`. On an OBJECT field's option it reads the record's OWN columns: the server never reads a related record there, so a read THROUGH a reference field (`record.account.tier`) would fault and every write picking the option would be refused, and `objectstack validate` refuses it — enforce such a restriction with a `validations[]` `script` rule, whose `condition` is read one hop through a reference. | @@ -832,6 +832,7 @@ HTTP methods a view data source may request — the subset of `HttpMethod` witho | **summary** | `{ type: 'none' } \| { type: 'count' } \| { type: 'sum'; field: string } \| { type: 'avg'; field: string } \| … +2 more` | optional | The statistic each lane shows at its foot. `{ type: 'count' }` counts the lane records; `{ type: 'sum', field: 'amount' }` totals a number field over all of the lane records, `avg` averages it, and `min` / `max` show its smallest / largest value, each computed by the query (a field the reader may not read shows no figure); `{ type: 'none' }` shows nothing. A list view board whose lanes come from a lookup field draws one page of records: its `sum`, `avg`, `min` and `max` still cover every record of each lane, and its `count` counts that page. Only on a board handed its records whole, without their query, does `sum` total the records handed in and the other three show nothing. Takes precedence over summarizeField. Omit to keep summarizeField's sum, or no statistic without it. | | **showFieldLabels** | `boolean` | optional | Whether each card names its fields beside their values. Omit for true (names shown); false shows the values alone. | | **hideEmptyFields** | `boolean` | optional | Whether a card leaves out a field that holds no value. Omit for true (left out); false keeps the field with an empty value. | +| **cardFooter** | `{ comments?: boolean; attachments?: boolean }` | optional | The counts each card shows at its foot, each read for the whole board over its loaded cards in grouped reads, never one per card. Omit to show none. | | **titleField** | `string` | optional | Field displayed as the card title. Omit to fall back to the record display name (ADR-0079 resolver chain) | | **columns** | `string[]` | ✅ | Fields to show on cards | @@ -863,6 +864,13 @@ HTTP methods a view data source may request — the subset of `HttpMethod` witho | **type** | `'max'` | ✅ | | | **field** | `string` | ✅ | The field whose largest value over all of the lane's records the lane shows (e.g. amount) | +### Nested Shape: `KanbanConfig.cardFooter` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **comments** | `boolean` | optional | Show how many comment threads of the record are open (not resolved). Omit or false: not shown, and not read. | +| **attachments** | `boolean` | optional | Show how many files are attached to the record (objects with enable.files). Omit or false: not shown, and not read. | + --- @@ -1186,6 +1194,7 @@ An any-of group: `{ or: [rule, ...] }` matches a record when ANY of its rules ma | **summary** | `{ type: 'none' } \| { type: 'count' } \| { type: 'sum'; field: string } \| { type: 'avg'; field: string } \| … +2 more` | optional | The statistic each lane shows at its foot. `{ type: 'count' }` counts the lane records; `{ type: 'sum', field: 'amount' }` totals a number field over all of the lane records, `avg` averages it, and `min` / `max` show its smallest / largest value, each computed by the query (a field the reader may not read shows no figure); `{ type: 'none' }` shows nothing. A list view board whose lanes come from a lookup field draws one page of records: its `sum`, `avg`, `min` and `max` still cover every record of each lane, and its `count` counts that page. Only on a board handed its records whole, without their query, does `sum` total the records handed in and the other three show nothing. Takes precedence over summarizeField. Omit to keep summarizeField's sum, or no statistic without it. | | **showFieldLabels** | `boolean` | optional | Whether each card names its fields beside their values. Omit for true (names shown); false shows the values alone. | | **hideEmptyFields** | `boolean` | optional | Whether a card leaves out a field that holds no value. Omit for true (left out); false keeps the field with an empty value. | +| **cardFooter** | `{ comments?: boolean; attachments?: boolean }` | optional | The counts each card shows at its foot, each read for the whole board over its loaded cards in grouped reads, never one per card. Omit to show none. | | **titleField** | `string` | optional | Field displayed as the card title. Omit to fall back to the record display name (ADR-0079 resolver chain) | | **columns** | `string[]` | ✅ | Fields to show on cards | @@ -1654,6 +1663,7 @@ An any-of group: `{ or: [rule, ...] }` matches a record when ANY of its rules ma | **summary** | `{ type: 'none' } \| { type: 'count' } \| { type: 'sum'; field: string } \| { type: 'avg'; field: string } \| … +2 more` | optional | The statistic each lane shows at its foot. `{ type: 'count' }` counts the lane records; `{ type: 'sum', field: 'amount' }` totals a number field over all of the lane records, `avg` averages it, and `min` / `max` show its smallest / largest value, each computed by the query (a field the reader may not read shows no figure); `{ type: 'none' }` shows nothing. A list view board whose lanes come from a lookup field draws one page of records: its `sum`, `avg`, `min` and `max` still cover every record of each lane, and its `count` counts that page. Only on a board handed its records whole, without their query, does `sum` total the records handed in and the other three show nothing. Takes precedence over summarizeField. Omit to keep summarizeField's sum, or no statistic without it. | | **showFieldLabels** | `boolean` | optional | Whether each card names its fields beside their values. Omit for true (names shown); false shows the values alone. | | **hideEmptyFields** | `boolean` | optional | Whether a card leaves out a field that holds no value. Omit for true (left out); false keeps the field with an empty value. | +| **cardFooter** | `{ comments?: boolean; attachments?: boolean }` | optional | The counts each card shows at its foot, each read for the whole board over its loaded cards in grouped reads, never one per card. Omit to show none. | | **titleField** | `string` | optional | Field displayed as the card title. Omit to fall back to the record display name (ADR-0079 resolver chain) | | **columns** | `string[]` | ✅ | Fields to show on cards | 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 b7944172efe..0c649ac175e 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/` | 231 | 221 | 6 | 0 | 4 | +| `ui/` | 232 | 222 | 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` | 66 | +| `view.zod.ts` | 67 | | `widget.zod.ts` | 1 | -| **total** | **231** | +| **total** | **232** | ## `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 231**, in 4 file(s). +**4 strip of 232**, in 4 file(s). | File | Strip | Sites | |---|---|---| | `action-params.zod.ts` | 1 | 1 | | `app.zod.ts` | 1 | 20 | -| `view.zod.ts` | 1 | 66 | +| `view.zod.ts` | 1 | 67 | | `widget.zod.ts` | 1 | 1 | -| **total** | **4** | **231** | +| **total** | **4** | **232** | | Bucket | Sites | |---|---| diff --git a/packages/spec/authorable-surface/ui.json b/packages/spec/authorable-surface/ui.json index 9d5f664dd72..dd4ebb92385 100644 --- a/packages/spec/authorable-surface/ui.json +++ b/packages/spec/authorable-surface/ui.json @@ -753,6 +753,7 @@ "ui/JoinedReportBlock:runtimeFilter", "ui/JoinedReportBlock:type", "ui/JoinedReportBlock:values", + "ui/KanbanConfig:cardFooter", "ui/KanbanConfig:columns", "ui/KanbanConfig:groupByField", "ui/KanbanConfig:hideEmptyFields", From c49cbc2937e98b7a247dc92df7d50da6246a915d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 05:21:53 +0000 Subject: [PATCH 49/50] chore(spec): regenerate the view reference after merging main Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- content/docs/references/ui/view.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/content/docs/references/ui/view.mdx b/content/docs/references/ui/view.mdx index ba01fb943a8..0a7a0317890 100644 --- a/content/docs/references/ui/view.mdx +++ b/content/docs/references/ui/view.mdx @@ -364,7 +364,7 @@ Column footer summary configuration | **required** | `boolean` | optional | Required override | | **hidden** | `boolean` | optional | Hidden override | | **colSpan** | `integer` | optional | Absolute column span (1-4). The renderer clamps it to the form grid's current column count, so the cell starts at a real column boundary at every surface width and never overflows (`colSpan: 4` in a 3-column grid renders as 3); a `colSpan` within the column count renders as authored, and `colSpan: 1` emits no span class at all. | -| **span** | `Enum<'auto' \| 'full'>` | optional (default: `"auto"`) | Relative field width. 'auto' (default — omit it): the renderer sizes the field from its widget type × the current column count — only textarea, markdown, html, richtext and repeater, plus a file or image field whose object field declares `multiple: true`, resolve to the full column count (repeater reaches it through the wide `field:grid` widget it maps to); an authored `colSpan` still wins over that default (`colSpan: 1` keeps such a field in one cell). 'full': resolves to the form grid's full column count. How far down the container-query tiers that span is emitted is the renderer's, not this key's: the renderer emits one clamped col-span class per multi-column tier (`@md:col-span-2 @2xl:col-span-3` for a 3-column grid), so the field takes the whole row at every multi-column tier, not just the widest. | +| **span** | `Enum<'auto' \| 'full'>` | optional (default: `"auto"`) | Relative field width. 'auto' (default — omit it): the renderer sizes the field from its widget type × the current column count — only textarea, markdown, html, richtext and repeater, plus a file or image field whose object field declares `multiple: true`, resolve to the full column count (repeater by its object-field type: the JSON editor it maps to is shared with json, composite and record, which stay one cell); an authored `colSpan` still wins over that default (`colSpan: 1` keeps such a field in one cell). 'full': resolves to the form grid's full column count. How far down the container-query tiers that span is emitted is the renderer's, not this key's: the renderer emits one clamped col-span class per multi-column tier (`@md:col-span-2 @2xl:col-span-3` for a 3-column grid), so the field takes the whole row at every multi-column tier, not just the widest. | | **widget** | `string` | optional | Custom widget/component name (overrides type-based inference) | | **language** | `string` | optional | Code editor language (for type=code) | | **keyField** | `{ field?: string; label?: string \| Record; placeholder?: string \| Record; helpText?: string \| Record; … }` | optional | Key column config for record-typed fields | @@ -494,7 +494,7 @@ Form-view select option — the object-field option shape minus the per-option ` | **required** | `boolean` | optional | Required override | | **hidden** | `boolean` | optional | Hidden override | | **colSpan** | `integer` | optional | Absolute column span (1-4). The renderer clamps it to the form grid's current column count, so the cell starts at a real column boundary at every surface width and never overflows (`colSpan: 4` in a 3-column grid renders as 3); a `colSpan` within the column count renders as authored, and `colSpan: 1` emits no span class at all. | -| **span** | `Enum<'auto' \| 'full'>` | optional (default: `"auto"`) | Relative field width. 'auto' (default — omit it): the renderer sizes the field from its widget type × the current column count — only textarea, markdown, html, richtext and repeater, plus a file or image field whose object field declares `multiple: true`, resolve to the full column count (repeater reaches it through the wide `field:grid` widget it maps to); an authored `colSpan` still wins over that default (`colSpan: 1` keeps such a field in one cell). 'full': resolves to the form grid's full column count. How far down the container-query tiers that span is emitted is the renderer's, not this key's: the renderer emits one clamped col-span class per multi-column tier (`@md:col-span-2 @2xl:col-span-3` for a 3-column grid), so the field takes the whole row at every multi-column tier, not just the widest. | +| **span** | `Enum<'auto' \| 'full'>` | optional (default: `"auto"`) | Relative field width. 'auto' (default — omit it): the renderer sizes the field from its widget type × the current column count — only textarea, markdown, html, richtext and repeater, plus a file or image field whose object field declares `multiple: true`, resolve to the full column count (repeater by its object-field type: the JSON editor it maps to is shared with json, composite and record, which stay one cell); an authored `colSpan` still wins over that default (`colSpan: 1` keeps such a field in one cell). 'full': resolves to the form grid's full column count. How far down the container-query tiers that span is emitted is the renderer's, not this key's: the renderer emits one clamped col-span class per multi-column tier (`@md:col-span-2 @2xl:col-span-3` for a 3-column grid), so the field takes the whole row at every multi-column tier, not just the widest. | | **widget** | `string` | optional | Custom widget/component name (overrides type-based inference) | | **language** | `string` | optional | Code editor language (for type=code) | | **keyField** | `{ field?: string; label?: string \| Record; placeholder?: string \| Record; helpText?: string \| Record; … }` | optional | Key column config for record-typed fields | From ebd9872fcdbfdece26f4e27969669bbd02f9c42a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 06:28:30 +0000 Subject: [PATCH 50/50] chore(spec): regenerate the spec artifacts and references after merging main Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As9cjn4Y9vAUQbVH4fq --- content/docs/references/index.mdx | 9 +++++---- .../2026-07-unknown-key-strictness-ledger.counts/ui.md | 9 +++++---- packages/spec/api-surface/ui.json | 6 ++++++ packages/spec/authorable-surface/ui.json | 4 ++++ packages/spec/declaration-map/ui.json | 2 ++ packages/spec/export-origins/ui.json | 6 ++++++ packages/spec/json-schema.manifest/ui.json | 1 + 7 files changed, 29 insertions(+), 8 deletions(-) diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index d7d492af30c..e95ff3d27b3 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 — 1736 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1737 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 | 185 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **222** | **1736** | 14 protocol modules | +| [UI Protocol](/docs/references/ui) | 17 | 186 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | +| **Total** | **223** | **1737** | 14 protocol modules | --- @@ -389,7 +389,7 @@ The runtime environment — logging, jobs, cache, metrics, notifications, i18n a ## UI Protocol -**Source:** `packages/spec/src/ui/` · **Import:** `@objectstack/spec/ui` · **16 pages, 185 schemas** +**Source:** `packages/spec/src/ui/` · **Import:** `@objectstack/spec/ui` · **17 pages, 186 schemas** Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. @@ -397,6 +397,7 @@ Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI lay | :--- | :--- | | [`action.zod.ts`](/docs/references/ui/action) | `Action`, `ActionAi`, `ActionLocation`, `ActionParam`, `ActionRefusal`, `ActionText`, `ActionType`, `InlineAction` | | [`action-params.zod.ts`](/docs/references/ui/action-params) | `ActionSession` | +| [`ai-chat-nav-params.zod.ts`](/docs/references/ui/ai-chat-nav-params) | `AiChatNavParams` | | [`app.zod.ts`](/docs/references/ui/app) | `ActionNavItem`, `App`, `AppBranding`, `AppContextSelector`, `AppLandingEntry`, `ComponentNavItem`, `DashboardNavItem`, `DocNavItem`, `GroupNavItem`, `NavigationArea`, `NavigationContribution`, `NavigationItem`, `ObjectNavItem`, `PageNavItem`, `ReportNavItem`, `UrlNavItem` | | [`bulk-action.zod.ts`](/docs/references/ui/bulk-action) | `BulkActionDef`, `BulkActionExecution`, `BulkActionOperation`, `BulkActionParam`, `BulkActionResult` | | [`chart.zod.ts`](/docs/references/ui/chart) | `ChartAggregate`, `ChartAggregateFunction`, `ChartAnnotation`, `ChartAxis`, `ChartConfig`, `ChartDrillDown`, `ChartGroupBy`, `ChartInteraction`, `ChartSeries`, `ChartType` | 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 0c649ac175e..ea7e630c5a5 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/` | 232 | 222 | 6 | 0 | 4 | +| `ui/` | 233 | 223 | 6 | 0 | 4 | ## `ui/` — sites @@ -33,6 +33,7 @@ classify and is not listed (it becomes reportable the day it grows its first sit |---|---| | `action-params.zod.ts` | 1 | | `action.zod.ts` | 13 | +| `ai-chat-nav-params.zod.ts` | 1 | | `app.zod.ts` | 20 | | `bulk-action.zod.ts` | 6 | | `chart.zod.ts` | 8 | @@ -46,7 +47,7 @@ classify and is not listed (it becomes reportable the day it grows its first sit | `sharing.zod.ts` | 1 | | `view.zod.ts` | 67 | | `widget.zod.ts` | 1 | -| **total** | **232** | +| **total** | **233** | ## `ui/` — open @@ -54,7 +55,7 @@ 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 232**, in 4 file(s). +**4 strip of 233**, in 4 file(s). | File | Strip | Sites | |---|---|---| @@ -62,7 +63,7 @@ over it is here. | `app.zod.ts` | 1 | 20 | | `view.zod.ts` | 1 | 67 | | `widget.zod.ts` | 1 | 1 | -| **total** | **4** | **232** | +| **total** | **4** | **233** | | Bucket | Sites | |---|---| diff --git a/packages/spec/api-surface/ui.json b/packages/spec/api-surface/ui.json index d74335e9139..9b884f84ce5 100644 --- a/packages/spec/api-surface/ui.json +++ b/packages/spec/api-surface/ui.json @@ -9,6 +9,7 @@ "ACTION_PARAM_BUILTIN_KEYS (const)", "ACTION_SUCCESS_RESULT_ROOT (const)", "ACTION_SUCCESS_TEMPLATE_ROOTS (const)", + "AI_CHAT_COMPONENT_REF (const)", "ASSEMBLED_VIEW_ITEMS_KEY (const)", "Action (const)", "Action (type)", @@ -52,6 +53,9 @@ "AddRecordConfig (type)", "AddRecordConfigParsed (type)", "AddRecordConfigSchema (const)", + "AiChatNavParams (type)", + "AiChatNavParamsParsed (type)", + "AiChatNavParamsSchema (const)", "AnonymousFormIntakeCandidate (interface)", "App (const)", "App (type)", @@ -562,7 +566,9 @@ "chartAggregateCategoryKey (function)", "chartAggregateResultKeys (function)", "chartAggregateValueKey (function)", + "checkAiChatNavParams (function)", "checkAppLandingItems (function)", + "checkAppSingleAiChatEntry (function)", "checkDashboardReservedDateRangeGlobalFilters (function)", "checkDashboardWidgetChartMeasureArity (function)", "checkDashboardWidgetMetricMeasureArity (function)", diff --git a/packages/spec/authorable-surface/ui.json b/packages/spec/authorable-surface/ui.json index dd4ebb92385..e8e047df488 100644 --- a/packages/spec/authorable-surface/ui.json +++ b/packages/spec/authorable-surface/ui.json @@ -176,6 +176,10 @@ "ui/AddRecordConfig:formView [RETIRED]", "ui/AddRecordConfig:mode [RETIRED]", "ui/AddRecordConfig:position", + "ui/AiChatNavParams:placeholder", + "ui/AiChatNavParams:subtitle", + "ui/AiChatNavParams:suggestions", + "ui/AiChatNavParams:title", "ui/App:_lock", "ui/App:_lockDocsUrl", "ui/App:_lockReason", diff --git a/packages/spec/declaration-map/ui.json b/packages/spec/declaration-map/ui.json index 7ba7afb043e..556dfc4f846 100644 --- a/packages/spec/declaration-map/ui.json +++ b/packages/spec/declaration-map/ui.json @@ -29,6 +29,8 @@ "ActionType": "ui/ActionType", "AddRecordConfig": "ui/AddRecordConfig", "AddRecordConfigSchema": "ui/AddRecordConfig", + "AiChatNavParams": "ui/AiChatNavParams", + "AiChatNavParamsSchema": "ui/AiChatNavParams", "App": "ui/App", "AppBranding": "ui/AppBranding", "AppBrandingSchema": "ui/AppBranding", diff --git a/packages/spec/export-origins/ui.json b/packages/spec/export-origins/ui.json index d5d706f9a4d..d1c24a34bd6 100644 --- a/packages/spec/export-origins/ui.json +++ b/packages/spec/export-origins/ui.json @@ -9,6 +9,7 @@ "ACTION_PARAM_BUILTIN_KEYS": "src/ui/action-params.zod.ts#ACTION_PARAM_BUILTIN_KEYS (const)", "ACTION_SUCCESS_RESULT_ROOT": "src/ui/action-copy-template.ts#ACTION_SUCCESS_RESULT_ROOT (const)", "ACTION_SUCCESS_TEMPLATE_ROOTS": "src/ui/action-copy-template.ts#ACTION_SUCCESS_TEMPLATE_ROOTS (const)", + "AI_CHAT_COMPONENT_REF": "src/ui/ai-chat-nav-params.zod.ts#AI_CHAT_COMPONENT_REF (const)", "ASSEMBLED_VIEW_ITEMS_KEY": "src/ui/assembled-views.zod.ts#ASSEMBLED_VIEW_ITEMS_KEY (const)", "Action": "src/ui/action.zod.ts#Action (type)", "ActionAi": "src/ui/action.zod.ts#ActionAi (type)", @@ -50,6 +51,9 @@ "AddRecordConfig": "src/ui/view.zod.ts#AddRecordConfig (type)", "AddRecordConfigParsed": "src/ui/view.zod.ts#AddRecordConfigParsed (type)", "AddRecordConfigSchema": "src/ui/view.zod.ts#AddRecordConfigSchema (const)", + "AiChatNavParams": "src/ui/ai-chat-nav-params.zod.ts#AiChatNavParams (type)", + "AiChatNavParamsParsed": "src/ui/ai-chat-nav-params.zod.ts#AiChatNavParamsParsed (type)", + "AiChatNavParamsSchema": "src/ui/ai-chat-nav-params.zod.ts#AiChatNavParamsSchema (const)", "AnonymousFormIntakeCandidate": "src/ui/anonymous-form-intake.ts#AnonymousFormIntakeCandidate (interface)", "App": "src/ui/app.zod.ts#App (type)", "AppBranding": "src/ui/app.zod.ts#AppBranding (type)", @@ -545,7 +549,9 @@ "chartAggregateCategoryKey": "src/ui/chart-aggregate.ts#chartAggregateCategoryKey (function)", "chartAggregateResultKeys": "src/ui/chart-aggregate.ts#chartAggregateResultKeys (function)", "chartAggregateValueKey": "src/ui/chart-aggregate.ts#chartAggregateValueKey (function)", + "checkAiChatNavParams": "src/ui/ai-chat-nav-params.zod.ts#checkAiChatNavParams (function)", "checkAppLandingItems": "src/ui/app.zod.ts#checkAppLandingItems (function)", + "checkAppSingleAiChatEntry": "src/ui/ai-chat-nav-params.zod.ts#checkAppSingleAiChatEntry (function)", "checkDashboardReservedDateRangeGlobalFilters": "src/ui/dashboard.zod.ts#checkDashboardReservedDateRangeGlobalFilters (function)", "checkDashboardWidgetChartMeasureArity": "src/ui/dashboard.zod.ts#checkDashboardWidgetChartMeasureArity (function)", "checkDashboardWidgetMetricMeasureArity": "src/ui/dashboard.zod.ts#checkDashboardWidgetMetricMeasureArity (function)", diff --git a/packages/spec/json-schema.manifest/ui.json b/packages/spec/json-schema.manifest/ui.json index 90275f60ec6..77b2b243653 100644 --- a/packages/spec/json-schema.manifest/ui.json +++ b/packages/spec/json-schema.manifest/ui.json @@ -16,6 +16,7 @@ "ui/ActionText", "ui/ActionType", "ui/AddRecordConfig", + "ui/AiChatNavParams", "ui/App", "ui/AppBranding", "ui/AppContextSelector",