diff --git a/.changeset/34905-required-when-shown.md b/.changeset/34905-required-when-shown.md new file mode 100644 index 00000000000..126c37393d0 --- /dev/null +++ b/.changeset/34905-required-when-shown.md @@ -0,0 +1,34 @@ +--- +'@objectstack/objectql': minor +'@objectstack/lint': minor +'@objectstack/spec': minor +'@object-ui/app-shell': minor +'@object-ui/i18n': minor +--- + +fix(objectql)!: a field that is `required` and hidden by its own `visibleWhen` is required only when shown, so one admin setting no longer locks every record outside the condition + +Clause-②: yes (narrowing + widening of the required write contract) — widened: an insert or update whose record a `required` field's own `visibleWhen` cleanly hides no longer needs that field, and an explicit null onto a row already shown and empty is accepted. Narrowed: a write that moves a record INTO the condition while that field is empty is refused; 18.5.0 accepted it. +Metadata-protocol: semantic + + + +**BREAKING** for flows, bulk updates, imports and API PATCHes that move existing records into a `required` field's `visibleWhen` condition without filling the field. Such a write is now refused with `required` naming the field (on a bulk update, one such row refuses the batch). Fill the field in the same write. A field with `required` and no `visibleWhen` is unchanged. + +**What changed (ADR-0113 D1 and D5, amended).** A field that declares `required: true` and its own `visibleWhen` used to be enforced on every save. In Studio an administrator can add one in a few clicks, and from then on every record that fails the condition refused every write, even an edit of an unrelated field, naming a field nobody could see. The engine now judges such a field from its visibility on the write: + +- the predicate evaluates cleanly to anything but TRUE on the record (the stored row with the write over it), so FALSE, or `null` such as an unset boolean: the field is not required for that write, so a record outside the condition can be created and edited, and the form's clear-on-hide `null` is accepted; +- the predicate is true: the field is required by the same non-regression rule `requiredWhen` uses, against the prior record, which the engine now reads on update for objects with such a field; +- the predicate cannot be evaluated: it counts as shown, the field stays required exactly as before, and the server logs a warning naming the field and the fault. + +The predicate is evaluated with the acting user bound as `current_user`, so a role-gated field is judged per writer; a system write with no user counts as shown. A `formula` field it reads is computed over the record first, as a read of that record computes it. A formula that faults for a reason a read shares (an empty operand) is judged on the `null` a read serves; a formula whose read value the write path cannot know (it reads through a reference, calls `label()`, calls `can` on a write that picks no permission-gated option and so resolves no permission map, reads `current_user` on a system write with no user, or reads such a formula at any depth) counts as shown; the system-write case is logged as `no-acting-user`, as the direct `current_user` spelling is. Only the field's own `visibleWhen` is read: a field group's `visibleWhen` and form-view predicates are not. + +The refusal for such a field now comes from the rule pass rather than the record walk. A single-fault write gets the same `required` code and sentence; a write with several faults may name fewer of them in one `400`, or answer a dangling reference first, and a `beforeUpdate` hook now runs before the refusal and may fill the field. + +**A formula-driven `visibleWhen` on the form.** The form computes the object's formula fields over the record being edited before it judges the field rules (the form-side recompute in `@object-ui/core`, `@object-ui/components` and `@object-ui/console`), so it shows such a field where the server requires it. A formula the form cannot compute (it reads through a reference, calls `label()` or `can()`, reads `os`, or reads the user when nobody is signed in) leaves the field shown and required, and the server decides on save. + +**`@objectstack/lint`.** Three new warnings at `objectstack validate` and the object save door, on a `required` field with a `visibleWhen`: the predicate reads through a reference field (the server cannot evaluate it, so the field stays required everywhere); the predicate reads a `formula` field (with the counts-as-shown consequence when a formula it reads, at any depth, reads through a reference, calls `label()`, or calls `can`, which a write computes only when it picks a permission-gated option); and `storage.notNull: true` beside the pair (the column still refuses the null on a record outside the condition). + +**`@object-ui/app-shell`.** Studio's field inspector shows the reference-read and formula-read warnings under the Visible-when editor of a required field. + +**`@objectstack/spec`.** The `required` and `visibleWhen` descriptions on `FieldSchema` say how the two combine. diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index 844a84b278c..21163750710 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -959,7 +959,10 @@ What the failure does depends on what the predicate guards: At **submit** a broken field rule is refused, not passed. A field `visibleWhen` that cannot be evaluated refuses the submit on the client, with a message naming the field -and the rule, because no server evaluates a field's `visibleWhen`. A broken +and the rule. The server reads a field's `visibleWhen` only when the field is also +`required`, to decide whether the requirement applies to the write: hidden means not +required, and a `visibleWhen` it cannot evaluate counts as shown, so the field stays +required and the server logs the fault. A broken `requiredWhen` or `readonlyWhen`, or an option's `visibleWhen`, is refused by the server, and the form shows that refusal beside the input. One exception: a `readonlyWhen` that reads a name the write does not bind (a bare field name, or diff --git a/content/docs/references/data/field.mdx b/content/docs/references/data/field.mdx index 612a0af3b69..6696ac79dc3 100644 --- a/content/docs/references/data/field.mdx +++ b/content/docs/references/data/field.mdx @@ -55,7 +55,7 @@ const result = CurrencyConfigSchema.parse(data); | **type** | `Enum<'text' \| 'textarea' \| 'email' \| 'url' \| 'phone' \| 'password' \| 'secret' \| 'markdown' \| 'html' \| 'richtext' \| 'number' \| 'currency' \| 'percent' \| 'date' \| … +35 more>` | ✅ | Field Data Type | | **description** | `string` | optional | Tooltip/Help text | | **format** | `string` | optional | Free-form string whose meaning depends on the field type and on the reader. The spec declares NO vocabulary for it and checks nothing but that it is a string, so any string parses on any field type. On an `autonumber` field it is the record-number PATTERN — the shorthand that predates `autonumberFormat`, which wins when both are present: `format: 'INV-{0000}'` mints `INV-0001` on both the query engine and the SQL driver, while a value carrying no `{...}` token is emitted as literal text with the bare counter appended (`format: 'email'` mints `email1`). Prefer `autonumberFormat` on a new field. On any other field type the server does not act on it: it picks no column type, coerces no value and runs no check from it. The Studio UI reads it as a display hint, in words and with defaults that its renderers own and declare. For example, the `date` and `datetime` cells read it as a display STYLE, and on a plain-text field the shared cell-renderer resolver reads a small set of words that promote the cell to a richer renderer, such as a link; each of those falls back silently to a default rendering when it does not recognise the word. To constrain a VALUE, use the field `type` (the write-time record validator's built-in email, url and phone checks key on `type`, never on this key) or a `format` validation rule, whose own `format` key is the closed set `email` \| `url` \| `phone` \| `json`. | -| **required** | `boolean` | optional (default: `false`) | Write-time contract (ADR-0113): an insert must provide a non-null value, and an update may not null it out. On a multi-value lookup (`multiple: true`) required means NON-EMPTY array — an emptied required set fails validation loudly; `[]` does not satisfy it. NOT a column constraint — the physical NOT NULL is a separate explicit opt-in (`storage.notNull`), so tightening this on a deployed object is safe: existing null rows stay readable, and editable as long as the write does not touch this field. | +| **required** | `boolean` | optional (default: `false`) | Write-time contract (ADR-0113): an insert must provide a non-null value, and an update may not null it out. With the field's own `visibleWhen` it is required WHEN SHOWN: a write whose record the predicate hides does not need it, a write that reveals the field empty is refused, and a predicate the server cannot evaluate counts as shown. On a multi-value lookup (`multiple: true`) required means NON-EMPTY array — an emptied required set fails validation loudly; `[]` does not satisfy it. NOT a column constraint — the physical NOT NULL is a separate explicit opt-in (`storage.notNull`), so tightening this on a deployed object is safe: existing null rows stay readable, and editable as long as the write does not touch this field. | | **storage** | `{ notNull?: boolean }` | optional | Physical storage constraints (ADR-0113). Owns the DDL the write contract deliberately does not imply. Absent = no storage-level constraint requested. | | **searchable** | `boolean` | optional (default: `false`) | Search this field when its object declares no `searchableFields`. The set `search` scans, and the set a `$searchFields` override may name, is then the type-based default (the text-like and select columns) plus every field marked `searchable: true`, of any type except `secret`, `password` and `vector`, which stay excluded (a virtual `formula` field has no stored column, so it is never scanned either). `false`, the default, does not remove a field the type-based default already scans; to choose the set, declare `searchableFields`. When the object declares `searchableFields`, that list is the whole search set and this flag is not read (ADR-0061). | | **multiple** | `boolean` | optional (default: `false`) | Allow multiple values (Stores as Array/JSON). Declarable ONLY on the multi-capable types — select, lookup, user, file, image — and redundantly on the inherently-multi option types (multiselect, checkboxes, tags); `multiple: true` on any other type, `radio` included, is REFUSED at parse. A cleared optional multi-value field is stored as `null`, the same as one never set: an empty list `[]` or an empty string written to it stores `null`, and the rule binds every writer (cascade repair, form clears, API writes). Read `null` and `[]` alike as empty, as the `is_empty` filter (`$empty`) does, since a row stored before this rule can still hold `[]`. On a `required` multi-value field the empty list is refused: `required` means a non-empty list. | @@ -106,7 +106,7 @@ const result = CurrencyConfigSchema.parse(data); | **dimensions** | `integer` | optional | Vector dimensionality (e.g., 1536 for OpenAI embeddings) | | **trackHistory** | `boolean` | optional | Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field. | | **group** | `string` | optional | Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system") | -| **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'` | +| **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`. On a `required` field the server reads it on every write: where it is not TRUE (FALSE, or null such as an unset boolean) the field is not required for that write, and a predicate the server cannot evaluate counts as shown, so the field stays required. Reads the record's own columns, with `formula` fields computed over the record being written, as the form computes them over the record being edited; a read THROUGH a reference field, or a formula that reads through one, calls label(), calls can() on a write that picks no permission-gated option, or reads current_user on a system write with no user, cannot be evaluated there. | | **readonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every update that writes the field — `objectstack validate` refuses it. Put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. | | **requiredWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is required when TRUE. A TRANSITION GATE, not an invariant: the write is refused only when the merged record violates the requirement AND the pre-write record complied — so the write that flips the predicate TRUE, an INSERT born inside the gate, and a write that clears the cell are all refused, while a row that was already missing the value keeps passing unrelated edits and state moves that stay inside the gate (ADR-0113 non-regression: adding the rule to a deployed object never bricks existing rows). Need an invariant every write must satisfy instead ('X may never exceed Y') — declare a `validations[]` `script` rule, which re-checks the merged record with no exemption. Enforced by `evaluateValidationRules`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every write that reaches it — `objectstack validate` refuses it; put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. The only slot; the `conditionalRequired` alias was removed in protocol 17. | | **dueLike** | `boolean` | optional | Deadline semantic (`date` / `datetime` only): TRUE declares this date a deadline, so a renderer may show relative overdue wording ("Overdue 3d") and an overdue colour once it has passed. Absent or FALSE: not a deadline — nothing is inferred from the field's name. Pair with `settledWhen` to say when the deadline is settled for a record. Refused on any other type. Display only: nothing on the write path reads it. | diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index e05806f2f96..75c9fbba046 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -233,7 +233,7 @@ const result = ApiMethod.parse(data); | **type** | `Enum<'text' \| 'textarea' \| 'email' \| 'url' \| 'phone' \| 'password' \| 'secret' \| …>` | ✅ | Field Data Type | | **description** | `string` | optional | Tooltip/Help text | | **format** | `string` | optional | Free-form string whose meaning depends on the field type and on the reader. The spec declares NO vocabulary for it and checks nothing but that it is a string, so any string parses on any field type. On an `autonumber` field it is the record-number PATTERN — the shorthand that predates `autonumberFormat`, which wins when both are present: `format: 'INV-{0000}'` mints `INV-0001` on both the query engine and the SQL driver, while a value carrying no `{...}` token is emitted as literal text with the bare counter appended (`format: 'email'` mints `email1`). Prefer `autonumberFormat` on a new field. On any other field type the server does not act on it: it picks no column type, coerces no value and runs no check from it. The Studio UI reads it as a display hint, in words and with defaults that its renderers own and declare. For example, the `date` and `datetime` cells read it as a display STYLE, and on a plain-text field the shared cell-renderer resolver reads a small set of words that promote the cell to a richer renderer, such as a link; each of those falls back silently to a default rendering when it does not recognise the word. To constrain a VALUE, use the field `type` (the write-time record validator's built-in email, url and phone checks key on `type`, never on this key) or a `format` validation rule, whose own `format` key is the closed set `email` \| `url` \| `phone` \| `json`. | -| **required** | `boolean` | optional (default: `false`) | Write-time contract (ADR-0113): an insert must provide a non-null value, and an update may not null it out. On a multi-value lookup (`multiple: true`) required means NON-EMPTY array — an emptied required set fails validation loudly; `[]` does not satisfy it. NOT a column constraint — the physical NOT NULL is a separate explicit opt-in (`storage.notNull`), so tightening this on a deployed object is safe: existing null rows stay readable, and editable as long as the write does not touch this field. | +| **required** | `boolean` | optional (default: `false`) | Write-time contract (ADR-0113): an insert must provide a non-null value, and an update may not null it out. With the field's own `visibleWhen` it is required WHEN SHOWN: a write whose record the predicate hides does not need it, a write that reveals the field empty is refused, and a predicate the server cannot evaluate counts as shown. On a multi-value lookup (`multiple: true`) required means NON-EMPTY array — an emptied required set fails validation loudly; `[]` does not satisfy it. NOT a column constraint — the physical NOT NULL is a separate explicit opt-in (`storage.notNull`), so tightening this on a deployed object is safe: existing null rows stay readable, and editable as long as the write does not touch this field. | | **storage** | `{ notNull?: boolean }` | optional | Physical storage constraints (ADR-0113). Owns the DDL the write contract deliberately does not imply. Absent = no storage-level constraint requested. | | **searchable** | `boolean` | optional (default: `false`) | Search this field when its object declares no `searchableFields`. The set `search` scans, and the set a `$searchFields` override may name, is then the type-based default (the text-like and select columns) plus every field marked `searchable: true`, of any type except `secret`, `password` and `vector`, which stay excluded (a virtual `formula` field has no stored column, so it is never scanned either). `false`, the default, does not remove a field the type-based default already scans; to choose the set, declare `searchableFields`. When the object declares `searchableFields`, that list is the whole search set and this flag is not read (ADR-0061). | | **multiple** | `boolean` | optional (default: `false`) | Allow multiple values (Stores as Array/JSON). Declarable ONLY on the multi-capable types — select, lookup, user, file, image — and redundantly on the inherently-multi option types (multiselect, checkboxes, tags); `multiple: true` on any other type, `radio` included, is REFUSED at parse. A cleared optional multi-value field is stored as `null`, the same as one never set: an empty list `[]` or an empty string written to it stores `null`, and the rule binds every writer (cascade repair, form clears, API writes). Read `null` and `[]` alike as empty, as the `is_empty` filter (`$empty`) does, since a row stored before this rule can still hold `[]`. On a `required` multi-value field the empty list is refused: `required` means a non-empty list. | @@ -284,7 +284,7 @@ const result = ApiMethod.parse(data); | **dimensions** | `integer` | optional | Vector dimensionality (e.g., 1536 for OpenAI embeddings) | | **trackHistory** | `boolean` | optional | Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field. | | **group** | `string` | optional | Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system") | -| **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'` | +| **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`. On a `required` field the server reads it on every write: where it is not TRUE (FALSE, or null such as an unset boolean) the field is not required for that write, and a predicate the server cannot evaluate counts as shown, so the field stays required. Reads the record's own columns, with `formula` fields computed over the record being written, as the form computes them over the record being edited; a read THROUGH a reference field, or a formula that reads through one, calls label(), calls can() on a write that picks no permission-gated option, or reads current_user on a system write with no user, cannot be evaluated there. | | **readonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every update that writes the field — `objectstack validate` refuses it. Put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. | | **requiredWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is required when TRUE. A TRANSITION GATE, not an invariant: the write is refused only when the merged record violates the requirement AND the pre-write record complied — so the write that flips the predicate TRUE, an INSERT born inside the gate, and a write that clears the cell are all refused, while a row that was already missing the value keeps passing unrelated edits and state moves that stay inside the gate (ADR-0113 non-regression: adding the rule to a deployed object never bricks existing rows). Need an invariant every write must satisfy instead ('X may never exceed Y') — declare a `validations[]` `script` rule, which re-checks the merged record with no exemption. Enforced by `evaluateValidationRules`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every write that reaches it — `objectstack validate` refuses it; put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. The only slot; the `conditionalRequired` alias was removed in protocol 17. | | **dueLike** | `boolean` | optional | Deadline semantic (`date` / `datetime` only): TRUE declares this date a deadline, so a renderer may show relative overdue wording ("Overdue 3d") and an overdue colour once it has passed. Absent or FALSE: not a deadline — nothing is inferred from the field's name. Pair with `settledWhen` to say when the deadline is settled for a record. Refused on any other type. Display only: nothing on the write path reads it. | @@ -613,7 +613,7 @@ const result = ApiMethod.parse(data); | **type** | `Enum<'text' \| 'textarea' \| 'email' \| 'url' \| 'phone' \| 'password' \| 'secret' \| …>` | ✅ | Field Data Type | | **description** | `string` | optional | Tooltip/Help text | | **format** | `string` | optional | Free-form string whose meaning depends on the field type and on the reader. The spec declares NO vocabulary for it and checks nothing but that it is a string, so any string parses on any field type. On an `autonumber` field it is the record-number PATTERN — the shorthand that predates `autonumberFormat`, which wins when both are present: `format: 'INV-{0000}'` mints `INV-0001` on both the query engine and the SQL driver, while a value carrying no `{...}` token is emitted as literal text with the bare counter appended (`format: 'email'` mints `email1`). Prefer `autonumberFormat` on a new field. On any other field type the server does not act on it: it picks no column type, coerces no value and runs no check from it. The Studio UI reads it as a display hint, in words and with defaults that its renderers own and declare. For example, the `date` and `datetime` cells read it as a display STYLE, and on a plain-text field the shared cell-renderer resolver reads a small set of words that promote the cell to a richer renderer, such as a link; each of those falls back silently to a default rendering when it does not recognise the word. To constrain a VALUE, use the field `type` (the write-time record validator's built-in email, url and phone checks key on `type`, never on this key) or a `format` validation rule, whose own `format` key is the closed set `email` \| `url` \| `phone` \| `json`. | -| **required** | `boolean` | optional (default: `false`) | Write-time contract (ADR-0113): an insert must provide a non-null value, and an update may not null it out. On a multi-value lookup (`multiple: true`) required means NON-EMPTY array — an emptied required set fails validation loudly; `[]` does not satisfy it. NOT a column constraint — the physical NOT NULL is a separate explicit opt-in (`storage.notNull`), so tightening this on a deployed object is safe: existing null rows stay readable, and editable as long as the write does not touch this field. | +| **required** | `boolean` | optional (default: `false`) | Write-time contract (ADR-0113): an insert must provide a non-null value, and an update may not null it out. With the field's own `visibleWhen` it is required WHEN SHOWN: a write whose record the predicate hides does not need it, a write that reveals the field empty is refused, and a predicate the server cannot evaluate counts as shown. On a multi-value lookup (`multiple: true`) required means NON-EMPTY array — an emptied required set fails validation loudly; `[]` does not satisfy it. NOT a column constraint — the physical NOT NULL is a separate explicit opt-in (`storage.notNull`), so tightening this on a deployed object is safe: existing null rows stay readable, and editable as long as the write does not touch this field. | | **storage** | `{ notNull?: boolean }` | optional | Physical storage constraints (ADR-0113). Owns the DDL the write contract deliberately does not imply. Absent = no storage-level constraint requested. | | **searchable** | `boolean` | optional (default: `false`) | Search this field when its object declares no `searchableFields`. The set `search` scans, and the set a `$searchFields` override may name, is then the type-based default (the text-like and select columns) plus every field marked `searchable: true`, of any type except `secret`, `password` and `vector`, which stay excluded (a virtual `formula` field has no stored column, so it is never scanned either). `false`, the default, does not remove a field the type-based default already scans; to choose the set, declare `searchableFields`. When the object declares `searchableFields`, that list is the whole search set and this flag is not read (ADR-0061). | | **multiple** | `boolean` | optional (default: `false`) | Allow multiple values (Stores as Array/JSON). Declarable ONLY on the multi-capable types — select, lookup, user, file, image — and redundantly on the inherently-multi option types (multiselect, checkboxes, tags); `multiple: true` on any other type, `radio` included, is REFUSED at parse. A cleared optional multi-value field is stored as `null`, the same as one never set: an empty list `[]` or an empty string written to it stores `null`, and the rule binds every writer (cascade repair, form clears, API writes). Read `null` and `[]` alike as empty, as the `is_empty` filter (`$empty`) does, since a row stored before this rule can still hold `[]`. On a `required` multi-value field the empty list is refused: `required` means a non-empty list. | @@ -664,7 +664,7 @@ const result = ApiMethod.parse(data); | **dimensions** | `integer` | optional | Vector dimensionality (e.g., 1536 for OpenAI embeddings) | | **trackHistory** | `boolean` | optional | Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field. | | **group** | `string` | optional | Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system") | -| **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'` | +| **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`. On a `required` field the server reads it on every write: where it is not TRUE (FALSE, or null such as an unset boolean) the field is not required for that write, and a predicate the server cannot evaluate counts as shown, so the field stays required. Reads the record's own columns, with `formula` fields computed over the record being written, as the form computes them over the record being edited; a read THROUGH a reference field, or a formula that reads through one, calls label(), calls can() on a write that picks no permission-gated option, or reads current_user on a system write with no user, cannot be evaluated there. | | **readonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every update that writes the field — `objectstack validate` refuses it. Put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. | | **requiredWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is required when TRUE. A TRANSITION GATE, not an invariant: the write is refused only when the merged record violates the requirement AND the pre-write record complied — so the write that flips the predicate TRUE, an INSERT born inside the gate, and a write that clears the cell are all refused, while a row that was already missing the value keeps passing unrelated edits and state moves that stay inside the gate (ADR-0113 non-regression: adding the rule to a deployed object never bricks existing rows). Need an invariant every write must satisfy instead ('X may never exceed Y') — declare a `validations[]` `script` rule, which re-checks the merged record with no exemption. Enforced by `evaluateValidationRules`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every write that reaches it — `objectstack validate` refuses it; put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. The only slot; the `conditionalRequired` alias was removed in protocol 17. | | **dueLike** | `boolean` | optional | Deadline semantic (`date` / `datetime` only): TRUE declares this date a deadline, so a renderer may show relative overdue wording ("Overdue 3d") and an overdue colour once it has passed. Absent or FALSE: not a deadline — nothing is inferred from the field's name. Pair with `settledWhen` to say when the deadline is settled for a record. Refused on any other type. Display only: nothing on the write path reads it. | diff --git a/content/docs/references/system/migration.mdx b/content/docs/references/system/migration.mdx index 78bfd1f989a..79de59dda95 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -58,7 +58,7 @@ Add a new field to an existing object | **type** | `Enum<'text' \| 'textarea' \| 'email' \| 'url' \| 'phone' \| 'password' \| 'secret' \| …>` | ✅ | Field Data Type | | **description** | `string` | optional | Tooltip/Help text | | **format** | `string` | optional | Free-form string whose meaning depends on the field type and on the reader. The spec declares NO vocabulary for it and checks nothing but that it is a string, so any string parses on any field type. On an `autonumber` field it is the record-number PATTERN — the shorthand that predates `autonumberFormat`, which wins when both are present: `format: 'INV-{0000}'` mints `INV-0001` on both the query engine and the SQL driver, while a value carrying no `{...}` token is emitted as literal text with the bare counter appended (`format: 'email'` mints `email1`). Prefer `autonumberFormat` on a new field. On any other field type the server does not act on it: it picks no column type, coerces no value and runs no check from it. The Studio UI reads it as a display hint, in words and with defaults that its renderers own and declare. For example, the `date` and `datetime` cells read it as a display STYLE, and on a plain-text field the shared cell-renderer resolver reads a small set of words that promote the cell to a richer renderer, such as a link; each of those falls back silently to a default rendering when it does not recognise the word. To constrain a VALUE, use the field `type` (the write-time record validator's built-in email, url and phone checks key on `type`, never on this key) or a `format` validation rule, whose own `format` key is the closed set `email` \| `url` \| `phone` \| `json`. | -| **required** | `boolean` | optional (default: `false`) | Write-time contract (ADR-0113): an insert must provide a non-null value, and an update may not null it out. On a multi-value lookup (`multiple: true`) required means NON-EMPTY array — an emptied required set fails validation loudly; `[]` does not satisfy it. NOT a column constraint — the physical NOT NULL is a separate explicit opt-in (`storage.notNull`), so tightening this on a deployed object is safe: existing null rows stay readable, and editable as long as the write does not touch this field. | +| **required** | `boolean` | optional (default: `false`) | Write-time contract (ADR-0113): an insert must provide a non-null value, and an update may not null it out. With the field's own `visibleWhen` it is required WHEN SHOWN: a write whose record the predicate hides does not need it, a write that reveals the field empty is refused, and a predicate the server cannot evaluate counts as shown. On a multi-value lookup (`multiple: true`) required means NON-EMPTY array — an emptied required set fails validation loudly; `[]` does not satisfy it. NOT a column constraint — the physical NOT NULL is a separate explicit opt-in (`storage.notNull`), so tightening this on a deployed object is safe: existing null rows stay readable, and editable as long as the write does not touch this field. | | **storage** | `{ notNull?: boolean }` | optional | Physical storage constraints (ADR-0113). Owns the DDL the write contract deliberately does not imply. Absent = no storage-level constraint requested. | | **searchable** | `boolean` | optional (default: `false`) | Search this field when its object declares no `searchableFields`. The set `search` scans, and the set a `$searchFields` override may name, is then the type-based default (the text-like and select columns) plus every field marked `searchable: true`, of any type except `secret`, `password` and `vector`, which stay excluded (a virtual `formula` field has no stored column, so it is never scanned either). `false`, the default, does not remove a field the type-based default already scans; to choose the set, declare `searchableFields`. When the object declares `searchableFields`, that list is the whole search set and this flag is not read (ADR-0061). | | **multiple** | `boolean` | optional (default: `false`) | Allow multiple values (Stores as Array/JSON). Declarable ONLY on the multi-capable types — select, lookup, user, file, image — and redundantly on the inherently-multi option types (multiselect, checkboxes, tags); `multiple: true` on any other type, `radio` included, is REFUSED at parse. A cleared optional multi-value field is stored as `null`, the same as one never set: an empty list `[]` or an empty string written to it stores `null`, and the rule binds every writer (cascade repair, form clears, API writes). Read `null` and `[]` alike as empty, as the `is_empty` filter (`$empty`) does, since a row stored before this rule can still hold `[]`. On a `required` multi-value field the empty list is refused: `required` means a non-empty list. | @@ -109,7 +109,7 @@ Add a new field to an existing object | **dimensions** | `integer` | optional | Vector dimensionality (e.g., 1536 for OpenAI embeddings) | | **trackHistory** | `boolean` | optional | Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field. | | **group** | `string` | optional | Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system") | -| **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'` | +| **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`. On a `required` field the server reads it on every write: where it is not TRUE (FALSE, or null such as an unset boolean) the field is not required for that write, and a predicate the server cannot evaluate counts as shown, so the field stays required. Reads the record's own columns, with `formula` fields computed over the record being written, as the form computes them over the record being edited; a read THROUGH a reference field, or a formula that reads through one, calls label(), calls can() on a write that picks no permission-gated option, or reads current_user on a system write with no user, cannot be evaluated there. | | **readonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every update that writes the field — `objectstack validate` refuses it. Put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. | | **requiredWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is required when TRUE. A TRANSITION GATE, not an invariant: the write is refused only when the merged record violates the requirement AND the pre-write record complied — so the write that flips the predicate TRUE, an INSERT born inside the gate, and a write that clears the cell are all refused, while a row that was already missing the value keeps passing unrelated edits and state moves that stay inside the gate (ADR-0113 non-regression: adding the rule to a deployed object never bricks existing rows). Need an invariant every write must satisfy instead ('X may never exceed Y') — declare a `validations[]` `script` rule, which re-checks the merged record with no exemption. Enforced by `evaluateValidationRules`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every write that reaches it — `objectstack validate` refuses it; put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. The only slot; the `conditionalRequired` alias was removed in protocol 17. | | **dueLike** | `boolean` | optional | Deadline semantic (`date` / `datetime` only): TRUE declares this date a deadline, so a renderer may show relative overdue wording ("Overdue 3d") and an overdue colour once it has passed. Absent or FALSE: not a deadline — nothing is inferred from the field's name. Pair with `settledWhen` to say when the deadline is settled for a record. Refused on any other type. Display only: nothing on the write path reads it. | @@ -494,7 +494,7 @@ Add a new field to an existing object | **type** | `Enum<'text' \| 'textarea' \| 'email' \| 'url' \| 'phone' \| 'password' \| 'secret' \| …>` | ✅ | Field Data Type | | **description** | `string` | optional | Tooltip/Help text | | **format** | `string` | optional | Free-form string whose meaning depends on the field type and on the reader. The spec declares NO vocabulary for it and checks nothing but that it is a string, so any string parses on any field type. On an `autonumber` field it is the record-number PATTERN — the shorthand that predates `autonumberFormat`, which wins when both are present: `format: 'INV-{0000}'` mints `INV-0001` on both the query engine and the SQL driver, while a value carrying no `{...}` token is emitted as literal text with the bare counter appended (`format: 'email'` mints `email1`). Prefer `autonumberFormat` on a new field. On any other field type the server does not act on it: it picks no column type, coerces no value and runs no check from it. The Studio UI reads it as a display hint, in words and with defaults that its renderers own and declare. For example, the `date` and `datetime` cells read it as a display STYLE, and on a plain-text field the shared cell-renderer resolver reads a small set of words that promote the cell to a richer renderer, such as a link; each of those falls back silently to a default rendering when it does not recognise the word. To constrain a VALUE, use the field `type` (the write-time record validator's built-in email, url and phone checks key on `type`, never on this key) or a `format` validation rule, whose own `format` key is the closed set `email` \| `url` \| `phone` \| `json`. | -| **required** | `boolean` | optional (default: `false`) | Write-time contract (ADR-0113): an insert must provide a non-null value, and an update may not null it out. On a multi-value lookup (`multiple: true`) required means NON-EMPTY array — an emptied required set fails validation loudly; `[]` does not satisfy it. NOT a column constraint — the physical NOT NULL is a separate explicit opt-in (`storage.notNull`), so tightening this on a deployed object is safe: existing null rows stay readable, and editable as long as the write does not touch this field. | +| **required** | `boolean` | optional (default: `false`) | Write-time contract (ADR-0113): an insert must provide a non-null value, and an update may not null it out. With the field's own `visibleWhen` it is required WHEN SHOWN: a write whose record the predicate hides does not need it, a write that reveals the field empty is refused, and a predicate the server cannot evaluate counts as shown. On a multi-value lookup (`multiple: true`) required means NON-EMPTY array — an emptied required set fails validation loudly; `[]` does not satisfy it. NOT a column constraint — the physical NOT NULL is a separate explicit opt-in (`storage.notNull`), so tightening this on a deployed object is safe: existing null rows stay readable, and editable as long as the write does not touch this field. | | **storage** | `{ notNull?: boolean }` | optional | Physical storage constraints (ADR-0113). Owns the DDL the write contract deliberately does not imply. Absent = no storage-level constraint requested. | | **searchable** | `boolean` | optional (default: `false`) | Search this field when its object declares no `searchableFields`. The set `search` scans, and the set a `$searchFields` override may name, is then the type-based default (the text-like and select columns) plus every field marked `searchable: true`, of any type except `secret`, `password` and `vector`, which stay excluded (a virtual `formula` field has no stored column, so it is never scanned either). `false`, the default, does not remove a field the type-based default already scans; to choose the set, declare `searchableFields`. When the object declares `searchableFields`, that list is the whole search set and this flag is not read (ADR-0061). | | **multiple** | `boolean` | optional (default: `false`) | Allow multiple values (Stores as Array/JSON). Declarable ONLY on the multi-capable types — select, lookup, user, file, image — and redundantly on the inherently-multi option types (multiselect, checkboxes, tags); `multiple: true` on any other type, `radio` included, is REFUSED at parse. A cleared optional multi-value field is stored as `null`, the same as one never set: an empty list `[]` or an empty string written to it stores `null`, and the rule binds every writer (cascade repair, form clears, API writes). Read `null` and `[]` alike as empty, as the `is_empty` filter (`$empty`) does, since a row stored before this rule can still hold `[]`. On a `required` multi-value field the empty list is refused: `required` means a non-empty list. | @@ -545,7 +545,7 @@ Add a new field to an existing object | **dimensions** | `integer` | optional | Vector dimensionality (e.g., 1536 for OpenAI embeddings) | | **trackHistory** | `boolean` | optional | Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field. | | **group** | `string` | optional | Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system") | -| **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'` | +| **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`. On a `required` field the server reads it on every write: where it is not TRUE (FALSE, or null such as an unset boolean) the field is not required for that write, and a predicate the server cannot evaluate counts as shown, so the field stays required. Reads the record's own columns, with `formula` fields computed over the record being written, as the form computes them over the record being edited; a read THROUGH a reference field, or a formula that reads through one, calls label(), calls can() on a write that picks no permission-gated option, or reads current_user on a system write with no user, cannot be evaluated there. | | **readonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every update that writes the field — `objectstack validate` refuses it. Put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. | | **requiredWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — field is required when TRUE. A TRANSITION GATE, not an invariant: the write is refused only when the merged record violates the requirement AND the pre-write record complied — so the write that flips the predicate TRUE, an INSERT born inside the gate, and a write that clears the cell are all refused, while a row that was already missing the value keeps passing unrelated edits and state moves that stay inside the gate (ADR-0113 non-regression: adding the rule to a deployed object never bricks existing rows). Need an invariant every write must satisfy instead ('X may never exceed Y') — declare a `validations[]` `script` rule, which re-checks the merged record with no exemption. Enforced by `evaluateValidationRules`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every write that reaches it — `objectstack validate` refuses it; put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. The only slot; the `conditionalRequired` alias was removed in protocol 17. | | **dueLike** | `boolean` | optional | Deadline semantic (`date` / `datetime` only): TRUE declares this date a deadline, so a renderer may show relative overdue wording ("Overdue 3d") and an overdue colour once it has passed. Absent or FALSE: not a deadline — nothing is inferred from the field's name. Pair with `settledWhen` to say when the deadline is settled for a record. Refused on any other type. Display only: nothing on the write path reads it. | diff --git a/docs/adr/0020-state-machine-converge-and-enforce.md b/docs/adr/0020-state-machine-converge-and-enforce.md index 5d377f25c50..821960a17cb 100644 --- a/docs/adr/0020-state-machine-converge-and-enforce.md +++ b/docs/adr/0020-state-machine-converge-and-enforce.md @@ -49,7 +49,7 @@ So the guardrail goal is currently unmet at runtime. The only artefacts that exi #### The prior-state plumbing gap (the real implementation constraint) -A transition check needs **both** the prior and the new state. But the write path can't supply the prior state today: on update, [`packages/objectql/src/engine-update.ts#validateRecord`](../../packages/objectql/src/engine-update.ts) calls `validateRecord(schema, hookContext.input.data, 'update')` — passing only the **PATCH payload**, not the prior record. On `PATCH { status: 'done' }` there is no way to know the *from*-state without a read. So enforcing `state_machine` is not just "add a dispatch branch"; it requires **plumbing the prior (or merged) record into the rule-evaluation step**. This is a shared need: `cross_field` and `script` rules are equally crippled by receiving only the patch — so the fix should land **once for the whole `validations` union**, not as a `state_machine`-only patch (see D3). +A transition check needs **both** the prior and the new state. But the write path can't supply the prior state today: on update, [`packages/objectql/src/engine-update.ts`](../../packages/objectql/src/engine-update.ts) called `validateRecord(schema, hookContext.input.data, 'update')` when this record was written — passing only the **PATCH payload**, not the prior record. On `PATCH { status: 'done' }` there is no way to know the *from*-state without a read. So enforcing `state_machine` is not just "add a dispatch branch"; it requires **plumbing the prior (or merged) record into the rule-evaluation step**. This is a shared need: `cross_field` and `script` rules are equally crippled by receiving only the patch — so the fix should land **once for the whole `validations` union**, not as a `state_machine`-only patch (see D3). ### The design-center shift: AI is the author — optimise naming for the model's priors diff --git a/docs/adr/0113-required-write-contract-vs-column-constraint.md b/docs/adr/0113-required-write-contract-vs-column-constraint.md index e5f1121c657..11633b8914e 100644 --- a/docs/adr/0113-required-write-contract-vs-column-constraint.md +++ b/docs/adr/0113-required-write-contract-vs-column-constraint.md @@ -1,6 +1,7 @@ # ADR-0113: `required` is a write-time contract — the column constraint becomes its own, explicitly-authored axis **Status**: Accepted (2026-07-30) — Q1/Q2/Q3 adjudicated same day (uniform semantics; `storage.notNull` spelling; the non-regression invariant unifies `required` and `requiredWhen`). **P0 implemented**: spec knob + parse-seam exclusivity, record-validator null-out rejection, rule-validator non-regression, driver DDL + drift rewired, `field-required-notnull-explicit` conversion. P1 (Console required-marker from the write contract) and P2 (criteria_json flip) follow. +**Amended (2026-11-17)** — D1 and D5: a field that declares `required: true` together with its own `visibleWhen` is required **when shown** (maintainer ruling A on #34905, recorded in comment 6956761249). See [Amendment — required when shown](#amendment-2026-11-17--required-when-shown). **Deciders**: ObjectStack Protocol Architects **Builds on**: [ADR-0049](./0049-no-unenforced-security-properties.md) (enforce-or-remove), [ADR-0078](./0078-no-silently-inert-metadata.md) (no silently inert metadata), the #3896/#3929 sharing-criteria case study, `driver-sql/schema-drift.ts` (the drift classifier whose `destructive` class this ADR exists to route around) **Consumers**: `@objectstack/spec` (`FieldSchema`), `@objectstack/objectql` (`validation/record-validator.ts`), `@objectstack/driver-sql` (`sql-driver.ts` column DDL, `schema-drift.ts`), `@objectstack/lint`, objectui form renderers (the required marker) @@ -127,6 +128,13 @@ already violated. That write was a no-op carrying a false claim; rejecting it costs nothing and needs no prior fetch. (`requiredWhen` evaluates against the prior record it already fetches, so it applies the exact rule.) +> **Amended (2026-11-17).** "`required` is the degenerate always-true-condition +> case" now holds for a `required` field with no `visibleWhen`. A field that +> declares both takes its own `visibleWhen` as the condition, exactly as +> `requiredWhen` takes its predicate — see +> [Amendment — required when shown](#amendment-2026-11-17--required-when-shown). +> The over-approximation above stays for the unconditional knob. + ### D2 — the column constraint becomes explicit A new field-level storage property owns the DDL: @@ -165,6 +173,12 @@ removing the last reason for the objectui#2962-style mirror hints. contract — and the transition is carried by rewriting old sources, not by the loader guessing: +> **Amended (2026-11-17).** It is still one meaning, read off the source alone: +> the write contract, conditioned on the field's own `visibleWhen` when the +> source declares one. Both keys sit in the same field definition, so nothing +> here depends on history or the physical column, which is what this decision +> rules out. See [Amendment — required when shown](#amendment-2026-11-17--required-when-shown). + - **The `field-required-notnull-explicit` conversion** (D2 table, protocol-17 step) stamps `storage: { notNull: true }` onto every `required: true` field of a pre-17 source. Under the old semantics that column WAS created @@ -244,3 +258,157 @@ validator tightenings ride the major). "adopting" `required`'s asymmetry, both are corollaries of the one non-regression invariant. The knobs stay one family with one temporal semantics; no divergence window ever exists. + +## Amendment (2026-11-17) — required when shown + +**Ruling.** Maintainer ruling A on #34905 (2026-11-17 18:10Z, recorded in issue +comment 6956761249): 「A 显示时必填+切换校验」 — hidden means not required, and a +write that shows the field without filling it is refused. + +**Why.** A field that is `required` and hidden by its `visibleWhen` was enforced +on every save. In Studio an administrator adds such a field to an object in a +few clicks, and from then on every record outside the condition refuses every +write, including an edit of an unrelated field, naming a field nobody can see or +fill. The form already drops the marker and the client check for a hidden field +(D4), and it writes `null` into a field its `visibleWhen` hides (clear-on-hide), +which the server then refused. The server is the side that decides (ADR-0124 +D1), so it now judges the requirement from the field's own visibility, as the +form does, on the record being written. For a `formula` the predicate reads the +two sides can differ; see the formula paragraph below. + +**The rule.** For a field with `required: true` and its own `visibleWhen` +(`evaluateRequiredWhenShown`, `packages/objectql/src/validation/rule-validator.ts`): + +1. **Hidden** — the predicate evaluates cleanly to anything but TRUE on the + merged record (stored row with the write over it): FALSE, or a `null` such as + an unset boolean under `visibleWhen: record.is_vip`. The requirement does not + apply to this write. This is the form's reading: it shows a field only for a + clean TRUE, and `requiredWhen` holds its condition only on TRUE. *Widening.* +2. **Shown** — cleanly TRUE: D1's non-regression invariant with the predicate as + the condition, judged against the prior record the engine now reads for such + a field. A write that reveals the field empty is refused; a row already shown + and empty rests under unrelated edits, and an explicit `null` onto it is + accepted (the exact rule, as `requiredWhen` has). *Narrowing:* a write that + moves a record into the condition without filling the field was accepted + before this amendment and is refused now — on a flow, a bulk update (one such + row refuses the batch), an import or an API PATCH alike. +3. **Fault** — the predicate cannot be evaluated (including a `formula` it reads + whose read value the write path cannot know, see below): it **counts as shown**, and the + field takes exactly the unconditional rule above (an insert must provide it, + an update may not clear it). The write is not refused for the fault itself: + this is not ADR-0137 D2's field-rule arm, because the fault costs only the + waiver, and the fallback is the behaviour every app had before. The fault is + logged at `warn`, naming the field and the fault (ADR-0137 D4). + +**Scope of the predicate.** `record`, `previous`, the acting user as +`current_user` (and its ADR-0068 aliases, with the permission map the option +gate reads) and `parent` where the write resolves a header. Binding the user +makes the requirement depend on who writes, which is what "required when shown" +means for a role-gated field; a system write with no acting user takes the fault +arm, logged as `no-acting-user`, whether the predicate reads the user directly or +through a `formula` that reads it (below). The lint refuses `current_user` in a field `visibleWhen` at authoring (see +the fence below), so that binding serves older stored metadata. `features`, +`app` and `page` are never bound on the server. + +**A `formula` field the predicate reads.** A formula is computed on read and is +never on the write path, so the stored row and the payload do not hold it. The +engine computes the object's formulas over the merged record and over the prior +record with the read path's own plan before it evaluates the predicate, so the +predicate sees the value a read of that record would serve +(`formulaValuesFor`, `packages/objectql/src/engine-top-level.ts`). A formula +that does not compute is answered by the reason, in two arms: + +- *A fault a read shares* — an operator over an empty operand (`record.amount > + 100` with `amount` unset), an undeclared key, a cycle of formulas. A read + serves `null` for it, so the predicate is judged on that `null`, which is what + the form judges: usually hidden. Not a fault of the predicate. +- *A value only a read can have* — the formula reads through a reference (the + write path follows no hop), calls `label()` (no option labels are read on a + write), calls `current_user.can()` and the write resolved no permission + map (it resolves one only when it picks a permission-gated option, so such a + formula is computed on that write and not on another), or reads the acting + user (`current_user` and its ADR-0068 aliases, or any bare `ctx` / `os` read + such as `os.org`, since the engine cannot separate the user-dependent part of + such a read; the result is the unconditional `required`) on a write that has + none, a system write, where a read would compute it for its reader; or it reads such + a formula, at any depth of the formulas it reads. A + formula over one can compute cleanly over the `null` it reads on the write + path and still not be the value a read serves, so the whole read closure + counts. The predicate is a fault, which counts as shown: the field keeps the + unconditional `required`, and the log names the chain (`reason: + 'no-acting-user'` when the missing user alone blocks it). The lint warns + about the first three marks (below); it does not warn about the acting-user + mark, since a formula reading the user is computed per writer on every write + that has one. + +**The form recomputes a formula too (a limit this amendment first recorded, +now closed).** The form used to judge the predicate on the formula value it +last read, none on a create, so it could hide a field the server required. It +now computes the object's `formula` fields over the record being edited before +it judges the field rules: the object form renderer over its `ruleRecord` +(`form.tsx`) and the console's form-view page over its live values +(`FormPage.tsx`), both through `planObjectFormulas` (`@object-ui/core`, +`formulaRecord.ts`) with the canonical `@objectstack/formula` engine in the +read order, binding the signed-in user's id and positions as +`applyFormulaPlan` binds them. What is left: a wizard's final-submit gate +(`gateFinalSubmit`, `WizardForm.tsx`) still judges `resolveFieldRuleState` over +its merged form values with no formula plan, and a form whose data source has +no `getObjectSchema`, or whose schema read fails, gets no plan +(`objectFormulas.ts`) and computes nothing, so both judge the formula value +last read, none on a create. A formula the form cannot compute (it reads +through a reference, calls `label()` or `current_user.can()`, reads `os`, +reads the user when nobody is signed in, is served without its expression, or +reads such a formula) drops the `visibleWhen` that reads it: the field is shown +and keeps its `required` flag, and the server, which judges the write, decides. +For a formula that reads `os`, calls `can()` or is served without its +expression (a field-level-security mask) the form can be stricter than the +server, which may compute it and hide the field. The server's answer is +the one ruling item 2 asks for. + +**Author-time fence (narrowed from the ruling's item 4).** The ruling asked for a +warning on `required` + `visibleWhen` reading roots the server cannot bind. That +half already exists at a stronger level: `@objectstack/lint` refuses every root +but `record`, `previous` and `parent` in any field `visibleWhen` +(`FIELD_RULE_BOUND_ROOTS`), at `objectstack validate`, at the object save door +and in Studio's predicate editor, so those roots reach the server only from +older stored metadata, which the fault arm covers. What is added are three +**warnings**, never refusals, since the field keeps the requirement it had: +a `required` field's `visibleWhen` that reads through a reference field (never +hydrated at the field level, so it always faults); one that reads a `formula` +field (written for the form-side limit above, since closed, and, when a formula in its read closure reads +through a reference or calls `label()` or `can`, the counts-as-shown +consequence; `required-visible-when-formula-issue.ts`, with the same verdict as +a Studio advisory in the field inspector); and `required` + `visibleWhen` ++ `storage.notNull` (the column refuses the null the waiver admits). The latter +is not a parse refusal like the Q1 rider, because the protocol-17 +`field-required-notnull-explicit` conversion stamped `storage.notNull` onto every +older `required` field; for those fields this amendment changes nothing on create. + +**Not in scope.** Only the object field's own `visibleWhen`. A field group's +`visibleWhen`, a form view's field or section predicate, a hidden tab and static +`hidden` are not read: the validator does not consume view metadata (ruled on +#13252; Studio's gated-section fence covers the section case at authoring). + +**Which server answer is canonical.** Three server sites answer "required, but +hidden". For the **record write contract** this rule is canonical; it is the +only one that judges an object field. The other two judge their own surface's +declarations before the engine sees the write, and keep their directions: +a flow screen's `required` field (`screen-input-contract.ts`) treats an +unevaluable predicate as not asked, because a screen field is input to a flow, +not a record column; the public form route (`form-routes.ts`) does not add a +form-view entry that has a `visibleWhen` to its own required list. A record +either of them writes is then judged by this rule. + +**Other readers left as they are.** The import template, the action parameter +schema and the MCP field descriptions still describe such a field as required. +The seed loader's early required warning (`requiredOnInsertByObject`) is now an +approximation for such a field: it warns where the write may waive. ADR-0124 D4 +allows a client hint stricter than the server, so they are listed here rather +than changed. + +**Where the refusal comes from.** The record walk no longer judges such a field; +the rule pass does, after the hooks, the strips and (on a non-system write) the +reference check. A write with one fault gets the same `required` code and +sentence. A write with several faults may name fewer of them in one `400`, or +answer a dangling reference first, and a `beforeUpdate` hook runs before the +refusal and may fill the field. diff --git a/docs/adr/0137-predicate-fault-semantics-are-contract.md b/docs/adr/0137-predicate-fault-semantics-are-contract.md index b4edf0ee4c0..f8ed4e76271 100644 --- a/docs/adr/0137-predicate-fault-semantics-are-contract.md +++ b/docs/adr/0137-predicate-fault-semantics-are-contract.md @@ -1,6 +1,6 @@ # ADR-0137: A predicate's FAULT semantics are part of the protocol — loud at submit, fail-open at render, and a blank predicate is a declared third state -**Status**: Accepted (2026-09-18) — **this record declares; it implements nothing.** D1's authoring refusal is ruled by decision batch #122 item 2 (card #15811, [`5644350409`](https://github.com/objectstack-ai/objectstack/issues/15811#issuecomment-5644350409), 2026-09-12) and lands in PR #18638, which owns the accept-set narrowing across every evaluated slot under one ADR-0087 id — this record's own PR carries **no** schema change, by decision batch #160 item 1 (2026-09-18: 「同意」 to **A**). **D2 / D3 / D4 are declared here and delivered by consumers** — the renderer and submit path in objectui#8069, which is `pm:blocked` on this record. See [Scope boundary](#scope-boundary-what-this-record-does-not-land) for what this record does not land and who lands it. +**Status**: Accepted (2026-09-18); amended 2026-11-17 (a server row for a `required` field's own `visibleWhen`, under D2) — **this record declares; it implements nothing.** D1's authoring refusal is ruled by decision batch #122 item 2 (card #15811, [`5644350409`](https://github.com/objectstack-ai/objectstack/issues/15811#issuecomment-5644350409), 2026-09-12) and lands in PR #18638, which owns the accept-set narrowing across every evaluated slot under one ADR-0087 id — this record's own PR carries **no** schema change, by decision batch #160 item 1 (2026-09-18: 「同意」 to **A**). **D2 / D3 / D4 are declared here and delivered by consumers** — the renderer and submit path in objectui#8069, which is `pm:blocked` on this record. See [Scope boundary](#scope-boundary-what-this-record-does-not-land) for what this record does not land and who lands it. **Deciders**: ObjectStack Protocol Architects (maintainer ruling on objectui#8069, decision batch #119 item 3, 2026-09-12: 「同意」 to **A**, with **Q2 yes** and **Q3 yes**), filed as objectstack#17778 by the director seat **Builds on**: [ADR-0058](./0058-expression-and-predicate-surface.md) (the expression & predicate surface — its D5 predicate failure tiers are the table this record writes the field-rule row of), [ADR-0089](./0089-unify-visibility-predicate-naming.md) (unified the `*When` family under one NAME; this record decides what that family does when it cannot RUN), [ADR-0087](./0087-metadata-protocol-upgrade-contract.md) (conversion-over-notification — D1 lands as a D3 semantic entry because no D2 conversion exists), [ADR-0124](./0124-server-enforces-client-is-courtesy.md) (D1 server-enforces — why a render-side direction is never the whole answer), [ADR-0078](./0078-no-silently-inert-metadata.md) (no silently-inert metadata — a predicate that cannot run is the purest case), [ADR-0049](./0049-no-unenforced-security-properties.md) (enforce-or-remove), [ADR-0032](./0032-unified-expression-layer.md) (the CEL layer these predicates are written in) **Consumers**: `@objectstack/spec` (`shared/expression.zod.ts` — the predicate contract; `data/field.zod.ts` — the field-rule triad), `@objectstack/objectql` (`validation/rule-validator.ts` — the server-side enforcer whose three fault directions this record measured), `@objectstack/lint` (`validate-expressions.ts`, `validate-visibility-predicates.ts` — the author-time reporters), and the ObjectUI form renderer + submit path (objectui#8069) @@ -146,6 +146,36 @@ A blank predicate takes this path too, wherever one is already stored — D1 kee new ones from being authored, and D2 is what a stored one meets. That is what makes "blank" a declared **third** state rather than a spelling of "no rule". +> **Amended (2026-11-17) — a new server row: a `required` field's own +> `visibleWhen` at submit.** Since ADR-0113's amendment of that date (ruling A +> on #34905, comment 6956761249) the write path evaluates the `visibleWhen` of a +> field that is also `required`, to decide whether the requirement applies. +> That row does **not** take D2's refusal: a fault there **counts as shown**, +> the field keeps the unconditional `required` it carried before, and the fault +> is logged per D4. D2's reason does not reach it — the fallback invents no +> verdict the author did not write, it is the requirement the author did write, +> left in force — and it is D3's direction carried to the server: a faulting +> `visibleWhen` shows the field, and a shown required field must be filled. +> A `formula` field the predicate reads whose read value the write path cannot +> know (it reads through a reference, calls `label()`, calls `can` on a write +> that resolved no permission map, reads the acting user on a write that has +> none, or reads such a formula) is such a fault; the acting-user case is +> logged as `no-acting-user`, as the direct `current_user` spelling is. That +> mark covers any read of a bare user-scope root (`current_user`, its ADR-0068 +> aliases, or a bare `ctx` / `os` read such as `os.org`), because the engine +> cannot separate the user-dependent part of such a read; the field then keeps +> the unconditional `required` it carried before this amendment. A +> formula calling `can` is computed on a write that picks a permission-gated +> option, which resolves the map. A formula that faults for a reason a read shares (an +> empty operand) is not: the predicate is judged on the `null` a read serves. A +> clean verdict that is not TRUE (FALSE, or `null`) is not a fault: it hides the +> field, as the form reads it. +> +> | slot, at submit | on a fault | +> |---|---| +> | `requiredWhen`, `readonlyWhen`, an option's `visibleWhen` | refused (D2) | +> | a `required` field's own `visibleWhen` (a formula it reads that the write path cannot compute included) | counted as shown: required, logged (D4) | + ### D3 — At RENDER, visibility stays fail-OPEN A faulting `visibleWhen` **shows** the field. `readonlyWhen` / `requiredWhen` keep diff --git a/packages/lint/src/required-visible-when-formula-issue.ts b/packages/lint/src/required-visible-when-formula-issue.ts new file mode 100644 index 00000000000..58f8ed19a9f --- /dev/null +++ b/packages/lint/src/required-visible-when-formula-issue.ts @@ -0,0 +1,173 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0113 D1, as amended] A `required` field whose own `visibleWhen` reads a + * `formula` field draws a WARNING where it is authored. + * + * The server judges the requirement on every write from that predicate, with + * each formula it reads computed over the record being written, the value a + * read of that record would serve. Two things the author can see at build time: + * + * - **The server's computed value decides.** The form computes the object's + * formulas over the record being edited before it judges the predicate + * (ADR-0113, as amended), so for a formula it can compute it judges what + * the server judges. A check that computes none, a wizard's final-submit + * check or a form whose data source serves no object schema, judges the + * formula value last read, none on a create, and can disagree with the + * server; the warning is the reminder that the server's value decides. + * - **Some formulas the write path cannot compute at all.** A formula that + * reads through a reference, calls `label()` or calls `current_user.can()`, + * or reads such a formula at any depth: the server cannot know the value a + * read serves, counts the predicate as SHOWN, and the field stays required + * on every write. The form cannot compute such a formula either: it shows + * the field and keeps it required. The engine's + * classifier is `unservableReason` in `@objectstack/objectql` + * (`engine-top-level.ts`); this reads the same three marks off the same + * sources (the member reader for reads and hops, `label(` as the engine's + * `planCallsOptionLabel` spells it, a `can` receiver call off the parse). + * A `can` call is the one the engine does compute on a write that picks a + * permission-gated option (that write resolves the permission map), so the + * message says the verdict for such a field can differ between writes. + * The engine's fourth mark, a formula that reads the acting user on a + * write with none (a system write, logged `no-acting-user`), draws no + * warning: such a formula is computed per writer on every write that has + * one, and the counts-as-shown fallback there is the strict direction. + * + * A warning, never a refusal: the server accepts the field, and a predicate it + * cannot evaluate keeps exactly the unconditional `required` the field had + * before the amendment. + */ +import { analyzeRelationshipTraversals, parseCelToAst } from '@objectstack/formula'; +import { REFERENCE_VALUE_TYPES } from '@objectstack/spec/data'; + +type AnyRec = Record; + +/** One finding of the expression rule (an `ExprIssue`). */ +export interface RequiredVisibleWhenFormulaIssue { + where: string; + message: string; + source: string; + severity: 'warning'; +} + +/** The CEL source of a string shorthand or a `cel` envelope; `undefined` otherwise. */ +function celSource(raw: unknown): string | undefined { + if (typeof raw === 'string') return raw.trim() ? raw : undefined; + if (raw && typeof raw === 'object' && !Array.isArray(raw)) { + const rec = raw as AnyRec; + if (typeof rec.dialect === 'string' && rec.dialect !== 'cel') return undefined; + if (typeof rec.source === 'string' && rec.source.trim()) return rec.source; + } + return undefined; +} + +/** The fields a source reads as values or through, over `roots`; `null` when the reader cannot say. */ +function readsOf(source: string, roots: readonly string[]): { all: Set; through: Set } | null { + const all = new Set(); + const through = new Set(); + for (const root of roots) { + const analysis = analyzeRelationshipTraversals(source, root); + if (!analysis) return null; + for (const name of analysis.bareFields) all.add(name); + for (const name of analysis.traversals.keys()) { + all.add(name); + through.add(name); + } + } + return { all, through }; +} + +/** A call of `label(`, spelled as the engine's `planCallsOptionLabel` reads it. */ +const LABEL_CALL = /\blabel\s*\(/; + +/** Does a cel-js AST hold a receiver call named `method` (`current_user.can(…)`)? */ +function callsReceiverMethod(node: unknown, method: string): boolean { + if (Array.isArray(node)) return node.some((child) => callsReceiverMethod(child, method)); + if (typeof node !== 'object' || node === null) return false; + const { op, args } = node as { op?: unknown; args?: unknown }; + if (typeof op !== 'string') return false; + if (op === 'rcall' && Array.isArray(args) && args[0] === method) return true; + return callsReceiverMethod(args, method); +} + +function callsCan(source: string): boolean { + try { + return callsReceiverMethod(parseCelToAst(source), 'can'); + } catch { + return false; + } +} + +/** + * The warning for field `fname` of object `objectName`, or `undefined` when it + * is not `required`, has no `visibleWhen`, or its `visibleWhen` reads no + * formula field. `fields` are the object's fields by name, as served. + */ +export function requiredVisibleWhenFormulaIssue( + objectName: string, + fname: string, + def: AnyRec, + fields: ReadonlyMap, +): RequiredVisibleWhenFormulaIssue | undefined { + if (def.required !== true) return undefined; + const source = celSource(def.visibleWhen); + if (!source) return undefined; + const isFormula = (name: string) => fields.get(name)?.type === 'formula'; + const predicateReads = readsOf(source, ['record', 'previous']); + if (!predicateReads) return undefined; + const formulas = [...predicateReads.all].filter(isFormula).sort(); + if (formulas.length === 0) return undefined; + + // Why the write path cannot compute a formula, walked through the formulas + // it reads; memoised, and a formula on a cycle is not revisited. + const verdicts = new Map(); + const unservable = (name: string): string | null => { + const known = verdicts.get(name); + if (known !== undefined) return known; + verdicts.set(name, null); + const expr = celSource(fields.get(name)?.expression); + let why: string | null = null; + if (expr) { + const reads = readsOf(expr, ['record']); + const hops = reads ? [...reads.through].filter((f) => REFERENCE_VALUE_TYPES.has(String(fields.get(f)?.type))) : []; + if (hops.length > 0) why = `reads through ${hops.map((f) => `'${f}'`).join(', ')}`; + else if (LABEL_CALL.test(expr)) why = 'calls label()'; + else if (callsCan(expr)) why = 'calls current_user.can()'; + else { + for (const read of [...(reads?.all ?? [])].filter(isFormula)) { + const inner = unservable(read); + if (inner) { + why = `reads the formula '${read}', which ${inner}`; + break; + } + } + } + } + verdicts.set(name, why); + return why; + }; + const blocked = formulas.flatMap((f) => { + const why = unservable(f); + return why === null ? [] : [`'${f}' ${why}`]; + }); + + const named = formulas.map((f) => `'${f}'`).join(', '); + let message = + `Field '${fname}' is \`required\`, and its \`visibleWhen\` reads the formula field ${named}. A reminder: the ` + + `server judges that requirement on the formula value it computes over the record being written (ADR-0113 D1). ` + + `The form computes the same formula over the record being edited; a check that does not (a wizard's ` + + `final-submit check, or a form whose data source serves no object schema) judges the value last read, none ` + + `on a create, and can disagree with the server.`; + if (blocked.length > 0) { + message += + ` Worse, ${blocked.join('; ')}, which the write path does not compute: the server counts the field as SHOWN ` + + `on every write, so it stays required on every record. The form cannot compute it either: it shows the ` + + `field and keeps it required.`; + if (blocked.some((b) => b.includes('calls current_user.can()'))) { + message += + ' (A `current_user.can()` call is computed on a write that picks a permission-gated option, which resolves ' + + 'the permission map, so on such a write the formula is judged on its value instead.)'; + } + } + return { where: `object '${objectName}' · field '${fname}' visibleWhen`, message, source, severity: 'warning' }; +} diff --git a/packages/lint/src/validate-expressions.test.ts b/packages/lint/src/validate-expressions.test.ts index 726254e0e4c..6d10b6f5017 100644 --- a/packages/lint/src/validate-expressions.test.ts +++ b/packages/lint/src/validate-expressions.test.ts @@ -4323,6 +4323,15 @@ const READ_SURFACES: Array<{ receiver: string; expected: string[]; declaredBy: s declaredBy: 'FieldSchema.conditionalFormatting[]', keys: () => shapeKeysOf(FieldSchema.shape.conditionalFormatting), }, + { + // [#34905] A `required` field with its own `visibleWhen` that also sets + // `storage.notNull` draws a warning naming that key: the column refuses the + // null the write contract now admits on a record the predicate hides. + receiver: 'storage', + expected: ['notNull'], + declaredBy: 'FieldSchema.storage', + keys: () => shapeKeysOf(FieldSchema.shape.storage), + }, ]; /** @@ -4362,7 +4371,13 @@ describe('validateStackExpressions — reads only keys the spec declares (meta-t // have hidden the new surface from this very scan. // `conditionalFormatting` joined in #22228 — the cell formatting rules, // read literally for the same reason. - expect(read).toEqual(['conditionalFormatting', 'expression', 'name', 'options', 'readonlyWhen', 'requiredWhen']); + // `required`, `storage` and `visibleWhen` joined in #34905 — a `required` + // field's own `visibleWhen` now decides whether the field is required on a + // write (ADR-0113 D1, amended), so its reads are checked here, and a + // `storage.notNull` beside the pair is warned. + expect(read).toEqual([ + 'conditionalFormatting', 'expression', 'name', 'options', 'readonlyWhen', 'required', 'requiredWhen', 'storage', 'visibleWhen', + ]); const declared = Object.keys(FieldSchema.shape); const tracked = TRACKED_UNDECLARED_READS.filter((t) => t.receiver === 'f').map((t) => t.key); expect(tracked).toEqual([]); @@ -6819,3 +6834,111 @@ describe('validateStackExpressions — flow value envelopes take the date-text f } }); }); + +/** + * [ADR-0113 D1, as amended] A `required` field's own `visibleWhen` decides its + * requirement on the write, and a predicate the server cannot evaluate counts + * as SHOWN — the field keeps the unconditional `required` it had before. Two + * shapes the author can see at build time leave the field required where the + * form hides it, so both are WARNINGS (never refusals): a read through a + * reference field, and `storage.notNull` beside the pair. The roots the server + * cannot bind are already refused for every field `visibleWhen` + * (`FIELD_RULE_BOUND_ROOTS`), so no second warning is drawn for them. + * `packages/objectql/src/engine-required-when-shown.test.ts` pins the runtime. + */ +describe('a `required` field\'s `visibleWhen` the server cannot use to lift the requirement (ADR-0113 D1)', () => { + const account = { + name: 'rws_account', + label: 'Account', + fields: { name: { type: 'text', label: 'Name' }, tier: { type: 'text', label: 'Tier' } }, + }; + const order = (fields: Record) => ({ + name: 'rws_order', + label: 'Order', + fields: { + account: { type: 'lookup', label: 'Account', reference: 'rws_account' }, + status: { type: 'text', label: 'Status' }, + ...fields, + }, + }); + const run = (...objects: Array>) => + validateStackExpressions(specValid({ objects: [account, ...objects] })); + const at = (issues: ReturnType, where: string) => issues.filter((i) => i.where === where); + const WHERE = "object 'rws_order' · field 'po_number' visibleWhen"; + + it('warns on a read through a reference, naming the counts-as-shown consequence', () => { + const issues = at(run(order({ + po_number: { type: 'text', label: 'PO', required: true, visibleWhen: "record.account.tier == 'enterprise'" }, + })), WHERE); + expect(issues).toHaveLength(1); + expect(issues[0].severity).toBe('warning'); + expect(issues[0].message.startsWith('`visibleWhen` reads `tier` through `record.account`, a `lookup` field')).toBe(true); + expect(issues[0].message).toContain('counts as SHOWN (ADR-0113 D1)'); + }); + + it('draws nothing for the same read on a field that is not required — display only', () => { + expect(at(run(order({ + po_number: { type: 'text', label: 'PO', visibleWhen: "record.account.tier == 'enterprise'" }, + })), WHERE)).toEqual([]); + }); + + it('draws nothing for a required field whose predicate reads its own columns', () => { + expect(at(run(order({ + po_number: { type: 'text', label: 'PO', required: true, visibleWhen: "record.status == 'sent'" }, + })), WHERE)).toEqual([]); + }); + + it('warns on `storage.notNull` beside `required` + `visibleWhen` — and the parse still accepts it', () => { + const issues = at(run(order({ + po_number: { type: 'text', label: 'PO', required: true, storage: { notNull: true }, visibleWhen: "record.status == 'sent'" }, + })), WHERE); + expect(issues).toHaveLength(1); + expect(issues[0].severity).toBe('warning'); + expect(issues[0].message).toContain('`storage.notNull: true`'); + }); + + // A formula the predicate reads: a reminder that the server judges it on the + // formula value it computes, and a formula the write path cannot compute (a + // hop, `label()`, `can`, at any depth) keeps the field required on every write. + it('warns when the predicate reads a formula field: the server judges it on the formula it computes', () => { + const issues = at(run(order({ + amount: { type: 'number', label: 'Amount' }, + risk: { type: 'formula', label: 'Risk', expression: "record.amount > 100 ? 'high' : 'low'", returnType: 'text' }, + po_number: { type: 'text', label: 'PO', required: true, visibleWhen: "record.risk == 'high'" }, + })), WHERE); + expect(issues).toHaveLength(1); + expect(issues[0].severity).toBe('warning'); + expect(issues[0].message).toContain("reads the formula field 'risk'"); + expect(issues[0].message).toContain('the formula value it computes over the record being written'); + expect(issues[0].message).not.toContain('counts the field as SHOWN'); + }); + + it('…and names the chain when a formula it reads reads through a reference, at any depth', () => { + const issues = at(run(order({ + tier_name: { type: 'formula', label: 'Tier', expression: 'record.account.tier', returnType: 'text' }, + risk: { type: 'formula', label: 'Risk', expression: "record.tier_name == 'gold' ? 'high' : 'low'", returnType: 'text' }, + po_number: { type: 'text', label: 'PO', required: true, visibleWhen: "record.risk == 'high'" }, + })), WHERE); + expect(issues).toHaveLength(1); + expect(issues[0].message).toContain("'risk' reads the formula 'tier_name', which reads through 'account'"); + expect(issues[0].message).toContain('counts the field as SHOWN on every write'); + }); + + it('…and when a formula it reads calls label()', () => { + const issues = at(run(order({ + stage: { type: 'select', label: 'Stage', options: [{ value: 'won', label: 'Won' }, { value: 'lost', label: 'Lost' }] }, + stage_label: { type: 'formula', label: 'Stage label', expression: 'label(record.stage)', returnType: 'text' }, + po_number: { type: 'text', label: 'PO', required: true, visibleWhen: "record.stage_label == 'Won'" }, + })), WHERE); + expect(issues).toHaveLength(1); + expect(issues[0].message).toContain("'stage_label' calls label()"); + }); + + it('draws no formula warning on a field that is not required', () => { + expect(at(run(order({ + amount: { type: 'number', label: 'Amount' }, + risk: { type: 'formula', label: 'Risk', expression: "record.amount > 100 ? 'high' : 'low'", returnType: 'text' }, + po_number: { type: 'text', label: 'PO', visibleWhen: "record.risk == 'high'" }, + })), WHERE)).toEqual([]); + }); +}); diff --git a/packages/lint/src/validate-expressions.ts b/packages/lint/src/validate-expressions.ts index a2f29f4e9ab..6136eba4597 100644 --- a/packages/lint/src/validate-expressions.ts +++ b/packages/lint/src/validate-expressions.ts @@ -171,6 +171,7 @@ import { objectExtensionsByTarget, objectsAsServed, objectsWithoutTiedFields, re import type { StoredObjectExtension } from './object-graph.js'; import { storedExpressionInputIssues } from './stored-expression-inputs.js'; import { extensionFormulaLoci, formulaCycleIssues } from './formula-cycle-issues.js'; +import { requiredVisibleWhenFormulaIssue } from './required-visible-when-formula-issue.js'; export interface ExprIssue { where: string; message: string; @@ -1294,9 +1295,10 @@ const FIELD_RULE_SLOT_CONSEQUENCE: Record = { '(plugin-form\'s `sectionFields` copies this object rule onto the runtime form field and ' + '`resolveFieldRuleState` evaluates it with the host scope bound, the `current_user` binding ' + 'ADR-0089 D1 gives every runtime record surface) — so the ' + - 'control is hidden in that one form while NO server-side gate evaluates a field-level ' + - '`visibleWhen` at all: the record still carries the value and every other reader still ' + - 'returns it, a SILENT enforcement gap. Where no host publishes a scope (the console public ' + + 'control is hidden in that one form while NO server-side gate hides anything by a field-level ' + + '`visibleWhen` (the write path reads one only to decide whether a `required` field must be ' + + 'filled): the record still carries the value and every other reader still returns it, a SILENT ' + + 'enforcement gap. Where no host publishes a scope (the console public ' + '`/f/:slug` route, and every non-form reader) the root is unbound, the predicate faults and ' + 'the renderer falls back to VISIBLE (`resolveFieldRuleState` evaluates visibility with ' + '`fallback: true`), leaving the field the test was meant to hide showing for everyone. ' + @@ -1632,7 +1634,7 @@ function faultOutcomeOf(site: FaultSite): (ExprFaultOutcome & NullGuardOutcome) * select option's own `visibleWhen`. */ -type FieldTraversalSlot = 'requiredWhen' | 'readonlyWhen' | 'option visibleWhen'; +type FieldTraversalSlot = 'requiredWhen' | 'readonlyWhen' | 'option visibleWhen' | 'visibleWhen'; /** [#20078] A root a field-level predicate binds, with the record shape it binds. */ interface FieldTraversalHolder { @@ -1659,6 +1661,15 @@ const FIELD_TRAVERSAL_CONSEQUENCE: Record = { 'option visibleWhen': 'The server REFUSES every write by an acting user that picks this option — an option gate it ' + 'cannot evaluate refuses the write, naming the option, the field and the fault (ADR-0137 D2)', + // [ADR-0113 D1, as amended] Judged only on a `required` field: the server + // reads that field's own `visibleWhen` to decide whether the requirement + // applies, and a predicate it cannot evaluate counts as SHOWN. A warning, + // not a refusal: the field keeps exactly the unconditional `required` it had + // before the amendment, so nothing gets worse; only the waiver never happens. + visibleWhen: + 'This field is `required`, and the server judges that requirement by this predicate on every ' + + 'write; a predicate it cannot evaluate counts as SHOWN (ADR-0113 D1), so the field stays required ' + + 'on every record, the ones the form hides it on included, and a user who cannot see it cannot save', }; /** @@ -3015,6 +3026,9 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression slot: FieldTraversalSlot, raw: unknown, holders: readonly FieldTraversalHolder[], + // [ADR-0113 D1, as amended] `warning` for the one slot whose fault the + // server answers with the pre-amendment `required` instead of a refusal. + severity: 'error' | 'warning' = 'error', ): void => { const source = celSourceOf(raw); if (!source) return; @@ -3030,7 +3044,7 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression where, message: fieldTraversalMessage(slot, root, field, fieldType, [...related].sort(), owner), source, - severity: 'error', + severity, }); } } @@ -4329,6 +4343,46 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression ] as const) { refuseFieldTraversal(`object '${objectName}' · field '${fname}' ${slot}`, slot, raw, fieldRuleHolders); } + // [ADR-0113 D1, as amended] A `required` field's own `visibleWhen` is a + // server concept now: the write path judges the requirement by it + // (`rule-validator.ts`, `evaluateRequiredWhenShown`) with the field-rule + // slots' binding, and a fault there counts as SHOWN. Two shapes the author + // can see at build time keep the field required where the form hides it, + // so both are WARNINGS, never refusals — the field keeps the requirement + // it had before the amendment, nothing gets worse: + // + // - a read THROUGH a reference field: never hydrated at the field level, + // so it faults on every row (the roots the server cannot bind — + // `features`, `app`, `page`, the acting user — are already refused for + // every field `visibleWhen` above, `FIELD_RULE_BOUND_ROOTS`); + // - `storage.notNull`: the column refuses the null the waiver admits, so + // a record outside the condition still cannot be created. A parse + // refusal like the `requiredWhen` rider's would break every pre-17 + // source the `field-required-notnull-explicit` conversion stamped. + // Literal member reads, like the gates above, for the #5017 scan. + if (f.required === true && f.visibleWhen != null) { + const visibleWhere = `object '${objectName}' · field '${fname}' visibleWhen`; + refuseFieldTraversal(visibleWhere, 'visibleWhen', f.visibleWhen, fieldRuleHolders, 'warning'); + if ((f.storage as AnyRec | undefined)?.notNull === true) { + issues.push({ + where: visibleWhere, + message: + `Field '${fname}' is \`required\` with a \`visibleWhen\`, so a write the predicate hides it on ` + + `does not need it (ADR-0113 D1) — but it also declares \`storage.notNull: true\`, and the column ` + + `refuses that null: a record outside the condition still cannot be created. Drop ` + + `\`storage.notNull\` (the write contract alone keeps shown rows filled), or drop \`visibleWhen\` ` + + `if the field applies to every record.`, + source: celSourceOf(f.visibleWhen) ?? '', + severity: 'warning', + }); + } + // A `formula` the predicate reads: a reminder that the server judges it + // on the formula value it computes at write time, and one the write + // path cannot compute keeps the field required on every write, shown + // by the form (`required-visible-when-formula-issue.ts`). + const formulaRead = objectName ? requiredVisibleWhenFormulaIssue(objectName, fname, f, fieldDefs) : undefined; + if (formulaRead) issues.push(formulaRead); + } judgeFieldFormula(fname, f, { objectName, optionFields: optionFieldNames, fieldDefs }); } // [#33100] A formula that reads its own value, itself or through the diff --git a/packages/objectql/src/engine-insert.ts b/packages/objectql/src/engine-insert.ts index 28efb7c3f95..8a3d302a4f9 100644 --- a/packages/objectql/src/engine-insert.ts +++ b/packages/objectql/src/engine-insert.ts @@ -67,7 +67,7 @@ import { dispatchHooksExplainingWithheldReadonly } from './hook-withheld-readonl import { declaredColumnSet, rowsWithDeclaredColumnsOnly, selectedStoredColumns, storedColumnsLeftUnwritten, withDeclaredColumnsOnly, withSelectedColumnsAnswered } from './declared-read-columns.js'; import { WRITE_PRECONDITION_OPTION, autonumberFieldNames, callerKeySets, callerSuppliedRow, computeStoredExpressions, - droppedFieldEvents, handBackWithheldInsertReadonly, hydrateWriteFormulas, insertStaticReadonlySubject, + droppedFieldEvents, formulaValuesFor, handBackWithheldInsertReadonly, hydrateWriteFormulas, insertStaticReadonlySubject, planStoredExpressions, recomputeAutonumberReaders, replacedStoredExpressionFields, shouldSkipStateMachine, storedExpressionsReading, stripComputedWriteFields, undeclaredWriteFieldErrors, withholdInsertReadonlyFromHooks, callerInputRefusalLogMeta, writeFailureLogMeta, @@ -1359,7 +1359,9 @@ export class InsertFacet { // `ReadonlyValueScope` (record-validator.ts). normalizeMultiValueFields(schemaForValidation, rows[i], 'include'); // [#22183] `keptOptionValues`: the option values an import kept for this write. - validateRecordInScope(schemaForValidation, rows[i], 'insert', 'include', { mediaValueShapeStrict, valueShapeStrict, messages: msgCtx, onAdmittedValueShapeViolation, keptOptionValues: opCtx.context?.keptOptionValues }); + // [ADR-0113 D1, as amended] `'deferred'`: a field required only when shown + // is judged by `evaluateValidationRules` below, against its visibility. + validateRecordInScope(schemaForValidation, rows[i], 'insert', 'include', { mediaValueShapeStrict, valueShapeStrict, messages: msgCtx, onAdmittedValueShapeViolation, keptOptionValues: opCtx.context?.keptOptionValues }, 'deferred'); // [ADR-0144 D8 rule 4] A `record`-mode amount is stored with its // currency code, or the row is refused (`ERR_CURRENCY_CODE_REQUIRED`). // [ADR-0144 D2, amended] A child amount's code is its parent's, laid on a copy of the row. @@ -1374,7 +1376,7 @@ export class InsertFacet { schemaForValidation, rows[i], suppliedPerRow[i], opCtx.context, msgCtx, ); if (referencesFirst) await checkReferences(); - emitValidationAdvisories(options?.onValidationAdvisory, evaluateValidationRules(schemaForValidation as any, rows[i], 'insert', { logger: this.logger, currentUser: this.buildEvalUser(opCtx.context), skipStateMachine: shouldSkipStateMachine(opCtx.context), messages: msgCtx, parent: insertParentOf(rows[i]), related: batchSummaries ? batchSummaries.overlay(insertRelatedForRow(rows[i])) : insertRelatedForRow(rows[i]), permissions: insertPermissionsFor(rows[i]) }), this.logger, object); + emitValidationAdvisories(options?.onValidationAdvisory, evaluateValidationRules(schemaForValidation as any, rows[i], 'insert', { logger: this.logger, currentUser: this.buildEvalUser(opCtx.context), skipStateMachine: shouldSkipStateMachine(opCtx.context), messages: msgCtx, parent: insertParentOf(rows[i]), related: batchSummaries ? batchSummaries.overlay(insertRelatedForRow(rows[i])) : insertRelatedForRow(rows[i]), permissions: insertPermissionsFor(rows[i]), formulaValues: formulaValuesFor(schemaForValidation, opCtx.context, insertPermissionsFor(rows[i])) }), this.logger, object); if (!referencesFirst) await checkReferences(); // [#25579] Admitted: a later row of this batch reads it in the summary. batchSummaries?.accept(rows[i]); diff --git a/packages/objectql/src/engine-required-when-shown.test.ts b/packages/objectql/src/engine-required-when-shown.test.ts new file mode 100644 index 00000000000..086acb5e87e --- /dev/null +++ b/packages/objectql/src/engine-required-when-shown.test.ts @@ -0,0 +1,552 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// ADR-0113 D1, as amended — `required` + the field's own `visibleWhen` is +// required WHEN SHOWN, on every engine write door. +// +// The defect (objectstack#34905, measured on 18.5.0): a field that is +// `required` and hidden by its `visibleWhen` was still enforced on save, so +// every record outside the condition refused every write — even an edit of an +// unrelated field — naming a field the user could not see or fill. +// +// What this file pins, through the real engine and an in-memory driver so +// "nothing is persisted" is read off the store: +// +// (a) the WIDENING — predicate cleanly FALSE on the merged record ⇒ the +// requirement is waived, on insert, on an unrelated edit, and on the +// form's clear-on-hide `null`; +// (b) the NARROWING — a write that REVEALS the field without filling it is +// refused (verdict on the merged record, compliance on the prior record), +// by id and on the bulk path, where one failing row refuses the batch; +// (c) a FAULT counts as shown — the field keeps the unconditional `required` +// it had before the amendment, the write is NOT refused for the fault +// itself (not ADR-0137 D2's arm), and the fault is logged; +// (d) the acting user is bound as `current_user`, so a role-gated predicate is +// judged per writer, and a system write with no user counts as shown; +// (e) the dry run agrees, and a plain `required` with no `visibleWhen` is +// untouched (no prior read, D1's over-approximation kept). +// (i) a `formula` the predicate reads that reads the acting user is computed +// per writer, and on a write with no acting user it counts as shown and +// is logged `no-acting-user`, as the direct spelling is. + +import { describe, it, expect, beforeEach } from 'vitest'; +import { ObjectQL } from './engine.js'; +import { needsPriorRecord } from './validation/rule-validator.js'; + +function makeDriver() { + const stores = new Map>(); + const storeFor = (o: string) => { + let s = stores.get(o); + if (!s) { s = new Map(); stores.set(o, s); } + return s; + }; + const checkOp = (value: any, cond: any): boolean => { + if (cond === null || typeof cond !== 'object' || Array.isArray(cond) || cond instanceof Date) { + return value === cond; + } + return Object.entries(cond).every(([op, target]: [string, any]) => { + switch (op) { + case '$eq': return value === target; + case '$ne': return value !== target; + case '$in': return Array.isArray(target) && target.includes(value); + default: return true; + } + }); + }; + const matches = (row: any, where: any): boolean => { + if (!where || typeof where !== 'object') return true; + return Object.entries(where).every(([k, v]: [string, any]) => { + if (k === '$and') return (v as any[]).every((w) => matches(row, w)); + if (k === '$or') return (v as any[]).some((w) => matches(row, w)); + if (k === '$not') return !matches(row, v); + return checkOp(row?.[k], v); + }); + }; + let n = 0; + const driver: any = { + name: 'memory', version: '0.0.0', supports: {}, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, + async find(object: string, ast: any) { + const rows = Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where)); + return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; + }, + async findOne(object: string, ast: any) { + for (const r of storeFor(object).values()) if (matches(r, ast?.where)) return r; + return null; + }, + async create(object: string, data: Record) { + n += 1; + const id = (data.id as string) ?? `r_${n}`; + const row = { ...data, id }; + storeFor(object).set(id, row); + return row; + }, + async update(object: string, id: string, data: Record) { + const s = storeFor(object); + const row = { ...s.get(id), ...data, id }; + s.set(id, row); + return row; + }, + async updateMany(object: string, ast: any, data: Record) { + const s = storeFor(object); + let count = 0; + for (const row of [...s.values()]) { + if (!matches(row, ast?.where)) continue; + s.set(row.id, { ...row, ...data, id: row.id }); + count += 1; + } + return count; + }, + async delete(object: string, id: string) { return storeFor(object).delete(id); }, + async count() { return 0; }, + async bulkCreate(object: string, rows: Record[]) { + return Promise.all(rows.map((r) => this.create(object, r, undefined))); + }, + async bulkUpdate() { return []; }, async bulkDelete() {}, + async beginTransaction() { return { __trx: true, commit: async () => {}, rollback: async () => {} }; }, + async commit() {}, async rollback() {}, + }; + return { driver, storeFor }; +} + +/** The error a write threw, or a failure saying it was accepted. */ +async function refusalOf(run: () => Promise): Promise { + let thrown: unknown; + let threw = false; + try { + await run(); + } catch (err) { + threw = true; + thrown = err; + } + expect(threw).toBe(true); + return thrown as any; +} + +/** The ADR-0112 envelope of a `required` refusal naming one field. */ +function expectRequired(err: any, field: string, cleared = false) { + expect(err.name).toBe('ValidationError'); + expect(err.code).toBe('VALIDATION_FAILED'); + const entry = (err.fields as any[]).find((f) => f.field === field); + expect(entry).toMatchObject({ field, code: 'required' }); + // The clear-out case keeps its distinct sentence (`required_cleared`). + if (cleared) expect(entry.message).toMatch(/required and cannot be cleared/); + else expect(entry.message).not.toMatch(/cannot be cleared/); + return entry; +} + +function capturingLogger() { + const lines: Array<{ level: string; msg: string; meta?: any }> = []; + const push = (level: string) => (msg: string, meta?: any) => void lines.push({ level, msg: String(msg), meta }); + const logger: any = { + lines, + trace() {}, fatal() {}, + debug: push('debug'), info: push('info'), warn: push('warn'), error: push('error'), + child() { return logger; }, + }; + return logger; +} + +const ADMIN = { context: { userId: 'u_admin', positions: ['org_admin'] } } as any; +const MEMBER = { context: { userId: 'u_member', positions: ['org_member'] } } as any; + +describe('ADR-0113 D1 (amended) — `required` + `visibleWhen` is required when shown', () => { + let engine: ObjectQL; + let logger: ReturnType; + let storeFor: ReturnType['storeFor']; + + beforeEach(async () => { + logger = capturingLogger(); + engine = new ObjectQL({ logger }); + const d = makeDriver(); + storeFor = d.storeFor; + engine.registerDriver(d.driver, true); + await engine.init(); + engine.registry.registerObject({ + name: 'rws_account', + fields: { + name: { type: 'text' }, + owner: { type: 'text' }, + tier: { type: 'text' }, + // The card's field: required, shown only for one tier. + vip_note: { type: 'text', required: true, visibleWhen: "record.tier == 'vip'" }, + }, + } as any, 'test-package'); + engine.registry.registerObject({ + name: 'rws_fault', + fields: { + status: { type: 'text' }, + // An author typo — `statsu` is declared nowhere: the predicate faults. + reason: { type: 'text', required: true, visibleWhen: "record.statsu == 'closed'" }, + }, + } as any, 'test-package'); + engine.registry.registerObject({ + name: 'rws_role', + fields: { + title: { type: 'text' }, + // Older stored metadata: a role-gated field predicate (today's lint + // refuses the root at authoring; the server still judges what is stored). + audit_note: { type: 'text', required: true, visibleWhen: "'org_admin' in current_user.positions" }, + }, + } as any, 'test-package'); + engine.registry.registerObject({ + name: 'rws_formula', + fields: { + amount: { type: 'number' }, + // Computed on read, never stored from the write payload. + risk_level: { type: 'formula', expression: "record.amount > 100 ? 'high' : 'low'", returnType: 'text' }, + review_note: { type: 'text', required: true, visibleWhen: "record.risk_level == 'high'" }, + }, + } as any, 'test-package'); + engine.registry.registerObject({ + name: 'rws_formula_fault', + fields: { + amount: { type: 'number' }, + // An author typo inside the formula: it cannot be computed on any row. + risk_level: { type: 'formula', expression: "record.amout > 100 ? 'high' : 'low'", returnType: 'text' }, + review_note: { type: 'text', required: true, visibleWhen: "record.risk_level == 'high'" }, + }, + } as any, 'test-package'); + engine.registry.registerObject({ + name: 'rws_formula_label', + fields: { + stage: { type: 'select', options: [{ value: 'won', label: 'Won' }, { value: 'lost', label: 'Lost' }] }, + // `label()` reads the reader's option labels, which no write builds. + stage_label: { type: 'formula', expression: 'label(record.stage)', returnType: 'text' }, + close_note: { type: 'text', required: true, visibleWhen: "record.stage_label == 'Won'" }, + }, + } as any, 'test-package'); + engine.registry.registerObject({ + name: 'rws_tier_account', + fields: { name: { type: 'text' }, tier: { type: 'text' } }, + } as any, 'test-package'); + engine.registry.registerObject({ + name: 'rws_tiered', + fields: { + account: { type: 'lookup', reference: 'rws_tier_account' }, + // A formula read through a reference: a read resolves the hop, the + // write path never does. + tier_name: { type: 'formula', expression: 'record.account.tier', returnType: 'text' }, + // A formula over that formula: it computes CLEANLY over the null the + // hop reads on the write path, so it alone looks computable. + risk: { type: 'formula', expression: "record.tier_name == 'gold' ? 'high' : 'low'", returnType: 'text' }, + review_note: { type: 'text', required: true, visibleWhen: "record.risk == 'high'" }, + }, + } as any, 'test-package'); + engine.registry.registerObject({ + name: 'rws_formula_user', + fields: { + title: { type: 'text' }, + // The authorable way to role-gate a field: the lint refuses + // `current_user` in a field `visibleWhen`, not in a formula. A read + // computes it for the reader; a write with no acting user cannot. + is_admin: { type: 'formula', expression: "'org_admin' in current_user.positions", returnType: 'boolean' }, + admin_note: { type: 'text', required: true, visibleWhen: 'record.is_admin' }, + }, + } as any, 'test-package'); + engine.registry.registerObject({ + name: 'rws_formula_user_chain', + fields: { + title: { type: 'text' }, + is_admin: { type: 'formula', expression: "'org_admin' in current_user.positions", returnType: 'boolean' }, + // A formula over that formula: it computes cleanly over the null the + // missing user leaves, so it alone looks computable. + needs_audit: { type: 'formula', expression: 'record.is_admin == true', returnType: 'boolean' }, + audit_note: { type: 'text', required: true, visibleWhen: 'record.needs_audit' }, + }, + } as any, 'test-package'); + engine.registry.registerObject({ + name: 'rws_flag', + fields: { + title: { type: 'text' }, + is_vip: { type: 'boolean' }, + // A bare-boolean predicate: an unset flag is null, not FALSE. + perk_note: { type: 'text', required: true, visibleWhen: 'record.is_vip' }, + }, + } as any, 'test-package'); + engine.registry.registerObject({ + name: 'rws_plain', + fields: { + title: { type: 'text' }, + code: { type: 'text', required: true }, + }, + } as any, 'test-package'); + }); + + const rows = (object: string) => [...storeFor(object).values()]; + + // ── (a) the widening ───────────────────────────────────────────────────── + + describe('(a) predicate cleanly FALSE ⇒ the requirement is waived', () => { + it('an INSERT outside the condition is accepted without the field', async () => { + const row = await engine.insert('rws_account', { name: 'Acme', tier: 'basic' }); + expect(row).toMatchObject({ name: 'Acme', tier: 'basic' }); + expect(rows('rws_account')).toHaveLength(1); + }); + + it('an edit of an unrelated field on a record outside the condition is accepted (the card)', async () => { + storeFor('rws_account').set('a1', { id: 'a1', name: 'Acme', tier: 'basic', owner: 'u1', vip_note: null }); + await engine.update('rws_account', { id: 'a1', owner: 'u2' }); + expect(storeFor('rws_account').get('a1')).toMatchObject({ owner: 'u2', vip_note: null }); + }); + + it("the form's clear-on-hide `null` is accepted when the write moves the record out of the condition", async () => { + storeFor('rws_account').set('a2', { id: 'a2', name: 'Acme', tier: 'vip', vip_note: 'keep warm' }); + await engine.update('rws_account', { id: 'a2', tier: 'basic', vip_note: null }); + expect(storeFor('rws_account').get('a2')).toMatchObject({ tier: 'basic', vip_note: null }); + }); + }); + + // ── (b) the narrowing ──────────────────────────────────────────────────── + + describe('(b) predicate TRUE ⇒ required, and a reveal without filling is refused', () => { + it('an INSERT inside the condition without the field is refused — nothing stored', async () => { + const err = await refusalOf(() => engine.insert('rws_account', { name: 'Acme', tier: 'vip' })); + expectRequired(err, 'vip_note'); + expect(rows('rws_account')).toHaveLength(0); + }); + + it('an INSERT inside the condition with the field is accepted', async () => { + await engine.insert('rws_account', { name: 'Acme', tier: 'vip', vip_note: 'call weekly' }); + expect(rows('rws_account')).toHaveLength(1); + }); + + it('an UPDATE that reveals the field without filling it is refused — the row is untouched', async () => { + storeFor('rws_account').set('a3', { id: 'a3', name: 'Acme', tier: 'basic', vip_note: null }); + const err = await refusalOf(() => engine.update('rws_account', { id: 'a3', tier: 'vip' })); + expectRequired(err, 'vip_note'); + expect(storeFor('rws_account').get('a3')).toEqual({ id: 'a3', name: 'Acme', tier: 'basic', vip_note: null }); + }); + + it('…and the same reveal WITH the field filled is accepted', async () => { + storeFor('rws_account').set('a4', { id: 'a4', name: 'Acme', tier: 'basic', vip_note: null }); + await engine.update('rws_account', { id: 'a4', tier: 'vip', vip_note: 'call weekly' }); + expect(storeFor('rws_account').get('a4')).toMatchObject({ tier: 'vip', vip_note: 'call weekly' }); + }); + + it('clearing the field while it is shown is refused with the clear-out sentence', async () => { + storeFor('rws_account').set('a5', { id: 'a5', name: 'Acme', tier: 'vip', vip_note: 'call weekly' }); + const err = await refusalOf(() => engine.update('rws_account', { id: 'a5', vip_note: null })); + expectRequired(err, 'vip_note', true); + expect(storeFor('rws_account').get('a5')).toMatchObject({ vip_note: 'call weekly' }); + }); + + it('a row already shown and empty rests: an unrelated edit, and an explicit null onto it, are accepted', async () => { + storeFor('rws_account').set('a6', { id: 'a6', name: 'Acme', tier: 'vip', vip_note: null }); + await engine.update('rws_account', { id: 'a6', owner: 'u3' }); + await engine.update('rws_account', { id: 'a6', vip_note: null }); + expect(storeFor('rws_account').get('a6')).toMatchObject({ owner: 'u3', vip_note: null }); + }); + + it('a BULK update that reveals the field on one empty row refuses the whole batch, naming that row', async () => { + storeFor('rws_account').set('b1', { id: 'b1', name: 'One', tier: 'basic', owner: 'x', vip_note: 'filled' }); + storeFor('rws_account').set('b2', { id: 'b2', name: 'Two', tier: 'basic', owner: 'x', vip_note: null }); + const err = await refusalOf(() => + engine.update('rws_account', { tier: 'vip' }, { where: { owner: 'x' }, multi: true } as any)); + const entry = expectRequired(err, 'vip_note'); + expect(entry.message).toContain('(record b2)'); + expect(rows('rws_account').map((r) => r.tier)).toEqual(['basic', 'basic']); + }); + }); + + // ── (c) a fault counts as shown ────────────────────────────────────────── + + describe('(c) a predicate that faults counts as shown, and says so in the log', () => { + it('an INSERT without the field is refused as `required` (not the D2 `rule_violation`), and the fault is logged', async () => { + const err = await refusalOf(() => engine.insert('rws_fault', { status: 'closed' })); + expectRequired(err, 'reason'); + expect((err.fields as any[]).some((f) => f.code === 'rule_violation')).toBe(false); + const line = logger.lines.find((l: any) => l.level === 'warn' && l.msg.includes("visibleWhen of required field 'reason'")); + expect(line?.meta).toMatchObject({ field: 'reason', reason: 'predicate-fault' }); + expect(rows('rws_fault')).toHaveLength(0); + }); + + it('an INSERT with the field is accepted — the fault costs the waiver, never the write', async () => { + await engine.insert('rws_fault', { status: 'closed', reason: 'duplicate' }); + expect(rows('rws_fault')).toHaveLength(1); + }); + + it('an UPDATE keeps the pre-amendment answers: a clear is refused, an unrelated edit of a null row rests', async () => { + storeFor('rws_fault').set('f1', { id: 'f1', status: 'open', reason: 'dup' }); + storeFor('rws_fault').set('f2', { id: 'f2', status: 'open', reason: null }); + const err = await refusalOf(() => engine.update('rws_fault', { id: 'f1', reason: '' })); + expectRequired(err, 'reason', true); + await engine.update('rws_fault', { id: 'f2', status: 'closed' }); + expect(storeFor('rws_fault').get('f2')).toMatchObject({ status: 'closed', reason: null }); + }); + }); + + // ── (d) the acting user ────────────────────────────────────────────────── + + describe('(d) `current_user` is bound, so a role-gated predicate is judged per writer', () => { + it('the writer the field is shown to must fill it', async () => { + const err = await refusalOf(() => engine.insert('rws_role', { title: 'Q3' }, ADMIN)); + expectRequired(err, 'audit_note'); + }); + + it('the writer it is hidden from saves without it', async () => { + await engine.insert('rws_role', { title: 'Q3' }, MEMBER); + expect(rows('rws_role')).toHaveLength(1); + }); + + it('a system write with no acting user counts as shown, logged as `no-acting-user`', async () => { + const err = await refusalOf(() => engine.insert('rws_role', { title: 'Q3' })); + expectRequired(err, 'audit_note'); + const line = logger.lines.find((l: any) => l.level === 'warn' && l.msg.includes("visibleWhen of required field 'audit_note'")); + expect(line?.meta).toMatchObject({ field: 'audit_note', reason: 'no-acting-user' }); + }); + }); + + // ── (e) the dry run, and the plain `required` control ──────────────────── + + describe('(e) the dry run agrees; a plain `required` is untouched', () => { + it('validate() accepts the hidden insert and refuses the shown, empty one', async () => { + const hidden = await engine.validate('rws_account', { name: 'A', tier: 'basic' }, { mode: 'insert' } as any); + expect(hidden.results?.[0]?.valid).toBe(true); + const shown = await engine.validate('rws_account', { name: 'A', tier: 'vip' }, { mode: 'insert' } as any); + expect(shown.results?.[0]?.valid).toBe(false); + expect(shown.results?.[0]?.errors).toEqual([expect.objectContaining({ field: 'vip_note', code: 'required' })]); + }); + + it('CONTROL — plain `required`: an insert without it, and an explicit null onto a null row, are refused as before', async () => { + const ins = await refusalOf(() => engine.insert('rws_plain', { title: 'x' })); + expectRequired(ins, 'code'); + storeFor('rws_plain').set('p1', { id: 'p1', title: 'x', code: null }); + const upd = await refusalOf(() => engine.update('rws_plain', { id: 'p1', code: null })); + expectRequired(upd, 'code', true); + }); + + it('CONTROL — only a field with BOTH keys asks for the prior record', () => { + expect(needsPriorRecord({ fields: { code: { required: true } as any } })).toBe(false); + expect(needsPriorRecord({ fields: { note: { visibleWhen: "record.a == 'b'" } as any } })).toBe(false); + expect(needsPriorRecord({ fields: { note: { required: true, visibleWhen: "record.a == 'b'" } as any } })).toBe(true); + }); + }); + + // ── (f) a predicate over a formula field reads the value the form sees ─── + describe('(f) a predicate that reads a formula field is judged on the computed value', () => { + it('an INSERT inside the condition without the field is refused', async () => { + const err = await refusalOf(() => engine.insert('rws_formula', { amount: 500 }, ADMIN)); + expectRequired(err, 'review_note'); + expect(rows('rws_formula')).toHaveLength(0); + }); + + it('an INSERT outside the condition is accepted without the field', async () => { + await engine.insert('rws_formula', { amount: 50 }, ADMIN); + expect(rows('rws_formula')).toHaveLength(1); + }); + + it('an UPDATE that moves the computed value into the condition without the field is refused', async () => { + const { id } = await engine.insert('rws_formula', { amount: 50 }, ADMIN); + const err = await refusalOf(() => engine.update('rws_formula', { id, amount: 500 }, ADMIN)); + expectRequired(err, 'review_note'); + expect(storeFor('rws_formula').get(id)?.amount).toBe(50); + }); + + it('a BULK update judges each row on its own computed value, with one formula plan for the batch', async () => { + storeFor('rws_formula').set('f1', { id: 'f1', amount: 50, review_note: 'filled' }); + storeFor('rws_formula').set('f2', { id: 'f2', amount: 50, review_note: null }); + const err = await refusalOf(() => + engine.update('rws_formula', { amount: 500 }, { where: { review_note: { $ne: 'x' } }, multi: true } as any)); + const entry = expectRequired(err, 'review_note'); + expect(entry.message).toContain('(record f2)'); + expect(rows('rws_formula').map((r) => r.amount)).toEqual([50, 50]); + }); + + it('a dry run judges the computed value the same way', async () => { + const inside = await engine.validate('rws_formula', { amount: 500 }, { mode: 'insert' } as any); + expect(inside.results?.[0]?.valid).toBe(false); + expect(inside.results?.[0]?.errors).toEqual([expect.objectContaining({ field: 'review_note', code: 'required' })]); + const outside = await engine.validate('rws_formula', { amount: 50 }, { mode: 'insert' } as any); + expect(outside.results?.[0]?.valid).toBe(true); + }); + + it('a formula over an EMPTY operand faults on a read too, so the predicate is judged on the null a read serves: hidden', async () => { + // `null > 100` has no overload: a read serves `risk_level = null`, and the + // form hides the field for `null == 'high'`. + await engine.insert('rws_formula', {}, ADMIN); + expect(rows('rws_formula')).toHaveLength(1); + expect(logger.lines.filter((l: any) => l.level === 'warn' && /review_note/.test(l.msg))).toHaveLength(0); + }); + + it('a formula that faults on every row (an undeclared key) reads null for a read too: judged on it, hidden', async () => { + await engine.insert('rws_formula_fault', { amount: 500 }, ADMIN); + expect(rows('rws_formula_fault')).toHaveLength(1); + }); + + it('a formula calling label() is one the write path cannot compute: the predicate counts as shown, logged', async () => { + const err = await refusalOf(() => engine.insert('rws_formula_label', { stage: 'won' }, ADMIN)); + expectRequired(err, 'close_note'); + const warn = logger.lines.find((l: any) => l.level === 'warn' && /close_note/.test(l.msg) && /counted as shown/.test(l.msg)); + expect(warn?.msg).toMatch(/label\(\)/); + expect(warn?.meta).toMatchObject({ field: 'close_note', reason: 'predicate-fault' }); + }); + }); + + // ── (h) a formula the write path cannot compute, read through another ─── + describe('(h) the formulas a predicate reads are judged through the formulas THEY read', () => { + it('a formula over a formula that reads through a reference counts as shown: refused, and logged naming the chain', async () => { + const acc = await engine.insert('rws_tier_account', { name: 'Acme', tier: 'gold' }, ADMIN); + const err = await refusalOf(() => engine.insert('rws_tiered', { account: acc.id }, ADMIN)); + expectRequired(err, 'review_note'); + expect(rows('rws_tiered')).toHaveLength(0); + const warn = logger.lines.find((l: any) => l.level === 'warn' && /review_note/.test(l.msg) && /counted as shown/.test(l.msg)); + expect(warn?.msg).toMatch(/'risk'/); + expect(warn?.msg).toMatch(/'tier_name'/); + expect(warn?.msg).toMatch(/account/); + }); + + it('…and with the field filled the insert is accepted: the fault costs the waiver, never the write', async () => { + const acc = await engine.insert('rws_tier_account', { name: 'Acme', tier: 'gold' }, ADMIN); + await engine.insert('rws_tiered', { account: acc.id, review_note: 'checked' }, ADMIN); + expect(rows('rws_tiered')).toHaveLength(1); + }); + }); + + // ── (i) a formula that reads the acting user, on a write with none ────── + describe('(i) a formula that reads `current_user` is judged per writer, and counts as shown with no acting user', () => { + it('a system write with no acting user counts as shown: refused, and logged as `no-acting-user` naming the formula', async () => { + const err = await refusalOf(() => engine.insert('rws_formula_user', { title: 'Q3' })); + expectRequired(err, 'admin_note'); + expect(rows('rws_formula_user')).toHaveLength(0); + const warn = logger.lines.find((l: any) => l.level === 'warn' && /admin_note/.test(l.msg) && /counted as shown/.test(l.msg)); + expect(warn?.msg).toMatch(/'is_admin'/); + expect(warn?.meta).toMatchObject({ field: 'admin_note', reason: 'no-acting-user' }); + }); + + it('the writer the formula shows the field to must fill it', async () => { + const err = await refusalOf(() => engine.insert('rws_formula_user', { title: 'Q3' }, ADMIN)); + expectRequired(err, 'admin_note'); + expect(rows('rws_formula_user')).toHaveLength(0); + }); + + it('…through a formula that reads it, at any depth: refused, and logged as `no-acting-user` naming the chain', async () => { + const err = await refusalOf(() => engine.insert('rws_formula_user_chain', { title: 'Q3' })); + expectRequired(err, 'audit_note'); + expect(rows('rws_formula_user_chain')).toHaveLength(0); + const warn = logger.lines.find((l: any) => l.level === 'warn' && /audit_note/.test(l.msg) && /counted as shown/.test(l.msg)); + expect(warn?.msg).toMatch(/'needs_audit'/); + expect(warn?.msg).toMatch(/'is_admin'/); + expect(warn?.meta).toMatchObject({ field: 'audit_note', reason: 'no-acting-user' }); + }); + + it('the writer it is hidden from saves without it, nothing logged', async () => { + await engine.insert('rws_formula_user', { title: 'Q3' }, MEMBER); + expect(rows('rws_formula_user')).toHaveLength(1); + expect(logger.lines.filter((l: any) => l.level === 'warn' && /admin_note/.test(l.msg))).toHaveLength(0); + }); + }); + + // ── (g) only a clean TRUE shows the field (the form's reading) ─────────── + describe('(g) a clean value that is not TRUE hides the field, as the form reads it', () => { + it('an unset boolean (null) hides the field: an INSERT without it is accepted, nothing logged', async () => { + await engine.insert('rws_flag', { title: 'plain' }, ADMIN); + expect(rows('rws_flag')).toHaveLength(1); + expect(logger.lines.filter((l: any) => l.level === 'warn' && /perk_note/.test(l.msg))).toHaveLength(0); + }); + + it('TRUE shows it: an INSERT without it is refused', async () => { + const err = await refusalOf(() => engine.insert('rws_flag', { title: 'vip', is_vip: true }, ADMIN)); + expectRequired(err, 'perk_note'); + }); + }); +}); diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index 853f70980a4..ad3e0edd11b 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -35,7 +35,7 @@ import type { SchemaRegistry } from './registry.js'; import { SEARCHABLE_ENUM_TYPES, SEARCHABLE_TEXTUAL_TYPES } from './search-filter.js'; import { ExpressionEngine, analyzeRelationshipTraversals, formulaReadOrder, isUnparseableDate } from '@objectstack/formula'; import type { EvalError, EvalOptionLabels, EvalPermissions } from '@objectstack/formula'; -import { declaredOptionLabels } from './formula-option-labels.js'; +import { declaredOptionLabels, planCallsOptionLabel } from './formula-option-labels.js'; import { ASSEMBLED_VIEW_ITEMS_KEY, AssembledViewArtifactSchema, isAggregatedViewContainer, isViewContainerShaped } from '@objectstack/spec'; import type { Expression } from '@objectstack/spec'; import { deriveViewContainerObject } from '@objectstack/metadata/view-container'; @@ -43,7 +43,7 @@ import { viewContainerNameRefusal } from './view-container-name-refusal.js'; import { ValidationError } from './validation/record-validator.js'; import { NotNullRefusalError } from './not-null-refusal-error.js'; import type { FieldValidationError } from './validation/record-validator.js'; -import { collectReferenceTraversals, referenceTraversalConflicts, staticReadonlyInsertSubject, stripReadonlyFields } from './validation/rule-validator.js'; +import { collectReferenceTraversals, readsPermissionPredicate, readsUserRoot, referenceTraversalConflicts, staticReadonlyInsertSubject, stripReadonlyFields } from './validation/rule-validator.js'; import type { ReferentialClearExemption, RelatedFieldBinding, RelatedRecordBinding } from './validation/rule-validator.js'; import { declaredColumnSet } from './declared-read-columns.js'; @@ -3124,6 +3124,116 @@ async function hydrateWriteFormulas( ); } +/** + * [ADR-0113 D1, as amended] The `formula` fields computed over a record for + * the rule validator's `formulaValues`: a required field's `visibleWhen` that + * reads a formula is judged on the value a read would serve. The SAME plan and + * evaluation a read uses, over a copy of the record. + * + * Two kinds of formula that does not compute, answered apart: + * + * - **Unservable** — the write path cannot know the value a read would serve: + * the formula reads through a reference (no hop is resolved here), calls + * `label()` (no option label is read here), calls `current_user.can()` + * and this write resolved no permission map, or reads the acting user + * (`current_user`, `user`, `ctx`, `os`) and this write has none — a system + * write; or it reads such a formula, at any depth (the plan's read closure, + * {@link orderFormulaPlan}). A formula over one may compute cleanly over the + * `null` it reads here, and still not be the value a read serves, so it is + * unservable too. Named in `unservable` with the reason, and the validator + * counts a predicate reading one as SHOWN; `noActingUser` names those + * unservable for the missing user alone, so the validator logs them as + * `no-acting-user`, as it logs the direct `current_user` spelling. + * - **A fault a read shares** — an operator over an empty operand, an + * undeclared key, a cycle: a read serves `null` for it, and so does this + * copy, so the predicate is judged on that `null`, as the form judges it. + * + * The plan, and which formulas are unservable, are built on the first call, + * so a write whose predicates read no formula pays nothing; a record already + * computed is answered from a memo, so the verdicts of several fields over the + * same merged and prior records compute each once. `undefined` when the + * object declares no formula. + */ +function formulaValuesFor( + schema: any, + execCtx: ExecutionContext | undefined, + permissions: EvalPermissions | undefined, +): ((record: Record) => { record: Record; unservable: ReadonlyMap; noActingUser: ReadonlySet }) | undefined { + const fields = schema?.fields; + if (!fields || typeof fields !== 'object') return undefined; + const formulaNames = Object.keys(fields).filter((name) => fields[name]?.type === 'formula'); + if (formulaNames.length === 0) return undefined; + // The same test `applyFormulaPlan` binds `current_user` by. + const actingUser = Boolean(execCtx?.userId); + let plan: FormulaPlanEntry[] | null | undefined; + const unservable = new Map(); + const noActingUser = new Set(); + const memo = new WeakMap>(); + return (record) => { + if (plan === undefined) { + try { + plan = planFormulaProjection(schema, undefined).plan; + } catch { + plan = null; + for (const name of formulaNames) unservable.set(name, 'cannot be planned (its expression does not compile)'); + } + // In read order, so a formula's reads are judged before it. + for (const entry of plan ?? []) { + const why = unservableReason(entry, permissions, actingUser, unservable, noActingUser); + if (!why) continue; + unservable.set(entry.name, why.reason); + if (why.noActingUser) noActingUser.add(entry.name); + } + } + if (plan === null) return { record, unservable, noActingUser }; + const hit = memo.get(record); + if (hit) return { record: hit, unservable, noActingUser }; + const copy: Record = { ...record }; + applyFormulaPlan(plan, [copy], execCtx, permissions); + memo.set(record, copy); + return { record: copy, unservable, noActingUser }; + }; +} + +/** + * Why the write path cannot compute the value a read serves for one formula, + * or `undefined` when it can ({@link formulaValuesFor}). `known` holds the + * formulas already judged unservable, earlier in read order, and + * `knownNoActingUser` those of them judged so for the missing acting user + * alone; `noActingUser` on the answer says the same of this one, directly or + * through the formula it reads. + */ +function unservableReason( + entry: FormulaPlanEntry, + permissions: EvalPermissions | undefined, + actingUser: boolean, + known: ReadonlyMap, + knownNoActingUser: ReadonlySet, +): { reason: string; noActingUser?: true } | undefined { + if (entry.hops) { + return { reason: `reads through ${[...entry.hops.keys()].map((f) => `'${f}'`).join(', ')}, a reference the write path does not follow` }; + } + if (planCallsOptionLabel([entry])) return { reason: 'calls label(), which the write path does not answer' }; + if (!permissions && readsPermissionPredicate(entry.expression)) { + return { reason: 'calls current_user.can(), and this write resolved no permission map' }; + } + // A read computes it for the reader; a system write has nobody to compute + // it for, so its `null` here is no value any read serves (ADR-0137 D4's + // `no-acting-user` arm, as for the direct `current_user` spelling). Read at + // bare-root granularity, so a formula reading only `os.org` counts too: the + // strict direction, the unconditional `required`. + if (!actingUser && readsUserRoot(entry.expression)) { + return { reason: 'reads the acting user or a bare ctx/os root, and this write has no acting user (a system write)', noActingUser: true }; + } + if (known.size === 0) return undefined; + const reads = storedExpressionReads(entry); + // Reads the member reader cannot name count as reading every formula. + const via = reads === null ? [...known.keys()][0] : [...reads].find((name) => known.has(name)); + if (via === undefined) return undefined; + const reason = `reads the formula '${via}', which ${known.get(via)}`; + return knownNoActingUser.has(via) ? { reason, noActingUser: true } : { reason }; +} + /** * [#24619] The stored computed fields: every field that is NOT a `formula` * and declares an `expression`. Such a field has a column, so a summary can @@ -5339,7 +5449,7 @@ export { assertDispatchableHookEvent, assertHookScopeNotSelfCancelling, assertOrderByIsMaterializable, assertProjectionHasNoDottedPaths, assertValidHookExcludeObjects, assertValidHookObject, assertValidUnscopedMultiWriteFlag, autonumberFieldNames, callerKeySets, callerSuppliedRow, computeStoredExpressions, - deleteWalkTargetOf, describeNonFilterWhere, emptySearchSetError, formulaPlanEntry, handBackWithheldInsertReadonly, + deleteWalkTargetOf, describeNonFilterWhere, emptySearchSetError, formulaPlanEntry, formulaValuesFor, handBackWithheldInsertReadonly, hydrateWriteFormulas, isWhereFilterObject, judgeWhereAdmission, noteRegistrationStamp, organizationPredicateDeleteRefusal, planFormulaProjection, planStoredExpressions, readStoredAutonumberCounter, recomputeAutonumberReaders, refuseSearchOverrideNamingNoField, refuseSearchOverrideNamingNoSearchableField, diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index 71476062daa..b57459009b3 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -55,7 +55,7 @@ import { homeAmountsTouched, planHomeAmounts, projectHomeAmounts, settleBulkHome import { assertFollowedCurrencyCodesUnchanged, parentCurrencyLockReads, touchesFollowedCurrencyCode } from './record-currency-parent-lock.js'; import { stripSearchCompanion } from './search-companion.js'; import { declaredOptionLabels } from './formula-option-labels.js'; -import { ValidationError, coerceBooleanFields, normalizeBlankTypedValues, normalizeMultiValueFields, normalizeNumericStringValues, validateRecord, validateRecordInScope } from './validation/record-validator.js'; +import { ValidationError, coerceBooleanFields, normalizeBlankTypedValues, normalizeMultiValueFields, normalizeNumericStringValues, validateRecordInScope } from './validation/record-validator.js'; import { emitValidationAdvisories, evaluateValidationRules, hasParentScopedReadonlyWhenInPayload, hasParentScopedRequiredWhen, hasReadonlyWhenInPayload, needsPriorRecord, stripReadonlyFields, stripReadonlyWhenFields, stripReadonlyWhenFieldsMulti } from './validation/rule-validator.js'; import type { ReferentialClearExemption } from './validation/rule-validator.js'; import { recordHookPayloadWrites } from './hook-write-provenance.js'; @@ -70,7 +70,7 @@ import { ENGINE_UPDATE_REJECT_MESSAGE, engineUpdateDispatchRejectError, resolveE import type { EngineUpdateDispatchData, EngineUpdateDispatchInput } from './engine-update-dispatch.js'; import { ENGINE_UPDATE_OPTION_KEYS, ENGINE_WHERE_SLOTS, WRITE_PRECONDITION_OPTION, applyFormulaPlan, applyStoredExpressionsToPatch, - computeStoredExpressions, declaredDatetimeLowering, foldEngineOptionAliases, hydrateWriteFormulas, + computeStoredExpressions, declaredDatetimeLowering, foldEngineOptionAliases, formulaValuesFor, hydrateWriteFormulas, lowerWhereFilterArray, masterIdOf, planFormulaProjection, planStoredExpressions, rejectUnknownEngineOptions, storedExpressionsReading, replacedStoredExpressionFields, settleBulkStoredExpressions, shouldSkipStateMachine, staticReadonlyStoredView, @@ -1190,7 +1190,10 @@ export class UpdateFacet { // this write. const judgeStrippedPayload = (payload: Record): void => { normalizeMultiValueFields(updateSchema, payload, 'skip'); - validateRecord(updateSchema, payload, 'update', { mediaValueShapeStrict, valueShapeStrict, messages: updateMsgCtx, onAdmittedValueShapeViolation, keptOptionValues: opCtx.context?.keptOptionValues }); + // [ADR-0113 D1, as amended] `'deferred'`: a clear of a field + // required only when shown is judged by `evaluateValidationRules` + // (both branches below), against its visibility and the prior row. + validateRecordInScope(updateSchema, payload, 'update', 'skip', { mediaValueShapeStrict, valueShapeStrict, messages: updateMsgCtx, onAdmittedValueShapeViolation, keptOptionValues: opCtx.context?.keptOptionValues }, 'deferred'); }; // [#19887] A `readonlyWhen` predicate's `record` is the payload the // write STORES, so it reads each multi-valued field in its stored @@ -1652,7 +1655,7 @@ export class UpdateFacet { async () => [priorRecord], ); if (referencesFirst) await checkReferences(); - emitValidationAdvisories(options?.onValidationAdvisory, evaluateValidationRules(updateSchema as any, hookContext.input.data as Record, 'update', { previous: priorRecord, logger: this.logger, currentUser: this.buildEvalUser(opCtx.context), skipStateMachine: shouldSkipStateMachine(opCtx.context), messages: updateMsgCtx, parent: roWhenParent, previousParent: roWhenPreviousParent, related: relatedForUpdate, permissions: permissionsForUpdate }), this.logger, object); + emitValidationAdvisories(options?.onValidationAdvisory, evaluateValidationRules(updateSchema as any, hookContext.input.data as Record, 'update', { previous: priorRecord, logger: this.logger, currentUser: this.buildEvalUser(opCtx.context), skipStateMachine: shouldSkipStateMachine(opCtx.context), messages: updateMsgCtx, parent: roWhenParent, previousParent: roWhenPreviousParent, related: relatedForUpdate, permissions: permissionsForUpdate, formulaValues: formulaValuesFor(updateSchema, opCtx.context, permissionsForUpdate) }), this.logger, object); if (!referencesFirst) await checkReferences(); // [commit 9d7f7259f] The by-id driver exit — where a driver's refusal // leaves this door, and where a recognised unique violation @@ -2101,6 +2104,8 @@ export class UpdateFacet { readPriorRows, ); if (referencesFirst) await checkReferences(); + // One formula closure for the batch: its plan is built once. + const bulkFormulaValues = formulaValuesFor(updateSchema, opCtx.context, bulkPermissions); if (rulesNeedRows) { // [#34465] Batch equals one-by-one for a rule that reads a // roll-up of a parent: each matched row is judged against @@ -2129,7 +2134,7 @@ export class UpdateFacet { try { const header = parentForRow?.(row); const related = bulkRelatedForRow?.({ ...(row ?? {}), ...bulkPatch }); - emitValidationAdvisories(options?.onValidationAdvisory, evaluateValidationRules(updateSchema as any, hookContext.input.data as Record, 'update', { previous: row, logger: this.logger, currentUser: bulkEvalUser, skipStateMachine: shouldSkipStateMachine(opCtx.context), messages: updateMsgCtx, parent: foldMaster ? summaryFold!.overlayRow(foldMaster, header) : header, previousParent: foldMaster ? summaryFold!.overlayRow(foldMaster, previousParentForRow?.(row)) : previousParentForRow?.(row), related: summaryFold ? summaryFold.overlay(related) : related, permissions: bulkPermissions }), this.logger, object); + emitValidationAdvisories(options?.onValidationAdvisory, evaluateValidationRules(updateSchema as any, hookContext.input.data as Record, 'update', { previous: row, logger: this.logger, currentUser: bulkEvalUser, skipStateMachine: shouldSkipStateMachine(opCtx.context), messages: updateMsgCtx, parent: foldMaster ? summaryFold!.overlayRow(foldMaster, header) : header, previousParent: foldMaster ? summaryFold!.overlayRow(foldMaster, previousParentForRow?.(row)) : previousParentForRow?.(row), related: summaryFold ? summaryFold.overlay(related) : related, permissions: bulkPermissions, formulaValues: bulkFormulaValues }), this.logger, object); summaryFold?.advance(i); } catch (err) { if (err instanceof ValidationError && row?.id != null) { @@ -2146,7 +2151,7 @@ export class UpdateFacet { // every such object down the per-row branch above, where the // binding is supplied. This branch only ever runs for the // rule families that never read a header. - emitValidationAdvisories(options?.onValidationAdvisory, evaluateValidationRules(updateSchema as any, hookContext.input.data as Record, 'update', { previous: null, logger: this.logger, currentUser: bulkEvalUser, skipStateMachine: shouldSkipStateMachine(opCtx.context), messages: updateMsgCtx, permissions: bulkPermissions }), this.logger, object); + emitValidationAdvisories(options?.onValidationAdvisory, evaluateValidationRules(updateSchema as any, hookContext.input.data as Record, 'update', { previous: null, logger: this.logger, currentUser: bulkEvalUser, skipStateMachine: shouldSkipStateMachine(opCtx.context), messages: updateMsgCtx, permissions: bulkPermissions, formulaValues: bulkFormulaValues }), this.logger, object); } if (!referencesFirst) await checkReferences(); // `updateMany` presence is part of the ladder verdict resolved above. diff --git a/packages/objectql/src/engine-validate.ts b/packages/objectql/src/engine-validate.ts index 25fd9f73b01..3725a92a823 100644 --- a/packages/objectql/src/engine-validate.ts +++ b/packages/objectql/src/engine-validate.ts @@ -50,6 +50,7 @@ import type { WriteObservabilityOptions } from '@objectstack/spec/contracts'; import { validateRecordInScope, normalizeBlankTypedValues, normalizeNumericStringValues, ValidationError, valueShapeStrictEffective, mediaStrictEffective } from './validation/record-validator.js'; import { evaluateValidationRules, hasParentScopedRequiredWhen, stripReadonlyFields, stripRuntimeOwnedFields } from './validation/rule-validator.js'; import { createBatchSummaryAccumulator } from './summary-batch-accumulation.js'; +import { formulaValuesFor } from './engine-top-level.js'; import { resolveMasterDetailRelation } from './master-detail.js'; import { assertRecordCurrencyCodes, followParentCurrencyCodes, parentCodeFieldServingOf, recordCurrencyPairs, RecordCurrencyCodeRequiredError, touchesRecordCurrency } from './validation/record-currency-code.js'; import { assertFollowedCurrencyCodesUnchanged, parentCurrencyLockReads, touchesFollowedCurrencyCode } from './record-currency-parent-lock.js'; @@ -565,7 +566,7 @@ export async function validate( // [#22183] The option values an import kept for this write — the // preview admits exactly what the write would. keptOptionValues: options?.context?.keptOptionValues, - }); + }, 'deferred'); // [ADR-0113 D1, as amended] as the write: `evaluateValidationRules` below judges it // [ADR-0144 D8 rule 4] The write's blank-code refusal, at the write's // step and on the write's image: the insert row as stored, or the stored // row with the patch over it (`judgedViews`, the by-id update's @@ -638,6 +639,7 @@ export async function validate( previousParent: previewParents?.previousParents[i], related: batchSummaries ? batchSummaries.overlay(previewRelatedForRow(judgedViews[i])) : previewRelatedForRow(judgedViews[i]), permissions: previewPermissionsFor(row), + formulaValues: formulaValuesFor(schemaForValidation, options?.context, previewPermissionsFor(row)), })); if (previewReferences && !referencesFirst) { await this.assertReferencesResolve(schemaForValidation, row, rawRows[i], options?.context, messages); diff --git a/packages/objectql/src/validation/record-validator.ts b/packages/objectql/src/validation/record-validator.ts index fd9b23e3cb9..93c17f2e5ee 100644 --- a/packages/objectql/src/validation/record-validator.ts +++ b/packages/objectql/src/validation/record-validator.ts @@ -291,6 +291,12 @@ interface FieldDef { required?: boolean; readonly?: boolean; system?: boolean; + /** + * The field's own visibility predicate (ADR-0036 B2). Read here for one + * question only — {@link requiredWhenShown}: does the engine judge this + * field's `required` against its visibility (ADR-0113 D1 as amended)? + */ + visibleWhen?: unknown; multiple?: boolean; maxLength?: number; minLength?: number; @@ -2270,6 +2276,31 @@ function keptOptionsFor( return Array.isArray(values) ? values : []; } +/** + * [ADR-0113 D1, as amended] Is this field's `required` judged together with its + * own `visibleWhen`? A field that declares both is "required when shown": the + * engine waives the requirement for a write whose merged record the predicate + * cleanly hides, and judges the rest by the non-regression invariant against + * the prior record. That judgement needs the merged and prior records and the + * acting user, which this module never holds, so it lives in the rule + * validator (`evaluateValidationRules`) and the engine's write path asks this + * module to leave such a field's presence to it ({@link validateRecordInScope}'s + * `requiredVisibility: 'deferred'`). + * + * A `readonly` field is never required here (the engine owns its presence) and + * an `autonumber` is runtime-owned, so neither is in the set: the same two + * exemptions the `required` arm below makes. + */ +export function requiredWhenShown( + def: { required?: boolean; readonly?: boolean; type?: string; visibleWhen?: unknown } | undefined | null, +): boolean { + return !!def + && def.required === true + && def.visibleWhen != null + && def.readonly !== true + && def.type !== 'autonumber'; +} + /** * Validate a payload against a list of declared fields. `objectSchema` * comes from `ObjectQL.getRegistry().getObject(name)` and exposes a @@ -2355,6 +2386,12 @@ export function validateRecordInScope( mode: Mode, scope: ReadonlyValueScope, options: ValidateRecordOptions = {}, + // [ADR-0113 D1, as amended] `'deferred'` leaves the presence of a field that + // is required when shown ({@link requiredWhenShown}) to the rule validator, + // which the engine's write path runs on the same write. ⛔ Only a caller that + // does run `evaluateValidationRules` afterwards may pass it; the default keeps + // such a field required unconditionally, the "counts as shown" answer. + requiredVisibility: 'enforced' | 'deferred' = 'enforced', ): void { if (!objectSchema?.fields || !data) return; @@ -2374,7 +2411,8 @@ export function validateRecordInScope( // [#21663] A readonly value: its SHAPE, never required (the engine owns // its presence) and never a constraint — see ReadonlyValueScope. const shapeOnly = def.readonly === true; - const err = validateOne(name, def, data[name], shapeOnly, mediaStrict, messages, valueStrict, onAdmitted, shapeOnly, keptOptionsFor(kept, name)); + const deferRequired = requiredVisibility === 'deferred' && requiredWhenShown(def); + const err = validateOne(name, def, data[name], shapeOnly || deferRequired, mediaStrict, messages, valueStrict, onAdmitted, shapeOnly, keptOptionsFor(kept, name)); if (err) errors.push(err); } } else { @@ -2397,7 +2435,11 @@ export function validateRecordInScope( // write that does not touch the field never reaches this check. (The // one over-approximation — explicit null onto an already-null legacy // row — is rejected too; that write was a no-op plus a false claim.) - if (def.required && isEmptyForRequired(def, value) && def.type !== 'autonumber') { + // [ADR-0113 D1, as amended] …unless the field is required only when + // shown and the caller runs the rule validator, which judges the clear + // against the field's visibility and the prior record. + const deferRequired = requiredVisibility === 'deferred' && requiredWhenShown(def); + if (def.required && !deferRequired && isEmptyForRequired(def, value) && def.type !== 'autonumber') { // Same catalog as every other built-in message (#3957) — one wire code // (`required`), a distinct sentence for the clear-out case. errors.push(buildFieldError( diff --git a/packages/objectql/src/validation/rule-validator.ts b/packages/objectql/src/validation/rule-validator.ts index e516aeb18cc..b120d83937d 100644 --- a/packages/objectql/src/validation/rule-validator.ts +++ b/packages/objectql/src/validation/rule-validator.ts @@ -235,7 +235,7 @@ import type { EvalContext, EvalPermissions, RelationshipTraversalAnalysis, Trave import type { Expression } from '@objectstack/spec'; import { AUDIT_PROVENANCE_FIELDS, RUNTIME_OWNED_FIELD_TYPES, referenceTargetOf, resolveInjectedSystemColumns } from '@objectstack/spec/data'; import type { ValidationAdvisoryEvent } from '@objectstack/spec/data'; -import { recordAdvisoryHit } from '@objectstack/core'; +import { isEmptyForRequired, recordAdvisoryHit } from '@objectstack/core'; // [#8215] The canonical spelling of the primary-key column — the sanctioned use // of this registry ("what is the canonical spelling of the column that plays // role X"). The role is structural, not per-object: the driver provisions `id` @@ -251,6 +251,7 @@ import addFormats from 'ajv-formats'; import { ValidationError, buildFieldError, + requiredWhenShown, resolveFieldLabel, type FieldValidationError, type ValidationMessageContext, @@ -432,6 +433,26 @@ export interface EvaluateRulesOptions { * calls `can` ({@link optionVisibilityReadsPermissions}). */ permissions?: EvalPermissions; + /** + * [ADR-0113 D1, as amended] The object's `formula` fields computed over a + * record, as a read computes them: a `formula` is never on the write path + * (computed on read, never stored), so a required field's `visibleWhen` that + * reads one is judged on the value this returns, the value a read of the + * written record would serve. The form computes the same formulas over the + * record being edited (`planObjectFormulas`, `@object-ui/core`), so the two + * agree, except for a formula the form cannot compute (among others, one + * reading `os` or calling `can`), where the form shows the field, keeps it + * required, and the write is judged here. + * `unservable` names, with the reason, each formula whose read value the + * write path cannot know (a hop, `label()`, `can` with no map, a read of the + * acting user on a write with none, or a formula reading one); + * `noActingUser` names those unservable for the missing acting user alone, + * which the verdict logs as `no-acting-user`. A formula that faults for a + * reason a read shares is `null` in the record, as a read serves it. Absent: + * a predicate that reads a formula field cannot be evaluated, and counts as + * shown. + */ + formulaValues?: (record: Record) => { record: Record; unservable: ReadonlyMap; noActingUser?: ReadonlySet }; /** * [#4977] The master-detail header this write's field `requiredWhen` * predicates read as `parent` — the SAME binding, resolved by the SAME engine @@ -1694,8 +1715,10 @@ export function hasParentScopedRequiredWhen( const fields = objectSchema?.fields; if (!fields) return false; for (const def of Object.values(fields)) { - if (!def?.requiredWhen) continue; - if (readsParentRoot(def.requiredWhen)) return true; + if (def?.requiredWhen && readsParentRoot(def.requiredWhen)) return true; + // [ADR-0113 D1, as amended] A required field's own `visibleWhen` decides + // its requirement on the same write and binds `parent` the same way. + if (requiredWhenShown(def) && readsParentRoot(def!.visibleWhen!)) return true; } return false; } @@ -3008,6 +3031,15 @@ interface ConditionalFieldDef { // off-contract — PD #12: no consumer-side dialect fallback returns here. requiredWhen?: string | Expression; readonlyWhen?: string | Expression; + /** + * [ADR-0113 D1, as amended] The static write contract and the field's own + * visibility predicate — read together, and only together: a field that + * declares both is required WHEN SHOWN ({@link evaluateRequiredWhenShown}). + * A field-level `visibleWhen` on a field that is not `required` is display + * only, and nothing here reads it. + */ + required?: boolean; + visibleWhen?: string | Expression; /** Static, unconditional read-only flag (`field.readonly`). #2948. */ readonly?: boolean; /** Auto-injected platform/audit field (`field.system`). Distinguishes the @@ -3046,8 +3078,12 @@ function isMissing(v: unknown): boolean { * sibling that only `previous` supplies (objectui#2284). */ function fieldsNeedPrior(fields: Record | undefined): boolean { if (!fields) return false; + // [ADR-0113 D1, as amended] A field required only when shown counts: the + // reveal-without-filling refusal compares against the prior record. A plain + // `required` with no `visibleWhen` does not, and keeps D1's no-prior-read + // path (the over-approximation that path exists to protect). return Object.values(fields).some( - (f) => f && (f.requiredWhen || f.readonlyWhen || fieldHasOptionVisibility(f)), + (f) => f && (f.requiredWhen || f.readonlyWhen || fieldHasOptionVisibility(f) || requiredWhenShown(f)), ); } @@ -3064,13 +3100,17 @@ function toExpression(cond: string | Expression): Expression { * `buildScope` mounts the SAME `EvalUser` object under `user`, `ctx.user` and * `os.user` as aliases, and mounts none of them when the evaluation carries no * user. `ctx` and `os` are listed at bare-root granularity because that is what - * {@link collectCelRootIdentifiers} reports — and that is exact at THIS call - * site rather than merely conservative: {@link evaluateOptionVisibility} - * evaluates with `{ record, previous, user, permissions }` and nothing else, so - * `buildScope` has no `org`/`env` to mount `os` from and no other source for - * `ctx` (`permissions` mounts no root at all — it reaches `can` through the - * environment, #18783). Both roots are therefore bound here if and only if a - * user is. + * {@link collectCelRootIdentifiers} reports — and that is exact at the + * option-visibility call site rather than merely conservative: + * {@link evaluateOptionVisibility} evaluates with + * `{ record, previous, user, permissions }` and nothing else, so `buildScope` + * has no `org`/`env` to mount `os` from and no other source for `ctx` + * (`permissions` mounts no root at all — it reaches `can` through the + * environment, #18783). Both roots are therefore bound there if and only if a + * user is. At the formula plan's call site (`formulaValuesFor`, through + * `readsUserRoot`) it is only conservative: `applyFormulaPlan` mounts `os.org` + * from the tenant with no user, so a formula reading only `os.org` is marked + * too — the strict direction, the unconditional `required`. */ const USER_SCOPE_ROOTS: readonly string[] = ['current_user', 'user', 'ctx', 'os']; @@ -3098,7 +3138,7 @@ const userRootCache = new Map(); * anything this reader cannot see is a predicate the evaluator could not have * run either, on any write, and it should be said loudly. */ -function readsUserRoot(cond: string | Expression): boolean { +export function readsUserRoot(cond: string | Expression): boolean { const expr = toExpression(cond); if (expr.dialect !== 'cel') return false; const source = typeof expr.source === 'string' ? expr.source : ''; @@ -3523,6 +3563,195 @@ export function nullPreviousReadDetail( + ` so the ${what} decides an insert without it.`; } +/** The three answers a required field's own `visibleWhen` can give a write. */ +type ShownVerdict = 'shown' | 'hidden' | 'fault'; + +/** Per-source `record` / `previous` member reads for {@link formulaReadsOf}; `null` when unnameable. Bounded like the other parse memos. */ +const visibleWhenReadsCache = new Map | null>(); +const VISIBLE_WHEN_READS_CACHE_CAP = 512; + +/** + * The `formula` fields a required field's `visibleWhen` reads through `record` + * or `previous`, by the platform's one member reader. A predicate whose reads + * cannot be named counts as reading every formula field the object declares. + */ +function formulaReadsOf(pred: string | Expression, fields: Record): string[] { + const formulaFields = Object.keys(fields).filter((name) => fields[name]?.type === 'formula'); + if (formulaFields.length === 0) return []; + const expr = toExpression(pred) as { dialect?: string; source?: unknown }; + if (typeof expr?.source !== 'string' || (expr.dialect !== undefined && expr.dialect !== 'cel')) return formulaFields; + let reads = visibleWhenReadsCache.get(expr.source); + if (reads === undefined) { + const named = new Set(); + reads = named; + for (const root of ['record', 'previous']) { + const analysis = analyzeRelationshipTraversals(expr.source, root); + if (!analysis) { reads = null; break; } + for (const name of analysis.bareFields) named.add(name); + for (const name of analysis.traversals.keys()) named.add(name); + } + if (visibleWhenReadsCache.size < VISIBLE_WHEN_READS_CACHE_CAP) visibleWhenReadsCache.set(expr.source, reads); + } + if (reads === null) return formulaFields; + const known = reads; + return formulaFields.filter((name) => known.has(name)); +} + +/** + * [ADR-0113 D1, as amended] A field that declares `required: true` AND its own + * `visibleWhen` is required WHEN SHOWN. The engine's write path leaves its + * presence to this function (`validateRecordInScope`'s `'deferred'` scope), and + * this function judges it from the field's visibility on the write: + * + * - **Hidden** — the predicate evaluates cleanly to anything but TRUE on the + * merged record (FALSE, or a `null` such as an unset boolean): the + * requirement is waived for this write, as the form hides the field for + * exactly those values. A record outside the condition can be created and + * edited, and the form's clear-on-hide `null` is accepted. + * - **Shown** — cleanly TRUE: the non-regression invariant `requiredWhen` uses, + * with the visibility predicate as the condition. Refused iff the merged + * record is empty AND the prior record complied (hidden there, or holding a + * value). So a write that REVEALS the field without filling it is refused — + * the narrowing this amendment ships — while a row already shown and empty + * rests under unrelated edits, and an explicit `null` onto it is accepted + * (the exact rule, not D1's no-prior-read over-approximation). + * - **Fault** — the predicate could not be evaluated (an undeclared key, a read + * through a reference, a root this write does not bind, a system write with + * no acting user under a `current_user` predicate, a `formula` field whose + * read value the write path cannot know, itself or through the formulas it + * reads — a formula reading the acting user on a system write among them): + * it COUNTS AS SHOWN, and + * the field falls back to exactly the unconditional `required` it carried + * before this amendment — an insert must provide it, an update may not clear + * it. Never the `requiredWhen` fault arm (ADR-0137 D2 refuses the write): + * a fault here costs the waiver, not the write. Logged at `warn`, naming the + * field and the fault, so the operator sees the waiver that did not happen + * (ADR-0137 D4); a system write, directly or through a formula, is logged + * with `reason: 'no-acting-user'`. + * + * The scope is the one the client's form binds for a field predicate, as far as + * the server can bind it: `record` (the merged record), `previous`, the acting + * user as `current_user` (and its ADR-0068 aliases) with the permission map the + * option gate reads, and `parent` where the engine resolved a header. A + * `formula` field the predicate reads is computed over the record first + * (`opts.formulaValues`, the read path's plan), because it is never on the + * write path; one that faults for a reason a read shares is judged on the + * `null` a read serves. That is the value a read of the written record serves, + * which the form also computes over the record being edited + * (`planObjectFormulas`, `@object-ui/core`). A role-gated field is judged per writer; the lint refuses + * `current_user` in a field `visibleWhen` at authoring, so only older stored + * metadata reaches that binding. `features`, `app` and `page` are never + * bound server-side; `objectstack validate` and the object save door already + * refuse them in a field `visibleWhen` (`FIELD_RULE_BOUND_ROOTS` in + * `@objectstack/lint`), so only older stored metadata reaches the fault arm + * through them. + * + * Only the object field's OWN `visibleWhen`. A field group's `visibleWhen`, a + * form view's field or section predicate, a hidden tab and static `hidden` are + * not read: the validator never consumes view metadata (ruled on #13252). + */ +function evaluateRequiredWhenShown( + fields: Record, + data: Record, + merged: Record, + previous: PreviousBinding, + mode: Mode, + opts: EvaluateRulesOptions, + errors: FieldValidationError[], +): void { + const user = (opts.currentUser ?? undefined) as any; + const parentExtra = opts.parent != null ? { parent: opts.parent } : undefined; + const prevParent = opts.previousParent !== undefined ? opts.previousParent : opts.parent; + const prevParentExtra = prevParent != null ? { parent: prevParent } : undefined; + const verdictOn = ( + pred: string | Expression, + record: Record, + prior: PreviousBinding, + extra: Record | undefined, + ): { verdict: ShownVerdict; error?: { kind: string; message: string }; noActingUser?: boolean } => { + // A `formula` field is not on the write path: judge the predicate on the + // computed value. A formula whose read value this path cannot know, itself + // or through the formulas it reads, is a fault; one that faults for a + // reason a read shares is judged on the `null` a read serves. + const formulas = formulaReadsOf(pred, fields); + if (formulas.length > 0) { + if (!opts.formulaValues) { + return { verdict: 'fault', error: { kind: 'formula', message: `reads the formula field ${formulas.map((f) => `'${f}'`).join(', ')}, which this write path does not compute` } }; + } + const now = opts.formulaValues(record); + const blocked = formulas.filter((f) => now.unservable.has(f)); + if (blocked.length > 0) { + return { + verdict: 'fault', + error: { kind: 'formula', message: `reads the formula field ${blocked.map((f) => `'${f}', which ${now.unservable.get(f)}`).join('; and ')}` }, + // Every blocked formula is so for the missing acting user alone: the + // `no-acting-user` arm, as for the direct `current_user` spelling. + noActingUser: blocked.every((f) => now.noActingUser?.has(f) === true), + }; + } + record = now.record; + prior = prior ? opts.formulaValues(prior).record as PreviousBinding : prior; + } + const res = ExpressionEngine.evaluate(toExpression(pred), { + ...ruleScope(record, prior, extra), + user, + permissions: opts.permissions, + }); + if (!res.ok) return { verdict: 'fault', error: res.error }; + // Only a clean TRUE shows the field, as the form reads it and as the + // `requiredWhen` loop holds its condition: FALSE, null or any other value + // hides it. + return { verdict: res.value === true ? 'shown' : 'hidden' }; + }; + for (const [name, def] of Object.entries(fields)) { + if (!requiredWhenShown(def)) continue; + const pred = def.visibleWhen!; + const now = verdictOn(pred, merged, previous, parentExtra); + if (now.verdict === 'hidden') continue; + if (now.verdict === 'fault') { + const viaFormula = now.noActingUser === true; + const noActingUser = viaFormula || (user === undefined && readsUserRoot(pred)); + opts.logger?.warn?.( + `visibleWhen of required field '${name}' could not be evaluated ` + + `(${noActingUser && !viaFormula ? 'no acting user to bind current_user (system write)' : `${now.error!.kind}: ${String(now.error!.message).split('\n')[0]}`})` + + ' — counted as shown, so the field stays required on this write', + { field: name, reason: noActingUser ? 'no-acting-user' : 'predicate-fault', error: now.error }, + ); + // The unconditional `required` this field carried before the amendment, + // exactly: the insert walk's presence check, and the update's clear. + if (mode === 'insert') { + if (isEmptyForRequired(def as any, merged[name])) { + errors.push(buildFieldError({ field: name, code: 'required', def }, opts.messages)); + } + } else if (Object.prototype.hasOwnProperty.call(data, name) && isEmptyForRequired(def as any, data[name])) { + errors.push(buildFieldError({ field: name, code: 'required', def, messageKey: 'required_cleared' }, opts.messages)); + } + continue; + } + if (!isEmptyForRequired(def as any, merged[name])) continue; + // Shown and empty. On update, a prior record that already violated (shown + // and empty there too) rests; a prior predicate that faults counts as shown + // there as well, the same answer the write gets. On insert the prior record + // complies vacuously. + if (mode === 'update' && previous) { + const before = verdictOn(pred, previous, previous, prevParentExtra); + if (before.verdict !== 'hidden' && isEmptyForRequired(def as any, previous[name])) continue; + } + // `required_cleared` only for a write that empties a value the row held; + // revealing a field that was never filled is the plain `required` sentence. + const clearing = mode === 'update' + && Object.prototype.hasOwnProperty.call(data, name) + && !!previous + && !isEmptyForRequired(def as any, previous[name]); + errors.push(buildFieldError( + clearing + ? { field: name, code: 'required', def, messageKey: 'required_cleared' } + : { field: name, code: 'required', def }, + opts.messages, + )); + } +} + /** * Evaluate an object's declared validation rules against an incoming write. * @@ -3655,6 +3884,12 @@ export function evaluateValidationRules( } } + // [ADR-0113 D1, as amended] `required` + the field's own `visibleWhen`: + // required WHEN SHOWN. See {@link evaluateRequiredWhenShown}. + if (hasFieldRules && fields) { + evaluateRequiredWhenShown(fields, data, merged, previous, mode, opts, errors); + } + // Per-option authorization / cascade gating (objectui#2284): reject a written // choice value whose option `visibleWhen` resolves cleanly to FALSE against the // merged record + `current_user`. Complements the client-side hiding, which is diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index e5f27868ab7..16dcd985356 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -1512,7 +1512,7 @@ export const FieldSchema = lazySchema(() => { * fail it. The describe is form help in Studio and carries the rule, not the * ruling date (#22093). */ - required: z.boolean().default(false).describe('Write-time contract (ADR-0113): an insert must provide a non-null value, and an update may not null it out. On a multi-value lookup (`multiple: true`) required means NON-EMPTY array — an emptied required set fails validation loudly; `[]` does not satisfy it. NOT a column constraint — the physical NOT NULL is a separate explicit opt-in (`storage.notNull`), so tightening this on a deployed object is safe: existing null rows stay readable, and editable as long as the write does not touch this field.'), + required: z.boolean().default(false).describe('Write-time contract (ADR-0113): an insert must provide a non-null value, and an update may not null it out. With the field\'s own `visibleWhen` it is required WHEN SHOWN: a write whose record the predicate hides does not need it, a write that reveals the field empty is refused, and a predicate the server cannot evaluate counts as shown. On a multi-value lookup (`multiple: true`) required means NON-EMPTY array — an emptied required set fails validation loudly; `[]` does not satisfy it. NOT a column constraint — the physical NOT NULL is a separate explicit opt-in (`storage.notNull`), so tightening this on a deployed object is safe: existing null rows stay readable, and editable as long as the write does not touch this field.'), /** * Physical storage constraints (ADR-0113). Deliberately separate from the @@ -2515,8 +2515,17 @@ export const FieldSchema = lazySchema(() => { * ADR-0137 D2 refuses the write. `objectstack validate` refuses it (#20078); * a `validations[]` `script` rule is the seam that reads one hop through a * reference. + * + * `visibleWhen` is display only, except on a `required` field: there the + * write path reads it too (ADR-0113 D1, as amended), and the field is + * required only on a write whose record the predicate shows: a clean TRUE, + * as the form reads it, with `formula` fields computed over the record being + * written. The form computes the same formulas over the record being edited + * (`planObjectFormulas`, `@object-ui/core`); where it cannot compute one (a + * hop, `label()`, `can()`, `os`, or no signed-in user) it shows the field, + * keeps it required, and the server decides. */ - visibleWhen: EvaluatedExpressionInputSchema.optional().describe("Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`"), + visibleWhen: EvaluatedExpressionInputSchema.optional().describe("Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`. On a `required` field the server reads it on every write: where it is not TRUE (FALSE, or null such as an unset boolean) the field is not required for that write, and a predicate the server cannot evaluate counts as shown, so the field stays required. Reads the record's own columns, with `formula` fields computed over the record being written, as the form computes them over the record being edited; a read THROUGH a reference field, or a formula that reads through one, calls label(), calls can() on a write that picks no permission-gated option, or reads current_user on a system write with no user, cannot be evaluated there."), readonlyWhen: EvaluatedExpressionInputSchema.optional().describe("Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every update that writes the field — `objectstack validate` refuses it. Put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference."), requiredWhen: EvaluatedExpressionInputSchema.optional().describe("Predicate (CEL) — field is required when TRUE. A TRANSITION GATE, not an invariant: the write is refused only when the merged record violates the requirement AND the pre-write record complied — so the write that flips the predicate TRUE, an INSERT born inside the gate, and a write that clears the cell are all refused, while a row that was already missing the value keeps passing unrelated edits and state moves that stay inside the gate (ADR-0113 non-regression: adding the rule to a deployed object never bricks existing rows). Need an invariant every write must satisfy instead ('X may never exceed Y') — declare a `validations[]` `script` rule, which re-checks the merged record with no exemption. Enforced by `evaluateValidationRules`. Reads the bound record's OWN columns: the field level never reads a related record, so a read THROUGH a reference field (`record.account.tier`) faults on every row and refuses every write that reaches it — `objectstack validate` refuses it; put such a check in a `validations[]` `script` rule, whose `condition` is read one hop through a reference. The only slot; the `conditionalRequired` alias was removed in protocol 17."), diff --git a/scripts/adr-anchors/packages__objectql__src__validation__rule-validator.ts.json b/scripts/adr-anchors/packages__objectql__src__validation__rule-validator.ts.json index 6befaf35d9f..8e39c1fa47a 100644 --- a/scripts/adr-anchors/packages__objectql__src__validation__rule-validator.ts.json +++ b/scripts/adr-anchors/packages__objectql__src__validation__rule-validator.ts.json @@ -2,8 +2,9 @@ "file": "packages/objectql/src/validation/rule-validator.ts", "adrs": [ "ADR-0058", + "ADR-0113", "ADR-0124", "ADR-0137" ], - "invariant": "A declared field lock is the SERVER's to enforce — the client grid is courtesy. That rule is ADR-0124 D1, and it is general by construction: ADR-0124 D2 forbids re-narrowing it to one surface, and D3 forbids the specific move this file exists to prevent — resolving an undecided case permissively on the expectation that the courtesy layer will hide the result. This anchor previously carried the rule as an ATTRIBUTION rather than a resolvable anchor, because no ADR had recorded it; #9628 recorded it and the citation was retargeted. A `readonlyWhen` whose predicate names a scope root the write path could not bind resolves to LOCKED, not to \"not locked\": \"could not check\" must never read as \"allowed\" on a field the author declared frozen. This narrowed ADR-0058 D5's fail-soft tier for that case first. ADR-0137 D2 then made every other faulting field-rule predicate REFUSE the write instead of failing open — a broken requiredWhen or readonlyWhen (undeclared key, null overload, parse fault) — and since #22402 (ruling A) a faulting option visibleWhen on the write path refuses too, save a system write with no acting user whose predicate reads one. What stays fail-open is the render side (ADR-0137 D3), a broken format regex or json_schema, and a validation rule that throws." + "invariant": "A declared field lock is the SERVER's to enforce — the client grid is courtesy. That rule is ADR-0124 D1, and it is general by construction: ADR-0124 D2 forbids re-narrowing it to one surface, and D3 forbids the specific move this file exists to prevent — resolving an undecided case permissively on the expectation that the courtesy layer will hide the result. This anchor previously carried the rule as an ATTRIBUTION rather than a resolvable anchor, because no ADR had recorded it; #9628 recorded it and the citation was retargeted. A `readonlyWhen` whose predicate names a scope root the write path could not bind resolves to LOCKED, not to \"not locked\": \"could not check\" must never read as \"allowed\" on a field the author declared frozen. This narrowed ADR-0058 D5's fail-soft tier for that case first. ADR-0137 D2 then made every other faulting field-rule predicate REFUSE the write instead of failing open — a broken requiredWhen or readonlyWhen (undeclared key, null overload, parse fault) — and since #22402 (ruling A) a faulting option visibleWhen on the write path refuses too, save a system write with no acting user whose predicate reads one. What stays fail-open is the render side (ADR-0137 D3), a broken format regex or json_schema, and a validation rule that throws. ADR-0113 D1 (amended 2026-11-17, ruling A on #34905) is enforced here too: a field that is `required` and carries its own `visibleWhen` is required only WHEN SHOWN (`evaluateRequiredWhenShown`) — cleanly hidden waives it, shown applies the non-regression invariant against the prior record, and a fault counts as shown (the unconditional `required`, logged), deliberately NOT the D2 refusal." } diff --git a/ui/docs/adr/0036-field-conditional-rules.md b/ui/docs/adr/0036-field-conditional-rules.md index a77b5e16b4e..9961e579d2a 100644 --- a/ui/docs/adr/0036-field-conditional-rules.md +++ b/ui/docs/adr/0036-field-conditional-rules.md @@ -19,7 +19,7 @@ We express them as three optional CEL predicates on `Field`: | Prop | When the predicate is TRUE | Enforced on | | -------------- | --------------------------------------------------- | ------------------ | -| `visibleWhen` | the field is shown (else hidden) | client (UX only) | +| `visibleWhen` | the field is shown (else hidden) | client; server reads it on a `required` field | | `readonlyWhen` | the field is read-only | **client + server**| | `requiredWhen` | the field is required | **client + server**| @@ -73,6 +73,16 @@ import dragged into the bundle. affordance. The server's `requiredWhen` / `readonlyWhen` are the real guards, so hiding a field client-side never weakens enforcement. + > **Amended (2026-11-17) — one exception: a `required` field.** The framework + > (ADR-0113, amended that day; ruling A on objectstack#34905) evaluates the + > `visibleWhen` of a field that is also `required`, on every write, to decide + > whether the requirement applies: hidden means not required for that write, + > a write that reveals the field empty is refused, and a predicate it cannot + > evaluate counts as shown. Before, such a field was enforced while the form + > hid it, and every record outside the condition refused every save. The + > server still hides nothing: a field's value is returned to every reader + > whatever its `visibleWhen` says. + ### The one fail-CLOSED fault (objectstack#4889) The exception is narrow, and worth stating in full because its symptom is @@ -106,7 +116,8 @@ Everything else keeps the fail-open policy, deliberately: included, is logged and skipped, and the write proceeds. Rejecting a write because a header was momentarily unreadable is a louder failure than refusing one field. -- **`visibleWhen`** is never evaluated server-side at all, per the bullet above. +- **`visibleWhen`** is evaluated server-side only on a `required` field, per the + amendment above, and a fault there counts as shown (the field stays required). ## Client enforcement (objectui) @@ -224,5 +235,6 @@ all of its errors. - Authors express conditional UX once, on the field, in the same CEL they already use for validation rules and formulas — no widget-level wiring. - Client and server cannot drift: identical engine, identical dialect. -- `visibleWhen` is intentionally client-only; never rely on it for security — +- `visibleWhen` hides nothing on the server (on a `required` field it only + decides the requirement); never rely on it for security — use `readonlyWhen` / `requiredWhen` (or a full validation rule) for guarantees. 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 4d56af7bcc4..bd1c804d337 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 @@ -145,6 +145,7 @@ import { useExternalWriteState, } from '../previews/external-object.js'; import { CelPredicateField } from '../CelPredicateField.js'; +import { useRequiredVisibleWhenFormulaReads, useRequiredVisibleWhenReferenceReads } from './requiredVisibleWhenReference.js'; import type { CelLintIssue, CelValueType } from '../celAuthoring.js'; import { t, tFormat, type SupportedLocale } from '../i18n.js'; import { FilterConditionField } from './FilterConditionField.js'; @@ -847,6 +848,24 @@ export function ObjectFieldInspector({ const name = String(selection.id); const idx = indexOfField(view, name); const entry = idx >= 0 ? view.entries[idx] : null; + // [ADR-0113 D1, as amended] A `required` field's own `visibleWhen` decides + // its requirement on the server; a read through a reference there faults and + // counts as shown, so the field stays required where the form hides it. + const siblingTypes = React.useMemo(() => { + const out: Record = {}; + for (const e of view.entries) out[e.name] = e.def?.type; + return out; + }, [view]); + const visibleWhenReferenceReads = useRequiredVisibleWhenReferenceReads(entry?.def ?? null, siblingTypes); + // …and a formula it reads is computed over the saved record there, and that + // value decides; one the server cannot compute keeps it required on every + // save, and the form shows it. + const siblingDefs = React.useMemo(() => { + const out: Record | undefined> = {}; + for (const e of view.entries) out[e.name] = e.def as Record | undefined; + return out; + }, [view]); + const visibleWhenFormulaReads = useRequiredVisibleWhenFormulaReads(entry?.def ?? null, siblingDefs); // A Chinese Label derives the API name through its pinyin (`romanizeHan`); // the dictionary starts loading as soon as the Label holds a Chinese // character, so the keystrokes after it derive. @@ -1932,6 +1951,40 @@ export function ObjectFieldInspector({ slot="visibleWhen" t={tr} /> + {visibleWhenReferenceReads.length > 0 && ( +

+ + + {tFormat('designer.field.requiredVisibleWhenReference', locale, { + fields: visibleWhenReferenceReads.join(', '), + })} + +

+ )} + {visibleWhenFormulaReads.formulas.length > 0 && ( +

+ + + {tFormat('designer.field.requiredVisibleWhenFormula', locale, { + fields: visibleWhenFormulaReads.formulas.join(', '), + })} + {visibleWhenFormulaReads.unservable.length > 0 && ( + <> + {' '} + {tFormat('designer.field.requiredVisibleWhenFormulaUnservable', locale, { + fields: visibleWhenFormulaReads.unservable.join(', '), + })} + + )} + +

+ )} analyzeRelationshipTraversals(source, root)?.traversals ?? null; + +const TYPES = { account: 'lookup', parent_deal: 'master_detail', status: 'text', ship_to: 'address' }; + +const reads = (def: Record) => referenceReadsInRequiredVisibleWhen(def, TYPES, read); + +describe('requiredVisibleWhenReference — the advisory (ADR-0113 D1, as amended)', () => { + it('names the reference a required field\'s visibleWhen reads through', () => { + expect(reads({ required: true, visibleWhen: "record.account.tier == 'vip'" })).toEqual(['account']); + }); + + it('reads the envelope spelling and `previous`, and names each reference once', () => { + expect(reads({ + required: true, + visibleWhen: { dialect: 'cel', source: "previous.parent_deal.stage == 'won' || record.account.tier == 'vip' || record.account.region == 'cn'" }, + })).toEqual(['account', 'parent_deal']); + }); + + it('draws nothing for a field that is not required — visibleWhen is display only there', () => { + expect(reads({ visibleWhen: "record.account.tier == 'vip'" })).toEqual([]); + }); + + it('draws nothing for the record\'s own columns, or for an object-valued field', () => { + expect(reads({ required: true, visibleWhen: "record.status == 'open'" })).toEqual([]); + expect(reads({ required: true, visibleWhen: "record.ship_to.city == 'Paris'" })).toEqual([]); + }); + + it('draws nothing for a predicate that does not parse, or a non-CEL envelope', () => { + expect(reads({ required: true, visibleWhen: 'record.account.' })).toEqual([]); + expect(reads({ required: true, visibleWhen: { dialect: 'js', source: 'record.account.tier' } })).toEqual([]); + expect(predicateSource(' ')).toBeNull(); + }); +}); + +const readFields: FieldReader = (source, root) => { + const a = analyzeRelationshipTraversals(source, root); + return a ? { bare: a.bareFields, through: new Set(a.traversals.keys()) } : null; +}; +const callsCan = (source: string) => callsReceiverMethod(parseCelToAst(source), 'can'); + +const SIBLINGS: Record> = { + account: { type: 'lookup', reference: 'account' }, + amount: { type: 'number' }, + stage: { type: 'select' }, + risk: { type: 'formula', expression: "record.amount > 100 ? 'high' : 'low'" }, + tier_name: { type: 'formula', expression: 'record.account.tier' }, + tier_risk: { type: 'formula', expression: "record.tier_name == 'gold' ? 'high' : 'low'" }, + stage_label: { type: 'formula', expression: 'label(record.stage)' }, + can_edit: { type: 'formula', expression: "current_user.can('account', 'edit')" }, +}; + +const formulaReads = (def: Record) => formulaReadsInRequiredVisibleWhen(def, SIBLINGS, readFields, callsCan); + +describe('requiredVisibleWhenReference — the formula advisory (ADR-0113 D1, as amended)', () => { + it('names a formula a required field\'s visibleWhen reads; one the server computes is not unservable', () => { + expect(formulaReads({ required: true, visibleWhen: "record.risk == 'high'" })).toEqual({ formulas: ['risk'], unservable: [] }); + }); + + it('marks a formula over a formula that reads through a reference, at any depth', () => { + expect(formulaReads({ required: true, visibleWhen: "record.tier_risk == 'high'" })) + .toEqual({ formulas: ['tier_risk'], unservable: ['tier_risk'] }); + }); + + it('marks a formula that calls label() or current_user.can()', () => { + expect(formulaReads({ required: true, visibleWhen: "record.stage_label == 'Won' || record.can_edit" })) + .toEqual({ formulas: ['stage_label', 'can_edit'], unservable: ['stage_label', 'can_edit'] }); + }); + + it('draws nothing for a field that is not required, or a predicate reading no formula', () => { + expect(formulaReads({ visibleWhen: "record.risk == 'high'" })).toEqual({ formulas: [], unservable: [] }); + expect(formulaReads({ required: true, visibleWhen: 'record.amount > 5' })).toEqual({ formulas: [], unservable: [] }); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/requiredVisibleWhenReference.ts b/ui/packages/app-shell/src/views/metadata-admin/inspectors/requiredVisibleWhenReference.ts new file mode 100644 index 00000000000..199b1f4920a --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/requiredVisibleWhenReference.ts @@ -0,0 +1,282 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The author-time advisory for a `required` field whose own `visibleWhen` + * reads THROUGH a reference field (`record.account.tier` on a lookup named + * `account`). + * + * ## The hazard + * + * Since ADR-0113's 2026-11-17 amendment a field that is `required` and carries + * its own `visibleWhen` is required only WHEN SHOWN: the server judges the + * requirement from that predicate on every write. The field level is never + * hydrated on the server, so a read through a reference meets the related + * record's bare id and faults; a fault counts as SHOWN, and the field stays + * required on every record, the ones the form hides it on included. The form + * resolves the predicate and hides the field, so the user is refused on save + * naming a field they cannot see. + * + * ## Why an advisory, not a blocking issue + * + * The server ACCEPTS the field and keeps exactly the unconditional `required` + * it had before the amendment, so nothing gets worse; only the waiver never + * happens. `@objectstack/lint` reports the same shape as a WARNING at + * `objectstack validate` and the object save door (the `visibleWhen` field + * traversal slot), and this is that verdict shown where the author writes the + * predicate. The roots the server cannot bind (`features`, `app`, `page`, the + * acting user) are already refused for every field `visibleWhen` by the + * predicate editor itself, so they draw nothing here. + * + * ## A `formula` the predicate reads + * + * The server computes each formula the predicate reads over the record being + * saved, and that value decides. The form computes the same formulas over the + * record being edited; a check that computes none (a wizard's final-submit + * check, or a form whose data source serves no object schema) judges the + * formula value last read, none on a create, and can disagree with the server. + * The advisory is that reminder, for any formula read. A formula the server + * cannot compute on a save at all (it reads through a reference, calls + * `label()` or `current_user.can()`, or reads such a formula) keeps the field + * required on every save, and the form, which cannot compute it either, shows + * the field and keeps it required; the advisory says that too. A `can` call is + * uncomputed on the server only on a save that picks no permission-gated + * option (a save that picks one resolves the permission map, and the server + * computes it). The server's fourth mark, a formula reading the acting user on a system + * write with no user, is not advised: a save from Studio's form always has a + * user. The lint's `required-visible-when-formula-issue.ts` is the same + * verdict at `objectstack validate`. + * + * ## The reads are found by the parser, never by a pattern + * + * `analyzeRelationshipTraversals` is the `@objectstack/formula` export the + * server and the lint run on the same predicate. It is loaded LAZILY, as every + * CEL affordance in this designer is, so the parser stays off the eager graph. + * A source that does not parse draws nothing: syntax belongs to the CEL lint. + */ + +import * as React from 'react'; +import { REFERENCE_VALUE_TYPES } from '@objectstack/spec/data'; + +/** The `record` / `previous` member reads a source takes through a field, by field. */ +export type TraversalReader = (source: string, root: string) => ReadonlyMap | null; + +/** The CEL source of a field predicate, or `null` when there is none. */ +export function predicateSource(raw: unknown): string | null { + let source: unknown = raw; + if (raw && typeof raw === 'object' && !Array.isArray(raw)) { + const env = raw as Record; + if (env.dialect !== undefined && env.dialect !== 'cel') return null; + source = env.source; + } + if (typeof source !== 'string') return null; + const trimmed = source.trim(); + return trimmed ? trimmed : null; +} + +/** + * The reference fields a `required` field's `visibleWhen` reads through, in + * first-seen order. Empty when the field is not required, has no predicate, the + * predicate does not parse, or every read is of this object's own columns. + */ +export function referenceReadsInRequiredVisibleWhen( + def: Record | null | undefined, + fieldTypes: Readonly>, + readTraversals: TraversalReader, +): string[] { + if (!def || def.required !== true) return []; + const source = predicateSource(def.visibleWhen); + if (!source) return []; + const out: string[] = []; + for (const root of ['record', 'previous']) { + const traversals = readTraversals(source, root); + if (!traversals) continue; + for (const field of traversals.keys()) { + const type = fieldTypes[field]; + if (typeof type === 'string' && REFERENCE_VALUE_TYPES.has(type) && !out.includes(field)) out.push(field); + } + } + return out; +} + +/* ── Formula reads (ADR-0113 D1, as amended) ──────────────────────────── */ + +/** The fields a source reads as values or through, over one root; `null` when the reader cannot say. */ +export type FieldReader = (source: string, root: string) => { bare: ReadonlySet; through: ReadonlySet } | null; + +/** A call of `label(`, spelled as the server's `planCallsOptionLabel` reads it. */ +const LABEL_CALL = /\blabel\s*\(/; + +/** + * The `formula` fields a `required` field's `visibleWhen` reads, and which of + * them the server cannot compute on a save: a formula that reads through a + * reference, calls `label()` or calls `current_user.can()`, or reads such a + * formula at any depth (the server's `unservableReason`). Both empty when the + * field is not required, has no predicate, or the predicate reads no formula. + * + * Any formula read draws the advisory: a reminder that the server judges the + * predicate on the formula value it computes over the record being saved. An + * unservable one keeps the field required on every save, and the form shows it. + */ +export function formulaReadsInRequiredVisibleWhen( + def: Record | null | undefined, + siblings: Readonly | undefined>>, + readFields: FieldReader, + callsCan: (source: string) => boolean, +): { formulas: string[]; unservable: string[] } { + const none = { formulas: [], unservable: [] }; + if (!def || def.required !== true) return none; + const source = predicateSource(def.visibleWhen); + if (!source) return none; + const isFormula = (name: string) => siblings[name]?.type === 'formula'; + const formulas: string[] = []; + for (const root of ['record', 'previous']) { + const reads = readFields(source, root); + if (!reads) continue; + for (const name of [...reads.bare, ...reads.through]) if (isFormula(name) && !formulas.includes(name)) formulas.push(name); + } + if (formulas.length === 0) return none; + const verdicts = new Map(); + const unservable = (name: string): boolean => { + const known = verdicts.get(name); + if (known !== undefined) return known; + verdicts.set(name, false); + const expr = predicateSource(siblings[name]?.expression); + let blocked = false; + if (expr) { + const reads = readFields(expr, 'record'); + const hop = reads ? [...reads.through].some((f) => { + const type = siblings[f]?.type; + return typeof type === 'string' && REFERENCE_VALUE_TYPES.has(type); + }) : false; + blocked = hop || LABEL_CALL.test(expr) || callsCan(expr) + || [...(reads?.bare ?? []), ...(reads?.through ?? [])].some((f) => isFormula(f) && unservable(f)); + } + verdicts.set(name, blocked); + return blocked; + }; + return { formulas, unservable: formulas.filter(unservable) }; +} + +/* ── The lazily loaded traversal reader ───────────────────────────────── */ + +type Analyze = (source: string, root: string) => { + traversals: ReadonlyMap; + bareFields?: ReadonlySet; +} | null; +type ParseAst = (source: string) => unknown; + +let analyzeCached: Promise | null = null; +let parseCached: Promise | null = null; + +function loadAnalyzer(): Promise { + if (!analyzeCached) { + analyzeCached = import('@objectstack/formula') + .then(({ analyzeRelationshipTraversals }) => + typeof analyzeRelationshipTraversals === 'function' ? (analyzeRelationshipTraversals as unknown as Analyze) : null, + ) + .catch(() => null); + } + return analyzeCached; +} + +function loadParser(): Promise { + if (!parseCached) { + parseCached = import('@objectstack/formula') + .then(({ parseCelToAst }) => (typeof parseCelToAst === 'function' ? (parseCelToAst as unknown as ParseAst) : null)) + .catch(() => null); + } + return parseCached; +} + +/** Does a cel-js AST hold a receiver call named `method` (`current_user.can(…)`)? */ +export function callsReceiverMethod(node: unknown, method: string): boolean { + if (Array.isArray(node)) return node.some((child) => callsReceiverMethod(child, method)); + if (typeof node !== 'object' || node === null) return false; + const { op, args } = node as { op?: unknown; args?: unknown }; + if (typeof op !== 'string') return false; + if (op === 'rcall' && Array.isArray(args) && args[0] === method) return true; + return callsReceiverMethod(args, method); +} + +/** + * The formula advisory for one field draft, stamped with its inputs like the + * reference one below. Empty while the parser loads and when it is unavailable. + */ +export function useRequiredVisibleWhenFormulaReads( + def: Record | null | undefined, + siblings: Readonly | undefined>>, +): { formulas: string[]; unservable: string[] } { + const source = def && def.required === true ? predicateSource(def.visibleWhen) : null; + const key = source ? JSON.stringify([source, siblings]) : ''; + const [state, setState] = React.useState<{ key: string; formulas: string[]; unservable: string[] }>({ key: '', formulas: [], unservable: [] }); + + React.useEffect(() => { + if (!key || !source) return; + let cancelled = false; + void Promise.all([loadAnalyzer(), loadParser()]).then(([analyze, parse]) => { + if (cancelled || !analyze) return; + const readFields: FieldReader = (src, root) => { + try { + const a = analyze(src, root); + return a ? { bare: a.bareFields ?? new Set(), through: new Set(a.traversals.keys()) } : null; + } catch { + return null; + } + }; + const callsCan = (src: string) => { + if (!parse) return false; + try { + return callsReceiverMethod(parse(src), 'can'); + } catch { + return false; + } + }; + setState({ key, ...formulaReadsInRequiredVisibleWhen(def, siblings, readFields, callsCan) }); + }); + return () => { + cancelled = true; + }; + // `key` carries `source` and `siblings`; `def` is read through them. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key]); + + return key && state.key === key ? { formulas: state.formulas, unservable: state.unservable } : { formulas: [], unservable: [] }; +} + +/** + * The advisory's reference fields for one field draft. Empty while the parser + * loads and when it is unavailable — this check reports only what it has read. + * The answer is STAMPED with the inputs it was computed from, so a verdict that + * lands after the author edited the predicate cannot describe the new one. + */ +export function useRequiredVisibleWhenReferenceReads( + def: Record | null | undefined, + fieldTypes: Readonly>, +): string[] { + const source = def && def.required === true ? predicateSource(def.visibleWhen) : null; + const key = source ? JSON.stringify([source, fieldTypes]) : ''; + const [state, setState] = React.useState<{ key: string; fields: string[] }>({ key: '', fields: [] }); + + React.useEffect(() => { + if (!key || !source) return; + let cancelled = false; + void loadAnalyzer().then((analyze) => { + if (cancelled || !analyze) return; + const reader: TraversalReader = (src, root) => { + try { + return analyze(src, root)?.traversals ?? null; + } catch { + return null; + } + }; + setState({ key, fields: referenceReadsInRequiredVisibleWhen(def, fieldTypes, reader) }); + }); + return () => { + cancelled = true; + }; + // `key` carries `source` and `fieldTypes`; `def` is read through them. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key]); + + return key && state.key === key ? state.fields : []; +} diff --git a/ui/packages/core/src/evaluator/__tests__/fieldRules.test.ts b/ui/packages/core/src/evaluator/__tests__/fieldRules.test.ts index f14ae6036cd..3b24f7d2797 100644 --- a/ui/packages/core/src/evaluator/__tests__/fieldRules.test.ts +++ b/ui/packages/core/src/evaluator/__tests__/fieldRules.test.ts @@ -617,3 +617,19 @@ describe('resolveFieldRuleState — `requiredWhen` as a transition gate (objects ).toBe(false); }); }); + +// [ADR-0113 D1, as amended — objectstack#34905] The server judges a required +// field's `visibleWhen` the way this reader does: only a clean TRUE shows the +// field. A clean value that is not TRUE (an unset boolean reads `null`) hides +// it, so the form drops the marker and the server waives the requirement on +// the same record. +describe('evalFieldPredicate — only a clean TRUE shows a field (the server reads it the same way)', () => { + it('an unset boolean (null) hides the field, without the fallback', () => { + expect(evalFieldPredicate('record.is_vip', { is_vip: null }, true)).toBe(false); + }); + + it('a clean non-boolean value hides it too; TRUE shows it', () => { + expect(evalFieldPredicate('record.tier', { tier: 'vip' }, true)).toBe(false); + expect(evalFieldPredicate('record.is_vip', { is_vip: true }, false)).toBe(true); + }); +}); diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 58b1df1eef8..ac3d1ee2864 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -580,6 +580,12 @@ const STUDIO_EN: Record = { 'designer.field.requiredWhen': 'Required when', 'designer.field.conditionalRulesHint': 'While a predicate is true the field becomes visible / read-only / required. Reference the live record as record., the last saved values as previous., and (in master-detail line items) the header record as parent..', + 'designer.field.requiredVisibleWhenReference': + 'This field is required, and the server decides that from this condition on every save. The condition reads through {fields}, a reference the server cannot follow here, so it counts the field as shown: it stays required on every record, including the ones this condition hides it on. Read a field of this object instead.', + 'designer.field.requiredVisibleWhenFormula': + 'This field is required, and the server decides that from this condition on every save, with {fields} computed over the record being saved. The form computes the same formula as you edit; a wizard\'s final-submit check, or a form whose data source serves no object schema, judges the value it last read instead (a new record has none) and can disagree with the server.', + 'designer.field.requiredVisibleWhenFormulaUnservable': + '{fields} reads through a reference, or calls label() or current_user.can(), itself or through another formula, which the server cannot compute on a save (current_user.can() only on a save that picks no permission-gated option): it counts this field as shown, so it stays required on every record. The form cannot compute it either: it shows this field and keeps it required.', // Bulk multi-select (Tier 2) 'designer.canvas.bulkSelected': '{n} selected', 'designer.canvas.bulkMoveTo': 'Move to section', diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index 18fe2fea5c9..311a1f9d475 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -497,6 +497,12 @@ const STUDIO_ZH: Record = { 'designer.field.requiredWhen': '必填条件', 'designer.field.conditionalRulesHint': '表达式为真时字段相应地变为可见 / 只读 / 必填。用 record.<字段> 引用当前记录,previous.<字段> 引用最近保存的值,parent.<字段>(主从明细行)引用表头记录。', + 'designer.field.requiredVisibleWhenReference': + '该字段为必填,服务器每次保存时按这条可见条件判断是否必填。条件经由引用字段 {fields} 读取关联记录,服务器在这里无法读取,因此按「显示」处理:所有记录(包括此条件隐藏该字段的记录)都仍要求填写。请改为读取本对象自己的字段。', + 'designer.field.requiredVisibleWhenFormula': + '该字段为必填,服务器每次保存时按这条可见条件判断是否必填,其中的 {fields} 按要保存的记录计算。表单在你编辑时也会同样计算该公式;但向导最后提交时的检查,以及数据源不提供对象定义的表单,用的是上次读取的公式值(新建记录时没有值),可能与服务器的判断不一致。', + 'designer.field.requiredVisibleWhenFormulaUnservable': + '{fields} 经由引用字段读取、调用了 label() 或 current_user.can()(直接或通过其他公式),服务器保存时无法计算(current_user.can() 仅在保存未选择受权限控制的选项时无法计算),因此按「显示」处理:所有记录都仍要求填写。表单同样无法计算它:会显示该字段并保持必填。', // Bulk multi-select (Tier 2) 'designer.canvas.bulkSelected': '已选 {n} 项', 'designer.canvas.bulkMoveTo': '移至分组',