Skip to content

Commit 0739dee

Browse files
fix(objectql)!: a required field hidden by its own visibleWhen is required only when shown (#34978)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBDUFMZqRLX4w5ukkNY5RaQh)_ Fixes #34905 Clause-②: yes (narrowing + widening of the required write contract) Metadata-protocol: semantic Skills-docs: none — no skill teaches `required` and `visibleWhen` together; objectstack-data's "Use visibleWhen to hide irrelevant fields" stays true, and the combination's meaning lives in the `FieldSchema` describes. ## 维护者速读 - 改了什么:字段同时设了「必填」和自己的「显示条件」(visibleWhen)时,服务端改为「显示时才必填」:条件不为真(为假或为空值,字段被隐藏)的记录,新建和保存都不再要求它;把记录改到条件内却不填它,会被拒绝;条件算不出来时按「显示」处理,保持原来的必填,并在服务端日志里写一条警告。条件里读到公式字段时,先按读取时的算法算出公式值再判断;公式因空值等原因算不出(读取时也是空值)就按空值判断,公式经由关联字段读取、调用 label() 或 can()(含间接经由其他公式)时写入路径无法得知读取值,按「显示」处理;公式读取当前用户(current_user)而本次写入没有操作用户(系统写入)时同样按「显示」处理,日志原因记为 `no-acting-user`,与条件里直接写 current_user 的情形一致。 - 为什么改:在 Studio 里给对象加一个「必填 + 显示条件」的字段只需几下点击,之后所有不满足条件的记录都无法新建,表单隐藏字段时会把它清空,也无法保存(提示「验证用-备注字段是必填项,不能清空」),整个组织被一处配置锁住。 - 风险与回滚:这是收紧加放宽。放宽:隐藏时不再必填。收紧:流程、批量更新、导入和 API 把已有记录改进条件却不填该字段,现在会被拒(批量里一行不合格整批拒),changeset 写明了 BREAKING。没有设显示条件的必填字段完全不变。另加三条 lint 警告(条件经由关联字段读取;条件读公式字段;同时设了 `storage.notNull`),Studio 字段面板对前两种显示提示。原先记录的已知限制(表单不重算公式)已由 main 上的表单侧重算(#35116)关闭:表单现在按正在编辑的记录重算公式再判断字段规则;表单算不了的公式(经由关联字段、label()、can()、读 os、未登录时读用户)让字段显示并保持必填,由服务端在保存时判定。回滚即 revert 本 PR。 - 先看:① `rule-validator.ts` 新增的 `evaluateRequiredWhenShown`(隐藏 / 显示 / 算不出三条分支,以及 `fieldsNeedPrior` 的新条件);② `record-validator.ts` 的 `requiredWhenShown` 与 `'deferred'` 参数(插入遍历和更新清空检查让给上面的规则);③ ADR-0113 末尾的修订一节(包括作者期围栏为什么收窄、三处服务端答案以哪处为准)。 - 两分钟验证:在仓根执行 `pnpm --filter @objectstack/objectql exec vitest run src/engine-required-when-shown.test.ts`,预期 35 个测试全部通过。 - 需要你做的:这是 Tier H(改了 ADR-0113 / ADR-0137),需要 os-zhuang 审批;请先看 ADR-0113 的修订一节。 ## What changes **Engine (`@objectstack/objectql`).** A field with `required: true` and its own `visibleWhen` is judged by a new pass, `evaluateRequiredWhenShown` in `rule-validator.ts`, run after the `requiredWhen` loop: - **Hidden**: the predicate evaluates cleanly to anything but TRUE on the merged 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. This is the form's reading, which shows a field only for a clean TRUE. The form's clear-on-hide `null` is accepted. - **Shown**: the predicate is true. The ADR-0113 D1 non-regression rule applies with the predicate as its condition, judged against the prior record. A write that reveals the field empty is refused with `required`. A row already shown and empty rests under unrelated edits. The message is `required_cleared` only when the payload clears a value that was there. - **Fault**: the predicate cannot be evaluated, so it counts as shown. The field takes exactly the unconditional rule it had before (an insert must provide it, an update may not clear it), and the server logs a `warn` naming the field and the fault, with `reason: 'predicate-fault'` or `'no-acting-user'` (ADR-0137 D4). This is a new arm. The `requiredWhen` fault arm, which refuses the write, is unchanged. The predicate is evaluated with `record`, `previous`, `parent` where the write resolves a header, and the acting user bound as `current_user` with the permission map the option gate reads. A system write with no acting user takes the fault arm. A `formula` field is computed on read and is never on the write path. So the engine computes the object's formulas over the merged record and the prior record before it evaluates a predicate that reads one. It uses the read path's own plan (`formulaValuesFor` in `engine-top-level.ts`, passed to the rule pass as `formulaValues` at the insert, by-id update, bulk update and `validate()` call sites). A formula that does not compute is answered by the reason (the seat's S2 ruling): - *A fault a read shares* (an operator over an empty operand, an undeclared key, a cycle): a read serves `null`, so the predicate is judged on that `null`, as the form judges it. Not a fault of the predicate. - *A value only a read can have*: the formula reads through a reference, calls `label()`, calls `current_user.can()` with no permission map resolved for the write (one is resolved only when the write picks a permission-gated option), or reads the acting user (`current_user`, `user`, `ctx`, `os`) on a write that has none (a system write), or it reads such a formula at any depth. `formulaValuesFor` marks these `unservable` once per write, walking the plan in read order so the whole read closure counts, and the predicate is a fault, which counts as shown and is logged naming the chain (`'risk', which reads the formula 'tier_name', which reads through 'account', …`). The acting-user mark is logged with `reason: 'no-acting-user'`, the reason the direct `current_user` spelling logs (`noActingUser` beside `unservable` on the `formulaValues` answer). A caller that passes no `formulaValues` gets the fault answer. The bulk update builds one formula closure per batch, predicate reads are memoised per source, and a record's formulas are computed once per write (L1-d's and the seat's N7). **The form recomputes formulas too (S3's known limit, now closed on main).** The form-side recompute (#35116, merged into this branch) computes the object's `formula` fields over the record being edited before the field rules are judged: the object form renderer over its `ruleRecord` (`ui/packages/components/src/renderers/form/form.tsx:2153`) and the console form-view page over its live values (`ui/apps/console/src/components/FormPage.tsx:2813`), both through `planObjectFormulas` (`ui/packages/core/src/evaluator/formulaRecord.ts:230`). A formula the form cannot compute (a hop, `label()`, `current_user.can()`, a read of `os`, a read of the user with nobody signed in, an expression not served, or a formula reading one) drops the `visibleWhen` that reads it, so the field is shown and keeps its `required` flag (`objectFormulas.ts:107`, `FormPage.tsx:2440`), and the server decides. For `os` and `can()` the form can be stricter than the server (`formulaRecord.ts:58`). The ADR-0113 amendment, the `visibleWhen` TSDoc and describe, the `formulaValues` and `evaluateRequiredWhenShown` jsdoc and the changeset now say this. The lint warning and the Studio advisory no longer say the form does not recompute (S6, fix round on `1ca9b694`): the plain formula read is a reminder that the server's computed value decides, naming the two checks that still compute none, and the unservable arm says the form shows the field and keeps it required. `record-validator.ts` gains `requiredWhenShown(def)` and a `requiredVisibility` parameter on `validateRecordInScope`. The three engine call sites (`engine-insert.ts`, `engine-update.ts`, `engine-validate.ts`) pass `'deferred'`, so the insert walk's presence check and the update's clear check leave such a field to the pass above. A field with `required` and no `visibleWhen`, a `readonly` field and an `autonumber` field keep the old path. `fieldsNeedPrior` counts a field only when it has both keys, so plain `required` still costs no prior-record read. `engine-update.ts` now calls `validateRecordInScope` directly (the `validateRecord` import it no longer uses is removed). The bulk update's per-row branch reads each row through the same `rulesNeedRows` path. **Lint (`@objectstack/lint`).** On a `required` field with a `visibleWhen`, three new **warnings** at `objectstack validate` and the object save door: - the predicate reads through a reference field: the field level is never hydrated on the server, so the predicate always faults and the field stays required everywhere; - the predicate reads a `formula` field (`required-visible-when-formula-issue.ts`): a reminder that the server judges the requirement on the formula value it computes over the record being written, while a check that computes none (a wizard's final-submit check, a form whose data source serves no object schema) judges the value last read; and when a formula in its read closure reads through a reference or calls `label()` or `can`, the message adds that the server counts the field as shown on every write and that the form, which cannot compute it either, shows the field and keeps it required (for `can`, that a write picking a permission-gated option computes it); a formula reading the acting user draws no warning, since it is computed per writer on every write that has one; - `storage.notNull: true` beside the pair: the column still refuses the null the write contract now admits. The reference-read check reuses the `requiredWhen` / `readonlyWhen` traversal refusal (`refuseFieldTraversal`) with a new `visibleWhen` slot and a `severity` argument. **Author-time fence, narrowed from ruling item 4 (agreed with the seat 18:27Z).** The ruling asked for a warning on `required` + `visibleWhen` reading the `features`, `app` or `page` roots. That half already exists at error level: `FIELD_RULE_BOUND_ROOTS` refuses every root but `record`, `previous` and `parent` in any field `visibleWhen`, at `objectstack validate`, at the object save door and in Studio's predicate editor. A weaker warning beside it would add nothing, so none is added. The `current_user` binding stays, for older stored metadata that predates the refusal. Only the reference-read warning and the `storage.notNull` warning are added. The ADR-0113 amendment records this narrowing. **Studio (`@object-ui/app-shell`, `@object-ui/i18n`).** The field inspector shows the reference-read warning and the formula-read warning under the Visible-when editor of a required field (`designer.field.requiredVisibleWhenReference`, `requiredVisibleWhenFormula`, `requiredVisibleWhenFormulaUnservable`, en and zh). The reads are found by the same `analyzeRelationshipTraversals` the server and the lint use, loaded lazily like the other CEL affordances, and the answer is stamped with the inputs it was computed from. **Spec (`@objectstack/spec`).** The `required` and `visibleWhen` describes on `FieldSchema` say how the two combine. The generated references (`field.mdx`, `object.mdx`, `migration.mdx`) are regenerated. **Records.** - ADR-0113: D1 and D5 notes and an "Amendment (2026-11-17) — required when shown" section covering the ruling, the rule, its scope, the narrowed fence, what is not in scope, which server answer is canonical, and the readers left as they are. - ADR-0137: an amendment note and a row in the field-rule fault table. - ui ADR-0036: the table row and the "not a server concept" bullet are amended. - `validating-metadata.mdx`: the submit paragraph is updated. - The `rule-validator.ts` ADR anchor names ADR-0113. **Scope.** Only the object field's own `visibleWhen` is read. A field group's `visibleWhen`, form-view field and section predicates, a hidden tab and static `hidden` are not, because the validator does not consume view metadata (#13252). **Which server answer is canonical.** For the record write contract, this rule. A flow screen's `required` field and the public form route judge their own surface's declarations before the engine sees the write, and keep their directions. A record either of them writes is then judged by this rule. ## Tests - `packages/objectql/src/engine-required-when-shown.test.ts` (new, 35 tests, real engine and in-memory driver): - (a) predicate false: an insert without the field is accepted; an edit of an unrelated field is accepted; the clear-on-hide `null` is accepted when the write moves the record out of the condition. - (b) predicate true: an insert without the field is refused and nothing is stored; with it, accepted. An update that reveals the field empty is refused and the row is untouched; the same reveal with the field filled is accepted. Clearing the field while shown is refused with the clear-out sentence. A row already shown and empty rests under an unrelated edit and an explicit `null`. A bulk update that reveals the field on one empty row refuses the whole batch and names `(record b2)`. - (c) a faulting predicate counts as shown: an insert without the field is refused as `required` (not the D2 `rule_violation`) and the fault is logged; with the field, accepted; an update keeps the old answers (a clear is refused, an unrelated edit of a null row rests). - (d) a role-gated predicate (`'org_admin' in current_user.positions`): the writer the field is shown to must fill it, the writer it is hidden from saves without it, and a system write with no acting user counts as shown, logged as `no-acting-user`. - (e) `validate()` (the dry run) accepts the hidden insert and refuses the shown empty one. Controls: plain `required` refuses as before, and only a field with both keys asks for the prior record. - (f) a predicate over a `formula` field (`record.risk_level == 'high'`, the formula computed from `amount`): an insert inside the condition without the field is refused; outside, accepted; an update that moves the computed value into the condition is refused and the row is untouched; `validate()` agrees; a bulk update judges each row on its own computed value and names `(record f2)`; a formula over an empty operand, and one with an undeclared key, are judged on the `null` a read serves (accepted, nothing logged); a formula calling `label()` counts as shown and is logged naming it. - (h) the seat's M2 disproof: `tier_name` reads `record.account.tier`, `risk` reads `tier_name`, the predicate reads `risk`: an insert inside the condition without the field is refused and logged naming the chain (it was accepted at `ab10c33f`); with the field, accepted. - (g) only a clean TRUE shows the field: an unset boolean under `visibleWhen: record.is_vip` hides it (insert accepted, nothing logged); TRUE shows it (insert refused). - (i) the review's S4 disproof: `is_admin: 'org_admin' in current_user.positions` (formula), `admin_note` required with `visibleWhen: record.is_admin`. An insert with no acting user and without the field is refused and logged `no-acting-user` naming `'is_admin'` (it was accepted silently at `84d2f737`); an org_admin writer without the field is refused; a non-admin writer saves without it, nothing logged; the same through a second formula (`needs_audit` over `is_admin`) is refused and logged naming the chain. - `ui/packages/core/src/evaluator/__tests__/fieldRules.test.ts`: the form side of (g), in a new describe: `null` and a clean non-boolean hide the field, TRUE shows it. - `packages/lint/src/validate-expressions.test.ts`: a new describe with 8 tests: 4 formula-read tests (the plain warning; the chain through a reference at depth 2; `label()`; nothing on a field that is not required), and (the reference-read warning; nothing for the same read on a field that is not required; nothing for a read of the record's own columns; the `storage.notNull` warning, with the parse still accepting it). The reads-only-declared-keys meta-test tables the new reads (`required`, `visibleWhen`, `storage.notNull`). - `ui/packages/app-shell/src/views/metadata-admin/inspectors/requiredVisibleWhenReference.test.ts` (new, 9 tests, real `analyzeRelationshipTraversals` and `parseCelToAst`): 5 for the reference advisory, 4 for the formula advisory (a computable formula; the chain through a reference; `label()` and `can`; nothing on a field that is not required). ## Acceptance notes - **Before and after, live (zh-CN console over `examples/app-crm`, a project package object `rws_customer`, field 验证用-备注字段 `required` with `visibleWhen: record.tier == 'vip'`).** Before is origin/main `c81f498b`, after is this branch. | Scenario | Before | After | | --- | --- | --- | | Change a VIP record to 普通 and save (the form sends `{"tier":"basic","vip_note":null}`) | 400 `验证用-备注字段是必填项,不能清空` | 200, saved | | Create a 普通 record without the field | 400 `验证用-备注字段不能为空` | 201, created | | Edit 负责人备注 on a 普通 record | 200 (the form sends only the changed field) | 200 | | Change a 普通 record to VIP without filling the field | API: 200, accepted | Form: the field appears with its marker and the client check `验证用-备注字段不能为空` stops the save; API PATCH `{"tier":"vip"}`: 400 `required` | | Change to VIP and fill the field in the same write (API) | not measured | 200 | The card's "edit an unrelated field" reading was measured on 18.5.0. On current main the edit form sends only changed fields, so that one save already passes before this PR; the clear-on-hide save and the create are the refusals that remained. - **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. ADR-0124 D4 allows a client hint stricter than the server, so they are listed in the amendment rather than changed. - Permissions are not resolved for a field `visibleWhen` that reads a `can` map beyond what the option gate already binds. ## Verification The latest fix round is on head `1ca9b694` (below, first section); the previous one on `e6f0dcb4`, the S4 round on `8248f9ff`. Everything else on head `2b709e12` unless named. ### Fix round: S6, S7 and N13 (delta contract review 6977080790) Head `1ca9b694`, one commit on `e6f0dcb4`. Text only: no predicate, verdict or call site moves, and the lint warning and the Studio advisory fire on exactly the same fields as before (option B, reword only). File list unchanged: the same 27 paths. No merge of `origin/main`: `overlap-check` says the branch merges cleanly. - **S6, the lint warning** (`required-visible-when-formula-issue.ts`). Plain formula read, old: "The server judges that requirement on the formula computed over the record being written (ADR-0113 D1); the form judges it on the formula value it last read, does not recompute it while the user edits, and has none on a create. So a create, or an edit that moves the formula into the condition, can be refused naming a field the form keeps hidden. Read the formula's own inputs in the predicate if the form should follow the edit." New: "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." Unservable arm, old: "so it stays required on every record, the ones the form hides it on included." New: "so it stays required on every record. The form cannot compute it either: it shows the field and keeps it required." The module doc, the push-site comment in `validate-expressions.ts`, and the test's title and pin (`does not recompute it` becomes `the formula value it computes over the record being written`) follow. - **S6, the Studio advisory** (`designer.field.requiredVisibleWhenFormula` and `...Unservable`, en and zh). The plain string now says the form computes the same formula as you edit, and that a wizard's final-submit check, or a form whose data source serves no object schema, judges the value it last read and can disagree with the server. The unservable string drops "including the ones this condition hides it on" and adds that the form cannot compute it either and shows the field, keeping it required. The module doc and function jsdoc of `requiredVisibleWhenReference.ts` and the comment in `ObjectFieldInspector.tsx` follow. - **S7, ADR-0113.** The recompute paragraph adds: "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." Both facts read at this head: `gateFinalSubmit(mergedData)` passes no plan to `resolveFieldRuleState`; `useObjectFormulaPlan` returns no plan when `getObjectSchema` is missing or its read rejects. Neither file is changed here. - **N13, ADR-0113.** The stricter-form sentence now names the third case: "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." `formulaRecord.ts` marks a formula with no served expression unservable; the server holds the expression. Evidence on `1ca9b694`: - `@objectstack/lint` typecheck (with `check:test-typecheck`) and full suite: 217 files, 9,248 tests passed, 5 skipped. The renamed pin alone, by title: 1 passed. - `@object-ui/i18n` type-check and full suite: 103 files, 1,947 passed, 13 skipped. `ui` `requiredVisibleWhenReference.test.ts`: 9 of 9 (no ui test pins the advisory text). - `pnpm check:i18n`: exit 0, 10 packages, all bundles in sync. `ui` `check:i18n-drift`: exit 0. - `node scripts/pm/dispatch-gates.mjs --commands`: 131 gates, the same set as before. 124 exit 0 on the first pass; 7 refused for missing `dist` (6 with exit 3, and `pnpm --dir ui exec vitest run scripts/` with exit 1 because `@objectstack/client` had no build). After a full `pnpm build` (120 of 120 tasks) all 7 exit 0. `--ran` with exit codes: 131 run, 0 NOT-MEASURED, 0 UNRUN (a derived zero). - No ablation: no tested behaviour moves; the changed pin passes. - Full dogfood battery on `1ca9b694` (`pnpm --filter @objectstack/dogfood test` under the verify lock, `VERDICT command-exit 0`): 483 files (480 passed, 3 skipped), 4,143 tests (4,075 passed, 68 skipped), no failures. ### Fix round: main merged twice, S5 and N11 (contract review 6970975755), and the form recompute Head `e6f0dcb4`. File list unchanged: the same 27 paths; nothing outside them edited. - **Merge 1, `c8d5313d` (main `961f4741`).** One conflict, `packages/objectql/src/engine-update.ts`, resolved as a union. Import block: main's `applyFormulaPlan`, `planFormulaProjection` and `storedExpressionsReading` kept beside this branch's `formulaValuesFor`. Bulk per-row rule call (around line 2137): main's summary-fold version kept (`header` / `related` locals, `overlayRow`, `overlay`, `summaryFold?.advance(i)`), with this branch's `formulaValues: bulkFormulaValues` added after `permissions: bulkPermissions`. The delta of `engine-update.ts` against main is again exactly this PR's four hunks (+11/-6). The merge driver deferred `content/docs/references/data/object.mdx`; `6c0fd9ee` regenerates it from the merged spec (`gen:schema && gen:docs`), restoring main's action `texts` row. - **Merge 2, `6c9ded43` (main `55020c33`, which contains #35116).** No conflicts. - **S5, `aefc8aa2` (prose and one log string, no logic change).** ADR-0137's note adds: "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." ADR-0113's parenthesis now reads "(`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`)". The server log reason is now "reads the acting user or a bare ctx/os root, and this write has no acting user (a system write)"; no test pins that string (the pins match the field, the formula names and `reason: 'no-acting-user'`). - **N11.** The `USER_SCOPE_ROOTS` docblock says bare-root reading is exact at the option-visibility call site and only conservative at the formula plan's (`formulaValuesFor` through `readsUserRoot`), where a formula reading only `os.org` is marked too. N12 stays open. - **The form recompute, `e6f0dcb4` (prose only).** As described under What changes. The ADR-0113 paragraph is this PR's own unlanded text, retitled and rewritten, and the fence paragraph's back-reference now says the warning was written for that limit, since closed. The describe change regenerated `field.mdx`, `object.mdx`, `migration.mdx` (one line each). - **Open question (not changed here).** The lint warning on every `required` field whose `visibleWhen` reads a formula, and the Studio formula advisory (en and zh), still give "the form does not recompute it" as their reason, and the lint test pins `does not recompute it`. With the form recomputing, the plain warning has no reason left; only the unservable arm (hop, `label()`, `can`) still names a real divergence. Changing what fires is behaviour, so it waits for the seat's word: narrow the warning and the advisory to the unservable arm (recommended), or reword them only. Evidence on `e6f0dcb4`: - `@objectstack/objectql` typecheck and full suite: 612 files, 13,835 tests passed. `@objectstack/spec` typecheck; full suite 853 files, 27,335 passed and 1 todo. - `@objectstack/spec` build, `gen:schema`, `gen:docs`, then `check:generated`: all 14 generated artifacts up to date. - `node scripts/pm/dispatch-gates.mjs --commands` on `e6f0dcb4`: 131 gates, the same set as on `aefc8aa2`. All 131 exit 0 (two first refused with exit 3, no `dist` for some packages; re-run after a full `pnpm build`, 120 of 120 tasks, both exit 0). `--ran`: 131 run, 0 NOT-MEASURED, 0 UNRUN. - Full dogfood battery: `pnpm --filter @objectstack/dogfood test` under the verify lock (`VERDICT command-exit 0`): 483 files (480 passed, 3 skipped), 4,143 tests (4,075 passed, 68 skipped). - `overlap-check` before each push: `origin/main` merges cleanly; #34935 conflicts in `packages/lint/src/validate-expressions.test.ts` (as before); #35165, #35128 and #34817 merge cleanly. - CI on `e6f0dcb4`: 70 check runs, 61 success, 9 skipped (the opt-in and placeholder runs), 0 failed; all eleven required contexts success. - Full build `pnpm build` (turbo): 119 of 119 tasks. - `@objectstack/objectql` full suite: 609 files, 13,699 tests passed. `src/engine-required-when-shown.test.ts`: 31 of 31. - `@objectstack/lint` full suite: 217 files, 9,195 tests passed. - `ui`: the `inspectors/` directory, 234 files, 3,099 passed and 1 skipped; `packages/core` `fieldRules.test.ts` 59 of 59; `tsc --noEmit` on app-shell exit 0; eslint on the changed ui files exit 0; `check:i18n-keys`, `check:i18n-drift`, `check:i18n-dead-keys`, `check:designer-field-key-parity` exit 0. - `@objectstack/spec`: `gen:schema` and `gen:docs` re-run; the regenerated `field.mdx`, `object.mdx`, `migration.mdx` are in the commit. - `node scripts/pm/dispatch-gates.mjs --commands` derived 130 gates on `2b709e12` (the same set as `ab10c33f`): all 130 exit 0. `dispatch-gates --ran`: 130 run, 0 NOT-MEASURED. - Full dogfood battery (`pnpm --filter @objectstack/dogfood test`, owed for the narrowing arm): 482 files (479 passed, 3 skipped), 4,140 tests (4,072 passed, 68 skipped), exit 0, on `2b709e12` under the verify lock. - Tier H: ADR-0113 and ADR-0137 are amended. Not readied, not queued, no auto-merge. ### Fix round for the seat's delta contract review (PASS at `84d2f737`, comment 6968679220): S4 and N8 Head `8248f9ff` (commits `7f14821c` test, `f7937161` fix, `6ae764eb` prose, `8248f9ff` regenerated references). File list unchanged: the same 27 paths. - **S4, confirmed and fixed.** The disproof test went first, at `7f14821c`, against the unchanged code: an insert into an object with `is_admin: 'org_admin' in current_user.positions` (a formula) and `admin_note` required with `visibleWhen: record.is_admin`, with no acting user and without `admin_note`, was **accepted** (`AssertionError: expected false to be true` in the refusal helper; 1 failed, 33 passed of 34). So the formula was computed as `null` on the system write, the field was judged hidden, and nothing was logged, where main refused the insert and ruling item 3 counts a system write as shown. - **The fix** is the mechanism the hop, `label()` and `can` marks use. `formulaValuesFor` now knows whether the write has an acting user (the same test `applyFormulaPlan` binds `current_user` by), and `unservableReason` marks a formula that reads the acting user (`readsUserRoot`, the option gate's AST reader over `current_user`, `user`, `ctx`, `os`) when the write has none, and carries the mark through the read closure as it carries a hop. The answer gains `noActingUser`, the formulas unservable for the missing user alone, and `evaluateRequiredWhenShown` logs such a fault with `reason: 'no-acting-user'`, the reason the direct spelling logs; the message names the chain (`reads the formula field 'needs_audit', which reads the formula 'is_admin', which reads the acting user, and this write has none (a system write)`). With an acting user nothing changes: the formula is computed for the writer. - **Pins** (group (i), 4 tests): the system-write insert is refused as `required`, nothing stored, logged `no-acting-user` naming `'is_admin'`; an org_admin writer without the field is refused; a non-admin writer saves without it, nothing logged; the same through a second formula is refused and logged naming both formulas. - **Ablations** (`node scripts/ablation-replace.mjs`, on the committed tree; the test imports the engine from `src/`, so no build sits between the mutation and the run): the new mark disabled (`if (false && !actingUser && readsUserRoot(...))`): anchor 1 → 0, 2 of 35 red (both system-write pins); the log flag forced off (`noActingUser: false`): anchor 1 → 0, 2 of 35 red (the `reason` assertion of both). Each restore matched the HEAD blob with an empty `git diff HEAD`. - **Prose (S4 and N8).** Where the unservable set is listed, it now names the acting-user mark and says a `can` formula is computed on a write that picks a permission-gated option: the ADR-0113 amendment (scope paragraph and the formula paragraph, which also says the lint does not warn on the acting-user mark), the ADR-0137 note, the `visibleWhen` describe (and the three regenerated references), the `formulaValues` and `evaluateRequiredWhenShown` jsdoc, the changeset, the lint message (a sentence added when a blocked formula calls `can`) and its module doc, the Studio helper's doc and both Studio strings (en and zh). The lint and the Studio advisory gain no new detection: a formula reading the acting user is computed per writer on every write that has one. - N9 and N10 stay open, as the review accepts. N4 to N6 stay open. Evidence on `8248f9ff`: - `src/engine-required-when-shown.test.ts`: 35 of 35. `@objectstack/objectql` typecheck and full suite: 612 files, 13,764 tests passed. `@objectstack/lint` typecheck and full suite: 218 files, 9,246 tests passed. ui `requiredVisibleWhenReference.test.ts` 9 of 9; `check:i18n-keys`, `check:i18n-drift`, `check:i18n-dead-keys`, `check:designer-field-key-parity` exit 0. - `@objectstack/spec` build, then `check:generated`: `check:docs` stale for the describe; `gen:docs` regenerated `field.mdx`, `object.mdx`, `migration.mdx` (the describe line only); re-run: all 14 artifacts up to date. - `node scripts/pm/dispatch-gates.mjs --commands` derived 130 gates; all 130 exit 0 (three first refused with exit 3, prerequisite not met, before a full build; re-run after `pnpm build` 120 of 120: exit 0). `--ran` with exit codes: 130 run, 0 NOT-MEASURED, a derived zero. - Full dogfood battery, `pnpm --filter @objectstack/dogfood test` under the verify lock: 482 files (479 passed, 3 skipped), 4,140 tests (4,072 passed, 68 skipped), exit 0. - CI on `8248f9ff`: 70 check runs, 61 success, 9 skipped, 0 failed. - `overlap-check`: `origin/main` merges cleanly; conflicts with #34935 (`validate-expressions.test.ts`) and #34709 (`engine-update.ts`) as the claim records, whichever lands second merges main. ### Ablations, third round (on `2b709e12`) Each run used `node scripts/ablation-replace.mjs` on the committed tree; each mutation landed (anchor 1 → 0) and each restore matched the file's HEAD blob, with an empty `git status` after the run. Logs in the project files (`objectstack-seat3/34905-live/ablations3/`). | Arm removed | Mutation | Red | | --- | --- | --- | | (i) closure propagation | `unservableReason` never follows a formula's reads | 1 of 31: (h) the chain | | (j) hop mark | a formula with `hops` is not marked | 1 of 31: (h) the chain | | (k) `label()` mark | a formula calling `label()` is not marked | 1 of 31: (f) `label()` | | (l) validator check | the predicate ignores `unservable` | 2 of 31: (h) the chain, (f) `label()` | | (m) computed record | the predicate is judged on the raw record | 4 of 31: the (f) values, and the empty-operand case | | (n) lint wiring | the formula warning is not pushed | 3 of 8 lint ADR-0113 tests | | (o) lint hop mark | a formula reading through a reference is not marked | 1 of 8 | | (p) Studio mark | the advisory's `unservable` ignores hop, `label()` and `can` | 1 of 9 | ### Ablations, second round (on `d5310535`) Each run used `node scripts/ablation-replace.mjs` and then `vitest run src/engine-required-when-shown.test.ts` (26 tests). Each mutation landed (anchor 1 → 0), and each restore matched the file's HEAD blob (`rule-validator.ts` `39e928a0`, `engine-insert.ts` `a201a50c`) with an empty `git diff HEAD`. | Arm removed | Mutation | Red | | --- | --- | --- | | (a) hidden waiver | `if (now.verdict === 'hidden') continue;` deleted | 9 of 26 | | (b) reveal compliance | the prior-record check always rests | 4 of 26 | | (c) fault arm | a fault treated as hidden | 4 of 26 | | (d) deferral | `engine-insert.ts` passes `'enforced'` instead of `'deferred'` | 8 of 26 | | (e) prior read | `requiredWhenShown(f)` dropped from `fieldsNeedPrior` | 15 of 26 | | (f) formula values | `formulaReadsOf` answers no formula read, so the predicate compares the absent formula as `null` (the L2 M1 defect) | 4 of 26: every (f) case | | (g) clean TRUE | the verdict back to "anything but FALSE is shown" | 1 of 26: (g) the unset boolean | | (h) engine wiring | the insert call site stops passing `formulaValues` | 2 of 26: (f) the insert outside the condition, and the update case, whose setup inserts a row outside it | Round 1 (on `81b671f3`, 19 tests) had (a) 5, (b) 3, (c) 3, (d) 4, (e) 10. The first try at (b) in round 1 used the bare replacement `continue;`, which the tool refused before running because that text already appears 44 times in the file. ### Fix round for the seat's L2 (FAIL at `81b671f3`) - **M1, confirmed and fixed.** The disproof test (an insert inside a formula-driven condition without the field) was accepted at `81b671f3`. It now refuses, and the predicate reads computed formula values, as described under What changes. - **S1, aligned to the form as the seat ruled.** Only a clean TRUE shows the field. This is stated in the ADR-0113 rule, the ADR-0137 note, both `FieldSchema` describes, the jsdoc and the changeset, and pinned on both sides. - **Nits taken:** N1 (the lint refuses `current_user` in a field `visibleWhen`, stated in the ADR scope paragraph and the jsdoc), N2 (the seed loader's early warning is listed among the readers left as they are), N3 (the refusal-order change is stated in the ADR and the changeset). N4 to N6 stay open. ### Fix round for the seat's delta L2 (FAIL at `ab10c33f`, comment 6963978999; rulings relayed 23:24Z) - **M2, confirmed and fixed.** The seat's disproof test ((h): a formula over a formula that reads through a reference) was accepted at `ab10c33f`. Fixed by the read closure, as the seat directed, not by the any-faulted-formula shortcut: `formulaValuesFor` marks every formula whose read value the write path cannot know, walking the plan in read order, and a predicate reading one counts as shown. - **S2, the ruling-consistent pair.** (a) A fault a read shares is judged on the `null` a read serves; the PR's own fixture with `amount` empty is now accepted without the field, as the form hides it. (b) A hop, `label()` or `can` with no map keeps counted-as-shown, with the new lint warning and Studio advisory beside the reference-read one. Both arms are in the ADR-0113 amendment, the ADR-0137 note and row, and the changeset. - **S3.** The prose is corrected in the amendment (a new "Known limit" paragraph, and the "the way the form shows it" sentence), the `visibleWhen` describe and TSDoc, the `formulaValues` and `evaluateRequiredWhenShown` jsdoc, and the changeset, which lists the edit regression as a known limit. The lint warning fires on every `required` field whose `visibleWhen` reads a formula. - **N7 folded.** One closure per bulk batch, predicate reads memoised per source, formulas computed once per record per write. - N4 to N6 stay open, as accepted. --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzfrHprnpf55xZtXBbx)_ <!-- signed: repo:objectstack#1 · os-warren · session_01JQwxbXGvw43spR79ztEvWt --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 084156d commit 0739dee

27 files changed

Lines changed: 2066 additions & 52 deletions
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
---
2+
'@objectstack/objectql': minor
3+
'@objectstack/lint': minor
4+
'@objectstack/spec': minor
5+
'@object-ui/app-shell': minor
6+
'@object-ui/i18n': minor
7+
---
8+
9+
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
10+
11+
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.
12+
Metadata-protocol: semantic
13+
14+
<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed or renamed, and nothing stored is rewritten: what moved is when the engine enforces required on a field that also declares visibleWhen. The one-line fix for a refused write is in the body: fill the field in the same write that moves the record into the condition. -->
15+
16+
**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.
17+
18+
**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:
19+
20+
- 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;
21+
- 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;
22+
- 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.
23+
24+
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.
25+
26+
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.
27+
28+
**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.
29+
30+
**`@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).
31+
32+
**`@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.
33+
34+
**`@objectstack/spec`.** The `required` and `visibleWhen` descriptions on `FieldSchema` say how the two combine.

‎content/docs/deployment/validating-metadata.mdx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -959,7 +959,10 @@ What the failure does depends on what the predicate guards:
959959

960960
At **submit** a broken field rule is refused, not passed. A field `visibleWhen` that
961961
cannot be evaluated refuses the submit on the client, with a message naming the field
962-
and the rule, because no server evaluates a field's `visibleWhen`. A broken
962+
and the rule. The server reads a field's `visibleWhen` only when the field is also
963+
`required`, to decide whether the requirement applies to the write: hidden means not
964+
required, and a `visibleWhen` it cannot evaluate counts as shown, so the field stays
965+
required and the server logs the fault. A broken
963966
`requiredWhen` or `readonlyWhen`, or an option's `visibleWhen`, is refused by the
964967
server, and the form shows that refusal beside the input. One exception: a
965968
`readonlyWhen` that reads a name the write does not bind (a bare field name, or

‎content/docs/references/data/field.mdx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ const result = CurrencyConfigSchema.parse(data);
5555
| **type** | `Enum<'text' \| 'textarea' \| 'email' \| 'url' \| 'phone' \| 'password' \| 'secret' \| 'markdown' \| 'html' \| 'richtext' \| 'number' \| 'currency' \| 'percent' \| 'date' \| … +35 more>` | ✅ | Field Data Type |
5656
| **description** | `string` | optional | Tooltip/Help text |
5757
| **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`. |
58-
| **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. |
58+
| **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. |
5959
| **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. |
6060
| **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). |
6161
| **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);
106106
| **dimensions** | `integer` | optional | Vector dimensionality (e.g., 1536 for OpenAI embeddings) |
107107
| **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. |
108108
| **group** | `string` | optional | Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system") |
109-
| **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'` |
109+
| **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. |
110110
| **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. |
111111
| **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. |
112112
| **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. |

0 commit comments

Comments
 (0)