Skip to content
28 changes: 28 additions & 0 deletions .changeset/36237-hop-list-equality.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
'@objectstack/formula': minor
'@objectstack/lint': minor
'@objectstack/spec': minor
---

fix(lint)!: `==` / `!=` between a list-valued field reached through a lookup hop and a scalar is refused, as the root-field case is

Clause-②: yes (narrowing)
Metadata-protocol: narrowed
Skills-docs: none — the `objectstack-formula` skill already teaches that a list field compared with a scalar literal is refused and the `has()`-guarded `in` rewrite; a hop read of a list field takes the same rewrite

<!-- adr-0087: not-required (already-registered cel-list-equality-refused) the same list-equality refusal and membership rewrite, one hop away; this change extends that entry's surface to the one-hop read at a validation rule predicate and a field expression, and states its doors (os validate, os build, the object save door) -->

**BREAKING** accept-set narrowing, shipped as `minor`; the new `@objectstack/formula` export `findHopListEquality` widens the package's public surface.

`record.labels == 'vip'` on a list-valued field has been refused as `list-equality` since the shared validator learned it, but the same comparison one hop away, `record.account.labels == 'vip'` where `account` is a lookup and `labels` a list-valued field of its target, was refused nowhere. A validation rule's `condition` / `when` and a formula's `expression` are the two sites that serve a hop: the engine hydrates the related row, so `record.account.labels` is the stored list, and comparing it with a scalar answers `false` (for `!=`, `true`) on every row. A rule written that way never fires and saves clean.

- **The refusal.** At those two sites, the publish lint (`os validate` / `os build`) and the object save door refuse a `==` / `!=` between a read of a hop target's list-valued field (an inherently multi-value type, or a multi-capable type declared `multiple: true`) and a non-null scalar literal, either operand order, in the root case's words, prescribing the root case's membership test on the hop read.
- **What carries it.** `@objectstack/formula` exports `findHopListEquality(source, listLeaves)`, which returns the `list-equality` refusals (same code and params as `validateExpression`'s) for the reference → list-valued-leaves map its caller hands in. `ExprSchemaHint` is unchanged. The ADR-0087 entry `cel-list-equality-refused` now names the one-hop read and its doors; the Studio draft check and the shared-validator half of the MCP `validate_expression` tool do not see a hop.
- **Still accepted.** A hop to a scalar field (`record.account.tier == 'vip'`), `record.account.labels == null`, `'vip' in record.account.labels`, a hop through a reference that is itself multi-valued, and every site that serves no hop (an action's `visible`, a flow condition), where `record.account` is the stored id.

FROM → TO:

- `record.account.labels == 'vip'` → `(has(record.account.labels) && record.account.labels != null && "vip" in record.account.labels)`
- `record.account.labels != 'vip'` → `(!has(record.account.labels) || record.account.labels == null || !("vip" in record.account.labels))`

One-line fix: test membership with `in` on the hop read, guarded as the refusal prescribes.
4 changes: 4 additions & 0 deletions packages/formula/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,10 @@ export type { UnknownFunctionCall } from './unknown-function';
// ADR-0032 — shared validator + introspection (one validator for build,
// registration, and the agent-callable validate_expression tool).
export { validateExpression, introspectScope, expectedDialect, inferExpressionType, nearestName, CEL_STDLIB_FUNCTIONS } from './validate';
// [#36237] The `list-equality` refusal one relationship hop away, for the
// caller that resolves hop targets (`@objectstack/lint`): the hint describes
// the root object's fields only.
export { findHopListEquality } from './validate';
export type { FieldRole, ExprInput, ExprSchemaHint, ExprFaultOutcome, ExprValidationError, ExprValidationResult, InferredValueType } from './validate';
// #22727 — the declaration authoring stamps onto a formula field: its
// `returnType`, and for a provably-money result its currency, copied from the
Expand Down
21 changes: 21 additions & 0 deletions packages/formula/src/relationship-traversal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,27 @@ export function rootMemberOf(node: unknown, roots: readonly string[]): { readonl
return op === 'id' && typeof args === 'string' && roots.includes(args) ? { root: args, field: member.name } : undefined;
}

/**
* [#36237] The ONE-HOP read `node` itself is — `record.account.labels`,
* `record['account']['labels']`, any mix of the {@link asMember} spellings —
* as `{ root, field, leaf }`, or `undefined` when `node` is anything else: a
* read of the root's own member (`record.labels`, {@link rootMemberOf}'s
* answer), a deeper read (`record.a.b.c`), a call, a literal.
*
* {@link rootMemberOf} one segment further, for a check that judges an
* OPERAND reached through a relationship: `@objectstack/lint`'s hop pass asks
* whether one side of a `==` is a read of the hop target's field.
*/
export function hopMemberOf(
node: unknown,
roots: readonly string[],
): { readonly root: string; readonly field: string; readonly leaf: string } | undefined {
const member = asMember(node);
if (!member) return undefined;
const read = rootMemberOf(member.receiver, roots);
return read ? { ...read, leaf: member.name } : undefined;
}

/**
* Analyse one authored CEL source for the hops it takes through `root`.
*
Expand Down
90 changes: 90 additions & 0 deletions packages/formula/src/validate-hop-list-equality-36237.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [#36237] `findHopListEquality` — the `list-equality` refusal one
* relationship hop away. `record.account.labels == 'vip'`, where `account` is
* a reference and `labels` a list-valued field of its target, compares the
* whole hydrated list with the scalar: one constant on every row, the root
* case's defect (`validate-list-equality-36167.test.ts`). The hint carries the
* root object's fields only, so the caller that resolves hop targets hands
* the reference → list-valued-leaves map in.
*
* The first describe proves the premise on the evaluator, over the shape the
* hop loader binds (the related row nested under the reference field).
*/

import { describe, it, expect } from 'vitest';

import { celEngine } from './cel-engine';
import { findHopListEquality } from './validate';

/** `account` reaches a target whose `labels` is list-valued. */
const LEAVES: ReadonlyMap<string, ReadonlySet<string>> = new Map([['account', new Set(['labels'])]]);

describe('the premise — a hydrated hop to a list, compared with a scalar, is a constant', () => {
const run = (source: string, labels: unknown) =>
celEngine.evaluate({ dialect: 'cel', source }, { record: { account: { id: 'a1', labels } } });
it.each([[['vip', 'eu']], [['eu']], [[]], [null]])('labels = %j', (labels) => {
expect(run("record.account.labels == 'vip'", labels)).toEqual({ ok: true, value: false });
expect(run("record.account.labels != 'vip'", labels)).toEqual({ ok: true, value: true });
});
});

describe('findHopListEquality — refused', () => {
it.each([
["record.account.labels == 'vip'", '==', 'false'],
["'vip' != record.account.labels", '!=', 'true'],
["record['account']['labels'] == 'vip'", '==', 'false'],
["record.amount > 1 && record.account.labels != 'vip'", '!=', 'true'],
] as const)('%s, under the root case\'s code and params', (source, operator, answer) => {
const errors = findHopListEquality(source, LEAVES);
expect(errors).toHaveLength(1);
const [e] = errors;
expect(e.code).toBe('list-equality');
expect(e.code === 'list-equality' && e.params.reference).toBe('record.account.labels');
expect(e.code === 'list-equality' && e.params.operator).toBe(operator);
expect(e.code === 'list-equality' && e.params.answer).toBe(answer);
expect(e.source).toBe(source);
});

it('the prescribed rewrite answers per row on the hydrated hop, and is not itself refused', () => {
const [eq] = findHopListEquality("record.account.labels == 'vip'", LEAVES);
const [ne] = findHopListEquality("record.account.labels != 'vip'", LEAVES);
const eqRewrite = eq!.code === 'list-equality' ? eq!.params.rewrite : '';
const neRewrite = ne!.code === 'list-equality' ? ne!.params.rewrite : '';
expect(eqRewrite).toBe('(has(record.account.labels) && record.account.labels != null && "vip" in record.account.labels)');
const run = (source: string, labels: unknown) =>
celEngine.evaluate({ dialect: 'cel', source }, { record: { account: { id: 'a1', labels } } });
expect(run(eqRewrite, ['vip', 'eu'])).toEqual({ ok: true, value: true });
expect(run(eqRewrite, ['eu'])).toEqual({ ok: true, value: false });
expect(run(eqRewrite, null)).toEqual({ ok: true, value: false });
expect(run(neRewrite, ['vip'])).toEqual({ ok: true, value: false });
expect(run(neRewrite, null)).toEqual({ ok: true, value: true });
expect(findHopListEquality(eqRewrite, LEAVES)).toEqual([]);
expect(findHopListEquality(neRewrite, LEAVES)).toEqual([]);
});
});

describe('findHopListEquality — CONTROL, accepted', () => {
it.each([
// A scalar field on the same hop target.
"record.account.name == 'vip'",
"record.account.labels == null",
"'vip' in record.account.labels",
// The list-valued field of the ROOT object is the shared validator's verdict, not this one's.
"record.labels == 'vip'",
// Another reference the map does not name.
"record.parent.labels == 'vip'",
// Two hops deep is the traversal checks' refusal.
"record.account.owner.labels == 'vip'",
// A comprehension macro binding `record` holds an item, not the row.
"[{'account': {'labels': 'x'}}].exists(record, record.account.labels == 'x')",
])('%s', (source) => {
expect(findHopListEquality(source, LEAVES)).toEqual([]);
});

it('an empty map, and a source that does not compile, get no verdict', () => {
expect(findHopListEquality("record.account.labels == 'vip'", new Map())).toEqual([]);
expect(findHopListEquality("record.account.labels == 'vip' &&", LEAVES)).toEqual([]);
});
});
60 changes: 58 additions & 2 deletions packages/formula/src/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import {
type FieldCelType,
} from './cel-engine';
import { templateEngine } from './template-engine';
import { findTraversalConflicts, readRootMembers, rootMemberOf, traversalsOf, type RootMemberRead } from './relationship-traversal';
import { findTraversalConflicts, hopMemberOf, 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
Expand Down Expand Up @@ -1567,6 +1567,62 @@ function checkListEquality(
: undefined;
};
const filterCompiled = schema?.filterCompiled === true;
forEachListEquality(tree, subjectOf, (read, op, operand) => {
errors.push(listEqualityRefusal(source, read, op, operand, filterCompiled));
});
}

/**
* [#36237] {@link checkListEquality} one relationship hop away: `==` / `!=`
* between a read of a list-valued field ON A HOP TARGET
* (`record.account.labels`) and a non-null scalar literal, refused under the
* same `list-equality` code, in the root case's words and with its
* `has()`-guarded `in` prescription (`record.account.labels` is a
* `<root>.<field>` read of the related record the hop hydrates).
*
* {@link ExprSchemaHint} describes the root object's fields and no hop
* target's, so this is a function of its own for the caller that resolves hop
* targets — `@objectstack/lint`, at the two sites that serve a hop (a
* validation rule's hydrated predicate, a formula's `expression`).
* `listLeaves` maps each single-valued reference field of the root object to
* the list-valued fields its target declares; a read it does not name gets no
* verdict. Only `record` hops are judged ({@link DEFAULT_TRAVERSAL_ROOT}, the
* root a hop is served from), and a source that does not compile gets none —
* that is `validateExpression`'s `invalid-cel` verdict.
*/
export function findHopListEquality(
source: string,
listLeaves: ReadonlyMap<string, ReadonlySet<string>>,
): ExprValidationError[] {
const errors: ExprValidationError[] = [];
if (listLeaves.size === 0 || (!source.includes('==') && !source.includes('!='))) return errors;
if (!compileCel(source).result.ok) return errors;
const tree = parseCelToAst(source);
if (tree == null) return errors;
const subjectOf = (node: unknown, bound: ReadonlySet<string>): ListSubjectRead | undefined => {
const read = hopMemberOf(node, [DEFAULT_TRAVERSAL_ROOT]);
return read && !bound.has(read.root) && listLeaves.get(read.field)?.has(read.leaf)
? { reference: `${read.root}.${read.field}.${read.leaf}`, bare: false }
: undefined;
};
forEachListEquality(tree, subjectOf, (read, op, operand) => {
errors.push(listEqualityRefusal(source, read, op, operand, false));
});
return errors;
}

/**
* Every `==` / `!=` in `tree` with a list subject (`subjectOf`) on one side
* and a scalar literal ({@link scalarLiteralOf}) on the other, either order,
* handed to `onHit` once per comparison. `subjectOf` is asked with the names
* the enclosing comprehension macros bind ({@link COMPREHENSION_MACRO_NAMES}):
* the receiver is read outside the binding, the body inside it.
*/
function forEachListEquality(
tree: unknown,
subjectOf: (node: unknown, bound: ReadonlySet<string>) => ListSubjectRead | undefined,
onHit: (read: ListSubjectRead, op: '==' | '!=', operand: string) => void,
): void {
const walk = (node: unknown, bound: ReadonlySet<string>): void => {
if (!node || typeof node !== 'object') return;
if (Array.isArray(node)) {
Expand All @@ -1592,7 +1648,7 @@ function checkListEquality(
const read = subjectOf(args[side], bound);
const operand = read ? scalarLiteralOf(args[1 - side]) : undefined;
if (!read || operand === undefined) continue;
errors.push(listEqualityRefusal(source, read, op, operand, filterCompiled));
onHit(read, op, operand);
break;
}
}
Expand Down
10 changes: 10 additions & 0 deletions packages/lint/src/authored-site-expression.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,9 @@ const EXT = {

const VALIDATOR = { kind: 'validator', why: 'the shared validator: the tool runs `validateExpression` itself' } as const;
const HOP_FIELD: Fixture = { objects: [REQ, BAL], expression: 'record.balance.nope > 1', severity: 'error', names: 'nope' };
// [#36237] A list-valued field on the hop target, compared with a scalar.
const BAL_TAGS = { name: 'bal', fields: { ...BAL.fields, tags: { type: 'tags', label: 'Tags' } } };
const HOP_LIST: Fixture = { objects: [REQ, BAL_TAGS], expression: "record.balance.tags == 'x'", severity: 'error', names: 'record.balance.tags' };
const BODY_HOP: Fixture = { objects: [REQ, BAL], expression: "record.meta.name == 'x'", severity: 'error', names: 'sys_metadata' };
const ANCHOR: Fixture = { objects: [EXT], expression: "record.owner_id == 'u1'", severity: 'warning', names: 'owner_id' };
const asValue = (f: Fixture): Fixture => ({ ...f, expression: `${f.expression} ? 1 : 0` });
Expand All @@ -206,6 +209,7 @@ const SITE_CALLS: Record<ObjectSite, Record<string, Classified>> = {
isBareReferenceToAny: { kind: 'plumbing', why: "filters the shared validator's findings on a field-rule slot" },
refuseStoredMetadataBodyHop: { kind: 'pass', fixture: BODY_HOP },
refuseUndeclaredHopField: { kind: 'pass', fixture: HOP_FIELD },
refuseHopListEquality: { kind: 'pass', fixture: HOP_LIST },
warnUnprovisionedAnchors: { kind: 'pass', fixture: ANCHOR },
atSlot: { kind: 'plumbing', why: "sets the judged slot's key path on the findings" },
celSourceOf: { kind: 'plumbing', why: 'reads the CEL source off the slot' },
Expand All @@ -231,6 +235,7 @@ const SITE_CALLS: Record<ObjectSite, Record<string, Classified>> = {
celSourceOf: { kind: 'plumbing', why: 'reads the CEL source off the field' },
refuseStoredMetadataBodyHop: { kind: 'pass', fixture: asValue(BODY_HOP) },
refuseUndeclaredHopField: { kind: 'pass', fixture: asValue(HOP_FIELD) },
refuseHopListEquality: { kind: 'pass', fixture: asValue(HOP_LIST) },
// [#35356] ADR-0157 D4: a working-day call whose calendar code is not a quoted literal.
computedCalendarCodeMessage: {
kind: 'pass',
Expand Down Expand Up @@ -547,6 +552,11 @@ const FLOW_CALLS: Record<string, FlowClassified> = {
why: 'runs only where a relationship hop is hydrated (a rule condition, a formula); nothing hydrates one at a flow condition',
fixture: { objects: [FLOW_OBJ, BAL], expression: 'record.balance.nope > 1' },
},
refuseHopListEquality: {
kind: 'pass-silent-here',
why: 'runs only where a relationship hop is hydrated (a rule condition, a formula); nothing hydrates one at a flow condition',
fixture: { objects: [FLOW_OBJ, BAL_TAGS], expression: "record.balance.tags == 'x'" },
},
};

/** The start node of a hand-written flow on `obj`, with the trigger `kind` names. */
Expand Down
Loading
Loading