Skip to content

Commit ad65d82

Browse files
fix(formula)!: validateExpression refuses == / != between a list-valued field and a scalar (#36207)
Part of #36167 Clause-②: no (narrowing) Metadata-protocol: narrowed Skills-docs: follow-up #36217 ## 维护者速读 - 要你做什么:这次改动把以前能保存的「多值字段直接等于单个值」的表达式写法改为拒绝(收紧),按规则需要你本人审阅批准后才能合并;条件构建器那一半另由一个拉取请求交付。 - 作者在 Studio 保存对象、发布校验、或让 AI 助手检查表达式时,若把一个多值字段(多选、多人等)直接与单个值比较相等(含流程条件里直接写字段名的写法),现在会被拒绝并给出改写建议;以前这种写法被静默接受。 - 属于「表达式校验与作者护栏」:这类条件在每一行都给出同一个固定答案,规则永远不触发或永远触发,且没有任何报错或日志。 - 若误判,作者会在保存或发布时看到一条拒绝;本改动可整体回退,已存储的数据照常加载和服务,仅在下一次经校验的保存时要求改写。 - 这是收窄已接受写法的破坏性变更,需要你审阅后亲自合并落地;条件构建器那一半另由一个拉取请求交付。 ## What changes The shared CEL validator (`validateExpression`) now refuses `==` / `!=` between a read of a list-valued field on `record` / `previous` (or, at a flow condition, its bare name) and a non-null string, number or boolean literal, as the new closed code `list-equality`. CEL compares the whole list with the scalar, so `record.labels == 'frontend'` answers `false` on every row (and `!=` answers `true`): the condition never changes, with no fault and no log line. - **The refusal** (`packages/formula/src/validate.ts`, `checkListEquality` / `listEqualityRefusal`): either operand order; member spellings `record.f`, `record['f']`, `previous.f`. The message names the field and prescribes the null-guarded membership test, `record.f != null && "v" in record.f` for `==` and `record.f == null || !("v" in record.f)` for `!=`. Params: `reference`, `operator`, `operand`, `answer`, `rewrite`. Subjects resolve through a new `rootMemberOf` helper in `relationship-traversal.ts`, which reuses the existing member-spelling reader. - **Bare names at a flow condition.** At a `'flattened'` site (a flow's start / edge / decision condition) a bare `labels` is the trigger record's field, as the type pass already reads it (#29959 / #33176 shape), so `labels == 'frontend'` is refused as `list-equality` naming `labels`. Two exceptions get no verdict: a name a flow variable holds (`ExprSchemaHint.flowVariables`), and any bare name in a flow whose nodes can bind names no reader sees (`bareNamesUnproven`). `record.labels` is refused in both cases. A name a comprehension macro binds (`exists`, `all`, `exists_one`, `map`, `filter`, the engine's own `COMPREHENSION_MACRO_NAMES`) is one item of the list inside that macro's body, so `record.items.exists(labels, labels == 'a')` is not judged there, at any site; the same name outside the macro still is. Measured reading: the docs' canonical spelling is `record.f` and the Studio flow edge writer writes `record.f`, but bare field names are a documented binding, and `examples/` writes record-triggered start conditions bare (`title != previous.title`, `status == "completed" && ...`). - **Which fields are lists.** A `fieldTypes` entry of an inherently multi-value type (`MULTI_OPTION_TYPES`: `multiselect`, `checkboxes`, `tags`), or a field named in the new optional `ExprSchemaHint.multiValueFields`. Every producer derives that member from `isMultiValueField` in `@objectstack/spec/data`; none hand-copies a type list. That is how a `select` / `radio` / `lookup` / `user` / `file` / `image` declared `multiple: true` becomes a list. When the member is absent, those types are judged exactly as before. - **Producers filled:** - The publish lint (`os validate` / `os build`): every CEL site that types the object's fields (predicate sites and formulas), via a per-object index (`buildMultiValueFieldIndex`). - `registerFlow`'s schema pass: `parseObjectFieldSchema` returns `multiValueFields`. Logged, never thrown, like every finding of that pass. - The scenario scorer (`recordExpressionRefusal`). - The MCP `validate_expression` tool, at the validation / formula / flow-condition sites. The list comes off the served definition (`McpDataBridge.servedObjectDefinitionOf`), which carries `multiple`; `describeObject`'s projection does not. The definition is read once and shared with the gate's own passes (`judgeAuthoredSiteExpression`), so the reads per call are unchanged. Those passes run with `sharedValidatorRunByCaller`, so the refusal is not given twice. A bridge without the member answers exactly as before. - Studio's object draft check (`validateMetadataDraft`: field rules, formulas, validation rules), through `CelSchemaHint.multiValueFields`. - **Still accepted:** - `S == null` / `S != null` (either side) and `"a" in S`. - A list compared with a list literal or with another list field. - A comparison whose other operand is not a literal. - Scalar fields (`select`, `user`, `lookup` without `multiple`). - **ADR-0087:** semantic entry `cel-list-equality-refused` (a structured TODO, not a D2 conversion, because the author's intent, membership versus whole-list match, is not recorded). Changeset: `minor` with the BREAKING arm, FROM → TO, and a one-line fix. **Interpretation, declared.** I read "non-null operand" as a non-null scalar *literal*. A non-literal operand (`record.labels == record.stage`), a list literal, or another list subject gets no verdict. Each of these can miss a catch. On the subject side, the pass refuses only a read it can show is the list field: a `record.` / `previous.` member read, or a bare name at a flow condition that no declared flow variable and no comprehension macro binds, in a flow whose nodes bind no unseen names. One premise is inherited from the type pass: the MCP tool reads a bare name as the field unless the caller hands it the flow's `variables`. ## Tests - `packages/formula/src/validate-list-equality-36167.test.ts` (156): first proves the premise on the real engine (`["frontend","qa"] == "frontend"` is false, and so is `null == "frontend"`). Then it covers: - each multi type × `record` / `previous` × `==` / `!=` × every spelling (dot, reversed, bracket, number, bool, compound); - the optional spellings `.?` / `[?]`, which get only `invalid-cel` against a scalar (pinned); - flattened and value roles; - `select` / `lookup` / `user` with and without `multiValueFields`; - every accepted shape and the no-hint case; - bare names at a flattened site (refused for each multi type and for `select` / `user` declared multiple), with controls: record scope, a shadowing flow variable, `bareNamesUnproven`, the accepted shapes; - a name a comprehension macro binds: `exists` / `all` / `exists_one` / `filter` / `map` over a variable named like a list field are accepted (premise on the engine: `record.items.exists(labels, labels == 'a')` answers per row). The same name outside the macro, an unbound name in the body, and `record.labels` in the body are still refused. - `expression-refusal-codes.test.ts`: `list-equality` is in the closed-code sweep and PINS (code, every param in the message). - Door pins named after the card: - lint `validate-expressions.list-equality-36167.test.ts` (20: action `visible`, a validation rule, a formula, and a record-triggered flow start condition, bare and `record.`, with a declared-variable control and two comprehension-variable controls); - service-automation `list-equality-advisory-36167.test.ts` (18, including the bare-name premise on the flow engine's own `evaluateCondition`: `labels == 'frontend'` is `false` for every list and for `null`); - mcp `mcp-validate-expression.list-equality-36167.test.ts` (11, through the real stdio bridge: a `select` / `user` declared `multiple: true` is refused once, in the publish gate's sentence read off `validateStackExpressions`; a bridge without `servedObjectDefinitionOf` answers as before; flow_condition, bare and `record.`, with a variable control); - scenarios `scenario-expressions-list-equality-36167.test.ts` (4); - app-shell `clientValidation.listEquality-36167.test.ts` (7, against the real formula engine). All fixtures go through `ObjectStackSchema.safeParse` first, where a door takes a stack. ## Acceptance notes - **Census: 0 producers** (measured at dd76082; the later commits only narrow what is refused). The scan covered `examples/` and `packages/qa`, plus hotcrm read-only at 6090c83: a name-based over-approximation of every list-field name compared with a literal. - The 3 raw hits are not producers: a doc comment on a single-valued `f_lookup`, and this PR's own pins. - `objectstack validate` over app-crm, app-showcase, app-todo and app-multi-package reports 0 `list-equality` findings, bare-name judging included (re-run at dd76082, each exit 0). - Positive control, measured: on app-crm, adding `multiple: true` to `crm_lead.assigned_to` plus `visible: record.assigned_to == "u1"` makes `validate` exit 1 with "`record.assigned_to` holds a list". The same predicate without `multiple: true` exits 0. Both files were restored byte-identical to HEAD. - **Not in this PR (builder half and catalog):** - The `CelPredicateField` as-you-type mounts in `inspectors/**` pass no `multiValueFields` (and no `fieldTypes`), so the editor shows no finding for a list field while the save is refused. Carried by #36219. - The Studio resource-edit catalog of field facts belongs to the `multiple` catalog card and was not widened here. - Studio's draft check *does* refuse, because it reads the field definitions directly. - **`registerFlow`'s advisory pass gives the validator no `flowVariables`.** It already types bare names that way. A flow variable that shares a list field's name can therefore draw a logged (never thrown) `list-equality` advisory, as it already can draw a type-mismatch one. `os validate`, the runtime publish gate and the MCP tool pass the variables. Carried by #36218 (review follow-ups of PR #36207). - **A list read through a relationship is not judged (gap, declared).** `record.account.labels == 'a'` validates clean even with `traversalHydration`: `rootMemberOf` answers only a direct member of `record` / `previous`, and the hint carries no hop target's field shapes. `ExprSchemaHint` holds the subject object's `fields` / `fieldTypes` / `multiValueFields`, `attachedOnRead` (names only) and `traversalHydration` (a boolean). Judging the hop needs either a new hint member, which is a new producer contract, or a lint pass beside `refuseUndeclaredHopField`, which already holds the target definitions. Reported to the seat to file; not widened here. Carried by #36237. - **Beyond the claimed file surface:** - `relationship-traversal.ts`: the shared member reader, not a copy of it. - The ADR-0087 semantic entry, which the `narrowed` declaration requires. - The scenario scorer, as an extra producer of the same hint. ## Verification First read, by risk: 1. `packages/formula/src/validate.ts` — `checkListEquality` / `listEqualityRefusal`: what counts as a subject (member read, and the bare name at a flattened site) and an operand. This is the narrowing itself. 2. `packages/lint/src/validate-expressions.ts` — `buildMultiValueFieldIndex` and the two sites that pass it, which decide what `os validate` refuses. 3. `packages/mcp/src/mcp-http-tools.ts` — `validate_expression`: the subject read moved ahead of the hint and handed to `gatePassFindings`, plus `multiValueFieldsOfServed`. Two-minute check: `pnpm --filter @objectstack/formula exec vitest run src/validate-list-equality-36167.test.ts` prints `Tests 156 passed`. **Every reading below was taken on this branch.** The head is 32d1de4. The second fix round's readings are at that head: the gates, the changed packages' suites, the new ablation and the dogfood battery. Earlier readings are marked with their head. **Dogfood battery** (full, no shard, no path) at the final head 32d1de4: `VERDICT command-exit 0`; Test Files 484 passed, 3 skipped (487); Tests 4107 passed, 68 skipped (4175). The earlier runs at 82d3bdd, 013e722 and dd76082 gave the same counts. <details><summary>Package suites</summary> At 32d1de4: - formula: build + test + typecheck, Test Files 70 passed, Tests 2063 passed, exit 0 - mcp: test 1463 passed; typecheck exit 0 - lint: test 9382 passed (the pin file alone: 20) - service-automation: test 4216 passed - scenarios: test 1280 passed - spec `src/migrations`: 198 passed - app-shell metadata-admin `celAuthoring*` / `clientValidation*`: 288 passed At 82d3bdd (first round): - service-automation typecheck exit 0, scenarios typecheck exit 0, lint typecheck exit 0 - app-shell `type-check` exit 0 </details> <details><summary>Ablation (one per tested behaviour; each leg through ablation-replace, restore proven by blob == HEAD and an empty git diff HEAD)</summary> Second fix round, at 32d1de4: - comprehension binding removed (the body walked with the enclosing bindings only): 6 failed / 150 passed (156) First fix round, at dd76082: - bare-name branch removed from `checkListEquality`: 16 failed / 129 passed (145) - MCP `multiValueFields` hint fill removed: 4 failed / 7 passed (11). The first attempt passed a newline as `--replacement`; the tool refused it (the replacement count did not rise) and restored, so that reading is void. It was redone with `--delete`. First round: - refusal call removed from `validateExpression`: 93 failed / 26 passed (119) - lint predicate-site fill removed: 1 failed / 9 passed (10) - lint formula-site fill removed: 1 failed / 9 passed (10) - `parseObjectFieldSchema` fill removed: 2 failed / 5 passed (7) - flow schemaHint pass-through removed: 1 failed / 6 passed (7) - scenario scorer fill removed: 1 failed / 3 passed (4) - Studio `CelSchemaHint` pass-through removed: 3 failed / 4 passed (7) - Studio draft-check validation-rule fill removed: 2 failed / 5 passed (7). The first attempt deleted extra lines and collected no tests, so it was void; it was redone with an exact `--replacement`. Each mutated module is resolved from source by the suite that judged it, so no rebuild leg was needed. </details> <details><summary>Gates (32d1de4)</summary> - `node scripts/pm/dispatch-gates.mjs --ran`: 105 derived (one more than before: `check:swallow-census-controls`), 104 run, 1 NOT MEASURED, 0 unrun. - NOT MEASURED: `check:dual-build-cjs-loads` exit 3, PREREQUISITE NOT MET (packages outside this diff have no `dist/`). CI runs it. - `pnpm --dir ui exec vitest run scripts/`: in the battery it timed out one case (`js-comment-mask-returns-interpolation-9424`, a 15 s window, while the dogfood battery shared the box). Re-run alone under the lock: 172 files / 5121 tests, exit 0. - `pnpm --filter @objectstack/cli exec vitest run test/migrate-meta-engine-guidance.test.ts`: exit 99 the first time (lock queue); re-run under the lock, 3/3, exit 0. - `check:nul-bytes` exit 0. `overlap-check` against origin/main 5e8e243: VERDICT clean. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5miLqNucRZevceHwNh)_ <!-- signed: repo:objectstack#4 · os-project-manager · session_01FEkQ5krBqrrgxCYgjXmfbv --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent c30ce97 commit ad65d82

22 files changed

Lines changed: 1326 additions & 31 deletions
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
---
2+
'@objectstack/formula': minor
3+
'@objectstack/lint': minor
4+
'@objectstack/mcp': minor
5+
'@objectstack/service-automation': minor
6+
'@objectstack/spec': minor
7+
'@objectstack/scenarios': minor
8+
'@object-ui/app-shell': minor
9+
---
10+
11+
fix(formula)!: `validateExpression` refuses `==` / `!=` between a list-valued field and a scalar, which answers a constant on every row
12+
13+
Clause-②: no (narrowing)
14+
Metadata-protocol: narrowed
15+
Skills-docs: follow-up #36217
16+
17+
<!-- adr-0087: registered cel-list-equality-refused -->
18+
19+
**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.
20+
21+
- **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.
22+
- **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.
23+
- **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`).
24+
- **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.
25+
26+
FROM → TO:
27+
28+
- `record.labels == 'frontend'` → `record.labels != null && 'frontend' in record.labels`
29+
- `record.labels != 'frontend'` → `record.labels == null || !('frontend' in record.labels)`
30+
- at a flow condition, `labels == 'frontend'` → `labels != null && 'frontend' in labels`
31+
32+
One-line fix: test membership with `in`, null-guarded (`'a' in null` faults); compare the list with `null` to test whether it is set.

‎packages/formula/src/cel-engine.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1060,7 +1060,7 @@ function comparesDateTextAgainstUndeclared(source: string, env: Environment): bo
10601060
// A macro (`list.exists(x, …)`): `rcall` [name, receiver, [variable, …body]].
10611061
const args = v.args;
10621062
if (v.op === 'rcall' && Array.isArray(args) && args.length === 3 && Array.isArray(args[2])
1063-
&& MACRO_NAMES.has(String(args[0]))) {
1063+
&& COMPREHENSION_MACRO_NAMES.has(String(args[0]))) {
10641064
const [variable, ...body] = args[2] as unknown[];
10651065
const name = isCelNode(variable) && variable.op === 'id' && typeof variable.args === 'string' ? variable.args : null;
10661066
visit(args[1], bound);
@@ -1073,8 +1073,12 @@ function comparesDateTextAgainstUndeclared(source: string, env: Environment): bo
10731073
return found;
10741074
}
10751075

1076-
/** The CEL macros that bind a variable over a list's items (`list.exists(x, …)`). */
1077-
const MACRO_NAMES: ReadonlySet<string> = new Set(['all', 'exists', 'exists_one', 'map', 'filter']);
1076+
/**
1077+
* The CEL macros that bind a variable over a list's items (`list.exists(x, …)`).
1078+
* Package-internal (not re-exported from the entry): `validate.ts`'s
1079+
* list-equality pass reads the same set, so a name a macro binds is read alike.
1080+
*/
1081+
export const COMPREHENSION_MACRO_NAMES: ReadonlySet<string> = new Set(['all', 'exists', 'exists_one', 'map', 'filter']);
10781082

10791083
/**
10801084
* A typed environment for the soundness check. Each field carries a concrete

‎packages/formula/src/expression-refusal-codes.test.ts‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -840,6 +840,50 @@ const PINS: { readonly [C in ExpressionRefusalCode]: readonly [Pin<C>, ...Pin<C>
840840
"label() reads a select field's option label; read any other field directly (record.first).",
841841
},
842842
],
843+
// [#36167] A list-valued field compared with a scalar answers a constant.
844+
'list-equality': [
845+
{
846+
produce: () =>
847+
onlyError('predicate', "record.labels == 'frontend'", {
848+
scope: 'record',
849+
fields: ['labels'],
850+
fieldTypes: { labels: 'multiselect' },
851+
}),
852+
params: {
853+
reference: 'record.labels',
854+
operator: '==',
855+
operand: '"frontend"',
856+
answer: 'false',
857+
rewrite: 'record.labels != null && "frontend" in record.labels',
858+
},
859+
message:
860+
'list compared with a scalar — `record.labels` holds a list (a multi-value field), and `==` compares the whole ' +
861+
'list with `"frontend"`, so the expression answers `false` on every row whatever the list holds: the condition ' +
862+
'never changes. Test membership with `in`: write `record.labels != null && "frontend" in record.labels`. ' +
863+
'To test whether the list is set, compare it with `null`.',
864+
},
865+
{
866+
produce: () =>
867+
onlyError('predicate', "'u1' != previous.owners", {
868+
scope: 'record',
869+
fields: ['owners'],
870+
fieldTypes: { owners: 'user' },
871+
multiValueFields: ['owners'],
872+
}),
873+
params: {
874+
reference: 'previous.owners',
875+
operator: '!=',
876+
operand: '"u1"',
877+
answer: 'true',
878+
rewrite: 'previous.owners == null || !("u1" in previous.owners)',
879+
},
880+
message:
881+
'list compared with a scalar — `previous.owners` holds a list (a multi-value field), and `!=` compares the whole ' +
882+
'list with `"u1"`, so the expression answers `true` on every row whatever the list holds: the condition ' +
883+
'never changes. Test membership with `in`: write `previous.owners == null || !("u1" in previous.owners)`. ' +
884+
'To test whether the list is set, compare it with `null`.',
885+
},
886+
],
843887
'empty-expression': [
844888
{
845889
produce: () => rootsRefusal(' '),
@@ -926,6 +970,8 @@ const SWEEP_SOURCES: readonly string[] = [
926970
'has(status) && other == 1',
927971
'daysBetween(record.a, record.b) > 3',
928972
"label(record.name) + label(record.status)",
973+
// [#36167] A list-valued field compared with a scalar.
974+
"record.tags == 'frontend'",
929975
];
930976

931977
const SWEEP_INPUTS: readonly ExprInput[] = [
@@ -950,7 +996,7 @@ const SWEEP_SCHEMAS: readonly (ExprSchemaHint | undefined)[] = [
950996
scope: 'record',
951997
objectName: 'deal',
952998
fields: ['amount', 'close_date', 'name', 'active', 'account', 'status'],
953-
fieldTypes: { close_date: 'date', name: 'text', active: 'boolean', account: 'lookup' },
999+
fieldTypes: { close_date: 'date', name: 'text', active: 'boolean', account: 'lookup', tags: 'multiselect' },
9541000
roleCatalog: ['org_admin', 'sales'],
9551001
optionFields: ['status'],
9561002
},

‎packages/formula/src/expression-refusal.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,22 @@ export interface ExpressionRefusalParams {
324324
* fault sentence for that call.
325325
*/
326326
'label-field-no-options': { readonly field: string };
327+
/**
328+
* [#36167] `==` / `!=` between a list-valued field read (`ExprSchemaHint.multiValueFields`,
329+
* or a `fieldTypes` type that is inherently multi) and a non-null scalar
330+
* literal: CEL compares the whole list with the scalar, so the expression
331+
* answers the same constant on every row. `reference` is the read as
332+
* `<root>.<field>`, `operand` the literal as CEL prints it, `answer` the
333+
* constant (`false` for `==`, `true` for `!=`), and `rewrite` the
334+
* null-guarded membership test that replaces the comparison.
335+
*/
336+
'list-equality': {
337+
readonly reference: string;
338+
readonly operator: '==' | '!=';
339+
readonly operand: string;
340+
readonly answer: 'false' | 'true';
341+
readonly rewrite: string;
342+
};
327343
/** `collectCelRootIdentifiers` was handed no expression. */
328344
'empty-expression': Readonly<Record<string, never>>;
329345
/** `collectCelRootIdentifiers` could not parse the source; `detail` is the parser's reason. */
@@ -395,6 +411,7 @@ const CODE_TABLE = {
395411
'traversal-bare-and-traversed': true,
396412
'traversal-multi-hop': true,
397413
'label-field-no-options': true,
414+
'list-equality': true,
398415
'empty-expression': true,
399416
'cel-parse-failed': true,
400417
} as const satisfies Record<ExpressionRefusalCode, true>;

‎packages/formula/src/relationship-traversal.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,27 @@ export function readRootMembers(ast: CelAstNode, roots: readonly string[]): Root
217217
return reads;
218218
}
219219

220+
/**
221+
* The member `node` ITSELF reads on one of `roots` — `record.tags`,
222+
* `record.?tags`, `record['tags']`, `previous[?'tags']` — or `undefined` when
223+
* `node` is anything else: a deeper read (`record.a.b`), a call, a literal, a
224+
* computed key (`record[someVar]`).
225+
*
226+
* The same {@link asMember} spellings {@link readRootMembers} collects, asked
227+
* of one node instead of gathered from a tree, for a check that judges an
228+
* OPERAND rather than every read: `validateExpression`'s list-equality pass
229+
* asks whether one side of a `==` is a field read, and gets the answer the
230+
* field-existence pass would give for the same spelling.
231+
*/
232+
export function rootMemberOf(node: unknown, roots: readonly string[]): { readonly root: string; readonly field: string } | undefined {
233+
const member = asMember(node);
234+
if (!member) return undefined;
235+
const receiver = member.receiver as { op?: unknown; args?: unknown } | null | undefined;
236+
if (!receiver || typeof receiver !== 'object') return undefined;
237+
const { op, args } = receiver;
238+
return op === 'id' && typeof args === 'string' && roots.includes(args) ? { root: args, field: member.name } : undefined;
239+
}
240+
220241
/**
221242
* Analyse one authored CEL source for the hops it takes through `root`.
222243
*

0 commit comments

Comments
 (0)