From 3875a770bd9eb61a8f92b1c12f801d7780a903fd Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 02:13:16 +0000 Subject: [PATCH 01/13] =?UTF-8?q?feat(spec,ui):=20uiReadonly=20/=20uiReado?= =?UTF-8?q?nlyWhen=20hand=20lock=20=E2=80=94=20spec=20keys=20and=20the=20d?= =?UTF-8?q?ialog=20surfaces=20(WIP)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXSuJCALDHFWaV6Bv5 --- packages/spec/src/data/field.zod.ts | 66 +++++++++++++ .../components/src/renderers/form/form.tsx | 13 ++- ui/packages/core/src/evaluator/fieldRules.ts | 33 ++++++- ui/packages/core/src/evaluator/handLock.ts | 97 +++++++++++++++++++ ui/packages/core/src/evaluator/index.ts | 1 + ui/packages/plugin-form/src/ObjectForm.tsx | 7 +- ui/packages/plugin-form/src/autoLayout.ts | 15 ++- ui/packages/plugin-form/src/sanitize.ts | 6 +- ui/packages/plugin-form/src/sectionFields.ts | 8 +- ui/packages/types/src/form.ts | 8 ++ ui/packages/types/src/zod/form.zod.ts | 2 + 11 files changed, 244 insertions(+), 12 deletions(-) create mode 100644 ui/packages/core/src/evaluator/handLock.ts diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index c346c229c2f..5882e31d81b 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -2915,6 +2915,22 @@ export const FieldSchema = lazySchema(() => { */ 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."), + /** + * The CONDITIONAL hand lock (ruling record 7180466652, the two-tier field-lock + * model): while TRUE no person edits the field at the console, and every + * other write keeps it. The conditional twin of `uiReadonly` — see there for + * which writes are "by hand". Same scope as `readonlyWhen`: the bound + * record's OWN columns, e.g. P`record.status != 'draft'`. + * + * Allowed beside `readonlyWhen` (unlike `uiReadonly` beside `readonly`): the + * two predicates can differ, and where `readonlyWhen` is TRUE the server lock + * is the stricter one — it also drops the field from non-system writes. + * + * Read by the console only, through the one hand-lock verdict in + * `@object-ui/core` (`fieldReadOnlyByHand`); the engine never reads it, so a + * TRUE predicate refuses no API, import, action or flow write. + */ + uiReadonlyWhen: EvaluatedExpressionInputSchema.optional().describe("Predicate (CEL) — the field is read-only BY HAND when TRUE: no console surface lets a person edit it (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit, kanban and calendar drag), while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key."), 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."), /** @@ -3046,6 +3062,38 @@ export const FieldSchema = lazySchema(() => { readonly: z.boolean().default(false).describe('Read-only — never editable in forms, AND server-enforced on BOTH write paths: a non-system write to this field is silently dropped from the payload on UPDATE and on INSERT (a create can no longer directly seed e.g. `approval_status: "approved"`), symmetric with `readonlyWhen`. A stripped INSERT field still falls back to its `defaultValue`. Exempt from the strip on BOTH paths: `isSystem` writes (seed replay, migration). Exempt on the UPDATE path ONLY: an opt-in "historical" import (`preserveAudit`) — which admits a whitelist (the audit/timestamp family plus author-declared business `readonly` fields). On INSERT the exemption does NOT apply: a non-system create that requests `preserveAudit` still has its readonly fields stripped, and is warned loudly that the exemption is UPDATE-only — replaying archival readonly facts on create requires a system context. A normal (non-system) import is NOT system-context and still strips.'), + /** + * The HAND lock (ruling record 7180466652, the two-tier field-lock model). + * `readonly` is the SERVER lock — no client may write the field. This is + * the lock below it: no PERSON edits the field by hand at the console, and + * every other write keeps it, judged by the object's validations exactly as + * an ordinary field (a `state_machine` rule included). It is the shape of a + * status that moves only through actions — an order confirmed or cancelled + * by its buttons, never typed. + * + * "By hand" = the create and edit dialogs and the payload they submit, the + * record page's inline edit, the highlight-strip chip, grid inline edit and + * its multi-row save, kanban drag between columns grouped by the field, and + * calendar drag. NOT by hand = REST create/update, import (the console import + * wizard included), declarative and script actions, flows. A console create + * leaves the field out, so the server applies its `defaultValue`; an API, + * import or action insert may set it, judged by validations (a state + * machine's `initialStates`). + * + * Refused beside `readonly: true` (the superRefine below): the server lock + * already keeps every client out, so the pair says two things at once. + * Absent reads as `false`; no default is materialised, so a field that does + * not author it parses unchanged. + * + * Read by the console only, through the one hand-lock verdict in + * `@object-ui/core` (`fieldReadOnlyByHand`); `describe_object` (MCP) reports + * it as its own key. The engine never reads it — no write is stripped or + * reported in `x-objectstack-dropped-fields` for it. Not a security + * boundary: a caller who may edit the object can write the field through + * the API; field permissions (`editable` on a permission set) are that. + */ + uiReadonly: z.boolean().optional().describe("Read-only BY HAND: no console surface lets a person edit the field (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit and multi-row save, kanban and calendar drag), while every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`; an API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`."), + /** * [ADR-0066 D3] Capabilities required to READ/EDIT this field. A field * declaring `requiredPermissions` is masked on read and denied on write unless @@ -3331,6 +3379,24 @@ export const FieldSchema = lazySchema(() => { }); } } + // The hand lock beside the server lock (ruling record 7180466652): a + // `readonly: true` field already keeps every client out, so `uiReadonly` + // beside it says two things at once — refused at every door that parses a + // field (`defineStack`, `os validate`, the metadata save). The conditional + // pair (`uiReadonlyWhen` beside `readonlyWhen`) is allowed: the predicates + // can differ, and the server lock is the stricter where both hold. + if (field.uiReadonly === true && field.readonly === true) { + ctx.addIssue({ + code: 'custom', + path: ['uiReadonly'], + message: + '`uiReadonly: true` locks the field against editing by hand at the console while API, import, action and ' + + 'flow writes keep it, and this field is also `readonly: true`, which keeps every client write out. Keep ' + + 'one: `readonly` when no client may write the field, `uiReadonly` when people at the console may not but ' + + 'actions, imports and the API may (each write judged by the object\'s validations).', + }); + } + // A required field is always asked for when a record is created: the // person creating the record sees every value the record must have, so // `showOnCreate: false` beside `required: true` is refused (#36425 item 6, diff --git a/ui/packages/components/src/renderers/form/form.tsx b/ui/packages/components/src/renderers/form/form.tsx index 00f6a5df323..5c24b3e979b 100644 --- a/ui/packages/components/src/renderers/form/form.tsx +++ b/ui/packages/components/src/renderers/form/form.tsx @@ -2187,6 +2187,7 @@ ComponentRegistry.register('form', // `readonly`, so it has nothing to evaluate it for. visibleWhen: isFailClosedSectionGate(f) ? undefined : (f as any).visibleWhen, readonlyWhen: isCreateForm ? undefined : (f as any).readonlyWhen, + uiReadonlyWhen: isCreateForm ? undefined : (f as any).uiReadonlyWhen, requiredWhen: (f as any).requiredWhen, }, ruleRecord, @@ -2262,6 +2263,7 @@ ComponentRegistry.register('form', { visibleWhen: gate ? undefined : visibleWhen, readonlyWhen: isCreateForm ? undefined : (f as any).readonlyWhen, + uiReadonlyWhen: isCreateForm ? undefined : (f as any).uiReadonlyWhen, requiredWhen: (f as any).requiredWhen, }, ruleRecord, @@ -2505,6 +2507,7 @@ ComponentRegistry.register('form', { visibleWhen: (f as any).visibleWhen, readonlyWhen: isCreateForm ? undefined : (f as any).readonlyWhen, + uiReadonlyWhen: isCreateForm ? undefined : (f as any).uiReadonlyWhen, requiredWhen: (f as any).requiredWhen, }, ruleRecord, @@ -3736,6 +3739,7 @@ ComponentRegistry.register('form', readonly: staticReadonly, visibleWhen, readonlyWhen, + uiReadonlyWhen, requiredWhen, ...fieldProps } = field; @@ -3804,7 +3808,14 @@ ComponentRegistry.register('form', // see `isFailClosedSectionGate`. const failClosedGate = isFailClosedSectionGate(field); const ruleState = resolveFieldRuleState( - { visibleWhen: failClosedGate ? undefined : visibleWhen, readonlyWhen: isCreateForm ? undefined : readonlyWhen, requiredWhen }, + { + visibleWhen: failClosedGate ? undefined : visibleWhen, + readonlyWhen: isCreateForm ? undefined : readonlyWhen, + // The hand lock's predicate (`Field.uiReadonlyWhen`), folded into the + // same read-only verdict; judged on an edit only, as `readonlyWhen`. + uiReadonlyWhen: isCreateForm ? undefined : uiReadonlyWhen, + requiredWhen, + }, ruleRecord, { required: staticRequired, diff --git a/ui/packages/core/src/evaluator/fieldRules.ts b/ui/packages/core/src/evaluator/fieldRules.ts index f7e06a716bc..9a26645def9 100644 --- a/ui/packages/core/src/evaluator/fieldRules.ts +++ b/ui/packages/core/src/evaluator/fieldRules.ts @@ -403,6 +403,8 @@ const REQUIRED_WHEN_ABSENT = false; export interface FieldRuleFaults { visibleWhen?: string; readonlyWhen?: string; + /** The hand lock's predicate (`@objectstack/spec` `Field.uiReadonlyWhen`); fail-open, as `readonlyWhen`. */ + uiReadonlyWhen?: string; requiredWhen?: string; } @@ -462,10 +464,24 @@ export function resolveFieldRuleState( rules: { visibleWhen?: FieldRulePredicate; readonlyWhen?: FieldRulePredicate; + /** + * The HAND lock's predicate (`@objectstack/spec` `Field.uiReadonlyWhen`, + * ruling record 7180466652): folded into the same `readonly` verdict, since + * every caller of this function is a console surface a person edits + * through. Fail-open on a fault, as `readonlyWhen`. + */ + uiReadonlyWhen?: FieldRulePredicate; requiredWhen?: FieldRulePredicate; }, record: Record, - statics: { required?: boolean; readonly?: boolean; serverOwnedValue?: boolean; name?: string }, + statics: { + required?: boolean; + readonly?: boolean; + /** The static hand lock (`Field.uiReadonly`): read-only on every console surface. */ + uiReadonly?: boolean; + serverOwnedValue?: boolean; + name?: string; + }, previous?: Record, scope?: Record, fieldContext?: string, @@ -499,8 +515,13 @@ export function resolveFieldRuleState( ) : VISIBLE_WHEN_ABSENT; + // The server lock (`readonly` / `readonlyWhen`) and the hand lock + // (`uiReadonly` / `uiReadonlyWhen`) answer one question here — "may a person + // edit this field now" — so they fold into one verdict. Short-circuited in + // that order: a predicate the verdict no longer needs never runs. const readonly = statics.readonly === true || + statics.uiReadonly === true || (rules.readonlyWhen != null ? evalFieldPredicate( rules.readonlyWhen, @@ -510,6 +531,16 @@ export function resolveFieldRuleState( scope, diag('readonlyWhen'), ) + : READONLY_WHEN_ABSENT) || + (rules.uiReadonlyWhen != null + ? evalFieldPredicate( + rules.uiReadonlyWhen, + record, + READONLY_WHEN_FAULTED, + previous, + scope, + diag('uiReadonlyWhen'), + ) : READONLY_WHEN_ABSENT); // Short-circuited, not evaluated-and-discarded: the verdict cannot depend on diff --git a/ui/packages/core/src/evaluator/handLock.ts b/ui/packages/core/src/evaluator/handLock.ts new file mode 100644 index 00000000000..f369e12325e --- /dev/null +++ b/ui/packages/core/src/evaluator/handLock.ts @@ -0,0 +1,97 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * "May a person edit this field by hand, now?" — the ONE answer every console + * surface a person edits through reads (ruling record 7180466652, the + * two-tier field-lock model of `@objectstack/spec` `Field`). + * + * Two locks, two tiers each: + * + * | | server lock — no client writes | hand lock — no person edits at the console | + * |:------------|:-------------------------------|:-------------------------------------------| + * | always | `readonly` | `uiReadonly` | + * | conditional | `readonlyWhen` | `uiReadonlyWhen` | + * + * Both tiers lock a hand surface, so this verdict folds all four. Only the + * server lock is read on the write path (objectql); the hand lock is read here + * and nowhere on the server, so API, import, action and flow writes keep a + * hand-locked field and the object's validations judge them. + * + * The hand surfaces (each reads this module, never `def.readonly` alone): the + * create and edit dialogs and the payload they submit, the record page's + * inline edit, the highlight-strip chip, grid inline edit and its multi-row + * save, kanban drag between columns grouped by the field, and calendar drag. + * NOT hand surfaces, and so still on the raw `readonly` read: the import + * wizard's target mapping (an import keeps the write) and the Studio/designer + * authoring reads (they describe the declaration, not a person's edit). + * + * The predicate halves run through {@link resolveFieldRuleState}, the one + * evaluator of field-level CEL, so a predicate here means what it means on + * the form; a predicate that cannot be evaluated leaves the field editable, + * as `readonlyWhen` does everywhere on the client (the server decides). + */ +import { resolveFieldRuleState, type FieldRulePredicate } from './fieldRules.js'; + +/** The field-lock keys of a field definition this verdict reads. */ +export interface FieldHandLockDef { + readonly?: unknown; + readonlyWhen?: unknown; + uiReadonly?: unknown; + uiReadonlyWhen?: unknown; +} + +/** Optional evaluation context for the predicate halves. */ +export interface FieldHandLockContext { + /** The stored row an edit starts from, bound as `previous`. */ + previous?: Record; + /** The host shell's predicate scope (`current_user` and friends). */ + scope?: Record; + /** Locator for a fault warning, e.g. `"field 'status'"`. */ + fieldContext?: string; +} + +/** + * The STATIC half: true when the field is read-only by hand on every record — + * `readonly: true` or `uiReadonly: true`. For a surface that decides before it + * has a record (which columns a create dialog lists, which fields a payload may + * carry); a surface that has the record reads {@link fieldReadOnlyByHand}. + */ +export function fieldStaticallyReadOnlyByHand(def: FieldHandLockDef | null | undefined): boolean { + return def?.readonly === true || def?.uiReadonly === true; +} + +/** True when the field declares a conditional lock of either tier. */ +export function fieldHasConditionalHandLock(def: FieldHandLockDef | null | undefined): boolean { + return def?.readonlyWhen != null || def?.uiReadonlyWhen != null; +} + +/** + * The FULL verdict over one record: the static half, or `readonlyWhen` / + * `uiReadonlyWhen` TRUE over `record`. With no record the predicates are + * judged over an empty one (a column-level question, answered fail-open). + */ +export function fieldReadOnlyByHand( + def: FieldHandLockDef | null | undefined, + record?: Record | null, + context: FieldHandLockContext = {}, +): boolean { + if (fieldStaticallyReadOnlyByHand(def)) return true; + if (!fieldHasConditionalHandLock(def)) return false; + return resolveFieldRuleState( + { + readonlyWhen: (def?.readonlyWhen ?? undefined) as FieldRulePredicate | undefined, + uiReadonlyWhen: (def?.uiReadonlyWhen ?? undefined) as FieldRulePredicate | undefined, + }, + record ?? {}, + {}, + context.previous, + context.scope, + context.fieldContext, + ).readonly; +} diff --git a/ui/packages/core/src/evaluator/index.ts b/ui/packages/core/src/evaluator/index.ts index 4aac1357c75..3ab3005925e 100644 --- a/ui/packages/core/src/evaluator/index.ts +++ b/ui/packages/core/src/evaluator/index.ts @@ -11,6 +11,7 @@ export * from './ExpressionEvaluator.js'; export * from './predicateInput.js'; export * from './declaredPredicate.js'; export * from './fieldRules.js'; +export * from './handLock.js'; export { planObjectFormulas, type ObjectFormulaPlan } from './formulaRecord.js'; // Named, not `export *`: `SUBJECT_PERMISSIONS`, `SUBJECT_CAPABILITIES` stay in // the module for its in-package readers and off the public entry diff --git a/ui/packages/plugin-form/src/ObjectForm.tsx b/ui/packages/plugin-form/src/ObjectForm.tsx index 05a4d93583c..620a604403f 100644 --- a/ui/packages/plugin-form/src/ObjectForm.tsx +++ b/ui/packages/plugin-form/src/ObjectForm.tsx @@ -21,7 +21,7 @@ import { pickLocalized, useObjectTranslation, useLocalization, withHomeAmountSou import { useRecordInvalidation } from './recordInvalidation'; import { useReportedDirtyChange } from './formDirtyReport'; import { mapFieldTypeToFormType, buildValidationRules, formatFileSize, fieldHelpText, withFollowedParentObject, withFormObject, PERMISSION_SET_GRANT_COLUMNS } from '@object-ui/fields'; -import { isExpressionComputedField } from '@object-ui/core'; +import { fieldStaticallyReadOnlyByHand, isExpressionComputedField } from '@object-ui/core'; import { useIsMobile, toast, FormSectionNavContext } from '@object-ui/components'; import { resolveSuccessNavigate } from './successBehavior'; import { resolveSubmitRedirect, submitRedirectScope } from './submitRedirect'; @@ -1006,7 +1006,8 @@ const SimpleObjectForm: React.FC<{ schema: LocalizedObjectFormSchema; dataSource required: isRequiredInForm(field, isCreateFormMode(schema)), // `_draftOnly`: a field only the draft declares, under the console's // draft preview — drawn, never fillable (see `fromObjectSchema`). - disabled: schema.readOnly || schema.mode === 'view' || field.readonly || field._draftOnly === true, + // `uiReadonly` is the hand lock: drawn, never filled by a person. + disabled: schema.readOnly || schema.mode === 'view' || fieldStaticallyReadOnlyByHand(field) || field._draftOnly === true, placeholder: field.placeholder, // The help line under the control: the spec's `inlineHelpText`, // else `description`, through the one read `fromObjectSchema` @@ -1019,6 +1020,8 @@ const SimpleObjectForm: React.FC<{ schema: LocalizedObjectFormSchema; dataSource // engine (same dialect the server enforces). Undefined when absent. visibleWhen: field.visibleWhen, readonlyWhen: field.readonlyWhen, + // The hand lock's predicate, folded with `readonlyWhen` by the form renderer. + uiReadonlyWhen: field.uiReadonlyWhen, requiredWhen: field.requiredWhen, // Field-group membership (Field.group → object.fieldGroups[].key). // Carried through so the form can auto-derive sections from the diff --git a/ui/packages/plugin-form/src/autoLayout.ts b/ui/packages/plugin-form/src/autoLayout.ts index 2fd92d91053..ca6bc3b8a18 100644 --- a/ui/packages/plugin-form/src/autoLayout.ts +++ b/ui/packages/plugin-form/src/autoLayout.ts @@ -17,7 +17,7 @@ */ import type { FormField } from '@object-ui/types'; -import { isExpressionComputedField } from '@object-ui/core'; +import { fieldStaticallyReadOnlyByHand, isExpressionComputedField } from '@object-ui/core'; import { SERVER_OWNED_FIELD_NAMES } from './sanitize'; /** FormField types that are computed/aggregate and must be excluded from modal edit/create forms */ @@ -286,8 +286,11 @@ export function filterSystemFields( // textarea into the edit dialog. Applied in create AND edit. if (objField?.hidden === true) return false; // Also drop fields the schema explicitly marks readonly — these are - // platform-managed (e.g. id alias, formula result columns). - if (objField?.readonly === true) return false; + // platform-managed (e.g. id alias, formula result columns) — and fields + // hand-locked by `uiReadonly`: no person edits them in a dialog, so + // neither dialog draws an input for them (`fieldStaticallyReadOnlyByHand`, + // the one hand-lock read in `@object-ui/core`). + if (fieldStaticallyReadOnlyByHand(objField)) return false; return true; }); } @@ -327,8 +330,10 @@ export function filterCreateModeFields( const objField = objectSchema.fields[field.name]; if (!objField) return true; // keep fields not in schema (custom fields) - // Drop fields the schema declares as readonly — they are auto-managed. - if (objField.readonly === true) return false; + // Drop fields the schema declares as readonly — they are auto-managed — + // and hand-locked (`uiReadonly`) fields: a console create leaves them out + // and the server applies their `defaultValue`. + if (fieldStaticallyReadOnlyByHand(objField)) return false; return !isAutoGeneratedFieldType(objField.type) && !isExpressionComputedField(objField); }); diff --git a/ui/packages/plugin-form/src/sanitize.ts b/ui/packages/plugin-form/src/sanitize.ts index 8ad76d92e58..00e2c5dad4d 100644 --- a/ui/packages/plugin-form/src/sanitize.ts +++ b/ui/packages/plugin-form/src/sanitize.ts @@ -6,6 +6,8 @@ * LICENSE file in the root directory of this source tree. */ +import { fieldStaticallyReadOnlyByHand } from '@object-ui/core'; + /** * The refused-field roster: every field name the SERVER owns on write. * @@ -199,7 +201,9 @@ function stripUnwritable( const t = String(fieldDef.type || '').toLowerCase(); if (COMPUTED_FIELD_TYPES.has(t)) continue; if (fieldDef.computed === true) continue; - if (fieldDef.readOnly === true || fieldDef.readonly === true) continue; + // A hand-locked field (`uiReadonly`) is never in a dialog's payload + // either: a person cannot edit it, so a dialog never writes it. + if (fieldDef.readOnly === true || fieldStaticallyReadOnlyByHand(fieldDef)) continue; } out[key] = value; diff --git a/ui/packages/plugin-form/src/sectionFields.ts b/ui/packages/plugin-form/src/sectionFields.ts index f1a74df5666..bea5dff9e07 100644 --- a/ui/packages/plugin-form/src/sectionFields.ts +++ b/ui/packages/plugin-form/src/sectionFields.ts @@ -41,7 +41,7 @@ */ import type { FormField } from '@object-ui/types'; -import { evalFieldPredicate, isBlankPredicateText, isExpressionComputedField, type FieldRulePredicate } from '@object-ui/core'; +import { evalFieldPredicate, fieldStaticallyReadOnlyByHand, isBlankPredicateText, isExpressionComputedField, type FieldRulePredicate } from '@object-ui/core'; import { mapFieldTypeToFormType, buildValidationRules, fieldHelpText, withFollowedParentObject, withFormObject } from '@object-ui/fields'; import { withHomeAmountSource } from '@object-ui/i18n'; import { isCreateFormMode, isRequiredInForm } from './schemaDefaults'; @@ -341,7 +341,8 @@ export function fromObjectSchema(fieldName: string, ctx: SectionFieldsContext): // out of every write): an underscore-private convention between two of // this repository's packages, never an authoring key. It is drawn disabled // rather than `readonly`, which `filterSystemFields` drops before render. - disabled: ctx.readOnly || ctx.mode === 'view' || field.readonly || field._draftOnly === true, + // `uiReadonly` is the hand lock: the dialog draws the field, never fills it. + disabled: ctx.readOnly || ctx.mode === 'view' || fieldStaticallyReadOnlyByHand(field) || field._draftOnly === true, placeholder: field.placeholder, // The help line under the control: the spec's `inlineHelpText`, else // `description`, through the one read `ObjectForm`'s field builder shares @@ -369,6 +370,9 @@ export function fromObjectSchema(fieldName: string, ctx: SectionFieldsContext): // silently dropped rules that the flat (schema-order) form honors. visibleWhen: field.visibleWhen, readonlyWhen: field.readonlyWhen, + // The hand lock's predicate (`Field.uiReadonlyWhen`): the form renderer + // folds it into the same read-only verdict as `readonlyWhen`. + uiReadonlyWhen: field.uiReadonlyWhen, requiredWhen: field.requiredWhen, // A stored field carrying an `expression` is computed by the engine on // every write, so a typed value never stands (objectstack#31759): it draws diff --git a/ui/packages/types/src/form.ts b/ui/packages/types/src/form.ts index c88feb4cedd..a1c190205c8 100644 --- a/ui/packages/types/src/form.ts +++ b/ui/packages/types/src/form.ts @@ -1915,6 +1915,14 @@ export interface FormField { * @example "record.status == 'paid'" */ readonlyWhen?: string | { dialect?: string; source: string }; + /** + * CEL predicate: when TRUE the field is read-only BY HAND — the form draws it + * and a person cannot edit it, while API, import, action and flow writes keep + * it (no server strip). Aligns with @objectstack/spec Field.uiReadonlyWhen + * and folds into the same read-only verdict as `readonlyWhen`. Fails open. + * @example "record.status != 'draft'" + */ + uiReadonlyWhen?: string | { dialect?: string; source: string }; /** * CEL predicate: when TRUE the field is required (the server enforces the * same rule in its rule-validator). Aligns with @objectstack/spec diff --git a/ui/packages/types/src/zod/form.zod.ts b/ui/packages/types/src/zod/form.zod.ts index a0f8507f925..9220276f02a 100644 --- a/ui/packages/types/src/zod/form.zod.ts +++ b/ui/packages/types/src/zod/form.zod.ts @@ -1126,6 +1126,8 @@ export const FormFieldSchema = z.looseObject({ .describe('Field-level visibility rule (CEL) — field shown only when TRUE'), readonlyWhen: FieldRulePredicateWireSchema.optional() .describe('Field-level read-only rule (CEL)'), + uiReadonlyWhen: FieldRulePredicateWireSchema.optional() + .describe('Field-level hand-lock rule (CEL) — read-only by hand when TRUE, writes through the API keep it'), requiredWhen: FieldRulePredicateWireSchema.optional() .describe('Field-level required rule (CEL)'), colSpan: z.number().optional().describe('Column span in grid layout (legacy — prefer span)'), From 6361492c4cddb65b0cdd060a360d58174929f3fc Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 02:19:25 +0000 Subject: [PATCH 02/13] feat(ui,mcp): hand-lock verdict on every hand surface; describe_object reports uiReadonly / uiReadonlyWhen (WIP) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXSuJCALDHFWaV6Bv5 --- packages/mcp/src/mcp-http-tools.ts | 4 ++- packages/mcp/src/mcp-server-runtime.ts | 23 ++++++++++++++++ packages/runtime/src/domains/mcp.ts | 22 ++++++++++++++++ .../src/utils/editFormLockedByState.ts | 3 ++- ui/packages/fields/src/requiredWhenPrompt.ts | 5 +++- .../plugin-calendar/src/ObjectCalendar.tsx | 26 +++++++++++++++++-- .../plugin-detail/src/DetailSection.tsx | 7 +++-- .../plugin-detail/src/HeaderHighlight.tsx | 6 +++-- .../plugin-detail/src/InlineEditSaveBar.tsx | 7 ++--- .../plugin-detail/src/RecordDetailPanel.tsx | 5 ++-- ui/packages/plugin-detail/src/RelatedList.tsx | 6 +++-- .../src/renderers/recordPathStageChange.tsx | 9 +++++-- ui/packages/plugin-form/src/WizardForm.tsx | 1 + ui/packages/plugin-grid/src/ObjectGrid.tsx | 1 + .../plugin-grid/src/inline-edit-options.ts | 11 ++++---- .../plugin-grid/src/objectGridCellFacts.ts | 11 +++++++- .../src/objectGridRequiredPrompt.tsx | 4 +-- .../plugin-kanban/src/ObjectKanban.tsx | 25 ++++++++++++++++-- 18 files changed, 148 insertions(+), 28 deletions(-) diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 4a867dae7a8..abd03aed691 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -3852,7 +3852,9 @@ export function registerObjectTools( description: 'Get the schema of a data object as you may read it, with what a write needs: name, label, description; ' + 'each field\'s name, type, label, description (where set: the author\'s, or the platform\'s on a column ' - + 'it injects), required, readonly (leave it out of a write), system, ' + + 'it injects), required, readonly (leave it out of a write), uiReadonly / uiReadonlyWhen where set ' + + '(a person cannot edit the field at the console; your write may still set it, judged by the ' + + 'validations), system, ' + 'options (send the value) and defaultValue (omit the field to get it; never copy the value); the active ' + 'validations; the enabled features. readonly is the schema\'s, not your edit permission.', inputSchema: strictToolInput( diff --git a/packages/mcp/src/mcp-server-runtime.ts b/packages/mcp/src/mcp-server-runtime.ts index 49cfccdfc04..03de461c0ba 100644 --- a/packages/mcp/src/mcp-server-runtime.ts +++ b/packages/mcp/src/mcp-server-runtime.ts @@ -168,6 +168,7 @@ export function describeServedObject(def: ServedObjectDef, declared: ServedObjec // is read there; the served definition, without that expression, is // what the answer is built from. readonly: writeNeverSetsField(declared.fields?.[key]), + ...describedHandLock(f), system: f?.system === true, ...(declaresOptions(f) ? { options: describedOptions(f.options as unknown[]) } : {}), ...(f?.defaultValue !== undefined ? { defaultValue: f.defaultValue } : {}), @@ -177,6 +178,28 @@ export function describeServedObject(def: ServedObjectDef, declared: ServedObjec }; } +/** + * The HAND lock as `describe_object` serves it (ruling record 7180466652, the + * two-tier field-lock model): `uiReadonly: true` and the `uiReadonlyWhen` + * predicate text, each its own key and only where the field authors it, so a + * definition that authors neither keeps the shape it always had. ⛔ Never + * folded into `readonly`: that key tells an agent to leave the field out of a + * write, and a hand-locked field is exactly the one an agent's write (an API, + * import or action write) still sets, judged by the object's validations — a + * person at the console cannot edit it. Read off the served field. + * + * The twin is `describedHandLock` in `packages/runtime/src/domains/mcp.ts`. + */ +function describedHandLock(f: unknown): { uiReadonly?: true; uiReadonlyWhen?: string } { + const field = (f ?? {}) as { uiReadonly?: unknown; uiReadonlyWhen?: unknown }; + const when = field.uiReadonlyWhen as string | { source?: unknown } | undefined; + const source = typeof when === 'string' ? when : typeof when?.source === 'string' ? when.source : undefined; + return { + ...(field.uiReadonly === true ? { uiReadonly: true as const } : {}), + ...(source !== undefined && source.trim() !== '' ? { uiReadonlyWhen: source } : {}), + }; +} + /** * [#34721] An object's or a field's `description` as `list_objects` and * `describe_object` serve it: `{ description }` when the definition, as the diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index ede5c42baca..2625ebb73b0 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -757,6 +757,7 @@ function describeServedObject(def: any, declared: any): Record // field. Only the boolean is read there; the served definition, // without that expression, is what the answer is built from. readonly: writeNeverSetsField(declared?.fields?.[k]), + ...describedHandLock(f), system: f?.system === true, ...(declaresOptions(f) ? { options: describedOptions(f.options) } : {}), ...(f?.defaultValue !== undefined ? { defaultValue: f.defaultValue } : {}), @@ -766,6 +767,27 @@ function describeServedObject(def: any, declared: any): Record }; } +/** + * The HAND lock as `describe_object` serves it (ruling record 7180466652, the + * two-tier field-lock model): `uiReadonly: true` and the `uiReadonlyWhen` + * predicate text, each its own key and only where the field authors it, so a + * definition that authors neither keeps the shape it always had. ⛔ Never + * folded into `readonly`: that key tells an agent to leave the field out of a + * write, and a hand-locked field is exactly the one an agent's write (an API, + * import or action write) still sets, judged by the object's validations — a + * person at the console cannot edit it. Read off the served field. + * + * The twin is `describedHandLock` in `packages/mcp/src/mcp-server-runtime.ts`. + */ +function describedHandLock(f: any): { uiReadonly?: true; uiReadonlyWhen?: string } { + const when = f?.uiReadonlyWhen; + const source = typeof when === 'string' ? when : typeof when?.source === 'string' ? when.source : undefined; + return { + ...(f?.uiReadonly === true ? { uiReadonly: true as const } : {}), + ...(source !== undefined && source.trim() !== '' ? { uiReadonlyWhen: source } : {}), + }; +} + /** * [#35137] The field names a {@link describeServedObject} answer lists, in its * order: the served-schema half of `fieldVisibilityOf`. The stdio twin is diff --git a/ui/packages/app-shell/src/utils/editFormLockedByState.ts b/ui/packages/app-shell/src/utils/editFormLockedByState.ts index 27e2eb65b76..b75ae4615fe 100644 --- a/ui/packages/app-shell/src/utils/editFormLockedByState.ts +++ b/ui/packages/app-shell/src/utils/editFormLockedByState.ts @@ -94,7 +94,8 @@ export function editFormLockedByState( const staticReadonly = isExpressionComputedField(def) || (typeof def.type === 'string' && isAutoGeneratedFieldType(def.type)); const state = resolveFieldRuleState( - { visibleWhen: def.visibleWhen, readonlyWhen: def.readonlyWhen }, + // The form folds the hand lock's predicate into the same verdict, so this does too. + { visibleWhen: def.visibleWhen, readonlyWhen: def.readonlyWhen, uiReadonlyWhen: def.uiReadonlyWhen }, ruleRecord, { readonly: staticReadonly, name }, ruleRecord, diff --git a/ui/packages/fields/src/requiredWhenPrompt.ts b/ui/packages/fields/src/requiredWhenPrompt.ts index 94c899a81b5..547a99d0964 100644 --- a/ui/packages/fields/src/requiredWhenPrompt.ts +++ b/ui/packages/fields/src/requiredWhenPrompt.ts @@ -142,6 +142,9 @@ export function collectRequiredWhenPromptFields( { visibleWhen: def.visibleWhen as never, readonlyWhen: def.readonlyWhen as never, + // The hand lock folds into the same read-only verdict: a person is + // never asked to fill a field they may not edit (`uiReadonlyWhen`). + uiReadonlyWhen: def.uiReadonlyWhen as never, requiredWhen: def.requiredWhen as never, }, next, @@ -150,7 +153,7 @@ export function collectRequiredWhenPromptFields( // gate (objectstack#30220). A record already inside the gate without // the value rests there, the engine lets the write through, and nothing // is asked. - { required: def.required === true, readonly: def.readonly === true, name }, + { required: def.required === true, readonly: def.readonly === true, uiReadonly: def.uiReadonly === true, name }, // The stored record, so a predicate reading `previous.*` sees what the // form would show it. record, diff --git a/ui/packages/plugin-calendar/src/ObjectCalendar.tsx b/ui/packages/plugin-calendar/src/ObjectCalendar.tsx index 7e60adc5fa2..91fe779972e 100644 --- a/ui/packages/plugin-calendar/src/ObjectCalendar.tsx +++ b/ui/packages/plugin-calendar/src/ObjectCalendar.tsx @@ -77,6 +77,8 @@ import { toast, } from '@object-ui/components'; import { + fieldReadOnlyByHand, + fieldStaticallyReadOnlyByHand, buildExpandFields, convertSortToQueryParams, getRecordDisplayName, @@ -1290,6 +1292,13 @@ export const ObjectCalendar: React.FC = ({ }; const quickCreateGranted = resolveAffordance('calendarQuickCreate', writeAffordanceSource).allowed; const rescheduleGranted = resolveAffordance('calendarReschedule', writeAffordanceSource).allowed; + // The static half of the one hand-lock verdict on the date fields a drag + // writes (`readonly` / `uiReadonly`): a locked start field closes the drag, a + // locked end field the resize handle. The conditional half is judged per + // record at the drop (`handleEventDropDefault`). + const lockFieldDefs = objectSchema?.fields as Record | undefined> | undefined; + const startFieldLocked = !!calendarConfig && fieldStaticallyReadOnlyByHand(lockFieldDefs?.[calendarConfig.startDateField]); + const endFieldLocked = !!calendarConfig?.endDateField && fieldStaticallyReadOnlyByHand(lockFieldDefs?.[calendarConfig.endDateField]); // Default drag-to-reschedule handler. When the caller hasn't provided an // `onEventDrop`, persist the new dates back to the data source so dragging @@ -1318,6 +1327,19 @@ export const ObjectCalendar: React.FC = ({ return; } + // A drag is an edit by hand: a date field locked over THIS record — the + // one hand-lock verdict (`readonlyWhen`, the hand lock `uiReadonlyWhen`; + // the static half closed the gesture below) — takes no write, and a fresh + // array identity puts the event back where the record has it. + const lockDefs = objectSchema?.fields as Record | undefined> | undefined; + if ( + fieldReadOnlyByHand(lockDefs?.[startDateField], record) || + (writesEnd && fieldReadOnlyByHand(lockDefs?.[endDateField as string], record)) + ) { + setData((prev) => prev.slice()); + return; + } + // A `date` field is written as the calendar day, a `datetime` as the // instant (objectui#10866, `toStoredDateValue`). The month grid moves a // value by calendar days and keeps its time of day (objectui#11005), so a @@ -1755,7 +1777,7 @@ export const ObjectCalendar: React.FC = ({ onEventDrop={ onEventDrop ? (event, newStart, newEnd) => onEventDrop(event.data, newStart, newEnd) - : rescheduleGranted + : rescheduleGranted && !startFieldLocked ? (event, newStart, newEnd) => { void handleEventDropDefault(event.data, newStart, newEnd); } @@ -1764,7 +1786,7 @@ export const ObjectCalendar: React.FC = ({ onTimeRangeSelect={rangeSelectCreate} // With no `endDateField` the end is not stored, so no gesture may // move it on its own: no resize-end handle is drawn. - endEditable={Boolean(calendarConfig.endDateField)} + endEditable={Boolean(calendarConfig.endDateField) && !endFieldLocked} /> {/* objectui#7210 — a month drawn from the first N rows of a larger set diff --git a/ui/packages/plugin-detail/src/DetailSection.tsx b/ui/packages/plugin-detail/src/DetailSection.tsx index 42111f04454..99f060eee12 100644 --- a/ui/packages/plugin-detail/src/DetailSection.tsx +++ b/ui/packages/plugin-detail/src/DetailSection.tsx @@ -35,7 +35,7 @@ import { useRecordContext, useRecordPagePreferences, } from '@object-ui/react'; -import { resolveFieldAffordance, isDeadlineSettled } from '@object-ui/core'; +import { fieldReadOnlyByHand, resolveFieldAffordance, isDeadlineSettled } from '@object-ui/core'; import { withHomeAmountSource } from '@object-ui/i18n'; import { usePermissions } from '@object-ui/permissions'; import { @@ -648,7 +648,10 @@ export const DetailSection: React.FC = ({ // framework flags `readonly:true` even when the view schema doesn't). And // never offer inline edit on immutable audit/identity fields by name // (created_at / id / …), in case a schema surfaces one as a section row. - const isReadonly = field.readonly === true || objectDefField?.readonly === true; + // The object field's lock goes through the one hand-lock verdict — `readonly`, + // `readonlyWhen`, `uiReadonly`, `uiReadonlyWhen` over this record + // (`fieldReadOnlyByHand`, `@object-ui/core`) — never `readonly` alone. + const isReadonly = field.readonly === true || fieldReadOnlyByHand(objectDefField, data); const isSystemField = NON_EDITABLE_SYSTEM_FIELDS.has(field.name); // Types the fields package excludes from in-place editing — the SAME // alias-aware contract the grid consults, not a second list (objectui#4221). diff --git a/ui/packages/plugin-detail/src/HeaderHighlight.tsx b/ui/packages/plugin-detail/src/HeaderHighlight.tsx index 5d4b2d6e6a6..f46587e879d 100644 --- a/ui/packages/plugin-detail/src/HeaderHighlight.tsx +++ b/ui/packages/plugin-detail/src/HeaderHighlight.tsx @@ -17,7 +17,7 @@ import { TooltipTrigger, } from '@object-ui/components'; import type { HighlightField } from '@object-ui/types'; -import { EXPANDABLE_FIELD_TYPES, resolveFieldAffordance, isDeadlineSettled } from '@object-ui/core'; +import { EXPANDABLE_FIELD_TYPES, fieldReadOnlyByHand, resolveFieldAffordance, isDeadlineSettled } from '@object-ui/core'; import { usePermissions } from '@object-ui/permissions'; import { getCellRenderer, resolveCellRendererType, useBooleanValueLabel } from '@object-ui/fields'; import { useSafeFieldLabel, useInlineEdit, usePredicateScope } from '@object-ui/react'; @@ -223,8 +223,10 @@ export const HeaderHighlight: React.FC = ({ // keeps its display precedence for renderer selection just below. // A stored field carrying an `expression` is computed too (objectstack#31759). const isComputed = isComputedDetailField(field.type, objectDefField); + // The object field's lock is the one hand-lock verdict over this + // record (`fieldReadOnlyByHand`), as the details body reads it. const isReadonly = - field.readonly === true || objectDefField?.readonly === true; + field.readonly === true || fieldReadOnlyByHand(objectDefField, data); const isSystem = NON_EDITABLE_SYSTEM_FIELDS.has(field.name); // Same shared exclusion the details body and the grid consult, so a // credential chip never opens the plain text editor that would show diff --git a/ui/packages/plugin-detail/src/InlineEditSaveBar.tsx b/ui/packages/plugin-detail/src/InlineEditSaveBar.tsx index 3e6c649cac6..9eb108db3eb 100644 --- a/ui/packages/plugin-detail/src/InlineEditSaveBar.tsx +++ b/ui/packages/plugin-detail/src/InlineEditSaveBar.tsx @@ -83,7 +83,7 @@ import { isExternalWriteRefusal, type WriteFieldError, } from '@object-ui/react'; -import { getRecordDisplayName, resolveFieldAffordance } from '@object-ui/core'; +import { fieldReadOnlyByHand, getRecordDisplayName, resolveFieldAffordance } from '@object-ui/core'; import { usePermissions } from '@object-ui/permissions'; import { collectRequiredWhenPromptFields, @@ -419,12 +419,13 @@ export const InlineEditSaveBar: React.FC = ({ /** A field this reader may fill on this page: the question the inline editors ask. */ const fillable = React.useCallback( (name: string, def: Record) => - def.readonly !== true + // The one hand-lock verdict over this record (`fieldReadOnlyByHand`). + !fieldReadOnlyByHand(def, data) && !isComputedDetailField(undefined, def as never) && !NON_EDITABLE_SYSTEM_FIELDS.has(name) && !!objectName && resolveFieldAffordance('recordEdit', perms, objectName, name), - [objectName, perms], + [objectName, perms, data], ); /** diff --git a/ui/packages/plugin-detail/src/RecordDetailPanel.tsx b/ui/packages/plugin-detail/src/RecordDetailPanel.tsx index 0ba2726f9ea..28210a742b8 100644 --- a/ui/packages/plugin-detail/src/RecordDetailPanel.tsx +++ b/ui/packages/plugin-detail/src/RecordDetailPanel.tsx @@ -50,7 +50,7 @@ */ import React from 'react'; -import { isExpandableFieldType, resolveAffordance, type SchemaLike } from '@object-ui/core'; +import { fieldStaticallyReadOnlyByHand, isExpandableFieldType, resolveAffordance, type SchemaLike } from '@object-ui/core'; import type { DataSource } from '@object-ui/types'; import { SYSTEM_MANAGED_FIELD_NAMES } from '@object-ui/types'; import { InlineEditProvider, RecordContextProvider } from '@object-ui/react'; @@ -181,7 +181,8 @@ export function buildRecordDetailFields( name, label: def.label, type: def.type as any, - readonly: !!def.readonly || isLookup, + // The static hand-lock verdict (`readonly` or `uiReadonly`). + readonly: fieldStaticallyReadOnlyByHand(def) || isLookup, options: def.options, currency: def.currency, // The spec's one declaration of a fixed currency: `FieldSchema` diff --git a/ui/packages/plugin-detail/src/RelatedList.tsx b/ui/packages/plugin-detail/src/RelatedList.tsx index e20109b9201..8ce0f6c5e08 100644 --- a/ui/packages/plugin-detail/src/RelatedList.tsx +++ b/ui/packages/plugin-detail/src/RelatedList.tsx @@ -54,6 +54,7 @@ import type { DataSource, FieldMetadata } from '@object-ui/types'; import type { ViewFilterElement } from '@objectstack/spec/ui'; import { getCellRenderer, resolveCellRendererType, RecordPickerDialog, deriveLookupColumns, MaskedCellRenderer, RecordHoverCard, formatCurrency } from '@object-ui/fields'; import { + fieldStaticallyReadOnlyByHand, buildExpandFields, collectPredicateFieldRefs, columnIdentity, @@ -1149,7 +1150,8 @@ export function derivedAddOf( && def.required === true && def.multiple !== true && def.hidden !== true - && def.readonly !== true + // A console create fills no hand-locked field (`uiReadonly`), as no `readonly` one. + && !fieldStaticallyReadOnlyByHand(def) && typeof def.reference === 'string' && def.reference !== ''); if (catalogs.length !== 1) return undefined; const [catalogField, catalogDef] = catalogs[0]; @@ -1159,7 +1161,7 @@ export function derivedAddOf( && name !== catalogField && def.required === true && !insertDefaults(def) - && def.readonly !== true + && !fieldStaticallyReadOnlyByHand(def) && !isComputedFieldType(undefined, def.type)); if (leftToWrite) return undefined; return { picker: { object: catalogDef.reference as string }, linkField: catalogField }; diff --git a/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx b/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx index da66095c0eb..e5b59c69c30 100644 --- a/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx +++ b/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx @@ -86,6 +86,7 @@ import { AlertDialogTitle, } from '@object-ui/components'; import { + fieldReadOnlyByHand, getRecordDisplayName, resolveFieldAffordance, stateMachineNextValues, @@ -164,10 +165,12 @@ export function stageRefusalLines( type FieldDef = { type?: unknown; readonly?: unknown; + uiReadonly?: unknown; required?: unknown; label?: unknown; visibleWhen?: any; readonlyWhen?: any; + uiReadonlyWhen?: any; requiredWhen?: any; }; @@ -247,7 +250,9 @@ export function useStageChange( && canUpdate(dataSource) && !!inline?.canEdit && !inline.editing - && fieldDef?.readonly !== true + // The one hand-lock verdict over the stored record (`fieldReadOnlyByHand`): + // a status that moves only through actions (`uiReadonly`) offers no stage. + && !fieldReadOnlyByHand(fieldDef, ctx?.data as Record | undefined) && !isComputedDetailField(undefined, fieldDef) && !NON_EDITABLE_SYSTEM_FIELDS.has(statusField) && resolveFieldAffordance('recordEdit', perms, objectName, statusField); @@ -262,7 +267,7 @@ export function useStageChange( // fill-in asks the same one). const fillable = (name: string, def: Record): boolean => name !== statusField - && def.readonly !== true + && !fieldReadOnlyByHand(def, record) && !isComputedDetailField(undefined, def as FieldDef) && !NON_EDITABLE_SYSTEM_FIELDS.has(name) && !!objectName diff --git a/ui/packages/plugin-form/src/WizardForm.tsx b/ui/packages/plugin-form/src/WizardForm.tsx index 2d1ffa68657..42d08c50c99 100644 --- a/ui/packages/plugin-form/src/WizardForm.tsx +++ b/ui/packages/plugin-form/src/WizardForm.tsx @@ -902,6 +902,7 @@ export const WizardForm: React.FC = ({ { visibleWhen, readonlyWhen: (field as any).readonlyWhen, + uiReadonlyWhen: (field as any).uiReadonlyWhen, requiredWhen: (field as any).requiredWhen, }, ruleRecord, diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index a13ea04860e..7ecadc56d66 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -1568,6 +1568,7 @@ export const ObjectGrid: React.FC = ({ const recordUpdate = recordVerdict.current(recordId, 'update'); const kind = cellReadOnlyKind({ fieldDef, + row, fieldWritable: !objectName || resolveFieldAffordance('listInlineEdit', perms, objectName, columnKey), gridEditable, objectEditable: objectInlineEditable, diff --git a/ui/packages/plugin-grid/src/inline-edit-options.ts b/ui/packages/plugin-grid/src/inline-edit-options.ts index d66c2051075..821ed09afc3 100644 --- a/ui/packages/plugin-grid/src/inline-edit-options.ts +++ b/ui/packages/plugin-grid/src/inline-edit-options.ts @@ -13,7 +13,7 @@ */ import { isInlineExcludedFieldType, hasInCellPanelEditWidget } from '@object-ui/fields'; -import { isExpressionComputedField } from '@object-ui/core'; +import { fieldStaticallyReadOnlyByHand, isExpressionComputedField, type FieldHandLockDef } from '@object-ui/core'; /** * For a field governed by a blocking `state_machine` validation, the values @@ -47,16 +47,17 @@ const NON_EDITABLE_FIELD_TYPES = new Set([ /** * Why a field is not edited in place (objectstack#35684), or `null` when it - * is: `readonly` (declared so), `computed` (an expression, a formula, a + * is: `readonly` (declared so — `readonly` or the hand lock `uiReadonly`, the + * static half of `fieldReadOnlyByHand` in `@object-ui/core`), `computed` (an expression, a formula, a * summary, an auto number) or `notInline` (a file, or a type the fields * package keeps out of a cell). The reasons {@link isFieldInlineEditable} * answers `false` for, told apart so a cell can say which. */ export function fieldInlineReadOnlyKind( - fieldDef: { type?: unknown; readonly?: unknown } | null | undefined, + fieldDef: ({ type?: unknown } & FieldHandLockDef) | null | undefined, ): 'readonly' | 'computed' | 'notInline' | null { if (!fieldDef) return null; - if (fieldDef.readonly === true) return 'readonly'; + if (fieldStaticallyReadOnlyByHand(fieldDef)) return 'readonly'; if (isExpressionComputedField(fieldDef)) return 'computed'; if (typeof fieldDef.type !== 'string') return null; if (COMPUTED_FIELD_TYPES.has(fieldDef.type)) return 'computed'; @@ -81,7 +82,7 @@ export function fieldInlineReadOnlyKind( * grid's own `editable` flag still governs. */ export function isFieldInlineEditable( - fieldDef: { type?: unknown; readonly?: unknown } | null | undefined, + fieldDef: ({ type?: unknown } & FieldHandLockDef) | null | undefined, ): boolean { return fieldInlineReadOnlyKind(fieldDef) === null; } diff --git a/ui/packages/plugin-grid/src/objectGridCellFacts.ts b/ui/packages/plugin-grid/src/objectGridCellFacts.ts index 09a070ed45c..123ba33e889 100644 --- a/ui/packages/plugin-grid/src/objectGridCellFacts.ts +++ b/ui/packages/plugin-grid/src/objectGridCellFacts.ts @@ -13,6 +13,7 @@ * acts on a cell, never while it draws. */ import { buildValidationRules, RICH_TEXT_FIELD_TYPES } from '@object-ui/fields'; +import { fieldReadOnlyByHand, type FieldHandLockDef } from '@object-ui/core'; import { fieldInlineReadOnlyKind } from './inline-edit-options'; /** Why a cell opens no editor, in the order a cell names them. */ @@ -45,7 +46,13 @@ export function readOnlyReasonText(kind: CellReadOnlyKind, t: (key: string) => s /** The grid-wide and row answers a cell's reason is read from. */ export interface CellReadOnlyInputs { /** The object's field definition for the column, when it has one. */ - fieldDef: { type?: unknown; readonly?: unknown } | null | undefined; + fieldDef: ({ type?: unknown } & FieldHandLockDef) | null | undefined; + /** + * The row the cell belongs to: the conditional locks (`readonlyWhen`, and the + * hand lock `uiReadonlyWhen`) are judged over it. Absent, only the static + * half is read. + */ + row?: Record | null; /** May this reader write the field (`resolveFieldAffordance('listInlineEdit', …)`)? */ fieldWritable: boolean; /** The authored `editable` the grid was handed (the list page folds `userActions.editInline` into it). */ @@ -68,6 +75,8 @@ export interface CellReadOnlyInputs { export function cellReadOnlyKind(inputs: CellReadOnlyInputs): CellReadOnlyKind | null { const fieldKind = fieldInlineReadOnlyKind(inputs.fieldDef); if (fieldKind) return fieldKind; + // The conditional half of the one hand-lock verdict, over this row. + if (inputs.row != null && fieldReadOnlyByHand(inputs.fieldDef, inputs.row)) return 'readonly'; if (!inputs.fieldWritable) return 'noFieldPermission'; if (!inputs.canUpdate) return 'noPermission'; if (!inputs.objectEditable) return 'objectReadOnly'; diff --git a/ui/packages/plugin-grid/src/objectGridRequiredPrompt.tsx b/ui/packages/plugin-grid/src/objectGridRequiredPrompt.tsx index 69b41ffe12b..6615fb2fbf9 100644 --- a/ui/packages/plugin-grid/src/objectGridRequiredPrompt.tsx +++ b/ui/packages/plugin-grid/src/objectGridRequiredPrompt.tsx @@ -44,7 +44,7 @@ */ import React from 'react'; -import { getRecordDisplayName, resolveFieldAffordance } from '@object-ui/core'; +import { fieldStaticallyReadOnlyByHand, getRecordDisplayName, resolveFieldAffordance } from '@object-ui/core'; import { collectRequiredWhenPromptFields, requiredWhenPromptReads, @@ -117,7 +117,7 @@ export function useCellRequiredPrompt(inputs: CellRequiredPromptInputs): { // A field this reader may write from the list: the field grant the cell // editors ask (`listInlineEdit`). const fillable = (name: string, def: Record): boolean => - def.readonly !== true + !fieldStaticallyReadOnlyByHand(def) && (!objectName || resolveFieldAffordance('listInlineEdit', perms, objectName, name)); const label = (f: RequiredWhenPromptField): RequiredFieldsDialogField => { diff --git a/ui/packages/plugin-kanban/src/ObjectKanban.tsx b/ui/packages/plugin-kanban/src/ObjectKanban.tsx index 908a872bc29..d1906f3ea55 100644 --- a/ui/packages/plugin-kanban/src/ObjectKanban.tsx +++ b/ui/packages/plugin-kanban/src/ObjectKanban.tsx @@ -39,6 +39,8 @@ import { deriveRecordPageHref, } from '@object-ui/plugin-detail'; import { + fieldReadOnlyByHand, + fieldStaticallyReadOnlyByHand, extractRecords, buildExpandFields, convertSortToQueryParams, @@ -2087,6 +2089,17 @@ export const ObjectKanban: React.FC = ({ perms, }).allowed; + // A drag writes the lane field, so the field's own lock closes it: the one + // hand-lock verdict of `@object-ui/core` (`readonly`, `uiReadonly`, and the + // conditional `readonlyWhen` / `uiReadonlyWhen`). The static half draws every + // card as not movable; the conditional half is judged per card at the drop, + // in `handleCardMove`. Before this the board read no field lock at all, so a + // `readonly` lane field took the drop and its write was silently stripped. + const laneFieldDef = schema.groupBy + ? (objectDef?.fields as Record | undefined> | undefined)?.[schema.groupBy] + : undefined; + const laneFieldLocked = fieldStaticallyReadOnlyByHand(laneFieldDef); + // The board's drop gate (#25933): a lane is a value of `groupBy`, so when the // object's blocking `state_machine` rule governs that same field, a card may // enter only the lanes its column's value may move to. The read is the one @@ -2159,6 +2172,14 @@ export const ObjectKanban: React.FC = ({ const record = (Array.isArray(rawData) ? rawData : []).find( (r) => String(r?.id ?? r?._id) === String(cardId), ); + // The lane field's conditional lock over THIS record (`readonlyWhen`, the + // hand lock `uiReadonlyWhen`): no write, and the card goes back — a fresh + // array identity re-buckets the board from the unchanged rows. + const laneDef = (objectDef?.fields as Record | undefined> | undefined)?.[groupBy]; + if (fieldReadOnlyByHand(laneDef, record, { fieldContext: `field '${groupBy}'` })) { + setFetchedData((prev) => prev.map((r) => r)); + return { kind: 'refused', message: tt('grid.readOnlyReason.readonly', 'This field is read-only.') }; + } const fields = collectRequiredWhenPromptFields( objectDef?.fields, record, @@ -2176,7 +2197,7 @@ export const ObjectKanban: React.FC = ({ return persistCardMove(cardId, fromColumnId, toColumnId); }, - [schema.groupBy, rawData, objectDef, persistCardMove], + [schema.groupBy, rawData, objectDef, persistCardMove, tt], ); // Label + localized options for each prompted field, resolved with the same @@ -2398,7 +2419,7 @@ export const ObjectKanban: React.FC = ({ // objectui#12082: handed only when `kanbanCardMove` allows the write, // and the cards are drawn not movable otherwise (see `cardMoveGranted`). onCardMove={cardMoveGranted ? handleCardMove : undefined} - cardsMovable={cardMoveGranted} + cardsMovable={cardMoveGranted && !laneFieldLocked} // objectstack#33548 — the host's answer to "does a card click open // anything"; absent ⇒ every card as before. rowOpensRecord={rowOpensRecord} From 755763f6300150e7eff116ac5240ca969f30c31b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 02:26:39 +0000 Subject: [PATCH 03/13] feat(spec,ui): line-item grid skips uiReadonly; regenerate spec artifacts and liveness rows (WIP) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXSuJCALDHFWaV6Bv5 --- content/docs/references/data/field.mdx | 2 ++ content/docs/references/data/object.mdx | 4 ++++ content/docs/references/system/migration.mdx | 4 ++++ packages/spec/authorable-surface/data.json | 2 ++ packages/spec/liveness/field.json | 14 ++++++++++++++ packages/spec/liveness/state-counts/field.md | 2 +- packages/spec/src/data/inline-grid-columns.ts | 5 +++-- .../src/widgets/grid-field/GridFieldWidget.tsx | 10 +++++++--- ui/packages/plugin-form/src/deriveMasterDetail.ts | 5 +++++ 9 files changed, 42 insertions(+), 6 deletions(-) diff --git a/content/docs/references/data/field.mdx b/content/docs/references/data/field.mdx index 7dbc343c3bb..b3ccf992881 100644 --- a/content/docs/references/data/field.mdx +++ b/content/docs/references/data/field.mdx @@ -111,6 +111,7 @@ const result = CurrencyConfigSchema.parse(data); | **group** | `string` | optional | Older spelling of field-group membership, still read: the key of one of the object's fieldGroups (e.g. "contact_info"); the field joins that group in field declaration order. New metadata lists members on the group instead (fieldGroups[].fields), which also sets their order. A field a group lists may not name a different group here; a field naming a group whose fields list leaves it out follows the listed ones. | | **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. | +| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND when TRUE: no console surface lets a person edit it (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit, kanban and calendar drag), while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | | **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. | | **settledWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the deadline is SETTLED while TRUE: no overdue wording or colour applies to this record, e.g. P`record.status == 'done'`. Evaluated per record like `visibleWhen`, reading the record's own columns as `record`. Requires `dueLike: true` on a `date` / `datetime` field; refused otherwise. Display only: nothing on the write path reads it. | @@ -120,6 +121,7 @@ const result = CurrencyConfigSchema.parse(data); | **showOnCreate** | `boolean` | optional | Ask for this field when a record is created. Absent or `true`: the field is on every create surface (the create dialog, the full-page create, an action-opened create). `false`: no create surface shows it; editing, the record page and lists still do, so a value is filled in after the record exists. Refused on a `required: true` field, with or without a `defaultValue`: a required field is always asked for on create. Keep the field on create, or drop `required`. A `requiredWhen` field is accepted, and its create is still refused when the predicate holds and the value is empty. | | **internal** | `boolean` | optional | Never return this field's value on the generic data path — the engine OMITS the key from `find`/`findOne` results, the 201 create body and the by-id update body, on the default projection AND when a client names the field in `?select=`. Storage, filtering and indexing are untouched, so a server-side verifier can still match on the column and a purpose-built mint route can still return the value once at creation. The read protection for ADR-0100's third credential channel (auth-subsystem one-way hashes on `text` columns). Omission, not masking: a mask signals 'a value is set', which carries no information on a `required` column. | | **readonly** | `boolean` | optional (default: `false`) | Read-only — never editable in forms, AND server-enforced on BOTH write paths: a non-system write to this field is silently dropped from the payload on UPDATE and on INSERT (a create can no longer directly seed e.g. `approval_status: "approved"`), symmetric with `readonlyWhen`. A stripped INSERT field still falls back to its `defaultValue`. Exempt from the strip on BOTH paths: `isSystem` writes (seed replay, migration). Exempt on the UPDATE path ONLY: an opt-in "historical" import (`preserveAudit`) — which admits a whitelist (the audit/timestamp family plus author-declared business `readonly` fields). On INSERT the exemption does NOT apply: a non-system create that requests `preserveAudit` still has its readonly fields stripped, and is warned loudly that the exemption is UPDATE-only — replaying archival readonly facts on create requires a system context. A normal (non-system) import is NOT system-context and still strips. | +| **uiReadonly** | `boolean` | optional | Read-only BY HAND: no console surface lets a person edit the field (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit and multi-row save, kanban and calendar drag), while every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`; an API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | | **requiredPermissions** | `string[]` | optional | [ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate). | | **maskingRule** | `Enum<'phone' \| 'id_card' \| 'bank_account' \| 'email' \| 'name'> \| { keepHead: integer; keepTail: integer }` | optional | Partial masking rule enforced by the runtime FieldMasker (single channel — API, UI, export and AI context all see the same masked value). A named preset ('phone' 138****5678, 'id_card' keep 6+4, 'bank_account' keep last 4, 'email' j***@example.com, 'name' keep first char) or `{ keepHead, keepTail }`. Masked for every non-system caller unless the field's `requiredPermissions` are ALL held (that evaluation is the unmask gate); a permission set marking the field non-readable still deletes it entirely. Deterministic, length-preserving output; masked callers cannot filter/sort/group/aggregate on the field. | | **ackPlaintextMasking** | `boolean` | optional | [ADR-0100] Affirm a generic `password` field's plaintext-at-rest / masked-on-read contract is intended, silencing the author-time warning. No effect on non-password fields. | diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 08f2650afd8..e38b9e406fd 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -299,6 +299,7 @@ const result = ApiMethod.parse(data); | **group** | `string` | optional | Older spelling of field-group membership, still read: the key of one of the object's fieldGroups (e.g. "contact_info"); the field joins that group in field declaration order. New metadata lists members on the group instead (fieldGroups[].fields), which also sets their order. A field a group lists may not name a different group here; a field naming a group whose fields list leaves it out follows the listed ones. | | **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. | +| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND when TRUE: no console surface lets a person edit it (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit, kanban and calendar drag), while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | | **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. | | **settledWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the deadline is SETTLED while TRUE: no overdue wording or colour applies to this record, e.g. P`record.status == 'done'`. Evaluated per record like `visibleWhen`, reading the record's own columns as `record`. Requires `dueLike: true` on a `date` / `datetime` field; refused otherwise. Display only: nothing on the write path reads it. | @@ -308,6 +309,7 @@ const result = ApiMethod.parse(data); | **showOnCreate** | `boolean` | optional | Ask for this field when a record is created. Absent or `true`: the field is on every create surface (the create dialog, the full-page create, an action-opened create). `false`: no create surface shows it; editing, the record page and lists still do, so a value is filled in after the record exists. Refused on a `required: true` field, with or without a `defaultValue`: a required field is always asked for on create. Keep the field on create, or drop `required`. A `requiredWhen` field is accepted, and its create is still refused when the predicate holds and the value is empty. | | **internal** | `boolean` | optional | Never return this field's value on the generic data path — the engine OMITS the key from `find`/`findOne` results, the 201 create body and the by-id update body, on the default projection AND when a client names the field in `?select=`. Storage, filtering and indexing are untouched, so a server-side verifier can still match on the column and a purpose-built mint route can still return the value once at creation. The read protection for ADR-0100's third credential channel (auth-subsystem one-way hashes on `text` columns). Omission, not masking: a mask signals 'a value is set', which carries no information on a `required` column. | | **readonly** | `boolean` | optional (default: `false`) | Read-only — never editable in forms, AND server-enforced on BOTH write paths: a non-system write to this field is silently dropped from the payload on UPDATE and on INSERT (a create can no longer directly seed e.g. `approval_status: "approved"`), symmetric with `readonlyWhen`. A stripped INSERT field still falls back to its `defaultValue`. Exempt from the strip on BOTH paths: `isSystem` writes (seed replay, migration). Exempt on the UPDATE path ONLY: an opt-in "historical" import (`preserveAudit`) — which admits a whitelist (the audit/timestamp family plus author-declared business `readonly` fields). On INSERT the exemption does NOT apply: a non-system create that requests `preserveAudit` still has its readonly fields stripped, and is warned loudly that the exemption is UPDATE-only — replaying archival readonly facts on create requires a system context. A normal (non-system) import is NOT system-context and still strips. | +| **uiReadonly** | `boolean` | optional | Read-only BY HAND: no console surface lets a person edit the field (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit and multi-row save, kanban and calendar drag), while every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`; an API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | | **requiredPermissions** | `string[]` | optional | [ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate). | | **maskingRule** | `Enum<'phone' \| 'id_card' \| 'bank_account' \| 'email' \| 'name'> \| { keepHead: integer; keepTail: integer }` | optional | Partial masking rule enforced by the runtime FieldMasker (single channel — API, UI, export and AI context all see the same masked value). A named preset ('phone' 138****5678, 'id_card' keep 6+4, 'bank_account' keep last 4, 'email' j***@example.com, 'name' keep first char) or `{ keepHead, keepTail }`. Masked for every non-system caller unless the field's `requiredPermissions` are ALL held (that evaluation is the unmask gate); a permission set marking the field non-readable still deletes it entirely. Deterministic, length-preserving output; masked callers cannot filter/sort/group/aggregate on the field. | | **ackPlaintextMasking** | `boolean` | optional | [ADR-0100] Affirm a generic `password` field's plaintext-at-rest / masked-on-read contract is intended, silencing the author-time warning. No effect on non-password fields. | @@ -698,6 +700,7 @@ const result = ApiMethod.parse(data); | **group** | `string` | optional | Older spelling of field-group membership, still read: the key of one of the object's fieldGroups (e.g. "contact_info"); the field joins that group in field declaration order. New metadata lists members on the group instead (fieldGroups[].fields), which also sets their order. A field a group lists may not name a different group here; a field naming a group whose fields list leaves it out follows the listed ones. | | **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. | +| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND when TRUE: no console surface lets a person edit it (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit, kanban and calendar drag), while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | | **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. | | **settledWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the deadline is SETTLED while TRUE: no overdue wording or colour applies to this record, e.g. P`record.status == 'done'`. Evaluated per record like `visibleWhen`, reading the record's own columns as `record`. Requires `dueLike: true` on a `date` / `datetime` field; refused otherwise. Display only: nothing on the write path reads it. | @@ -707,6 +710,7 @@ const result = ApiMethod.parse(data); | **showOnCreate** | `boolean` | optional | Ask for this field when a record is created. Absent or `true`: the field is on every create surface (the create dialog, the full-page create, an action-opened create). `false`: no create surface shows it; editing, the record page and lists still do, so a value is filled in after the record exists. Refused on a `required: true` field, with or without a `defaultValue`: a required field is always asked for on create. Keep the field on create, or drop `required`. A `requiredWhen` field is accepted, and its create is still refused when the predicate holds and the value is empty. | | **internal** | `boolean` | optional | Never return this field's value on the generic data path — the engine OMITS the key from `find`/`findOne` results, the 201 create body and the by-id update body, on the default projection AND when a client names the field in `?select=`. Storage, filtering and indexing are untouched, so a server-side verifier can still match on the column and a purpose-built mint route can still return the value once at creation. The read protection for ADR-0100's third credential channel (auth-subsystem one-way hashes on `text` columns). Omission, not masking: a mask signals 'a value is set', which carries no information on a `required` column. | | **readonly** | `boolean` | optional (default: `false`) | Read-only — never editable in forms, AND server-enforced on BOTH write paths: a non-system write to this field is silently dropped from the payload on UPDATE and on INSERT (a create can no longer directly seed e.g. `approval_status: "approved"`), symmetric with `readonlyWhen`. A stripped INSERT field still falls back to its `defaultValue`. Exempt from the strip on BOTH paths: `isSystem` writes (seed replay, migration). Exempt on the UPDATE path ONLY: an opt-in "historical" import (`preserveAudit`) — which admits a whitelist (the audit/timestamp family plus author-declared business `readonly` fields). On INSERT the exemption does NOT apply: a non-system create that requests `preserveAudit` still has its readonly fields stripped, and is warned loudly that the exemption is UPDATE-only — replaying archival readonly facts on create requires a system context. A normal (non-system) import is NOT system-context and still strips. | +| **uiReadonly** | `boolean` | optional | Read-only BY HAND: no console surface lets a person edit the field (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit and multi-row save, kanban and calendar drag), while every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`; an API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | | **requiredPermissions** | `string[]` | optional | [ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate). | | **maskingRule** | `Enum<'phone' \| 'id_card' \| 'bank_account' \| 'email' \| 'name'> \| { keepHead: integer; keepTail: integer }` | optional | Partial masking rule enforced by the runtime FieldMasker (single channel — API, UI, export and AI context all see the same masked value). A named preset ('phone' 138****5678, 'id_card' keep 6+4, 'bank_account' keep last 4, 'email' j***@example.com, 'name' keep first char) or `{ keepHead, keepTail }`. Masked for every non-system caller unless the field's `requiredPermissions` are ALL held (that evaluation is the unmask gate); a permission set marking the field non-readable still deletes it entirely. Deterministic, length-preserving output; masked callers cannot filter/sort/group/aggregate on the field. | | **ackPlaintextMasking** | `boolean` | optional | [ADR-0100] Affirm a generic `password` field's plaintext-at-rest / masked-on-read contract is intended, silencing the author-time warning. No effect on non-password fields. | diff --git a/content/docs/references/system/migration.mdx b/content/docs/references/system/migration.mdx index 27eb5adf5d5..78a3e7afec5 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -114,6 +114,7 @@ Add a new field to an existing object | **group** | `string` | optional | Older spelling of field-group membership, still read: the key of one of the object's fieldGroups (e.g. "contact_info"); the field joins that group in field declaration order. New metadata lists members on the group instead (fieldGroups[].fields), which also sets their order. A field a group lists may not name a different group here; a field naming a group whose fields list leaves it out follows the listed ones. | | **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. | +| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND when TRUE: no console surface lets a person edit it (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit, kanban and calendar drag), while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | | **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. | | **settledWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the deadline is SETTLED while TRUE: no overdue wording or colour applies to this record, e.g. P`record.status == 'done'`. Evaluated per record like `visibleWhen`, reading the record's own columns as `record`. Requires `dueLike: true` on a `date` / `datetime` field; refused otherwise. Display only: nothing on the write path reads it. | @@ -123,6 +124,7 @@ Add a new field to an existing object | **showOnCreate** | `boolean` | optional | Ask for this field when a record is created. Absent or `true`: the field is on every create surface (the create dialog, the full-page create, an action-opened create). `false`: no create surface shows it; editing, the record page and lists still do, so a value is filled in after the record exists. Refused on a `required: true` field, with or without a `defaultValue`: a required field is always asked for on create. Keep the field on create, or drop `required`. A `requiredWhen` field is accepted, and its create is still refused when the predicate holds and the value is empty. | | **internal** | `boolean` | optional | Never return this field's value on the generic data path — the engine OMITS the key from `find`/`findOne` results, the 201 create body and the by-id update body, on the default projection AND when a client names the field in `?select=`. Storage, filtering and indexing are untouched, so a server-side verifier can still match on the column and a purpose-built mint route can still return the value once at creation. The read protection for ADR-0100's third credential channel (auth-subsystem one-way hashes on `text` columns). Omission, not masking: a mask signals 'a value is set', which carries no information on a `required` column. | | **readonly** | `boolean` | optional (default: `false`) | Read-only — never editable in forms, AND server-enforced on BOTH write paths: a non-system write to this field is silently dropped from the payload on UPDATE and on INSERT (a create can no longer directly seed e.g. `approval_status: "approved"`), symmetric with `readonlyWhen`. A stripped INSERT field still falls back to its `defaultValue`. Exempt from the strip on BOTH paths: `isSystem` writes (seed replay, migration). Exempt on the UPDATE path ONLY: an opt-in "historical" import (`preserveAudit`) — which admits a whitelist (the audit/timestamp family plus author-declared business `readonly` fields). On INSERT the exemption does NOT apply: a non-system create that requests `preserveAudit` still has its readonly fields stripped, and is warned loudly that the exemption is UPDATE-only — replaying archival readonly facts on create requires a system context. A normal (non-system) import is NOT system-context and still strips. | +| **uiReadonly** | `boolean` | optional | Read-only BY HAND: no console surface lets a person edit the field (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit and multi-row save, kanban and calendar drag), while every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`; an API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | | **requiredPermissions** | `string[]` | optional | [ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate). | | **maskingRule** | `Enum<'phone' \| 'id_card' \| 'bank_account' \| 'email' \| 'name'> \| { keepHead: integer; keepTail: integer }` | optional | Partial masking rule enforced by the runtime FieldMasker (single channel — API, UI, export and AI context all see the same masked value). A named preset ('phone' 138****5678, 'id_card' keep 6+4, 'bank_account' keep last 4, 'email' j***@example.com, 'name' keep first char) or `{ keepHead, keepTail }`. Masked for every non-system caller unless the field's `requiredPermissions` are ALL held (that evaluation is the unmask gate); a permission set marking the field non-readable still deletes it entirely. Deterministic, length-preserving output; masked callers cannot filter/sort/group/aggregate on the field. | | **ackPlaintextMasking** | `boolean` | optional | [ADR-0100] Affirm a generic `password` field's plaintext-at-rest / masked-on-read contract is intended, silencing the author-time warning. No effect on non-password fields. | @@ -556,6 +558,7 @@ Add a new field to an existing object | **group** | `string` | optional | Older spelling of field-group membership, still read: the key of one of the object's fieldGroups (e.g. "contact_info"); the field joins that group in field declaration order. New metadata lists members on the group instead (fieldGroups[].fields), which also sets their order. A field a group lists may not name a different group here; a field naming a group whose fields list leaves it out follows the listed ones. | | **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. | +| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND when TRUE: no console surface lets a person edit it (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit, kanban and calendar drag), while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | | **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. | | **settledWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the deadline is SETTLED while TRUE: no overdue wording or colour applies to this record, e.g. P`record.status == 'done'`. Evaluated per record like `visibleWhen`, reading the record's own columns as `record`. Requires `dueLike: true` on a `date` / `datetime` field; refused otherwise. Display only: nothing on the write path reads it. | @@ -565,6 +568,7 @@ Add a new field to an existing object | **showOnCreate** | `boolean` | optional | Ask for this field when a record is created. Absent or `true`: the field is on every create surface (the create dialog, the full-page create, an action-opened create). `false`: no create surface shows it; editing, the record page and lists still do, so a value is filled in after the record exists. Refused on a `required: true` field, with or without a `defaultValue`: a required field is always asked for on create. Keep the field on create, or drop `required`. A `requiredWhen` field is accepted, and its create is still refused when the predicate holds and the value is empty. | | **internal** | `boolean` | optional | Never return this field's value on the generic data path — the engine OMITS the key from `find`/`findOne` results, the 201 create body and the by-id update body, on the default projection AND when a client names the field in `?select=`. Storage, filtering and indexing are untouched, so a server-side verifier can still match on the column and a purpose-built mint route can still return the value once at creation. The read protection for ADR-0100's third credential channel (auth-subsystem one-way hashes on `text` columns). Omission, not masking: a mask signals 'a value is set', which carries no information on a `required` column. | | **readonly** | `boolean` | optional (default: `false`) | Read-only — never editable in forms, AND server-enforced on BOTH write paths: a non-system write to this field is silently dropped from the payload on UPDATE and on INSERT (a create can no longer directly seed e.g. `approval_status: "approved"`), symmetric with `readonlyWhen`. A stripped INSERT field still falls back to its `defaultValue`. Exempt from the strip on BOTH paths: `isSystem` writes (seed replay, migration). Exempt on the UPDATE path ONLY: an opt-in "historical" import (`preserveAudit`) — which admits a whitelist (the audit/timestamp family plus author-declared business `readonly` fields). On INSERT the exemption does NOT apply: a non-system create that requests `preserveAudit` still has its readonly fields stripped, and is warned loudly that the exemption is UPDATE-only — replaying archival readonly facts on create requires a system context. A normal (non-system) import is NOT system-context and still strips. | +| **uiReadonly** | `boolean` | optional | Read-only BY HAND: no console surface lets a person edit the field (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit and multi-row save, kanban and calendar drag), while every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`; an API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | | **requiredPermissions** | `string[]` | optional | [ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate). | | **maskingRule** | `Enum<'phone' \| 'id_card' \| 'bank_account' \| 'email' \| 'name'> \| { keepHead: integer; keepTail: integer }` | optional | Partial masking rule enforced by the runtime FieldMasker (single channel — API, UI, export and AI context all see the same masked value). A named preset ('phone' 138****5678, 'id_card' keep 6+4, 'bank_account' keep last 4, 'email' j***@example.com, 'name' keep first char) or `{ keepHead, keepTail }`. Masked for every non-system caller unless the field's `requiredPermissions` are ALL held (that evaluation is the unmask gate); a permission set marking the field non-readable still deletes it entirely. Deterministic, length-preserving output; masked callers cannot filter/sort/group/aggregate on the field. | | **ackPlaintextMasking** | `boolean` | optional | [ADR-0100] Affirm a generic `password` field's plaintext-at-rest / masked-on-read contract is intended, silencing the author-time warning. No effect on non-password fields. | diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index 2eaeca8f81f..2006cbdea15 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -387,6 +387,8 @@ "data/Field:trackHistory", "data/Field:transferBehavior", "data/Field:type", + "data/Field:uiReadonly", + "data/Field:uiReadonlyWhen", "data/Field:unique", "data/Field:unitConfig", "data/Field:useGrouping", diff --git a/packages/spec/liveness/field.json b/packages/spec/liveness/field.json index 97663e07f5c..a0314f8b6b3 100644 --- a/packages/spec/liveness/field.json +++ b/packages/spec/liveness/field.json @@ -148,6 +148,13 @@ "evidence": "packages/objectql/src/validation/rule-validator.ts", "note": "renderer CEL + server write path: stripReadonlyWhenFields drops UPDATE writes when the predicate is TRUE against {...previous, ...data} (B2); INSERT exempt." }, + "uiReadonlyWhen": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidenceScope": "in-repo", + "evidence": "ui/packages/core/src/evaluator/handLock.ts#fieldReadOnlyByHand (the one hand-lock verdict, the predicate run through ui/packages/core/src/evaluator/fieldRules.ts#resolveFieldRuleState); its readers are the hand surfaces listed on `uiReadonly`, with the per-record reads in the form renderer (ui/packages/components/src/renderers/form/form.tsx), the record page (DetailSection, HeaderHighlight, InlineEditSaveBar, recordPathStageChange), the grid cell (ui/packages/plugin-grid/src/objectGridCellFacts.ts#cellReadOnlyKind), the line-item cell (ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx), kanban and calendar drops; packages/runtime/src/domains/mcp.ts#describedHandLock (describe_object)", + "note": "renderer only, by ruling (the two-tier field-lock model): while TRUE no person edits the field at the console; the engine never reads it, so API, import, action and flow writes keep it, judged by validations. Allowed beside `readonlyWhen`, the stricter server lock. Fail-open on a fault, as `readonlyWhen` on the client." + }, "visibleWhen": { "status": "live", "note": "renderer CEL." @@ -192,6 +199,13 @@ "proof": "packages/qa/dogfood/test/showcase-static-readonly.dogfood.test.ts#readonly-static-write", "note": "renderer + server write path: a non-system write to the field is silently dropped on BOTH UPDATE (#2948/#3003 — engine stripReadonlyFields; was renderer-only, i.e. false compliance for approval/status columns) and INSERT — first (#3043) at the DataProtocol createData/import ingress only, so external REST/GraphQL/MCP creates couldn't seed approval_status:'approved' a step shorter than #3003 while a direct engine.insert caller still could; since the maintainer ruling of 2026-09-03 (option C, #14147) inside engine.insert itself, by the SAME stripReadonlyFields under the SAME isSystem gate as UPDATE, with the ingress copy deleted, so every non-system caller is stripped and seeding a readonly column at create time is a system act (isSystem / runAs:'system' / seeds); a stripped INSERT field falls back to its defaultValue; symmetric with readonlyWhen (which stays INSERT-exempt, needing a prior record)." }, + "uiReadonly": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidenceScope": "in-repo", + "evidence": "ui/packages/core/src/evaluator/handLock.ts#fieldStaticallyReadOnlyByHand and #fieldReadOnlyByHand (the one hand-lock verdict every hand surface reads): the create and edit dialogs and their payload (ui/packages/plugin-form/src/autoLayout.ts, sectionFields.ts, ObjectForm.tsx, sanitize.ts), record-page inline edit and the stage path (ui/packages/plugin-detail/src/DetailSection.tsx, InlineEditSaveBar.tsx, renderers/recordPathStageChange.tsx), the highlight-strip chip (HeaderHighlight.tsx), grid inline edit (ui/packages/plugin-grid/src/inline-edit-options.ts), kanban drag (ui/packages/plugin-kanban/src/ObjectKanban.tsx), calendar drag (ui/packages/plugin-calendar/src/ObjectCalendar.tsx), the line-item grid (packages/spec/src/data/inline-grid-columns.ts#deriveInlineGridColumns); packages/spec/src/data/field.zod.ts#uiReadonly (the parse refuses it beside `readonly: true`); packages/runtime/src/domains/mcp.ts#describedHandLock (describe_object)", + "note": "renderer only, by ruling (the two-tier field-lock model): no person edits the field at the console, and every other write keeps it — the engine never reads the key, so REST, import, action and flow writes set it, judged by validations (a state_machine rule included); a console create leaves it out and the server applies its defaultValue. The import mapping and Studio reads stay on raw `readonly`." + }, "hidden": { "status": "live", "note": "renderer." diff --git a/packages/spec/liveness/state-counts/field.md b/packages/spec/liveness/state-counts/field.md index 0c182d3c5ed..493c258c783 100644 --- a/packages/spec/liveness/state-counts/field.md +++ b/packages/spec/liveness/state-counts/field.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `field` | 111 | 0 | 0 | 1 | 5 | 117 | +| `field` | 113 | 0 | 0 | 1 | 5 | 119 | diff --git a/packages/spec/src/data/inline-grid-columns.ts b/packages/spec/src/data/inline-grid-columns.ts index af3d86ba6fa..1ff39b24b71 100644 --- a/packages/spec/src/data/inline-grid-columns.ts +++ b/packages/spec/src/data/inline-grid-columns.ts @@ -31,7 +31,8 @@ * ownership columns) or {@link INLINE_GRID_SORT_FIELDS} (a line's sort * position: the grid stamps it on drag-reorder instead); * - the relationship field back to the parent, and any name in `exclude`; - * - a field flagged `system`, `readonly` or `hidden`; + * - a field flagged `system`, `readonly`, `uiReadonly` or `hidden` (a cell is + * an edit by hand, so the hand lock skips it as the server lock does); * - a field whose `type` is in {@link INLINE_GRID_NON_EDITABLE_TYPES}. * * NOTHING is dropped by the column budget. Past `maxColumns` (default @@ -241,7 +242,7 @@ export function deriveInlineGridColumns( const candidates: Candidate[] = []; for (const [name, field] of Object.entries(fields as AnyRec)) { if (INLINE_GRID_SYSTEM_FIELDS.has(name) || exclude.has(name) || INLINE_GRID_SORT_FIELDS.has(name)) continue; - if (prop(field, 'system') || prop(field, 'readonly') || prop(field, 'hidden')) continue; + if (prop(field, 'system') || prop(field, 'readonly') || prop(field, 'uiReadonly') || prop(field, 'hidden')) continue; if (INLINE_GRID_NON_EDITABLE_TYPES.has(prop(field, 'type'))) continue; candidates.push({ name, diff --git a/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx index 7f8aa2b031d..3caf84c8c3d 100644 --- a/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx +++ b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx @@ -15,7 +15,7 @@ import { TooltipTrigger, } from '@object-ui/components'; import { Plus, Trash2, SlidersHorizontal, Maximize2, Copy, GripVertical, Info } from 'lucide-react'; -import { formatDate, formatDateTime, resolveFieldRuleState, toDisplayDate } from '@object-ui/core'; +import { formatDate, formatDateTime, resolveFieldRuleState, toDisplayDate, type FieldRulePredicate } from '@object-ui/core'; import { useDisplayLocale, useLocalization, formatDisplayNumber } from '@object-ui/i18n'; import { currencySymbol } from '../../currency.js'; import { LookupField } from '../LookupField.js'; @@ -839,11 +839,15 @@ function GridFieldBody({ ); const cellRules = useCallback( (c: GridColumn, row: Row): { readonly: boolean; required: boolean } => { - if (!c.readonlyWhen && !c.requiredWhen) { + // The child FIELD's hand-lock predicate, carried onto the column in memory + // by `@object-ui/plugin-form`'s column derivation (never an authored + // `inlineColumns` key), folds into the same per-row verdict. + const uiReadonlyWhen = (c as { uiReadonlyWhen?: FieldRulePredicate }).uiReadonlyWhen; + if (!c.readonlyWhen && !uiReadonlyWhen && !c.requiredWhen) { return { readonly: false, required: !!c.required }; } const s = resolveFieldRuleState( - { readonlyWhen: c.readonlyWhen, requiredWhen: c.requiredWhen }, + { readonlyWhen: c.readonlyWhen, uiReadonlyWhen, requiredWhen: c.requiredWhen }, ruleRecordOf(booleanColumns, row), { required: !!c.required, readonly: false }, undefined, diff --git a/ui/packages/plugin-form/src/deriveMasterDetail.ts b/ui/packages/plugin-form/src/deriveMasterDetail.ts index 38fc0fa7f47..257a3687cd4 100644 --- a/ui/packages/plugin-form/src/deriveMasterDetail.ts +++ b/ui/packages/plugin-form/src/deriveMasterDetail.ts @@ -308,6 +308,10 @@ function deriveColumn(name: string, d: any, booleanLabel: BooleanValueLabel): Gr // so the grid cell evaluates them per row (against the row + `parent` // header). if (d?.readonlyWhen) col.readonlyWhen = d.readonlyWhen; + // The child FIELD's hand-lock predicate (`uiReadonlyWhen`), carried onto its + // column in memory: the cell folds it into the same per-row read-only verdict + // (`resolveFieldRuleState`). Not an `inlineColumns` key an author writes. + if (d?.uiReadonlyWhen) (col as { uiReadonlyWhen?: unknown }).uiReadonlyWhen = d.uiReadonlyWhen; if (d?.requiredWhen) col.requiredWhen = d.requiredWhen; // A field carrying an arithmetic `expression` (e.g. amount = quantity * // unit_price) becomes a live read-only computed column. The expression may @@ -432,6 +436,7 @@ export function hydrateColumns( } if (type === 'file') applyFileColumnProps(next, d); if (next.readonlyWhen == null && d?.readonlyWhen) next.readonlyWhen = d.readonlyWhen; + if ((next as { uiReadonlyWhen?: unknown }).uiReadonlyWhen == null && d?.uiReadonlyWhen) (next as { uiReadonlyWhen?: unknown }).uiReadonlyWhen = d.uiReadonlyWhen; if (next.requiredWhen == null && d?.requiredWhen) { next.requiredWhen = d.requiredWhen; } From 53379997d7cce78afd6ac600de50a493c5552cd5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 02:37:43 +0000 Subject: [PATCH 04/13] test(spec,ui,mcp): hand-lock pins for spec, core, dialogs, record page, grid, line-item grid, kanban, calendar (WIP) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXSuJCALDHFWaV6Bv5 --- .../src/__tests__/mcp-server-runtime.test.ts | 30 +++- .../mcp-object-hand-lock-36806.test.ts | 169 ++++++++++++++++++ .../spec/src/data/field-ui-readonly.test.ts | 93 ++++++++++ .../__tests__/handLock-36806.test.ts | 58 ++++++ .../widgets/GridField.handLock-36806.test.tsx | 56 ++++++ .../ObjectCalendar.handLock-36806.test.tsx | 137 ++++++++++++++ .../DetailSection.doubleClickEdit.test.tsx | 61 +++++++ .../__tests__/dialogHandLock-36806.test.ts | 44 +++++ .../src/deriveMasterDetail.test.ts | 22 +++ ...objectGridCellFacts.handLock-36806.test.ts | 53 ++++++ .../src/ObjectKanban.handLock-36806.test.tsx | 140 +++++++++++++++ .../plugin-kanban/src/ObjectKanban.tsx | 4 +- .../__tests__/form-field-zod-coverage.test.ts | 1 + 13 files changed, 864 insertions(+), 4 deletions(-) create mode 100644 packages/runtime/src/domains/mcp-object-hand-lock-36806.test.ts create mode 100644 packages/spec/src/data/field-ui-readonly.test.ts create mode 100644 ui/packages/core/src/evaluator/__tests__/handLock-36806.test.ts create mode 100644 ui/packages/fields/src/widgets/GridField.handLock-36806.test.tsx create mode 100644 ui/packages/plugin-calendar/src/__tests__/ObjectCalendar.handLock-36806.test.tsx create mode 100644 ui/packages/plugin-form/src/__tests__/dialogHandLock-36806.test.ts create mode 100644 ui/packages/plugin-grid/src/objectGridCellFacts.handLock-36806.test.ts create mode 100644 ui/packages/plugin-kanban/src/ObjectKanban.handLock-36806.test.tsx diff --git a/packages/mcp/src/__tests__/mcp-server-runtime.test.ts b/packages/mcp/src/__tests__/mcp-server-runtime.test.ts index f8de20284cf..36a40d0f5e3 100644 --- a/packages/mcp/src/__tests__/mcp-server-runtime.test.ts +++ b/packages/mcp/src/__tests__/mcp-server-runtime.test.ts @@ -3,7 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; -import { MCPServerRuntime } from '../mcp-server-runtime.js'; +import { MCPServerRuntime, describeServedObject } from '../mcp-server-runtime.js'; import type { MCPServerRuntimeConfig } from '../mcp-server-runtime.js'; import type { AIToolDefinition, ToolCallPart } from '@objectstack/spec/contracts'; import type { ToolRegistry, ToolExecutionResult } from '../types.js'; @@ -343,3 +343,31 @@ describe('MCPServerRuntime', () => { }); }); }); + +// [#36806] The stdio twin of the HTTP bridge's describe: the hand lock +// (`uiReadonly`, `uiReadonlyWhen`) is reported as its own keys, never folded +// into `readonly`, and a field that authors neither keeps its shape. The HTTP +// half is `packages/runtime/src/domains/mcp-object-hand-lock-36806.test.ts`. +describe('[#36806] describeServedObject reports the hand lock as its own keys', () => { + const described = describeServedObject({ + name: 'hand_order', + fields: { + status: { type: 'text', uiReadonly: true }, + note: { type: 'text', uiReadonlyWhen: { dialect: 'cel', source: "record.status != 'draft'" } }, + subject: { type: 'text' }, + }, + } as never) as { fields: Array> }; + const field = (name: string) => described.fields.find((f) => f.name === name)!; + + it('uiReadonly: true beside readonly: false', () => { + expect(field('status')).toMatchObject({ readonly: false, uiReadonly: true }); + }); + + it('uiReadonlyWhen as its predicate text, from an envelope too', () => { + expect(field('note')).toMatchObject({ readonly: false, uiReadonlyWhen: "record.status != 'draft'" }); + }); + + it('CONTROL — a field authoring neither carries neither key', () => { + expect('uiReadonly' in field('subject') || 'uiReadonlyWhen' in field('subject')).toBe(false); + }); +}); diff --git a/packages/runtime/src/domains/mcp-object-hand-lock-36806.test.ts b/packages/runtime/src/domains/mcp-object-hand-lock-36806.test.ts new file mode 100644 index 00000000000..5a905c19ead --- /dev/null +++ b/packages/runtime/src/domains/mcp-object-hand-lock-36806.test.ts @@ -0,0 +1,169 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36806] The HTTP MCP bridge's `describe_object` reports the HAND lock — + * `uiReadonly` and `uiReadonlyWhen` — as their own keys, never folded into + * `readonly`: `readonly` tells an agent to leave a field out of a write, and a + * hand-locked field is one an agent's write still sets (the engine never reads + * either key), while a person at the console cannot edit it. + * + * Driven over the real security layer, through the bridge the real `/mcp` + * entry builds, on the harness of `mcp-object-descriptions-34721.test.ts`. + * The stdio twin is pinned in `packages/mcp/src/__tests__/mcp-server-runtime.test.ts`. + */ + +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + OBJECT_SCHEMA_MASK_DISABLE_ENV, + SysMetadataAuditObject, + SysMetadataHistoryObject, + SysMetadataObject, +} from '@objectstack/metadata-core'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import { AUDIT_FIELD_DEFS, OWNER_FIELD_DEF } from '@objectstack/spec/data'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SecurityPlugin } from '@objectstack/plugin-security'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { HttpDispatcher } from '../http-dispatcher.js'; +// Paid at collection, not inside a case's clock: the dispatcher's reach loads it lazily. +import '@objectstack/metadata'; + +/** A kernel over `services`, with an `mcp` service that hands back the bridge `handleMcp` built. */ +function kernelOver(services: Record) { + const mcp: any = { + lastOpts: undefined, + handleHttpRequest: async (_req: Request, o: any) => { + mcp.lastOpts = o; + return new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } }); + }, + }; + const all: Record = { ...services, mcp }; + const get = (n: string) => all[n] ?? null; + return { getService: get, getServiceAsync: async (n: string) => get(n), context: { getService: get } } as any; +} + +/** Drive the real `/mcp` entry for `executionContext` and hand back the bridge it built. */ +async function bridgeFor(kernel: any, executionContext: Record) { + const dispatcher = new HttpDispatcher(kernel, undefined, { enforceProjectMembership: false }); + const res = await dispatcher.handleMcp({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, { + request: new Request('http://localhost/api/v1/mcp', { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, + body: '{}', + }), + response: {}, + environmentId: undefined, + executionContext: { ...executionContext }, + } as any); + expect(res.response?.status, 'precondition: the MCP route must have been served').toBe(200); + return kernel.getService('mcp').lastOpts.bridge; +} + +const OBJ = 'mcp_hand_order'; +const STAFF = { userId: 'usr_staff', positions: [] as string[], permissions: ['mcp_hand_staff'], systemPermissions: [] as string[] }; + +const prevMcp = process.env.OS_MCP_SERVER_ENABLED; +const prevMask = process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV]; +beforeEach(() => { + process.env.OS_MCP_SERVER_ENABLED = 'true'; + delete process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV]; +}); +afterEach(() => { + if (prevMcp === undefined) delete process.env.OS_MCP_SERVER_ENABLED; + else process.env.OS_MCP_SERVER_ENABLED = prevMcp; + if (prevMask === undefined) delete process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV]; + else process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV] = prevMask; +}); + +describe('[#36806] HTTP MCP describe_object reports uiReadonly / uiReadonlyWhen as their own keys', () => { + let engine: ObjectQL; + let services: Record; + + beforeAll(async () => { + engine = new ObjectQL(); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any); + const storeObjects = [SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject] as any[]; + await driver.initObjects(storeObjects); + engine.registerDriver(driver as any, true); + await engine.init(); + for (const o of storeObjects) engine.registry.registerObject(o, '@objectstack/platform-objects'); + engine.registerApp({ + id: 'com.objectstack.qa.mcp-object-hand-lock', + name: 'MCP object hand lock', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [ + { + name: OBJ, + label: 'Order', + sharingModel: 'public_read_write', + fields: { + subject: { name: 'subject', type: 'text', label: 'Subject' }, + status: { name: 'status', type: 'text', label: 'Status', uiReadonly: true }, + note: { name: 'note', type: 'text', label: 'Note', uiReadonlyWhen: "record.status != 'draft'" }, + locked: { name: 'locked', type: 'text', label: 'Locked', readonly: true }, + }, + }, + ], + } as never); + await engine.syncSchemas(); + const all = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }; + const sets = [PermissionSetSchema.parse({ name: 'mcp_hand_staff', label: 'Staff', objects: { '*': all } })]; + const pluginServices: Record = { + manifest: { register: vi.fn() }, + objectql: engine, + metadata: { + get: async (type: string, name: string) => + (type === 'permission' ? sets.find((s: any) => s?.name === name) : engine.getSchema(name)) ?? null, + list: async () => sets, + }, + }; + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService: vi.fn((name: string, service: unknown) => { pluginServices[name] = service; }), + getService: (name: string) => { + if (!(name in pluginServices)) throw new Error(`service not registered: ${name}`); + return pluginServices[name]; + }, + }; + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'mcp_hand_staff' }); + await plugin.init(ctx as never); + await plugin.start(ctx as never); + vi.spyOn((engine as unknown as { logger: { warn: () => void } }).logger, 'warn').mockImplementation(() => undefined); + services = { + protocol: new ObjectStackProtocolImplementation(engine as any), + security: pluginServices.security, + objectql: engine, + }; + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + }, 60_000); + + afterAll(async () => { + vi.restoreAllMocks(); + try { await engine?.destroy(); } catch { /* noop */ } + }); + + const field = (described: any, name: string) => described.fields.find((f: any) => f.name === name); + + it('a `uiReadonly` field reads uiReadonly: true and readonly: false — not UI-editable, and still a write an agent may send', async () => { + const described = await (await bridgeFor(kernelOver(services), STAFF)).describeObject(OBJ); + expect(field(described, 'status')).toMatchObject({ name: 'status', readonly: false, uiReadonly: true }); + expect('uiReadonlyWhen' in field(described, 'status')).toBe(false); + }); + + it('a `uiReadonlyWhen` field carries its predicate text, and readonly stays false', async () => { + const described = await (await bridgeFor(kernelOver(services), STAFF)).describeObject(OBJ); + expect(field(described, 'note')).toMatchObject({ readonly: false, uiReadonlyWhen: "record.status != 'draft'" }); + expect('uiReadonly' in field(described, 'note')).toBe(false); + }); + + it('CONTROL — a field that authors neither key keeps the shape it had; a `readonly` one reads readonly: true alone', async () => { + const described = await (await bridgeFor(kernelOver(services), STAFF)).describeObject(OBJ); + const subject = field(described, 'subject'); + expect('uiReadonly' in subject || 'uiReadonlyWhen' in subject).toBe(false); + expect(field(described, 'locked')).toMatchObject({ readonly: true }); + expect('uiReadonly' in field(described, 'locked')).toBe(false); + }); +}); diff --git a/packages/spec/src/data/field-ui-readonly.test.ts b/packages/spec/src/data/field-ui-readonly.test.ts new file mode 100644 index 00000000000..15ef6161bd4 --- /dev/null +++ b/packages/spec/src/data/field-ui-readonly.test.ts @@ -0,0 +1,93 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36806] The hand lock — `uiReadonly` and `uiReadonlyWhen` — the lower tier + * of the two-tier field-lock model (ruling record 7180466652): no person edits + * the field at the console, while API, import, action and flow writes keep it. + * + * Both keys are authorable field keys with no default (absent = unlocked), and + * the one pair refused is `uiReadonly: true` beside `readonly: true`, located + * at `['uiReadonly']`. `uiReadonlyWhen` beside `readonlyWhen` is accepted. The + * refusal is asserted as a full `safeParse` failure at the key; every control + * is a full `safeParse` success, never mere absence of `unrecognized_keys`. + * The line-item grid's column rule (`deriveInlineGridColumns`) skips a + * `uiReadonly` child field, as it skips a `readonly` one. + */ + +import { describe, expect, it } from 'vitest'; +import { FieldSchema } from './field.zod'; +import { ObjectSchema } from './object.zod'; +import { deriveInlineGridColumns } from './inline-grid-columns'; + +type Issue = { code: string; path: PropertyKey[]; message: string }; + +function uiReadonlyIssues(result: { success: boolean; error?: { issues: Issue[] } }): Issue[] { + if (result.success) return []; + return (result.error?.issues ?? []).filter((issue) => issue.path[issue.path.length - 1] === 'uiReadonly'); +} + +describe('Field.uiReadonly / Field.uiReadonlyWhen', () => { + it('parse, and stay absent when not authored (no default is materialised)', () => { + const locked = FieldSchema.safeParse({ name: 'status', type: 'text', uiReadonly: true }); + expect(locked.success).toBe(true); + expect(locked.success && locked.data.uiReadonly).toBe(true); + + const when = FieldSchema.safeParse({ name: 'status', type: 'text', uiReadonlyWhen: "record.stage != 'draft'" }); + expect(when.success).toBe(true); + expect(when.success && when.data.uiReadonlyWhen).toBeDefined(); + + const untouched = FieldSchema.safeParse({ name: 'status', type: 'text' }); + expect(untouched.success).toBe(true); + expect(untouched.success && ('uiReadonly' in untouched.data || 'uiReadonlyWhen' in untouched.data)).toBe(false); + }); + + it('refuses `uiReadonly: true` beside `readonly: true`, at the key, naming both locks', () => { + const issues = uiReadonlyIssues( + FieldSchema.safeParse({ name: 'status', type: 'text', readonly: true, uiReadonly: true }), + ); + expect(issues).toHaveLength(1); + expect(issues[0].code).toBe('custom'); + expect(issues[0].message).toMatch(/^`uiReadonly: true` locks the field against editing by hand at the console/); + }); + + it('refuses the pair through the object door too', () => { + const parsed = ObjectSchema.safeParse({ + name: 'sales_order', + fields: { status: { type: 'text', readonly: true, uiReadonly: true } }, + }); + expect(parsed.success).toBe(false); + expect(uiReadonlyIssues(parsed as never)).toHaveLength(1); + }); + + it('accepts the controls beside the refused pair', () => { + const controls = [ + { name: 'status', type: 'text', uiReadonly: true }, + { name: 'status', type: 'text', uiReadonly: true, readonly: false }, + { name: 'status', type: 'text', uiReadonly: false, readonly: true }, + // The conditional pair is allowed: the server lock is the stricter one. + { name: 'status', type: 'text', readonlyWhen: "record.stage == 'paid'", uiReadonlyWhen: "record.stage != 'draft'" }, + { name: 'status', type: 'text', readonly: true, uiReadonlyWhen: "record.stage != 'draft'" }, + { name: 'status', type: 'text', uiReadonly: true, uiReadonlyWhen: "record.stage != 'draft'" }, + ]; + for (const field of controls) { + const parsed = FieldSchema.safeParse(field); + expect(parsed.success, JSON.stringify(field)).toBe(true); + } + }); + + it('the line-item grid skips a `uiReadonly` child field, as it skips a `readonly` one', () => { + const columns = deriveInlineGridColumns({ + fields: { + product: { type: 'text' }, + status: { type: 'text', uiReadonly: true }, + locked: { type: 'text', readonly: true }, + note: { type: 'text', uiReadonlyWhen: "record.product == 'x'" }, + }, + } as never); + const names = columns.map((c: { name: string }) => c.name); + expect(names).toContain('product'); + expect(names).toContain('note'); + expect(names).not.toContain('status'); + expect(names).not.toContain('locked'); + }); +}); diff --git a/ui/packages/core/src/evaluator/__tests__/handLock-36806.test.ts b/ui/packages/core/src/evaluator/__tests__/handLock-36806.test.ts new file mode 100644 index 00000000000..15cbbdff6ad --- /dev/null +++ b/ui/packages/core/src/evaluator/__tests__/handLock-36806.test.ts @@ -0,0 +1,58 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * #36806 — the one hand-lock verdict folds all four field-lock keys + * (`readonly`, `readonlyWhen`, `uiReadonly`, `uiReadonlyWhen`), and the form's + * shared verdict (`resolveFieldRuleState`) folds the hand lock the same way. + */ +import { describe, it, expect } from 'vitest'; +import { + fieldReadOnlyByHand, + fieldStaticallyReadOnlyByHand, + resolveFieldRuleState, +} from '../../index'; + +describe('fieldReadOnlyByHand (#36806)', () => { + it('the static half: readonly or uiReadonly', () => { + expect(fieldStaticallyReadOnlyByHand({ uiReadonly: true })).toBe(true); + expect(fieldStaticallyReadOnlyByHand({ readonly: true })).toBe(true); + expect(fieldStaticallyReadOnlyByHand({})).toBe(false); + expect(fieldStaticallyReadOnlyByHand(undefined)).toBe(false); + // Only a literal `true` locks — no truthy coercion. + expect(fieldStaticallyReadOnlyByHand({ uiReadonly: 'yes' })).toBe(false); + }); + + it('the full verdict judges uiReadonlyWhen and readonlyWhen over the record', () => { + const def = { uiReadonlyWhen: "record.status != 'draft'" }; + expect(fieldReadOnlyByHand(def, { status: 'approved' })).toBe(true); + expect(fieldReadOnlyByHand(def, { status: 'draft' })).toBe(false); + const server = { readonlyWhen: "record.status == 'paid'" }; + expect(fieldReadOnlyByHand(server, { status: 'paid' })).toBe(true); + expect(fieldReadOnlyByHand(server, { status: 'draft' })).toBe(false); + expect(fieldReadOnlyByHand({ uiReadonly: true }, { status: 'draft' })).toBe(true); + expect(fieldReadOnlyByHand({}, { status: 'draft' })).toBe(false); + }); + + it('a predicate that cannot be evaluated leaves the field editable (fail-open)', () => { + expect(fieldReadOnlyByHand({ uiReadonlyWhen: 'record.(' }, { status: 'x' })).toBe(false); + }); +}); + +describe('resolveFieldRuleState folds the hand lock (#36806)', () => { + it('statics.uiReadonly locks', () => { + expect(resolveFieldRuleState({}, {}, { uiReadonly: true }).readonly).toBe(true); + expect(resolveFieldRuleState({}, {}, {}).readonly).toBe(false); + }); + + it('uiReadonlyWhen TRUE locks, FALSE does not', () => { + const rules = { uiReadonlyWhen: "record.status != 'draft'" }; + expect(resolveFieldRuleState(rules, { status: 'approved' }, {}).readonly).toBe(true); + expect(resolveFieldRuleState(rules, { status: 'draft' }, {}).readonly).toBe(false); + }); +}); diff --git a/ui/packages/fields/src/widgets/GridField.handLock-36806.test.tsx b/ui/packages/fields/src/widgets/GridField.handLock-36806.test.tsx new file mode 100644 index 00000000000..2962552ae42 --- /dev/null +++ b/ui/packages/fields/src/widgets/GridField.handLock-36806.test.tsx @@ -0,0 +1,56 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * #36806 — the line-item grid reads the hand lock. A child field's + * `uiReadonlyWhen`, carried onto its column by `@object-ui/plugin-form`'s + * column derivation, locks the cell on the rows its predicate is TRUE over + * (with the parent header in scope, as `readonlyWhen`), and leaves the others + * editable. (A `uiReadonly` child field never becomes a column at all: the + * spec's `deriveInlineGridColumns` skips it, pinned in `@objectstack/spec`.) + */ +import { describe, it, expect } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import React from 'react'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; + +describe('line-item grid hand lock (uiReadonlyWhen, #36806)', () => { + const field = { + columns: [ + { name: 'product', label: 'Product', type: 'text' as const }, + { name: 'qty', label: 'Qty', type: 'number' as const, uiReadonlyWhen: "parent.status != 'draft' || record.shipped == true" }, + ], + } as any; + + it('locks the cell where the predicate is TRUE, per row and over the header', () => { + render( + {}} + field={field} + contextRecord={{ status: 'draft' }} + />, + ); + const qty = screen.getAllByLabelText('Qty') as HTMLInputElement[]; + expect(qty[0].disabled).toBe(true); + expect(qty[1].disabled).toBe(false); + expect((screen.getAllByLabelText('Product')[0] as HTMLInputElement).disabled).toBe(false); + }); + + it('locks every row when the header makes the predicate TRUE', () => { + render( + {}} + field={field} + contextRecord={{ status: 'approved' }} + />, + ); + expect((screen.getAllByLabelText('Qty')[0] as HTMLInputElement).disabled).toBe(true); + }); +}); diff --git a/ui/packages/plugin-calendar/src/__tests__/ObjectCalendar.handLock-36806.test.tsx b/ui/packages/plugin-calendar/src/__tests__/ObjectCalendar.handLock-36806.test.tsx new file mode 100644 index 00000000000..72b6bdd82ce --- /dev/null +++ b/ui/packages/plugin-calendar/src/__tests__/ObjectCalendar.handLock-36806.test.tsx @@ -0,0 +1,137 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#36806 — a calendar drag is an edit by hand, so the date fields it + * writes take the one hand-lock verdict of `@object-ui/core`: a `uiReadonly` + * (or `readonly`) start field closes the drag, a locked end field the resize + * handle, and a conditional lock (`uiReadonlyWhen`) TRUE over the record takes + * the drop and writes nothing. On the harness of + * `ObjectCalendar.endEditable-29020.test.tsx`. + */ + +import React from 'react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, render, screen, waitFor, within, fireEvent } from '@testing-library/react'; +import { LocalizationProvider } from '@object-ui/i18n'; +import { ObjectCalendar } from '../ObjectCalendar'; + +const TITLE = 'Build homepage'; +const MONTH_HANDLE = 'Resize event end'; +const CLOCK = '2026-01-15T12:00:00.000Z'; + +afterEach(() => { + cleanup(); + vi.useRealTimers(); +}); + +function mount(lock: { due?: Record; end?: Record }, calendar: Record, row: Record) { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(new Date(CLOCK)); + const objectSchema = { + name: 'task', + fields: { + name: { type: 'text' }, + stage: { type: 'text' }, + due_date: { type: 'date', ...(lock.due ?? {}) }, + end_date: { type: 'date', ...(lock.end ?? {}) }, + }, + }; + const ds = { + getObjectSchema: vi.fn(async () => objectSchema), + find: vi.fn(async () => ({ value: [{ id: 't1', name: TITLE, ...row }] })), + update: vi.fn(async () => ({})), + create: vi.fn(async () => ({ id: 't2' })), + }; + const schema = { type: 'object-calendar', objectName: 'task', defaultView: 'month', calendar: { titleField: 'name', ...calendar } } as never; + render( + + + , + ); + return ds; +} + +/** `January 12, 2026` out of a month cell's accessible name. */ +function dayOf(cell: Element): string { + const m = (cell.getAttribute('aria-label') ?? '').match(/[A-Z][a-z]+ \d{1,2}, \d{4}/); + return m ? m[0] : ''; +} + +function cellFor(day: string): HTMLElement { + const cell = screen.getAllByRole('gridcell').find((c) => dayOf(c) === day); + expect(cell, `no month cell for ${day}`).toBeDefined(); + return cell as HTMLElement; +} + +/** jsdom has no DataTransfer round-trip; carry the payload in a synthetic one. */ +function performDnd(source: Element, target: Element) { + const store: Record = {}; + const dataTransfer = { + effectAllowed: '', + dropEffect: '', + setData: (k: string, v: string) => { + store[k] = v; + }, + getData: (k: string) => store[k] ?? '', + setDragImage: () => {}, + types: ['text/plain'], + }; + fireEvent.dragStart(source, { dataTransfer }); + fireEvent.dragOver(target, { dataTransfer }); + fireEvent.drop(target, { dataTransfer }); + fireEvent.dragEnd(source, { dataTransfer }); +} + + +/** Wait until the object schema has landed, so the lock reads are in force. */ +async function settled(ds: { getObjectSchema: ReturnType }) { + await screen.findAllByLabelText(TITLE); + await waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalled()); +} + +describe('ObjectCalendar: a locked date field closes the drag (objectstack#36806)', () => { + it.each([['uiReadonly', { uiReadonly: true }], ['readonly', { readonly: true }]])( + 'a `%s` start field: a drop writes nothing', + async (_name, lock) => { + const ds = mount({ due: lock }, { startDateField: 'due_date' }, { due_date: '2026-01-12' }); + await settled(ds); + const [pill] = within(cellFor('January 12, 2026')).getAllByLabelText(TITLE); + performDnd(pill, cellFor('January 13, 2026')); + await new Promise((r) => setTimeout(r, 0)); + expect(ds.update).not.toHaveBeenCalled(); + }, + ); + + it('a `uiReadonly` end field draws no resize-end handle', async () => { + const ds = mount( + { end: { uiReadonly: true } }, + { startDateField: 'due_date', endDateField: 'end_date' }, + { due_date: '2026-01-12', end_date: '2026-01-13' }, + ); + await settled(ds); + await waitFor(() => expect(screen.queryAllByLabelText(MONTH_HANDLE)).toHaveLength(0)); + }); + + it('a `uiReadonlyWhen` TRUE over the record: the drop writes nothing', async () => { + const ds = mount({ due: { uiReadonlyWhen: "record.stage == 'done'" } }, { startDateField: 'due_date' }, { due_date: '2026-01-12', stage: 'done' }); + await settled(ds); + const [pill] = within(cellFor('January 12, 2026')).getAllByLabelText(TITLE); + performDnd(pill, cellFor('January 13, 2026')); + await new Promise((r) => setTimeout(r, 0)); + expect(ds.update).not.toHaveBeenCalled(); + }); + + it('CONTROL — the same predicate FALSE over the record writes the move', async () => { + const ds = mount({ due: { uiReadonlyWhen: "record.stage == 'done'" } }, { startDateField: 'due_date' }, { due_date: '2026-01-12', stage: 'open' }); + await settled(ds); + const [pill] = within(cellFor('January 12, 2026')).getAllByLabelText(TITLE); + performDnd(pill, cellFor('January 13, 2026')); + await waitFor(() => expect(ds.update).toHaveBeenCalledWith('task', 't1', { due_date: '2026-01-13' })); + }); +}); diff --git a/ui/packages/plugin-detail/src/__tests__/DetailSection.doubleClickEdit.test.tsx b/ui/packages/plugin-detail/src/__tests__/DetailSection.doubleClickEdit.test.tsx index e9e6fd96a63..0951203a903 100644 --- a/ui/packages/plugin-detail/src/__tests__/DetailSection.doubleClickEdit.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/DetailSection.doubleClickEdit.test.tsx @@ -184,3 +184,64 @@ describe('DetailSection inline-edit — object-readonly & system-field gate', () expect(screen.queryByDisplayValue('CR-1')).toBeNull(); }); }); + +/** + * #36806 — the record page's inline edit reads the hand lock: a `uiReadonly` + * field, and a `uiReadonlyWhen` field whose predicate is TRUE over the record, + * offer no inline edit (no double-click entry, no input in global edit mode), + * exactly like `readonly`. A `uiReadonlyWhen` FALSE over the record stays + * editable (the control). + */ +describe('DetailSection hand lock (uiReadonly / uiReadonlyWhen, #36806)', () => { + beforeAll(() => { + Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1280 }); + }); + + const objectSchema = { + fields: { + title: { type: 'text' }, + status: { type: 'text', uiReadonly: true }, + note: { type: 'text', uiReadonlyWhen: "record.status != 'draft'" }, + }, + }; + const section: DetailViewSection = { + fields: [ + { name: 'title', label: 'Title' }, + { name: 'status', label: 'Status' }, + { name: 'note', label: 'Note' }, + ], + } as DetailViewSection; + + it('a uiReadonly field and a uiReadonlyWhen-TRUE field offer no inline-edit entry', () => { + const onEnter = vi.fn(); + render( + , + ); + fireEvent.doubleClick(screen.getByText('approved')); + fireEvent.doubleClick(screen.getByText('N-1')); + expect(onEnter).not.toHaveBeenCalled(); + fireEvent.doubleClick(screen.getByText('Hello')); + expect(onEnter).toHaveBeenCalledWith('title'); + }); + + it('stays read-only in global inline-edit mode; uiReadonlyWhen FALSE stays editable', () => { + render( + , + ); + expect(screen.getByDisplayValue('Hello')).toBeInTheDocument(); + expect(screen.queryByDisplayValue('draft')).toBeNull(); + // status == 'draft' → the predicate is FALSE → note is an input. + expect(screen.getByDisplayValue('N-1')).toBeInTheDocument(); + }); +}); diff --git a/ui/packages/plugin-form/src/__tests__/dialogHandLock-36806.test.ts b/ui/packages/plugin-form/src/__tests__/dialogHandLock-36806.test.ts new file mode 100644 index 00000000000..f5f929394d2 --- /dev/null +++ b/ui/packages/plugin-form/src/__tests__/dialogHandLock-36806.test.ts @@ -0,0 +1,44 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * #36806 — the create and edit dialogs read the hand lock: a `uiReadonly` + * field is left off both dialogs (as `readonly` is) and never rides in the + * payload a dialog submits, so a UI create falls back to the field's + * `defaultValue` on the server. A `uiReadonlyWhen` field stays listed — its + * predicate is judged per record by the form renderer. + */ +import { describe, it, expect } from 'vitest'; +import { filterCreateModeFields, filterSystemFields } from '../autoLayout'; +import { sanitizeFormData } from '../sanitize'; +import type { FormField } from '@object-ui/types'; + +const objectSchema = { + fields: { + title: { type: 'text' }, + status: { type: 'select', uiReadonly: true }, + note: { type: 'text', uiReadonlyWhen: "record.status != 'draft'" }, + }, +}; +const fields = [ + { name: 'title', type: 'text' }, + { name: 'status', type: 'select' }, + { name: 'note', type: 'text' }, +] as FormField[]; + +describe('dialog hand lock (#36806)', () => { + it('a uiReadonly field is off the create and the edit dialog; uiReadonlyWhen stays', () => { + expect(filterCreateModeFields(fields, objectSchema).map((f) => f.name)).toEqual(['title', 'note']); + expect(filterSystemFields(fields, objectSchema).map((f) => f.name)).toEqual(['title', 'note']); + }); + + it('a uiReadonly field never rides in the submitted payload', () => { + const out = sanitizeFormData({ title: 'A', status: 'approved', note: 'n' }, objectSchema); + expect(out).toEqual({ title: 'A', note: 'n' }); + }); +}); diff --git a/ui/packages/plugin-form/src/deriveMasterDetail.test.ts b/ui/packages/plugin-form/src/deriveMasterDetail.test.ts index a45eee97069..ea7bd0c551b 100644 --- a/ui/packages/plugin-form/src/deriveMasterDetail.test.ts +++ b/ui/packages/plugin-form/src/deriveMasterDetail.test.ts @@ -652,3 +652,25 @@ describe('people, multi-select, tags, check and rating columns take their extras expect(cols[1]).toEqual({ name: 'stars', type: 'rating', max: 3 }); }); }); + +describe('line-item columns and the hand lock (#36806)', () => { + it('skips a uiReadonly child field and carries a uiReadonlyWhen one onto its column', () => { + const schema = { + name: 'line', + fields: { + parent: { type: 'master_detail', reference: 'order' }, + product: { type: 'text', label: 'Product' }, + status: { type: 'text', label: 'Status', uiReadonly: true }, + qty: { type: 'number', label: 'Qty', uiReadonlyWhen: "parent.status != 'draft'" }, + }, + }; + const cols = deriveColumns(schema, { booleanLabel, relationshipField: 'parent' }); + const byName = Object.fromEntries(cols.map((c) => [c.name, c])); + expect(byName.status).toBeUndefined(); + expect((byName.qty as { uiReadonlyWhen?: unknown }).uiReadonlyWhen).toBe("parent.status != 'draft'"); + expect((byName.product as { uiReadonlyWhen?: unknown }).uiReadonlyWhen).toBeUndefined(); + // An authored column list keeps the predicate too (the hydrate path). + const hydrated = hydrateColumns([{ name: 'qty' }], schema, { booleanLabel }); + expect((hydrated[0] as { uiReadonlyWhen?: unknown }).uiReadonlyWhen).toBe("parent.status != 'draft'"); + }); +}); diff --git a/ui/packages/plugin-grid/src/objectGridCellFacts.handLock-36806.test.ts b/ui/packages/plugin-grid/src/objectGridCellFacts.handLock-36806.test.ts new file mode 100644 index 00000000000..714c9807ada --- /dev/null +++ b/ui/packages/plugin-grid/src/objectGridCellFacts.handLock-36806.test.ts @@ -0,0 +1,53 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * #36806 — grid inline edit reads the hand lock. A `uiReadonly` column names + * the `readonly` reason; a `uiReadonlyWhen` column names it on the rows its + * predicate is TRUE over and edits on the others. The cell gate is the one + * the data table's paste and multi-row staging read (`readOnlyReasonOf`), so + * the multi-row save is locked by the same verdict. + */ +import { describe, it, expect } from 'vitest'; +import { cellReadOnlyKind, type CellReadOnlyInputs } from './objectGridCellFacts'; +import { fieldInlineReadOnlyKind, isFieldInlineEditable } from './inline-edit-options'; + +const OPEN: CellReadOnlyInputs = { + fieldDef: { type: 'text' }, + fieldWritable: true, + gridEditable: true, + objectEditable: true, + canUpdate: true, + approvalLocked: false, + recordUpdate: true, +}; + +describe('grid hand lock (#36806)', () => { + it('a uiReadonly column is read-only with the readonly reason', () => { + expect(fieldInlineReadOnlyKind({ type: 'text', uiReadonly: true })).toBe('readonly'); + expect(isFieldInlineEditable({ type: 'text', uiReadonly: true })).toBe(false); + expect(cellReadOnlyKind({ ...OPEN, fieldDef: { type: 'text', uiReadonly: true } })).toBe('readonly'); + }); + + it('a uiReadonlyWhen column is judged per row', () => { + const fieldDef = { type: 'text', uiReadonlyWhen: "record.status != 'draft'" }; + expect(cellReadOnlyKind({ ...OPEN, fieldDef, row: { status: 'approved' } })).toBe('readonly'); + expect(cellReadOnlyKind({ ...OPEN, fieldDef, row: { status: 'draft' } })).toBeNull(); + }); + + it('readonlyWhen TRUE over the row locks the cell too (the same verdict)', () => { + const fieldDef = { type: 'text', readonlyWhen: "record.status == 'paid'" }; + expect(cellReadOnlyKind({ ...OPEN, fieldDef, row: { status: 'paid' } })).toBe('readonly'); + expect(cellReadOnlyKind({ ...OPEN, fieldDef, row: { status: 'draft' } })).toBeNull(); + }); + + it('controls: a plain column edits', () => { + expect(fieldInlineReadOnlyKind({ type: 'text' })).toBeNull(); + expect(cellReadOnlyKind({ ...OPEN, row: { status: 'approved' } })).toBeNull(); + }); +}); diff --git a/ui/packages/plugin-kanban/src/ObjectKanban.handLock-36806.test.tsx b/ui/packages/plugin-kanban/src/ObjectKanban.handLock-36806.test.tsx new file mode 100644 index 00000000000..35291610337 --- /dev/null +++ b/ui/packages/plugin-kanban/src/ObjectKanban.handLock-36806.test.tsx @@ -0,0 +1,140 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#36806 — a kanban drag writes the lane field, so the lane field's + * own lock closes it, through the one hand-lock verdict of `@object-ui/core` + * (`fieldReadOnlyByHand`): `uiReadonly` (the hand lock) and `readonly` (the + * server lock) draw every card as not movable and hand no drop to the write; + * a conditional lock (`uiReadonlyWhen`) TRUE over the dragged record takes the + * drop and writes nothing. Before, the board read no field lock at all, so a + * `readonly` lane field took the drop and the write was silently stripped. + * + * The harness is `ObjectKanban.moveGrant-12082.test.tsx`'s: the drop is + * synthesized through `DndContext`'s real `onDragEnd`, captured by the module + * mock below; the card's `aria-disabled` is dnd-kit's sortable state. + */ +import React from 'react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, act, cleanup, waitFor } from '@testing-library/react'; +import { registerAllFields } from '@object-ui/fields'; +import { toast } from '@object-ui/components'; +import type { DataSource, ObjectKanbanSchema } from '@object-ui/types'; +import { ObjectKanban } from './ObjectKanban'; + +// Pay the board's lazy chunk at import time (AGENTS.md §测试纪律); specifier +// byte-identical to the component's own lazy import. +import './KanbanImpl'; + +const dnd = vi.hoisted(() => ({ + onDragEnd: undefined as undefined | ((event: unknown) => void), +})); + +vi.mock('@dnd-kit/core', async (importOriginal) => { + const actual = await importOriginal(); + const ReactMod = await import('react'); + const CapturingDndContext = (props: Record) => { + dnd.onDragEnd = props.onDragEnd as (event: unknown) => void; + return ReactMod.createElement(actual.DndContext, props as never); + }; + return { ...actual, DndContext: CapturingDndContext }; +}); + +registerAllFields(); + +const OBJECT = 'task'; +const CARD = 'Fix the widget'; + +const statusField = (lock: Record) => ({ + type: 'picklist', + label: 'Status', + options: [ + { value: 'backlog', label: 'Backlog' }, + { value: 'in_progress', label: 'In Progress' }, + ], + ...lock, +}); + +const schema = { + type: 'object-kanban', + objectName: OBJECT, + groupBy: 'status', + cardTitle: 'title', + columns: [ + { id: 'backlog', title: 'Backlog' }, + { id: 'in_progress', title: 'In Progress' }, + ], +} satisfies ObjectKanbanSchema; + +function makeDataSource(lock: Record) { + return { + getObjectSchema: vi.fn(async () => ({ name: OBJECT, fields: { title: { type: 'text', label: 'Title' }, status: statusField(lock) } })), + find: vi.fn(async () => ({ value: [{ id: 't1', title: CARD, status: 'backlog' }] })), + update: vi.fn(async () => ({ id: 't1', status: 'in_progress' })), + } as unknown as DataSource & { update: ReturnType }; +} + +async function mountBoard(lock: Record) { + const ds = makeDataSource(lock); + render(); + expect(await screen.findByText(CARD)).toBeTruthy(); + await act(async () => { + await Promise.resolve(); + await Promise.resolve(); + }); + await waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalled()); + return ds; +} + +const cardNode = () => screen.getByRole('button', { name: CARD }); + +async function dropOnInProgress() { + expect(dnd.onDragEnd).toBeTypeOf('function'); + await act(async () => { + dnd.onDragEnd!({ active: { id: 't1' }, over: { id: 'in_progress' } }); + }); +} + +beforeEach(() => { + dnd.onDragEnd = undefined; + vi.spyOn(toast, 'error').mockImplementation(() => 'toast-id' as never); +}); + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +describe('ObjectKanban: the lane field\'s lock closes the drag (objectstack#36806)', () => { + it.each([ + ['uiReadonly', { uiReadonly: true }], + ['readonly', { readonly: true }], + ])('a `%s` lane field draws the cards as not movable, and a drop writes nothing', async (_name, lock) => { + const ds = await mountBoard(lock); + await waitFor(() => expect(cardNode().getAttribute('aria-disabled')).toBe('true')); + await dropOnInProgress(); + expect(ds.update).not.toHaveBeenCalled(); + }); + + it('a `uiReadonlyWhen` TRUE over the dragged record takes the drop and writes nothing', async () => { + const ds = await mountBoard({ uiReadonlyWhen: "record.status == 'backlog'" }); + expect(cardNode().getAttribute('aria-disabled')).toBe('false'); + await dropOnInProgress(); + expect(ds.update).not.toHaveBeenCalled(); + }); + + it('CONTROL — a `uiReadonlyWhen` FALSE over the record, and no lock at all, write the move', async () => { + for (const lock of [{ uiReadonlyWhen: "record.status == 'in_progress'" }, {}]) { + const ds = await mountBoard(lock); + expect(cardNode().getAttribute('aria-disabled')).toBe('false'); + await dropOnInProgress(); + await waitFor(() => expect(ds.update).toHaveBeenCalledWith(OBJECT, 't1', { status: 'in_progress' })); + cleanup(); + } + }); +}); diff --git a/ui/packages/plugin-kanban/src/ObjectKanban.tsx b/ui/packages/plugin-kanban/src/ObjectKanban.tsx index d1906f3ea55..d930a93b8da 100644 --- a/ui/packages/plugin-kanban/src/ObjectKanban.tsx +++ b/ui/packages/plugin-kanban/src/ObjectKanban.tsx @@ -2095,9 +2095,7 @@ export const ObjectKanban: React.FC = ({ // card as not movable; the conditional half is judged per card at the drop, // in `handleCardMove`. Before this the board read no field lock at all, so a // `readonly` lane field took the drop and its write was silently stripped. - const laneFieldDef = schema.groupBy - ? (objectDef?.fields as Record | undefined> | undefined)?.[schema.groupBy] - : undefined; + // `laneFieldDef` is the lane field's definition, read above for its lane titles. const laneFieldLocked = fieldStaticallyReadOnlyByHand(laneFieldDef); // The board's drop gate (#25933): a lane is a value of `groupBy`, so when the diff --git a/ui/packages/types/src/__tests__/form-field-zod-coverage.test.ts b/ui/packages/types/src/__tests__/form-field-zod-coverage.test.ts index 189e978647e..feca53c9663 100644 --- a/ui/packages/types/src/__tests__/form-field-zod-coverage.test.ts +++ b/ui/packages/types/src/__tests__/form-field-zod-coverage.test.ts @@ -72,6 +72,7 @@ const DECLARED_KEYS = [ 'visibleOn', 'visibleWhen', 'readonlyWhen', + 'uiReadonlyWhen', 'requiredWhen', 'colSpan', 'span', From 7a4d8dd6953f552695fcdf6da9b2b214496a9d03 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 02:43:51 +0000 Subject: [PATCH 05/13] test(dogfood,mcp): write-keeps pin over PATCH, import and action; changeset (WIP) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXSuJCALDHFWaV6Bv5 --- .../36806-field-ui-readonly-hand-lock.md | 34 ++++ ...i-readonly-hand-lock-36806.dogfood.test.ts | 172 ++++++++++++++++++ 2 files changed, 206 insertions(+) create mode 100644 .changeset/36806-field-ui-readonly-hand-lock.md create mode 100644 packages/qa/dogfood/test/ui-readonly-hand-lock-36806.dogfood.test.ts diff --git a/.changeset/36806-field-ui-readonly-hand-lock.md b/.changeset/36806-field-ui-readonly-hand-lock.md new file mode 100644 index 00000000000..4f07b638f7d --- /dev/null +++ b/.changeset/36806-field-ui-readonly-hand-lock.md @@ -0,0 +1,34 @@ +--- +'@objectstack/spec': minor +'@objectstack/runtime': patch +'@objectstack/mcp': patch +'@object-ui/core': minor +'@object-ui/types': patch +'@object-ui/components': patch +'@object-ui/fields': patch +'@object-ui/plugin-form': patch +'@object-ui/plugin-detail': patch +'@object-ui/plugin-grid': patch +'@object-ui/plugin-kanban': patch +'@object-ui/plugin-calendar': patch +'@object-ui/app-shell': patch +--- + +feat(spec,ui): a field can be read-only by hand at the console while actions, imports, the API and flows keep writing it (`uiReadonly` / `uiReadonlyWhen`) + +Clause-②: yes (widening: two new optional authorable keys `Field.uiReadonly` and `Field.uiReadonlyWhen`) +Metadata-protocol: added +Skills-docs: follow-up #37405 + +A status column that only moves through actions, or a field an integration fills, used to have no honest declaration: `readonly: true` also strips every client write, so the action, the import and the API lost the field too. Fields now carry two lock tiers: + +| | server lock: no client writes | hand lock: no person edits at the console | +|:--|:--|:--| +| always | `readonly` | `uiReadonly` | +| conditional | `readonlyWhen` | `uiReadonlyWhen` (CEL, the same scope as `readonlyWhen`) | + +- **`uiReadonly: true` / `uiReadonlyWhen`.** Every console surface a person edits through locks the field: the create and edit dialogs (the field is left off them and out of the payload they submit, so a create from the console lands on the field's `defaultValue`), the record page's inline edit and stage path, the highlight-strip chip, grid inline edit and its multi-row save, kanban drag between columns grouped by the field, calendar drag, and the line-item grid (a `uiReadonly` child field is not a column; a `uiReadonlyWhen` one locks its cell per row). The engine never reads either key, so REST, import, declarative and script actions, and flows write the field, and the object's validations (a `state_machine`, for one) judge each write. +- **Refused: `uiReadonly: true` beside `readonly: true`** (at `['uiReadonly']`, at every door that parses a field: `defineStack`, `os validate`, metadata save). Keep one: `readonly` when no client may write the field, `uiReadonly` when people at the console may not. `uiReadonlyWhen` beside `readonlyWhen` is accepted. +- **Kanban: a `readonly` lane field no longer drags.** The board read no field lock before, so a card grouped by a `readonly` field could be dragged and its PATCH was silently stripped. The board now reads both locks. +- **`@object-ui/core` exports the one verdict:** `fieldReadOnlyByHand(def, record?, context?)`, `fieldStaticallyReadOnlyByHand(def)`, `fieldHasConditionalHandLock(def)`. `resolveFieldRuleState` takes `uiReadonlyWhen` in its rules and `uiReadonly` in its statics. The import wizard's target mapping and the Studio/designer reads stay on the raw `readonly`. +- **MCP `describe_object`** reports `uiReadonly` and `uiReadonlyWhen` as their own keys where set (never folded into `readonly`, which tells an agent to leave the field out of a write), on the HTTP and the stdio transport, and the tool description names them. diff --git a/packages/qa/dogfood/test/ui-readonly-hand-lock-36806.dogfood.test.ts b/packages/qa/dogfood/test/ui-readonly-hand-lock-36806.dogfood.test.ts new file mode 100644 index 00000000000..d674ff6e48d --- /dev/null +++ b/packages/qa/dogfood/test/ui-readonly-hand-lock-36806.dogfood.test.ts @@ -0,0 +1,172 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#36806] The hand lock keeps every write path open (ruling record +// 7180466652, the two-tier field-lock model). `uiReadonly: true` locks a field +// against editing by hand at the console and NOTHING else: the engine's +// readonly strip keys on `readonly` alone, so a REST PATCH, an import and a +// declarative action all write the field, and the object's validations judge +// each write. Proven here over the real HTTP stack of a booted scratch app: +// +// - a PATCH to the `uiReadonly` field lands, and the answer carries no +// `X-ObjectStack-Dropped-Fields` (the control: the same PATCH to a +// `readonly` sibling is stripped and advertised, as it always was); +// - the object's `state_machine` judges the write the hand lock no longer +// gates: an illegal move is refused with the machine's own message on the +// PATCH door, the import door and the action door alike; +// - a create that leaves the field out (what the console's create dialog +// submits, since a hand-locked field is never in its payload) lands on the +// field's `defaultValue`, and an API create outside `initialStates` is +// refused by the machine, not by the lock. + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { defineStack } from '@objectstack/spec'; +import { ObjectSchema, Field } from '@objectstack/spec/data'; + +const OBJ = 'hlk_order'; +const MACHINE_MESSAGE = 'An order moves draft, then submitted, then approved; an approved order never moves back.'; +const idOf = (b: any): string => String(b?.id ?? b?.record?.id ?? b?.data?.id ?? ''); +const recordOf = (b: any) => b?.record ?? b?.data ?? b; + +const order = ObjectSchema.create({ + name: OBJ, + label: 'Order', + pluralLabel: 'Orders', + fields: { + name: Field.text({ label: 'Name', required: true }), + status: { + ...Field.select(['draft', 'submitted', 'approved'], { label: 'Status' }), + defaultValue: 'draft', + uiReadonly: true, + }, + locked_note: Field.text({ label: 'Locked note', readonly: true }), + }, + validations: [ + { + type: 'state_machine', + name: 'hlk_order_flow', + message: MACHINE_MESSAGE, + field: 'status', + initialStates: ['draft'], + transitions: { draft: ['submitted'], submitted: ['approved', 'draft'], approved: [] }, + }, + ], + actions: [ + { name: 'hlk_submit', label: 'Submit', objectName: OBJ, operation: 'update', patch: { status: 'submitted' } }, + { name: 'hlk_back_to_draft', label: 'Back to draft', objectName: OBJ, operation: 'update', patch: { status: 'draft' } }, + ], +} as never); + +const stackConfig = defineStack({ + manifest: { + id: 'com.dogfood.ui-readonly-hand-lock', + namespace: 'hlk', + version: '0.0.0', + type: 'app', + name: 'Hand Lock Fixture', + description: 'One object whose status is locked by hand at the console and judged by a state machine on every write.', + }, + objects: [order], +} as never); + +describe('[#36806] a uiReadonly field keeps every write path, judged by the validations', () => { + let stack: VerifyStack; + let admin = ''; + + const create = async (name: string): Promise => { + const res = await stack.apiAs(admin, 'POST', `/data/${OBJ}`, { name }); + expect(res.status, await res.clone().text()).toBe(201); + return idOf(await res.json()); + }; + const statusOf = async (id: string) => + recordOf(await (await stack.apiAs(admin, 'GET', `/data/${OBJ}/${id}`)).json()).status; + /** Walk a fresh order to `approved` through the PATCH door. */ + const approved = async (name: string): Promise => { + const id = await create(name); + for (const status of ['submitted', 'approved']) { + const res = await stack.apiAs(admin, 'PATCH', `/data/${OBJ}/${id}`, { status }); + expect(res.status, await res.clone().text()).toBe(200); + } + expect(await statusOf(id)).toBe('approved'); + return id; + }; + + beforeAll(async () => { + stack = await bootStack(stackConfig as never); + admin = await stack.signIn(); + }, 240_000); + + afterAll(async () => { + await stack?.stop?.(); + }); + + it('a create that leaves the hand-locked field out lands on its defaultValue', async () => { + const id = await create('hlk default'); + expect(await statusOf(id)).toBe('draft'); + }); + + it('a PATCH to the uiReadonly field lands with no X-ObjectStack-Dropped-Fields; a readonly sibling is still stripped', async () => { + const id = await create('hlk patch'); + const res = await stack.apiAs(admin, 'PATCH', `/data/${OBJ}/${id}`, { status: 'submitted' }); + const body: any = await res.json(); + expect(res.status, JSON.stringify(body)).toBe(200); + expect(res.headers.get('X-ObjectStack-Dropped-Fields')).toBeNull(); + expect(body?.droppedFields, JSON.stringify(body?.droppedFields)).toBeUndefined(); + expect(await statusOf(id)).toBe('submitted'); + + // The control: the server lock still strips, and says so. + const control = await stack.apiAs(admin, 'PATCH', `/data/${OBJ}/${id}`, { locked_note: 'forged' }); + expect(control.status).toBe(200); + expect(control.headers.get('X-ObjectStack-Dropped-Fields') ?? '').toContain('locked_note;reason=readonly'); + }); + + it('PATCH door: an illegal move is refused with the state machine\'s message, and the field keeps its value', async () => { + const id = await approved('hlk patch refused'); + const res = await stack.apiAs(admin, 'PATCH', `/data/${OBJ}/${id}`, { status: 'draft' }); + const body: any = await res.json(); + const code = body?.error?.code ?? body?.code; + expect({ status: res.status, code }, JSON.stringify(body)).toEqual({ status: 400, code: 'VALIDATION_FAILED' }); + expect(JSON.stringify(body)).toContain(MACHINE_MESSAGE); + expect(await statusOf(id)).toBe('approved'); + }); + + it('action door: a declarative update writes the field, and the machine refuses an illegal move', async () => { + const id = await create('hlk action'); + const ok = await stack.apiAs(admin, 'POST', `/actions/${OBJ}/hlk_submit`, { recordId: id }); + expect(ok.status, await ok.clone().text()).toBe(200); + expect(await statusOf(id)).toBe('submitted'); + + const lockedId = await approved('hlk action refused'); + const res = await stack.apiAs(admin, 'POST', `/actions/${OBJ}/hlk_back_to_draft`, { recordId: lockedId }); + const body: any = await res.json(); + const code = body?.error?.code ?? body?.code; + expect({ status: res.status, code }, JSON.stringify(body)).toEqual({ status: 400, code: 'VALIDATION_FAILED' }); + expect(JSON.stringify(body)).toContain(MACHINE_MESSAGE); + expect(await statusOf(lockedId)).toBe('approved'); + }); + + it('import door: an update row writes the field, and the machine refuses an illegal move on its row', async () => { + const movable = await create('hlk import'); + const lockedId = await approved('hlk import refused'); + const res = await stack.apiAs(admin, 'POST', `/data/${OBJ}/import`, { + format: 'json', + writeMode: 'update', + matchFields: ['id'], + rows: [{ id: movable, status: 'submitted' }, { id: lockedId, status: 'draft' }], + }); + const report: any = await res.json(); + expect(res.status, JSON.stringify(report)).toBe(200); + expect(report.results?.[0]?.ok, JSON.stringify(report.results)).toBe(true); + expect(report.results?.[1]?.ok, JSON.stringify(report.results)).toBe(false); + expect(JSON.stringify(report.results?.[1])).toContain(MACHINE_MESSAGE); + expect(await statusOf(movable)).toBe('submitted'); + expect(await statusOf(lockedId)).toBe('approved'); + }); + + it('an API create outside initialStates is refused by the machine, not by the lock', async () => { + const res = await stack.apiAs(admin, 'POST', `/data/${OBJ}`, { name: 'hlk born approved', status: 'approved' }); + const body: any = await res.json(); + const code = body?.error?.code ?? body?.code; + expect({ status: res.status, code }, JSON.stringify(body)).toEqual({ status: 400, code: 'VALIDATION_FAILED' }); + }); +}); From 9c72ad912d4bdde84916417a26622c801ba9a7ab Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 03:22:53 +0000 Subject: [PATCH 06/13] chore(driver-sql,metadata-core,metadata-protocol): classify uiReadonly / uiReadonlyWhen in the FieldSchema key censuses Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXSuJCALDHFWaV6Bv5 --- packages/drivers/driver-sql/src/builtin-column-collision.ts | 2 ++ packages/metadata-core/src/object-schema-fls-references.ts | 5 +++++ .../src/protocol.meta-types-degenerate-derivation.test.ts | 4 +++- .../runtime/src/domains/mcp-object-hand-lock-36806.test.ts | 1 - 4 files changed, 10 insertions(+), 2 deletions(-) diff --git a/packages/drivers/driver-sql/src/builtin-column-collision.ts b/packages/drivers/driver-sql/src/builtin-column-collision.ts index e4f92361beb..b7520336c29 100644 --- a/packages/drivers/driver-sql/src/builtin-column-collision.ts +++ b/packages/drivers/driver-sql/src/builtin-column-collision.ts @@ -122,8 +122,10 @@ export const FIELD_KEY_STORAGE_CLASS: Readonly> = transferBehavior: 'presentation', // a Change Owner cascade of the relationship (ruling 7000907189 point 4) — read by the Change Owner action, never by `createColumn` internal: 'presentation', readonly: 'presentation', + uiReadonly: 'presentation', // the console's hand lock (#36806) — read by the console's edit surfaces, never by `createColumn` visibleWhen: 'presentation', readonlyWhen: 'presentation', + uiReadonlyWhen: 'presentation', // the hand lock's CEL predicate (#36806) — read by the console, never by `createColumn` requiredWhen: 'presentation', // `conditionalRequired` (the pre-17 spelling of `requiredWhen`) was a row // here while the spec carried its tombstone; the tombstone aged out of diff --git a/packages/metadata-core/src/object-schema-fls-references.ts b/packages/metadata-core/src/object-schema-fls-references.ts index 68a73acd7c1..973edcfe25e 100644 --- a/packages/metadata-core/src/object-schema-fls-references.ts +++ b/packages/metadata-core/src/object-schema-fls-references.ts @@ -635,6 +635,8 @@ export const FIELD_REFERENCE_POSITIONS: Readonly> = { // A boolean facet: whether a create surface asks for this field (#36425); // it names no field. showOnCreate: keep, + // A boolean facet: the console's hand lock (#36806); it names no field. + uiReadonly: keep, requiredPermissions: keep, maskingRule: keep, ackPlaintextMasking: keep, system: keep, sortable: keep, inlineHelpText: keep, placeholder: keep, externalId: keep, // A boolean facet of this date field: it declares the field a deadline @@ -681,6 +683,9 @@ export const FIELD_REFERENCE_POSITIONS: Readonly> = { expression, visibleWhen: expression, readonlyWhen: expression, + // The hand lock's predicate (#36806), CEL over this object's record as + // `readonlyWhen` is. + uiReadonlyWhen: expression, requiredWhen: expression, // The deadline's settle predicate (#22227), a `visibleWhen`-family CEL over // this object's record. Deleted when it mentions a denied field: the caller diff --git a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts index 9584a8f7e1a..91ba0ca677c 100644 --- a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts +++ b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts @@ -407,8 +407,10 @@ describe('#17501 — /meta/types serves a real schema for `action`, and moves no // actions and which are buttons, per action scope (list, record). // [#35315] `field` 86 → 87: `transferBehavior`, whether Change Owner on the // referenced record can cascade along the reference. + // [#36806] `field` 87 → 89: `uiReadonly` and `uiReadonlyWhen`, the hand + // lock (no person edits the field at the console; writes keep it). const CARD_PROPERTY_COUNTS: Record = { - agent: 24, app: 24, dashboard: 21, dataset: 17, field: 87, flow: 24, + agent: 24, app: 24, dashboard: 21, dataset: 17, field: 89, flow: 24, hook: 24, object: 52, page: 28, position: 14, report: 24, skill: 17, tool: 14, }; diff --git a/packages/runtime/src/domains/mcp-object-hand-lock-36806.test.ts b/packages/runtime/src/domains/mcp-object-hand-lock-36806.test.ts index 5a905c19ead..6e455722475 100644 --- a/packages/runtime/src/domains/mcp-object-hand-lock-36806.test.ts +++ b/packages/runtime/src/domains/mcp-object-hand-lock-36806.test.ts @@ -20,7 +20,6 @@ import { SysMetadataObject, } from '@objectstack/metadata-core'; import { PermissionSetSchema } from '@objectstack/spec/security'; -import { AUDIT_FIELD_DEFS, OWNER_FIELD_DEF } from '@objectstack/spec/data'; import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; import { SecurityPlugin } from '@objectstack/plugin-security'; From 86e274964ecb2e56b433a82eb154104fd5522497 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 04:18:51 +0000 Subject: [PATCH 07/13] feat(spec,platform-objects): the Studio field form offers uiReadonly and uiReadonlyWhen, translated in every metadata-forms locale Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXSuJCALDHFWaV6Bv5 --- .../src/apps/translations/ar.metadata-forms.generated.ts | 8 ++++++++ .../src/apps/translations/de.metadata-forms.generated.ts | 8 ++++++++ .../src/apps/translations/en.metadata-forms.generated.ts | 8 ++++++++ .../apps/translations/es-ES.metadata-forms.generated.ts | 8 ++++++++ .../src/apps/translations/fr.metadata-forms.generated.ts | 8 ++++++++ .../apps/translations/ja-JP.metadata-forms.generated.ts | 8 ++++++++ .../src/apps/translations/ko.metadata-forms.generated.ts | 8 ++++++++ .../apps/translations/pt-BR.metadata-forms.generated.ts | 8 ++++++++ .../src/apps/translations/ru.metadata-forms.generated.ts | 8 ++++++++ .../apps/translations/zh-CN.metadata-forms.generated.ts | 8 ++++++++ .../apps/translations/zh-Hant.metadata-forms.generated.ts | 8 ++++++++ packages/spec/src/data/field.form.ts | 6 ++++++ 12 files changed, 94 insertions(+) diff --git a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index 43316d31730..30a5343fd8d 100644 --- a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts @@ -893,6 +893,10 @@ export const arMetadataForms: NonNullable = { label: "للقراءة فقط", helpText: "الحقل للقراءة فقط في النماذج" }, + uiReadonly: { + label: "للقراءة فقط في الواجهة", + helpText: "لا يمكن لأحد تعديل هذا الحقل يدويًا في وحدة التحكم (مربعات الحوار وصفحة السجل والشبكات والسحب في كانبان والتقويم)، بينما تواصل الإجراءات والاستيرادات وواجهة API والتدفقات الكتابة فيه، وتحكم قواعد التحقق الخاصة بالكائن على كل كتابة. اتركه معطلًا عند تفعيل للقراءة فقط: فهو يمنع بالفعل كل كتابة من العميل." + }, hidden: { label: "مخفي", helpText: "إخفاء الحقل من طرق عرض الواجهة الافتراضية" @@ -917,6 +921,10 @@ export const arMetadataForms: NonNullable = { label: "للقراءة فقط عندما", helpText: "شرط CEL على السجل (مثل record.status == 'paid') — يكون الحقل للقراءة فقط ما دام صحيحًا (TRUE)، ويُفرض من جهة الخادم: يُسقَط تغيير التحديث على حقل مقفل وتُحفظ القيمة المخزَّنة. يقرأ أعمدة السجل نفسه؛ ويرفض objectstack validate القراءة عبر حقل مرجعي." }, + uiReadonlyWhen: { + label: "للقراءة فقط في الواجهة عندما", + helpText: "شرط CEL على السجل (مثل record.status != 'draft') — لا يمكن لأحد تعديل الحقل في وحدة التحكم ما دام TRUE؛ وتواصل الإجراءات والاستيرادات وواجهة API والتدفقات الكتابة فيه، وتحكم عليها قواعد التحقق الخاصة بالكائن. يقرأ أعمدة السجل نفسه، كما يفعل للقراءة فقط عندما." + }, requiredWhen: { label: "مطلوب عندما", helpText: "شرط CEL على السجل — يكون الحقل مطلوبًا ما دام صحيحًا (TRUE)، ويُفرض من جهة الخادم كبوابة انتقال: تُرفض الكتابة التي تترك القيمة مفقودة إذا كان السجل ممتثلًا قبلها، لذا يظل الصف الذي تنقصه القيمة أصلًا يجتاز التعديلات غير المتعلقة. لقاعدة يجب أن تستوفيها كل كتابة، استخدم قاعدة script في validations. يُرفض بجانب storage.notNull." diff --git a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index 2418140afd6..20052c43420 100644 --- a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts @@ -893,6 +893,10 @@ export const deMetadataForms: NonNullable = { label: "Schreibgeschützt", helpText: "Das Feld ist in Formularen schreibgeschützt" }, + uiReadonly: { + label: "In der Oberfläche schreibgeschützt", + helpText: "Niemand kann dieses Feld in der Konsole von Hand bearbeiten (Dialoge, Datensatzseite, Tabellen, Ziehen im Kanban und Kalender), während Aktionen, Importe, die API und Flows es weiterhin schreiben; jeder Schreibvorgang wird von den Validierungen des Objekts beurteilt. Ausgeschaltet lassen, wenn Schreibgeschützt eingeschaltet ist: Das hält bereits jeden Client-Schreibvorgang fern." + }, hidden: { label: "Ausgeblendet", helpText: "Feld in den Standardansichten der Oberfläche ausblenden" @@ -917,6 +921,10 @@ export const deMetadataForms: NonNullable = { label: "Schreibgeschützt wenn", helpText: "CEL-Prädikat über den Datensatz (z. B. record.status == 'paid') – das Feld ist schreibgeschützt, solange es TRUE ist, serverseitig durchgesetzt: Die Änderung eines gesperrten Felds durch eine Aktualisierung wird verworfen und der gespeicherte Wert behalten. Liest die eigenen Spalten des Datensatzes; objectstack validate lehnt ein Lesen über ein Referenzfeld ab." }, + uiReadonlyWhen: { + label: "In der Oberfläche schreibgeschützt wenn", + helpText: "CEL-Prädikat über den Datensatz (z. B. record.status != 'draft') – solange es TRUE ist, kann niemand das Feld in der Konsole bearbeiten; Aktionen, Importe, die API und Flows schreiben es weiterhin, beurteilt von den Validierungen des Objekts. Liest die eigenen Spalten des Datensatzes, wie Schreibgeschützt wenn." + }, requiredWhen: { label: "Erforderlich wenn", helpText: "CEL-Prädikat über den Datensatz – das Feld ist erforderlich, solange es TRUE ist, serverseitig als Übergangsschranke durchgesetzt: Ein Schreibvorgang, der den Wert fehlen lässt, wird abgelehnt, wenn der Datensatz die Regel zuvor erfüllte; eine Zeile, der der Wert bereits fehlt, besteht daher weiterhin unabhängige Bearbeitungen. Für eine Regel, die jeder Schreibvorgang erfüllen muss, verwenden Sie eine Skriptregel unter validations. Neben storage.notNull abgelehnt." diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index 44c4749a0ef..8258938c035 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -893,6 +893,10 @@ export const enMetadataForms: NonNullable = { label: "Readonly", helpText: "Field is read-only in forms" }, + uiReadonly: { + label: "Ui Readonly", + helpText: "People cannot edit this field in the console (dialogs, the record page, grids, kanban and calendar drag), while actions, imports, the API and flows still write it, each write judged by the object's validations. Leave it off when Read-only is on: that one already keeps every client write out." + }, hidden: { label: "Hidden", helpText: "Hide field from default UI views" @@ -917,6 +921,10 @@ export const enMetadataForms: NonNullable = { label: "Readonly When", helpText: "CEL predicate over the record (e.g. record.status == 'paid') — the field is read-only while it is TRUE, enforced server-side: an update's change to a locked field is dropped and the stored value kept. Reads the record's own columns; objectstack validate refuses a read through a reference field." }, + uiReadonlyWhen: { + label: "Ui Readonly When", + helpText: "CEL predicate over the record (e.g. record.status != 'draft') — people cannot edit the field in the console while it is TRUE; actions, imports, the API and flows still write it, judged by the object's validations. Reads the record's own columns, as Read-only when does." + }, requiredWhen: { label: "Required When", helpText: "CEL predicate over the record — the field is required while it is TRUE, enforced server-side as a transition gate: a write that leaves the value missing is refused when the record complied before it, so a row already missing the value keeps passing unrelated edits. For a rule every write must meet, use a validations script rule. Refused beside storage.notNull." diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index bb66aea373d..a89c3ae68ab 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -893,6 +893,10 @@ export const esESMetadataForms: NonNullable = label: "Solo lectura", helpText: "El campo es de solo lectura en formularios" }, + uiReadonly: { + label: "Solo lectura en la interfaz", + helpText: "Nadie puede editar este campo a mano en la consola (diálogos, página del registro, cuadrículas, arrastre en kanban y calendario), mientras que las acciones, las importaciones, la API y los flujos siguen escribiéndolo, y las validaciones del objeto juzgan cada escritura. Déjelo desactivado cuando Solo lectura esté activado: ese ya impide toda escritura de cliente." + }, hidden: { label: "Oculto", helpText: "Oculta el campo en las vistas UI predeterminadas" @@ -917,6 +921,10 @@ export const esESMetadataForms: NonNullable = label: "Condición de solo lectura", helpText: "Predicado CEL sobre el registro (p. ej., record.status == 'paid'): el campo es de solo lectura mientras sea TRUE, y se aplica en el servidor: el cambio de una actualización sobre un campo bloqueado se descarta y se conserva el valor almacenado. Lee las columnas propias del registro; objectstack validate rechaza una lectura a través de un campo de referencia." }, + uiReadonlyWhen: { + label: "Condición de solo lectura en la interfaz", + helpText: "Predicado CEL sobre el registro (p. ej., record.status != 'draft'): mientras sea TRUE, nadie puede editar el campo en la consola; las acciones, las importaciones, la API y los flujos siguen escribiéndolo, juzgados por las validaciones del objeto. Lee las columnas propias del registro, como Condición de solo lectura." + }, requiredWhen: { label: "Condición de obligatoriedad", helpText: "Predicado CEL sobre el registro: el campo es obligatorio mientras sea TRUE, y se aplica en el servidor como compuerta de transición: se rechaza una escritura que deja el valor vacío si el registro cumplía antes de ella, así que una fila a la que ya le faltaba el valor sigue superando ediciones no relacionadas. Para una regla que toda escritura deba cumplir, use una regla script en validations. Se rechaza junto a storage.notNull." diff --git a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts index 06130d95ac2..93d2b467ae5 100644 --- a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts @@ -893,6 +893,10 @@ export const frMetadataForms: NonNullable = { label: "Lecture seule", helpText: "Le champ est en lecture seule dans les formulaires" }, + uiReadonly: { + label: "Lecture seule dans l'interface", + helpText: "Personne ne peut modifier ce champ à la main dans la console (boîtes de dialogue, page de l'enregistrement, grilles, glisser-déposer du kanban et du calendrier), tandis que les actions, les imports, l'API et les flux continuent de l'écrire, chaque écriture étant jugée par les validations de l'objet. Laissez-le désactivé lorsque Lecture seule est activé : celui-ci bloque déjà toute écriture client." + }, hidden: { label: "Masqué", helpText: "Masquer le champ dans les vues d’interface par défaut" @@ -917,6 +921,10 @@ export const frMetadataForms: NonNullable = { label: "Lecture seule si", helpText: "Prédicat CEL sur l’enregistrement (par ex. record.status == 'paid') — le champ est en lecture seule tant qu’il est TRUE, ce qui est appliqué côté serveur : la modification d’un champ verrouillé par une mise à jour est ignorée et la valeur stockée est conservée. Lit les colonnes propres de l’enregistrement ; objectstack validate refuse une lecture via un champ de référence." }, + uiReadonlyWhen: { + label: "Lecture seule dans l'interface si", + helpText: "Prédicat CEL sur l'enregistrement (par ex. record.status != 'draft') : tant qu'il vaut TRUE, personne ne peut modifier le champ dans la console ; les actions, les imports, l'API et les flux continuent de l'écrire, jugés par les validations de l'objet. Lit les colonnes propres de l'enregistrement, comme Lecture seule si." + }, requiredWhen: { label: "Obligatoire si", helpText: "Prédicat CEL sur l’enregistrement — le champ est obligatoire tant qu’il est TRUE, ce qui est appliqué côté serveur comme un contrôle de transition : une écriture qui laisse la valeur manquante est refusée lorsque l’enregistrement était conforme avant elle, de sorte qu’une ligne à laquelle la valeur manque déjà continue d’accepter les modifications sans rapport. Pour une règle que chaque écriture doit respecter, utilisez une règle de script de validations. Refusé avec storage.notNull." diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index 23261e71d45..08d8d8d57aa 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -893,6 +893,10 @@ export const jaJPMetadataForms: NonNullable = label: "読み取り専用", helpText: "フォームでフィールドを読み取り専用にする" }, + uiReadonly: { + label: "画面上で読み取り専用", + helpText: "コンソールではこのフィールドを手で編集できません(ダイアログ、レコードページ、グリッド、かんばんとカレンダーのドラッグ)。アクション、インポート、API、フローは引き続き書き込めて、各書き込みはオブジェクトの検証ルールで判定されます。「読み取り専用」がオンのときはオフのままにしてください。そちらがすでにすべてのクライアント書き込みを拒否します。" + }, hidden: { label: "非表示", helpText: "既定 UI ビューからフィールドを非表示" @@ -917,6 +921,10 @@ export const jaJPMetadataForms: NonNullable = label: "読み取り専用条件", helpText: "レコードに対する CEL 述語(例:record.status == 'paid')。TRUE の間はフィールドが読み取り専用になり、サーバー側で強制されます。ロック中のフィールドへの更新による変更は破棄され、保存済みの値が保持されます。レコード自身の列だけを読み、参照フィールドを経由した読み取りは objectstack validate が拒否します。" }, + uiReadonlyWhen: { + label: "画面上で読み取り専用の条件", + helpText: "レコードに対する CEL 述語(例: record.status != 'draft')。TRUE の間はコンソールでこのフィールドを編集できません。アクション、インポート、API、フローは引き続き書き込めて、オブジェクトの検証ルールで判定されます。「読み取り専用条件」と同じく、レコード自身の列を読みます。" + }, requiredWhen: { label: "必須条件", helpText: "レコードに対する CEL 述語。TRUE の間はフィールドが必須となり、サーバー側で状態遷移のゲートとして強制されます。書き込み前のレコードが条件を満たしていて、書き込みで値が欠けるとき、その書き込みは拒否されます。そのため、もともと値が欠けている行は無関係な編集を引き続き通過します。すべての書き込みで満たすべきルールには validations の script ルールを使ってください。storage.notNull と同時に宣言すると拒否されます。" diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index 700890fea29..d29a4bfe45a 100644 --- a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts @@ -893,6 +893,10 @@ export const koMetadataForms: NonNullable = { label: "읽기 전용", helpText: "양식에서 필드가 읽기 전용임" }, + uiReadonly: { + label: "화면에서 읽기 전용", + helpText: "콘솔에서는 이 필드를 직접 편집할 수 없습니다(대화 상자, 레코드 페이지, 그리드, 칸반 및 캘린더 끌기). 작업, 가져오기, API, 플로우는 계속 기록할 수 있으며 각 기록은 개체의 유효성 검사로 판정됩니다. 읽기 전용이 켜져 있으면 끈 상태로 두세요. 읽기 전용이 이미 모든 클라이언트 기록을 막습니다." + }, hidden: { label: "숨김", helpText: "기본 UI 뷰에서 필드 숨김" @@ -917,6 +921,10 @@ export const koMetadataForms: NonNullable = { label: "읽기 전용 조건", helpText: "레코드에 대한 CEL 조건식(예: record.status == 'paid')입니다. TRUE인 동안 필드가 읽기 전용이며 서버에서 강제됩니다. 업데이트가 잠긴 필드를 바꾸면 그 변경은 버려지고 저장된 값이 유지됩니다. 레코드 자체의 열을 읽으며, objectstack validate는 참조 필드를 통한 읽기를 거부합니다." }, + uiReadonlyWhen: { + label: "화면에서 읽기 전용 조건", + helpText: "레코드에 대한 CEL 조건식(예: record.status != 'draft') — TRUE인 동안 콘솔에서 이 필드를 편집할 수 없습니다. 작업, 가져오기, API, 플로우는 계속 기록하며 개체의 유효성 검사로 판정됩니다. 읽기 전용 조건과 마찬가지로 레코드 자체의 열을 읽습니다." + }, requiredWhen: { label: "필수 조건", helpText: "레코드에 대한 CEL 조건식입니다. TRUE인 동안 필드가 필수이며 서버에서 전이 관문으로 강제됩니다. 레코드가 이전에 조건을 충족했는데 값이 빠진 채로 쓰면 거부되므로, 이미 값이 빠진 행은 관련 없는 편집을 계속 통과합니다. 모든 쓰기가 충족해야 하는 규칙에는 validations 스크립트 규칙을 사용하세요. storage.notNull과 함께 쓰면 거부됩니다." diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index 473a97654d0..95aa18c59c9 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts @@ -893,6 +893,10 @@ export const ptBRMetadataForms: NonNullable = label: "Somente leitura", helpText: "O campo é somente leitura nos formulários" }, + uiReadonly: { + label: "Somente leitura na interface", + helpText: "Ninguém pode editar este campo manualmente no console (diálogos, página do registro, grades, arrastar no kanban e no calendário), enquanto ações, importações, a API e fluxos continuam gravando-o, cada gravação julgada pelas validações do objeto. Deixe desativado quando Somente leitura estiver ativado: ele já bloqueia toda gravação do cliente." + }, hidden: { label: "Oculto", helpText: "Ocultar o campo nas visualizações padrão da interface" @@ -917,6 +921,10 @@ export const ptBRMetadataForms: NonNullable = label: "Somente leitura quando", helpText: "Predicado CEL sobre o registro (por exemplo record.status == 'paid') — o campo fica somente leitura enquanto ele for TRUE, aplicado no servidor: a alteração de uma atualização em um campo bloqueado é descartada e o valor armazenado é mantido. Lê as próprias colunas do registro; o objectstack validate recusa uma leitura por meio de um campo de referência." }, + uiReadonlyWhen: { + label: "Somente leitura na interface quando", + helpText: "Predicado CEL sobre o registro (por ex., record.status != 'draft') — enquanto for TRUE, ninguém pode editar o campo no console; ações, importações, a API e fluxos continuam gravando-o, julgados pelas validações do objeto. Lê as colunas do próprio registro, como Somente leitura quando." + }, requiredWhen: { label: "Obrigatório quando", helpText: "Predicado CEL sobre o registro — o campo é obrigatório enquanto ele for TRUE, aplicado no servidor como um portão de transição: uma gravação que deixa o valor ausente é recusada quando o registro estava em conformidade antes dela, de modo que uma linha que já não tinha o valor continua aceitando edições não relacionadas. Para uma regra que toda gravação deve cumprir, use uma regra de script em validations. Recusado ao lado de storage.notNull." diff --git a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index 62e6b87e23e..50b3d6cabe8 100644 --- a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts @@ -893,6 +893,10 @@ export const ruMetadataForms: NonNullable = { label: "Только для чтения", helpText: "Поле в формах только для чтения" }, + uiReadonly: { + label: "Только для чтения в интерфейсе", + helpText: "Никто не может изменить это поле вручную в консоли (диалоги, страница записи, таблицы, перетаскивание в канбане и календаре), а действия, импорт, API и потоки продолжают записывать его, и каждая запись проверяется правилами проверки объекта. Оставьте выключенным, если включено «Только для чтения»: оно уже запрещает любую запись клиентом." + }, hidden: { label: "Скрытое", helpText: "Скрывать поле в представлениях интерфейса по умолчанию" @@ -917,6 +921,10 @@ export const ruMetadataForms: NonNullable = { label: "Только для чтения, когда", helpText: "Предикат CEL над записью (например, record.status == 'paid') — поле доступно только для чтения, пока он ИСТИНЕН; проверяется на сервере: изменение заблокированного поля при обновлении отбрасывается, а сохранённое значение остаётся. Читает собственные столбцы записи; objectstack validate отклоняет чтение через поле ссылки." }, + uiReadonlyWhen: { + label: "Только для чтения в интерфейсе, когда", + helpText: "Предикат CEL по записи (например, record.status != 'draft') — пока он TRUE, никто не может изменить поле в консоли; действия, импорт, API и потоки продолжают записывать его, и записи проверяются правилами проверки объекта. Читает собственные столбцы записи, как «Только для чтения, когда»." + }, requiredWhen: { label: "Обязательно, когда", helpText: "Предикат CEL над записью — поле обязательно, пока он ИСТИНЕН; проверяется на сервере как условие перехода: запись, оставляющая значение пустым, отклоняется, если до неё запись соответствовала правилу, поэтому строка, в которой значения уже нет, продолжает проходить несвязанные правки. Для правила, которому должна соответствовать каждая запись, используйте правило проверки script. Отклоняется вместе с storage.notNull." diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index dee1da3bbb2..7167e560db6 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -893,6 +893,10 @@ export const zhCNMetadataForms: NonNullable = label: "只读", helpText: "在表单中只读" }, + uiReadonly: { + label: "界面只读", + helpText: "用户无法在控制台中编辑此字段(对话框、记录页、表格、看板和日历拖动),而动作、导入、API 和流程仍可写入,每次写入都由对象的校验规则裁决。已开启“只读”时请保持关闭:只读已经阻止所有客户端写入。" + }, hidden: { label: "隐藏", helpText: "在默认界面视图中隐藏" @@ -917,6 +921,10 @@ export const zhCNMetadataForms: NonNullable = label: "只读条件", helpText: "基于记录的 CEL 谓词(例如 record.status == 'paid')——为 TRUE 时字段只读,并在服务器端强制执行:更新中对已锁定字段的修改会被丢弃,保留已存储的值。只读取记录自身的列;objectstack validate 会拒绝经由引用字段的读取。" }, + uiReadonlyWhen: { + label: "界面只读条件", + helpText: "基于记录的 CEL 谓词(例如 record.status != 'draft')——为 TRUE 时用户无法在控制台中编辑该字段;动作、导入、API 和流程仍可写入,并由对象的校验规则裁决。与“只读条件”一样读取记录自身的列。" + }, requiredWhen: { label: "必填条件", helpText: "基于记录的 CEL 谓词——为 TRUE 时字段必填,并在服务器端作为状态转换门槛执行:若写入前记录合规,而写入后缺少该值,则拒绝写入;因此原本就缺少该值的行,其无关编辑仍可通过。若需要每次写入都必须满足的规则,请使用 validations 中的 script 规则。与 storage.notNull 同时声明会被拒绝。" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index b1851fb0e28..be8b035c252 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts @@ -893,6 +893,10 @@ export const zhHantMetadataForms: NonNullable label: "唯讀", helpText: "在表單中唯讀" }, + uiReadonly: { + label: "介面唯讀", + helpText: "使用者無法在主控台中編輯此欄位(對話框、記錄頁、表格、看板與行事曆拖曳),而動作、匯入、API 與流程仍可寫入,每次寫入都由物件的驗證規則裁決。已開啟「唯讀」時請保持關閉:唯讀已經阻止所有用戶端寫入。" + }, hidden: { label: "隱藏", helpText: "在預設介面檢視中隱藏" @@ -917,6 +921,10 @@ export const zhHantMetadataForms: NonNullable label: "唯讀條件", helpText: "基於記錄的 CEL 謂詞(例如 record.status == 'paid')——為 TRUE 時欄位唯讀,並在伺服器端強制執行:更新中對已鎖定欄位的修改會被丟棄,保留已儲存的值。唯讀取記錄自身的欄;objectstack validate 會拒絕經由參照欄位的讀取。" }, + uiReadonlyWhen: { + label: "介面唯讀條件", + helpText: "針對記錄的 CEL 述詞(例如 record.status != 'draft')——為 TRUE 時使用者無法在主控台中編輯該欄位;動作、匯入、API 與流程仍可寫入,並由物件的驗證規則裁決。與「唯讀條件」一樣讀取記錄自身的欄位。" + }, requiredWhen: { label: "必填條件", helpText: "基於記錄的 CEL 謂詞——為 TRUE 時欄位必填,並在伺服器端作為狀態轉換門檻執行:若寫入前記錄合規,而寫入後缺少該值,則拒絕寫入;因此原本就缺少該值的列,其無關編輯仍可通過。若需要每次寫入都必須滿足的規則,請使用 validations 中的 script 規則。與 storage.notNull 同時宣告會被拒絕。" diff --git a/packages/spec/src/data/field.form.ts b/packages/spec/src/data/field.form.ts index 0fb83eb6764..42ee9d473a0 100644 --- a/packages/spec/src/data/field.form.ts +++ b/packages/spec/src/data/field.form.ts @@ -465,6 +465,9 @@ export const fieldForm = defineForm({ }, // UI & Visibility { field: 'readonly', colSpan: 1, helpText: 'Field is read-only in forms' }, + // #36806 — the hand lock: read by every console surface a person edits + // through, never by the engine. The parse refuses it beside `readonly`. + { field: 'uiReadonly', colSpan: 1, helpText: 'People cannot edit this field in the console (dialogs, the record page, grids, kanban and calendar drag), while actions, imports, the API and flows still write it, each write judged by the object\'s validations. Leave it off when Read-only is on: that one already keeps every client write out.' }, { field: 'hidden', colSpan: 1, helpText: 'Hide field from default UI views' }, // #36425 — whether a create asks for the field; read by every create // surface of the Console (the create dialog, the full-page create, an @@ -478,6 +481,9 @@ export const fieldForm = defineForm({ // that row: `type: 'code'`, `language: 'expression'`. { field: 'visibleWhen', type: 'code', language: 'expression', colSpan: 2, helpText: "CEL predicate over the record (e.g. record.type == 'invoice') — the form shows this field only while it is TRUE." }, { field: 'readonlyWhen', type: 'code', language: 'expression', colSpan: 2, helpText: "CEL predicate over the record (e.g. record.status == 'paid') — the field is read-only while it is TRUE, enforced server-side: an update's change to a locked field is dropped and the stored value kept. Reads the record's own columns; objectstack validate refuses a read through a reference field." }, + // #36806 — the hand lock's predicate: the console locks the field while it + // is TRUE; writes from actions, imports, the API and flows keep it. + { field: 'uiReadonlyWhen', type: 'code', language: 'expression', colSpan: 2, helpText: "CEL predicate over the record (e.g. record.status != 'draft') — people cannot edit the field in the console while it is TRUE; actions, imports, the API and flows still write it, judged by the object's validations. Reads the record's own columns, as Read-only when does." }, { field: 'requiredWhen', type: 'code', language: 'expression', colSpan: 2, helpText: "CEL predicate over the record — the field is required while it is TRUE, enforced server-side as a transition gate: a write that leaves the value missing is refused when the record complied before it, so a row already missing the value keeps passing unrelated edits. For a rule every write must meet, use a validations script rule. Refused beside storage.notNull." }, // Partial masking (#8993): a preset name or a {keepHead, keepTail} JSON // object; the runtime FieldMasker enforces it on read AND export. From 62c400a2324b48eb957673f7012930788a4d6581 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 04:31:40 +0000 Subject: [PATCH 08/13] =?UTF-8?q?test(platform-objects):=20the=20metadata-?= =?UTF-8?q?form=20translated-leaf=20count=20moves=20837=20=E2=86=92=20839?= =?UTF-8?q?=20for=20the=20two=20hand-lock=20rows?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXSuJCALDHFWaV6Bv5 --- .../object-lifecycle-panel-echo-decisions.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts index f70ef6712b1..d3b0c573d6d 100644 --- a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts @@ -1331,7 +1331,9 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // children — three row labels, authored in all three locales. // 837 since #37143: the `ai_context` form (ADR-0160 D1 clause 2) — two // section labels and seven row labels, authored in all three locales. - expect(translated.length, `${locale} positive control`).toBe(837); + // 839 since #36806: the field form offers the `uiReadonly` and + // `uiReadonlyWhen` rows (the hand lock), authored in every locale. + expect(translated.length, `${locale} positive control`).toBe(839); } // ⭐ DARK — the blindness, executable. On a synthetic two-locale catalog the // all-three predicate returns 0 while the per-locale one returns 1, so the From 309363d498b2556405f662581f775067508c7fdc Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:36:20 +0000 Subject: [PATCH 09/13] fix(spec,ui,lint): hand lock review rework (operands, scope, fail-closed fault, lint slot, narrowed describes) Per the L1 rework and contract review on #36806: S1 host scope on every surface and lock-predicate operands fetched by the grid row load and ListView (grid columns, kanban lane, calendar dates); S2 a faulted uiReadonlyWhen locks the field, the edit form refuses to submit, os validate checks the slot; S3(a) authored line-item columns carry the child field's hand lock; S4 uiReadonlyWhen judges existing records only; describes name the honouring surfaces; N1/N2. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXSuJCALDHFWaV6Bv5 --- .../36806-field-ui-readonly-hand-lock.md | 9 +- content/docs/references/data/field.mdx | 4 +- content/docs/references/data/object.mdx | 8 +- content/docs/references/system/migration.mdx | 8 +- .../lint/src/validate-expressions.test.ts | 43 ++++- packages/lint/src/validate-expressions.ts | 19 ++- packages/mcp/src/mcp-http-tools.ts | 7 +- .../ar.metadata-forms.generated.ts | 2 +- .../de.metadata-forms.generated.ts | 2 +- .../en.metadata-forms.generated.ts | 2 +- .../es-ES.metadata-forms.generated.ts | 2 +- .../fr.metadata-forms.generated.ts | 2 +- .../ja-JP.metadata-forms.generated.ts | 2 +- .../ko.metadata-forms.generated.ts | 2 +- .../pt-BR.metadata-forms.generated.ts | 2 +- .../ru.metadata-forms.generated.ts | 2 +- .../zh-CN.metadata-forms.generated.ts | 2 +- .../zh-Hant.metadata-forms.generated.ts | 2 +- packages/spec/liveness/field.json | 6 +- packages/spec/src/data/field.form.ts | 2 +- packages/spec/src/data/field.zod.ts | 37 +++-- ...lyWhen-fault-refuses-submit-36806.test.tsx | 115 ++++++++++++++ .../components/src/renderers/form/form.tsx | 42 ++++- .../__tests__/handLock-36806.test.ts | 31 +++- ui/packages/core/src/evaluator/fieldRules.ts | 19 ++- ui/packages/core/src/evaluator/handLock.ts | 10 +- .../widgets/GridField.handLock-36806.test.tsx | 20 +++ .../widgets/grid-field/GridFieldWidget.tsx | 5 + ui/packages/i18n/src/locales/ar.ts | 1 + ui/packages/i18n/src/locales/de.ts | 1 + ui/packages/i18n/src/locales/en.ts | 1 + ui/packages/i18n/src/locales/es.ts | 1 + ui/packages/i18n/src/locales/fr.ts | 1 + ui/packages/i18n/src/locales/ja.ts | 1 + ui/packages/i18n/src/locales/ko.ts | 1 + ui/packages/i18n/src/locales/pt-BR.ts | 1 + ui/packages/i18n/src/locales/ru.ts | 1 + ui/packages/i18n/src/locales/zh-Hans.ts | 1 + ui/packages/i18n/src/locales/zh-Hant.ts | 1 + .../plugin-calendar/src/ObjectCalendar.tsx | 9 +- .../plugin-detail/src/DetailSection.tsx | 2 +- .../plugin-detail/src/HeaderHighlight.tsx | 2 +- .../plugin-detail/src/InlineEditSaveBar.tsx | 7 +- .../src/renderers/recordPathStageChange.tsx | 8 +- .../src/deriveMasterDetail.test.ts | 23 +++ .../plugin-form/src/deriveMasterDetail.ts | 26 ++- ui/packages/plugin-grid/src/ObjectGrid.tsx | 6 +- .../lockOperandProjection-36806.test.tsx | 140 ++++++++++++++++ ...objectGridCellFacts.handLock-36806.test.ts | 15 ++ .../plugin-grid/src/objectGridCellFacts.ts | 4 +- .../plugin-grid/src/objectGridRowLoad.ts | 20 ++- .../plugin-kanban/src/ObjectKanban.tsx | 4 +- ui/packages/plugin-list/src/ListView.tsx | 24 +++ .../ListView.lockOperandSelect-36806.test.tsx | 149 ++++++++++++++++++ 54 files changed, 788 insertions(+), 69 deletions(-) create mode 100644 ui/packages/components/src/renderers/form/__tests__/uiReadonlyWhen-fault-refuses-submit-36806.test.tsx create mode 100644 ui/packages/plugin-grid/src/__tests__/lockOperandProjection-36806.test.tsx create mode 100644 ui/packages/plugin-list/src/__tests__/ListView.lockOperandSelect-36806.test.tsx diff --git a/.changeset/36806-field-ui-readonly-hand-lock.md b/.changeset/36806-field-ui-readonly-hand-lock.md index 4f07b638f7d..b7d0a330bfb 100644 --- a/.changeset/36806-field-ui-readonly-hand-lock.md +++ b/.changeset/36806-field-ui-readonly-hand-lock.md @@ -2,6 +2,9 @@ '@objectstack/spec': minor '@objectstack/runtime': patch '@objectstack/mcp': patch +'@objectstack/lint': patch +'@objectstack/metadata-core': patch +'@objectstack/platform-objects': patch '@object-ui/core': minor '@object-ui/types': patch '@object-ui/components': patch @@ -11,6 +14,8 @@ '@object-ui/plugin-grid': patch '@object-ui/plugin-kanban': patch '@object-ui/plugin-calendar': patch +'@object-ui/plugin-list': patch +'@object-ui/i18n': patch '@object-ui/app-shell': patch --- @@ -27,8 +32,10 @@ A status column that only moves through actions, or a field an integration fills | always | `readonly` | `uiReadonly` | | conditional | `readonlyWhen` | `uiReadonlyWhen` (CEL, the same scope as `readonlyWhen`) | -- **`uiReadonly: true` / `uiReadonlyWhen`.** Every console surface a person edits through locks the field: the create and edit dialogs (the field is left off them and out of the payload they submit, so a create from the console lands on the field's `defaultValue`), the record page's inline edit and stage path, the highlight-strip chip, grid inline edit and its multi-row save, kanban drag between columns grouped by the field, calendar drag, and the line-item grid (a `uiReadonly` child field is not a column; a `uiReadonlyWhen` one locks its cell per row). The engine never reads either key, so REST, import, declarative and script actions, and flows write the field, and the object's validations (a `state_machine`, for one) judge each write. +- **`uiReadonly: true` / `uiReadonlyWhen`.** These console surfaces lock the field: the create and edit dialogs (the field is left off them and out of the payload they submit, so a create from the console lands on the field's `defaultValue`, and a `required` field therefore needs one), the record page's inline edit and stage path, the highlight-strip chip, grid inline edit and its multi-row save, kanban drag between columns grouped by the field, calendar drag, and the line-item grid (a `uiReadonly` child field is not a derived column, and an authored column over it is locked; a `uiReadonlyWhen` one locks its cell per row). The Gantt, the timesheet cell, the kanban swimlane drag and the in-app assistant do not read the keys yet. The engine never reads either key, so REST, import, declarative and script actions, and flows write the field, and the object's validations (a `state_machine`, for one) judge each write. +- **`uiReadonlyWhen` is judged on an existing record only** (the create dialog does not read it), over the host's predicate scope on every surface. Grids and list views fetch the operands of a shown or dragged field's lock predicates. A predicate that cannot be evaluated LOCKS the field (no server judges the hand lock), the edit dialog refuses to submit until it is fixed, and `os validate` checks it as it checks `readonlyWhen`. - **Refused: `uiReadonly: true` beside `readonly: true`** (at `['uiReadonly']`, at every door that parses a field: `defineStack`, `os validate`, metadata save). Keep one: `readonly` when no client may write the field, `uiReadonly` when people at the console may not. `uiReadonlyWhen` beside `readonlyWhen` is accepted. - **Kanban: a `readonly` lane field no longer drags.** The board read no field lock before, so a card grouped by a `readonly` field could be dragged and its PATCH was silently stripped. The board now reads both locks. - **`@object-ui/core` exports the one verdict:** `fieldReadOnlyByHand(def, record?, context?)`, `fieldStaticallyReadOnlyByHand(def)`, `fieldHasConditionalHandLock(def)`. `resolveFieldRuleState` takes `uiReadonlyWhen` in its rules and `uiReadonly` in its statics. The import wizard's target mapping and the Studio/designer reads stay on the raw `readonly`. - **MCP `describe_object`** reports `uiReadonly` and `uiReadonlyWhen` as their own keys where set (never folded into `readonly`, which tells an agent to leave the field out of a write), on the HTTP and the stdio transport, and the tool description names them. +- **Censuses and Studio.** The FLS reference scrub classifies both keys (`@objectstack/metadata-core`: `uiReadonly` kept, `uiReadonlyWhen` an expression position). The Studio field form offers both rows beside Read-only and Read-only when, with their labels and help translated in every metadata-forms locale pack (`@objectstack/platform-objects`). diff --git a/content/docs/references/data/field.mdx b/content/docs/references/data/field.mdx index b3ccf992881..582a54842c8 100644 --- a/content/docs/references/data/field.mdx +++ b/content/docs/references/data/field.mdx @@ -111,7 +111,7 @@ const result = CurrencyConfigSchema.parse(data); | **group** | `string` | optional | Older spelling of field-group membership, still read: the key of one of the object's fieldGroups (e.g. "contact_info"); the field joins that group in field declaration order. New metadata lists members on the group instead (fieldGroups[].fields), which also sets their order. A field a group lists may not name a different group here; a field naming a group whose fields list leaves it out follows the listed ones. | | **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. | -| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND when TRUE: no console surface lets a person edit it (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit, kanban and calendar drag), while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | +| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND on an existing record while TRUE: the console surfaces that honour `uiReadonly` (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the line-item grid) do not let a person edit it, while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. A create is not judged: the create dialog offers the field whatever the predicate says. A predicate the console cannot evaluate locks the field, and the edit dialog refuses to submit until it is fixed. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | | **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. | | **settledWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the deadline is SETTLED while TRUE: no overdue wording or colour applies to this record, e.g. P`record.status == 'done'`. Evaluated per record like `visibleWhen`, reading the record's own columns as `record`. Requires `dueLike: true` on a `date` / `datetime` field; refused otherwise. Display only: nothing on the write path reads it. | @@ -121,7 +121,7 @@ const result = CurrencyConfigSchema.parse(data); | **showOnCreate** | `boolean` | optional | Ask for this field when a record is created. Absent or `true`: the field is on every create surface (the create dialog, the full-page create, an action-opened create). `false`: no create surface shows it; editing, the record page and lists still do, so a value is filled in after the record exists. Refused on a `required: true` field, with or without a `defaultValue`: a required field is always asked for on create. Keep the field on create, or drop `required`. A `requiredWhen` field is accepted, and its create is still refused when the predicate holds and the value is empty. | | **internal** | `boolean` | optional | Never return this field's value on the generic data path — the engine OMITS the key from `find`/`findOne` results, the 201 create body and the by-id update body, on the default projection AND when a client names the field in `?select=`. Storage, filtering and indexing are untouched, so a server-side verifier can still match on the column and a purpose-built mint route can still return the value once at creation. The read protection for ADR-0100's third credential channel (auth-subsystem one-way hashes on `text` columns). Omission, not masking: a mask signals 'a value is set', which carries no information on a `required` column. | | **readonly** | `boolean` | optional (default: `false`) | Read-only — never editable in forms, AND server-enforced on BOTH write paths: a non-system write to this field is silently dropped from the payload on UPDATE and on INSERT (a create can no longer directly seed e.g. `approval_status: "approved"`), symmetric with `readonlyWhen`. A stripped INSERT field still falls back to its `defaultValue`. Exempt from the strip on BOTH paths: `isSystem` writes (seed replay, migration). Exempt on the UPDATE path ONLY: an opt-in "historical" import (`preserveAudit`) — which admits a whitelist (the audit/timestamp family plus author-declared business `readonly` fields). On INSERT the exemption does NOT apply: a non-system create that requests `preserveAudit` still has its readonly fields stripped, and is warned loudly that the exemption is UPDATE-only — replaying archival readonly facts on create requires a system context. A normal (non-system) import is NOT system-context and still strips. | -| **uiReadonly** | `boolean` | optional | Read-only BY HAND: no console surface lets a person edit the field (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit and multi-row save, kanban and calendar drag), while every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`; an API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | +| **uiReadonly** | `boolean` | optional | Read-only BY HAND: the console's editing surfaces do not let a person edit the field — the create and edit dialogs (it is left off them and out of their payload), record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag and the line-item grid; other console surfaces do not read it yet. Every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`, so a `required` field needs a `defaultValue`: without one every create from the console fails. An API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | | **requiredPermissions** | `string[]` | optional | [ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate). | | **maskingRule** | `Enum<'phone' \| 'id_card' \| 'bank_account' \| 'email' \| 'name'> \| { keepHead: integer; keepTail: integer }` | optional | Partial masking rule enforced by the runtime FieldMasker (single channel — API, UI, export and AI context all see the same masked value). A named preset ('phone' 138****5678, 'id_card' keep 6+4, 'bank_account' keep last 4, 'email' j***@example.com, 'name' keep first char) or `{ keepHead, keepTail }`. Masked for every non-system caller unless the field's `requiredPermissions` are ALL held (that evaluation is the unmask gate); a permission set marking the field non-readable still deletes it entirely. Deterministic, length-preserving output; masked callers cannot filter/sort/group/aggregate on the field. | | **ackPlaintextMasking** | `boolean` | optional | [ADR-0100] Affirm a generic `password` field's plaintext-at-rest / masked-on-read contract is intended, silencing the author-time warning. No effect on non-password fields. | diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index e38b9e406fd..264e9188671 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -299,7 +299,7 @@ const result = ApiMethod.parse(data); | **group** | `string` | optional | Older spelling of field-group membership, still read: the key of one of the object's fieldGroups (e.g. "contact_info"); the field joins that group in field declaration order. New metadata lists members on the group instead (fieldGroups[].fields), which also sets their order. A field a group lists may not name a different group here; a field naming a group whose fields list leaves it out follows the listed ones. | | **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. | -| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND when TRUE: no console surface lets a person edit it (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit, kanban and calendar drag), while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | +| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND on an existing record while TRUE: the console surfaces that honour `uiReadonly` (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the line-item grid) do not let a person edit it, while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. A create is not judged: the create dialog offers the field whatever the predicate says. A predicate the console cannot evaluate locks the field, and the edit dialog refuses to submit until it is fixed. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | | **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. | | **settledWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the deadline is SETTLED while TRUE: no overdue wording or colour applies to this record, e.g. P`record.status == 'done'`. Evaluated per record like `visibleWhen`, reading the record's own columns as `record`. Requires `dueLike: true` on a `date` / `datetime` field; refused otherwise. Display only: nothing on the write path reads it. | @@ -309,7 +309,7 @@ const result = ApiMethod.parse(data); | **showOnCreate** | `boolean` | optional | Ask for this field when a record is created. Absent or `true`: the field is on every create surface (the create dialog, the full-page create, an action-opened create). `false`: no create surface shows it; editing, the record page and lists still do, so a value is filled in after the record exists. Refused on a `required: true` field, with or without a `defaultValue`: a required field is always asked for on create. Keep the field on create, or drop `required`. A `requiredWhen` field is accepted, and its create is still refused when the predicate holds and the value is empty. | | **internal** | `boolean` | optional | Never return this field's value on the generic data path — the engine OMITS the key from `find`/`findOne` results, the 201 create body and the by-id update body, on the default projection AND when a client names the field in `?select=`. Storage, filtering and indexing are untouched, so a server-side verifier can still match on the column and a purpose-built mint route can still return the value once at creation. The read protection for ADR-0100's third credential channel (auth-subsystem one-way hashes on `text` columns). Omission, not masking: a mask signals 'a value is set', which carries no information on a `required` column. | | **readonly** | `boolean` | optional (default: `false`) | Read-only — never editable in forms, AND server-enforced on BOTH write paths: a non-system write to this field is silently dropped from the payload on UPDATE and on INSERT (a create can no longer directly seed e.g. `approval_status: "approved"`), symmetric with `readonlyWhen`. A stripped INSERT field still falls back to its `defaultValue`. Exempt from the strip on BOTH paths: `isSystem` writes (seed replay, migration). Exempt on the UPDATE path ONLY: an opt-in "historical" import (`preserveAudit`) — which admits a whitelist (the audit/timestamp family plus author-declared business `readonly` fields). On INSERT the exemption does NOT apply: a non-system create that requests `preserveAudit` still has its readonly fields stripped, and is warned loudly that the exemption is UPDATE-only — replaying archival readonly facts on create requires a system context. A normal (non-system) import is NOT system-context and still strips. | -| **uiReadonly** | `boolean` | optional | Read-only BY HAND: no console surface lets a person edit the field (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit and multi-row save, kanban and calendar drag), while every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`; an API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | +| **uiReadonly** | `boolean` | optional | Read-only BY HAND: the console's editing surfaces do not let a person edit the field — the create and edit dialogs (it is left off them and out of their payload), record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag and the line-item grid; other console surfaces do not read it yet. Every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`, so a `required` field needs a `defaultValue`: without one every create from the console fails. An API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | | **requiredPermissions** | `string[]` | optional | [ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate). | | **maskingRule** | `Enum<'phone' \| 'id_card' \| 'bank_account' \| 'email' \| 'name'> \| { keepHead: integer; keepTail: integer }` | optional | Partial masking rule enforced by the runtime FieldMasker (single channel — API, UI, export and AI context all see the same masked value). A named preset ('phone' 138****5678, 'id_card' keep 6+4, 'bank_account' keep last 4, 'email' j***@example.com, 'name' keep first char) or `{ keepHead, keepTail }`. Masked for every non-system caller unless the field's `requiredPermissions` are ALL held (that evaluation is the unmask gate); a permission set marking the field non-readable still deletes it entirely. Deterministic, length-preserving output; masked callers cannot filter/sort/group/aggregate on the field. | | **ackPlaintextMasking** | `boolean` | optional | [ADR-0100] Affirm a generic `password` field's plaintext-at-rest / masked-on-read contract is intended, silencing the author-time warning. No effect on non-password fields. | @@ -700,7 +700,7 @@ const result = ApiMethod.parse(data); | **group** | `string` | optional | Older spelling of field-group membership, still read: the key of one of the object's fieldGroups (e.g. "contact_info"); the field joins that group in field declaration order. New metadata lists members on the group instead (fieldGroups[].fields), which also sets their order. A field a group lists may not name a different group here; a field naming a group whose fields list leaves it out follows the listed ones. | | **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. | -| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND when TRUE: no console surface lets a person edit it (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit, kanban and calendar drag), while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | +| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND on an existing record while TRUE: the console surfaces that honour `uiReadonly` (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the line-item grid) do not let a person edit it, while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. A create is not judged: the create dialog offers the field whatever the predicate says. A predicate the console cannot evaluate locks the field, and the edit dialog refuses to submit until it is fixed. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | | **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. | | **settledWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the deadline is SETTLED while TRUE: no overdue wording or colour applies to this record, e.g. P`record.status == 'done'`. Evaluated per record like `visibleWhen`, reading the record's own columns as `record`. Requires `dueLike: true` on a `date` / `datetime` field; refused otherwise. Display only: nothing on the write path reads it. | @@ -710,7 +710,7 @@ const result = ApiMethod.parse(data); | **showOnCreate** | `boolean` | optional | Ask for this field when a record is created. Absent or `true`: the field is on every create surface (the create dialog, the full-page create, an action-opened create). `false`: no create surface shows it; editing, the record page and lists still do, so a value is filled in after the record exists. Refused on a `required: true` field, with or without a `defaultValue`: a required field is always asked for on create. Keep the field on create, or drop `required`. A `requiredWhen` field is accepted, and its create is still refused when the predicate holds and the value is empty. | | **internal** | `boolean` | optional | Never return this field's value on the generic data path — the engine OMITS the key from `find`/`findOne` results, the 201 create body and the by-id update body, on the default projection AND when a client names the field in `?select=`. Storage, filtering and indexing are untouched, so a server-side verifier can still match on the column and a purpose-built mint route can still return the value once at creation. The read protection for ADR-0100's third credential channel (auth-subsystem one-way hashes on `text` columns). Omission, not masking: a mask signals 'a value is set', which carries no information on a `required` column. | | **readonly** | `boolean` | optional (default: `false`) | Read-only — never editable in forms, AND server-enforced on BOTH write paths: a non-system write to this field is silently dropped from the payload on UPDATE and on INSERT (a create can no longer directly seed e.g. `approval_status: "approved"`), symmetric with `readonlyWhen`. A stripped INSERT field still falls back to its `defaultValue`. Exempt from the strip on BOTH paths: `isSystem` writes (seed replay, migration). Exempt on the UPDATE path ONLY: an opt-in "historical" import (`preserveAudit`) — which admits a whitelist (the audit/timestamp family plus author-declared business `readonly` fields). On INSERT the exemption does NOT apply: a non-system create that requests `preserveAudit` still has its readonly fields stripped, and is warned loudly that the exemption is UPDATE-only — replaying archival readonly facts on create requires a system context. A normal (non-system) import is NOT system-context and still strips. | -| **uiReadonly** | `boolean` | optional | Read-only BY HAND: no console surface lets a person edit the field (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit and multi-row save, kanban and calendar drag), while every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`; an API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | +| **uiReadonly** | `boolean` | optional | Read-only BY HAND: the console's editing surfaces do not let a person edit the field — the create and edit dialogs (it is left off them and out of their payload), record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag and the line-item grid; other console surfaces do not read it yet. Every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`, so a `required` field needs a `defaultValue`: without one every create from the console fails. An API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | | **requiredPermissions** | `string[]` | optional | [ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate). | | **maskingRule** | `Enum<'phone' \| 'id_card' \| 'bank_account' \| 'email' \| 'name'> \| { keepHead: integer; keepTail: integer }` | optional | Partial masking rule enforced by the runtime FieldMasker (single channel — API, UI, export and AI context all see the same masked value). A named preset ('phone' 138****5678, 'id_card' keep 6+4, 'bank_account' keep last 4, 'email' j***@example.com, 'name' keep first char) or `{ keepHead, keepTail }`. Masked for every non-system caller unless the field's `requiredPermissions` are ALL held (that evaluation is the unmask gate); a permission set marking the field non-readable still deletes it entirely. Deterministic, length-preserving output; masked callers cannot filter/sort/group/aggregate on the field. | | **ackPlaintextMasking** | `boolean` | optional | [ADR-0100] Affirm a generic `password` field's plaintext-at-rest / masked-on-read contract is intended, silencing the author-time warning. No effect on non-password fields. | diff --git a/content/docs/references/system/migration.mdx b/content/docs/references/system/migration.mdx index 78a3e7afec5..1d37db00796 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -114,7 +114,7 @@ Add a new field to an existing object | **group** | `string` | optional | Older spelling of field-group membership, still read: the key of one of the object's fieldGroups (e.g. "contact_info"); the field joins that group in field declaration order. New metadata lists members on the group instead (fieldGroups[].fields), which also sets their order. A field a group lists may not name a different group here; a field naming a group whose fields list leaves it out follows the listed ones. | | **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. | -| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND when TRUE: no console surface lets a person edit it (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit, kanban and calendar drag), while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | +| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND on an existing record while TRUE: the console surfaces that honour `uiReadonly` (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the line-item grid) do not let a person edit it, while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. A create is not judged: the create dialog offers the field whatever the predicate says. A predicate the console cannot evaluate locks the field, and the edit dialog refuses to submit until it is fixed. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | | **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. | | **settledWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the deadline is SETTLED while TRUE: no overdue wording or colour applies to this record, e.g. P`record.status == 'done'`. Evaluated per record like `visibleWhen`, reading the record's own columns as `record`. Requires `dueLike: true` on a `date` / `datetime` field; refused otherwise. Display only: nothing on the write path reads it. | @@ -124,7 +124,7 @@ Add a new field to an existing object | **showOnCreate** | `boolean` | optional | Ask for this field when a record is created. Absent or `true`: the field is on every create surface (the create dialog, the full-page create, an action-opened create). `false`: no create surface shows it; editing, the record page and lists still do, so a value is filled in after the record exists. Refused on a `required: true` field, with or without a `defaultValue`: a required field is always asked for on create. Keep the field on create, or drop `required`. A `requiredWhen` field is accepted, and its create is still refused when the predicate holds and the value is empty. | | **internal** | `boolean` | optional | Never return this field's value on the generic data path — the engine OMITS the key from `find`/`findOne` results, the 201 create body and the by-id update body, on the default projection AND when a client names the field in `?select=`. Storage, filtering and indexing are untouched, so a server-side verifier can still match on the column and a purpose-built mint route can still return the value once at creation. The read protection for ADR-0100's third credential channel (auth-subsystem one-way hashes on `text` columns). Omission, not masking: a mask signals 'a value is set', which carries no information on a `required` column. | | **readonly** | `boolean` | optional (default: `false`) | Read-only — never editable in forms, AND server-enforced on BOTH write paths: a non-system write to this field is silently dropped from the payload on UPDATE and on INSERT (a create can no longer directly seed e.g. `approval_status: "approved"`), symmetric with `readonlyWhen`. A stripped INSERT field still falls back to its `defaultValue`. Exempt from the strip on BOTH paths: `isSystem` writes (seed replay, migration). Exempt on the UPDATE path ONLY: an opt-in "historical" import (`preserveAudit`) — which admits a whitelist (the audit/timestamp family plus author-declared business `readonly` fields). On INSERT the exemption does NOT apply: a non-system create that requests `preserveAudit` still has its readonly fields stripped, and is warned loudly that the exemption is UPDATE-only — replaying archival readonly facts on create requires a system context. A normal (non-system) import is NOT system-context and still strips. | -| **uiReadonly** | `boolean` | optional | Read-only BY HAND: no console surface lets a person edit the field (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit and multi-row save, kanban and calendar drag), while every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`; an API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | +| **uiReadonly** | `boolean` | optional | Read-only BY HAND: the console's editing surfaces do not let a person edit the field — the create and edit dialogs (it is left off them and out of their payload), record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag and the line-item grid; other console surfaces do not read it yet. Every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`, so a `required` field needs a `defaultValue`: without one every create from the console fails. An API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | | **requiredPermissions** | `string[]` | optional | [ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate). | | **maskingRule** | `Enum<'phone' \| 'id_card' \| 'bank_account' \| 'email' \| 'name'> \| { keepHead: integer; keepTail: integer }` | optional | Partial masking rule enforced by the runtime FieldMasker (single channel — API, UI, export and AI context all see the same masked value). A named preset ('phone' 138****5678, 'id_card' keep 6+4, 'bank_account' keep last 4, 'email' j***@example.com, 'name' keep first char) or `{ keepHead, keepTail }`. Masked for every non-system caller unless the field's `requiredPermissions` are ALL held (that evaluation is the unmask gate); a permission set marking the field non-readable still deletes it entirely. Deterministic, length-preserving output; masked callers cannot filter/sort/group/aggregate on the field. | | **ackPlaintextMasking** | `boolean` | optional | [ADR-0100] Affirm a generic `password` field's plaintext-at-rest / masked-on-read contract is intended, silencing the author-time warning. No effect on non-password fields. | @@ -558,7 +558,7 @@ Add a new field to an existing object | **group** | `string` | optional | Older spelling of field-group membership, still read: the key of one of the object's fieldGroups (e.g. "contact_info"); the field joins that group in field declaration order. New metadata lists members on the group instead (fieldGroups[].fields), which also sets their order. A field a group lists may not name a different group here; a field naming a group whose fields list leaves it out follows the listed ones. | | **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. | -| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND when TRUE: no console surface lets a person edit it (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit, kanban and calendar drag), while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | +| **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the field is read-only BY HAND on an existing record while TRUE: the console surfaces that honour `uiReadonly` (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the line-item grid) do not let a person edit it, while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. A create is not judged: the create dialog offers the field whatever the predicate says. A predicate the console cannot evaluate locks the field, and the edit dialog refuses to submit until it is fixed. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key. | | **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. | | **settledWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the deadline is SETTLED while TRUE: no overdue wording or colour applies to this record, e.g. P`record.status == 'done'`. Evaluated per record like `visibleWhen`, reading the record's own columns as `record`. Requires `dueLike: true` on a `date` / `datetime` field; refused otherwise. Display only: nothing on the write path reads it. | @@ -568,7 +568,7 @@ Add a new field to an existing object | **showOnCreate** | `boolean` | optional | Ask for this field when a record is created. Absent or `true`: the field is on every create surface (the create dialog, the full-page create, an action-opened create). `false`: no create surface shows it; editing, the record page and lists still do, so a value is filled in after the record exists. Refused on a `required: true` field, with or without a `defaultValue`: a required field is always asked for on create. Keep the field on create, or drop `required`. A `requiredWhen` field is accepted, and its create is still refused when the predicate holds and the value is empty. | | **internal** | `boolean` | optional | Never return this field's value on the generic data path — the engine OMITS the key from `find`/`findOne` results, the 201 create body and the by-id update body, on the default projection AND when a client names the field in `?select=`. Storage, filtering and indexing are untouched, so a server-side verifier can still match on the column and a purpose-built mint route can still return the value once at creation. The read protection for ADR-0100's third credential channel (auth-subsystem one-way hashes on `text` columns). Omission, not masking: a mask signals 'a value is set', which carries no information on a `required` column. | | **readonly** | `boolean` | optional (default: `false`) | Read-only — never editable in forms, AND server-enforced on BOTH write paths: a non-system write to this field is silently dropped from the payload on UPDATE and on INSERT (a create can no longer directly seed e.g. `approval_status: "approved"`), symmetric with `readonlyWhen`. A stripped INSERT field still falls back to its `defaultValue`. Exempt from the strip on BOTH paths: `isSystem` writes (seed replay, migration). Exempt on the UPDATE path ONLY: an opt-in "historical" import (`preserveAudit`) — which admits a whitelist (the audit/timestamp family plus author-declared business `readonly` fields). On INSERT the exemption does NOT apply: a non-system create that requests `preserveAudit` still has its readonly fields stripped, and is warned loudly that the exemption is UPDATE-only — replaying archival readonly facts on create requires a system context. A normal (non-system) import is NOT system-context and still strips. | -| **uiReadonly** | `boolean` | optional | Read-only BY HAND: no console surface lets a person edit the field (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit and multi-row save, kanban and calendar drag), while every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`; an API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | +| **uiReadonly** | `boolean` | optional | Read-only BY HAND: the console's editing surfaces do not let a person edit the field — the create and edit dialogs (it is left off them and out of their payload), record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag and the line-item grid; other console surfaces do not read it yet. Every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`, so a `required` field needs a `defaultValue`: without one every create from the console fails. An API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`. | | **requiredPermissions** | `string[]` | optional | [ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate). | | **maskingRule** | `Enum<'phone' \| 'id_card' \| 'bank_account' \| 'email' \| 'name'> \| { keepHead: integer; keepTail: integer }` | optional | Partial masking rule enforced by the runtime FieldMasker (single channel — API, UI, export and AI context all see the same masked value). A named preset ('phone' 138****5678, 'id_card' keep 6+4, 'bank_account' keep last 4, 'email' j***@example.com, 'name' keep first char) or `{ keepHead, keepTail }`. Masked for every non-system caller unless the field's `requiredPermissions` are ALL held (that evaluation is the unmask gate); a permission set marking the field non-readable still deletes it entirely. Deterministic, length-preserving output; masked callers cannot filter/sort/group/aggregate on the field. | | **ackPlaintextMasking** | `boolean` | optional | [ADR-0100] Affirm a generic `password` field's plaintext-at-rest / masked-on-read contract is intended, silencing the author-time warning. No effect on non-password fields. | diff --git a/packages/lint/src/validate-expressions.test.ts b/packages/lint/src/validate-expressions.test.ts index 3cf89da5cb2..2c2d33739ea 100644 --- a/packages/lint/src/validate-expressions.test.ts +++ b/packages/lint/src/validate-expressions.test.ts @@ -1802,6 +1802,46 @@ describe('validateStackExpressions (ADR-0032 build-time)', () => { expect(issues.some(i => i.where.includes('requiredWhen') && /bare reference `status`/.test(i.message))).toBe(true); }); + // [#36806] The console hand lock has no server judge (ADR-0137 D2): the + // console locks the field on a fault, so this pass is the only place an + // author hears about one. Judged as `readonlyWhen` is at the field site. + describe('`uiReadonlyWhen` is checked as `readonlyWhen` is (#36806)', () => { + const lint = (uiReadonlyWhen: string) => + validateStackExpressions({ + objects: [{ + name: 'hlk_order', + fields: { + status: { type: 'select', options: [{ value: 'draft', label: 'Draft' }], uiReadonlyWhen }, + }, + }], + }).filter(i => i.where === "object 'hlk_order' · field 'status' uiReadonlyWhen"); + + it('accepts a predicate over the record\'s own columns', () => { + expect(lint("record.status != 'draft'")).toEqual([]); + }); + + it('refuses a bare field reference', () => { + const found = lint("status != 'draft'"); + expect(found.map(i => i.severity)).toContain('error'); + expect(found.some(i => /bare reference `status`/.test(i.message))).toBe(true); + }); + + it('refuses a predicate that does not parse', () => { + expect(lint('record.(').some(i => i.severity === 'error')).toBe(true); + }); + + it('refuses a field the object does not declare', () => { + expect(lint("record.stage == 'won'").some(i => i.severity === 'error' && /stage/.test(i.message))).toBe(true); + }); + + it('refuses a root the field level does not bind, naming the console\'s locked outcome', () => { + const found = lint("current_user.id == 'u1'"); + expect(found.map(i => i.severity)).toEqual(['error']); + expect(found[0]!.message).toMatch(/`uiReadonlyWhen` reads `current_user`/); + expect(found[0]!.message).toMatch(/resolves a hand lock it cannot evaluate to LOCKED/); + }); + }); + // `qty` carries `required` + `defaultValue` so it can never be null. That // is not decoration: it mirrors the real `showcase_invoice_line.quantity`, // and without it `record.qty >= 100` is a genuine #4811 finding — `>=` on a @@ -4412,7 +4452,8 @@ describe('validateStackExpressions — reads only keys the spec declares (meta-t const slots = [...fieldKeys![1].matchAll(/'([^']+)'/g)].map((m) => m[1]); // [#25767] `conditionalRequired` left the list with its tombstone: the // schema no longer declares it, so the walk no longer reads it. - expect(slots).toEqual(['requiredWhen', 'readonlyWhen', 'visibleWhen', 'settledWhen']); + // [#36806] `uiReadonlyWhen`, the console hand lock, joined as the fifth. + expect(slots).toEqual(['requiredWhen', 'readonlyWhen', 'visibleWhen', 'settledWhen', 'uiReadonlyWhen']); expect(slots.filter((k) => !Object.keys(FieldSchema.shape).includes(k))).toEqual([]); }); diff --git a/packages/lint/src/validate-expressions.ts b/packages/lint/src/validate-expressions.ts index 47d488876b0..e03fa61acae 100644 --- a/packages/lint/src/validate-expressions.ts +++ b/packages/lint/src/validate-expressions.ts @@ -1374,6 +1374,13 @@ const FIELD_RULE_SLOT_CONSEQUENCE: Record = { // the honest cell until it does; re-measure and write the slot's own cell // then, as #6716 did for the other three. settledWhen: FIELD_RULE_SLOT_CONSEQUENCE_GENERIC, + // [#36806] The console hand lock: no server reads it, and the console's one + // verdict (`fieldReadOnlyByHand`, `@object-ui/core`) resolves a fault to + // LOCKED (`UI_READONLY_WHEN_FAULTED`), while the edit dialog refuses to save. + uiReadonlyWhen: + 'the predicate faults wherever that root is unbound, and the console resolves a hand lock it ' + + 'cannot evaluate to LOCKED: no person can edit the field there, and the edit dialog refuses to ' + + 'save until the predicate is fixed — while actions, imports, the API and flows keep writing it', // [#26646] A field group's section predicate takes the field `visibleWhen` // slot's verdict, with its own fault direction: the form renderer's // section gate (`sectionGateVisible`) evaluates it with the same engine, @@ -4267,7 +4274,17 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression // root verdict over FIELD_RULE_BOUND_ROOTS. Like `visibleWhen` it is // display only, so the server-side gates further down (the `parent` // gate, the null guard, the traversal refusal) do not apply to it. - for (const key of ['requiredWhen', 'readonlyWhen', 'visibleWhen', 'settledWhen'] as const) { + // + // [#36806] `uiReadonlyWhen` — the console hand lock (ruling 7180466652, + // the two-tier field-lock model) — is the sixth slot, judged as + // `readonlyWhen` is at this site: the `record`-scoped `check` and the + // root verdict over FIELD_RULE_BOUND_ROOTS (the spec gives it the same + // scope). No server ever evaluates it, so a fault has no judge but this + // pass (ADR-0137 D2): the console locks the field and the edit dialog + // refuses to submit. Display only as far as the write path goes, so it + // carries no write gate and the server-side gates further down (the + // `parent` gate, the null guard, the traversal refusal) do not apply. + for (const key of ['requiredWhen', 'readonlyWhen', 'visibleWhen', 'settledWhen', 'uiReadonlyWhen'] as const) { const where = `object '${objectName}' · field '${fname}' ${key}`; const raw = (f as AnyRec)[key]; // [#13935] Verdict FIRST, emitted second. `check` needs to know which diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index abd03aed691..fc3dd3f6eab 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -3846,6 +3846,9 @@ export function registerObjectTools( }, ); + // #36806: the uiReadonly clause names only the console surfaces that honour + // the hand lock; the Gantt, the timesheet cell, the swimlane drag and the + // assistant are #37448. server.registerTool( note('describe_object'), { @@ -3853,8 +3856,8 @@ export function registerObjectTools( 'Get the schema of a data object as you may read it, with what a write needs: name, label, description; ' + 'each field\'s name, type, label, description (where set: the author\'s, or the platform\'s on a column ' + 'it injects), required, readonly (leave it out of a write), uiReadonly / uiReadonlyWhen where set ' - + '(a person cannot edit the field at the console; your write may still set it, judged by the ' - + 'validations), system, ' + + '(a person cannot edit the field in the console\'s dialogs, record page, grids, kanban or calendar; ' + + 'your write may still set it, judged by the validations), system, ' + 'options (send the value) and defaultValue (omit the field to get it; never copy the value); the active ' + 'validations; the enabled features. readonly is the schema\'s, not your edit permission.', inputSchema: strictToolInput( diff --git a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index 30a5343fd8d..7a4fedb4d61 100644 --- a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts @@ -923,7 +923,7 @@ export const arMetadataForms: NonNullable = { }, uiReadonlyWhen: { label: "للقراءة فقط في الواجهة عندما", - helpText: "شرط CEL على السجل (مثل record.status != 'draft') — لا يمكن لأحد تعديل الحقل في وحدة التحكم ما دام TRUE؛ وتواصل الإجراءات والاستيرادات وواجهة API والتدفقات الكتابة فيه، وتحكم عليها قواعد التحقق الخاصة بالكائن. يقرأ أعمدة السجل نفسه، كما يفعل للقراءة فقط عندما." + helpText: "شرط CEL على السجل (مثل record.status != 'draft') — ما دام TRUE، لا يمكن لأحد تعديل الحقل في سجل موجود من وحدة التحكم (مربع التعديل، صفحة السجل، الجداول، والسحب في كانبان والتقويم)؛ ولا يُقيَّم في مربع إنشاء سجل جديد. تواصل الإجراءات والاستيراد وواجهة API والتدفقات الكتابة فيه، وتحكم عليها قواعد التحقق الخاصة بالكائن. يقرأ أعمدة السجل نفسه، مثل للقراءة فقط عندما." }, requiredWhen: { label: "مطلوب عندما", diff --git a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index 20052c43420..ad94ea66a9d 100644 --- a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts @@ -923,7 +923,7 @@ export const deMetadataForms: NonNullable = { }, uiReadonlyWhen: { label: "In der Oberfläche schreibgeschützt wenn", - helpText: "CEL-Prädikat über den Datensatz (z. B. record.status != 'draft') – solange es TRUE ist, kann niemand das Feld in der Konsole bearbeiten; Aktionen, Importe, die API und Flows schreiben es weiterhin, beurteilt von den Validierungen des Objekts. Liest die eigenen Spalten des Datensatzes, wie Schreibgeschützt wenn." + helpText: "CEL-Prädikat über den Datensatz (z. B. record.status != 'draft') – solange es TRUE ist, kann niemand das Feld eines bestehenden Datensatzes in der Konsole bearbeiten (Bearbeitungsdialog, Datensatzseite, Tabellen, Ziehen in Kanban und Kalender); der Erstellungsdialog eines neuen Datensatzes wertet es nicht aus. Aktionen, Importe, die API und Flows schreiben es weiterhin, beurteilt von den Validierungen des Objekts. Liest die eigenen Spalten des Datensatzes, wie Schreibgeschützt wenn." }, requiredWhen: { label: "Erforderlich wenn", diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index 8258938c035..b4412e3fc0f 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -923,7 +923,7 @@ export const enMetadataForms: NonNullable = { }, uiReadonlyWhen: { label: "Ui Readonly When", - helpText: "CEL predicate over the record (e.g. record.status != 'draft') — people cannot edit the field in the console while it is TRUE; actions, imports, the API and flows still write it, judged by the object's validations. Reads the record's own columns, as Read-only when does." + helpText: "CEL predicate over the record (e.g. record.status != 'draft') — while it is TRUE, people cannot edit the field of an existing record in the console (the edit dialog, the record page, grids, kanban and calendar drag); a new record's create dialog is not judged. Actions, imports, the API and flows still write it, judged by the object's validations. Reads the record's own columns, as Read-only when does." }, requiredWhen: { label: "Required When", diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index a89c3ae68ab..09f303845a1 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -923,7 +923,7 @@ export const esESMetadataForms: NonNullable = }, uiReadonlyWhen: { label: "Condición de solo lectura en la interfaz", - helpText: "Predicado CEL sobre el registro (p. ej., record.status != 'draft'): mientras sea TRUE, nadie puede editar el campo en la consola; las acciones, las importaciones, la API y los flujos siguen escribiéndolo, juzgados por las validaciones del objeto. Lee las columnas propias del registro, como Condición de solo lectura." + helpText: "Predicado CEL sobre el registro (p. ej., record.status != 'draft'): mientras sea TRUE, nadie puede editar el campo de un registro existente en la consola (el diálogo de edición, la página del registro, las cuadrículas y el arrastre en kanban y calendario); el diálogo de creación de un registro nuevo no lo evalúa. Las acciones, las importaciones, la API y los flujos siguen escribiéndolo, juzgados por las validaciones del objeto. Lee las columnas propias del registro, como Solo lectura cuando." }, requiredWhen: { label: "Condición de obligatoriedad", diff --git a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts index 93d2b467ae5..db46500ced3 100644 --- a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts @@ -923,7 +923,7 @@ export const frMetadataForms: NonNullable = { }, uiReadonlyWhen: { label: "Lecture seule dans l'interface si", - helpText: "Prédicat CEL sur l'enregistrement (par ex. record.status != 'draft') : tant qu'il vaut TRUE, personne ne peut modifier le champ dans la console ; les actions, les imports, l'API et les flux continuent de l'écrire, jugés par les validations de l'objet. Lit les colonnes propres de l'enregistrement, comme Lecture seule si." + helpText: "Prédicat CEL sur l'enregistrement (p. ex. record.status != 'draft') : tant qu'il vaut TRUE, personne ne peut modifier le champ d'un enregistrement existant dans la console (la boîte d'édition, la page de l'enregistrement, les grilles, le glisser-déposer du kanban et du calendrier) ; la boîte de création d'un nouvel enregistrement ne l'évalue pas. Les actions, les imports, l'API et les flux continuent de l'écrire, jugés par les validations de l'objet. Lit les colonnes propres de l'enregistrement, comme Lecture seule si." }, requiredWhen: { label: "Obligatoire si", diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index 08d8d8d57aa..b0ced8bf199 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -923,7 +923,7 @@ export const jaJPMetadataForms: NonNullable = }, uiReadonlyWhen: { label: "画面上で読み取り専用の条件", - helpText: "レコードに対する CEL 述語(例: record.status != 'draft')。TRUE の間はコンソールでこのフィールドを編集できません。アクション、インポート、API、フローは引き続き書き込めて、オブジェクトの検証ルールで判定されます。「読み取り専用条件」と同じく、レコード自身の列を読みます。" + helpText: "レコードに対する CEL 述語(例: record.status != 'draft')— TRUE の間、既存レコードのこのフィールドはコンソールで編集できません(編集ダイアログ、レコードページ、グリッド、かんばんとカレンダーのドラッグ)。新規レコードの作成ダイアログでは判定されません。アクション、インポート、API、フローは引き続き書き込み、オブジェクトの検証ルールが判定します。「読み取り専用条件」と同じくレコード自身の列を読みます。" }, requiredWhen: { label: "必須条件", diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index d29a4bfe45a..c9e2e0bf8e1 100644 --- a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts @@ -923,7 +923,7 @@ export const koMetadataForms: NonNullable = { }, uiReadonlyWhen: { label: "화면에서 읽기 전용 조건", - helpText: "레코드에 대한 CEL 조건식(예: record.status != 'draft') — TRUE인 동안 콘솔에서 이 필드를 편집할 수 없습니다. 작업, 가져오기, API, 플로우는 계속 기록하며 개체의 유효성 검사로 판정됩니다. 읽기 전용 조건과 마찬가지로 레코드 자체의 열을 읽습니다." + helpText: "레코드에 대한 CEL 조건식(예: record.status != 'draft') — TRUE인 동안 기존 레코드의 이 필드는 콘솔에서 편집할 수 없습니다(편집 대화상자, 레코드 페이지, 그리드, 칸반 및 캘린더 드래그). 새 레코드의 생성 대화상자는 판단하지 않습니다. 작업, 가져오기, API 및 흐름은 계속 기록하며, 객체의 유효성 검사가 판단합니다. '읽기 전용 조건'처럼 레코드 자체의 열을 읽습니다." }, requiredWhen: { label: "필수 조건", diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index 95aa18c59c9..4598566df0f 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts @@ -923,7 +923,7 @@ export const ptBRMetadataForms: NonNullable = }, uiReadonlyWhen: { label: "Somente leitura na interface quando", - helpText: "Predicado CEL sobre o registro (por ex., record.status != 'draft') — enquanto for TRUE, ninguém pode editar o campo no console; ações, importações, a API e fluxos continuam gravando-o, julgados pelas validações do objeto. Lê as colunas do próprio registro, como Somente leitura quando." + helpText: "Predicado CEL sobre o registro (ex.: record.status != 'draft') — enquanto for TRUE, ninguém pode editar o campo de um registro existente no console (a caixa de edição, a página do registro, as grades e o arrastar no kanban e no calendário); a caixa de criação de um novo registro não o avalia. Ações, importações, a API e os fluxos continuam gravando-o, julgados pelas validações do objeto. Lê as colunas do próprio registro, como Somente leitura quando." }, requiredWhen: { label: "Obrigatório quando", diff --git a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index 50b3d6cabe8..8f88b9903d9 100644 --- a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts @@ -923,7 +923,7 @@ export const ruMetadataForms: NonNullable = { }, uiReadonlyWhen: { label: "Только для чтения в интерфейсе, когда", - helpText: "Предикат CEL по записи (например, record.status != 'draft') — пока он TRUE, никто не может изменить поле в консоли; действия, импорт, API и потоки продолжают записывать его, и записи проверяются правилами проверки объекта. Читает собственные столбцы записи, как «Только для чтения, когда»." + helpText: "Предикат CEL над записью (например, record.status != 'draft') — пока он TRUE, никто не может изменить поле существующей записи в консоли (диалог редактирования, страница записи, таблицы, перетаскивание в канбане и календаре); диалог создания новой записи его не оценивает. Действия, импорт, API и потоки по-прежнему записывают его, и каждую запись оценивают проверки объекта. Читает собственные столбцы записи, как «Только чтение, если»." }, requiredWhen: { label: "Обязательно, когда", diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index 7167e560db6..6cc0aba8f02 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -923,7 +923,7 @@ export const zhCNMetadataForms: NonNullable = }, uiReadonlyWhen: { label: "界面只读条件", - helpText: "基于记录的 CEL 谓词(例如 record.status != 'draft')——为 TRUE 时用户无法在控制台中编辑该字段;动作、导入、API 和流程仍可写入,并由对象的校验规则裁决。与“只读条件”一样读取记录自身的列。" + helpText: "基于记录的 CEL 谓词(例如 record.status != 'draft')——为 TRUE 时,用户无法在控制台中编辑已有记录的该字段(编辑对话框、记录页、表格、看板和日历拖动);新建记录的创建对话框不做判断。动作、导入、API 和流程仍可写入,并由对象的校验规则裁决。与“只读条件”一样读取记录自身的列。" }, requiredWhen: { label: "必填条件", diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index be8b035c252..2a94d30ccf0 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts @@ -923,7 +923,7 @@ export const zhHantMetadataForms: NonNullable }, uiReadonlyWhen: { label: "介面唯讀條件", - helpText: "針對記錄的 CEL 述詞(例如 record.status != 'draft')——為 TRUE 時使用者無法在主控台中編輯該欄位;動作、匯入、API 與流程仍可寫入,並由物件的驗證規則裁決。與「唯讀條件」一樣讀取記錄自身的欄位。" + helpText: "基於記錄的 CEL 謂詞(例如 record.status != 'draft')——為 TRUE 時,使用者無法在控制台中編輯既有記錄的該欄位(編輯對話框、記錄頁、表格、看板和行事曆拖曳);新建記錄的建立對話框不做判斷。動作、匯入、API 和流程仍可寫入,並由物件的驗證規則裁決。與「唯讀條件」一樣讀取記錄自身的欄。" }, requiredWhen: { label: "必填條件", diff --git a/packages/spec/liveness/field.json b/packages/spec/liveness/field.json index a0314f8b6b3..e0bf2c5273d 100644 --- a/packages/spec/liveness/field.json +++ b/packages/spec/liveness/field.json @@ -153,7 +153,7 @@ "verifiedAt": "2026-11-26", "evidenceScope": "in-repo", "evidence": "ui/packages/core/src/evaluator/handLock.ts#fieldReadOnlyByHand (the one hand-lock verdict, the predicate run through ui/packages/core/src/evaluator/fieldRules.ts#resolveFieldRuleState); its readers are the hand surfaces listed on `uiReadonly`, with the per-record reads in the form renderer (ui/packages/components/src/renderers/form/form.tsx), the record page (DetailSection, HeaderHighlight, InlineEditSaveBar, recordPathStageChange), the grid cell (ui/packages/plugin-grid/src/objectGridCellFacts.ts#cellReadOnlyKind), the line-item cell (ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx), kanban and calendar drops; packages/runtime/src/domains/mcp.ts#describedHandLock (describe_object)", - "note": "renderer only, by ruling (the two-tier field-lock model): while TRUE no person edits the field at the console; the engine never reads it, so API, import, action and flow writes keep it, judged by validations. Allowed beside `readonlyWhen`, the stricter server lock. Fail-open on a fault, as `readonlyWhen` on the client." + "note": "renderer only, by ruling (the two-tier field-lock model): while TRUE no person edits the field of an existing record at the console surfaces listed on `uiReadonly` (the edit dialog, not the create dialog: a create is not judged); the engine never reads it, so API, import, action and flow writes keep it, judged by validations. Allowed beside `readonlyWhen`, the stricter server lock. Fail-closed on a fault (no server judges it, ADR-0137 D2): the field locks, the edit dialog refuses to submit, and `objectstack validate` checks the predicate (packages/lint/src/validate-expressions.ts)." }, "visibleWhen": { "status": "live", @@ -203,8 +203,8 @@ "status": "live", "verifiedAt": "2026-11-26", "evidenceScope": "in-repo", - "evidence": "ui/packages/core/src/evaluator/handLock.ts#fieldStaticallyReadOnlyByHand and #fieldReadOnlyByHand (the one hand-lock verdict every hand surface reads): the create and edit dialogs and their payload (ui/packages/plugin-form/src/autoLayout.ts, sectionFields.ts, ObjectForm.tsx, sanitize.ts), record-page inline edit and the stage path (ui/packages/plugin-detail/src/DetailSection.tsx, InlineEditSaveBar.tsx, renderers/recordPathStageChange.tsx), the highlight-strip chip (HeaderHighlight.tsx), grid inline edit (ui/packages/plugin-grid/src/inline-edit-options.ts), kanban drag (ui/packages/plugin-kanban/src/ObjectKanban.tsx), calendar drag (ui/packages/plugin-calendar/src/ObjectCalendar.tsx), the line-item grid (packages/spec/src/data/inline-grid-columns.ts#deriveInlineGridColumns); packages/spec/src/data/field.zod.ts#uiReadonly (the parse refuses it beside `readonly: true`); packages/runtime/src/domains/mcp.ts#describedHandLock (describe_object)", - "note": "renderer only, by ruling (the two-tier field-lock model): no person edits the field at the console, and every other write keeps it — the engine never reads the key, so REST, import, action and flow writes set it, judged by validations (a state_machine rule included); a console create leaves it out and the server applies its defaultValue. The import mapping and Studio reads stay on raw `readonly`." + "evidence": "ui/packages/core/src/evaluator/handLock.ts#fieldStaticallyReadOnlyByHand and #fieldReadOnlyByHand (the one hand-lock verdict every hand surface reads): the create and edit dialogs and their payload (ui/packages/plugin-form/src/autoLayout.ts, sectionFields.ts, ObjectForm.tsx, sanitize.ts), record-page inline edit and the stage path (ui/packages/plugin-detail/src/DetailSection.tsx, InlineEditSaveBar.tsx, renderers/recordPathStageChange.tsx), the highlight-strip chip (HeaderHighlight.tsx), grid inline edit (ui/packages/plugin-grid/src/inline-edit-options.ts), kanban drag (ui/packages/plugin-kanban/src/ObjectKanban.tsx), calendar drag (ui/packages/plugin-calendar/src/ObjectCalendar.tsx), the line-item grid (packages/spec/src/data/inline-grid-columns.ts#deriveInlineGridColumns, and an authored column over the field through ui/packages/plugin-form/src/deriveMasterDetail.ts#hydrateColumns); packages/spec/src/data/field.zod.ts#uiReadonly (the parse refuses it beside `readonly: true`); packages/runtime/src/domains/mcp.ts#describedHandLock (describe_object)", + "note": "renderer only, by ruling (the two-tier field-lock model): no person edits the field at the console, and every other write keeps it — the engine never reads the key, so REST, import, action and flow writes set it, judged by validations (a state_machine rule included); a console create leaves it out and the server applies its defaultValue (so a `required` field without one fails every console create). Honoured on the surfaces in evidence only; the Gantt, the timesheet cell, the kanban swimlane drag and the in-app assistant do not read it yet (#37448). The import mapping and Studio reads stay on raw `readonly`." }, "hidden": { "status": "live", diff --git a/packages/spec/src/data/field.form.ts b/packages/spec/src/data/field.form.ts index 42ee9d473a0..eced0424acf 100644 --- a/packages/spec/src/data/field.form.ts +++ b/packages/spec/src/data/field.form.ts @@ -483,7 +483,7 @@ export const fieldForm = defineForm({ { field: 'readonlyWhen', type: 'code', language: 'expression', colSpan: 2, helpText: "CEL predicate over the record (e.g. record.status == 'paid') — the field is read-only while it is TRUE, enforced server-side: an update's change to a locked field is dropped and the stored value kept. Reads the record's own columns; objectstack validate refuses a read through a reference field." }, // #36806 — the hand lock's predicate: the console locks the field while it // is TRUE; writes from actions, imports, the API and flows keep it. - { field: 'uiReadonlyWhen', type: 'code', language: 'expression', colSpan: 2, helpText: "CEL predicate over the record (e.g. record.status != 'draft') — people cannot edit the field in the console while it is TRUE; actions, imports, the API and flows still write it, judged by the object's validations. Reads the record's own columns, as Read-only when does." }, + { field: 'uiReadonlyWhen', type: 'code', language: 'expression', colSpan: 2, helpText: "CEL predicate over the record (e.g. record.status != 'draft') — while it is TRUE, people cannot edit the field of an existing record in the console (the edit dialog, the record page, grids, kanban and calendar drag); a new record's create dialog is not judged. Actions, imports, the API and flows still write it, judged by the object's validations. Reads the record's own columns, as Read-only when does." }, { field: 'requiredWhen', type: 'code', language: 'expression', colSpan: 2, helpText: "CEL predicate over the record — the field is required while it is TRUE, enforced server-side as a transition gate: a write that leaves the value missing is refused when the record complied before it, so a row already missing the value keeps passing unrelated edits. For a rule every write must meet, use a validations script rule. Refused beside storage.notNull." }, // Partial masking (#8993): a preset name or a {keepHead, keepTail} JSON // object; the runtime FieldMasker enforces it on read AND export. diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index 5882e31d81b..87ce82ac937 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -2917,10 +2917,17 @@ export const FieldSchema = lazySchema(() => { 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."), /** * The CONDITIONAL hand lock (ruling record 7180466652, the two-tier field-lock - * model): while TRUE no person edits the field at the console, and every - * other write keeps it. The conditional twin of `uiReadonly` — see there for - * which writes are "by hand". Same scope as `readonlyWhen`: the bound - * record's OWN columns, e.g. P`record.status != 'draft'`. + * model): while TRUE no person edits the field of an existing record at the + * console surfaces that honour `uiReadonly`, and every other write keeps it. + * The conditional twin of `uiReadonly` — see there for which writes are "by + * hand". A create is not judged (the create dialog has no record to read). + * Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. + * P`record.status != 'draft'`. + * + * A predicate that cannot be evaluated (a syntax error, a missing operand) + * fails CLOSED — the field is locked — because no server judges this key + * (ADR-0137 D2); the edit dialog also refuses to submit, as it does for a + * faulted `visibleWhen`. `objectstack validate` checks the predicate. * * Allowed beside `readonlyWhen` (unlike `uiReadonly` beside `readonly`): the * two predicates can differ, and where `readonlyWhen` is TRUE the server lock @@ -2930,7 +2937,7 @@ export const FieldSchema = lazySchema(() => { * `@object-ui/core` (`fieldReadOnlyByHand`); the engine never reads it, so a * TRUE predicate refuses no API, import, action or flow write. */ - uiReadonlyWhen: EvaluatedExpressionInputSchema.optional().describe("Predicate (CEL) — the field is read-only BY HAND when TRUE: no console surface lets a person edit it (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit, kanban and calendar drag), while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key."), + uiReadonlyWhen: EvaluatedExpressionInputSchema.optional().describe("Predicate (CEL) — the field is read-only BY HAND on an existing record while TRUE: the console surfaces that honour `uiReadonly` (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the line-item grid) do not let a person edit it, while REST, import, action and flow writes keep it, judged by the object's validations — see `uiReadonly`. A create is not judged: the create dialog offers the field whatever the predicate says. A predicate the console cannot evaluate locks the field, and the edit dialog refuses to submit until it is fixed. Same scope as `readonlyWhen`: the bound record's OWN columns, e.g. P`record.status != 'draft'`. Allowed beside `readonlyWhen`, which is the stricter lock: where `readonlyWhen` is TRUE non-system writes are dropped as well. The engine never reads this key."), 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."), /** @@ -3072,13 +3079,17 @@ export const FieldSchema = lazySchema(() => { * by its buttons, never typed. * * "By hand" = the create and edit dialogs and the payload they submit, the - * record page's inline edit, the highlight-strip chip, grid inline edit and - * its multi-row save, kanban drag between columns grouped by the field, and - * calendar drag. NOT by hand = REST create/update, import (the console import - * wizard included), declarative and script actions, flows. A console create - * leaves the field out, so the server applies its `defaultValue`; an API, - * import or action insert may set it, judged by validations (a state - * machine's `initialStates`). + * record page's inline edit and stage path, the highlight-strip chip, grid + * inline edit and its multi-row save, kanban drag between columns grouped by + * the field, calendar drag, and the line-item grid. Those are the surfaces + * that honour it today; the Gantt's drag and in-place edit, the timesheet + * cell, the kanban swimlane drag and the in-app assistant acting for a + * person do not read it yet (#37448). NOT by hand = REST create/update, + * import (the console import wizard included), declarative and script + * actions, flows. A console create leaves the field out, so the server + * applies its `defaultValue` — a `required` field with no `defaultValue` + * therefore fails every console create; an API, import or action insert may + * set it, judged by validations (a state machine's `initialStates`). * * Refused beside `readonly: true` (the superRefine below): the server lock * already keeps every client out, so the pair says two things at once. @@ -3092,7 +3103,7 @@ export const FieldSchema = lazySchema(() => { * boundary: a caller who may edit the object can write the field through * the API; field permissions (`editable` on a permission set) are that. */ - uiReadonly: z.boolean().optional().describe("Read-only BY HAND: no console surface lets a person edit the field (create and edit dialogs, record-page inline edit, the highlight strip, grid inline edit and multi-row save, kanban and calendar drag), while every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`; an API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`."), + uiReadonly: z.boolean().optional().describe("Read-only BY HAND: the console's editing surfaces do not let a person edit the field — the create and edit dialogs (it is left off them and out of their payload), record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag and the line-item grid; other console surfaces do not read it yet. Every other write KEEPS it — REST create/update, import, declarative and script actions and flows write it, judged by the object's validations exactly as an ordinary field (a `state_machine` rule included). For a field that changes only through actions, e.g. an order `status` moved by Confirm / Cancel buttons. A console create leaves the field out and the server applies its `defaultValue`, so a `required` field needs a `defaultValue`: without one every create from the console fails. An API, import or action insert may set it, judged by validations (a state machine's `initialStates`). Absent = false. Refused beside `readonly: true`, which already keeps every client out: `readonly` when no client may write the field, `uiReadonly` when only people at the console may not. Not a security boundary — field permissions are. The conditional twin is `uiReadonlyWhen`."), /** * [ADR-0066 D3] Capabilities required to READ/EDIT this field. A field diff --git a/ui/packages/components/src/renderers/form/__tests__/uiReadonlyWhen-fault-refuses-submit-36806.test.tsx b/ui/packages/components/src/renderers/form/__tests__/uiReadonlyWhen-fault-refuses-submit-36806.test.tsx new file mode 100644 index 00000000000..ea5d65fe8bf --- /dev/null +++ b/ui/packages/components/src/renderers/form/__tests__/uiReadonlyWhen-fault-refuses-submit-36806.test.tsx @@ -0,0 +1,115 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#36806 (REWORK S2) — an EDIT form refuses a submit whose field + * `uiReadonlyWhen` could not be evaluated, as it does for a faulted + * `visibleWhen` (objectui#8069). + * + * The hand lock is console-only: no server evaluates `uiReadonlyWhen`, so + * ADR-0137 D2's "the submit refuses what render let through" has this form as + * its one possible judge. Render holds the field locked (the hand lock fails + * closed); the refusal says the rule itself must be fixed. A CREATE form never + * judges the hand lock's predicate (no stored record to read), so it neither + * locks nor refuses there. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react'; +import { ComponentRegistry } from '@object-ui/core'; +import { toast } from '../../../ui/sonner'; +// Registers the renderers at module scope (object-ui/no-dynamic-import-in-test-hook). +import '../../../renderers'; + +beforeEach(() => { + vi.spyOn(toast, 'error').mockImplementation(() => 'id' as never); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const proto = Element.prototype as unknown as { scrollIntoView?: () => void }; + if (!proto.scrollIntoView) proto.scrollIntoView = () => {}; +}); + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +const EDIT = { + mode: 'edit', + defaultValues: { stage: 'open', discount: '5' }, + previousValues: { stage: 'open', discount: '5' }, +}; + +function renderForm( + fields: Array>, + onSubmit: (data: unknown) => Promise, + extra: Record = {}, +) { + const Form = ComponentRegistry.get('form')!; + return render( +
, + ); +} + +const submit = () => fireEvent.click(screen.getByRole('button', { name: /save/i })); +const refusalText = () => screen.queryByRole('alert')?.textContent ?? ''; + +/** A predicate the engine cannot parse: a fault whatever the record holds. */ +const BROKEN = 'record.stage =='; + +const base = (discount: Record) => [ + { name: 'stage', label: 'Stage', type: 'input' }, + { name: 'discount', label: 'Discount', type: 'input', ...discount }, +]; + +describe('objectstack#36806 — a faulted uiReadonlyWhen refuses an edit form\'s submit', () => { + it('refuses, calls no host, names the field and the rule; the field is drawn locked', async () => { + const onSubmit = vi.fn().mockResolvedValue(undefined); + renderForm(base({ uiReadonlyWhen: BROKEN }), onSubmit, EDIT); + expect(screen.getByLabelText(/^Discount/)).toHaveAttribute('readonly'); + + submit(); + + await waitFor(() => expect(refusalText()).toMatch(/uiReadonlyWhen rule of Discount could not be evaluated/)); + expect(onSubmit).not.toHaveBeenCalled(); + }); + + it('refuses on a field that also carries a visibleWhen (the other evaluation path)', async () => { + const onSubmit = vi.fn().mockResolvedValue(undefined); + renderForm(base({ visibleWhen: 'true', uiReadonlyWhen: BROKEN }), onSubmit, EDIT); + submit(); + await waitFor(() => expect(refusalText()).toMatch(/uiReadonlyWhen rule of Discount could not be evaluated/)); + expect(onSubmit).not.toHaveBeenCalled(); + }); + + it('CONTROL — a uiReadonlyWhen that evaluates submits', async () => { + const onSubmit = vi.fn().mockResolvedValue(undefined); + renderForm(base({ uiReadonlyWhen: "record.stage == 'won'" }), onSubmit, EDIT); + expect(screen.getByLabelText(/^Discount/)).not.toHaveAttribute('readonly'); + submit(); + await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1)); + }); + + it('CONTROL — a create form does not judge it: the field edits and the submit goes through', async () => { + const onSubmit = vi.fn().mockResolvedValue(undefined); + renderForm(base({ uiReadonlyWhen: BROKEN }), onSubmit); + expect(screen.getByLabelText(/^Discount/)).not.toHaveAttribute('readonly'); + submit(); + await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1)); + }); +}); diff --git a/ui/packages/components/src/renderers/form/form.tsx b/ui/packages/components/src/renderers/form/form.tsx index 5c24b3e979b..acc9b9ce026 100644 --- a/ui/packages/components/src/renderers/form/form.tsx +++ b/ui/packages/components/src/renderers/form/form.tsx @@ -580,6 +580,10 @@ const useSafeFormTranslation = createSafeTranslation( // not be evaluated (see `handleSubmit`). Byte-identical to the `en` pack. 'form.visibleWhenFaulted': "Can't submit: the visibleWhen rule of {{fields}} could not be evaluated. The rule must be fixed before this form can be submitted.", + // objectstack#36806 — the same refusal for a faulted `uiReadonlyWhen` (the + // hand lock no server judges). Byte-identical to the `en` pack. + 'form.uiReadonlyWhenFaulted': + "Can't submit: the uiReadonlyWhen rule of {{fields}} could not be evaluated. The rule must be fixed before this form can be submitted.", // objectui#12108 — the hint under an empty field the server fills at insert // (see `renderFieldDescription`). Byte-identical to the `en` pack. 'form.serverDefaultHint': 'Set automatically when saved.', @@ -2247,14 +2251,33 @@ ComponentRegistry.register('form', // stored BLANK field rule is a fault like any other (ADR-0137 D2; see // `FieldRuleFaults`) and is refused; a new one is refused earlier, at // authoring, by the form schema's triad wire. - const { conditionallyHiddenFieldNames, faultedVisibleWhenFieldNames } = React.useMemo(() => { + // [objectstack#36806] A faulted `uiReadonlyWhen` (the hand lock's + // predicate) is refused the same way, on an edit form (a create never + // judges it). It has the one possible judge here: no server evaluates the + // hand lock, so ADR-0137 D2's "the submit refuses what render let through" + // can only be this form. Render already holds the field locked (the hand + // lock fails closed); the refusal says the rule itself must be fixed. + const { conditionallyHiddenFieldNames, faultedVisibleWhenFieldNames, faultedUiReadonlyWhenFieldNames } = React.useMemo(() => { const hidden = new Set(); const faulted: string[] = []; + const faultedHandLock: string[] = []; for (const f of fields as FormFieldConfig[]) { const name = f?.name; if (!name) continue; const visibleWhen = (f as any).visibleWhen; const visibleOn = (f as any).visibleOn; + const uiReadonlyWhen = isCreateForm ? undefined : (f as any).uiReadonlyWhen; + if (uiReadonlyWhen != null && visibleWhen == null && f.type !== 'section-divider') { + const handLock = resolveFieldRuleState( + { uiReadonlyWhen }, + ruleRecord, + { readonly: (f as any).readonly === true }, + previousRecord, + predicateScope, + `field '${name}'`, + ); + if (handLock.faults.uiReadonlyWhen !== undefined) faultedHandLock.push(name); + } if (visibleWhen == null && visibleOn == null) continue; if (visibleWhen != null) { // A fail-closed section gate (objectui#13055) is judged off the triad. @@ -2279,6 +2302,7 @@ ComponentRegistry.register('form', `field '${name}'`, ); if (st.faults.visibleWhen !== undefined && f.type !== 'section-divider') faulted.push(name); + if (st.faults.uiReadonlyWhen !== undefined && f.type !== 'section-divider') faultedHandLock.push(name); if (!st.visible || (gate && !sectionGateVisible(f, ruleRecord, previousRecord, predicateScope))) { hidden.add(name); continue; @@ -2293,7 +2317,11 @@ ComponentRegistry.register('form', hidden.add(name); } } - return { conditionallyHiddenFieldNames: hidden, faultedVisibleWhenFieldNames: faulted }; + return { + conditionallyHiddenFieldNames: hidden, + faultedVisibleWhenFieldNames: faulted, + faultedUiReadonlyWhenFieldNames: faultedHandLock, + }; }, [fields, ruleRecord, previousRecord, isCreateForm, predicateScope]); // ── The section grouping contract (objectui#6236, maintainer ruling @@ -3649,6 +3677,16 @@ ComponentRegistry.register('form', setRejectedFieldNames(faultedVisibleWhenFieldNames); return Promise.resolve(); } + if (faultedUiReadonlyWhenFieldNames.length > 0) { + event?.preventDefault?.(); + raiseRefusal(t('form.uiReadonlyWhenFaulted', { + fields: faultedUiReadonlyWhenFieldNames + .map((n) => fieldLabelByName[n] || n) + .join(t('validation.formInvalidJoiner')), + })); + setRejectedFieldNames(faultedUiReadonlyWhenFieldNames); + return Promise.resolve(); + } return submitThroughValidation(event); }; diff --git a/ui/packages/core/src/evaluator/__tests__/handLock-36806.test.ts b/ui/packages/core/src/evaluator/__tests__/handLock-36806.test.ts index 15cbbdff6ad..a995b6cfd8f 100644 --- a/ui/packages/core/src/evaluator/__tests__/handLock-36806.test.ts +++ b/ui/packages/core/src/evaluator/__tests__/handLock-36806.test.ts @@ -39,8 +39,29 @@ describe('fieldReadOnlyByHand (#36806)', () => { expect(fieldReadOnlyByHand({}, { status: 'draft' })).toBe(false); }); - it('a predicate that cannot be evaluated leaves the field editable (fail-open)', () => { - expect(fieldReadOnlyByHand({ uiReadonlyWhen: 'record.(' }, { status: 'x' })).toBe(false); + // REWORK S2: no server judges the hand lock (ADR-0137 D2), so a fault + // LOCKS the field — unlike `readonlyWhen`, whose fault the server answers. + it('a uiReadonlyWhen that cannot be evaluated LOCKS the field (fail-closed)', () => { + expect(fieldReadOnlyByHand({ uiReadonlyWhen: 'record.(' }, { status: 'x' })).toBe(true); + // The control: a faulted readonlyWhen stays open on the client. + expect(fieldReadOnlyByHand({ readonlyWhen: 'record.(' }, { status: 'x' })).toBe(false); + }); + + // REWORK S1: a projected row that lacks the operand cannot be judged. + it('a row missing the predicate\'s operand is locked, and judged once the operand is read', () => { + const def = { uiReadonlyWhen: "record.status != 'draft'" }; + expect(fieldReadOnlyByHand(def, { name: 'projected row' })).toBe(true); + expect(fieldReadOnlyByHand(def, { name: 'full row', status: 'draft' })).toBe(false); + }); + + // REWORK S1: the host scope binds `current_user` on every surface. + it('judges a current_user predicate over the host scope it is given', () => { + const def = { uiReadonlyWhen: "current_user.id != record.owner" }; + const scope = { current_user: { id: 'u1' } }; + expect(fieldReadOnlyByHand(def, { owner: 'u1' }, { scope })).toBe(false); + expect(fieldReadOnlyByHand(def, { owner: 'u2' }, { scope })).toBe(true); + // No scope: the root is unbound, the predicate faults, the field locks. + expect(fieldReadOnlyByHand(def, { owner: 'u1' })).toBe(true); }); }); @@ -55,4 +76,10 @@ describe('resolveFieldRuleState folds the hand lock (#36806)', () => { expect(resolveFieldRuleState(rules, { status: 'approved' }, {}).readonly).toBe(true); expect(resolveFieldRuleState(rules, { status: 'draft' }, {}).readonly).toBe(false); }); + + it('a faulted uiReadonlyWhen locks and is reported under its own key', () => { + const state = resolveFieldRuleState({ uiReadonlyWhen: 'record.(' }, { status: 'x' }, {}); + expect(state.readonly).toBe(true); + expect(state.faults?.uiReadonlyWhen).toBeTruthy(); + }); }); diff --git a/ui/packages/core/src/evaluator/fieldRules.ts b/ui/packages/core/src/evaluator/fieldRules.ts index 9a26645def9..9bc3142cbb7 100644 --- a/ui/packages/core/src/evaluator/fieldRules.ts +++ b/ui/packages/core/src/evaluator/fieldRules.ts @@ -353,6 +353,18 @@ export function evalFieldPredicate( const VISIBLE_WHEN_FAULTED = true; const READONLY_WHEN_FAULTED = false; const REQUIRED_WHEN_FAULTED = false; +/** + * The hand lock's predicate (`Field.uiReadonlyWhen`, objectstack#36806) fails + * CLOSED, unlike `readonlyWhen`. ADR-0137 D2 lets a lock fail open at render + * only because a judge stands behind it: the server drops a `readonlyWhen` + * write the client let through. No server evaluates `uiReadonlyWhen` — it is a + * console-only lock — so a fault that opened the field would be a silent edit + * nobody judges. Closed costs a person the edit (the warning names the fault, + * and actions, imports and the API still write the field); open would cost the + * lock. The same verdict covers a row that does not carry the predicate's + * operands (`No such key`): locked until the row is read in full. + */ +const UI_READONLY_WHEN_FAULTED = true; /** * The verdict {@link resolveFieldRuleState} applies when the author declared NO @@ -403,7 +415,7 @@ const REQUIRED_WHEN_ABSENT = false; export interface FieldRuleFaults { visibleWhen?: string; readonlyWhen?: string; - /** The hand lock's predicate (`@objectstack/spec` `Field.uiReadonlyWhen`); fail-open, as `readonlyWhen`. */ + /** The hand lock's predicate (`@objectstack/spec` `Field.uiReadonlyWhen`); fails CLOSED (no server judges it). */ uiReadonlyWhen?: string; requiredWhen?: string; } @@ -468,7 +480,8 @@ export function resolveFieldRuleState( * The HAND lock's predicate (`@objectstack/spec` `Field.uiReadonlyWhen`, * ruling record 7180466652): folded into the same `readonly` verdict, since * every caller of this function is a console surface a person edits - * through. Fail-open on a fault, as `readonlyWhen`. + * through. Fails CLOSED on a fault (see `UI_READONLY_WHEN_FAULTED`): no + * server judges it, so a fault never opens the field. */ uiReadonlyWhen?: FieldRulePredicate; requiredWhen?: FieldRulePredicate; @@ -536,7 +549,7 @@ export function resolveFieldRuleState( ? evalFieldPredicate( rules.uiReadonlyWhen, record, - READONLY_WHEN_FAULTED, + UI_READONLY_WHEN_FAULTED, previous, scope, diag('uiReadonlyWhen'), diff --git a/ui/packages/core/src/evaluator/handLock.ts b/ui/packages/core/src/evaluator/handLock.ts index f369e12325e..1608d3c4fd9 100644 --- a/ui/packages/core/src/evaluator/handLock.ts +++ b/ui/packages/core/src/evaluator/handLock.ts @@ -33,8 +33,11 @@ * * The predicate halves run through {@link resolveFieldRuleState}, the one * evaluator of field-level CEL, so a predicate here means what it means on - * the form; a predicate that cannot be evaluated leaves the field editable, - * as `readonlyWhen` does everywhere on the client (the server decides). + * the form. A `readonlyWhen` that cannot be evaluated leaves the field + * editable (the server drops the write); a `uiReadonlyWhen` that cannot be + * evaluated LOCKS it, since no server judges the hand lock — including a row + * that does not carry the predicate's operands, so a surface whose row is a + * projection reads them first (the grid's row load, `@object-ui/plugin-grid`). */ import { resolveFieldRuleState, type FieldRulePredicate } from './fieldRules.js'; @@ -74,7 +77,8 @@ export function fieldHasConditionalHandLock(def: FieldHandLockDef | null | undef /** * The FULL verdict over one record: the static half, or `readonlyWhen` / * `uiReadonlyWhen` TRUE over `record`. With no record the predicates are - * judged over an empty one (a column-level question, answered fail-open). + * judged over an empty one: `readonlyWhen` then answers open, `uiReadonlyWhen` + * locked (it cannot be judged, and nothing behind it judges the write). */ export function fieldReadOnlyByHand( def: FieldHandLockDef | null | undefined, diff --git a/ui/packages/fields/src/widgets/GridField.handLock-36806.test.tsx b/ui/packages/fields/src/widgets/GridField.handLock-36806.test.tsx index 2962552ae42..b06d29f4556 100644 --- a/ui/packages/fields/src/widgets/GridField.handLock-36806.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.handLock-36806.test.tsx @@ -53,4 +53,24 @@ describe('line-item grid hand lock (uiReadonlyWhen, #36806)', () => { ); expect((screen.getAllByLabelText('Qty')[0] as HTMLInputElement).disabled).toBe(true); }); + + // REWORK S3(a): an authored column over a `uiReadonly` child field carries + // `uiReadonly: true` (plugin-form's `hydrateColumns`), and the cell reads it. + it('a column carrying uiReadonly locks every row', () => { + render( + {}} + field={{ + columns: [ + { name: 'product', label: 'Product', type: 'text' }, + { name: 'status', label: 'Status', type: 'text', uiReadonly: true }, + ], + } as any} + contextRecord={{}} + />, + ); + expect((screen.getAllByLabelText('Status')[0] as HTMLInputElement).disabled).toBe(true); + expect((screen.getAllByLabelText('Product')[0] as HTMLInputElement).disabled).toBe(false); + }); }); diff --git a/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx index 3caf84c8c3d..365c2afc0af 100644 --- a/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx +++ b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx @@ -842,6 +842,11 @@ function GridFieldBody({ // The child FIELD's hand-lock predicate, carried onto the column in memory // by `@object-ui/plugin-form`'s column derivation (never an authored // `inlineColumns` key), folds into the same per-row verdict. + // A child field's static `uiReadonly` rides the same in-memory carry + // when an AUTHORED column names it (objectstack#36806): locked on every + // row, no predicate to judge. + const uiReadonly = (c as { uiReadonly?: boolean }).uiReadonly === true; + if (uiReadonly) return { readonly: true, required: !!c.required }; const uiReadonlyWhen = (c as { uiReadonlyWhen?: FieldRulePredicate }).uiReadonlyWhen; if (!c.readonlyWhen && !uiReadonlyWhen && !c.requiredWhen) { return { readonly: false, required: !!c.required }; diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index c973810411c..536e9254057 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -209,6 +209,7 @@ const ar = { uploadInFlight: "انتظر حتى ينتهي الرفع قبل الحفظ.", clearedOnHide: "تم مسح ما لم يعد ينطبق على القيم الحالية: {{fields}}", visibleWhenFaulted: "تعذّر الإرسال: تعذّر تقييم قاعدة visibleWhen لـ {{fields}}. يجب إصلاح القاعدة قبل أن يصبح إرسال هذا النموذج ممكنًا.", + uiReadonlyWhenFaulted: "تعذّر الإرسال: تعذّر تقييم قاعدة uiReadonlyWhen لـ {{fields}}. يجب إصلاح القاعدة قبل أن يصبح إرسال هذا النموذج ممكنًا.", discardTitle: "تجاهل التغييرات؟", discardMessage: "لديك تغييرات غير محفوظة. إذا أغلقت هذا النموذج الآن، ستفقد تعديلاتك.", // objectui#4024 — the create/edit dialog's `sr-only` accessible diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index a320b24c533..0f60e7e107c 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -195,6 +195,7 @@ const de = { uploadInFlight: "Warten Sie, bis der Upload abgeschlossen ist, bevor Sie speichern.", clearedOnHide: "Geleert, was für die aktuellen Werte nicht mehr gilt: {{fields}}", visibleWhenFaulted: "Absenden nicht möglich: Die visibleWhen-Regel von {{fields}} konnte nicht ausgewertet werden. Die Regel muss korrigiert werden, bevor dieses Formular abgesendet werden kann.", + uiReadonlyWhenFaulted: "Absenden nicht möglich: Die uiReadonlyWhen-Regel von {{fields}} konnte nicht ausgewertet werden. Die Regel muss korrigiert werden, bevor dieses Formular abgesendet werden kann.", discardTitle: "Änderungen verwerfen?", discardMessage: "Sie haben ungespeicherte Änderungen. Wenn Sie dieses Formular jetzt schließen, gehen Ihre Bearbeitungen verloren.", // objectui#4024 — the create/edit dialog's `sr-only` accessible diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index f4a855f7919..70ae3372c59 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -280,6 +280,7 @@ const en = { // `validation.formInvalidJoiner` — because the fix is to the metadata, not // to anything the person filling the form can type. visibleWhenFaulted: "Can't submit: the visibleWhen rule of {{fields}} could not be evaluated. The rule must be fixed before this form can be submitted.", + uiReadonlyWhenFaulted: "Can't submit: the uiReadonlyWhen rule of {{fields}} could not be evaluated. The rule must be fixed before this form can be submitted.", fieldRequired: 'This field is required', saveError: 'Failed to save', unsavedChanges: 'You have unsaved changes. Are you sure you want to leave?', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 59526248614..b8328d4eb7d 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -202,6 +202,7 @@ const es = { uploadInFlight: "Espere a que finalice la carga antes de guardar.", clearedOnHide: "Se borró lo que ya no corresponde a los valores actuales: {{fields}}", visibleWhenFaulted: "No se puede enviar: no se pudo evaluar la regla visibleWhen de {{fields}}. Hay que corregir la regla antes de poder enviar este formulario.", + uiReadonlyWhenFaulted: "No se puede enviar: no se pudo evaluar la regla uiReadonlyWhen de {{fields}}. Hay que corregir la regla antes de poder enviar este formulario.", discardTitle: "¿Descartar los cambios?", discardMessage: "Tiene cambios sin guardar. Si cierra este formulario ahora, sus ediciones se perderán.", // objectui#4024 — the create/edit dialog's `sr-only` accessible diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index ec43ca6a53c..1952e71d141 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -197,6 +197,7 @@ const fr = { uploadInFlight: "Attendez la fin du téléversement avant de sauvegarder.", clearedOnHide: "Ce qui ne s'applique plus aux valeurs actuelles a été effacé : {{fields}}", visibleWhenFaulted: "Envoi impossible : la règle visibleWhen de {{fields}} n'a pas pu être évaluée. La règle doit être corrigée avant que ce formulaire puisse être envoyé.", + uiReadonlyWhenFaulted: "Envoi impossible : la règle uiReadonlyWhen de {{fields}} n'a pas pu être évaluée. La règle doit être corrigée avant que ce formulaire puisse être envoyé.", discardTitle: "Abandonner les modifications ?", discardMessage: "Vous avez des modifications non enregistrées. Si vous fermez ce formulaire maintenant, vos modifications seront perdues.", // objectui#4024 — the create/edit dialog's `sr-only` accessible diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 46dd0bc148e..15bb17f66e2 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -195,6 +195,7 @@ const ja = { uploadInFlight: "アップロードが完了してから保存してください。", clearedOnHide: "現在の値に該当しなくなった項目をクリアしました: {{fields}}", visibleWhenFaulted: "送信できません: {{fields}} の visibleWhen ルールを評価できませんでした。このフォームを送信するには、先にルールを修正する必要があります。", + uiReadonlyWhenFaulted: "送信できません: {{fields}} の uiReadonlyWhen ルールを評価できませんでした。このフォームを送信するには、先にルールを修正する必要があります。", discardTitle: "変更を破棄しますか?", discardMessage: "保存されていない変更があります。このままフォームを閉じると編集内容は失われます。", // objectui#4024 — the create/edit dialog's `sr-only` accessible diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index ba348a5feb5..48aaa82abce 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -195,6 +195,7 @@ const ko = { uploadInFlight: "업로드가 완료된 후에 저장하세요.", clearedOnHide: "현재 값에 더 이상 해당하지 않는 항목을 비웠습니다: {{fields}}", visibleWhenFaulted: "제출할 수 없습니다: {{fields}}의 visibleWhen 규칙을 평가할 수 없습니다. 이 양식을 제출하려면 먼저 규칙을 수정해야 합니다.", + uiReadonlyWhenFaulted: "제출할 수 없습니다: {{fields}}의 uiReadonlyWhen 규칙을 평가할 수 없습니다. 이 양식을 제출하려면 먼저 규칙을 수정해야 합니다.", discardTitle: "변경 내용을 버릴까요?", discardMessage: "저장하지 않은 변경 내용이 있습니다. 지금 이 양식을 닫으면 편집 내용이 사라집니다.", // objectui#4024 — the create/edit dialog's `sr-only` accessible diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 9c7252b9f10..ba994af03eb 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -197,6 +197,7 @@ const pt = { uploadInFlight: "Aguarde a conclusão do upload antes de salvar.", clearedOnHide: "O que não se aplica mais aos valores atuais foi limpo: {{fields}}", visibleWhenFaulted: "Não é possível enviar: não foi possível avaliar a regra visibleWhen de {{fields}}. A regra precisa ser corrigida antes que este formulário possa ser enviado.", + uiReadonlyWhenFaulted: "Não é possível enviar: não foi possível avaliar a regra uiReadonlyWhen de {{fields}}. A regra precisa ser corrigida antes que este formulário possa ser enviado.", discardTitle: "Descartar as alterações?", discardMessage: "Você tem alterações não salvas. Se fechar este formulário agora, suas edições serão perdidas.", // objectui#4024 — the create/edit dialog's `sr-only` accessible diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 0a489487cb7..321734195d9 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -202,6 +202,7 @@ const ru = { uploadInFlight: "Дождитесь завершения загрузки, прежде чем сохранять.", clearedOnHide: "Очищено то, что больше не применимо к текущим значениям: {{fields}}", visibleWhenFaulted: "Невозможно отправить: не удалось вычислить правило visibleWhen для {{fields}}. Правило нужно исправить, прежде чем эту форму можно будет отправить.", + uiReadonlyWhenFaulted: "Невозможно отправить: не удалось вычислить правило uiReadonlyWhen для {{fields}}. Правило нужно исправить, прежде чем эту форму можно будет отправить.", discardTitle: "Отменить изменения?", discardMessage: "Есть несохранённые изменения. Если закрыть форму сейчас, правки будут потеряны.", // objectui#4024 — the create/edit dialog's `sr-only` accessible diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index c77a5fc0c11..8b1694768cc 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -204,6 +204,7 @@ const zh = { uploadInFlight: '请等待上传完成后再保存。', clearedOnHide: '已清空不再适用于当前取值的字段:{{fields}}', visibleWhenFaulted: '无法提交:{{fields}} 的 visibleWhen 规则无法求值。需先修正该规则,才能提交此表单。', + uiReadonlyWhenFaulted: '无法提交:{{fields}} 的 uiReadonlyWhen 规则无法求值。需先修正该规则,才能提交此表单。', fieldRequired: '此字段为必填项', saveError: '保存失败', unsavedChanges: '您有未保存的更改,确定要离开吗?', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index a5bb6a6b512..6704b06d2ec 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -204,6 +204,7 @@ const zhHant = { uploadInFlight: '請等待上傳完成後再儲存。', clearedOnHide: '已清空不再適用於當前取值的欄位:{{fields}}', visibleWhenFaulted: '無法提交:{{fields}} 的 visibleWhen 規則無法求值。需先修正該規則,才能提交此表單。', + uiReadonlyWhenFaulted: '無法提交:{{fields}} 的 uiReadonlyWhen 規則無法求值。需先修正該規則,才能提交此表單。', fieldRequired: '此欄位為必填項', saveError: '儲存失敗', unsavedChanges: '您有未儲存的更改,確定要離開嗎?', diff --git a/ui/packages/plugin-calendar/src/ObjectCalendar.tsx b/ui/packages/plugin-calendar/src/ObjectCalendar.tsx index 91fe779972e..575a3da4901 100644 --- a/ui/packages/plugin-calendar/src/ObjectCalendar.tsx +++ b/ui/packages/plugin-calendar/src/ObjectCalendar.tsx @@ -50,6 +50,7 @@ import { useFilterScope, useResolvedFilter, classifyLoadError, + usePredicateScope, } from '@object-ui/react'; import { RECORD_OVERLAY_DEFAULT_WIDTH, @@ -1308,6 +1309,8 @@ export const ObjectCalendar: React.FC = ({ // before the early returns for `loading` / `error` / `!calendarConfig`, // otherwise React detects a hook-order change when those conditions // flip across re-renders (e.g. tab switching between board → calendar). + // The host's predicate scope, as the edit dialog binds it (objectstack#36806). + const predicateScope = usePredicateScope(); const handleEventDropDefault = useCallback(async (record: any, newStart: Date, newEnd?: Date) => { if (!calendarConfig) return; const { startDateField, endDateField } = calendarConfig; @@ -1333,8 +1336,8 @@ export const ObjectCalendar: React.FC = ({ // array identity puts the event back where the record has it. const lockDefs = objectSchema?.fields as Record | undefined> | undefined; if ( - fieldReadOnlyByHand(lockDefs?.[startDateField], record) || - (writesEnd && fieldReadOnlyByHand(lockDefs?.[endDateField as string], record)) + fieldReadOnlyByHand(lockDefs?.[startDateField], record, { scope: predicateScope }) || + (writesEnd && fieldReadOnlyByHand(lockDefs?.[endDateField as string], record, { scope: predicateScope })) ) { setData((prev) => prev.slice()); return; @@ -1411,7 +1414,7 @@ export const ObjectCalendar: React.FC = ({ }) : tt('form.recordNotFoundOrHidden', "This record doesn't exist, or you don't have access to it."); } - }, [calendarConfig, schema.objectName, dataSource, data, tt, t, labels, objectSchema]); + }, [calendarConfig, schema.objectName, dataSource, data, tt, t, labels, objectSchema, predicateScope]); // Quick-create state: clicking an empty day cell opens a small dialog // pre-filled with that date. On submit, dataSource.create() inserts a diff --git a/ui/packages/plugin-detail/src/DetailSection.tsx b/ui/packages/plugin-detail/src/DetailSection.tsx index 99f060eee12..ee29edbf453 100644 --- a/ui/packages/plugin-detail/src/DetailSection.tsx +++ b/ui/packages/plugin-detail/src/DetailSection.tsx @@ -651,7 +651,7 @@ export const DetailSection: React.FC = ({ // The object field's lock goes through the one hand-lock verdict — `readonly`, // `readonlyWhen`, `uiReadonly`, `uiReadonlyWhen` over this record // (`fieldReadOnlyByHand`, `@object-ui/core`) — never `readonly` alone. - const isReadonly = field.readonly === true || fieldReadOnlyByHand(objectDefField, data); + const isReadonly = field.readonly === true || fieldReadOnlyByHand(objectDefField, data, { scope: predicateScope }); const isSystemField = NON_EDITABLE_SYSTEM_FIELDS.has(field.name); // Types the fields package excludes from in-place editing — the SAME // alias-aware contract the grid consults, not a second list (objectui#4221). diff --git a/ui/packages/plugin-detail/src/HeaderHighlight.tsx b/ui/packages/plugin-detail/src/HeaderHighlight.tsx index f46587e879d..b05eb8b19b0 100644 --- a/ui/packages/plugin-detail/src/HeaderHighlight.tsx +++ b/ui/packages/plugin-detail/src/HeaderHighlight.tsx @@ -226,7 +226,7 @@ export const HeaderHighlight: React.FC = ({ // The object field's lock is the one hand-lock verdict over this // record (`fieldReadOnlyByHand`), as the details body reads it. const isReadonly = - field.readonly === true || fieldReadOnlyByHand(objectDefField, data); + field.readonly === true || fieldReadOnlyByHand(objectDefField, data, { scope: predicateScope }); const isSystem = NON_EDITABLE_SYSTEM_FIELDS.has(field.name); // Same shared exclusion the details body and the grid consult, so a // credential chip never opens the plain text editor that would show diff --git a/ui/packages/plugin-detail/src/InlineEditSaveBar.tsx b/ui/packages/plugin-detail/src/InlineEditSaveBar.tsx index 9eb108db3eb..824cb5382d6 100644 --- a/ui/packages/plugin-detail/src/InlineEditSaveBar.tsx +++ b/ui/packages/plugin-detail/src/InlineEditSaveBar.tsx @@ -76,6 +76,7 @@ import { Button, cn } from '@object-ui/components'; import { Check, X, Loader2 } from 'lucide-react'; import { useInlineEdit, + usePredicateScope, useRecordContext, useSafeFieldLabel, extractFieldErrors, @@ -416,16 +417,18 @@ export const InlineEditSaveBar: React.FC = ({ // than the draft alone, which the server would refuse again. `null` for a // conflict of the plain Save, whose write is the draft. const conflictWriteRef = React.useRef | null>(null); + // The host's predicate scope, as the edit dialog binds it (objectstack#36806). + const predicateScope = usePredicateScope(); /** A field this reader may fill on this page: the question the inline editors ask. */ const fillable = React.useCallback( (name: string, def: Record) => // The one hand-lock verdict over this record (`fieldReadOnlyByHand`). - !fieldReadOnlyByHand(def, data) + !fieldReadOnlyByHand(def, data, { scope: predicateScope }) && !isComputedDetailField(undefined, def as never) && !NON_EDITABLE_SYSTEM_FIELDS.has(name) && !!objectName && resolveFieldAffordance('recordEdit', perms, objectName, name), - [objectName, perms, data], + [objectName, perms, data, predicateScope], ); /** diff --git a/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx b/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx index e5b59c69c30..9b1bd7b63b4 100644 --- a/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx +++ b/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx @@ -107,6 +107,7 @@ import { isExternalWriteRefusal, isPermissionError, useInlineEdit, + usePredicateScope, useRecordContext, useSafeFieldLabel, } from '@object-ui/react'; @@ -228,6 +229,9 @@ export function useStageChange( const rereadRecord = async () => { await (ctx?.reread ?? ctx?.refresh)?.(); }; const inline = useInlineEdit(); const perms = usePermissions(); + // The host's predicate scope (`current_user` and friends), as the form binds + // it, so a hand-lock predicate means the same here as in the edit dialog. + const predicateScope = usePredicateScope(); const { t } = useDetailTranslation(); const { fieldLabel, translateOptions } = useSafeFieldLabel(); const { language } = useObjectTranslation(); @@ -252,7 +256,7 @@ export function useStageChange( && !inline.editing // The one hand-lock verdict over the stored record (`fieldReadOnlyByHand`): // a status that moves only through actions (`uiReadonly`) offers no stage. - && !fieldReadOnlyByHand(fieldDef, ctx?.data as Record | undefined) + && !fieldReadOnlyByHand(fieldDef, ctx?.data as Record | undefined, { scope: predicateScope }) && !isComputedDetailField(undefined, fieldDef) && !NON_EDITABLE_SYSTEM_FIELDS.has(statusField) && resolveFieldAffordance('recordEdit', perms, objectName, statusField); @@ -267,7 +271,7 @@ export function useStageChange( // fill-in asks the same one). const fillable = (name: string, def: Record): boolean => name !== statusField - && !fieldReadOnlyByHand(def, record) + && !fieldReadOnlyByHand(def, record, { scope: predicateScope }) && !isComputedDetailField(undefined, def as FieldDef) && !NON_EDITABLE_SYSTEM_FIELDS.has(name) && !!objectName diff --git a/ui/packages/plugin-form/src/deriveMasterDetail.test.ts b/ui/packages/plugin-form/src/deriveMasterDetail.test.ts index ea7bd0c551b..568de1cc9f6 100644 --- a/ui/packages/plugin-form/src/deriveMasterDetail.test.ts +++ b/ui/packages/plugin-form/src/deriveMasterDetail.test.ts @@ -673,4 +673,27 @@ describe('line-item columns and the hand lock (#36806)', () => { const hydrated = hydrateColumns([{ name: 'qty' }], schema, { booleanLabel }); expect((hydrated[0] as { uiReadonlyWhen?: unknown }).uiReadonlyWhen).toBe("parent.status != 'draft'"); }); + + // REWORK S3(a): an AUTHORED column over a `uiReadonly` child field, typed + // or not, carries the lock — no server strip stands behind the hand lock. + it('an authored column over a uiReadonly child field carries the lock, typed or untyped', () => { + const schema = { + name: 'line', + fields: { + status: { type: 'text', label: 'Status', uiReadonly: true }, + qty: { type: 'number', label: 'Qty', uiReadonlyWhen: "record.status != 'draft'" }, + note: { type: 'text', label: 'Note' }, + }, + }; + const [untyped, typed, typedWhen, plain] = hydrateColumns( + [{ name: 'status' }, { name: 'status', type: 'text' }, { name: 'qty', type: 'number' }, { name: 'note' }], + schema, + { booleanLabel }, + ) as Array<{ uiReadonly?: boolean; uiReadonlyWhen?: unknown }>; + expect(untyped!.uiReadonly).toBe(true); + expect(typed!.uiReadonly).toBe(true); + expect(typedWhen!.uiReadonlyWhen).toBe("record.status != 'draft'"); + expect(plain!.uiReadonly).toBeUndefined(); + expect(plain!.uiReadonlyWhen).toBeUndefined(); + }); }); diff --git a/ui/packages/plugin-form/src/deriveMasterDetail.ts b/ui/packages/plugin-form/src/deriveMasterDetail.ts index 257a3687cd4..cd554b0b87d 100644 --- a/ui/packages/plugin-form/src/deriveMasterDetail.ts +++ b/ui/packages/plugin-form/src/deriveMasterDetail.ts @@ -415,7 +415,9 @@ export function hydrateColumns( return cols.map((col) => { if (col.type) { if (col.type === 'currency') reportCurrencyColumnScale(col, childSchema?.name, false); - return col; // explicit type — respect the author's choice + // explicit type — respect the author's choice, save the child field's + // hand lock, which no authored column may open (objectstack#36806) + return withHandLock(col, (fields as any)[col.name]); } const d = (fields as any)[col.name]; if (!d) return col; // unknown field — leave as-is (grid falls back to text) @@ -436,7 +438,7 @@ export function hydrateColumns( } if (type === 'file') applyFileColumnProps(next, d); if (next.readonlyWhen == null && d?.readonlyWhen) next.readonlyWhen = d.readonlyWhen; - if ((next as { uiReadonlyWhen?: unknown }).uiReadonlyWhen == null && d?.uiReadonlyWhen) (next as { uiReadonlyWhen?: unknown }).uiReadonlyWhen = d.uiReadonlyWhen; + Object.assign(next, withHandLock(next, d)); if (next.requiredWhen == null && d?.requiredWhen) { next.requiredWhen = d.requiredWhen; } @@ -450,6 +452,26 @@ export function hydrateColumns( }); } +/** + * The child FIELD's hand lock carried onto an authored line-item column + * (objectstack#36806): `uiReadonly: true` and `uiReadonlyWhen`, in memory only + * (never authored `inlineColumns` keys), read by `GridFieldWidget`'s per-row + * cell verdict. Derived columns never list a `uiReadonly` child field + * (`deriveInlineGridColumns` skips it); an AUTHORED column may name one, typed + * or not, and the lock must hold there too — no server strip stands behind it. + */ +function withHandLock(col: GridColumn, d: Record | undefined): GridColumn { + if (!d) return col; + const lockStatic = d.uiReadonly === true; + const lockWhen = d.uiReadonlyWhen; + if (!lockStatic && lockWhen == null) return col; + const next = { ...col } as GridColumn & { uiReadonly?: boolean; uiReadonlyWhen?: unknown }; + if (lockStatic) next.uiReadonly = true; + // The FIELD's predicate, never a column's own: the column may not open it. + if (lockWhen != null) next.uiReadonlyWhen = lockWhen; + return next; +} + /** * Field names for a child's full "row form" (the per-row expand editor) — the * form an inline master-detail collection opens when its author listed no diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 7ecadc56d66..334ba7098ec 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -1557,6 +1557,9 @@ export const ObjectGrid: React.FC = ({ latestCellHooks.current = { requiredPrompt, askStateMove, openReferencedRecord }; }); const opensReferencedRecords = !!openReferencedRecord; + // The host's predicate scope for the cell gate's lock predicates, as the + // edit dialog binds it (objectstack#36806). + const cellLockScope = usePredicateScope(); const gridCellSelection = useMemo((): GridCellSelection | null => (hostCellSelection ? { describeCell: (row, columnKey) => { @@ -1569,6 +1572,7 @@ export const ObjectGrid: React.FC = ({ const kind = cellReadOnlyKind({ fieldDef, row, + scope: cellLockScope, fieldWritable: !objectName || resolveFieldAffordance('listInlineEdit', perms, objectName, columnKey), gridEditable, objectEditable: objectInlineEditable, @@ -1633,7 +1637,7 @@ export const ObjectGrid: React.FC = ({ } : null), [ hostCellSelection, opensReferencedRecords, objectFields, objectSchema, objectName, perms, - gridEditable, objectInlineEditable, approvalLocks, recordVerdict, pageRecordIds, t, leaveHeldRows, + gridEditable, objectInlineEditable, approvalLocks, recordVerdict, pageRecordIds, t, leaveHeldRows, cellLockScope, ]); // objectstack#35685 — the state-machine confirm, the grid's next question // when the required-fields prompt has nothing to ask. diff --git a/ui/packages/plugin-grid/src/__tests__/lockOperandProjection-36806.test.tsx b/ui/packages/plugin-grid/src/__tests__/lockOperandProjection-36806.test.tsx new file mode 100644 index 00000000000..3cc65d2c22b --- /dev/null +++ b/ui/packages/plugin-grid/src/__tests__/lockOperandProjection-36806.test.tsx @@ -0,0 +1,140 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#36806 (REWORK S1) — a grid reads its lock predicates' operands. + * + * The cell gate judges `readonlyWhen` / `uiReadonlyWhen` over the ROW + * (`cellReadOnlyKind` → `fieldReadOnlyByHand`), and the row is the view's + * projection. A grid showing `subject` but not the `status` its hand lock + * reads fetched rows without `status`, so CEL faulted `No such key` on every + * row. The fetch now unions the shown columns' lock operands into `$select`, + * through the gates every other harvested field takes. + */ +import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; +import { render, cleanup } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; + +/** Stable stub identity: `ObjectGrid` carries `perms` in memo dep arrays. */ +const { permsStub, state } = vi.hoisted(() => { + const state: { denied: string[] } = { denied: [] }; + return { + state, + permsStub: { + isLoaded: true, + checkField: (_object: string, field: string, action: string) => + action === 'read' ? !state.denied.includes(field) : true, + check: () => ({ allowed: true }), + getFieldPermissions: () => [], + getRowFilter: () => undefined, + getObjectApiOperations: () => undefined, + roles: [], + userId: null, + systemPermissions: undefined, + hasCapabilities: () => true, + can: () => true, + cannot: () => false, + }, + }; +}); + +vi.mock('@object-ui/permissions', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, usePermissions: () => permsStub as any }; +}); + +import { ObjectGrid } from '../ObjectGrid'; +import { ActionProvider } from '@object-ui/react'; +import { registerAllFields } from '@object-ui/fields'; +import type { DataSource, ObjectGridSchema } from '@object-ui/types'; + +beforeAll(() => { + registerAllFields(); +}); + +const OBJECT = 'hlk_order'; + +const OBJECT_FIELDS = { + id: { type: 'text', label: 'Id' }, + subject: { type: 'text', label: 'Subject', uiReadonlyWhen: "record.status != 'draft'" }, + amount: { type: 'number', label: 'Amount', readonlyWhen: "record.stage == 'paid'" }, + note: { type: 'text', label: 'Note', uiReadonlyWhen: 'record.secret_flag == true' }, + status: { type: 'text', label: 'Status' }, + stage: { type: 'text', label: 'Stage' }, + secret_flag: { type: 'boolean', label: 'Secret flag' }, +}; + +const ROWS: Array> = [ + { id: 'o1', subject: 'Draft order', amount: 1, note: 'n', status: 'draft', stage: 'open', secret_flag: false }, +]; + +const makeDataSource = () => ({ + find: vi.fn(async (_object: string, params: Record) => { + const select = params.$select as string[] | undefined; + const data = ROWS.map((row) => + select ? Object.fromEntries(select.filter((k) => k in row).map((k) => [k, row[k]])) : { ...row }, + ); + return { data, total: data.length }; + }), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + getObjectSchema: vi.fn(async () => ({ name: OBJECT, fields: OBJECT_FIELDS })), +}); + +type Ds = ReturnType; + +const renderGrid = (ds: Ds, columns: string[]) => + render( + + + , + ); + +const lastSelect = (ds: Ds) => [...((ds.find.mock.calls.at(-1)?.[1]?.$select as string[] | undefined) ?? [])].sort(); + +beforeEach(() => { + vi.clearAllMocks(); + state.denied = ['secret_flag']; +}); +afterEach(() => cleanup()); + +describe('ObjectGrid — a shown column\'s lock operands are projected (objectstack#36806)', () => { + it('asks for the operand of a shown column\'s uiReadonlyWhen', async () => { + const ds = makeDataSource(); + renderGrid(ds, ['subject']); + await vi.waitFor(() => expect(ds.find).toHaveBeenCalled()); + expect(lastSelect(ds)).toEqual(['id', 'status', 'subject']); + }); + + it('asks for the operand of a shown column\'s readonlyWhen too', async () => { + const ds = makeDataSource(); + renderGrid(ds, ['amount']); + await vi.waitFor(() => expect(ds.find).toHaveBeenCalled()); + expect(lastSelect(ds)).toEqual(['amount', 'id', 'stage']); + }); + + it('does not request an operand the principal may not read (the cell then stays locked)', async () => { + const ds = makeDataSource(); + renderGrid(ds, ['note']); + await vi.waitFor(() => expect(ds.find).toHaveBeenCalled()); + expect(lastSelect(ds)).toEqual(['id', 'note']); + }); + + it('control: a column with no lock predicate harvests nothing', async () => { + const ds = makeDataSource(); + renderGrid(ds, ['status']); + await vi.waitFor(() => expect(ds.find).toHaveBeenCalled()); + expect(lastSelect(ds)).toEqual(['id', 'status']); + }); +}); diff --git a/ui/packages/plugin-grid/src/objectGridCellFacts.handLock-36806.test.ts b/ui/packages/plugin-grid/src/objectGridCellFacts.handLock-36806.test.ts index 714c9807ada..925e9c36700 100644 --- a/ui/packages/plugin-grid/src/objectGridCellFacts.handLock-36806.test.ts +++ b/ui/packages/plugin-grid/src/objectGridCellFacts.handLock-36806.test.ts @@ -46,6 +46,21 @@ describe('grid hand lock (#36806)', () => { expect(cellReadOnlyKind({ ...OPEN, fieldDef, row: { status: 'draft' } })).toBeNull(); }); + // REWORK S1: a projected row without the operand cannot be judged, and no + // server judges the hand lock, so the cell locks rather than opens. + it('a row missing the uiReadonlyWhen operand is locked', () => { + const fieldDef = { type: 'text', uiReadonlyWhen: "record.status != 'draft'" }; + expect(cellReadOnlyKind({ ...OPEN, fieldDef, row: { name: 'projected' } })).toBe('readonly'); + }); + + // REWORK S1: the host scope reaches the cell gate. + it('judges a current_user predicate over the scope the grid passes', () => { + const fieldDef = { type: 'text', uiReadonlyWhen: 'current_user.id != record.owner' }; + const scope = { current_user: { id: 'u1' } }; + expect(cellReadOnlyKind({ ...OPEN, fieldDef, row: { owner: 'u1' }, scope })).toBeNull(); + expect(cellReadOnlyKind({ ...OPEN, fieldDef, row: { owner: 'u2' }, scope })).toBe('readonly'); + }); + it('controls: a plain column edits', () => { expect(fieldInlineReadOnlyKind({ type: 'text' })).toBeNull(); expect(cellReadOnlyKind({ ...OPEN, row: { status: 'approved' } })).toBeNull(); diff --git a/ui/packages/plugin-grid/src/objectGridCellFacts.ts b/ui/packages/plugin-grid/src/objectGridCellFacts.ts index 123ba33e889..c2ea864d1ec 100644 --- a/ui/packages/plugin-grid/src/objectGridCellFacts.ts +++ b/ui/packages/plugin-grid/src/objectGridCellFacts.ts @@ -53,6 +53,8 @@ export interface CellReadOnlyInputs { * half is read. */ row?: Record | null; + /** The host's predicate scope (`current_user` and friends), as the edit dialog binds it. */ + scope?: Record; /** May this reader write the field (`resolveFieldAffordance('listInlineEdit', …)`)? */ fieldWritable: boolean; /** The authored `editable` the grid was handed (the list page folds `userActions.editInline` into it). */ @@ -76,7 +78,7 @@ export function cellReadOnlyKind(inputs: CellReadOnlyInputs): CellReadOnlyKind | const fieldKind = fieldInlineReadOnlyKind(inputs.fieldDef); if (fieldKind) return fieldKind; // The conditional half of the one hand-lock verdict, over this row. - if (inputs.row != null && fieldReadOnlyByHand(inputs.fieldDef, inputs.row)) return 'readonly'; + if (inputs.row != null && fieldReadOnlyByHand(inputs.fieldDef, inputs.row, { scope: inputs.scope })) return 'readonly'; if (!inputs.fieldWritable) return 'noFieldPermission'; if (!inputs.canUpdate) return 'noPermission'; if (!inputs.objectEditable) return 'objectReadOnly'; diff --git a/ui/packages/plugin-grid/src/objectGridRowLoad.ts b/ui/packages/plugin-grid/src/objectGridRowLoad.ts index 190b528f4aa..b9d8732d45e 100644 --- a/ui/packages/plugin-grid/src/objectGridRowLoad.ts +++ b/ui/packages/plugin-grid/src/objectGridRowLoad.ts @@ -443,6 +443,24 @@ export function useObjectGridRowLoad({ .filter((f) => isProjectableField(f, declared as Record)) .filter((f) => passesProjectionGate(f)) : []; + // [objectstack#36806] A shown column's field-lock predicates' + // operands (`readonlyWhen`, `uiReadonlyWhen`). The cell gate judges + // them over the ROW (`cellReadOnlyKind` → `fieldReadOnlyByHand`), + // so a grid showing `amount` but not the `status` its lock reads + // fetched rows without it and CEL faulted `No such key` — open for + // `readonlyWhen` (the server drops the write), locked for the hand + // lock (nothing behind it judges one). Read them, so each row is + // judged as it is. The same two gates as the harvests above. + const lockOperandFields = declared + ? collectPredicateFieldRefs( + shownColumns + .map((entry) => (declared as Record)[columnIdentity(entry) ?? '']) + .flatMap((def) => [def?.readonlyWhen, def?.uiReadonlyWhen]) + .filter((pred) => pred != null), + ) + .filter((f) => isProjectableField(f, declared as Record)) + .filter((f) => passesProjectionGate(f)) + : []; // [objectui#13036] A shown `referenceVia` pointer column's TYPE // half. `recordPointerFace` resolves the record through // `resolveRecordPointer` (objectui#12608), which reads the sibling @@ -515,7 +533,7 @@ export function useObjectGridRowLoad({ : []; // A UNION, never an append: a grouping field that IS also a column // must not produce a duplicate `$select` entry. - const extraFields = [...predicateFields, ...groupingFields, ...concurrencyFields, ...rowColorFields, ...deadlineFields, ...referenceViaFields, ...dependsOnFields, ...nameFields, ...recordCurrencyFields]; + const extraFields = [...predicateFields, ...groupingFields, ...concurrencyFields, ...rowColorFields, ...deadlineFields, ...lockOperandFields, ...referenceViaFields, ...dependsOnFields, ...nameFields, ...recordCurrencyFields]; const withHarvestedFields = (list: any[]): any[] => { if (extraFields.length === 0) return list; const names = new Set(list.map((f: any) => columnIdentity(f))); diff --git a/ui/packages/plugin-kanban/src/ObjectKanban.tsx b/ui/packages/plugin-kanban/src/ObjectKanban.tsx index d930a93b8da..031e012747d 100644 --- a/ui/packages/plugin-kanban/src/ObjectKanban.tsx +++ b/ui/packages/plugin-kanban/src/ObjectKanban.tsx @@ -2174,7 +2174,7 @@ export const ObjectKanban: React.FC = ({ // hand lock `uiReadonlyWhen`): no write, and the card goes back — a fresh // array identity re-buckets the board from the unchanged rows. const laneDef = (objectDef?.fields as Record | undefined> | undefined)?.[groupBy]; - if (fieldReadOnlyByHand(laneDef, record, { fieldContext: `field '${groupBy}'` })) { + if (fieldReadOnlyByHand(laneDef, record, { fieldContext: `field '${groupBy}'`, scope: predicateScope })) { setFetchedData((prev) => prev.map((r) => r)); return { kind: 'refused', message: tt('grid.readOnlyReason.readonly', 'This field is read-only.') }; } @@ -2195,7 +2195,7 @@ export const ObjectKanban: React.FC = ({ return persistCardMove(cardId, fromColumnId, toColumnId); }, - [schema.groupBy, rawData, objectDef, persistCardMove, tt], + [schema.groupBy, rawData, objectDef, persistCardMove, tt, predicateScope], ); // Label + localized options for each prompted field, resolved with the same diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 36e5278a329..f069812bf85 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -4531,6 +4531,30 @@ export const ListView = React.forwardRef(({ .map((def) => def!.settledWhen), )) addSpeculative(f); + // [objectstack#36806] The field locks' operands (`readonlyWhen`, + // `uiReadonlyWhen`) of every field a person edits in place from + // this list: the shown grid columns, the kanban's lane field (a card + // drag writes it) and the calendar's start / end fields (an event + // drag writes them). Each surface judges the lock over the ROW + // (`fieldReadOnlyByHand`), so a row projected without the operand + // faulted `No such key`: open for `readonlyWhen` (the server drops + // the write), locked for the hand lock (nothing behind it judges + // one). Through `addSpeculative`, like every binding here: an + // operand the viewer may not read is never requested, and that + // field then stays locked by hand. + const lockDefs = objectDef?.fields as Record | undefined; + const editedInPlace = [ + ...cols, + (schema.kanban as { groupByField?: unknown } | undefined)?.groupByField, + (schema.calendar as { startDateField?: unknown } | undefined)?.startDateField, + (schema.calendar as { endDateField?: unknown } | undefined)?.endDateField, + ].filter((name): name is string => typeof name === 'string' && name.length > 0); + for (const f of collectPredicateFieldRefs( + editedInPlace + .flatMap((name) => [lockDefs?.[name]?.readonlyWhen, lockDefs?.[name]?.uiReadonlyWhen]) + .filter((pred) => pred != null), + )) addSpeculative(f); + // [objectui#13036] A shown `referenceVia` pointer column's TYPE // half. The grid draws such a column through `resolveRecordPointer` // (objectui#12608), which reads the sibling the field names off the diff --git a/ui/packages/plugin-list/src/__tests__/ListView.lockOperandSelect-36806.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.lockOperandSelect-36806.test.tsx new file mode 100644 index 00000000000..1f8f03d6ce9 --- /dev/null +++ b/ui/packages/plugin-list/src/__tests__/ListView.lockOperandSelect-36806.test.tsx @@ -0,0 +1,149 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#36806 (REWORK S1) — a list projects the field locks' operands of + * every field a person edits in place from it. + * + * Each surface judges `readonlyWhen` / `uiReadonlyWhen` over the ROW + * (`fieldReadOnlyByHand`): the grid cell, the kanban card drag (it writes the + * lane field) and the calendar event drag (it writes the start / end fields). + * `ListView` builds the `$select` those rows arrive through, and a list that + * did not show the predicate's operand fetched rows without it: CEL faulted + * `No such key`, and the hand lock (which fails closed) held the field locked + * on every row. The harvest sits beside the deadline arm + * (`ListView.deadlineSettledSelect-11815.test.tsx`). + * + * What is pinned: the operand is in `$select` for a shown grid column, the + * kanban lane field and the calendar date fields; CONTROL: an operand the + * viewer may not read is not requested (the FLS gate inside `addSpeculative`). + */ +import '@testing-library/jest-dom/vitest'; +import React from 'react'; +import { describe, it, expect, vi, beforeAll, afterAll, beforeEach, afterEach } from 'vitest'; +import { render, waitFor, cleanup } from '@testing-library/react'; + +const { holder, makePerms } = vi.hoisted(() => { + const makePerms = (isLoaded: boolean, denied: string[]) => ({ + isLoaded, + checkField: (_object: string, field: string, action: string) => + action === 'read' ? !denied.includes(field) : true, + check: () => ({ allowed: true }), + getFieldPermissions: () => [], + getRowFilter: () => undefined, + getObjectApiOperations: () => undefined, + roles: [], + userId: null, + systemPermissions: undefined, + hasCapabilities: () => true, + can: () => true, + cannot: () => false, + }); + return { holder: { current: makePerms(true, []) }, makePerms }; +}); + +vi.mock('@object-ui/permissions', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, usePermissions: () => holder.current as any }; +}); + +import { ListView } from '../ListView'; +import { SchemaRendererProvider } from '@object-ui/react'; +import { ComponentRegistry } from '@object-ui/core'; + +const OBJECT = 'hlk_order'; + +const objectDef = { + name: OBJECT, + label: 'Order', + fields: { + id: { name: 'id', type: 'text' }, + title: { name: 'title', type: 'text', label: 'Title' }, + status: { name: 'status', type: 'text', label: 'Status' }, + approved: { name: 'approved', type: 'boolean', label: 'Approved' }, + stage: { name: 'stage', type: 'select', label: 'Stage', options: [{ value: 'a', label: 'A' }], uiReadonlyWhen: "record.status != 'draft'" }, + amount: { name: 'amount', type: 'number', label: 'Amount', readonlyWhen: 'record.approved == true' }, + starts_on: { name: 'starts_on', type: 'date', label: 'Starts on', uiReadonlyWhen: "record.status == 'closed'" }, + ends_on: { name: 'ends_on', type: 'date', label: 'Ends on', uiReadonlyWhen: 'record.approved == true' }, + secret_flag: { name: 'secret_flag', type: 'boolean', label: 'Secret flag' }, + note: { name: 'note', type: 'text', label: 'Note', uiReadonlyWhen: 'record.secret_flag == true' }, + }, +}; + +const makeDataSource = () => + ({ + find: vi.fn(async () => ({ data: [], total: 0 })), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + getObjectSchema: vi.fn(async (name: string) => (name === OBJECT ? objectDef : null)), + }) as any; + +async function selectFor(extra: Record): Promise { + const dataSource = makeDataSource(); + const schema: any = { type: 'list-view', objectName: OBJECT, viewType: 'grid', userActions: { editInline: false }, ...extra }; + render( + + + , + ); + await waitFor(() => expect(dataSource.find).toHaveBeenCalled()); + return [...((dataSource.find.mock.calls.at(-1)?.[1]?.$select as string[] | undefined) ?? [])].sort(); +} + +const STUBBED = ['object-grid', 'object-kanban', 'object-calendar']; +const prev: Record = {}; +beforeAll(() => { + for (const type of STUBBED) { + prev[type] = ComponentRegistry.get(type); + ComponentRegistry.register(type, () =>
, { namespace: 'stub' } as never); + } +}); +afterAll(() => { + for (const type of STUBBED) { + if (prev[type]) ComponentRegistry.register(type, prev[type] as never); + else ComponentRegistry.unregister(type); + } +}); + +beforeEach(() => { + vi.clearAllMocks(); + holder.current = makePerms(true, ['secret_flag']); +}); +afterEach(() => cleanup()); + +describe('ListView — the field locks\' operands are projected (objectstack#36806)', () => { + it('a shown grid column: the uiReadonlyWhen and readonlyWhen operands', async () => { + expect(await selectFor({ columns: ['title', 'stage'] })).toEqual(['id', 'stage', 'status', 'title']); + expect(await selectFor({ columns: ['title', 'amount'] })).toEqual(['amount', 'approved', 'id', 'title']); + }); + + it('the kanban lane field\'s operand, though no column shows it', async () => { + const select = await selectFor({ viewType: 'kanban', columns: ['title'], kanban: { groupByField: 'stage' } }); + expect(select).toContain('status'); + expect(select).toContain('stage'); + }); + + it('the calendar start and end fields\' operands', async () => { + const select = await selectFor({ + viewType: 'calendar', + columns: ['title'], + calendar: { startDateField: 'starts_on', endDateField: 'ends_on' }, + }); + expect(select).toEqual(expect.arrayContaining(['approved', 'ends_on', 'starts_on', 'status'])); + }); + + it('CONTROL: an operand the viewer may not read is not requested', async () => { + expect(await selectFor({ columns: ['title', 'note'] })).toEqual(['id', 'note', 'title']); + }); + + it('CONTROL: a column with no lock predicate pulls nothing in', async () => { + expect(await selectFor({ columns: ['title', 'status'] })).toEqual(['id', 'status', 'title']); + }); +}); From 116e0426e9d1c8dfd9cbec1661c6fe32fe1ed3e5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:47:02 +0000 Subject: [PATCH 10/13] test(components): pay the react-runtime load at collection in the uiReadonlyWhen refusal pin check:test-source-alias: the layout renderers reach @object-ui/react-runtime through a dynamic import, so the test imports it at module top. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXSuJCALDHFWaV6Bv5 --- .../uiReadonlyWhen-fault-refuses-submit-36806.test.tsx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ui/packages/components/src/renderers/form/__tests__/uiReadonlyWhen-fault-refuses-submit-36806.test.tsx b/ui/packages/components/src/renderers/form/__tests__/uiReadonlyWhen-fault-refuses-submit-36806.test.tsx index ea5d65fe8bf..77a2c5658ad 100644 --- a/ui/packages/components/src/renderers/form/__tests__/uiReadonlyWhen-fault-refuses-submit-36806.test.tsx +++ b/ui/packages/components/src/renderers/form/__tests__/uiReadonlyWhen-fault-refuses-submit-36806.test.tsx @@ -23,6 +23,9 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react'; import { ComponentRegistry } from '@object-ui/core'; import { toast } from '../../../ui/sonner'; +// The layout renderers reach `@object-ui/react-runtime` through a dynamic import; +// pay that load during collection, not inside a clocked case (check:test-source-alias). +import '@object-ui/react-runtime'; // Registers the renderers at module scope (object-ui/no-dynamic-import-in-test-hook). import '../../../renderers'; From c07eb982d9b728494410456c74cd0c1553cfffa8 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 08:48:50 +0000 Subject: [PATCH 11/13] fix(metadata-core,fields,components): hand lock never opens for a denied viewer or locks a new line-item row Contract delta S5/S6 and N6: a new line-item row (no id) does not judge uiReadonlyWhen; the FLS scrub serves uiReadonly: true when it deletes a uiReadonlyWhen that reads a denied field; the form's hand-lock fault check short-circuits on readonlyWhen on both evaluation paths. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXSuJCALDHFWaV6Bv5 --- .../36806-field-ui-readonly-hand-lock.md | 4 +-- .../src/object-schema-fls-references.test.ts | 23 +++++++++++++++ .../src/object-schema-fls-references.ts | 26 +++++++++++++++-- ...lyWhen-fault-refuses-submit-36806.test.tsx | 12 ++++++++ .../components/src/renderers/form/form.tsx | 5 +++- .../widgets/GridField.handLock-36806.test.tsx | 29 +++++++++++++++++-- .../widgets/grid-field/GridFieldWidget.tsx | 8 ++++- ui/packages/plugin-list/src/ListView.tsx | 6 ++-- 8 files changed, 103 insertions(+), 10 deletions(-) diff --git a/.changeset/36806-field-ui-readonly-hand-lock.md b/.changeset/36806-field-ui-readonly-hand-lock.md index b7d0a330bfb..f75c4d00289 100644 --- a/.changeset/36806-field-ui-readonly-hand-lock.md +++ b/.changeset/36806-field-ui-readonly-hand-lock.md @@ -33,9 +33,9 @@ A status column that only moves through actions, or a field an integration fills | conditional | `readonlyWhen` | `uiReadonlyWhen` (CEL, the same scope as `readonlyWhen`) | - **`uiReadonly: true` / `uiReadonlyWhen`.** These console surfaces lock the field: the create and edit dialogs (the field is left off them and out of the payload they submit, so a create from the console lands on the field's `defaultValue`, and a `required` field therefore needs one), the record page's inline edit and stage path, the highlight-strip chip, grid inline edit and its multi-row save, kanban drag between columns grouped by the field, calendar drag, and the line-item grid (a `uiReadonly` child field is not a derived column, and an authored column over it is locked; a `uiReadonlyWhen` one locks its cell per row). The Gantt, the timesheet cell, the kanban swimlane drag and the in-app assistant do not read the keys yet. The engine never reads either key, so REST, import, declarative and script actions, and flows write the field, and the object's validations (a `state_machine`, for one) judge each write. -- **`uiReadonlyWhen` is judged on an existing record only** (the create dialog does not read it), over the host's predicate scope on every surface. Grids and list views fetch the operands of a shown or dragged field's lock predicates. A predicate that cannot be evaluated LOCKS the field (no server judges the hand lock), the edit dialog refuses to submit until it is fixed, and `os validate` checks it as it checks `readonlyWhen`. +- **`uiReadonlyWhen` is judged on an existing record only** (the create dialog does not read it, nor does a new line-item row), over the host's predicate scope on every surface. Grids and list views fetch the operands of a shown or dragged field's lock predicates. A predicate that cannot be evaluated LOCKS the field (no server judges the hand lock), the edit dialog refuses to submit until it is fixed, and `os validate` checks it as it checks `readonlyWhen`. - **Refused: `uiReadonly: true` beside `readonly: true`** (at `['uiReadonly']`, at every door that parses a field: `defineStack`, `os validate`, metadata save). Keep one: `readonly` when no client may write the field, `uiReadonly` when people at the console may not. `uiReadonlyWhen` beside `readonlyWhen` is accepted. - **Kanban: a `readonly` lane field no longer drags.** The board read no field lock before, so a card grouped by a `readonly` field could be dragged and its PATCH was silently stripped. The board now reads both locks. - **`@object-ui/core` exports the one verdict:** `fieldReadOnlyByHand(def, record?, context?)`, `fieldStaticallyReadOnlyByHand(def)`, `fieldHasConditionalHandLock(def)`. `resolveFieldRuleState` takes `uiReadonlyWhen` in its rules and `uiReadonly` in its statics. The import wizard's target mapping and the Studio/designer reads stay on the raw `readonly`. - **MCP `describe_object`** reports `uiReadonly` and `uiReadonlyWhen` as their own keys where set (never folded into `readonly`, which tells an agent to leave the field out of a write), on the HTTP and the stdio transport, and the tool description names them. -- **Censuses and Studio.** The FLS reference scrub classifies both keys (`@objectstack/metadata-core`: `uiReadonly` kept, `uiReadonlyWhen` an expression position). The Studio field form offers both rows beside Read-only and Read-only when, with their labels and help translated in every metadata-forms locale pack (`@objectstack/platform-objects`). +- **Censuses and Studio.** The FLS reference scrub classifies both keys (`@objectstack/metadata-core`: `uiReadonly` kept, `uiReadonlyWhen` an expression position). A caller denied a field the `uiReadonlyWhen` reads is served the field with `uiReadonly: true` in place of the predicate, so the lock never opens for them. The Studio field form offers both rows beside Read-only and Read-only when, with their labels and help translated in every metadata-forms locale pack (`@objectstack/platform-objects`). diff --git a/packages/metadata-core/src/object-schema-fls-references.test.ts b/packages/metadata-core/src/object-schema-fls-references.test.ts index 79d9a63bcb5..95924b30e6a 100644 --- a/packages/metadata-core/src/object-schema-fls-references.test.ts +++ b/packages/metadata-core/src/object-schema-fls-references.test.ts @@ -449,6 +449,29 @@ describe('[ADR-0106 D1] references to a denied field — inside a READABLE field expect(served.fields.title).not.toHaveProperty('inlineAmountField'); }); + // [#36806] No server judges the hand lock, and the console fails it closed: + // a predicate the caller cannot be served must not silently OPEN the field. + it('[#36806] serves a field locked by hand (`uiReadonly: true`) when its `uiReadonlyWhen` reads the denied field', () => { + const served = mask({ name: 'thing', fields: fieldsWith({ uiReadonlyWhen: 'record.secret_score > 0' }) }); + expect(served.fields.title).not.toHaveProperty('uiReadonlyWhen'); + expect(served.fields.title.uiReadonly).toBe(true); + }); + + it('[#36806] CONTROL: a `uiReadonlyWhen` over readable fields is served as written, with no static lock added', () => { + const served = mask({ name: 'thing', fields: fieldsWith({ uiReadonlyWhen: "record.id != ''" }) }); + expect(served.fields.title.uiReadonlyWhen).toBe("record.id != ''"); + expect(served.fields.title).not.toHaveProperty('uiReadonly'); + }); + + it('[#36806] CONTROL: a deleted `readonlyWhen` adds no hand lock (the server still judges it), nor does a field already `readonly`', () => { + const served = mask({ name: 'thing', fields: fieldsWith({ readonlyWhen: 'record.secret_score > 0' }) }); + expect(served.fields.title).not.toHaveProperty('readonlyWhen'); + expect(served.fields.title).not.toHaveProperty('uiReadonly'); + const locked = mask({ name: 'thing', fields: fieldsWith({ readonly: true, uiReadonlyWhen: 'record.secret_score > 0' }) }); + expect(locked.fields.title).not.toHaveProperty('uiReadonly'); + expect(locked.fields.title.readonly).toBe(true); + }); + it('drops a `lookupAutofill` pair whose target is denied, and keeps a source named on the referenced object', () => { // #27945 — `target` is a field of THIS object; `source` names a field of // the lookup's `reference` object, which this projection cannot judge. diff --git a/packages/metadata-core/src/object-schema-fls-references.ts b/packages/metadata-core/src/object-schema-fls-references.ts index 973edcfe25e..5890918d1e8 100644 --- a/packages/metadata-core/src/object-schema-fls-references.ts +++ b/packages/metadata-core/src/object-schema-fls-references.ts @@ -684,7 +684,9 @@ export const FIELD_REFERENCE_POSITIONS: Readonly> = { visibleWhen: expression, readonlyWhen: expression, // The hand lock's predicate (#36806), CEL over this object's record as - // `readonlyWhen` is. + // `readonlyWhen` is. Deleted when it mentions a denied field, and the + // field is then served `uiReadonly: true` (`readableField` below): no + // server judges the hand lock, so a deleted predicate must not open it. uiReadonlyWhen: expression, requiredWhen: expression, // The deadline's settle predicate (#22227), a `visibleWhen`-family CEL over @@ -705,7 +707,27 @@ export const FIELD_REFERENCE_POSITIONS: Readonly> = { ...PROTECTION_ENVELOPE, }; -const readableField = block(FIELD_REFERENCE_POSITIONS); +/** + * [#36806] A served field whose hand lock's predicate (`uiReadonlyWhen`) the + * caller may not evaluate — it mentions a field denied to them, so the table + * deletes it — is served LOCKED by hand instead (`uiReadonly: true`). Every + * other predicate the table deletes is still judged where it matters: the + * server evaluates `readonlyWhen` / `requiredWhen` on the write. Nothing + * judges the hand lock but the console, and the console fails it CLOSED, so + * deleting the predicate outright would silently OPEN the field for exactly the + * caller who cannot see why it is locked. A field already `readonly: true` is + * locked harder and gains nothing (the spec refuses the pair). + */ +const readableFieldTable = block(FIELD_REFERENCE_POSITIONS); +const readableField: Scrub = (value, denied, scope) => { + const out = readableFieldTable(value, denied, scope); + if (out === value || !out || typeof out !== 'object' || Array.isArray(out)) return out; + const before = value as Record; + const after = out as Record; + const lockDeleted = before.uiReadonlyWhen != null && !('uiReadonlyWhen' in after); + if (!lockDeleted || after.readonly === true || after.uiReadonly === true) return out; + return { ...after, uiReadonly: true }; +}; // ── Object level ────────────────────────────────────────────────────────────── diff --git a/ui/packages/components/src/renderers/form/__tests__/uiReadonlyWhen-fault-refuses-submit-36806.test.tsx b/ui/packages/components/src/renderers/form/__tests__/uiReadonlyWhen-fault-refuses-submit-36806.test.tsx index 77a2c5658ad..ce3adb74db4 100644 --- a/ui/packages/components/src/renderers/form/__tests__/uiReadonlyWhen-fault-refuses-submit-36806.test.tsx +++ b/ui/packages/components/src/renderers/form/__tests__/uiReadonlyWhen-fault-refuses-submit-36806.test.tsx @@ -100,6 +100,18 @@ describe('objectstack#36806 — a faulted uiReadonlyWhen refuses an edit form\'s expect(onSubmit).not.toHaveBeenCalled(); }); + // Contract delta N6: the same verdict on both evaluation paths — a field the + // server lock already holds never has its hand lock judged. + it('CONTROL — a field readonlyWhen already locks submits, with or without a visibleWhen', async () => { + for (const extra of [{}, { visibleWhen: 'true' }]) { + const onSubmit = vi.fn().mockResolvedValue(undefined); + const view = renderForm(base({ ...extra, readonlyWhen: "record.stage == 'open'", uiReadonlyWhen: BROKEN }), onSubmit, EDIT); + submit(); + await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1)); + view.unmount(); + } + }); + it('CONTROL — a uiReadonlyWhen that evaluates submits', async () => { const onSubmit = vi.fn().mockResolvedValue(undefined); renderForm(base({ uiReadonlyWhen: "record.stage == 'won'" }), onSubmit, EDIT); diff --git a/ui/packages/components/src/renderers/form/form.tsx b/ui/packages/components/src/renderers/form/form.tsx index acc9b9ce026..026b412074a 100644 --- a/ui/packages/components/src/renderers/form/form.tsx +++ b/ui/packages/components/src/renderers/form/form.tsx @@ -2268,8 +2268,11 @@ ComponentRegistry.register('form', const visibleOn = (f as any).visibleOn; const uiReadonlyWhen = isCreateForm ? undefined : (f as any).uiReadonlyWhen; if (uiReadonlyWhen != null && visibleWhen == null && f.type !== 'section-divider') { + // `readonlyWhen` rides along so the verdict short-circuits exactly as + // on the `visibleWhen` path below: a field the server lock already + // holds never has its hand lock judged, so it never blocks the save. const handLock = resolveFieldRuleState( - { uiReadonlyWhen }, + { readonlyWhen: (f as any).readonlyWhen, uiReadonlyWhen }, ruleRecord, { readonly: (f as any).readonly === true }, previousRecord, diff --git a/ui/packages/fields/src/widgets/GridField.handLock-36806.test.tsx b/ui/packages/fields/src/widgets/GridField.handLock-36806.test.tsx index b06d29f4556..9ab2345cb08 100644 --- a/ui/packages/fields/src/widgets/GridField.handLock-36806.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.handLock-36806.test.tsx @@ -30,7 +30,7 @@ describe('line-item grid hand lock (uiReadonlyWhen, #36806)', () => { it('locks the cell where the predicate is TRUE, per row and over the header', () => { render( {}} field={field} contextRecord={{ status: 'draft' }} @@ -45,7 +45,7 @@ describe('line-item grid hand lock (uiReadonlyWhen, #36806)', () => { it('locks every row when the header makes the predicate TRUE', () => { render( {}} field={field} contextRecord={{ status: 'approved' }} @@ -54,6 +54,31 @@ describe('line-item grid hand lock (uiReadonlyWhen, #36806)', () => { expect((screen.getAllByLabelText('Qty')[0] as HTMLInputElement).disabled).toBe(true); }); + // Contract delta S5: a create is not judged. A new line (no id) seeds only + // the grid's columns, so an operand that is not a column (`status`, a + // hand-locked child field) is absent and the fail-closed verdict would lock + // the cell on every new line. + it('does not judge uiReadonlyWhen on a new line, even when its operand is not a column', () => { + render( + {}} + field={{ + columns: [ + { name: 'product', label: 'Product', type: 'text' }, + { name: 'qty', label: 'Qty', type: 'number', uiReadonlyWhen: "record.status != 'draft'" }, + ], + } as any} + contextRecord={{}} + />, + ); + const qty = screen.getAllByLabelText('Qty') as HTMLInputElement[]; + // The stored line has no `status`: judged, faulted, locked (fail-closed). + expect(qty[0].disabled).toBe(true); + // The new line is not judged: editable. + expect(qty[1].disabled).toBe(false); + }); + // REWORK S3(a): an authored column over a `uiReadonly` child field carries // `uiReadonly: true` (plugin-form's `hydrateColumns`), and the cell reads it. it('a column carrying uiReadonly locks every row', () => { diff --git a/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx index 365c2afc0af..ed11c181957 100644 --- a/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx +++ b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx @@ -847,7 +847,13 @@ function GridFieldBody({ // row, no predicate to judge. const uiReadonly = (c as { uiReadonly?: boolean }).uiReadonly === true; if (uiReadonly) return { readonly: true, required: !!c.required }; - const uiReadonlyWhen = (c as { uiReadonlyWhen?: FieldRulePredicate }).uiReadonlyWhen; + // The hand lock's predicate judges a STORED line only (objectstack#36806, + // S5): a create is not judged, as the create dialog does not judge it, + // and a new line seeds only the grid's columns, so an operand that is not + // a column is an absent key the fail-closed verdict would lock on. + const uiReadonlyWhen = rowHasId(row) + ? (c as { uiReadonlyWhen?: FieldRulePredicate }).uiReadonlyWhen + : undefined; if (!c.readonlyWhen && !uiReadonlyWhen && !c.requiredWhen) { return { readonly: false, required: !!c.required }; } diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index f069812bf85..facb38ca45a 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -4540,8 +4540,10 @@ export const ListView = React.forwardRef(({ // faulted `No such key`: open for `readonlyWhen` (the server drops // the write), locked for the hand lock (nothing behind it judges // one). Through `addSpeculative`, like every binding here: an - // operand the viewer may not read is never requested, and that - // field then stays locked by hand. + // operand the viewer may not read is never requested — and that + // viewer is never served the predicate either: the definition's FLS + // scrub (`@objectstack/metadata-core`) deletes it and serves the + // field `uiReadonly: true` in its place, so it stays locked by hand. const lockDefs = objectDef?.fields as Record | undefined; const editedInPlace = [ ...cols, From 73681b489cbf4a09a20e1f94ad820323782d76f2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 09:26:02 +0000 Subject: [PATCH 12/13] chore(spec): regenerate object reference docs from the merged tree Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXSuJCALDHFWaV6Bv5 --- content/docs/references/data/object.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 264e9188671..b93aac552d6 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -203,7 +203,7 @@ const result = ApiMethod.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **list** | `{ pinned: string[]; more?: string[] }` | optional | The list scope's arrangement: actions of the object placed at `list_toolbar`, as drawn on the list page toolbar, and `$import` / `$export` as pinned buttons (not pinned, they stay in the page's own Import / Export menu). Omit to draw it as before. | -| **record** | `{ pinned: string[]; more?: string[] }` | optional | The record scope's arrangement: actions of the object placed at `record_header` or `record_more`, as drawn in the record header (record page, side preview, a phone's bottom bar). Omit to draw it as before. | +| **record** | `{ pinned: string[]; more?: string[] }` | optional | The record scope's arrangement: actions of the object placed at `record_header` or `record_more`, as drawn in the record header (record page, side preview, a phone's bottom bar). The same order leads the actions a grid row already offers, adding none: the row's ⋮ menu, its right-click menu and, on a list page, the selection bar's actions for one selected record (`pinned` names first, then `more` names, then the rest as before). The selection bar's buttons, at most three, are the first of that order; a row's own inline button does not change. Omit to draw each as before. | ### Nested Shape: `Object.userActions` @@ -744,7 +744,7 @@ const result = ApiMethod.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **list** | `{ pinned: string[]; more?: string[] }` | optional | The list scope's arrangement: actions of the object placed at `list_toolbar`, as drawn on the list page toolbar, and `$import` / `$export` as pinned buttons (not pinned, they stay in the page's own Import / Export menu). Omit to draw it as before. | -| **record** | `{ pinned: string[]; more?: string[] }` | optional | The record scope's arrangement: actions of the object placed at `record_header` or `record_more`, as drawn in the record header (record page, side preview, a phone's bottom bar). Omit to draw it as before. | +| **record** | `{ pinned: string[]; more?: string[] }` | optional | The record scope's arrangement: actions of the object placed at `record_header` or `record_more`, as drawn in the record header (record page, side preview, a phone's bottom bar). The same order leads the actions a grid row already offers, adding none: the row's ⋮ menu, its right-click menu and, on a list page, the selection bar's actions for one selected record (`pinned` names first, then `more` names, then the rest as before). The selection bar's buttons, at most three, are the first of that order; a row's own inline button does not change. Omit to draw each as before. | ### Nested Shape: `ObjectExtension.indexes[number]` From 30090e7316a4612f81f61b21c479f64cc3ab45b2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 11:01:59 +0000 Subject: [PATCH 13/13] test(dogfood): classify Field.uiReadonlyWhen in the expression conformance ledger Adds the cel-field-ui-readonly-when row: the console hand lock's predicate, evaluated by the hand-lock verdict in core/evaluator, fail-closed, UI only. A row of its own rather than a cel-field-rule cover, since its evaluator, its fail policy and its reach all differ. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXSuJCALDHFWaV6Bv5 --- .../dogfood/test/expression-conformance.ledger.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/packages/qa/dogfood/test/expression-conformance.ledger.ts b/packages/qa/dogfood/test/expression-conformance.ledger.ts index d565753eacd..07f89a4393e 100644 --- a/packages/qa/dogfood/test/expression-conformance.ledger.ts +++ b/packages/qa/dogfood/test/expression-conformance.ledger.ts @@ -230,6 +230,21 @@ export const EXPRESSION_SURFACE: ExprSurface[] = [ 'console (ui/) isDeadlineSettled (core/evaluator/deadlineSettled.ts) → evalRowPredicate → evalFieldPredicate (core/evaluator/fieldRules.ts) → @objectstack/formula celEngine (interpret), evaluated per record with the row bound as `record`, by every host that draws a date cell beside a row (grid, list, gallery, kanban, tree, the record detail sections and the approval snapshot); the verdict reaches the date / datetime cell as `deadlineSettled`, and a settled deadline paints no overdue wording and no overdue colour. A predicate that faults is logged once per predicate text (warnPredicateFailure, fieldRules.ts: no `warnOnError` is passed, so evalRowPredicate takes the evalFieldPredicate route) and answers NOT settled, so the deadline shows as it does without the key. Display only: nothing on the write path reads it. Judged at authoring by lint\'s field-rule pass (`validate-expressions.ts`) as `visibleWhen` is', covers: ['data/field.zod.ts:FieldSchema.settledWhen'], }, + { + // #36806 — the console hand lock's predicate. A row of its own rather than + // a fourth `cel-field-rule` cover, for the three reasons that row cannot + // speak for it: its evaluator is the console's hand-lock verdict, not the + // server rule-validator; a fault LOCKS the field (`fail-closed`), where + // that row is `fail-soft-log`; and no server reads it at all. The server + // lock is `readonlyWhen`, classified by `cel-field-rule`. + id: 'cel-field-ui-readonly-when', + summary: "a field's console hand lock (Field.uiReadonlyWhen) — UI only, fails closed", + dialect: 'cel', mode: 'interpret', state: 'enforced', failPolicy: 'fail-closed', + enforcement: + 'console (ui/) fieldReadOnlyByHand (core/evaluator/handLock.ts) → resolveFieldRuleState → evalFieldPredicate (core/evaluator/fieldRules.ts) → @objectstack/formula celEngine (interpret), evaluated per existing record with the row bound as `record` (plus `previous` and the host predicate scope), by the hosts that let a person edit a stored record: the edit dialog (which also refuses submit while the predicate faults), the record page (inline edit, highlight chip, save bar, stage path), grid cells and the line-item grid\'s stored rows, kanban drag and calendar drag. A create is not judged. A predicate that faults answers LOCKED (UI_READONLY_WHEN_FAULTED = true), because nothing behind it judges the write. UI only: no server evaluates it, and an API or automation write is not refused by it; the server lock is `readonlyWhen`. Judged at authoring by lint\'s field-rule pass (`validate-expressions.ts`) as `readonlyWhen` is', + covers: ['data/field.zod.ts:FieldSchema.uiReadonlyWhen'], + proof: 'ui/packages/core/src/evaluator/__tests__/handLock-36806.test.ts', + }, { // Split out of `cel-field-rule` by #15500. Both keys used to be spelled // `data/field.zod.ts:visibleWhen` and were therefore ONE ratchet key, so