Skip to content

Commit f66cd5a

Browse files
fix(app-shell): a parenthesised metadata form condition is evaluated as a group, so the field form offers percent and currency rows only where the type allows (#38262)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoTzqUn46dDyQAFJbmNA3TzE)_ Fixes #38070 repo:objectstack#3 · os-tesla · session_01L9qibyUSf2nKJWW6qBemSU Clause-②: no Metadata-protocol: none ## 维护者速读 - 管理员在 Studio 编辑字段时,「百分比显示」只在百分比字段和返回百分比的公式上出现,「货币」设置只在货币字段和返回货币的公式上出现;以前文本、货币、数字公式和空白字段上两组都会出现。 - 替每个打开字段编辑器的管理员解决:表单里带括号的显示条件以前一律被当成「显示」。 - 只改 Studio 表单读条件的方式,读不懂的条件照旧显示(按既有裁决);出问题最多是某行该出现没出现或反之,可以直接撤回。 - 无 ## What changes - `ui/packages/app-shell/src/views/metadata-admin/predicate.ts`: the Studio metadata form evaluator reads `(expr)` grouping, as CEL does. One branch in `evalExpr`: when the whole text is one balanced group, it evaluates the inside. The branch sits after the `||` / `&&` splits, which already leave a group whole, and before negation, so `!(a && b)` negates the group. The matching `)` is found quote-aware, by the same rule `splitTopLevel` uses, so a parenthesis inside a string literal is never counted. The header's supported-subset list gains the grouping line, and a new header section says why. - Unchanged on purpose: a predicate the evaluator still cannot read (an unbalanced parenthesis, a function call such as `size(data.x)`) still fails open with the objectstack#6936 warning. The card's ask to make it fail closed was cut in the claim's `Premise corrected` (comment 7237651782), quoting objectstack#6936 comment 5230638168 (Option C: an unresolvable path evaluates TRUE, with a development-mode warning) and ADR-0137 D3 ("A faulting `visibleWhen` shows the field."). - One existing pin changes its diagnostic, not its verdict. The §9.7 pin `('admin' in current_user.positions)` used to raise the objectstack#6936 unresolved-root warning, because the whole text was one operand with the root segment `('admin' in current_user`. With the group stripped first, the membership sits at depth 0 and raises the more precise objectui#6617 warning instead. The verdict stays `true`, and the §9.3 verdict table that pins it is untouched. objectui#6617 is diagnostic-only by its ruling, so this moves no ruled verdict. The header paragraph and the `carriesTopLevelIn` docblock that called this spelling undetected are rewritten to match. - `packages/spec/src/data/field.metadata-form.ts` is not edited: `percentDisplay` and `currencyConfig` keep their parenthesised CEL, which now evaluates as written. - Changeset: `@object-ui/app-shell` patch. ## Tests `ui/packages/app-shell/src/views/metadata-admin/predicate.test.ts`, a new top-level `describe` (§10) in the shared harness: - 10.1 grammar: a whole-text group, a nested group, `!(…)` over a comparison and over `&&`, `(a || b) && c` against the ungrouped `a || b && c`, a nested `a || (b && (c || d))`, an `in` set inside a group, and `(` / `)` inside a string literal. Each case is true and false on two drafts, with no warning. - 10.2 still unreadable, still fail-open: an unbalanced `(`, a group followed by `== true`, and `size(data.tags) > 0` each evaluate `true` and warn once. - 10.3 the two bundled rows, read from `fieldForm` in `@objectstack/spec/data`: a non-vacuity guard that both still spell a group, then `percentDisplay` and `currencyConfig` on seven drafts (table below), with no warning. - §9.7 pin rewritten as described above. | draft | `percentDisplay` before → after | `currencyConfig` before → after | |---|---|---| | text | true → **false** | true → **false** | | percent | true → true | true → **false** | | currency | true → **false** | true → true | | formula returning percent | true → true | true → **false** | | formula returning currency | true → **false** | true → true | | formula returning number | true → **false** | true → **false** | | empty draft | true → **false** | true → **false** | "Before" was measured on `origin/main` bd5407e with a copy of the evaluator. "After" is the §10.3 pin at this head. ## Acceptance notes - Seen while measuring, not in this card: some malformed shapes already evaluate `false` silently, without a throw or a warning. `data.type ==`, `data.type === 'text'`, `data.type > 3` and `data.type == 'text')` all behave this way, which does not match the header's "fail-open on any parse error". Recorded here only, per the claim. - Grouping is base CEL and the forms declare `dialect: 'cel'`, so this does not grow the interim evaluator into a second dialect (the claim's ruling on the route). ## Verification - Two-minute check: `pnpm --dir ui exec vitest run packages/app-shell/src/views/metadata-admin/predicate.test.ts`. Expect 173 passed, 24 of them grouping-dependent (§10 and the §9.7 pin). - Read first: the grouping branch in `evalExpr` and `matchingCloseParen` (`predicate.ts`), then §10.3 in `predicate.test.ts`. <details><summary>Local readings at 571bb00</summary> - `pnpm --dir ui exec vitest run` on `predicate.test.ts`, `SchemaForm.unresolvedPredicate.test.tsx`, `SchemaForm.optionVisibleWhen.test.tsx` and `SchemaForm.nestedAnyOfPredicate-9830.test.tsx`: Test Files 4 passed, Tests 198 passed. - Ablation through `scripts/ablation-replace.mjs`: the grouping branch's condition was prefixed with `false &&` (anchor 1 → 0, blob `1c645a78f74b` → `f5ef536be108`). `predicate.test.ts` then had 24 failed and 149 passed: all of 10.1, all seven 10.3 row cases, and the §9.7 pin. 10.2 and the guard stayed green, as expected. Restore: blob == HEAD (`1c645a78f74b`), `git diff HEAD` empty. - `eslint` on both source files: 0 errors, 1 warning (the existing `let cur: any` in `resolveValue`, not this diff). - `dispatch-gates --commands` derived 38 families, all run with exit codes recorded (`--ran`: 38 derived, 38 run, 0 NOT-MEASURED, 0 UNRUN). 37 exit 0. `pnpm --dir ui exec vitest run scripts/` exit 1: 7 failed and 5138 passed, in `check-doc-snippet-types.test.ts` (1) and `spec-symbol-ledger-plugin-detail-7265.test.ts` (6). Both read the built `@objectstack/spec` type declarations, and this worktree's spec `dist` comes from an `OS_SKIP_DTS=1` closure build. Neither test reads a file this diff changes, so treat that red as NOT MEASURED locally. CI's `Test UI` runs them on a clean build. `pnpm check:changeset-fixed` (run beyond the derivation) exit 0. - `@object-ui/app-shell` `type-check`: NOT MEASURED locally, because the `@object-ui/*` and spec closures carry no type declarations in this worktree (2606 errors, none in a changed file). CI's `Type Check UI` decides. - `overlap-check.mjs`: VERDICT clean exit 0 against origin/main bd5407e, and 0 open PR heads share a file. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibxvV3AxCdD5DiVBy6V)_ Co-authored-by: Claude <noreply@anthropic.com>
1 parent 73ec085 commit f66cd5a

3 files changed

Lines changed: 191 additions & 19 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
---
4+
5+
fix(app-shell): a parenthesised metadata form condition is evaluated as a group, so the field form offers its percent and currency rows only where the field type allows
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The Studio metadata form evaluator had no parenthesised grouping. A `visibleWhen` such as `data.type == 'percent' || (data.type == 'formula' && data.returnType == 'percent')` read its group as the path `(data.type`, failed to resolve it and showed the row on every draft. The field form's `percentDisplay` and `currencyConfig` rows were therefore offered on text, currency, number-returning formula and empty drafts. The evaluator now reads `(expr)` as CEL does, at any depth and under `!`. A condition it still cannot read (an unbalanced parenthesis, a function call) keeps failing open with its development warning, unchanged.

‎ui/packages/app-shell/src/views/metadata-admin/predicate.test.ts‎

Lines changed: 103 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
*/
2323

2424
import { describe, it, expect, beforeEach, afterEach, vi, type MockInstance } from 'vitest';
25-
import { objectForm } from '@objectstack/spec/data';
25+
import { objectForm, fieldForm } from '@objectstack/spec/data';
2626
import { evaluatePredicate, resetPredicateWarnings } from './predicate';
2727

2828
/**
@@ -843,17 +843,18 @@ describe('`in` with a path on the right is diagnosed, not resolved (objectui#661
843843
/* 9.7 — the spellings the reused walk cannot see fail to SILENCE, which is the
844844
pre-existing behaviour, never to a false claim about the author's code */
845845

846-
it('a parenthesised membership sits at depth > 0 and is not detected — silent, as before', () => {
847-
// The evaluator does not support parentheses at all: the whole text is a
848-
// path-shaped operand with an unbound root, so #6936 fires and the verdict
849-
// is fail-open true. Widening the walk to reach it would mean teaching the
850-
// detection about syntax the evaluator itself rejects.
846+
it('a parenthesised membership is now detected: the group is stripped first (objectstack#38070)', () => {
847+
// Before grouping was read, the whole text was one operand whose root
848+
// segment `('admin' in current_user` is not a scope name, so #6936 fired. The
849+
// VERDICT is the same either way (true, the §9.3 table pins it); only the
850+
// diagnostic moved, from the generic unresolved-root warning to the precise
851+
// membership one, which is diagnostic-only by the objectui#6617 ruling.
851852
expect(
852853
evaluatePredicate("('admin' in current_user.positions)", userScope({}, { positions: [] })),
853854
).toBe(true);
854855
expect(warn).toHaveBeenCalledTimes(1);
855-
expect(warnings()).toContain(SIG.unresolvedPath6936);
856-
expect(warnings()).not.toContain(SIG.inWithoutLiteralSet6617);
856+
expect(warnings()).toContain(SIG.inWithoutLiteralSet6617);
857+
expect(warnings()).not.toContain(SIG.unresolvedPath6936);
857858
});
858859

859860
it('a tab-separated `in` is not detected — a miss is silence, not a false claim', () => {
@@ -863,3 +864,97 @@ describe('`in` with a path on the right is diagnosed, not resolved (objectui#661
863864
expect(warnings()).not.toContain(SIG.inWithoutLiteralSet6617);
864865
});
865866
});
867+
868+
/* ── 10. parenthesised grouping is read, as CEL reads it (objectstack#38070) ── */
869+
870+
describe('a parenthesised group is evaluated, not read as a path (objectstack#38070)', () => {
871+
/* 10.1 — the grammar: whole-text groups, nested groups, negated groups */
872+
873+
it.each([
874+
["(data.type == 'text')", { type: 'text' }, true],
875+
["(data.type == 'text')", { type: 'number' }, false],
876+
["((data.type == 'text'))", { type: 'text' }, true],
877+
["((data.type == 'text'))", { type: 'number' }, false],
878+
["!(data.type == 'text')", { type: 'text' }, false],
879+
["!(data.type == 'text')", { type: 'number' }, true],
880+
["!(data.a && data.b)", { a: true, b: true }, false],
881+
["!(data.a && data.b)", { a: true, b: false }, true],
882+
// Grouping overrides the default `&&`-binds-tighter reading.
883+
["(data.a || data.b) && data.c", { a: true, b: false, c: false }, false],
884+
["data.a || data.b && data.c", { a: true, b: false, c: false }, true],
885+
["(data.a || data.b) && data.c", { a: false, b: true, c: true }, true],
886+
["data.a || (data.b && (data.c || data.d))", { a: false, b: true, c: false, d: true }, true],
887+
["data.a || (data.b && (data.c || data.d))", { a: false, b: true, c: false, d: false }, false],
888+
// An `in` set inside a group, and a parenthesis inside a string literal.
889+
["(data.type in ['a','b'])", { type: 'b' }, true],
890+
["(data.type in ['a','b'])", { type: 'z' }, false],
891+
["(data.label == 'a (b')", { label: 'a (b' }, true],
892+
["(data.label == 'a ) b')", { label: 'a ) b' }, true],
893+
])('%s over %j is %s', (expr, data, expected) => {
894+
expect(evaluatePredicate(expr as string, scope(data as Record<string, unknown>))).toBe(expected);
895+
expect(warn).not.toHaveBeenCalled();
896+
});
897+
898+
/* 10.2 — what is still unreadable still fails OPEN, with #6936's warning
899+
(objectstack#6936 ruling C; ADR-0137 D3: a faulting visibleWhen shows) */
900+
901+
it.each([
902+
"(data.type == 'text'",
903+
"(data.type == 'text') == true",
904+
'size(data.tags) > 0',
905+
])('%s still fails open and warns', (expr) => {
906+
expect(evaluatePredicate(expr, scope({ type: 'number', tags: [] }))).toBe(true);
907+
expect(warn).toHaveBeenCalledTimes(1);
908+
});
909+
910+
/* 10.3 — the two bundled field-form rows that carried the bug */
911+
912+
type Row = { field?: string; visibleWhen?: string | { source: string }; [k: string]: unknown };
913+
const findRow = (node: unknown, field: string): Row | undefined => {
914+
if (!node || typeof node !== 'object') return undefined;
915+
if (Array.isArray(node)) {
916+
for (const n of node) {
917+
const hit = findRow(n, field);
918+
if (hit) return hit;
919+
}
920+
return undefined;
921+
}
922+
const n = node as Row;
923+
if (n.field === field && n.visibleWhen) return n;
924+
for (const v of Object.values(n)) {
925+
const hit = findRow(v, field);
926+
if (hit) return hit;
927+
}
928+
return undefined;
929+
};
930+
const predicateOf = (field: string): string => {
931+
const row = findRow(fieldForm, field);
932+
const pred = row?.visibleWhen;
933+
const source = typeof pred === 'string' ? pred : pred?.source;
934+
if (!source) throw new Error(`fieldForm ships no visibleWhen row for ${field}`);
935+
return source;
936+
};
937+
938+
it('both rows still spell a parenthesised group (non-vacuity guard)', () => {
939+
// If a later edit drops the parentheses, the table below stops testing the
940+
// grouping branch; this keeps that change from passing silently.
941+
expect(predicateOf('percentDisplay')).toContain('(');
942+
expect(predicateOf('currencyConfig')).toContain('(');
943+
});
944+
945+
const DRAFTS: Array<[label: string, draft: Record<string, unknown>, percent: boolean, currency: boolean]> = [
946+
['text', { type: 'text' }, false, false],
947+
['percent', { type: 'percent' }, true, false],
948+
['currency', { type: 'currency' }, false, true],
949+
['formula returning percent', { type: 'formula', returnType: 'percent' }, true, false],
950+
['formula returning currency', { type: 'formula', returnType: 'currency' }, false, true],
951+
['formula returning number', { type: 'formula', returnType: 'number' }, false, false],
952+
['an empty draft', {}, false, false],
953+
];
954+
955+
it.each(DRAFTS)('on %s, each row is offered only where its type allows', (_label, draft, percent, currency) => {
956+
expect(evaluatePredicate(predicateOf('percentDisplay'), scope(draft))).toBe(percent);
957+
expect(evaluatePredicate(predicateOf('currencyConfig'), scope(draft))).toBe(currency);
958+
expect(warn).not.toHaveBeenCalled();
959+
});
960+
});

‎ui/packages/app-shell/src/views/metadata-admin/predicate.ts‎

Lines changed: 78 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
* - `path` truthy check
2020
* - `path && expr` conjunction
2121
* - `path || expr` disjunction
22+
* - `(expr)` grouping, any depth: `a || (b && c)`, `!(a && b)`
2223
*
2324
* Paths support dot notation: `data.type`, `data.config.kind`.
2425
*
@@ -209,16 +210,39 @@
209210
* either a membership test this evaluator cannot run, or text that is not a valid
210211
* predicate at all.
211212
*
212-
* Two spellings are deliberately NOT detected, and both fail to SILENCE (the
213-
* status quo) rather than to a false claim: a tab-separated `in`, and a
214-
* parenthesised `('admin' in current_user.positions)` where the operator sits at
215-
* `depth > 0`. Widening the walk to reach them would mean teaching it about
216-
* whitespace classes and parentheses the evaluator itself does not support —
217-
* growing the parser to improve a warning, which is the trade this file does not
218-
* make.
213+
* One spelling is deliberately NOT detected, and it fails to SILENCE (the
214+
* status quo) rather than to a false claim: a tab-separated `in`. Widening the
215+
* walk to reach it would mean teaching it about whitespace classes the evaluator
216+
* itself does not support — growing the parser to improve a warning, which is
217+
* the trade this file does not make. A parenthesised
218+
* `('admin' in current_user.positions)` IS detected: the grouping branch strips
219+
* the group before this tail runs, so the operator is back at depth 0 (see the
220+
* next section).
219221
*
220222
* This diagnostic retires with the file at ROADMAP M9, same as #4049's and
221223
* #4266's.
224+
*
225+
* ## Parenthesised grouping is read, as CEL reads it (objectstack#38070)
226+
*
227+
* These predicates declare `dialect: 'cel'`, and CEL groups with parentheses, so
228+
* an author has no reason to avoid them. This evaluator used to have no grouping
229+
* at all: the `||` / `&&` splitters already skipped text inside parentheses, but
230+
* nothing ever opened the group, so `data.type == 'percent' || (data.type ==
231+
* 'formula' && data.returnType == 'percent')` handed `(data.type` to
232+
* {@link resolveValue} as a path. Its root `(data` is not a scope name, so the
233+
* whole predicate took objectstack#6936's fail-open `true` — on EVERY row, and
234+
* the field form offered its percent and currency rows on every field type.
235+
*
236+
* The fix is one branch in `evalExpr`: when the whole text is one balanced group,
237+
* evaluate its inside. It sits after the `||` / `&&` splits (which leave a group
238+
* whole) and before negation (so `!(…)` negates the evaluated group). The group
239+
* match is quote-aware by the same rule as {@link splitTopLevel}.
240+
*
241+
* What does NOT change: a predicate this evaluator still cannot read — an
242+
* unbalanced `(`, a function call such as `size(data.x)` — still fails OPEN with
243+
* objectstack#6936's warning, as that ruling and ADR-0137 D3 (a faulting
244+
* `visibleWhen` shows the field) require. Grouping is base CEL, not a new
245+
* operator, so this does not grow the file into a second evaluator.
222246
*/
223247

224248
/**
@@ -535,10 +559,12 @@ const IN_OPERATOR = ' in ';
535559
* and send the author to un-write a spelling that is in fact fine; see the
536560
* header section on why this stays a detection rather than becoming a parser.
537561
*
538-
* Returns false for the two spellings the reused walk cannot see — a
539-
* tab-separated `in`, and one nested at `depth > 0` inside parentheses. Both are
540-
* misses, i.e. silence, which is the pre-existing behaviour; neither is a false
541-
* statement about the author's code.
562+
* Returns false for a tab-separated `in`, the one spelling the reused walk
563+
* cannot see — a miss, i.e. silence, which is the pre-existing behaviour, never
564+
* a false statement about the author's code. A membership wrapped in its own
565+
* group reaches here with the group already stripped by `evalExpr`'s grouping
566+
* branch, so it sits at depth 0 and is seen; an `in` still at `depth > 0` here
567+
* belongs to text that is not one whole group, which stays a miss.
542568
*/
543569
function carriesTopLevelIn(expr: string): boolean {
544570
return splitTopLevel(expr, IN_OPERATOR).length > 1;
@@ -587,6 +613,15 @@ function evalExpr(
587613
if (andParts.length > 1) {
588614
return andParts.every((p) => evalExpr(p.trim(), ctx, source));
589615
}
616+
// Handle grouping: one parenthesised group spanning the WHOLE text. It runs
617+
// after the `||` / `&&` splits, which already skip anything inside a group
618+
// (`splitTopLevel` tracks depth), so `a || (b && c)` reaches here as `a` and
619+
// `(b && c)`, and `(a || b) && c` as `(a || b)` and `c`. It runs before
620+
// negation, so `!(a && b)` negates the evaluated group. See the header section
621+
// "Parenthesised grouping is read, as CEL reads it".
622+
if (expr.startsWith('(') && matchingCloseParen(expr) === expr.length - 1) {
623+
return evalExpr(expr.slice(1, -1).trim(), ctx, source);
624+
}
590625
// Handle negation
591626
if (expr.startsWith('!')) {
592627
return !evalExpr(expr.slice(1).trim(), ctx, source);
@@ -661,6 +696,38 @@ function splitTopLevel(expr: string, op: string): string[] {
661696
return out;
662697
}
663698

699+
/**
700+
* The index of the `)` that closes the `(` at index 0, or -1 when it is never
701+
* closed. Quote-aware by the same rule {@link splitTopLevel} uses (a quote
702+
* opens a run that only the same unescaped quote closes), so a parenthesis
703+
* inside a string literal (`data.label == 'a (b'`) is never counted.
704+
*
705+
* Only `(` / `)` count here, not `[` / `]`: the caller asks one question, "is
706+
* the whole text one group?", and a bracketed `in` set inside the group is
707+
* balanced on its own.
708+
*/
709+
function matchingCloseParen(expr: string): number {
710+
let depth = 0;
711+
let inStr: string | null = null;
712+
for (let i = 0; i < expr.length; i++) {
713+
const ch = expr[i];
714+
if (inStr) {
715+
if (ch === inStr && expr[i - 1] !== '\\') inStr = null;
716+
continue;
717+
}
718+
if (ch === "'" || ch === '"') {
719+
inStr = ch;
720+
continue;
721+
}
722+
if (ch === '(') depth++;
723+
else if (ch === ')') {
724+
depth--;
725+
if (depth === 0) return i;
726+
}
727+
}
728+
return -1;
729+
}
730+
664731
function resolveValue(
665732
path: string,
666733
ctx: PredicateCtx,

0 commit comments

Comments
 (0)