From 662d0c6ec6cc8c406f89140719f49ca10723b092 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 18:31:23 +0000 Subject: [PATCH 01/17] fix(objectql): a required field hidden by its own visibleWhen is required only when shown The engine judged `required` without the field's own `visibleWhen`, so one admin setting locked every record outside the condition. The rule validator now judges such a field from its visibility on the write: cleanly hidden waives it, shown applies the non-regression invariant against the prior record (a reveal without filling is refused), and a fault counts as shown, logged. Claude-Session: https://claude.ai/code/session_01WGufzfrHprnpf55xZtXBbx Co-authored-by: Claude --- packages/objectql/src/engine-insert.ts | 4 +- .../src/engine-required-when-shown.test.ts | 346 ++++++++++++++++++ packages/objectql/src/engine-update.ts | 7 +- packages/objectql/src/engine-validate.ts | 2 +- .../src/validation/record-validator.ts | 46 ++- .../objectql/src/validation/rule-validator.ts | 149 +++++++- 6 files changed, 544 insertions(+), 10 deletions(-) create mode 100644 packages/objectql/src/engine-required-when-shown.test.ts diff --git a/packages/objectql/src/engine-insert.ts b/packages/objectql/src/engine-insert.ts index a682a250645..4b973839d46 100644 --- a/packages/objectql/src/engine-insert.ts +++ b/packages/objectql/src/engine-insert.ts @@ -1345,7 +1345,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. 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..2804b28243c --- /dev/null +++ b/packages/objectql/src/engine-required-when-shown.test.ts @@ -0,0 +1,346 @@ +// 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). + +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_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); + }); + }); +}); diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index 28044fb359b..e943ba01570 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 { recordHookPayloadWrites } from './hook-write-provenance.js'; import { dispatchHooksExplainingWithheldReadonly } from './hook-withheld-readonly-fault.js'; @@ -1161,7 +1161,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 diff --git a/packages/objectql/src/engine-validate.ts b/packages/objectql/src/engine-validate.ts index 25fd9f73b01..e202e7cd0f9 100644 --- a/packages/objectql/src/engine-validate.ts +++ b/packages/objectql/src/engine-validate.ts @@ -565,7 +565,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 diff --git a/packages/objectql/src/validation/record-validator.ts b/packages/objectql/src/validation/record-validator.ts index 9bdee3661a9..118368962e1 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; @@ -2235,6 +2241,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 @@ -2320,6 +2351,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; @@ -2339,7 +2376,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 { @@ -2362,7 +2400,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 311d8a0f165..d64d49b91f6 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, @@ -1638,8 +1639,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; } @@ -2932,6 +2935,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 @@ -2970,8 +2982,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)), ); } @@ -3447,6 +3463,125 @@ 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'; + +/** + * [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 is cleanly FALSE on the merged record: the + * requirement is waived for this write. 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): 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). + * + * 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. So a + * role-gated field is judged per writer. `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 } } => { + const res = ExpressionEngine.evaluate(toExpression(pred), { + ...ruleScope(record, prior, extra), + user, + permissions: opts.permissions, + }); + if (!res.ok) return { verdict: 'fault', error: res.error }; + return { verdict: res.value === false ? 'hidden' : 'shown' }; + }; + 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 noActingUser = user === undefined && readsUserRoot(pred); + opts.logger?.warn?.( + `visibleWhen of required field '${name}' could not be evaluated ` + + `(${noActingUser ? 'no acting user to bind current_user (system write)' : `${now.error!.kind}: ${String(now.error!.message).split(' +')[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. * @@ -3579,6 +3714,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 From 6d76caf2b84555a59e35dc97d8ae475aba0d7f33 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 18:35:59 +0000 Subject: [PATCH 02/17] feat(lint,app-shell): warn when a required field's visibleWhen cannot lift the requirement; amend ADR-0113, ADR-0137, ui ADR-0036 Lint warns on a required field's visibleWhen that reads through a reference, and on required + visibleWhen + storage.notNull; Studio shows the reference warning under the Visible-when editor. The records say required + visibleWhen means required when shown, and name which server answer is canonical. Claude-Session: https://claude.ai/code/session_01WGufzfrHprnpf55xZtXBbx Co-authored-by: Claude --- .changeset/34905-required-when-shown.md | 30 ++++ .../docs/deployment/validating-metadata.mdx | 5 +- ...red-write-contract-vs-column-constraint.md | 91 ++++++++++++ ...-predicate-fault-semantics-are-contract.md | 18 ++- .../lint/src/validate-expressions.test.ts | 63 ++++++++ packages/lint/src/validate-expressions.ts | 57 +++++++- packages/spec/src/data/field.zod.ts | 8 +- ...l__src__validation__rule-validator.ts.json | 3 +- ui/docs/adr/0036-field-conditional-rules.md | 18 ++- .../inspectors/ObjectFieldInspector.tsx | 23 +++ .../requiredVisibleWhenReference.test.ts | 53 +++++++ .../requiredVisibleWhenReference.ts | 135 ++++++++++++++++++ ui/packages/i18n/src/namespaces/studio/en.ts | 2 + ui/packages/i18n/src/namespaces/studio/zh.ts | 2 + 14 files changed, 495 insertions(+), 13 deletions(-) create mode 100644 .changeset/34905-required-when-shown.md create mode 100644 ui/packages/app-shell/src/views/metadata-admin/inspectors/requiredVisibleWhenReference.test.ts create mode 100644 ui/packages/app-shell/src/views/metadata-admin/inspectors/requiredVisibleWhenReference.ts diff --git a/.changeset/34905-required-when-shown.md b/.changeset/34905-required-when-shown.md new file mode 100644 index 00000000000..6f9155012e2 --- /dev/null +++ b/.changeset/34905-required-when-shown.md @@ -0,0 +1,30 @@ +--- +'@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 is cleanly false on the record (the stored row with the write over it): 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. Only the field's own `visibleWhen` is read: a field group's `visibleWhen` and form-view predicates are not. + +**`@objectstack/lint`.** Two 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), 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 warning 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 8d45ee2ec62..884b136a09a 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -958,7 +958,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/docs/adr/0113-required-write-contract-vs-column-constraint.md b/docs/adr/0113-required-write-contract-vs-column-constraint.md index e5f1121c657..b8e3c269b30 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,80 @@ 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 the way the form shows it. + +**The rule.** For a field with `required: true` and its own `visibleWhen` +(`evaluateRequiredWhenShown`, `packages/objectql/src/validation/rule-validator.ts`): + +1. **Hidden** — the predicate is cleanly FALSE on the merged record (stored row + with the write over it): the requirement does not apply to this write. *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: 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. `features`, `app` and `page` are never bound on the server. + +**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 two +**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), 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. +ADR-0124 D4 allows a client hint stricter than the server, so they are listed +here rather than changed. diff --git a/docs/adr/0137-predicate-fault-semantics-are-contract.md b/docs/adr/0137-predicate-fault-semantics-are-contract.md index b4edf0ee4c0..180e379ecb2 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,22 @@ 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. +> +> | slot, at submit | on a fault | +> |---|---| +> | `requiredWhen`, `readonlyWhen`, an option's `visibleWhen` | refused (D2) | +> | a `required` field's own `visibleWhen` | 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/validate-expressions.test.ts b/packages/lint/src/validate-expressions.test.ts index 726254e0e4c..f252606a17f 100644 --- a/packages/lint/src/validate-expressions.test.ts +++ b/packages/lint/src/validate-expressions.test.ts @@ -6819,3 +6819,66 @@ 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`'); + }); +}); diff --git a/packages/lint/src/validate-expressions.ts b/packages/lint/src/validate-expressions.ts index 630a4a1f1ed..b232cd26f2d 100644 --- a/packages/lint/src/validate-expressions.ts +++ b/packages/lint/src/validate-expressions.ts @@ -1294,9 +1294,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 +1633,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 +1660,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 +3025,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 +3043,7 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression where, message: fieldTraversalMessage(slot, root, field, fieldType, [...related].sort(), owner), source, - severity: 'error', + severity, }); } } @@ -4329,6 +4342,40 @@ 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', + }); + } + } judgeFieldFormula(fname, f, { objectName, optionFields: optionFieldNames, fieldDefs }); } // [#33100] A formula that reads its own value, itself or through the diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index e5f27868ab7..1d235be4780 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,12 @@ 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. */ - 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 FALSE 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; a read THROUGH a reference field 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..8df118bd681 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 { 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,15 @@ 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); // 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 +1942,19 @@ export function ObjectFieldInspector({ slot="visibleWhen" t={tr} /> + {visibleWhenReferenceReads.length > 0 && ( +

+ + + {tFormat('designer.field.requiredVisibleWhenReference', locale, { + fields: visibleWhenReferenceReads.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(); + }); +}); 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..3b62fb96e79 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/requiredVisibleWhenReference.ts @@ -0,0 +1,135 @@ +// 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. + * + * ## 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; +} + +/* ── The lazily loaded traversal reader ───────────────────────────────── */ + +type Analyze = (source: string, root: string) => { traversals: ReadonlyMap } | null; + +let analyzeCached: 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; +} + +/** + * 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/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 2afd064015b..f4ac3ea48cf 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -580,6 +580,8 @@ 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.', // 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 bc84bdf4c31..d5f7b045332 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -497,6 +497,8 @@ const STUDIO_ZH: Record = { 'designer.field.requiredWhen': '必填条件', 'designer.field.conditionalRulesHint': '表达式为真时字段相应地变为可见 / 只读 / 必填。用 record.<字段> 引用当前记录,previous.<字段> 引用最近保存的值,parent.<字段>(主从明细行)引用表头记录。', + 'designer.field.requiredVisibleWhenReference': + '该字段为必填,服务器每次保存时按这条可见条件判断是否必填。条件经由引用字段 {fields} 读取关联记录,服务器在这里无法读取,因此按「显示」处理:所有记录(包括此条件隐藏该字段的记录)都仍要求填写。请改为读取本对象自己的字段。', // Bulk multi-select (Tier 2) 'designer.canvas.bulkSelected': '已选 {n} 项', 'designer.canvas.bulkMoveTo': '移至分组', From 55509ef57f0cb104d49c60756dd9461416145a4c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 19:14:51 +0000 Subject: [PATCH 03/17] fix(objectql,lint): escape the fault log's line split; table the new field reads; regenerate field references The counts-as-shown warning split the fault message on a literal newline that had been written raw into the source, which broke the objectql build. The lint meta-test now tables the reads the required-when-shown checks take (`required`, `visibleWhen`, `storage.notNull`), and the generated field references carry the amended `required` and `visibleWhen` descriptions. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfrHprnpf55xZtXBbx --- content/docs/references/data/field.mdx | 4 ++-- content/docs/references/data/object.mdx | 8 ++++---- content/docs/references/system/migration.mdx | 8 ++++---- packages/lint/src/validate-expressions.test.ts | 17 ++++++++++++++++- .../objectql/src/validation/rule-validator.ts | 3 +-- 5 files changed, 27 insertions(+), 13 deletions(-) diff --git a/content/docs/references/data/field.mdx b/content/docs/references/data/field.mdx index 612a0af3b69..ec89913a9c3 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 FALSE 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; a read THROUGH a reference field 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 d5640b9fcf6..d6791458cba 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 FALSE 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; a read THROUGH a reference field 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. | @@ -610,7 +610,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. | @@ -661,7 +661,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 FALSE 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; a read THROUGH a reference field 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 102c9953f41..22b2c835f60 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 FALSE 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; a read THROUGH a reference field 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 FALSE 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; a read THROUGH a reference field 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/packages/lint/src/validate-expressions.test.ts b/packages/lint/src/validate-expressions.test.ts index f252606a17f..ee5422ca295 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([]); diff --git a/packages/objectql/src/validation/rule-validator.ts b/packages/objectql/src/validation/rule-validator.ts index d64d49b91f6..ce3de6103a6 100644 --- a/packages/objectql/src/validation/rule-validator.ts +++ b/packages/objectql/src/validation/rule-validator.ts @@ -3542,8 +3542,7 @@ function evaluateRequiredWhenShown( const noActingUser = user === undefined && readsUserRoot(pred); opts.logger?.warn?.( `visibleWhen of required field '${name}' could not be evaluated ` - + `(${noActingUser ? 'no acting user to bind current_user (system write)' : `${now.error!.kind}: ${String(now.error!.message).split(' -')[0]}`})` + + `(${noActingUser ? '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 }, ); From 81b671f31154b4c4c03f4cc19d7f2524cca7e4a4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 20:07:21 +0000 Subject: [PATCH 04/17] docs(adr): ADR-0020's write-path anchor names the file, not the validateRecord call it no longer holds The update path now calls validateRecordInScope, so the symbol anchor on validateRecord no longer resolves; the sentence describes the write path as it was when the record was written. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfrHprnpf55xZtXBbx --- docs/adr/0020-state-machine-converge-and-enforce.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From d5310535ec9d0b3ab327df8cf1f7222c61f5bebb Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:49:31 +0000 Subject: [PATCH 05/17] fix(objectql): judge a required field's visibleWhen on computed formula values, and only a clean TRUE shows it A formula field is computed on read and never on the write path, so a visibleWhen reading one compared null and waived the requirement on every write. The engine now computes the object's formulas over the merged and the prior record with the read path's plan before it evaluates the predicate; a formula that cannot be computed there makes the predicate a fault, which counts as shown. A clean verdict that is not TRUE (FALSE, or null such as an unset boolean) now hides the field, as the form reads it and as requiredWhen holds its condition. ADR-0113, ADR-0137, the FieldSchema describes and the changeset state both, and the refusal-order change and the seed loader's early warning are recorded. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfrHprnpf55xZtXBbx --- .changeset/34905-required-when-shown.md | 6 +- ...red-write-contract-vs-column-constraint.md | 35 +++++++-- ...-predicate-fault-semantics-are-contract.md | 5 +- packages/objectql/src/engine-insert.ts | 4 +- .../src/engine-required-when-shown.test.ts | 78 +++++++++++++++++++ packages/objectql/src/engine-top-level.ts | 38 ++++++++- packages/objectql/src/engine-update.ts | 8 +- packages/objectql/src/engine-validate.ts | 2 + .../objectql/src/validation/rule-validator.ts | 70 +++++++++++++++-- packages/spec/src/data/field.zod.ts | 5 +- .../evaluator/__tests__/fieldRules.test.ts | 16 ++++ 11 files changed, 242 insertions(+), 25 deletions(-) diff --git a/.changeset/34905-required-when-shown.md b/.changeset/34905-required-when-shown.md index 6f9155012e2..1964e3372be 100644 --- a/.changeset/34905-required-when-shown.md +++ b/.changeset/34905-required-when-shown.md @@ -17,11 +17,13 @@ Metadata-protocol: semantic **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 is cleanly false on the record (the stored row with the write over it): 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 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. Only the field's own `visibleWhen` is read: a field group's `visibleWhen` and form-view predicates are not. +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 computes it; a formula that cannot be computed there counts as shown. 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. **`@objectstack/lint`.** Two 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), and `storage.notNull: true` beside the pair (the column still refuses the null on a record outside the condition). 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 b8e3c269b30..a056184e7b6 100644 --- a/docs/adr/0113-required-write-contract-vs-column-constraint.md +++ b/docs/adr/0113-required-write-contract-vs-column-constraint.md @@ -277,8 +277,11 @@ D1), so it now judges the requirement the way the form shows it. **The rule.** For a field with `required: true` and its own `visibleWhen` (`evaluateRequiredWhenShown`, `packages/objectql/src/validation/rule-validator.ts`): -1. **Hidden** — the predicate is cleanly FALSE on the merged record (stored row - with the write over it): the requirement does not apply to this write. *Widening.* +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 @@ -287,7 +290,8 @@ D1), so it now judges the requirement the way the form shows it. 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: it **counts as shown**, and the +3. **Fault** — the predicate cannot be evaluated (including a `formula` field it + reads that cannot be computed on the record): 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 @@ -299,7 +303,17 @@ D1), so it now judges the requirement the way the form shows it. 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. `features`, `app` and `page` are never bound on the server. +arm. 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 the form shows. A formula that cannot be computed there +(it faults, reads through a reference, or calls `label()`) makes the predicate a +fault, which counts as shown. **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 @@ -333,5 +347,14 @@ 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. -ADR-0124 D4 allows a client hint stricter than the server, so they are listed -here rather than changed. +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 180e379ecb2..8dc6f00f379 100644 --- a/docs/adr/0137-predicate-fault-semantics-are-contract.md +++ b/docs/adr/0137-predicate-fault-semantics-are-contract.md @@ -156,11 +156,14 @@ makes "blank" a declared **third** state rather than a spelling of "no rule". > 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 that cannot be computed on the record is +> such a fault. 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` | counted as shown: required, logged (D4) | +> | a `required` field's own `visibleWhen` (a formula it reads included) | counted as shown: required, logged (D4) | ### D3 — At RENDER, visibility stays fail-OPEN diff --git a/packages/objectql/src/engine-insert.ts b/packages/objectql/src/engine-insert.ts index 4b973839d46..a201a50ccd1 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, @@ -1362,7 +1362,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 index 2804b28243c..b8a05497611 100644 --- a/packages/objectql/src/engine-required-when-shown.test.ts +++ b/packages/objectql/src/engine-required-when-shown.test.ts @@ -185,6 +185,33 @@ describe('ADR-0113 D1 (amended) — `required` + `visibleWhen` is required when 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_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: { @@ -343,4 +370,55 @@ describe('ADR-0113 D1 (amended) — `required` + `visibleWhen` is required when 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 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 that cannot be computed counts as shown, and the fault is logged', async () => { + const err = await refusalOf(() => engine.insert('rws_formula_fault', { amount: 50 }, ADMIN)); + expectRequired(err, 'review_note'); + 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_level/); + expect(warn?.meta).toMatchObject({ field: 'review_note', reason: 'predicate-fault' }); + }); + }); + + // ── (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 dac2d18b839..3258f0ac5ee 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -3048,6 +3048,42 @@ 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 value the + * form shows. The SAME plan and evaluation a read uses, over a copy of the + * record; the plan is built on the first call, so a write whose predicates + * read no formula pays nothing. No hop is resolved and no option label is + * read here, so a formula that needs either faults, and the predicate counts + * as shown. `undefined` when the object declares no formula. + */ +function formulaValuesFor( + schema: any, + execCtx: ExecutionContext | undefined, + permissions: EvalPermissions | undefined, +): ((record: Record) => { record: Record; faulted: 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; + let plan: FormulaPlanEntry[] | null | undefined; + return (record) => { + if (plan === undefined) { + try { + plan = planFormulaProjection(schema, undefined).plan; + } catch { + plan = null; + } + } + if (plan === null) return { record, faulted: new Set(formulaNames) }; + const copy: Record = { ...record }; + const faulted = new Set(); + applyFormulaPlan(plan, [copy], execCtx, permissions, (name) => { faulted.add(name); }); + return { record: copy, faulted }; + }; +} + /** * [#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 @@ -5235,7 +5271,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 e943ba01570..ac660b98b9a 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -66,7 +66,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, applyStoredExpressionsToPatch, - computeStoredExpressions, declaredDatetimeLowering, foldEngineOptionAliases, hydrateWriteFormulas, + computeStoredExpressions, declaredDatetimeLowering, foldEngineOptionAliases, formulaValuesFor, hydrateWriteFormulas, lowerWhereFilterArray, masterIdOf, planStoredExpressions, rejectUnknownEngineOptions, replacedStoredExpressionFields, settleBulkStoredExpressions, shouldSkipStateMachine, staticReadonlyStoredView, stripComputedWriteFields, undeclaredWriteFieldErrors, updateStaticReadonlySubject, writeFailureLogMeta, @@ -1626,7 +1626,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 @@ -2078,7 +2078,7 @@ export class UpdateFacet { if (rulesNeedRows) { for (const row of priorRows ?? []) { try { - 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: parentForRow?.(row), previousParent: previousParentForRow?.(row), related: bulkRelatedForRow?.({ ...(row ?? {}), ...bulkPatch }), 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: parentForRow?.(row), previousParent: previousParentForRow?.(row), related: bulkRelatedForRow?.({ ...(row ?? {}), ...bulkPatch }), permissions: bulkPermissions, formulaValues: formulaValuesFor(updateSchema, opCtx.context, bulkPermissions) }), this.logger, object); } catch (err) { if (err instanceof ValidationError && row?.id != null) { throw new ValidationError(err.fields.map((f) => ({ ...f, message: `${f.message} (record ${String(row.id)})` }))); @@ -2094,7 +2094,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: formulaValuesFor(updateSchema, opCtx.context, bulkPermissions) }), 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 e202e7cd0f9..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'; @@ -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/rule-validator.ts b/packages/objectql/src/validation/rule-validator.ts index ce3de6103a6..39e928a0c46 100644 --- a/packages/objectql/src/validation/rule-validator.ts +++ b/packages/objectql/src/validation/rule-validator.ts @@ -433,6 +433,16 @@ 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 the form sees. + * `faulted` names each formula that could not be computed on that record. + * Absent: a predicate that reads a formula field cannot be evaluated, and + * counts as shown. + */ + formulaValues?: (record: Record) => { record: Record; faulted: ReadonlySet }; /** * [#4977] The master-detail header this write's field `requiredWhen` * predicates read as `parent` — the SAME binding, resolved by the SAME engine @@ -3466,15 +3476,37 @@ export function nullPreviousReadDetail( /** The three answers a required field's own `visibleWhen` can give a write. */ type ShownVerdict = 'shown' | 'hidden' | 'fault'; +/** + * 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; + const reads = new Set(); + for (const root of ['record', 'previous']) { + const analysis = analyzeRelationshipTraversals(expr.source, root); + if (!analysis) return formulaFields; + for (const name of analysis.bareFields) reads.add(name); + for (const name of analysis.traversals.keys()) reads.add(name); + } + return formulaFields.filter((name) => reads.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 is cleanly FALSE on the merged record: the - * requirement is waived for this write. A record outside the condition can be - * created and edited, and the form's clear-on-hide `null` is accepted. + * - **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 @@ -3484,7 +3516,8 @@ type ShownVerdict = 'shown' | 'hidden' | 'fault'; * (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): it COUNTS AS SHOWN, and + * no acting user under a `current_user` predicate, a `formula` field that + * cannot be computed on the record): 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): @@ -3495,8 +3528,12 @@ type ShownVerdict = 'shown' | 'hidden' | 'fault'; * 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. So a - * role-gated field is judged per writer. `features`, `app` and `page` are never + * 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. So 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 @@ -3525,13 +3562,32 @@ function evaluateRequiredWhenShown( prior: PreviousBinding, extra: Record | undefined, ): { verdict: ShownVerdict; error?: { kind: string; message: string } } => { + // A `formula` field is not on the write path: judge the predicate on the + // computed value, and count a formula that cannot be computed as a fault. + 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 then = prior ? opts.formulaValues(prior) : undefined; + const faulted = formulas.filter((f) => now.faulted.has(f) || (then?.faulted.has(f) ?? false)); + if (faulted.length > 0) { + return { verdict: 'fault', error: { kind: 'formula', message: `reads the formula field ${faulted.map((f) => `'${f}'`).join(', ')}, which could not be computed on this record` } }; + } + record = now.record; + prior = then ? then.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 }; - return { verdict: res.value === false ? 'hidden' : 'shown' }; + // 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; diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index 1d235be4780..bd53a126054 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -2518,9 +2518,10 @@ export const FieldSchema = lazySchema(() => { * * `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. + * required only on a write whose record the predicate shows: a clean TRUE, + * as the form reads it, with `formula` fields computed first. */ - 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 FALSE 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; a read THROUGH a reference field cannot be evaluated there."), + 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 as a read computes them; a read THROUGH a reference field 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/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); + }); +}); From ab10c33f3a54c080936af8aae47258a7144e49b0 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:04:15 +0000 Subject: [PATCH 06/17] docs(spec): regenerate the field references for the amended visibleWhen describe Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfrHprnpf55xZtXBbx --- content/docs/references/data/field.mdx | 2 +- content/docs/references/data/object.mdx | 4 ++-- content/docs/references/system/migration.mdx | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/content/docs/references/data/field.mdx b/content/docs/references/data/field.mdx index ec89913a9c3..2dfbae84aa1 100644 --- a/content/docs/references/data/field.mdx +++ b/content/docs/references/data/field.mdx @@ -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'`. On a `required` field the server reads it on every write: where it is FALSE 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; a read THROUGH a reference field cannot be evaluated there. | +| **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 as a read computes them; a read THROUGH a reference field 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 d6791458cba..248c5852963 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -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'`. On a `required` field the server reads it on every write: where it is FALSE 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; a read THROUGH a reference field cannot be evaluated there. | +| **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 as a read computes them; a read THROUGH a reference field 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. | @@ -661,7 +661,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'`. On a `required` field the server reads it on every write: where it is FALSE 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; a read THROUGH a reference field cannot be evaluated there. | +| **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 as a read computes them; a read THROUGH a reference field 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 22b2c835f60..7a02d6217e0 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -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'`. On a `required` field the server reads it on every write: where it is FALSE 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; a read THROUGH a reference field cannot be evaluated there. | +| **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 as a read computes them; a read THROUGH a reference field 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. | @@ -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'`. On a `required` field the server reads it on every write: where it is FALSE 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; a read THROUGH a reference field cannot be evaluated there. | +| **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 as a read computes them; a read THROUGH a reference field 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. | From 2b709e1229f11d065a083237f40d4f854c541959 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 23:34:14 +0000 Subject: [PATCH 07/17] fix(objectql): judge a required field's visibleWhen through the formulas it reads, and warn where a formula drives it A predicate reading a formula that reads another formula was waived silently when the inner one could not be computed on the write path: the outer formula computed cleanly over the null the inner one read. The engine now marks the formulas whose read value the write path cannot know (a hop, label(), can() with no permission map, or a formula reading one, at any depth) and counts a predicate reading one as shown. A formula that faults for a reason a read shares (an empty operand) is judged on the null a read serves, as the form judges it. The lint and Studio's field inspector warn on a required field whose visibleWhen reads a formula: the form judges the value it last read and does not recompute it, and an unservable formula keeps the field required on every write. ADR-0113, ADR-0137, the visibleWhen describe and the changeset state both arms and the known limit. 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. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfrHprnpf55xZtXBbx --- .changeset/34905-required-when-shown.md | 8 +- content/docs/references/data/field.mdx | 2 +- content/docs/references/data/object.mdx | 4 +- content/docs/references/system/migration.mdx | 4 +- ...red-write-contract-vs-column-constraint.md | 46 ++++- ...-predicate-fault-semantics-are-contract.md | 11 +- .../required-visible-when-formula-issue.ts | 157 ++++++++++++++++++ .../lint/src/validate-expressions.test.ts | 45 +++++ packages/lint/src/validate-expressions.ts | 6 + .../src/engine-required-when-shown.test.ts | 77 ++++++++- packages/objectql/src/engine-top-level.ts | 76 +++++++-- packages/objectql/src/engine-update.ts | 6 +- .../objectql/src/validation/rule-validator.ts | 64 ++++--- packages/spec/src/data/field.zod.ts | 7 +- .../inspectors/ObjectFieldInspector.tsx | 32 +++- .../requiredVisibleWhenReference.test.ts | 45 ++++- .../requiredVisibleWhenReference.ts | 143 +++++++++++++++- ui/packages/i18n/src/namespaces/studio/en.ts | 4 + ui/packages/i18n/src/namespaces/studio/zh.ts | 4 + 19 files changed, 676 insertions(+), 65 deletions(-) create mode 100644 packages/lint/src/required-visible-when-formula-issue.ts diff --git a/.changeset/34905-required-when-shown.md b/.changeset/34905-required-when-shown.md index 1964e3372be..1a7e0f38c6e 100644 --- a/.changeset/34905-required-when-shown.md +++ b/.changeset/34905-required-when-shown.md @@ -21,12 +21,14 @@ Metadata-protocol: semantic - 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 computes it; a formula that cannot be computed there counts as shown. Only the field's own `visibleWhen` is read: a field group's `visibleWhen` and form-view predicates are not. +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()` or `can`, or reads such a formula at any depth) counts as shown. 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. -**`@objectstack/lint`.** Two 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), and `storage.notNull: true` beside the pair (the column still refuses the null on a record outside the condition). +**Known limit: a formula-driven `visibleWhen`.** The form judges the predicate on the formula value it last read and does not recompute it while the user edits; the server judges the record being written. An edit that moves a formula into the condition (say, raising `amount` so `risk_level` becomes `'high'`) without filling the field is refused, naming a field the form still hides; 18.5.0 accepted that edit. A create inside such a condition was refused before and still is. Until the form recomputes formulas (a follow-up), read the formula's own inputs in the predicate, or fill the field in the same write. -**`@object-ui/app-shell`.** Studio's field inspector shows the reference-read warning under the Visible-when editor of a required field. +**`@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 (the known limit above, and the counts-as-shown consequence when a formula it reads, at any depth, reads through a reference or calls `label()` or `can`); 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/references/data/field.mdx b/content/docs/references/data/field.mdx index 2dfbae84aa1..95639973fc3 100644 --- a/content/docs/references/data/field.mdx +++ b/content/docs/references/data/field.mdx @@ -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'`. 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 as a read computes them; a read THROUGH a reference field cannot be evaluated there. | +| **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, while the form judges the formula value it last read and does not recompute it as the user edits; a read THROUGH a reference field, or a formula that reads through one or calls label() or can(), 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 248c5852963..fd15eda9dc5 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -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'`. 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 as a read computes them; a read THROUGH a reference field cannot be evaluated there. | +| **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, while the form judges the formula value it last read and does not recompute it as the user edits; a read THROUGH a reference field, or a formula that reads through one or calls label() or can(), 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. | @@ -661,7 +661,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'`. 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 as a read computes them; a read THROUGH a reference field cannot be evaluated there. | +| **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, while the form judges the formula value it last read and does not recompute it as the user edits; a read THROUGH a reference field, or a formula that reads through one or calls label() or can(), 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 7a02d6217e0..c04d2496e5f 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -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'`. 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 as a read computes them; a read THROUGH a reference field cannot be evaluated there. | +| **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, while the form judges the formula value it last read and does not recompute it as the user edits; a read THROUGH a reference field, or a formula that reads through one or calls label() or can(), 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. | @@ -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'`. 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 as a read computes them; a read THROUGH a reference field cannot be evaluated there. | +| **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, while the form judges the formula value it last read and does not recompute it as the user edits; a read THROUGH a reference field, or a formula that reads through one or calls label() or can(), 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/0113-required-write-contract-vs-column-constraint.md b/docs/adr/0113-required-write-contract-vs-column-constraint.md index a056184e7b6..771e25f8a37 100644 --- a/docs/adr/0113-required-write-contract-vs-column-constraint.md +++ b/docs/adr/0113-required-write-contract-vs-column-constraint.md @@ -272,7 +272,9 @@ 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 the way the form shows it. +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`): @@ -290,8 +292,8 @@ D1), so it now judges the requirement the way the form shows it. 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` field it - reads that cannot be computed on the record): it **counts as shown**, and the +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 @@ -311,9 +313,33 @@ the fence below), so that binding serves older stored metadata. `features`, 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 the form shows. A formula that cannot be computed there -(it faults, reads through a reference, or calls `label()`) makes the predicate a -fault, which counts as shown. +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), or calls `current_user.can()` and the write resolved no permission + map; 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`. The lint warns about it (below). + +**Known limit: the form does not recompute a formula.** The form judges the +predicate on the formula value it last read, over its live values +(`ruleRecord` in `form.tsx`); a create form has none, and an edit of the +formula's inputs does not move it. The server judges the record being +written. So on a create the form keeps a formula-driven field hidden while the +server may require it (main refused that create too), and an edit that moves +the computed value into the condition is refused naming a field the form still +hides; main accepted that edit. The server's answer is the one ruling item 2 +asks for; the form-side recompute is a follow-up card, and until it lands the +lint warns on every `required` field whose `visibleWhen` reads a formula. **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 @@ -321,10 +347,14 @@ 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 two +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), and `required` + `visibleWhen` +hydrated at the field level, so it always faults); one that reads a `formula` +field (the known limit above, 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 diff --git a/docs/adr/0137-predicate-fault-semantics-are-contract.md b/docs/adr/0137-predicate-fault-semantics-are-contract.md index 8dc6f00f379..ab8fd3a28db 100644 --- a/docs/adr/0137-predicate-fault-semantics-are-contract.md +++ b/docs/adr/0137-predicate-fault-semantics-are-contract.md @@ -156,14 +156,17 @@ makes "blank" a declared **third** state rather than a spelling of "no rule". > 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 that cannot be computed on the record is -> such a fault. A clean verdict that is not TRUE (FALSE, or `null`) is not a -> fault: it hides the field, as the form reads it. +> A `formula` field the predicate reads whose read value the write path cannot +> know (it reads through a reference, calls `label()` or `can`, or reads such a +> formula) is such a fault. 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 included) | counted as shown: required, logged (D4) | +> | 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 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..f6dfb03b735 --- /dev/null +++ b/packages/lint/src/required-visible-when-formula-issue.ts @@ -0,0 +1,157 @@ +// 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 gaps the author can see at build time: + * + * - **The form does not recompute a formula.** It judges the predicate on the + * formula value it last read, while the user edits, and a create form has + * none. A create, or an edit that moves the formula into the condition, is + * judged by the server on a value the form never showed, and can be refused + * naming a field the form keeps hidden. + * - **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 records the form hides it on included. 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 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}. 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.`; + 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 ones the form hides it on included.`; + } + 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 ee5422ca295..4a9231cfcd0 100644 --- a/packages/lint/src/validate-expressions.test.ts +++ b/packages/lint/src/validate-expressions.test.ts @@ -6896,4 +6896,49 @@ describe('a `required` field\'s `visibleWhen` the server cannot use to lift the expect(issues[0].severity).toBe('warning'); expect(issues[0].message).toContain('`storage.notNull: true`'); }); + + // A formula the predicate reads: the form shows the value it last read and + // does not recompute it, 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 form does not recompute it', () => { + 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('does not recompute it'); + 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 b232cd26f2d..fbeb796d634 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; @@ -4375,6 +4376,11 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression severity: 'warning', }); } + // A `formula` the predicate reads: the form does not recompute it, and + // one the write path cannot compute keeps the field required on every + // write (`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 }); } diff --git a/packages/objectql/src/engine-required-when-shown.test.ts b/packages/objectql/src/engine-required-when-shown.test.ts index b8a05497611..d59a5a5196a 100644 --- a/packages/objectql/src/engine-required-when-shown.test.ts +++ b/packages/objectql/src/engine-required-when-shown.test.ts @@ -203,6 +203,32 @@ describe('ADR-0113 D1 (amended) — `required` + `visibleWhen` is required when 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_flag', fields: { @@ -391,6 +417,16 @@ describe('ADR-0113 D1 (amended) — `required` + `visibleWhen` is required when 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); @@ -399,12 +435,45 @@ describe('ADR-0113 D1 (amended) — `required` + `visibleWhen` is required when expect(outside.results?.[0]?.valid).toBe(true); }); - it('a formula that cannot be computed counts as shown, and the fault is logged', async () => { - const err = await refusalOf(() => engine.insert('rws_formula_fault', { amount: 50 }, ADMIN)); + 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_level/); - expect(warn?.meta).toMatchObject({ field: 'review_note', reason: 'predicate-fault' }); + 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); }); }); diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index 3258f0ac5ee..e49b0eb8555 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, referenceTraversalConflicts, staticReadonlyInsertSubject, stripReadonlyFields } from './validation/rule-validator.js'; import type { RelatedFieldBinding, RelatedRecordBinding } from './validation/rule-validator.js'; import { declaredColumnSet } from './declared-read-columns.js'; @@ -3051,39 +3051,89 @@ 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 value the - * form shows. The SAME plan and evaluation a read uses, over a copy of the - * record; the plan is built on the first call, so a write whose predicates - * read no formula pays nothing. No hop is resolved and no option label is - * read here, so a formula that needs either faults, and the predicate counts - * as shown. `undefined` when the object declares no formula. + * 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), or calls `current_user.can()` + * and this write resolved no permission map; 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. + * - **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; faulted: ReadonlySet }) | undefined { +): ((record: Record) => { record: Record; unservable: ReadonlyMap }) | 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; let plan: FormulaPlanEntry[] | null | undefined; + const unservable = new Map(); + 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, unservable); + if (why) unservable.set(entry.name, why); } } - if (plan === null) return { record, faulted: new Set(formulaNames) }; + if (plan === null) return { record, unservable }; + const hit = memo.get(record); + if (hit) return { record: hit, unservable }; const copy: Record = { ...record }; - const faulted = new Set(); - applyFormulaPlan(plan, [copy], execCtx, permissions, (name) => { faulted.add(name); }); - return { record: copy, faulted }; + applyFormulaPlan(plan, [copy], execCtx, permissions); + memo.set(record, copy); + return { record: copy, unservable }; }; } +/** + * 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. + */ +function unservableReason( + entry: FormulaPlanEntry, + permissions: EvalPermissions | undefined, + known: ReadonlyMap, +): string | undefined { + if (entry.hops) { + return `reads through ${[...entry.hops.keys()].map((f) => `'${f}'`).join(', ')}, a reference the write path does not follow`; + } + if (planCallsOptionLabel([entry])) return 'calls label(), which the write path does not answer'; + if (!permissions && readsPermissionPredicate(entry.expression)) { + return 'calls current_user.can(), and this write resolved no permission map'; + } + 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)); + return via === undefined ? undefined : `reads the formula '${via}', which ${known.get(via)}`; +} + /** * [#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 diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index ac660b98b9a..ed769c9a0d8 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -2075,10 +2075,12 @@ 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) { for (const row of priorRows ?? []) { try { - 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: parentForRow?.(row), previousParent: previousParentForRow?.(row), related: bulkRelatedForRow?.({ ...(row ?? {}), ...bulkPatch }), permissions: bulkPermissions, formulaValues: formulaValuesFor(updateSchema, opCtx.context, 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: parentForRow?.(row), previousParent: previousParentForRow?.(row), related: bulkRelatedForRow?.({ ...(row ?? {}), ...bulkPatch }), permissions: bulkPermissions, formulaValues: bulkFormulaValues }), this.logger, object); } catch (err) { if (err instanceof ValidationError && row?.id != null) { throw new ValidationError(err.fields.map((f) => ({ ...f, message: `${f.message} (record ${String(row.id)})` }))); @@ -2094,7 +2096,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, formulaValues: formulaValuesFor(updateSchema, opCtx.context, 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/validation/rule-validator.ts b/packages/objectql/src/validation/rule-validator.ts index 39e928a0c46..79315f12f55 100644 --- a/packages/objectql/src/validation/rule-validator.ts +++ b/packages/objectql/src/validation/rule-validator.ts @@ -437,12 +437,18 @@ export interface EvaluateRulesOptions { * [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 the form sees. - * `faulted` names each formula that could not be computed on that record. - * Absent: a predicate that reads a formula field cannot be evaluated, and - * counts as shown. + * reads one is judged on the value this returns, the value a read of the + * written record would serve. That is not always the value the form shows: + * the form judges the formula value it last read and does not recompute it + * while the user edits (a create form has none), so a write that changes a + * formula's inputs can be judged on a value the form never showed. + * `unservable` names, with the reason, each formula whose read value the + * write path cannot know (a hop, `label()`, `can` with no map, or a formula + * reading one); 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; faulted: ReadonlySet }; + formulaValues?: (record: Record) => { record: Record; unservable: ReadonlyMap }; /** * [#4977] The master-detail header this write's field `requiredWhen` * predicates read as `parent` — the SAME binding, resolved by the SAME engine @@ -3476,6 +3482,10 @@ export function nullPreviousReadDetail( /** 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 @@ -3486,14 +3496,21 @@ function formulaReadsOf(pred: string | Expression, fields: Record(); - for (const root of ['record', 'previous']) { - const analysis = analyzeRelationshipTraversals(expr.source, root); - if (!analysis) return formulaFields; - for (const name of analysis.bareFields) reads.add(name); - for (const name of analysis.traversals.keys()) reads.add(name); + 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); } - return formulaFields.filter((name) => reads.has(name)); + if (reads === null) return formulaFields; + const known = reads; + return formulaFields.filter((name) => known.has(name)); } /** @@ -3516,8 +3533,9 @@ function formulaReadsOf(pred: string | Expression, fields: Record | undefined, ): { verdict: ShownVerdict; error?: { kind: string; message: string } } => { // A `formula` field is not on the write path: judge the predicate on the - // computed value, and count a formula that cannot be computed as a fault. + // 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 then = prior ? opts.formulaValues(prior) : undefined; - const faulted = formulas.filter((f) => now.faulted.has(f) || (then?.faulted.has(f) ?? false)); - if (faulted.length > 0) { - return { verdict: 'fault', error: { kind: 'formula', message: `reads the formula field ${faulted.map((f) => `'${f}'`).join(', ')}, which could not be computed on this 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 ')}` } }; } record = now.record; - prior = then ? then.record as PreviousBinding : prior; + prior = prior ? opts.formulaValues(prior).record as PreviousBinding : prior; } const res = ExpressionEngine.evaluate(toExpression(pred), { ...ruleScope(record, prior, extra), diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index bd53a126054..fad3f1f2e8c 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -2519,9 +2519,12 @@ export const FieldSchema = lazySchema(() => { * `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 first. + * as the form reads it, with `formula` fields computed over the record being + * written. The form judges a formula on the value it last read and does not + * recompute it while the user edits, so for a formula-driven predicate the + * two sides can differ on a create or an edit of the formula's inputs. */ - 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 as a read computes them; a read THROUGH a reference field cannot be evaluated there."), + 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, while the form judges the formula value it last read and does not recompute it as the user edits; a read THROUGH a reference field, or a formula that reads through one or calls label() or can(), 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/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx index 8df118bd681..6d0d4e2b5ec 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,7 +145,7 @@ import { useExternalWriteState, } from '../previews/external-object.js'; import { CelPredicateField } from '../CelPredicateField.js'; -import { useRequiredVisibleWhenReferenceReads } from './requiredVisibleWhenReference.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'; @@ -857,6 +857,15 @@ export function ObjectFieldInspector({ return out; }, [view]); const visibleWhenReferenceReads = useRequiredVisibleWhenReferenceReads(entry?.def ?? null, siblingTypes); + // …and a formula it reads is computed over the saved record there, while the + // form judges the value it last read; one the server cannot compute keeps it + // required on every save. + 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. @@ -1955,6 +1964,27 @@ export function ObjectFieldInspector({

)} + {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(', '), + })} + + )} + +

+ )} { + 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 index 3b62fb96e79..9b5a5b94c2f 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/requiredVisibleWhenReference.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/requiredVisibleWhenReference.ts @@ -27,6 +27,18 @@ * 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; the form judges the formula value it last read, does not recompute it + * while the user edits, and has none on a create. So a save can be + * refused naming a field the form keeps hidden, and the advisory says so 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, which the advisory + * says too. 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 @@ -79,11 +91,76 @@ export function referenceReadsInRequiredVisibleWhen( 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: the form judges the predicate on the + * formula value it last read and does not recompute it, while the server + * judges the record being saved. An unservable one keeps the field required on + * every save. + */ +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 } | null; +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) { @@ -96,6 +173,70 @@ function loadAnalyzer(): Promise { 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. diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index f4ac3ea48cf..5565ef48336 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -582,6 +582,10 @@ const STUDIO_EN: Record = { '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 shows the value it last read and does not recompute it while you edit (a new record has none), so a save can be refused naming this field while the form keeps it hidden. Read the formula\'s own inputs instead if the form should follow the edit.', + '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: it counts this field as shown, so it stays required on every record, including the ones this condition hides it on.', // 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 d5f7b045332..95f64c0f595 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -499,6 +499,10 @@ const STUDIO_ZH: Record = { '表达式为真时字段相应地变为可见 / 只读 / 必填。用 record.<字段> 引用当前记录,previous.<字段> 引用最近保存的值,parent.<字段>(主从明细行)引用表头记录。', 'designer.field.requiredVisibleWhenReference': '该字段为必填,服务器每次保存时按这条可见条件判断是否必填。条件经由引用字段 {fields} 读取关联记录,服务器在这里无法读取,因此按「显示」处理:所有记录(包括此条件隐藏该字段的记录)都仍要求填写。请改为读取本对象自己的字段。', + 'designer.field.requiredVisibleWhenFormula': + '该字段为必填,服务器每次保存时按这条可见条件判断是否必填,其中的 {fields} 按要保存的记录计算。表单显示的是上次读取的公式值,编辑时不会重新计算(新建记录时没有值),因此保存可能因该字段被拒绝,而表单仍隐藏它。如需表单随编辑变化,请改为直接读取公式本身的输入字段。', + 'designer.field.requiredVisibleWhenFormulaUnservable': + '{fields} 经由引用字段读取、调用了 label() 或 current_user.can()(直接或通过其他公式),服务器保存时无法计算,因此按「显示」处理:所有记录(包括此条件隐藏该字段的记录)都仍要求填写。', // Bulk multi-select (Tier 2) 'designer.canvas.bulkSelected': '已选 {n} 项', 'designer.canvas.bulkMoveTo': '移至分组', From 01a584b9c041f300f804e3bd49692b63c66dfeec Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 01:23:22 +0000 Subject: [PATCH 08/17] docs(spec): regenerate the object reference over the merged tree Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfrHprnpf55xZtXBbx --- content/docs/references/data/object.mdx | 1 + 1 file changed, 1 insertion(+) diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index fd15eda9dc5..4fa8f48bed0 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -500,6 +500,7 @@ const result = ApiMethod.parse(data); | **target** | `string` | optional | URL, Script Name, Flow ID, or API Endpoint. Supports $`{param.X}` and $`{ctx.X}` interpolation. For type:'url': an http:// or https:// URL, a mailto: address, or an in-app path starting with / or ./ (a console route; a record is /apps/APP/OBJECT/record/ID, APP being the app's route segment — see onSuccess.navigate) — every other scheme and a protocol-relative //host are refused. | | **openIn** | `Enum<'self' \| 'new-tab'>` | optional | For type:'url' — where to open `target`. 'new-tab' opens a new browser tab; 'self' navigates in place. When omitted, external/absolute URLs open in a new tab and relative URLs navigate in place. Static execution option — keep it OUT of `params` (which is user-input-collection only). | | **body** | `{ language: 'expression'; source: string } \| { language: 'js'; source: string; capabilities?: Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log' \| …>[]; timeoutMs?: integer; … }` | optional | Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`. An action body runs as system, and its update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' is refused with PERMISSION_DENIED; an insert is not judged by this rule. | +| **refusals** | `Record; params?: string[] }>` | optional | Refusal catalogue keyed by the SCREAMING_SNAKE code the action's js body throws: `{ message, status?, reasons?, params? }`. The body refuses by code only, optionally with a declared reason and params; the runtime answers with the declared message (translated through objects.``._actions.``.refusals.``.message, or globalActions.``.refusals.``.message for an object-less action, ….reasons.``.message for a reason, in the caller's locale, holes filled from params) and status. A code not declared here, or a reason a code with reasons does not declare, is refused loudly — at save when the body throws it literally, otherwise at run time. Only a type: 'script' action with a js body declares one | | **operation** | `Enum<'update'>` | optional | The declarative single-record field write, mirroring a list view's `bulkActionDefs`: `'update'` applies `patch` (merged under the collected `params`) to the current record on the data plane AS THE CALLER — never system-elevated — so the caller's permissions, the object's hooks and its validations fire as for a user edit. `type` stays at its default `'script'` (the platform action route the write is performed on); `target`/`body`/`method`/`bodyExtra` are refused beside it. `'delete'` and `'custom'` have no row-level form. | | **patch** | `Record` | optional | For `operation: 'update'` — static field values written to the current record, merged UNDER the user-supplied `params` so a fixed value can be declared without exposing it in the dialog. Written on the data plane as the caller: object permissions, hooks and validations fire as for a user edit. Refused on an action without `operation: 'update'` (it would be silently dropped). | | **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | The bulk dispatch contract this action's BODY is written for, in `bulkActionDefs`' own vocabulary: 'perRecord' = one dispatch per selected row carrying that row's `recordId` (the view's `bulkActions: ['']` bare-string form); 'aggregate' = ONE dispatch for the whole selection carrying every id in `params._selectedIds` (a `bulkActionDefs` entry with `execution: 'aggregate'`). Optional with NO default — omit it only when the body genuinely serves both. A list view wiring a declared action under the other contract is refused by `@objectstack/lint` (`action-dispatch-contract-mismatch`). | From 84d2f7370c37f81d57f1ffb4ad902bfb29755cdf Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 02:18:40 +0000 Subject: [PATCH 09/17] docs(spec): regenerate the object and migration references over the merged tree Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfrHprnpf55xZtXBbx --- content/docs/references/data/object.mdx | 7 ++++--- content/docs/references/system/migration.mdx | 4 ++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 4fa8f48bed0..19ac21bec69 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -177,7 +177,7 @@ const result = ApiMethod.parse(data); | **relatedLists** | `string[]` | optional | Business order of this object's related lists on its record page, most important first. Each entry is a child object name (e.g. "task"), or object.field when that child has more than one relationship to this object (e.g. "event.related_to"). Listed relationships come first in this order; unlisted ones follow in the derived order (owned master_detail children, then lookup children). An entry whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere. An entry whose child exists nowhere is refused by os validate / os build (which leave a sys_ / cloud_ / ai_ name to the runtime) and by a metadata write that names no package; a write into a package stores it, since a child outside the package may be a downstream package's object that points here, and the record page places nothing for it. It orders only: relatedList: false on the relationship still hides a list, and relatedList: 'primary' still places a list in the record's body, so the order applies among the body tables and among the side cards. | | **stageField** | `string \| false` | optional | [ADR-0085] Lifecycle stage field (linear/ordered), or false to declare the status field non-linear and suppress stage heuristics. Absent = heuristic detection allowed. When the named field carries options, it must be a single-value `select` / `radio` with inline `options`, each declaring its `kind` ('open' / 'won' / 'lost'); a picklist-backed or multi-value stage field is refused. A name that resolves to no declared field, or a field with no options, is not judged at parse. | | **editMode** | `Enum<'modal' \| 'page'>` | optional | Edit-interaction intent for records of this object: 'modal' opens the edit form as a dialog over the current view; 'page' navigates to a dedicated full-page edit route. Absent = the renderer picks its own default (objectui defaults to modal). Cross-renderer intent, not pixel styling (family). | -| **listViews** | `Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| 'chart' \| 'tree'>; data?: object \| object \| object; … }>` | optional | Built-in named list views (segmented tabs) shipped with the object schema — "views" mode, dropdown userFilters allowed, no page-only tabs (ADR-0047) | +| **listViews** | `Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }>` | optional | Built-in named list views (segmented tabs) shipped with the object schema — "views" mode, dropdown userFilters allowed, no page-only tabs (ADR-0047) | | **searchableFields** | `string[]` | optional | Fields the `$search` query matches against (ADR-0061). Canonical default for the record picker, list quick-search and global search; views may narrow it. When unset, search auto-defaults to the name/title field plus short-text fields. Entries must name a STORED column: a virtual `formula` field is computed on read and materializes no column, so searching it can never match and it is refused — mirror the value onto a stored text field and declare that. | | **enable** | `{ trackHistory?: boolean; searchable?: boolean; apiEnabled?: boolean; apiMethods?: Enum<'get' \| 'list' \| 'create' \| 'update' \| 'delete' \| 'bulk'>[]; … }` | optional | Enabled system features modules | | **sharingModel** | `Enum<'private' \| 'public_read' \| 'public_read_write' \| 'controlled_by_parent'>` | optional | Org-Wide Default record visibility (OWD) for INTERNAL users. Canonical four only (legacy aliases removed, ADR-0090 D4): private (owner-only) \| public_read (everyone reads, owner writes) \| public_read_write (everyone reads+writes) \| controlled_by_parent (derived from the master record). A CUSTOM object that omits this resolves to private at runtime (ADR-0090 D1). | @@ -385,7 +385,7 @@ const result = ApiMethod.parse(data); | :--- | :--- | :--- | :--- | | **name** | `string` | optional | Internal view name (lowercase snake_case) | | **label** | `string \| Record` | optional | Display label — the default-language string, or an inline locale map (`{ en, "zh-CN" }`) resolved at render time | -| **type** | `Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| 'chart' \| 'tree'>` | optional (default: `"grid"`) | | +| **type** | `Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>` | optional (default: `"grid"`) | | | **data** | `{ provider: 'object'; object: string } \| { provider: 'value'; items: any[] } \| { provider: 'schema'; schemaId: string; schema?: Record }` | optional | Data source configuration (defaults to "object" provider) | | **columns** | `string[] \| { field: string; label?: string \| Record; width?: number; align?: Enum<'left' \| 'center' \| 'right'>; … }[]` | ✅ | Fields to display as columns — the PROJECTION of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: this list is the candidate set AND the baseline order; `hiddenFields` subtracts from it and `fieldOrder` orders what survives. `hiddenFields` and `fieldOrder` cannot add a field omitted here. An empty list declares no projection, so neither of them applies: which columns show is then left to the renderer (objectui's `ListView` grid derives the object's default columns). | | **filter** | `({ field: string; operator: Enum<'equals' \| 'not_equals' \| 'contains' \| 'not_contains' \| 'icontains' \| …>; value?: string \| number \| boolean \| null \| (string \| number)[] } \| { or: object[] })[]` | optional | Filter criteria (JSON Rules) | @@ -405,6 +405,7 @@ const result = ApiMethod.parse(data); | **chart** | `{ chartType?: Enum<'bar' \| 'line' \| 'pie' \| 'area' \| 'scatter'>; dataset: string; dimensions?: string[]; values: string[] }` | optional | Chart binding — applies when the view renders as a chart. A `type: 'chart'` view must bind one: it names the ADR-0021 `dataset` and the measures (`values`) the chart plots, and there is no default binding | | **map** | `{ latitudeField?: string; longitudeField?: string; locationField?: string; titleField?: string; … }` | optional | Map configuration — applies when the view renders as a map layout | | **tree** | `{ parentField?: string; labelField?: string; fields?: string[]; defaultExpandedDepth?: integer }` | optional | Tree/hierarchy configuration — applies when the view renders as a tree layout | +| **timesheet** | `{ rowFields: string[]; dateField: string; valueField: string }` | optional | Timesheet binding — applies when the view renders as a timesheet. A `type: 'timesheet'` view must bind one: the row fields, the date field and the numeric value field the weekly grid pivots and edits | | **pageName** | `never` | optional | [REMOVED] `view.pageName` was removed in @objectstack/spec 17.5.0 (ADR-0049 enforce-or-remove) — it named the page a `type: 'page'` view was to mount, and that mount was never built: no renderer read the key, so the named page was never reached and the view drew an empty grid. Delete the key; to put a published page in front of users, give the app a navigation item — `{ type: 'page', pageName: '' }` under the app's `navigation` — which is a different key on a different surface and is the page mount that has always rendered. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **description** | `string \| Record` | optional | View description for documentation/tooltips | | **sharing** | `{ lockedBy?: string }` | optional | View sharing configuration: who locked the view configuration | @@ -421,7 +422,7 @@ const result = ApiMethod.parse(data); | **inlineEdit** | `boolean` | optional | Allow inline editing of records directly in the list view | | **exportOptions** | `Enum<'csv' \| 'xlsx' \| 'json'>[] \| { formats?: Enum<'csv' \| 'xlsx' \| 'json'>[]; maxRecords?: integer; includeHeaders?: boolean; fileNamePrefix?: string; … }` | optional | Export configuration for the list toolbar export menu: `{ formats?, maxRecords?, includeHeaders?, fileNamePrefix?, streaming? }`. A bare format array is the legacy spelling and lifts to `{ formats: [...] }` at parse. | | **userActions** | `{ sort?: boolean; search?: boolean; filter?: boolean; refresh?: boolean; … }` | optional | User action toggles for the view toolbar | -| **appearance** | `{ showDescription?: boolean; allowedVisualizations?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| 'chart' \| 'tree'>[] }` | optional | Appearance and visualization configuration | +| **appearance** | `{ showDescription?: boolean; allowedVisualizations?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>[] }` | optional | Appearance and visualization configuration | | **tabs** | `never` | optional | [REMOVED] `view.list.tabs` was removed in @objectstack/spec 17.5.0 (ADR-0049 enforce-or-remove) — no renderer ever mounted a tab bar for it, so authoring it drew nothing: the tab strip above an object's records is the saved-view switcher (ViewTabBar), which renders one tab per named list view and never read this key. Delete the key, and move each tab you want to a named list view under the object's `listViews` instead: the tab's `name` becomes the entry's key, its `label` the entry's `label`, and its `filter` rules join the view's own `filter` on that entry (copy the view's `columns` too); a tab whose `view` already named a list view needs nothing more. Every `listViews` entry renders as a tab in the switcher. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **addRecord** | `{ enabled: boolean; position?: Enum<'top' \| 'bottom' \| 'both'> }` | optional | Add record entry point configuration | | **showRecordCount** | `boolean` | optional | Show record count at the bottom of the list | diff --git a/content/docs/references/system/migration.mdx b/content/docs/references/system/migration.mdx index c04d2496e5f..4228669eb8d 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -356,7 +356,7 @@ Create a new object | **relatedLists** | `string[]` | optional | Business order of this object's related lists on its record page, most important first. Each entry is a child object name (e.g. "task"), or object.field when that child has more than one relationship to this object (e.g. "event.related_to"). Listed relationships come first in this order; unlisted ones follow in the derived order (owned master_detail children, then lookup children). An entry whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere. An entry whose child exists nowhere is refused by os validate / os build (which leave a sys_ / cloud_ / ai_ name to the runtime) and by a metadata write that names no package; a write into a package stores it, since a child outside the package may be a downstream package's object that points here, and the record page places nothing for it. It orders only: relatedList: false on the relationship still hides a list, and relatedList: 'primary' still places a list in the record's body, so the order applies among the body tables and among the side cards. | | **stageField** | `string \| false` | optional | [ADR-0085] Lifecycle stage field (linear/ordered), or false to declare the status field non-linear and suppress stage heuristics. Absent = heuristic detection allowed. When the named field carries options, it must be a single-value `select` / `radio` with inline `options`, each declaring its `kind` ('open' / 'won' / 'lost'); a picklist-backed or multi-value stage field is refused. A name that resolves to no declared field, or a field with no options, is not judged at parse. | | **editMode** | `Enum<'modal' \| 'page'>` | optional | Edit-interaction intent for records of this object: 'modal' opens the edit form as a dialog over the current view; 'page' navigates to a dedicated full-page edit route. Absent = the renderer picks its own default (objectui defaults to modal). Cross-renderer intent, not pixel styling (family). | -| **listViews** | `Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| 'chart' \| 'tree'>; data?: object \| object \| object; … }>` | optional | Built-in named list views (segmented tabs) shipped with the object schema — "views" mode, dropdown userFilters allowed, no page-only tabs (ADR-0047) | +| **listViews** | `Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }>` | optional | Built-in named list views (segmented tabs) shipped with the object schema — "views" mode, dropdown userFilters allowed, no page-only tabs (ADR-0047) | | **searchableFields** | `string[]` | optional | Fields the `$search` query matches against (ADR-0061). Canonical default for the record picker, list quick-search and global search; views may narrow it. When unset, search auto-defaults to the name/title field plus short-text fields. Entries must name a STORED column: a virtual `formula` field is computed on read and materializes no column, so searching it can never match and it is refused — mirror the value onto a stored text field and declare that. | | **enable** | `{ trackHistory?: boolean; searchable?: boolean; apiEnabled?: boolean; apiMethods?: Enum<'get' \| 'list' \| 'create' \| 'update' \| 'delete' \| 'bulk'>[]; … }` | optional | Enabled system features modules | | **sharingModel** | `Enum<'private' \| 'public_read' \| 'public_read_write' \| 'controlled_by_parent'>` | optional | Org-Wide Default record visibility (OWD) for INTERNAL users. Canonical four only (legacy aliases removed, ADR-0090 D4): private (owner-only) \| public_read (everyone reads, owner writes) \| public_read_write (everyone reads+writes) \| controlled_by_parent (derived from the master record). A CUSTOM object that omits this resolves to private at runtime (ADR-0090 D1). | @@ -657,7 +657,7 @@ Create a new object | **relatedLists** | `string[]` | optional | Business order of this object's related lists on its record page, most important first. Each entry is a child object name (e.g. "task"), or object.field when that child has more than one relationship to this object (e.g. "event.related_to"). Listed relationships come first in this order; unlisted ones follow in the derived order (owned master_detail children, then lookup children). An entry whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere. An entry whose child exists nowhere is refused by os validate / os build (which leave a sys_ / cloud_ / ai_ name to the runtime) and by a metadata write that names no package; a write into a package stores it, since a child outside the package may be a downstream package's object that points here, and the record page places nothing for it. It orders only: relatedList: false on the relationship still hides a list, and relatedList: 'primary' still places a list in the record's body, so the order applies among the body tables and among the side cards. | | **stageField** | `string \| false` | optional | [ADR-0085] Lifecycle stage field (linear/ordered), or false to declare the status field non-linear and suppress stage heuristics. Absent = heuristic detection allowed. When the named field carries options, it must be a single-value `select` / `radio` with inline `options`, each declaring its `kind` ('open' / 'won' / 'lost'); a picklist-backed or multi-value stage field is refused. A name that resolves to no declared field, or a field with no options, is not judged at parse. | | **editMode** | `Enum<'modal' \| 'page'>` | optional | Edit-interaction intent for records of this object: 'modal' opens the edit form as a dialog over the current view; 'page' navigates to a dedicated full-page edit route. Absent = the renderer picks its own default (objectui defaults to modal). Cross-renderer intent, not pixel styling (family). | -| **listViews** | `Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| 'chart' \| 'tree'>; data?: object \| object \| object; … }>` | optional | Built-in named list views (segmented tabs) shipped with the object schema — "views" mode, dropdown userFilters allowed, no page-only tabs (ADR-0047) | +| **listViews** | `Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }>` | optional | Built-in named list views (segmented tabs) shipped with the object schema — "views" mode, dropdown userFilters allowed, no page-only tabs (ADR-0047) | | **searchableFields** | `string[]` | optional | Fields the `$search` query matches against (ADR-0061). Canonical default for the record picker, list quick-search and global search; views may narrow it. When unset, search auto-defaults to the name/title field plus short-text fields. Entries must name a STORED column: a virtual `formula` field is computed on read and materializes no column, so searching it can never match and it is refused — mirror the value onto a stored text field and declare that. | | **enable** | `{ trackHistory?: boolean; searchable?: boolean; apiEnabled?: boolean; apiMethods?: Enum<'get' \| 'list' \| 'create' \| 'update' \| 'delete' \| 'bulk'>[]; … }` | optional | Enabled system features modules | | **sharingModel** | `Enum<'private' \| 'public_read' \| 'public_read_write' \| 'controlled_by_parent'>` | optional | Org-Wide Default record visibility (OWD) for INTERNAL users. Canonical four only (legacy aliases removed, ADR-0090 D4): private (owner-only) \| public_read (everyone reads, owner writes) \| public_read_write (everyone reads+writes) \| controlled_by_parent (derived from the master record). A CUSTOM object that omits this resolves to private at runtime (ADR-0090 D1). | From 7f14821c80cd5fb59bd483c939ea058b1a8cee08 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 05:04:21 +0000 Subject: [PATCH 10/17] test(objectql): a formula reading current_user, on a write with no acting user, gates a required field The disproof test for review S4: the insert is accepted silently today. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt --- .../src/engine-required-when-shown.test.ts | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/packages/objectql/src/engine-required-when-shown.test.ts b/packages/objectql/src/engine-required-when-shown.test.ts index d59a5a5196a..82dba2e4bdc 100644 --- a/packages/objectql/src/engine-required-when-shown.test.ts +++ b/packages/objectql/src/engine-required-when-shown.test.ts @@ -229,6 +229,17 @@ describe('ADR-0113 D1 (amended) — `required` + `visibleWhen` is required when 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_flag', fields: { @@ -477,6 +488,30 @@ describe('ADR-0113 D1 (amended) — `required` + `visibleWhen` is required when }); }); + // ── (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('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 () => { From f7937161bebf1f817fdda8ada14efbc8f564cd81 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 05:04:21 +0000 Subject: [PATCH 11/17] fix(objectql): a formula reading the acting user counts as shown on a write with none formulaValuesFor marks a formula that reads current_user (user, ctx, os) unservable when the write has no acting user, through the read closure like the hop, label() and can marks, and names it in noActingUser so the required-when-shown verdict logs it as no-acting-user (ADR-0137 D4), as it logs the direct current_user spelling. Closes review S4. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt --- .../src/engine-required-when-shown.test.ts | 24 +++++++ packages/objectql/src/engine-top-level.ts | 62 +++++++++++++------ .../objectql/src/validation/rule-validator.ts | 36 +++++++---- 3 files changed, 91 insertions(+), 31 deletions(-) diff --git a/packages/objectql/src/engine-required-when-shown.test.ts b/packages/objectql/src/engine-required-when-shown.test.ts index 82dba2e4bdc..086acb5e87e 100644 --- a/packages/objectql/src/engine-required-when-shown.test.ts +++ b/packages/objectql/src/engine-required-when-shown.test.ts @@ -24,6 +24,9 @@ // 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'; @@ -240,6 +243,17 @@ describe('ADR-0113 D1 (amended) — `required` + `visibleWhen` is required when 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: { @@ -505,6 +519,16 @@ describe('ADR-0113 D1 (amended) — `required` + `visibleWhen` is required when 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); diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index fd3a7ef0115..65304455d89 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -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, readsPermissionPredicate, 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'; @@ -3105,12 +3105,16 @@ async function hydrateWriteFormulas( * * - **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), or calls `current_user.can()` - * and this write resolved no permission map; 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. + * `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. @@ -3125,13 +3129,16 @@ function formulaValuesFor( schema: any, execCtx: ExecutionContext | undefined, permissions: EvalPermissions | undefined, -): ((record: Record) => { record: Record; unservable: ReadonlyMap }) | 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) { @@ -3143,42 +3150,59 @@ function formulaValuesFor( } // In read order, so a formula's reads are judged before it. for (const entry of plan ?? []) { - const why = unservableReason(entry, permissions, unservable); - if (why) unservable.set(entry.name, why); + 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 }; + if (plan === null) return { record, unservable, noActingUser }; const hit = memo.get(record); - if (hit) return { record: hit, unservable }; + if (hit) return { record: hit, unservable, noActingUser }; const copy: Record = { ...record }; applyFormulaPlan(plan, [copy], execCtx, permissions); memo.set(record, copy); - return { record: copy, unservable }; + 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. + * 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, -): string | undefined { + knownNoActingUser: ReadonlySet, +): { reason: string; noActingUser?: true } | undefined { if (entry.hops) { - return `reads through ${[...entry.hops.keys()].map((f) => `'${f}'`).join(', ')}, a reference the write path does not follow`; + return { reason: `reads through ${[...entry.hops.keys()].map((f) => `'${f}'`).join(', ')}, a reference the write path does not follow` }; } - if (planCallsOptionLabel([entry])) return 'calls label(), which the write path does not answer'; + if (planCallsOptionLabel([entry])) return { reason: 'calls label(), which the write path does not answer' }; if (!permissions && readsPermissionPredicate(entry.expression)) { - return 'calls current_user.can(), and this write resolved no permission map'; + 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, and this write has none (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)); - return via === undefined ? undefined : `reads the formula '${via}', which ${known.get(via)}`; + if (via === undefined) return undefined; + const reason = `reads the formula '${via}', which ${known.get(via)}`; + return knownNoActingUser.has(via) ? { reason, noActingUser: true } : { reason }; } /** diff --git a/packages/objectql/src/validation/rule-validator.ts b/packages/objectql/src/validation/rule-validator.ts index 1b5409b8329..6dd81f48627 100644 --- a/packages/objectql/src/validation/rule-validator.ts +++ b/packages/objectql/src/validation/rule-validator.ts @@ -443,12 +443,15 @@ export interface EvaluateRulesOptions { * while the user edits (a create form has none), so a write that changes a * formula's inputs can be judged on a value the form never showed. * `unservable` names, with the reason, each formula whose read value the - * write path cannot know (a hop, `label()`, `can` with no map, or a formula - * reading one); 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. + * 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 }; + 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 @@ -3120,7 +3123,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 : ''; @@ -3601,13 +3604,15 @@ function formulaReadsOf(pred: string | Expression, fields: Record, prior: PreviousBinding, extra: Record | undefined, - ): { verdict: ShownVerdict; error?: { kind: string; message: string } } => { + ): { 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 @@ -3661,7 +3666,13 @@ function evaluateRequiredWhenShown( 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 ')}` } }; + 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; @@ -3683,10 +3694,11 @@ function evaluateRequiredWhenShown( const now = verdictOn(pred, merged, previous, parentExtra); if (now.verdict === 'hidden') continue; if (now.verdict === 'fault') { - const noActingUser = user === undefined && readsUserRoot(pred); + 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 ? 'no acting user to bind current_user (system write)' : `${now.error!.kind}: ${String(now.error!.message).split('\n')[0]}`})` + + `(${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 }, ); From 6ae764eba5ed6891b5f2a6aa50356ea9bde23d22 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 05:06:28 +0000 Subject: [PATCH 12/17] docs: name the acting-user mark and the can() condition wherever the unservable set is listed The ADR-0113 amendment, the ADR-0137 note, the visibleWhen describe, the changeset, the lint message and the Studio strings now say that a formula reading the acting user counts as shown on a write with none (logged no-acting-user), and that a can() formula is computed on a write that picks a permission-gated option (review N8). Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt --- .changeset/34905-required-when-shown.md | 4 ++-- ...uired-write-contract-vs-column-constraint.md | 17 +++++++++++++---- ...37-predicate-fault-semantics-are-contract.md | 8 ++++++-- .../src/required-visible-when-formula-issue.ts | 12 ++++++++++++ packages/spec/src/data/field.zod.ts | 2 +- .../inspectors/requiredVisibleWhenReference.ts | 6 +++++- ui/packages/i18n/src/namespaces/studio/en.ts | 2 +- ui/packages/i18n/src/namespaces/studio/zh.ts | 2 +- 8 files changed, 41 insertions(+), 12 deletions(-) diff --git a/.changeset/34905-required-when-shown.md b/.changeset/34905-required-when-shown.md index 1a7e0f38c6e..288651e8ad2 100644 --- a/.changeset/34905-required-when-shown.md +++ b/.changeset/34905-required-when-shown.md @@ -21,13 +21,13 @@ Metadata-protocol: semantic - 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()` or `can`, or reads such a formula at any depth) counts as shown. Only the field's own `visibleWhen` is read: a field group's `visibleWhen` and form-view predicates are not. +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. **Known limit: a formula-driven `visibleWhen`.** The form judges the predicate on the formula value it last read and does not recompute it while the user edits; the server judges the record being written. An edit that moves a formula into the condition (say, raising `amount` so `risk_level` becomes `'high'`) without filling the field is refused, naming a field the form still hides; 18.5.0 accepted that edit. A create inside such a condition was refused before and still is. Until the form recomputes formulas (a follow-up), read the formula's own inputs in the predicate, or fill the field in the same write. -**`@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 (the known limit above, and the counts-as-shown consequence when a formula it reads, at any depth, reads through a reference or calls `label()` or `can`); and `storage.notNull: true` beside the pair (the column still refuses the null on a record outside the condition). +**`@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 (the known limit above, and 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. 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 771e25f8a37..0a34be0e2da 100644 --- a/docs/adr/0113-required-write-contract-vs-column-constraint.md +++ b/docs/adr/0113-required-write-contract-vs-column-constraint.md @@ -305,7 +305,8 @@ two sides can differ; see the formula paragraph below. 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. The lint refuses `current_user` in a field `visibleWhen` at authoring (see +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. @@ -323,12 +324,20 @@ that does not compute is answered by the reason, in two arms: 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), or calls `current_user.can()` and the write resolved no permission - map; or it reads such a formula, at any depth of the formulas it reads. 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) 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`. The lint warns about it (below). + 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. **Known limit: the form does not recompute a formula.** The form judges the predicate on the formula value it last read, over its live values diff --git a/docs/adr/0137-predicate-fault-semantics-are-contract.md b/docs/adr/0137-predicate-fault-semantics-are-contract.md index ab8fd3a28db..ed0fb685b87 100644 --- a/docs/adr/0137-predicate-fault-semantics-are-contract.md +++ b/docs/adr/0137-predicate-fault-semantics-are-contract.md @@ -157,8 +157,12 @@ makes "blank" a declared **third** state rather than a spelling of "no rule". > 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()` or `can`, or reads such a -> formula) is such a fault. A formula that faults for a reason a read shares (an +> 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. 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. diff --git a/packages/lint/src/required-visible-when-formula-issue.ts b/packages/lint/src/required-visible-when-formula-issue.ts index f6dfb03b735..79f560dfb8a 100644 --- a/packages/lint/src/required-visible-when-formula-issue.ts +++ b/packages/lint/src/required-visible-when-formula-issue.ts @@ -22,6 +22,13 @@ * (`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 @@ -152,6 +159,11 @@ export function requiredVisibleWhenFormulaIssue( 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 ones the form hides it on included.`; + 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/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index fad3f1f2e8c..e893e0cbe6d 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -2524,7 +2524,7 @@ export const FieldSchema = lazySchema(() => { * recompute it while the user edits, so for a formula-driven predicate the * two sides can differ on a create or an edit of the formula's inputs. */ - 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, while the form judges the formula value it last read and does not recompute it as the user edits; a read THROUGH a reference field, or a formula that reads through one or calls label() or can(), cannot be evaluated there."), + 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, while the form judges the formula value it last read and does not recompute it as the user edits; 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/ui/packages/app-shell/src/views/metadata-admin/inspectors/requiredVisibleWhenReference.ts b/ui/packages/app-shell/src/views/metadata-admin/inspectors/requiredVisibleWhenReference.ts index 9b5a5b94c2f..794d9fe9b3f 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/requiredVisibleWhenReference.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/requiredVisibleWhenReference.ts @@ -36,7 +36,11 @@ * 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, which the advisory - * says too. The lint's `required-visible-when-formula-issue.ts` is the same + * says too; a `can` call 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 diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 6fb27912dbf..639fe49c48e 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -585,7 +585,7 @@ const STUDIO_EN: Record = { '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 shows the value it last read and does not recompute it while you edit (a new record has none), so a save can be refused naming this field while the form keeps it hidden. Read the formula\'s own inputs instead if the form should follow the edit.', '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: it counts this field as shown, so it stays required on every record, including the ones this condition hides it on.', + '{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, including the ones this condition hides it on.', // 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 9c105e91110..87e0a75ffcc 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -502,7 +502,7 @@ const STUDIO_ZH: Record = { 'designer.field.requiredVisibleWhenFormula': '该字段为必填,服务器每次保存时按这条可见条件判断是否必填,其中的 {fields} 按要保存的记录计算。表单显示的是上次读取的公式值,编辑时不会重新计算(新建记录时没有值),因此保存可能因该字段被拒绝,而表单仍隐藏它。如需表单随编辑变化,请改为直接读取公式本身的输入字段。', 'designer.field.requiredVisibleWhenFormulaUnservable': - '{fields} 经由引用字段读取、调用了 label() 或 current_user.can()(直接或通过其他公式),服务器保存时无法计算,因此按「显示」处理:所有记录(包括此条件隐藏该字段的记录)都仍要求填写。', + '{fields} 经由引用字段读取、调用了 label() 或 current_user.can()(直接或通过其他公式),服务器保存时无法计算(current_user.can() 仅在保存未选择受权限控制的选项时无法计算),因此按「显示」处理:所有记录(包括此条件隐藏该字段的记录)都仍要求填写。', // Bulk multi-select (Tier 2) 'designer.canvas.bulkSelected': '已选 {n} 项', 'designer.canvas.bulkMoveTo': '移至分组', From 8248f9ff5450a9de2fdced6792997cc93f94b639 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 05:09:32 +0000 Subject: [PATCH 13/17] docs(spec): regenerate the field, object and migration references for the visibleWhen describe Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt --- content/docs/references/data/field.mdx | 2 +- content/docs/references/data/object.mdx | 4 ++-- content/docs/references/system/migration.mdx | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/content/docs/references/data/field.mdx b/content/docs/references/data/field.mdx index 95639973fc3..e50ad7751a7 100644 --- a/content/docs/references/data/field.mdx +++ b/content/docs/references/data/field.mdx @@ -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'`. 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, while the form judges the formula value it last read and does not recompute it as the user edits; a read THROUGH a reference field, or a formula that reads through one or calls label() or can(), cannot be evaluated there. | +| **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, while the form judges the formula value it last read and does not recompute it as the user edits; 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 19ac21bec69..961155a6005 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -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'`. 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, while the form judges the formula value it last read and does not recompute it as the user edits; a read THROUGH a reference field, or a formula that reads through one or calls label() or can(), cannot be evaluated there. | +| **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, while the form judges the formula value it last read and does not recompute it as the user edits; 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. | @@ -663,7 +663,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'`. 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, while the form judges the formula value it last read and does not recompute it as the user edits; a read THROUGH a reference field, or a formula that reads through one or calls label() or can(), cannot be evaluated there. | +| **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, while the form judges the formula value it last read and does not recompute it as the user edits; 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 4228669eb8d..8a6be582378 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -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'`. 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, while the form judges the formula value it last read and does not recompute it as the user edits; a read THROUGH a reference field, or a formula that reads through one or calls label() or can(), cannot be evaluated there. | +| **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, while the form judges the formula value it last read and does not recompute it as the user edits; 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. | @@ -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'`. 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, while the form judges the formula value it last read and does not recompute it as the user edits; a read THROUGH a reference field, or a formula that reads through one or calls label() or can(), cannot be evaluated there. | +| **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, while the form judges the formula value it last read and does not recompute it as the user edits; 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. | From 6c0fd9ee4623fe382be1b8c6a60d2b968fa7e27c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 09:26:55 +0000 Subject: [PATCH 14/17] chore(spec): regenerate object.mdx reference after merging main The merge driver deferred content/docs/references/data/object.mdx; rebuilt from the merged spec with gen:schema && gen:docs, which restores main's action texts row beside this branch's visibleWhen describe. Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- content/docs/references/data/object.mdx | 1 + 1 file changed, 1 insertion(+) diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 961155a6005..9c7927e786c 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -502,6 +502,7 @@ const result = ApiMethod.parse(data); | **openIn** | `Enum<'self' \| 'new-tab'>` | optional | For type:'url' — where to open `target`. 'new-tab' opens a new browser tab; 'self' navigates in place. When omitted, external/absolute URLs open in a new tab and relative URLs navigate in place. Static execution option — keep it OUT of `params` (which is user-input-collection only). | | **body** | `{ language: 'expression'; source: string } \| { language: 'js'; source: string; capabilities?: Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log' \| …>[]; timeoutMs?: integer; … }` | optional | Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`. An action body runs as system, and its update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' is refused with PERMISSION_DENIED; an insert is not judged by this rule. | | **refusals** | `Record; params?: string[] }>` | optional | Refusal catalogue keyed by the SCREAMING_SNAKE code the action's js body throws: `{ message, status?, reasons?, params? }`. The body refuses by code only, optionally with a declared reason and params; the runtime answers with the declared message (translated through objects.``._actions.``.refusals.``.message, or globalActions.``.refusals.``.message for an object-less action, ….reasons.``.message for a reason, in the caller's locale, holes filled from params) and status. A code not declared here, or a reason a code with reasons does not declare, is refused loudly — at save when the body throws it literally, otherwise at run time. Only a type: 'script' action with a js body declares one | +| **texts** | `Record` | optional | Texts the action's js body writes into records, keyed by the snake_case key it asks for with ctx.text(KEY, params): `{ message, params? }`. ctx.text answers the sentence in the organization's language (the Localization setting when somebody set it, else the app's i18n.defaultLocale), translated through objects.``._actions.``.texts.``.message (globalActions.``.texts.``.message for an object-less action) with the declared message as the fallback, its holes filled from params. A key not declared here is refused — at save when the body asks for it literally, otherwise at run time. Only a type: 'script' action with a js body declares one | | **operation** | `Enum<'update'>` | optional | The declarative single-record field write, mirroring a list view's `bulkActionDefs`: `'update'` applies `patch` (merged under the collected `params`) to the current record on the data plane AS THE CALLER — never system-elevated — so the caller's permissions, the object's hooks and its validations fire as for a user edit. `type` stays at its default `'script'` (the platform action route the write is performed on); `target`/`body`/`method`/`bodyExtra` are refused beside it. `'delete'` and `'custom'` have no row-level form. | | **patch** | `Record` | optional | For `operation: 'update'` — static field values written to the current record, merged UNDER the user-supplied `params` so a fixed value can be declared without exposing it in the dialog. Written on the data plane as the caller: object permissions, hooks and validations fire as for a user edit. Refused on an action without `operation: 'update'` (it would be silently dropped). | | **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | The bulk dispatch contract this action's BODY is written for, in `bulkActionDefs`' own vocabulary: 'perRecord' = one dispatch per selected row carrying that row's `recordId` (the view's `bulkActions: ['']` bare-string form); 'aggregate' = ONE dispatch for the whole selection carrying every id in `params._selectedIds` (a `bulkActionDefs` entry with `execution: 'aggregate'`). Optional with NO default — omit it only when the body genuinely serves both. A list view wiring a declared action under the other contract is refused by `@objectstack/lint` (`action-dispatch-contract-mismatch`). | From aefc8aa2307f63c0320b4d6f9378e78a04a4c606 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 09:28:16 +0000 Subject: [PATCH 15/17] docs(adr): name the bare-root reach of the no-acting-user formula mark ADR-0137's note and ADR-0113's formula paragraph now say the 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), since the engine cannot separate the user-dependent part of such a read, and the result is the unconditional required. The server log reason says the same; the USER_SCOPE_ROOTS docblock keeps 'exact' for option visibility and calls the formula plan's reading conservative. Prose and a log string only; no logic change. Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- ...ired-write-contract-vs-column-constraint.md | 6 ++++-- ...7-predicate-fault-semantics-are-contract.md | 6 +++++- packages/objectql/src/engine-top-level.ts | 2 +- .../objectql/src/validation/rule-validator.ts | 18 +++++++++++------- 4 files changed, 21 insertions(+), 11 deletions(-) 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 0a34be0e2da..5ad61aa10b7 100644 --- a/docs/adr/0113-required-write-contract-vs-column-constraint.md +++ b/docs/adr/0113-required-write-contract-vs-column-constraint.md @@ -327,8 +327,10 @@ that does not compute is answered by the reason, in two arms: 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) on a write that has none, a - system write, where a read would compute it for its reader; or it reads such + 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 diff --git a/docs/adr/0137-predicate-fault-semantics-are-contract.md b/docs/adr/0137-predicate-fault-semantics-are-contract.md index ed0fb685b87..f8ed4e76271 100644 --- a/docs/adr/0137-predicate-fault-semantics-are-contract.md +++ b/docs/adr/0137-predicate-fault-semantics-are-contract.md @@ -160,7 +160,11 @@ makes "blank" a declared **third** state rather than a spelling of "no rule". > 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. A +> 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 diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index fe7960fba92..ad3e0edd11b 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -3223,7 +3223,7 @@ function unservableReason( // 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, and this write has none (a system write)', noActingUser: true }; + 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); diff --git a/packages/objectql/src/validation/rule-validator.ts b/packages/objectql/src/validation/rule-validator.ts index 1f4ad08912b..81e36fa744b 100644 --- a/packages/objectql/src/validation/rule-validator.ts +++ b/packages/objectql/src/validation/rule-validator.ts @@ -3099,13 +3099,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']; From e6f0dcb484ef54210f551dc60fc04c882df94fcc Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 09:38:35 +0000 Subject: [PATCH 16/17] docs: the form recomputes formulas now; correct the known-limit prose The form-side recompute (#35116) makes the object form renderer and the console form-view page compute formula fields over the record being edited before judging field rules. The ADR-0113 amendment's known-limit paragraph, the visibleWhen TSDoc and describe (and its three regenerated references), the formulaValues and evaluateRequiredWhenShown jsdoc and the changeset now say so, naming the formulas the form cannot compute. Prose only. Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- .changeset/34905-required-when-shown.md | 4 +-- content/docs/references/data/field.mdx | 2 +- content/docs/references/data/object.mdx | 4 +-- content/docs/references/system/migration.mdx | 4 +-- ...red-write-contract-vs-column-constraint.md | 29 ++++++++++++------- .../objectql/src/validation/rule-validator.ts | 13 +++++---- packages/spec/src/data/field.zod.ts | 9 +++--- 7 files changed, 37 insertions(+), 28 deletions(-) diff --git a/.changeset/34905-required-when-shown.md b/.changeset/34905-required-when-shown.md index 288651e8ad2..126c37393d0 100644 --- a/.changeset/34905-required-when-shown.md +++ b/.changeset/34905-required-when-shown.md @@ -25,9 +25,9 @@ The predicate is evaluated with the acting user bound as `current_user`, so a ro 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. -**Known limit: a formula-driven `visibleWhen`.** The form judges the predicate on the formula value it last read and does not recompute it while the user edits; the server judges the record being written. An edit that moves a formula into the condition (say, raising `amount` so `risk_level` becomes `'high'`) without filling the field is refused, naming a field the form still hides; 18.5.0 accepted that edit. A create inside such a condition was refused before and still is. Until the form recomputes formulas (a follow-up), read the formula's own inputs in the predicate, or fill the field in the same write. +**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 (the known limit above, and 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). +**`@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. diff --git a/content/docs/references/data/field.mdx b/content/docs/references/data/field.mdx index e50ad7751a7..6696ac79dc3 100644 --- a/content/docs/references/data/field.mdx +++ b/content/docs/references/data/field.mdx @@ -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'`. 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, while the form judges the formula value it last read and does not recompute it as the user edits; 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. | +| **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 9c7927e786c..75c9fbba046 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -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'`. 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, while the form judges the formula value it last read and does not recompute it as the user edits; 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. | +| **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. | @@ -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'`. 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, while the form judges the formula value it last read and does not recompute it as the user edits; 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. | +| **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 8a6be582378..79de59dda95 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -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'`. 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, while the form judges the formula value it last read and does not recompute it as the user edits; 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. | +| **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. | @@ -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'`. 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, while the form judges the formula value it last read and does not recompute it as the user edits; 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. | +| **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/0113-required-write-contract-vs-column-constraint.md b/docs/adr/0113-required-write-contract-vs-column-constraint.md index 5ad61aa10b7..a43161713fb 100644 --- a/docs/adr/0113-required-write-contract-vs-column-constraint.md +++ b/docs/adr/0113-required-write-contract-vs-column-constraint.md @@ -341,16 +341,23 @@ that does not compute is answered by the reason, in two arms: mark, since a formula reading the user is computed per writer on every write that has one. -**Known limit: the form does not recompute a formula.** The form judges the -predicate on the formula value it last read, over its live values -(`ruleRecord` in `form.tsx`); a create form has none, and an edit of the -formula's inputs does not move it. The server judges the record being -written. So on a create the form keeps a formula-driven field hidden while the -server may require it (main refused that create too), and an edit that moves -the computed value into the condition is refused naming a field the form still -hides; main accepted that edit. The server's answer is the one ruling item 2 -asks for; the form-side recompute is a follow-up card, and until it lands the -lint warns on every `required` field whose `visibleWhen` reads a formula. +**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. 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` or calls `can()` 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 @@ -362,7 +369,7 @@ 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 (the known limit above, and, when a formula in its read closure reads +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` diff --git a/packages/objectql/src/validation/rule-validator.ts b/packages/objectql/src/validation/rule-validator.ts index 81e36fa744b..b120d83937d 100644 --- a/packages/objectql/src/validation/rule-validator.ts +++ b/packages/objectql/src/validation/rule-validator.ts @@ -438,10 +438,11 @@ export interface EvaluateRulesOptions { * 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. That is not always the value the form shows: - * the form judges the formula value it last read and does not recompute it - * while the user edits (a create form has none), so a write that changes a - * formula's inputs can be judged on a value the form never showed. + * 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); @@ -3636,8 +3637,8 @@ function formulaReadsOf(pred: string | Expression, fields: Record { * 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 judges a formula on the value it last read and does not - * recompute it while the user edits, so for a formula-driven predicate the - * two sides can differ on a create or an edit of the formula's inputs. + * 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'`. 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, while the form judges the formula value it last read and does not recompute it as the user edits; 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."), + 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."), From 1ca9b694b54d06a376b2669d7c0d13c724679c38 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 11:24:05 +0000 Subject: [PATCH 17/17] docs: reword the formula-read warning for the form recompute; name the residual judges The lint warning and the Studio advisory on a required field whose visibleWhen reads a formula no longer say the form does not recompute it. The plain read is a reminder that the server's computed value decides, naming the checks that still compute none (a wizard's final-submit check, a form whose data source serves no object schema); the unservable arm says the form shows the field and keeps it required. ADR-0113 names the two residual form-side judges and the expression-masked case where the form can be stricter. Messages only: what fires is unchanged. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt --- ...red-write-contract-vs-column-constraint.md | 12 ++++++-- .../required-visible-when-formula-issue.ts | 30 +++++++++++-------- .../lint/src/validate-expressions.test.ts | 10 +++---- packages/lint/src/validate-expressions.ts | 7 +++-- .../inspectors/ObjectFieldInspector.tsx | 6 ++-- .../requiredVisibleWhenReference.ts | 28 +++++++++-------- ui/packages/i18n/src/namespaces/studio/en.ts | 4 +-- ui/packages/i18n/src/namespaces/studio/zh.ts | 4 +-- 8 files changed, 57 insertions(+), 44 deletions(-) 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 a43161713fb..11633b8914e 100644 --- a/docs/adr/0113-required-write-contract-vs-column-constraint.md +++ b/docs/adr/0113-required-write-contract-vs-column-constraint.md @@ -350,13 +350,19 @@ it judges the field rules: the object form renderer over its `ruleRecord` (`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. A formula the form cannot compute (it reads +`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` or calls `can()` the form can be stricter than -the server, which may compute it and hide the field. The server's answer is +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 diff --git a/packages/lint/src/required-visible-when-formula-issue.ts b/packages/lint/src/required-visible-when-formula-issue.ts index 79f560dfb8a..58f8ed19a9f 100644 --- a/packages/lint/src/required-visible-when-formula-issue.ts +++ b/packages/lint/src/required-visible-when-formula-issue.ts @@ -6,18 +6,21 @@ * * 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 gaps the author can see at build time: + * read of that record would serve. Two things the author can see at build time: * - * - **The form does not recompute a formula.** It judges the predicate on the - * formula value it last read, while the user edits, and a create form has - * none. A create, or an edit that moves the formula into the condition, is - * judged by the server on a value the form never showed, and can be refused - * naming a field the form keeps hidden. + * - **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 records the form hides it on included. The engine's + * 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 @@ -150,15 +153,16 @@ export function requiredVisibleWhenFormulaIssue( const named = formulas.map((f) => `'${f}'`).join(', '); let message = - `Field '${fname}' is \`required\`, and its \`visibleWhen\` reads the formula field ${named}. 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.`; + `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 ones the form hides it on included.`; + `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 ' + diff --git a/packages/lint/src/validate-expressions.test.ts b/packages/lint/src/validate-expressions.test.ts index 4a9231cfcd0..6d10b6f5017 100644 --- a/packages/lint/src/validate-expressions.test.ts +++ b/packages/lint/src/validate-expressions.test.ts @@ -6897,10 +6897,10 @@ describe('a `required` field\'s `visibleWhen` the server cannot use to lift the expect(issues[0].message).toContain('`storage.notNull: true`'); }); - // A formula the predicate reads: the form shows the value it last read and - // does not recompute it, 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 form does not recompute it', () => { + // 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' }, @@ -6909,7 +6909,7 @@ describe('a `required` field\'s `visibleWhen` the server cannot use to lift the 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('does not recompute it'); + 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'); }); diff --git a/packages/lint/src/validate-expressions.ts b/packages/lint/src/validate-expressions.ts index 563634a1a9a..6136eba4597 100644 --- a/packages/lint/src/validate-expressions.ts +++ b/packages/lint/src/validate-expressions.ts @@ -4376,9 +4376,10 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression severity: 'warning', }); } - // A `formula` the predicate reads: the form does not recompute it, and - // one the write path cannot compute keeps the field required on every - // write (`required-visible-when-formula-issue.ts`). + // 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); } 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 6d0d4e2b5ec..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 @@ -857,9 +857,9 @@ export function ObjectFieldInspector({ return out; }, [view]); const visibleWhenReferenceReads = useRequiredVisibleWhenReferenceReads(entry?.def ?? null, siblingTypes); - // …and a formula it reads is computed over the saved record there, while the - // form judges the value it last read; one the server cannot compute keeps it - // required on every save. + // …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; 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 index 794d9fe9b3f..199b1f4920a 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/requiredVisibleWhenReference.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/requiredVisibleWhenReference.ts @@ -30,15 +30,18 @@ * ## A `formula` the predicate reads * * The server computes each formula the predicate reads over the record being - * saved; the form judges the formula value it last read, does not recompute it - * while the user edits, and has none on a create. So a save can be - * refused naming a field the form keeps hidden, and the advisory says so 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, which the advisory - * says too; a `can` call 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 + * 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`. @@ -110,10 +113,9 @@ const LABEL_CALL = /\blabel\s*\(/; * 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: the form judges the predicate on the - * formula value it last read and does not recompute it, while the server - * judges the record being saved. An unservable one keeps the field required on - * every save. + * 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, diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 1545e3316a9..ac3d1ee2864 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -583,9 +583,9 @@ const STUDIO_EN: Record = { '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 shows the value it last read and does not recompute it while you edit (a new record has none), so a save can be refused naming this field while the form keeps it hidden. Read the formula\'s own inputs instead if the form should follow the edit.', + '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, including the ones this condition hides it on.', + '{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 8366da86a64..311a1f9d475 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -500,9 +500,9 @@ const STUDIO_ZH: Record = { 'designer.field.requiredVisibleWhenReference': '该字段为必填,服务器每次保存时按这条可见条件判断是否必填。条件经由引用字段 {fields} 读取关联记录,服务器在这里无法读取,因此按「显示」处理:所有记录(包括此条件隐藏该字段的记录)都仍要求填写。请改为读取本对象自己的字段。', 'designer.field.requiredVisibleWhenFormula': - '该字段为必填,服务器每次保存时按这条可见条件判断是否必填,其中的 {fields} 按要保存的记录计算。表单显示的是上次读取的公式值,编辑时不会重新计算(新建记录时没有值),因此保存可能因该字段被拒绝,而表单仍隐藏它。如需表单随编辑变化,请改为直接读取公式本身的输入字段。', + '该字段为必填,服务器每次保存时按这条可见条件判断是否必填,其中的 {fields} 按要保存的记录计算。表单在你编辑时也会同样计算该公式;但向导最后提交时的检查,以及数据源不提供对象定义的表单,用的是上次读取的公式值(新建记录时没有值),可能与服务器的判断不一致。', 'designer.field.requiredVisibleWhenFormulaUnservable': - '{fields} 经由引用字段读取、调用了 label() 或 current_user.can()(直接或通过其他公式),服务器保存时无法计算(current_user.can() 仅在保存未选择受权限控制的选项时无法计算),因此按「显示」处理:所有记录(包括此条件隐藏该字段的记录)都仍要求填写。', + '{fields} 经由引用字段读取、调用了 label() 或 current_user.can()(直接或通过其他公式),服务器保存时无法计算(current_user.can() 仅在保存未选择受权限控制的选项时无法计算),因此按「显示」处理:所有记录都仍要求填写。表单同样无法计算它:会显示该字段并保持必填。', // Bulk multi-select (Tier 2) 'designer.canvas.bulkSelected': '已选 {n} 项', 'designer.canvas.bulkMoveTo': '移至分组',