diff --git a/.changeset/36167-cel-list-equality-refused.md b/.changeset/36167-cel-list-equality-refused.md new file mode 100644 index 00000000000..8cfd2d7c90f --- /dev/null +++ b/.changeset/36167-cel-list-equality-refused.md @@ -0,0 +1,32 @@ +--- +'@objectstack/formula': minor +'@objectstack/lint': minor +'@objectstack/mcp': minor +'@objectstack/service-automation': minor +'@objectstack/spec': minor +'@objectstack/scenarios': minor +'@object-ui/app-shell': minor +--- + +fix(formula)!: `validateExpression` refuses `==` / `!=` between a list-valued field and a scalar, which answers a constant on every row + +Clause-②: no (narrowing) +Metadata-protocol: narrowed +Skills-docs: follow-up #36217 + + + +**BREAKING** accept-set narrowing, shipped as `minor`. CEL compares the whole list with the scalar, so `record.labels == 'frontend'` is `false` for `['frontend', 'qa']` and for `null` alike, and `record.labels != 'frontend'` is always `true`: a condition written that way never fires (or always does), with no fault and no log line. The shared validator accepted it. + +- **The refusal.** `validateExpression` refuses a `==` / `!=` between a read of a list-valued field on `record` / `previous` (`record.f`, `record['f']`, either operand order) — or, at a flattened (flow) condition, its bare name `f`, which the run binds to the trigger record's field, unless a flow variable holds the name or a node can bind names no reader sees — and a non-null string, number or boolean literal, as the new `list-equality` code (params `reference`, `operator`, `operand`, `answer`, `rewrite`), prescribing the null-guarded membership test. +- **Which fields are lists.** A `fieldTypes` entry of an inherently multi-value type (`multiselect`, `checkboxes`, `tags`), or a field named in the new optional `ExprSchemaHint.multiValueFields` — the fields a caller reads as multi-valued through `isMultiValueField` (`@objectstack/spec/data`), which is how a `select` / `radio` / `lookup` / `user` / `file` / `image` field declared `multiple: true` becomes a list here. Absent, such a field is not judged, as before. +- **Who fills it.** The publish lint (`os validate` / `os build`, every CEL site that types the object's fields), the MCP `validate_expression` tool (read off the served definition, `McpDataBridge.servedObjectDefinitionOf`, at the validation / formula / flow-condition sites; a bridge without it answers as before), `registerFlow`'s schema pass (`parseObjectFieldSchema` returns `multiValueFields`; logged, never thrown, like every finding of that pass), the scenario scorer, and Studio's object draft check (field rules, formulas, validation rules; `CelSchemaHint.multiValueFields`). +- **Still accepted.** `S == null` / `S != null` (either side), `'a' in S`, a list compared with a list literal or with another list field, and a comparison whose other operand is not a literal. + +FROM → TO: + +- `record.labels == 'frontend'` → `record.labels != null && 'frontend' in record.labels` +- `record.labels != 'frontend'` → `record.labels == null || !('frontend' in record.labels)` +- at a flow condition, `labels == 'frontend'` → `labels != null && 'frontend' in labels` + +One-line fix: test membership with `in`, null-guarded (`'a' in null` faults); compare the list with `null` to test whether it is set. diff --git a/packages/formula/src/cel-engine.ts b/packages/formula/src/cel-engine.ts index 90164a8221c..da32d0f394e 100644 --- a/packages/formula/src/cel-engine.ts +++ b/packages/formula/src/cel-engine.ts @@ -1060,7 +1060,7 @@ function comparesDateTextAgainstUndeclared(source: string, env: Environment): bo // A macro (`list.exists(x, …)`): `rcall` [name, receiver, [variable, …body]]. const args = v.args; if (v.op === 'rcall' && Array.isArray(args) && args.length === 3 && Array.isArray(args[2]) - && MACRO_NAMES.has(String(args[0]))) { + && COMPREHENSION_MACRO_NAMES.has(String(args[0]))) { const [variable, ...body] = args[2] as unknown[]; const name = isCelNode(variable) && variable.op === 'id' && typeof variable.args === 'string' ? variable.args : null; visit(args[1], bound); @@ -1073,8 +1073,12 @@ function comparesDateTextAgainstUndeclared(source: string, env: Environment): bo return found; } -/** The CEL macros that bind a variable over a list's items (`list.exists(x, …)`). */ -const MACRO_NAMES: ReadonlySet = new Set(['all', 'exists', 'exists_one', 'map', 'filter']); +/** + * The CEL macros that bind a variable over a list's items (`list.exists(x, …)`). + * Package-internal (not re-exported from the entry): `validate.ts`'s + * list-equality pass reads the same set, so a name a macro binds is read alike. + */ +export const COMPREHENSION_MACRO_NAMES: ReadonlySet = new Set(['all', 'exists', 'exists_one', 'map', 'filter']); /** * A typed environment for the soundness check. Each field carries a concrete diff --git a/packages/formula/src/expression-refusal-codes.test.ts b/packages/formula/src/expression-refusal-codes.test.ts index 2d4162c6431..715468e4bf8 100644 --- a/packages/formula/src/expression-refusal-codes.test.ts +++ b/packages/formula/src/expression-refusal-codes.test.ts @@ -840,6 +840,50 @@ const PINS: { readonly [C in ExpressionRefusalCode]: readonly [Pin, ...Pin "label() reads a select field's option label; read any other field directly (record.first).", }, ], + // [#36167] A list-valued field compared with a scalar answers a constant. + 'list-equality': [ + { + produce: () => + onlyError('predicate', "record.labels == 'frontend'", { + scope: 'record', + fields: ['labels'], + fieldTypes: { labels: 'multiselect' }, + }), + params: { + reference: 'record.labels', + operator: '==', + operand: '"frontend"', + answer: 'false', + rewrite: 'record.labels != null && "frontend" in record.labels', + }, + message: + 'list compared with a scalar — `record.labels` holds a list (a multi-value field), and `==` compares the whole ' + + 'list with `"frontend"`, so the expression answers `false` on every row whatever the list holds: the condition ' + + 'never changes. Test membership with `in`: write `record.labels != null && "frontend" in record.labels`. ' + + 'To test whether the list is set, compare it with `null`.', + }, + { + produce: () => + onlyError('predicate', "'u1' != previous.owners", { + scope: 'record', + fields: ['owners'], + fieldTypes: { owners: 'user' }, + multiValueFields: ['owners'], + }), + params: { + reference: 'previous.owners', + operator: '!=', + operand: '"u1"', + answer: 'true', + rewrite: 'previous.owners == null || !("u1" in previous.owners)', + }, + message: + 'list compared with a scalar — `previous.owners` holds a list (a multi-value field), and `!=` compares the whole ' + + 'list with `"u1"`, so the expression answers `true` on every row whatever the list holds: the condition ' + + 'never changes. Test membership with `in`: write `previous.owners == null || !("u1" in previous.owners)`. ' + + 'To test whether the list is set, compare it with `null`.', + }, + ], 'empty-expression': [ { produce: () => rootsRefusal(' '), @@ -926,6 +970,8 @@ const SWEEP_SOURCES: readonly string[] = [ 'has(status) && other == 1', 'daysBetween(record.a, record.b) > 3', "label(record.name) + label(record.status)", + // [#36167] A list-valued field compared with a scalar. + "record.tags == 'frontend'", ]; const SWEEP_INPUTS: readonly ExprInput[] = [ @@ -950,7 +996,7 @@ const SWEEP_SCHEMAS: readonly (ExprSchemaHint | undefined)[] = [ scope: 'record', objectName: 'deal', fields: ['amount', 'close_date', 'name', 'active', 'account', 'status'], - fieldTypes: { close_date: 'date', name: 'text', active: 'boolean', account: 'lookup' }, + fieldTypes: { close_date: 'date', name: 'text', active: 'boolean', account: 'lookup', tags: 'multiselect' }, roleCatalog: ['org_admin', 'sales'], optionFields: ['status'], }, diff --git a/packages/formula/src/expression-refusal.ts b/packages/formula/src/expression-refusal.ts index 9fa9d53f5cd..c9dc67400ff 100644 --- a/packages/formula/src/expression-refusal.ts +++ b/packages/formula/src/expression-refusal.ts @@ -324,6 +324,22 @@ export interface ExpressionRefusalParams { * fault sentence for that call. */ 'label-field-no-options': { readonly field: string }; + /** + * [#36167] `==` / `!=` between a list-valued field read (`ExprSchemaHint.multiValueFields`, + * or a `fieldTypes` type that is inherently multi) and a non-null scalar + * literal: CEL compares the whole list with the scalar, so the expression + * answers the same constant on every row. `reference` is the read as + * `.`, `operand` the literal as CEL prints it, `answer` the + * constant (`false` for `==`, `true` for `!=`), and `rewrite` the + * null-guarded membership test that replaces the comparison. + */ + 'list-equality': { + readonly reference: string; + readonly operator: '==' | '!='; + readonly operand: string; + readonly answer: 'false' | 'true'; + readonly rewrite: string; + }; /** `collectCelRootIdentifiers` was handed no expression. */ 'empty-expression': Readonly>; /** `collectCelRootIdentifiers` could not parse the source; `detail` is the parser's reason. */ @@ -395,6 +411,7 @@ const CODE_TABLE = { 'traversal-bare-and-traversed': true, 'traversal-multi-hop': true, 'label-field-no-options': true, + 'list-equality': true, 'empty-expression': true, 'cel-parse-failed': true, } as const satisfies Record; diff --git a/packages/formula/src/relationship-traversal.ts b/packages/formula/src/relationship-traversal.ts index 5283e085ba0..d9a3c0d55ce 100644 --- a/packages/formula/src/relationship-traversal.ts +++ b/packages/formula/src/relationship-traversal.ts @@ -217,6 +217,27 @@ export function readRootMembers(ast: CelAstNode, roots: readonly string[]): Root return reads; } +/** + * The member `node` ITSELF reads on one of `roots` — `record.tags`, + * `record.?tags`, `record['tags']`, `previous[?'tags']` — or `undefined` when + * `node` is anything else: a deeper read (`record.a.b`), a call, a literal, a + * computed key (`record[someVar]`). + * + * The same {@link asMember} spellings {@link readRootMembers} collects, asked + * of one node instead of gathered from a tree, for a check that judges an + * OPERAND rather than every read: `validateExpression`'s list-equality pass + * asks whether one side of a `==` is a field read, and gets the answer the + * field-existence pass would give for the same spelling. + */ +export function rootMemberOf(node: unknown, roots: readonly string[]): { readonly root: string; readonly field: string } | undefined { + const member = asMember(node); + if (!member) return undefined; + const receiver = member.receiver as { op?: unknown; args?: unknown } | null | undefined; + if (!receiver || typeof receiver !== 'object') return undefined; + const { op, args } = receiver; + return op === 'id' && typeof args === 'string' && roots.includes(args) ? { root: args, field: member.name } : undefined; +} + /** * Analyse one authored CEL source for the hops it takes through `root`. * diff --git a/packages/formula/src/validate-list-equality-36167.test.ts b/packages/formula/src/validate-list-equality-36167.test.ts new file mode 100644 index 00000000000..3f1fdd0aeed --- /dev/null +++ b/packages/formula/src/validate-list-equality-36167.test.ts @@ -0,0 +1,265 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36167] `validateExpression` refuses `==` / `!=` between a LIST-valued + * field and a non-null scalar literal (`list-equality`). + * + * CEL compares the whole list with the scalar, so `record.labels == 'frontend'` + * is `false` for `['frontend', 'qa']` and for `null` alike: the condition + * answers one constant on every row. A field is a list subject when its + * `fieldTypes` type is inherently multi (`multiselect` / `checkboxes` / + * `tags`) or `ExprSchemaHint.multiValueFields` names it (a `select` / + * `lookup` / `user` declared `multiple: true`). + * + * The first describe proves the premise on the evaluator itself, so the + * refusal below is about a real constant and not a guess. + */ + +import { describe, it, expect } from 'vitest'; + +import { celEngine } from './cel-engine'; +import { validateExpression, type ExprSchemaHint } from './validate'; + +const MULTI_TYPES = ['multiselect', 'checkboxes', 'tags'] as const; +const CAPABLE_TYPES = ['select', 'lookup', 'user'] as const; + +/** A record-scoped hint over one field `f` of `type`, optionally declared multi-valued. */ +function hintFor(type: string, multi = false, scope: 'record' | 'flattened' = 'record'): ExprSchemaHint { + return { + objectName: 'probe', + fields: ['f', 'name', 'g'], + fieldTypes: { f: type, name: 'text' }, + ...(multi ? { multiValueFields: ['f'] } : {}), + scope, + }; +} + +/** Every operand order and member spelling of `.f 'a'`. */ +function comparisons(root: string, op: '==' | '!='): readonly string[] { + return [ + `${root}.f ${op} 'a'`, + `'a' ${op} ${root}.f`, + `${root}['f'] ${op} 'a'`, + `'a' ${op} ${root}["f"]`, + `${root}.f ${op} 3`, + `${root}.f ${op} true`, + `${root}.name == 'x' && ${root}.f ${op} 'a'`, + ]; +} + +function refusalsOf(source: string, hint: ExprSchemaHint, role: 'predicate' | 'value' = 'predicate') { + return validateExpression(role, source, hint).errors; +} + +describe('the premise — on the evaluator, a list compared with a scalar is a constant', () => { + const run = (source: string, labels: unknown) => + celEngine.evaluate({ dialect: 'cel', source }, { record: { labels } }); + it.each([[['frontend', 'qa']], [['qa']], [[]], [null]])('labels = %j', (labels) => { + expect(run("record.labels == 'frontend'", labels)).toEqual({ ok: true, value: false }); + expect(run("record.labels != 'frontend'", labels)).toEqual({ ok: true, value: true }); + }); + it('CONTROL — the prescribed membership test answers per row', () => { + const src = "record.labels != null && 'frontend' in record.labels"; + expect(run(src, ['frontend', 'qa'])).toEqual({ ok: true, value: true }); + expect(run(src, ['qa'])).toEqual({ ok: true, value: false }); + expect(run(src, null)).toEqual({ ok: true, value: false }); + }); +}); + +describe('list-equality — refused on an inherently multi-value type', () => { + for (const type of MULTI_TYPES) { + for (const root of ['record', 'previous']) { + for (const op of ['==', '!='] as const) { + for (const source of comparisons(root, op)) { + it(`${type}: refuses ${source}`, () => { + const errors = refusalsOf(source, hintFor(type)); + expect(errors.map((e) => e.code)).toEqual(['list-equality']); + const [e] = errors; + expect(e.code === 'list-equality' && e.params.reference).toBe(`${root}.f`); + expect(e.code === 'list-equality' && e.params.operator).toBe(op); + expect(e.code === 'list-equality' && e.params.answer).toBe(op === '==' ? 'false' : 'true'); + expect(e.message).toContain(`\`${root}.f\``); + expect(e.message).toContain(' in '); + expect(e.message).toContain(op === '==' ? `in ${root}.f\`` : `!(`); + }); + } + } + } + } + + it('the optional spellings (`.?f`, `[?\'f\']`) do not compile against a scalar: invalid-cel alone, no second refusal', () => { + for (const source of ["record.?f == 'a'", "previous[?'f'] != 'a'"]) { + expect(refusalsOf(source, hintFor('tags')).map((e) => e.code)).toEqual(['invalid-cel']); + } + }); + + it('refuses in a flattened (flow) condition and in a formula value too', () => { + expect(refusalsOf("record.f == 'a'", hintFor('tags', false, 'flattened')).map((e) => e.code)).toEqual(['list-equality']); + expect(refusalsOf("record.f == 'a'", hintFor('tags'), 'value').map((e) => e.code)).toEqual(['list-equality']); + }); + + it('refuses each comparison once, in the order written', () => { + const errors = refusalsOf("record.f == 'a' || previous.f != 'b'", hintFor('multiselect')); + expect(errors.map((e) => e.code === 'list-equality' && [e.params.reference, e.params.operator])).toEqual([ + ['record.f', '=='], + ['previous.f', '!='], + ]); + }); +}); + +describe('list-equality — select / lookup / user follow multiValueFields', () => { + for (const type of CAPABLE_TYPES) { + for (const op of ['==', '!='] as const) { + it(`${type} declared multiple: refuses record.f ${op} 'a'`, () => { + const errors = refusalsOf(`record.f ${op} 'a'`, hintFor(type, true)); + expect(errors.map((e) => e.code)).toEqual(['list-equality']); + expect(errors[0].message).toContain('`record.f`'); + expect(errors[0].message).toMatch(/\bin record\.f/); + }); + it(`${type} not declared multiple: accepts record.f ${op} 'a' (absent key, as before)`, () => { + expect(validateExpression('predicate', `record.f ${op} 'a'`, hintFor(type)).ok).toBe(true); + }); + } + } + + it('multiValueFields alone (no fieldTypes) is enough', () => { + const r = validateExpression('predicate', "record.f == 'a'", { fields: ['f'], scope: 'record', multiValueFields: ['f'] }); + expect(r.errors.map((e) => e.code)).toEqual(['list-equality']); + }); +}); + +describe('list-equality — accepted shapes', () => { + const accepted = [ + 'record.f == null', + 'record.f != null', + 'null == record.f', + 'null != previous.f', + "'a' in record.f", + "record.f != null && 'a' in record.f", + "record.f == null || !('a' in record.f)", + "record.f == ['a', 'b']", + 'record.f == previous.f', + 'size(record.f) == 2', + "record.f[0] == 'a'", + 'record.f == record.g', + ]; + for (const source of accepted) { + it(`accepts ${source}`, () => { + const r = validateExpression('predicate', source, hintFor('multiselect')); + expect(r.errors.map((e) => e.code)).toEqual([]); + }); + } + + it('CONTROL — a scalar field compared with a scalar is accepted', () => { + for (const type of ['text', 'select', 'lookup', 'user', 'number']) { + for (const op of ['==', '!=']) { + expect(validateExpression('predicate', `record.f ${op} 'a'`, hintFor(type)).ok).toBe(true); + } + } + expect(validateExpression('predicate', "record.name == 'a'", hintFor('multiselect')).ok).toBe(true); + }); + + it('CONTROL — no hint, no verdict', () => { + expect(validateExpression('predicate', "record.f == 'a'").ok).toBe(true); + expect(validateExpression('predicate', "record.f == 'a'", { scope: 'record' }).ok).toBe(true); + }); +}); + +describe('list-equality — a bare name at a flattened (flow) site is the trigger record field', () => { + const listEquality = (source: string, hint: ExprSchemaHint) => + refusalsOf(source, hint).filter((e) => e.code === 'list-equality'); + + for (const [type, multi] of [['tags', false], ['multiselect', false], ['user', true], ['select', true]] as const) { + for (const source of ["f == 'a'", "'a' != f", 'f == 3', "name == 'x' && f != 'a'"]) { + it(`${type}${multi ? ' (multiple)' : ''}: refuses \`${source}\`, naming the bare field and the \`in\` rewrite`, () => { + const errors = listEquality(source, hintFor(type, multi, 'flattened')); + expect(errors).toHaveLength(1); + expect(errors[0].params).toMatchObject({ reference: 'f' }); + expect(errors[0].message).toContain('`f` holds a list'); + expect(errors[0].message).toMatch(/ in f\b/); + }); + } + } + + // The premise for a bare name is measured on the flow engine's own + // `evaluateCondition`, which flattens the record into the run's scope: + // `service-automation`'s `list-equality-advisory-36167.test.ts`. + + it('CONTROL — a bare name at a record-scoped site is no field: no list-equality', () => { + expect(listEquality("f == 'a'", hintFor('tags'))).toEqual([]); + }); + + it('CONTROL — a bare name a flow variable holds is not the field: no list-equality; record.f still is', () => { + const hint = { ...hintFor('tags', false, 'flattened'), flowVariables: ['f'] }; + expect(listEquality("f == 'a'", hint)).toEqual([]); + expect(listEquality("record.f == 'a'", hint).map((e) => e.params.reference)).toEqual(['record.f']); + }); + + it('CONTROL — where nodes can bind names no reader sees, a bare name gets no verdict; record.f still does', () => { + const hint = { ...hintFor('tags', false, 'flattened'), bareNamesUnproven: true }; + expect(listEquality("f == 'a'", hint)).toEqual([]); + expect(listEquality("record.f == 'a'", hint).map((e) => e.params.reference)).toEqual(['record.f']); + }); + + for (const source of ['f == null', 'null != f', "'a' in f", "f != null && 'a' in f", "f == ['a']", "name == 'a'"]) { + it(`CONTROL — accepts \`${source}\``, () => { + expect(listEquality(source, hintFor('tags', false, 'flattened'))).toEqual([]); + }); + } + + it('CONTROL — a select / user not declared multiple is not judged bare either', () => { + for (const type of ['select', 'user']) expect(listEquality("f == 'a'", hintFor(type, false, 'flattened'))).toEqual([]); + }); +}); + +describe('list-equality — a name a comprehension macro binds is an item of the list, not the field', () => { + /** `labels` / `items` are list fields by type, `owners` by `multiple`. */ + const hint = (scope: 'record' | 'flattened'): ExprSchemaHint => ({ + objectName: 'probe', + fields: ['items', 'labels', 'owners'], + fieldTypes: { items: 'tags', labels: 'multiselect', owners: 'user' }, + multiValueFields: ['owners'], + scope, + }); + const refusedReferences = (source: string, scope: 'record' | 'flattened') => + refusalsOf(source, hint(scope)).filter((e) => e.code === 'list-equality').map((e) => e.params.reference); + + it('the premise: the bound name holds one item, so the comparison answers per row', () => { + const run = (items: unknown) => + celEngine.evaluate({ dialect: 'cel', source: "record.items.exists(labels, labels == 'a')" }, { record: { items } }); + expect(run(['a', 'b'])).toEqual({ ok: true, value: true }); + expect(run(['b'])).toEqual({ ok: true, value: false }); + }); + + for (const source of [ + "record.items.exists(labels, labels == 'a')", + "record.items.all(owners, owners != 'a')", + "record.items.exists_one(labels, 'a' == labels)", + "record.items.filter(owners, owners == 'a').size() > 0", + "record.items.map(labels, labels == 'a').size() > 0", + "record.items.exists(x, record.items.exists(labels, labels == x))", + ]) { + it(`flattened: accepts \`${source}\``, () => { + expect(refusedReferences(source, 'flattened')).toEqual([]); + }); + } + + it('flattened: the same name read outside the macro is still the field, and refused', () => { + expect(refusedReferences("record.items.exists(labels, labels == 'a') && labels == 'b'", 'flattened')).toEqual(['labels']); + expect(refusedReferences("labels != 'b' || record.items.all(labels, labels != 'a')", 'flattened')).toEqual(['labels']); + }); + + it('flattened: a body reading a name the macro does not bind still judges it', () => { + expect(refusedReferences("record.items.exists(x, labels == 'a')", 'flattened')).toEqual(['labels']); + }); + + it('a record. read inside a macro body is still the field, at either scope', () => { + for (const scope of ['record', 'flattened'] as const) { + expect(refusedReferences("record.items.exists(labels, record.labels == 'a')", scope)).toEqual(['record.labels']); + } + }); + + it('record scope: a bound name named like a field is accepted (bare names are no field there)', () => { + expect(refusedReferences("record.items.exists(labels, labels == 'a')", 'record')).toEqual([]); + }); +}); diff --git a/packages/formula/src/validate.ts b/packages/formula/src/validate.ts index cc889bde3c9..b0692e1423e 100644 --- a/packages/formula/src/validate.ts +++ b/packages/formula/src/validate.ts @@ -28,12 +28,14 @@ import { RECORD_ROOT_READ_RE, parseCelToAst, parseCelToAstWithReason, + printCelAst, + COMPREHENSION_MACRO_NAMES, type CelAstNode, type FieldCelType, } from './cel-engine'; import { templateEngine } from './template-engine'; -import { findTraversalConflicts, readRootMembers, traversalsOf, type RootMemberRead } from './relationship-traversal'; -import { REFERENCE_VALUE_TYPES } from '@objectstack/spec/data'; +import { findTraversalConflicts, readRootMembers, rootMemberOf, traversalsOf, type RootMemberRead } from './relationship-traversal'; +import { MULTI_OPTION_TYPES, REFERENCE_VALUE_TYPES } from '@objectstack/spec/data'; // #13594 — the one reader of cel-js's `found no matching overload for '…'` // template. Both this module (which asks whether the name is ADVERTISED, to word // a hint) and `firstUnknownFunctionCall` (which asks whether the environment @@ -105,6 +107,30 @@ export interface ExprSchemaHint { * `'flattened'` one (#29959). */ fieldTypes?: Readonly>; + /** + * The fields whose stored value is a LIST: each field the caller reads + * through `isMultiValueField` (`@objectstack/spec/data`) and finds + * multi-valued — an inherently-multi option type (`multiselect`, + * `checkboxes`, `tags`) or a multi-capable type declared `multiple: true` + * (`select`, `radio`, `lookup`, `user`, `file`, `image`). Read the field's + * definition through that predicate, the one the record validator and the + * query engine shape the stored value with, so this list and the value + * agree. + * + * {@link fieldTypes} alone already marks the inherently-multi types; this + * key is what makes a `multiple: true` field a list here, since a field + * type does not say whether it was declared multiple. A field either names + * as multi-valued is a LIST SUBJECT, and a `==` / `!=` between a read of it + * (`record.` / `previous.`, in every member spelling the + * field-existence pass reads) and a non-null scalar literal is refused + * under `list-equality`: CEL compares the whole list with the scalar, so + * the expression answers the same constant on every row. ` == null` + * / `!= null` stays accepted. Absent ⇒ only {@link fieldTypes}' inherently + * multi types are list subjects: a `select` / `lookup` / `user` field + * declared `multiple: true` is then judged as it was before this key, not + * at all. + */ + multiValueFields?: readonly string[]; /** * Evaluation scope of the authoring site — determines whether a bare top-level * identifier is legal (#1928): @@ -1410,6 +1436,158 @@ function checkAttachedLeaf( )); } +/** + * The fields the hint names as list-valued — {@link ExprSchemaHint.multiValueFields}, + * plus every {@link ExprSchemaHint.fieldTypes} entry whose type is an + * inherently-multi option type (`MULTI_OPTION_TYPES`, the half of + * `isMultiValueField` a type alone answers). Empty when the hint names none. + */ +function listSubjectsOf(schema: ExprSchemaHint | undefined): ReadonlySet { + const out = new Set(schema?.multiValueFields ?? []); + for (const [name, type] of Object.entries(schema?.fieldTypes ?? {})) { + if (MULTI_OPTION_TYPES.has(type)) out.add(name); + } + return out; +} + +/** + * A scalar literal operand — a string, number or boolean CEL literal, never + * `null` and never a list or map — printed as CEL, or `undefined` for any + * other operand. Only a literal is judged: its value is known before + * evaluation, so a list compared with it is provably the same answer on every + * row. Another field, a variable or a call may hold a list there, so it gets + * no verdict (a missed catch, never a false refusal). + */ +function scalarLiteralOf(node: unknown): string | undefined { + if (!node || typeof node !== 'object') return undefined; + const { op, args } = node as { op?: unknown; args?: unknown }; + if (op !== 'value') return undefined; + if (typeof args !== 'string' && typeof args !== 'number' && typeof args !== 'bigint' && typeof args !== 'boolean') { + return undefined; + } + return printCelAst(node) ?? undefined; +} + +/** + * [#36167] `==` / `!=` between a LIST SUBJECT ({@link listSubjectsOf}) read + * on `record` / `previous` and a non-null scalar literal — one `list-equality` + * refusal per comparison, either operand order. + * + * CEL's `==` compares the whole list with the scalar: `['frontend', 'qa'] == + * 'frontend'` is `false`, and so is `null == 'frontend'`, so the expression + * answers `false` (for `!=`, `true`) on every row whatever the list holds — a + * condition that never fires, or always does, with no fault and no log line. + * The prescription is membership, in the null-guarded spelling the Studio + * condition builder writes: `'a' in null` faults, so `S != null && V in S` + * for `==` and `S == null || !(V in S)` for `!=`. + * + * Accepted, deliberately: `S == null` / `S != null` (either side), which test + * whether the list is set; a list compared with a list literal or with + * another list subject, which is a real whole-list comparison; and an operand + * that is not a literal ({@link scalarLiteralOf}). + * + * The subject is read through `rootMemberOf`, the field-existence pass's own + * member reader, so `record.f` and `record['f']` (and `previous.…`) are + * judged alike, and the refusal renders the read as `.`. The + * optional spellings `record.?f` / `record[?'f']` never reach this pass + * against a scalar: CEL types them as an optional, and the comparison is + * refused as `invalid-cel` first. At a `'flattened'` (flow) site a bare `f` + * is the trigger record's field too, as the type pass reads it, and is + * rendered bare — except a name a flow variable holds + * ({@link ExprSchemaHint.flowVariables}), any bare name in a flow whose nodes + * can bind names no reader sees ({@link ExprSchemaHint.bareNamesUnproven}), + * and, at any site, a name a comprehension macro binds (`list.exists(f, …)`, + * {@link COMPREHENSION_MACRO_NAMES}) inside that macro's body, where it holds + * an item of the list and not the field (nor is `record.f` the field where a + * macro binds `record`). + */ +function checkListEquality( + ast: () => CelAstNode | null, + source: string, + schema: ExprSchemaHint | undefined, + errors: ExprValidationError[], +): void { + const subjects = listSubjectsOf(schema); + if (subjects.size === 0) return; + // CEL has no comments: a source that spells neither operator holds no comparison. + if (!source.includes('==') && !source.includes('!=')) return; + const tree = ast(); + if (tree == null) return; + // At a flattened (flow) site a bare name is the trigger record's field, as + // the type pass reads it — unless a flow variable holds the name + // (`flowVariables`), or a node can bind names no reader sees + // (`bareNamesUnproven`): then it is not proven to hold the list, and gets + // no verdict. + const bareSubjects = schema?.scope === 'flattened' && !schema.bareNamesUnproven + ? new Set([...subjects].filter((name) => !(schema.flowVariables ?? []).includes(name))) + : undefined; + // `bound`: the names the enclosing comprehension macros bind here. + const subjectOf = (node: unknown, bound: ReadonlySet): { reference: string } | undefined => { + const read = rootMemberOf(node, FIELD_EXISTENCE_ROOTS); + if (read) { + return subjects.has(read.field) && !bound.has(read.root) ? { reference: `${read.root}.${read.field}` } : undefined; + } + const { op, args } = (node ?? {}) as { op?: unknown; args?: unknown }; + return op === 'id' && typeof args === 'string' && bareSubjects?.has(args) && !bound.has(args) + ? { reference: args } + : undefined; + }; + const walk = (node: unknown, bound: ReadonlySet): void => { + if (!node || typeof node !== 'object') return; + if (Array.isArray(node)) { + for (const child of node) walk(child, bound); + return; + } + const { op, args } = node as { op?: unknown; args?: unknown }; + // A comprehension macro (`list.exists(x, …)`): `rcall` [name, receiver, + // [variable, …body]]. The receiver is read outside the binding, the body + // inside it — the same reading the engine's date-text pass takes. + if ( + op === 'rcall' && Array.isArray(args) && args.length === 3 && Array.isArray(args[2]) + && COMPREHENSION_MACRO_NAMES.has(String(args[0])) + ) { + const [variable, ...body] = args[2] as unknown[]; + const { op: vop, args: name } = (variable ?? {}) as { op?: unknown; args?: unknown }; + walk(args[1], bound); + walk(body, vop === 'id' && typeof name === 'string' ? new Set([...bound, name]) : bound); + return; + } + if ((op === '==' || op === '!=') && Array.isArray(args) && args.length === 2) { + for (const side of [0, 1] as const) { + const read = subjectOf(args[side], bound); + const operand = read ? scalarLiteralOf(args[1 - side]) : undefined; + if (!read || operand === undefined) continue; + errors.push(listEqualityRefusal(source, read.reference, op, operand)); + break; + } + } + for (const value of Object.values(node as Record)) walk(value, bound); + }; + walk(tree, new Set()); +} + +/** The `list-equality` refusal for ` `. */ +function listEqualityRefusal( + source: string, + reference: string, + operator: '==' | '!=', + operand: string, +): ExprValidationError { + const answer = operator === '==' ? 'false' : 'true'; + const rewrite = operator === '==' + ? `${reference} != null && ${operand} in ${reference}` + : `${reference} == null || !(${operand} in ${reference})`; + return refusal( + 'list-equality', + { reference, operator, operand, answer, rewrite }, + source, + `list compared with a scalar — \`${reference}\` holds a list (a multi-value field), and \`${operator}\` ` + + `compares the whole list with \`${operand}\`, so the expression answers \`${answer}\` on every row ` + + `whatever the list holds: the condition never changes. Test membership with \`in\`: write ` + + `\`${rewrite}\`. To test whether the list is set, compare it with \`null\`.`, + ); +} + /** * Is `name` written as a NAMESPACE in `source` — `name.x`, `name?.x`, * `name['x']`, `name.fn(…)` — rather than as a bare value (`name == 'x'`)? @@ -1697,6 +1875,7 @@ export function validateExpression( if (issue) errors.push(issue); } else { checkFieldExistence(ast, source, schema, errors); + checkListEquality(ast, source, schema, errors); checkOptionLabelTargets(ast, source, schema, errors); checkRoleCatalog(source, schema, errors); if (schema?.scope === 'record') { diff --git a/packages/lint/src/validate-expressions.list-equality-36167.test.ts b/packages/lint/src/validate-expressions.list-equality-36167.test.ts new file mode 100644 index 00000000000..69cb781bed8 --- /dev/null +++ b/packages/lint/src/validate-expressions.list-equality-36167.test.ts @@ -0,0 +1,161 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36167] The publish lint hands the shared validator the object's + * list-valued fields (`ExprSchemaHint.multiValueFields`, read through + * `isMultiValueField`), so `==` / `!=` between such a field and a scalar is + * refused at every CEL site that types the object's fields — an action's + * `visible`, a validation rule, a formula — including a `user` field declared + * `multiple: true`, which its type alone does not mark as a list. + * + * Every fixture goes through `ObjectStackSchema.safeParse` first, so no case + * pins a branch an author cannot reach. + */ + +import { describe, it, expect } from 'vitest'; + +import { ObjectStackSchema } from '@objectstack/spec'; + +import { validateStackExpressions } from './validate-expressions.js'; + +const MANIFEST = { id: 'com.example.list-equality', name: 'list_equality_probe', version: '1.0.0', type: 'app' } as const; + +function specValid(stack: Record): Record { + const result = ObjectStackSchema.safeParse({ manifest: MANIFEST, ...stack }); + if (!result.success) { + throw new Error( + 'fixture is not spec-valid: ' + + result.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`).join('; '), + ); + } + return result.data as unknown as Record; +} + +const OPTIONS = [ + { label: 'Frontend', value: 'frontend' }, + { label: 'QA', value: 'qa' }, +]; + +const ticket = { + name: 'ticket_probe', + label: 'Ticket probe', + fields: { + name: { type: 'text', label: 'Name' }, + labels: { type: 'multiselect', label: 'Labels', options: OPTIONS }, + stage: { type: 'select', label: 'Stage', options: OPTIONS }, + watchers: { type: 'user', label: 'Watchers', multiple: true }, + owner: { type: 'user', label: 'Owner' }, + }, +}; + +/** The errors the lint reports for one action `visible` predicate on the probe object. */ +function visibleErrors(visible: string) { + return validateStackExpressions( + specValid({ + objects: [ticket], + actions: [{ name: 'probe_action', label: 'Probe', objectName: 'ticket_probe', type: 'script', target: 'fn', visible }], + }), + ).filter((i) => i.severity === 'error'); +} + +describe('publish lint — list-equality at a CEL site', () => { + it.each([ + ["record.labels == 'frontend'", 'record.labels', 'record.labels != null && "frontend" in record.labels'], + ["record.labels != 'frontend'", 'record.labels', 'record.labels == null || !("frontend" in record.labels)'], + ["'u1' == record.watchers", 'record.watchers', 'record.watchers != null && "u1" in record.watchers'], + ])('refuses %s, naming the field and the `in` rewrite', (source, reference, rewrite) => { + const errors = visibleErrors(source); + expect(errors).toHaveLength(1); + expect(errors[0].message).toContain(`\`${reference}\` holds a list`); + expect(errors[0].message).toContain(rewrite); + }); + + it.each([ + 'record.labels == null', + 'record.watchers != null', + "'frontend' in record.labels", + "record.stage == 'frontend'", + "record.owner == 'u1'", + "record.name != 'x'", + ])('accepts %s', (source) => { + expect(visibleErrors(source)).toEqual([]); + }); + + it('refuses at a validation rule and in a formula too', () => { + const issues = validateStackExpressions( + specValid({ + objects: [ + { + ...ticket, + fields: { + ...ticket.fields, + is_frontend: { type: 'formula', label: 'Is frontend', expression: "record.watchers == 'u1'" }, + }, + validations: [ + { + name: 'watcher_rule', + type: 'script', + severity: 'error', + message: 'm', + condition: "record.labels != 'frontend'", + }, + ], + }, + ], + }), + ).filter((i) => i.severity === 'error' && i.message.includes('holds a list')); + expect(issues.map((i) => i.source).sort()).toEqual(["record.labels != 'frontend'", "record.watchers == 'u1'"]); + }); + + // A record-triggered flow's condition reads the trigger record flattened: + // a bare `labels` is `record.labels`, as the type pass reads it. + function flowErrors(condition: string, variables?: Array>) { + return validateStackExpressions( + specValid({ + objects: [ticket], + flows: [ + { + name: 'ticket_flow', + label: 'Ticket flow', + type: 'autolaunched', + ...(variables ? { variables } : {}), + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { objectName: 'ticket_probe', triggerType: 'record-after-update', condition } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'end' }], + }, + ], + }), + ).filter((i) => i.severity === 'error' && i.message.includes('holds a list')); + } + + it.each([ + ["labels == 'frontend'", 'labels'], + ["'u1' != watchers", 'watchers'], + ["record.labels == 'frontend'", 'record.labels'], + ])('refuses the flow start condition %s, naming %s', (condition, reference) => { + const errors = flowErrors(condition); + expect(errors).toHaveLength(1); + expect(errors[0].message).toContain(`\`${reference}\` holds a list`); + expect(errors[0].message).toContain(` in ${reference}`); + }); + + it.each([ + "stage == 'frontend'", "owner == 'u1'", "'frontend' in labels", 'watchers != null', + // A comprehension variable named like a list field holds one item: per row. + "record.labels.exists(watchers, watchers == 'frontend')", + "record.labels.all(labels, labels != 'qa')", + ])( + 'CONTROL — accepts the flow start condition %s', + (condition) => { + expect(flowErrors(condition)).toEqual([]); + }, + ); + + it('CONTROL — a bare name a declared flow variable holds is not the field', () => { + const variables = [{ name: 'labels', type: 'text', isInput: true, isOutput: false }]; + expect(flowErrors("labels == 'frontend'", variables)).toEqual([]); + expect(flowErrors("record.labels == 'frontend'", variables)).toHaveLength(1); + }); +}); diff --git a/packages/lint/src/validate-expressions.test.ts b/packages/lint/src/validate-expressions.test.ts index 303dde576a5..7909672869b 100644 --- a/packages/lint/src/validate-expressions.test.ts +++ b/packages/lint/src/validate-expressions.test.ts @@ -4217,7 +4217,10 @@ const READ_SURFACES: Array<{ receiver: string; expected: string[]; declaredBy: s // `referenceTo` is absent — likewise. // [#29026] `summaryOperations` joined: a `count` / `sum` roll-up is // always valued for the null-guard gate, and its function is read below. - expected: ['defaultValue', 'options', 'reference', 'required', 'summaryOperations', 'type'], + // [#36167] `multiple` joined: with `type`, it says whether the field's + // value is a list (`isMultiValueField`), handed to the validator as + // `ExprSchemaHint.multiValueFields`. + expected: ['defaultValue', 'multiple', 'options', 'reference', 'required', 'summaryOperations', 'type'], declaredBy: 'FieldSchema', keys: () => Object.keys(FieldSchema.shape), }, @@ -4432,6 +4435,9 @@ describe('validateStackExpressions — reads only keys the spec declares (meta-t // the metadata reads, `options` and `picklist`, go through // `declaresOptionsOnceServed`. 'fieldList', 'declaredNames', + // [#36167] object name → its list-valued field names; its keys are Map + // methods (`get`), never metadata keys. + 'multiValueFieldIndex', // [#33494] The names the door's stored extensions add (a Set of field // names), read to keep the target's served copy from filling a tied // name back in. Its keys are Set methods (`add`, `has`), never metadata keys. diff --git a/packages/lint/src/validate-expressions.ts b/packages/lint/src/validate-expressions.ts index dc5f02f5372..43ceea1163c 100644 --- a/packages/lint/src/validate-expressions.ts +++ b/packages/lint/src/validate-expressions.ts @@ -138,6 +138,7 @@ import { EvaluatedExpressionInputSchema, EVALUATED_EXPRESSION_SOURCE_REQUIRED } import { injectedSystemColumnDefs, isInjectedColumnDefinition, + isMultiValueField, platformProvisionsStorage, referenceCarrierOf, referenceTargetOf, @@ -486,6 +487,30 @@ function buildFieldTypeIndex(objects: AnyRec[]): Map { + const idx = new Map(); + for (const obj of objects) { + const name = typeof obj.name === 'string' ? obj.name : undefined; + if (!name) continue; + const out: string[] = []; + for (const [fn, def] of fieldEntries(obj)) { + if (typeof def.type === 'string' && isMultiValueField({ type: def.type, multiple: def.multiple === true })) out.push(fn); + } + idx.set(name, out); + } + return idx; +} + /** The field list of an object, whichever of the two `fields` shapes it uses. */ function fieldEntries(obj: AnyRec): Array<[string, AnyRec]> { const fields = obj.fields; @@ -2644,6 +2669,7 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression const fieldIndex = buildFieldIndex(servedObjects); const attachedOnReadIndex = buildAttachedOnReadIndex(objects); const fieldTypeIndex = buildFieldTypeIndex(typedObjects); + const multiValueFieldIndex = buildMultiValueFieldIndex(typedObjects); const nullableIndex = buildNullableFieldIndex(typedObjects); // [#33435] The flow and hook condition sites also judge the injected // columns a stored row can hold `null` in, and a `beforeInsert` hook the two @@ -2990,12 +3016,15 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression // `record.` read at a `record` site; the bare name and its // `record.` / `previous.` read at a flattened one (#29959). const fieldTypes = objectName ? fieldTypeIndex.get(objectName) : undefined; + // [#36167] The list-valued fields, so a list compared with a scalar is refused. + const multiValueFields = objectName ? multiValueFieldIndex.get(objectName) : undefined; // Spread only when given, so every other site's hint is unchanged. const roots = extraRoots ? { roots: extraRoots } : {}; const res = validatorRunByCaller ? VALIDATOR_RUN_BY_CALLER : validateExpression('predicate', raw as string | { dialect?: string; source?: string }, objectName ? { objectName, fields, attachedOnRead, fieldTypes, scope, traversalHydration, ...roots, + ...(multiValueFields ? { multiValueFields } : {}), ...(faultOutcome ? { faultOutcome } : {}), ...(flowBare ? { flowVariables: flowBare.variables } : {}), ...(flowBare?.unproven ? { bareNamesUnproven: true } : {}), @@ -3890,6 +3919,7 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression objectName, fields: fieldIndex.get(objectName), fieldTypes: fieldTypeIndex.get(objectName), + multiValueFields: multiValueFieldIndex.get(objectName), scope: 'record', traversalHydration: true, optionFields, diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index f953c9e2c0e..b4d8fad45eb 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -52,6 +52,8 @@ import { AggregationNodeSchema, SEARCH_COMPANION_FIELD } from '@objectstack/spec // [#35138] ADR-0079's one reading of an object's name field // (`nameField ?? displayNameField ?? derived`), which names a lookup group. import { resolveDisplayField } from '@objectstack/spec/data'; +// [#36167] Which served fields hold a list, read as the publish gate reads them. +import { isMultiValueField } from '@objectstack/spec/data'; // [#23529] The catalogue's spelling of `PERMISSION_DENIED`, the code whose // `details` `errorResultFromThrown` withholds. Imported, never hand-spelled. import { StandardErrorCode, type ErrorCode } from '@objectstack/spec/api'; @@ -959,6 +961,24 @@ function servedFieldOf(fields: Record, name: unknown): Record) : undefined; } +/** + * [#36167] The fields of the served definition `def` that hold a list, read + * through `isMultiValueField` (`@objectstack/spec/data`), the predicate the + * publish gate reads them with, among the field names the tool judges with; + * `undefined` when there is no definition. + */ +function multiValueFieldsOfServed( + def: Record | null, + judged: readonly string[], +): string[] | undefined { + const map = fieldMapOf(def ?? undefined); + if (!map) return undefined; + return judged.filter((name) => { + const field = servedFieldOf(map, name); + return typeof field?.type === 'string' && isMultiValueField({ type: field.type, multiple: field.multiple === true }); + }); +} + /** * [#35138] The field types whose group value is ONE declared option, so the * groups have the order the author declared the options in. A `multiselect` @@ -2867,6 +2887,10 @@ interface GatePassContext { * or an object it does not serve, adds none; a target it does not serve is * not judged, as at the gate. * + * [#36167] The subject's definition is read once, by the handler, which also + * hands its list-valued fields to the shared validator; `subject` is that read + * (`null` when the bridge serves none). + * * [#33147] The field being authored resolves through the same served * definition, and nothing else: a field the caller is not served reads as * one the object does not declare, so the answer never says whether it @@ -2887,11 +2911,10 @@ async function gatePassFindings( site: AuthoredExpressionSite, objectName: string, expression: string, + subject: Record | null, context: GatePassContext, ): Promise<{ errors: GatePassFinding[]; warnings: GatePassFinding[] }> { - if (!bridge.servedObjectDefinitionOf) return NO_GATE_PASS_FINDINGS; - const subject = await bridge.servedObjectDefinitionOf(objectName); - if (!subject) return NO_GATE_PASS_FINDINGS; + if (!bridge.servedObjectDefinitionOf || !subject) return NO_GATE_PASS_FINDINGS; const { authoredExpressionHopTargets, judgeAuthoredSiteExpression } = await import('@objectstack/lint'); const targets: Array> = []; const hops = site === 'flow_condition' ? [] : authoredExpressionHopTargets(subject, expression); @@ -3837,6 +3860,23 @@ export function registerObjectTools( } const { role, scope, slot, optionLabels, traversalHydration, gatePasses, faultOutcome: outcomeOf } = VALIDATE_SITE_MAP[site ?? 'formula']; + // The gate's envelope verdict first: `validateExpression` treats a + // blank source as "not authored" and answers ok, while the save gate + // refuses it. Each issue is the spec schema's own (code and message), + // so the tool and the gate cannot drift apart on this rule. + const slotParse = slot.safeParse(expression); + // [#32872, #36167] The subject as this caller is served it, read once + // where the gate judges the site with passes of its own: those passes + // read it, and so does the list-valued field set below. + const subject = slotParse.success && gatePasses && bridge.servedObjectDefinitionOf + ? await bridge.servedObjectDefinitionOf(objectName) + : null; + // [#36167] The object's list-valued fields, which the publish gate + // hands the shared validator (`ExprSchemaHint.multiValueFields`), so + // `record. == ` is refused here as `list-equality` in + // the gate's words. `describeObject`'s projection carries no + // `multiple`; the served definition does. Absent, as before. + const multiValueFields = multiValueFieldsOfServed(subject, fields); const faultOutcome = outcomeOf?.({ severity: severity ?? 'error', triggerKind: triggerKind ?? 'record_change', @@ -3854,6 +3894,7 @@ export function registerObjectTools( fieldTypes, scope, ...(optionFields ? { optionFields } : {}), + ...(multiValueFields ? { multiValueFields } : {}), // [#32640] The gate's relationship-traversal checks, where it runs them. ...(traversalHydration ? { traversalHydration } : {}), ...(faultOutcome ? { faultOutcome } : {}), @@ -3867,11 +3908,6 @@ export function registerObjectTools( // on the same flow). Absent, the hint is byte for byte as before. ...(variables !== undefined ? { flowVariables: variables.map((v) => v.name) } : {}), } as const; - // The gate's envelope verdict first: `validateExpression` treats a - // blank source as "not authored" and answers ok, while the save gate - // refuses it. Each issue is the spec schema's own (code and message), - // so the tool and the gate cannot drift apart on this rule. - const slotParse = slot.safeParse(expression); const result = slotParse.success ? validateExpression(role, expression, hint) : { @@ -3887,7 +3923,7 @@ export function registerObjectTools( // flow condition, every other pass the gate runs there, in the // gate's own words. const gate = slotParse.success && gatePasses - ? await gatePassFindings(bridge, (name) => guard(name) === undefined, gatePasses, objectName, expression, { + ? await gatePassFindings(bridge, (name) => guard(name) === undefined, gatePasses, objectName, expression, subject, { severity, field, triggerKind, diff --git a/packages/mcp/src/mcp-validate-expression.list-equality-36167.test.ts b/packages/mcp/src/mcp-validate-expression.list-equality-36167.test.ts new file mode 100644 index 00000000000..dbe7b9c362d --- /dev/null +++ b/packages/mcp/src/mcp-validate-expression.list-equality-36167.test.ts @@ -0,0 +1,171 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36167] `validate_expression` refuses `record. == `, + * which answers one constant on every row, as the publish gate refuses it. + * + * The gate hands the shared validator the object's list-valued fields + * (`ExprSchemaHint.multiValueFields`, read through `isMultiValueField`), so a + * `select` / `user` declared `multiple: true` is a list there. The tool's own + * field list comes from `describeObject`, whose projection carries no + * `multiple`; the served definition (`McpDataBridge.servedObjectDefinitionOf`) + * does, and the tool reads the list-valued fields off it, once, at the sites + * where it already reads it for the gate's own passes. A bridge without the + * member answers exactly as before. + * + * Driven through the stdio bridge (`createStdioDataBridge`), whose + * `servedObjectDefinitionOf` is the real one. The gate's sentence is read off + * `validateStackExpressions` on the same rule or formula field. + */ + +import { describe, it, expect } from 'vitest'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; +import { AUTHORED_FORMULA_FIELD_NAME, AUTHORED_RULE_NAME, validateStackExpressions } from '@objectstack/lint'; + +import { MCPServerRuntime } from './mcp-server-runtime.js'; +import type { McpDataBridge } from './mcp-http-tools.js'; +import { createStdioDataBridge, type StdioProtocolObjectReads } from './stdio-data-bridge.js'; + +const OBJECT = 'qa_list_eq'; + +const OPTIONS = [ + { value: 'a', label: 'A' }, + { value: 'b', label: 'B' }, +]; + +const SERVED = { + name: OBJECT, + label: 'List equality', + sharingModel: 'private', + fields: { + title: { type: 'text', label: 'Title', required: true }, + stage: { type: 'select', label: 'Stage', options: OPTIONS, required: true }, + picks: { type: 'select', label: 'Picks', options: OPTIONS, multiple: true }, + watchers: { type: 'user', label: 'Watchers', multiple: true }, + owner: { type: 'user', label: 'Owner', required: true }, + }, +}; + +const PRINCIPAL = { userId: 'u1', isSystem: false } as unknown as ExecutionContext; + +function stdioBridge(): McpDataBridge { + const protocol = { + getMetaItems: async () => ({ type: 'object', items: [SERVED] }), + getMetaItem: async ({ name }: { name: string }) => ({ type: 'object', name, item: name === OBJECT ? SERVED : undefined }), + } as unknown as StdioProtocolObjectReads; + return createStdioDataBridge({ + engine: {} as unknown as IDataEngine, + metadataService: { listObjects: async () => [], getObject: async () => undefined } as unknown as IMetadataService, + protocol: () => protocol, + resolvePrincipal: async () => PRINCIPAL, + }); +} + +/** The same bridge with `servedObjectDefinitionOf` taken away (a bridge predating it). */ +function withoutDefinitions(bridge: McpDataBridge): McpDataBridge { + const { servedObjectDefinitionOf: _omit, ...rest } = bridge as McpDataBridge & Record; + return rest as McpDataBridge; +} + +async function validate( + bridge: McpDataBridge, + expression: string, + site: 'validation' | 'formula' | 'flow_condition', + extra: Record = {}, +) { + const runtime = new MCPServerRuntime({ name: 'objectstack-test', version: '9.9.9' }); + const body = { + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { name: 'validate_expression', arguments: { objectName: OBJECT, expression, site, ...extra } }, + }; + const res = await runtime.handleHttpRequest( + new Request('http://localhost/mcp', { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, + body: JSON.stringify(body), + }), + { bridge, parsedBody: body } as never, + ); + const json = (await res.json()) as { result: { content: Array<{ text: string }> } }; + return JSON.parse(json.result.content[0]!.text) as { + ok: boolean; + errors: Array<{ code?: string; message: string; params?: Record }>; + warnings: Array<{ message: string }>; + }; +} + +/** The publish gate's `list-equality` sentences on the same rule or formula field. */ +function gateSentences(site: 'validation' | 'formula', expression: string): string[] { + const subject = site === 'validation' + ? { ...SERVED, validations: [{ name: AUTHORED_RULE_NAME, type: 'script', condition: expression, message: 'm' }] } + : { ...SERVED, fields: { ...SERVED.fields, [AUTHORED_FORMULA_FIELD_NAME]: { type: 'formula', label: 'F', expression } } }; + return validateStackExpressions({ objects: [subject] }) + .filter((i) => i.severity !== 'warning' && i.message.includes('holds a list')) + .map((i) => i.message); +} + +const listEquality = (r: Awaited>) => r.errors.filter((e) => e.code === 'list-equality'); + +describe('validate_expression — list-equality on a multiple: true field (#36167)', () => { + for (const [site, expression, reference] of [ + ['validation', "record.picks == 'a'", 'record.picks'], + ['validation', "'u1' != record.watchers", 'record.watchers'], + ['formula', "record.picks == 'a' ? 1 : 0", 'record.picks'], + ] as const) { + it(`${site}: refuses \`${expression}\` once, in the publish gate's words`, async () => { + const gate = gateSentences(site, expression); + expect(gate).toHaveLength(1); + const r = await validate(stdioBridge(), expression, site); + expect(r.ok).toBe(false); + const refused = listEquality(r); + expect(refused).toHaveLength(1); + expect(refused[0]!.params).toMatchObject({ reference }); + expect(refused[0]!.message).toContain(`\`${reference}\` holds a list`); + expect(refused[0]!.message).toContain(' in '); + expect(refused.map((e) => e.message)).toEqual(gate); + // Judged once: the gate's own passes (`judgeAuthoredSiteExpression`) + // leave the shared validator to the tool, so no second sentence. + expect(r.errors.filter((e) => e.message.includes('holds a list'))).toHaveLength(1); + }); + } + + it('a bridge that serves no definition answers as before: a multiple: true select is not judged', async () => { + const r = await validate(withoutDefinitions(stdioBridge()), "record.picks == 'a'", 'validation'); + expect(listEquality(r)).toEqual([]); + expect(r.ok).toBe(true); + }); + + for (const [site, expression] of [ + ['validation', "'a' in record.picks"], + ['validation', 'record.watchers != null'], + ['validation', "record.stage == 'a'"], + ['validation', "record.owner == 'u1'"], + ['formula', "record.stage == 'a' ? 1 : 0"], + ] as const) { + it(`CONTROL — ${site}: \`${expression}\` reads ok, as before`, async () => { + const r = await validate(stdioBridge(), expression, site); + expect(r.errors).toEqual([]); + expect(r.ok).toBe(true); + expect(r).toEqual(await validate(withoutDefinitions(stdioBridge()), expression, site)); + }); + } + + // A record-triggered flow's condition reads the trigger record flattened, so + // a bare `picks` is the field, as the type pass reads it. + it('flow_condition: refuses the bare `picks == \'a\'` and `record.picks == \'a\'`', async () => { + for (const [expression, reference] of [["picks == 'a'", 'picks'], ["record.picks == 'a'", 'record.picks']] as const) { + const r = await validate(stdioBridge(), expression, 'flow_condition'); + expect(listEquality(r).map((e) => e.params?.reference)).toEqual([reference]); + expect(r.ok).toBe(false); + } + }); + + it('CONTROL — flow_condition: a bare name a declared variable holds is not the field; without the member, as before', async () => { + const variables = [{ name: 'picks', type: 'text' }]; + expect(listEquality(await validate(stdioBridge(), "picks == 'a'", 'flow_condition', { variables }))).toEqual([]); + expect(listEquality(await validate(withoutDefinitions(stdioBridge()), "picks == 'a'", 'flow_condition'))).toEqual([]); + }); +}); diff --git a/packages/qa/scenarios/src/score/scenario-expressions.ts b/packages/qa/scenarios/src/score/scenario-expressions.ts index ebdc03cee14..681ab74127c 100644 --- a/packages/qa/scenarios/src/score/scenario-expressions.ts +++ b/packages/qa/scenarios/src/score/scenario-expressions.ts @@ -34,7 +34,7 @@ import { collectCelRootIdentifiers, isSupportedRlsExpression, validateExpression } from '@objectstack/formula'; import { APPROVER_EXPRESSION_ROOTS } from '@objectstack/spec/automation'; -import { resolveInjectedSystemColumns } from '@objectstack/spec/data'; +import { isMultiValueField, resolveInjectedSystemColumns } from '@objectstack/spec/data'; type Bag = Record; @@ -61,6 +61,17 @@ function declaredFieldTypes(def: Bag): Record { return types; } +/** [#36167] The declared fields whose value is a list (`isMultiValueField`), as the build's pass hands them. */ +function declaredMultiValueFields(def: Bag): string[] { + const out: string[] = []; + for (const [name, field] of isBag(def.fields) ? Object.entries(def.fields) : []) { + if (isBag(field) && typeof field.type === 'string' && isMultiValueField({ type: field.type, multiple: field.multiple === true })) { + out.push(name); + } + } + return out; +} + /** * Why a `record`-scoped expression of `object` does not compile, or * `undefined` when it does: `value` for a computed field, `predicate` for a @@ -74,6 +85,7 @@ export function recordExpressionRefusal(role: 'value' | 'predicate', raw: unknow objectName: object, fields: objectColumns(def), fieldTypes: declaredFieldTypes(def), + multiValueFields: declaredMultiValueFields(def), scope: 'record', traversalHydration: true, }); diff --git a/packages/qa/scenarios/test/scenario-expressions-list-equality-36167.test.ts b/packages/qa/scenarios/test/scenario-expressions-list-equality-36167.test.ts new file mode 100644 index 00000000000..bf904d7e6d3 --- /dev/null +++ b/packages/qa/scenarios/test/scenario-expressions-list-equality-36167.test.ts @@ -0,0 +1,32 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36167] The scorer judges a card's record expression as the build's pass + * does: it hands the shared validator the object's list-valued fields + * (`multiValueFields`, read through `isMultiValueField`), so a formula or a + * validation rule comparing a `multiple: true` field with a scalar — which + * answers one constant on every row — does not compile here either. + */ + +import { describe, it, expect } from 'vitest'; + +import { recordExpressionRefusal } from '../src/score/scenario-expressions.js'; + +const TICKET = { + fields: { + owners: { type: 'user', multiple: true }, + owner: { type: 'user' }, + }, +}; + +describe('recordExpressionRefusal — list-equality', () => { + it('refuses a multiple: true field compared with a scalar', () => { + expect(recordExpressionRefusal('predicate', "record.owners == 'u1'", 'ticket', TICKET)).toContain( + '`record.owners` holds a list', + ); + }); + + it.each(["record.owner == 'u1'", "'u1' in record.owners", 'record.owners != null'])('CONTROL — accepts %s', (source) => { + expect(recordExpressionRefusal('predicate', source, 'ticket', TICKET)).toBeUndefined(); + }); +}); diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 87dca9ae423..90b37354b58 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -832,7 +832,12 @@ export type FlowFunctionResolver = ( */ export type FlowObjectSchemaResolver = ( objectName: string, -) => { fields?: readonly string[]; fieldTypes?: Record } | undefined; +) => { + fields?: readonly string[]; + fieldTypes?: Record; + /** [#36167] The list-valued fields (`ExprSchemaHint.multiValueFields`, `@objectstack/formula`). */ + multiValueFields?: readonly string[]; +} | undefined; /** * The authorization envelope a `runAs:'user'` run needs to enforce its data diff --git a/packages/services/service-automation/src/flow-registration-checks.ts b/packages/services/service-automation/src/flow-registration-checks.ts index 11c149b32ba..d08c3978d8e 100644 --- a/packages/services/service-automation/src/flow-registration-checks.ts +++ b/packages/services/service-automation/src/flow-registration-checks.ts @@ -797,7 +797,16 @@ export function validateFlowExpressions( const schemaHint = typeof objectName === 'string' ? (() => { const s = this.objectSchemaResolver?.(objectName); - return s ? { objectName, fields: s.fields, fieldTypes: s.fieldTypes, scope: 'flattened' as const } : undefined; + return s + ? { + objectName, + fields: s.fields, + fieldTypes: s.fieldTypes, + // [#36167] A list compared with a scalar is reported (`list-equality`). + ...(s.multiValueFields ? { multiValueFields: s.multiValueFields } : {}), + scope: 'flattened' as const, + } + : undefined; })() : undefined; diff --git a/packages/services/service-automation/src/list-equality-advisory-36167.test.ts b/packages/services/service-automation/src/list-equality-advisory-36167.test.ts new file mode 100644 index 00000000000..a3b0a326316 --- /dev/null +++ b/packages/services/service-automation/src/list-equality-advisory-36167.test.ts @@ -0,0 +1,111 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36167] `registerFlow`'s schema-aware pass hands the shared validator the + * object's list-valued fields: `parseObjectFieldSchema` reads each field + * through `isMultiValueField` into `multiValueFields`, and the flow-condition + * hint carries it, so a `record. == ` condition — which + * answers one constant on every row — is reported on the advisory channel + * (logged, never thrown, like every other finding of that pass). + */ + +import { describe, it, expect } from 'vitest'; +import { AutomationEngine } from './engine.js'; +import { parseObjectFieldSchema } from './plugin.js'; + +const TICKET_FIELDS = { + name: { type: 'text' }, + labels: { type: 'multiselect' }, + stage: { type: 'select' }, + watchers: { type: 'user', multiple: true }, + owner: { type: 'user' }, +}; + +describe('parseObjectFieldSchema — multiValueFields', () => { + it('lists the inherently-multi types and the multi-capable types declared multiple, nothing else', () => { + expect(parseObjectFieldSchema(TICKET_FIELDS)?.multiValueFields).toEqual(['labels', 'watchers']); + expect(parseObjectFieldSchema([{ name: 'tags', type: 'tags' }, { name: 'stage', type: 'select', multiple: false }])?.multiValueFields) + .toEqual(['tags']); + }); +}); + +describe('registerFlow — a list compared with a scalar is reported (advisory)', () => { + function loggerCapturing(warns: string[]) { + const l: any = { + info: () => {}, error: () => {}, debug: () => {}, + warn: (m: string) => warns.push(m), + child: () => l, + }; + return l; + } + + function makeFlow(condition: string) { + return { + name: 'ticket_flow', label: 'Ticket Flow', type: 'record_change', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { objectName: 'ticket' } }, + { id: 'check', type: 'decision', label: 'Check', config: { condition } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'check' }, + { id: 'e2', source: 'check', target: 'end' }, + ], + }; + } + + function warningsFor(condition: string): string[] { + const warns: string[] = []; + const engine = new AutomationEngine(loggerCapturing(warns)); + engine.setObjectSchemaResolver((name) => (name === 'ticket' ? parseObjectFieldSchema(TICKET_FIELDS) : undefined)); + expect(() => engine.registerFlow('ticket_flow', makeFlow(condition) as any)).not.toThrow(); + return warns.filter((m) => /holds a list/.test(m)); + } + + it.each([ + ["record.labels == 'frontend'", 'record.labels'], + ["record.watchers != 'u1'", 'record.watchers'], + ])('reports %s, naming the field and `in`', (condition, reference) => { + const w = warningsFor(condition); + expect(w).toHaveLength(1); + expect(w[0]).toContain(`\`${reference}\` holds a list`); + expect(w[0]).toContain(` in ${reference}`); + }); + + // A bare name at a flow condition is the flattened trigger record's field. + it.each([ + ["labels == 'frontend'", 'labels'], + ["'u1' != watchers", 'watchers'], + ])('reports the bare %s, naming the field and `in`', (condition, reference) => { + const w = warningsFor(condition); + expect(w).toHaveLength(1); + expect(w[0]).toContain(`\`${reference}\` holds a list`); + expect(w[0]).toContain(` in ${reference}`); + }); + + it.each([ + "record.stage == 'won'", "record.owner == 'u1'", 'record.watchers != null', "'u1' in record.watchers", + "stage == 'won'", "owner == 'u1'", 'labels != null', "'frontend' in labels", + ])( + 'CONTROL — %s is not reported', + (condition) => { + expect(warningsFor(condition)).toEqual([]); + }, + ); +}); + +describe('the premise at a flow condition — the run flattens the record, and a bare list compared with a scalar is a constant', () => { + const engine = new AutomationEngine({ info: () => {}, warn: () => {}, error: () => {}, debug: () => {} } as any); + const run = (source: string, labels: unknown) => + engine.evaluateCondition(source, new Map([['labels', labels], ['record', { labels }]])); + it.each([[['frontend', 'qa']], [['frontend']], [[]], [null]])('labels = %j', (labels) => { + expect(run("labels == 'frontend'", labels)).toBe(false); + expect(run("record.labels == 'frontend'", labels)).toBe(false); + expect(run("labels != 'frontend'", labels)).toBe(true); + }); + it('CONTROL — the membership rewrite answers per row', () => { + expect(run("labels != null && 'frontend' in labels", ['frontend', 'qa'])).toBe(true); + expect(run("labels != null && 'frontend' in labels", ['qa'])).toBe(false); + expect(run("labels != null && 'frontend' in labels", null)).toBe(false); + }); +}); diff --git a/packages/services/service-automation/src/plugin.ts b/packages/services/service-automation/src/plugin.ts index 02ab3709496..e21129fa5ea 100644 --- a/packages/services/service-automation/src/plugin.ts +++ b/packages/services/service-automation/src/plugin.ts @@ -17,6 +17,7 @@ import type { } from '@objectstack/spec/integration'; import { isConnectorCredentialRejected, isConnectorUpstreamChanged, isConnectorUpstreamUnavailable, RetryConfigSchema } from '@objectstack/spec/integration'; import { stripReadDecorations } from '@objectstack/spec/kernel'; +import { isMultiValueField } from '@objectstack/spec/data'; import { postureEnforcesWall, type TenancyPosture } from '@objectstack/spec/security'; import type { MetadataMutationEvent, SysMetadataEngine } from '@objectstack/metadata-protocol'; import { SysMetadataRepository, shadowedStoredRowsOf } from '@objectstack/metadata-protocol'; @@ -167,29 +168,37 @@ import { ObjectStoreFlowActivationStore, type FlowActivationStoreEngine } from ' * condition validator consumes. Fields whose `type` isn't a string are still * listed (so existence checks work) but contribute no type (→ treated as `dyn`). * Returns `undefined` when there is nothing usable. Exported for unit testing. + * + * [#36167] `multiValueFields`: the fields whose stored value is a list, read + * through `isMultiValueField` (`@objectstack/spec/data`) — an inherently-multi + * option type, or a multi-capable type declared `multiple: true`, which the + * type alone does not say. The validator's `ExprSchemaHint.multiValueFields`, + * so a `==` / `!=` between such a field and a scalar is reported. */ export function parseObjectFieldSchema( fieldsDef: unknown, -): { fields: string[]; fieldTypes: Record } | undefined { +): { fields: string[]; fieldTypes: Record; multiValueFields: string[] } | undefined { if (!fieldsDef || typeof fieldsDef !== 'object') return undefined; const fields: string[] = []; const fieldTypes: Record = {}; + const multiValueFields: string[] = []; + const add = (n: string, def: unknown): void => { + fields.push(n); + const { type: t, multiple } = (def ?? {}) as { type?: unknown; multiple?: unknown }; + if (typeof t !== 'string') return; + fieldTypes[n] = t; + if (isMultiValueField({ type: t, multiple: multiple === true })) multiValueFields.push(n); + }; if (Array.isArray(fieldsDef)) { for (const f of fieldsDef as Array>) { const n = (f as { name?: unknown })?.name; if (typeof n !== 'string') continue; - fields.push(n); - const t = (f as { type?: unknown })?.type; - if (typeof t === 'string') fieldTypes[n] = t; + add(n, f); } } else { - for (const [n, def] of Object.entries(fieldsDef as Record)) { - fields.push(n); - const t = (def as { type?: unknown })?.type; - if (typeof t === 'string') fieldTypes[n] = t; - } + for (const [n, def] of Object.entries(fieldsDef as Record)) add(n, def); } - return { fields, fieldTypes }; + return { fields, fieldTypes, multiValueFields }; } /** diff --git a/packages/spec/src/migrations/entries/semantic/18.cel-list-equality-refused.ts b/packages/spec/src/migrations/entries/semantic/18.cel-list-equality-refused.ts new file mode 100644 index 00000000000..6ea16816c02 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.cel-list-equality-refused.ts @@ -0,0 +1,41 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// The shared CEL validator refuses `==` / `!=` between a list-valued field and +// a non-null scalar literal (`list-equality`, #36167). A structured TODO, not a +// D2 conversion: `record.labels == 'frontend'` answers `false` on every row, so +// the condition the author meant — membership, or a whole-list match — is not +// recorded, and the platform does not guess. +export const entry: SemanticMigration = { + id: 'cel-list-equality-refused', + surface: + 'Any CEL predicate or formula the shared validator types against an object (a validation rule, a field rule, a ' + + 'formula, an action\'s visible / disabled, a hook or flow condition): `==` or `!=` ' + + 'between a read of a list-valued field (`multiselect`, `checkboxes`, `tags`, or a `select` / `radio` / ' + + '`lookup` / `user` / `file` / `image` field declared `multiple: true`) on `record` / `previous` — or, at a ' + + 'flow condition, its bare name, which the run binds to the trigger record\'s field — and a non-null ' + + 'string, number or boolean literal, in either operand order. Not the shape: a name a comprehension macro ' + + 'binds (`record.items.exists(labels, labels == \'a\')`, where `labels` is one item), nor a bare name a ' + + 'declared flow variable holds', + replacement: + 'Test membership with `in`, null-guarded because `\'a\' in null` faults: `record.labels != null && ' + + '\'frontend\' in record.labels` for `==`, and `record.labels == null || !(\'frontend\' in record.labels)` for ' + + '`!=`. Compare the list with `null` to test whether it is set, and with a list literal for a whole-list match. ' + + '`os validate`, `os build`, the MCP `validate_expression` tool and the Studio object editor\'s draft check ' + + 'refuse the shape as `list-equality`, an error; the flow registration pass logs it.', + reason: + 'CEL compares the whole list with the scalar, so `[\'frontend\', \'qa\'] == \'frontend\'` is `false`, and so ' + + 'is `null == \'frontend\'`: the expression answers `false` (`true` for `!=`) on every row whatever the list ' + + 'holds, with no fault and no log line. A condition written that way never fires (or always does), and the ' + + 'validator accepted it. Only a read that is the list field is refused: a name a comprehension macro binds ' + + 'holds one item, and its comparison answers per row, so it is not. Which test the author meant is not ' + + 'recorded, so no mechanical rewrite is lossless. ' + + 'Measured at the change: no producer of the shape in this repository\'s examples, its QA fixtures or HotCRM. ' + + 'ADR-0032 / ADR-0087.', + acceptanceCriteria: + 'Load every module (`os validate` or `os build`): no `list-equality` finding. Every comparison of a list-valued ' + + 'field is a membership test, a null test or a whole-list match, and the condition answers per row. A stored row ' + + 'carrying the shape still loads and is served; its next save through a door that runs the publish lint is ' + + 'refused until it is corrected.', +}; diff --git a/ui/packages/app-shell/src/views/metadata-admin/celAuthoring.ts b/ui/packages/app-shell/src/views/metadata-admin/celAuthoring.ts index 634b78aa6c1..844a462746c 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/celAuthoring.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/celAuthoring.ts @@ -43,6 +43,17 @@ export interface CelSchemaHint { objectName?: string; /** Known field names of {@link objectName}, so `` refs can be checked. */ fields?: string[]; + /** + * The fields of {@link objectName} whose stored value is a LIST — read + * through `isMultiValueField` (`@objectstack/spec/data`): `multiselect` / + * `checkboxes` / `tags`, or a `select` / `lookup` / `user` declared + * `multiple: true`. Handed to the engine as `ExprSchemaHint.multiValueFields`, + * so `record. == 'a'` on one is refused (`list-equality`: the list + * compared with a scalar answers a constant) with the `in` rewrite. Omitted + * by a surface whose field catalog does not carry `multiple`: the hint is + * then exactly what it was before this key. + */ + multiValueFields?: string[]; /** * Which RLS clause is being edited: `USING` (read filter) or `CHECK` (write * filter). Naming one turns on `@objectstack/lint`'s RLS rule — a clause it @@ -668,6 +679,8 @@ export async function lintCelPredicate( const res = mod.validateExpression(hint.role ?? 'predicate', source, { objectName: hint.objectName, fields: hint.fields, + // Spread only when given, so every other surface's hint is unchanged. + ...(hint.multiValueFields ? { multiValueFields: hint.multiValueFields } : {}), scope: hint.scope ?? 'flattened', }); const issues: CelLintIssue[] = []; diff --git a/ui/packages/app-shell/src/views/metadata-admin/clientValidation.listEquality-36167.test.ts b/ui/packages/app-shell/src/views/metadata-admin/clientValidation.listEquality-36167.test.ts new file mode 100644 index 00000000000..3d9c32dc571 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/clientValidation.listEquality-36167.test.ts @@ -0,0 +1,76 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36167] The Studio CEL hint carries the object's list-valued fields + * (`CelSchemaHint.multiValueFields` → the engine's + * `ExprSchemaHint.multiValueFields`), so `record. == ` — + * which answers one constant on every row — is refused in Studio as the + * publish lint refuses it. The object draft gate reads each field through + * `isMultiValueField`, so a `select` / `user` declared `multiple: true` is a + * list there too. Against the REAL `@objectstack/formula` engine. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +// The CEL authoring helpers load these through dynamic imports; paying the first +// load at module top keeps it out of every clocked window (`check:test-source-alias`). +import '@objectstack/formula'; +import '@objectstack/lint'; +import '@object-ui/core'; +import { validateMetadataDraft } from './clientValidation'; +import { __setCelFormulaLoader, lintCelPredicate } from './celAuthoring'; + +afterEach(() => __setCelFormulaLoader(undefined)); + +const OPTIONS = [ + { label: 'Frontend', value: 'frontend' }, + { label: 'QA', value: 'qa' }, +]; + +describe('lintCelPredicate — multiValueFields', () => { + it('refuses a list field compared with a scalar when the hint names it', async () => { + const issues = await lintCelPredicate("record.watchers == 'u1'", { + fields: ['watchers'], + multiValueFields: ['watchers'], + scope: 'record', + }); + const errors = issues.filter((i) => i.severity === 'error'); + expect(errors).toHaveLength(1); + expect(errors[0].message).toContain('`record.watchers` holds a list'); + expect(errors[0].message).toContain('in record.watchers'); + }); + + it('CONTROL — without the hint member the same source is clean (as before)', async () => { + const issues = await lintCelPredicate("record.watchers == 'u1'", { fields: ['watchers'], scope: 'record' }); + expect(issues.filter((i) => i.severity === 'error')).toEqual([]); + }); +}); + +describe('validateMetadataDraft — object field rules on a list field', () => { + const draft = (visibleWhen: string) => ({ + name: 'ticket', + label: 'Ticket', + fields: { + labels: { type: 'multiselect', label: 'Labels', options: OPTIONS }, + stage: { type: 'select', label: 'Stage', options: OPTIONS, multiple: true }, + single: { type: 'select', label: 'Single', options: OPTIONS }, + note: { type: 'text', label: 'Note', visibleWhen }, + }, + }); + + it.each([ + ["record.labels == 'frontend'", 'record.labels'], + ["record.stage != 'qa'", 'record.stage'], + ])('refuses %s under fields.note.visibleWhen', async (source, reference) => { + const res = await validateMetadataDraft('object', draft(source)); + const issue = res.issues.find((i) => i.path === 'fields.note.visibleWhen'); + expect(issue?.message).toContain(`\`${reference}\` holds a list`); + }); + + it.each(["record.single == 'qa'", "'qa' in record.stage", 'record.labels != null'])( + 'CONTROL — %s raises no issue', + async (source) => { + const res = await validateMetadataDraft('object', draft(source)); + expect(res.issues.filter((i) => i.path === 'fields.note.visibleWhen')).toEqual([]); + }, + ); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/clientValidation.ts b/ui/packages/app-shell/src/views/metadata-admin/clientValidation.ts index bfeb59f0ee3..3e6385d651b 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/clientValidation.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/clientValidation.ts @@ -23,7 +23,8 @@ import type { SchemaFormIssue } from './SchemaForm.js'; import type { SchemaIssueDetail } from './i18n.js'; import { lintCelPredicate } from './celAuthoring.js'; -import { readFields } from './previews/object-fields-io.js'; +import { readFields, type FieldsView } from './previews/object-fields-io.js'; +import { isMultiValueField } from '@objectstack/spec/data'; /** * The structural slice of a Zod issue this module reads. @@ -815,6 +816,18 @@ function predicateSource(v: unknown): string | null { return null; } +/** + * [#36167] The draft's fields whose stored value is a list, read through + * `isMultiValueField` (`@objectstack/spec/data`) — the `multiValueFields` the + * CEL lint hands the engine, so `record. == 'a'` on a multi-value + * field is refused here as the publish lint refuses it. + */ +function multiValueFieldsOf(view: FieldsView): string[] { + return view.entries + .filter((e) => typeof e.def.type === 'string' && isMultiValueField({ type: e.def.type, multiple: e.def.multiple === true })) + .map((e) => e.name); +} + /** * Lint every field conditional rule — and every `formula` field's * `expression` (role `value`, objectui#1582 follow-up) — on an object draft. @@ -828,6 +841,7 @@ async function validateObjectFieldRules(draft: unknown): Promise e.name); + const multiValueFields = multiValueFieldsOf(view); const issues: SchemaFormIssue[] = []; for (let i = 0; i < view.entries.length; i++) { const entry = view.entries[i]; @@ -838,6 +852,7 @@ async function validateObjectFieldRules(draft: unknown): Promise n !== entry.name), + multiValueFields, scope: 'record', role: 'value', }); @@ -945,7 +961,9 @@ async function validateObjectValidationRules(draft: unknown): Promise e.name); + const view = readFields(d?.fields); + const fieldNames = view.entries.map((e) => e.name); + const multiValueFields = multiValueFieldsOf(view); const issues: SchemaFormIssue[] = []; const visit = async (rule: unknown, path: string, depth: number): Promise => { @@ -958,6 +976,7 @@ async function validateObjectValidationRules(draft: unknown): Promise