Skip to content

Commit 53c5a49

Browse files
committed
feat(lint): accept the gate a field group's requiresFeature lowers to; book it in the feature registry
Claude-Session: https://claude.ai/code/session_016WV4cyCnzVPr9GuD38DdGt Co-authored-by: Claude <noreply@anthropic.com>
1 parent 27b3ced commit 53c5a49

5 files changed

Lines changed: 160 additions & 11 deletions

File tree

‎packages/lint/src/runtime-gate.object-field-group-visibility-writes.test.ts‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
import { describe, expect, it } from 'vitest';
3131
import { EXPRESSION_INVALID, runAuthoringRules } from './authoring-rules.js';
3232
import { runRuntimeAuthoringRules, runtimeAuthoringRulesFor } from './runtime-gate.js';
33+
import { validateStackExpressions } from './validate-expressions.js';
3334

3435
/**
3536
* The card's probe object, verbatim but for the predicate: `stage` sits in
@@ -165,3 +166,71 @@ describe('#26646 — the object door gives the build\'s field group `visibleWhen
165166
expect(expressionFindings(result.errors), dump(result)).toEqual([]);
166167
});
167168
});
169+
170+
/**
171+
* #30692 — a field group's `requiresFeature` (ruling 6670372892 on #30210, row
172+
* 4 A). The spec lowers it at parse into the group's `visibleWhen` as the
173+
* flag's gate alone, or `(<authored>) && <gate>`, and both renderers bind the
174+
* host's `features` root for that predicate. The root verdict accepts exactly
175+
* that trailing gate; any other `features.*` read in a group predicate keeps
176+
* the verdict it had.
177+
*/
178+
describe('#30692 — the build and the object door accept the gate a group\'s `requiresFeature` lowers to', () => {
179+
const GATE = 'features.multiOrgEnabled != false';
180+
const LOWERED = [
181+
{ dialect: 'cel', source: GATE },
182+
{ dialect: 'cel', source: `(record.stage == 'won') && ${GATE}` },
183+
// The opt-in spelling of another flag of the same registry.
184+
{ dialect: 'cel', source: '(record.stage == \'won\') && features.twoFactor == true' },
185+
] as const;
186+
187+
for (const body of LOWERED) {
188+
it(`⭐ CONTROL — the lowered \`${body.source}\` publishes clean, and the build agrees`, () => {
189+
const result = gateObject(fxGroup(body));
190+
191+
expect(result.rulesRun).toContain('validateStackExpressions');
192+
expect(expressionFindings(result.errors), dump(result)).toEqual([]);
193+
expect(expressionFindings(result.advisories), dump(result)).toEqual([]);
194+
expect(buildFindings(fxGroup(body))).toEqual([]);
195+
});
196+
}
197+
198+
it('⭐ CONTROL — the unlowered key itself publishes clean (a door that judges the item before parse)', () => {
199+
const item = { ...fxGroup(undefined), fieldGroups: [{ key: 'g1', label: 'G1', requiresFeature: 'multiOrgEnabled' }] };
200+
expect(expressionFindings(gateObject(item).errors), dump(item)).toEqual([]);
201+
expect(buildFindings(item)).toEqual([]);
202+
});
203+
204+
const STILL_REFUSED = [
205+
// A gate that is not the flag's canonical one.
206+
'features.multiOrgEnabled == true',
207+
// The gate first: not the lowering's shape.
208+
`${GATE} && record.stage == 'won'`,
209+
// The authored part reads another root the group does not bind.
210+
`('org_admin' in current_user.positions) && ${GATE}`,
211+
// Two groups, not one: the part before the gate is \`record.stage == 'a') && (features.organization != false\`.
212+
`(record.stage == 'a') && (features.organization != false) && ${GATE}`,
213+
// A flag outside the registry.
214+
'(record.stage == \'won\') && features.notAFlag != false',
215+
] as const;
216+
217+
for (const body of STILL_REFUSED) {
218+
it(`⭐ LIT — \`${body}\` keeps its root verdict`, () => {
219+
const errs = expressionFindings(gateObject(fxGroup(body)).errors);
220+
expect(errs, dump(errs)).toHaveLength(1);
221+
expect(errs[0]).toMatchObject({ severity: 'error', where: WHERE });
222+
expect(errs[0]!.message).toMatch(/^`visibleWhen` reads `(features|current_user)`/);
223+
// The build's issue quotes the whole predicate the group carries, not the
224+
// part the root verdict judged.
225+
const issues = validateStackExpressions({ objects: [fxGroup(body)] }).filter((i) => i.where === WHERE);
226+
expect(issues.map((i) => i.source)).toEqual([body]);
227+
expect(buildFindings(fxGroup(body))).toEqual(errs);
228+
});
229+
}
230+
231+
it('a hand-written `features` read on a group is pointed at `requiresFeature`', () => {
232+
const errs = expressionFindings(gateObject(fxGroup('features.multiOrgEnabled == true')).errors);
233+
expect(errs, dump(errs)).toHaveLength(1);
234+
expect(errs[0]!.message).toContain("`requiresFeature: 'FLAG'`");
235+
});
236+
});

‎packages/lint/src/validate-expressions.ts‎

Lines changed: 57 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,12 @@ import type { FlowNodeParsed, FlowEdgeParsed, FlowTriggerKind } from '@objectsta
135135
// shared refusal to prevent.
136136
import { EvaluatedExpressionInputSchema, EVALUATED_EXPRESSION_SOURCE_REQUIRED } from '@objectstack/spec/shared';
137137
import { referenceCarrierOf, referenceTargetOf, REFERENCE_VALUE_TYPES } from '@objectstack/spec/data';
138-
import { isStoredMetadataBodyObject, STORED_METADATA_BODY_PRESCRIPTION } from '@objectstack/spec/kernel';
138+
import {
139+
isStoredMetadataBodyObject,
140+
STORED_METADATA_BODY_PRESCRIPTION,
141+
PUBLIC_AUTH_FEATURE_NAMES,
142+
featureGatePredicate,
143+
} from '@objectstack/spec/kernel';
139144
// [#22394] The acting user's declared members — the contract half of the option
140145
// verdict's member allowlist for `current_user` and its ADR-0068 aliases. Read
141146
// off the schema at first use, never restated here.
@@ -1023,6 +1028,43 @@ const FIELD_RULE_USER_ROOTS = ['current_user', 'user', 'ctx', 'os'] as const;
10231028
* and worded for it ({@link FIELD_RULE_SLOT_CONSEQUENCE}, {@link fieldRuleRootIssue}).
10241029
*/
10251030
const FIELD_GROUP_VISIBLE_WHEN_SLOT = 'field group visibleWhen';
1031+
1032+
/**
1033+
* [#30692] A field group's `visibleWhen` with the gate its `requiresFeature`
1034+
* lowered into it taken off, so the root verdict judges what the AUTHOR wrote.
1035+
*
1036+
* `fieldGroups[].requiresFeature` (`ObjectFieldGroupSchema`) is lowered at
1037+
* parse by the spec's `lowerRequiresFeature` into one of exactly two shapes —
1038+
* the gate alone, or `(<authored>) && <gate>` — where the gate is
1039+
* `featureGatePredicate(flag)` for a flag of `PUBLIC_AUTH_FEATURES`. Both
1040+
* renderers evaluate a group's predicate with the host's `features` root in
1041+
* scope (the form's section gate and the record page's `record:details`), so
1042+
* that gate is enforced where it is read; it is the ruled shape (#30210 row 4
1043+
* A, ruling 6670372892), and only it is accepted. A `features.*` read anywhere
1044+
* else in the predicate keeps its root verdict: this takes off the trailing
1045+
* gate the lowering appends, and nothing more.
1046+
*
1047+
* Returns `undefined` when the whole predicate is the gate (nothing authored
1048+
* left to judge), the authored part in the input's own spelling when the gate
1049+
* was composed onto one, and the input untouched otherwise — including when
1050+
* the part before the gate does not parse on its own, which is how a
1051+
* hand-written `(a) && (b) && <gate>` (whose "authored part" would be
1052+
* `a) && (b`) is told apart from the lowering's single parenthesised group.
1053+
*/
1054+
export function withoutLoweredFeatureGate(raw: unknown): unknown {
1055+
const source = celSourceOf(raw);
1056+
if (source === undefined) return raw;
1057+
for (const flag of PUBLIC_AUTH_FEATURE_NAMES) {
1058+
const gate = featureGatePredicate(flag);
1059+
if (source === gate) return undefined;
1060+
const tail = `) && ${gate}`;
1061+
if (!source.startsWith('(') || !source.endsWith(tail)) continue;
1062+
const authored = source.slice(1, source.length - tail.length);
1063+
if (!collectCelRootIdentifiers(authored).ok) return raw;
1064+
return typeof raw === 'string' ? authored : { ...(raw as AnyRec), source: authored };
1065+
}
1066+
return raw;
1067+
}
10261068
/**
10271069
* The slot-agnostic clause — provably true for any slot, specific to none.
10281070
* Used where the honest answer is "not measured for this slot", never as a
@@ -1120,7 +1162,15 @@ export function fieldRuleRootIssue(
11201162
// [#26646] A field group has no options and is not a field: its user-root
11211163
// prescription keeps only the two answers that apply to it.
11221164
const userRoot = (FIELD_RULE_USER_ROOTS as readonly string[]).includes(root);
1123-
const prescription = userRoot && slot === FIELD_GROUP_VISIBLE_WHEN_SLOT
1165+
const prescription = root === 'features' && slot === FIELD_GROUP_VISIBLE_WHEN_SLOT
1166+
// [#30692] A field group has its own door for a deployment feature: the
1167+
// `requiresFeature` key, whose lowered gate this rule accepts.
1168+
? `To show the group only where a deployment feature is on, declare it on the group ` +
1169+
`instead — \`requiresFeature: 'FLAG'\`, the same flag names an action's \`requiresFeature\` ` +
1170+
`takes — and keep \`visibleWhen\` for record state; the gate it lowers to is the one ` +
1171+
`\`features\` read this predicate accepts. To gate the group on record state, rewrite the ` +
1172+
`predicate against \`record\`.`
1173+
: userRoot && slot === FIELD_GROUP_VISIBLE_WHEN_SLOT
11241174
? `To hide the group's fields by role, declare field-level security on a permission set ` +
11251175
`for each field in the group (\`fields: { 'OBJECT.FIELD': { readable: false } }\`), which ` +
11261176
`the server enforces. To gate the group on record state, rewrite the predicate against ` +
@@ -3830,10 +3880,13 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression
38303880
const groupKey = typeof fieldGroup.key === 'string' ? fieldGroup.key : '?';
38313881
const where = `object '${objectName}' · field group '${groupKey}' visibleWhen`;
38323882
const raw: unknown = fieldGroup.visibleWhen;
3833-
const verdict = fieldRuleRootVerdict(FIELD_GROUP_VISIBLE_WHEN_SLOT, raw);
3883+
// [#30692] The root verdict judges the predicate without the gate a
3884+
// `requiresFeature` lowered into it ({@link withoutLoweredFeatureGate});
3885+
// every other check still reads the whole predicate.
3886+
const verdict = fieldRuleRootVerdict(FIELD_GROUP_VISIBLE_WHEN_SLOT, withoutLoweredFeatureGate(raw));
38343887
check(where, raw, objectName, 'record', verdict !== null);
38353888
if (verdict) {
3836-
issues.push({ where, message: verdict.message, source: verdict.source, severity: 'error' });
3889+
issues.push({ where, message: verdict.message, source: celSourceOf(raw) ?? verdict.source, severity: 'error' });
38373890
}
38383891
}
38393892
}

‎packages/platform-objects/src/feature-gate-guard.test.ts‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@
2626
* only checks it is booked, and its verdicts are pinned in
2727
* `identity/sys-user-create-user-email-required.test.ts`.
2828
*
29+
* A field group's `visibleWhen` is the third site (#30692): a group declaring
30+
* `requiresFeature` is lowered there, booked as `<object>.fieldGroups.<key>`,
31+
* and walked in both directions like an action.
32+
*
2933
* Scope notes: objects that moved to capability plugins per ADR-0029 K2
3034
* (plugin-security / plugin-sharing / plugin-audit / service-realtime /
3135
* plugin-webhooks) are outside this package and this guard; none of them
@@ -48,7 +52,8 @@ import * as system from './system/index.js';
4852

4953
type AnyParam = { name?: string; field?: string; visible?: { source?: string } };
5054
type AnyAction = { name?: string; visible?: { source?: string }; params?: AnyParam[] };
51-
type AnyObject = { name?: string; actions?: AnyAction[] };
55+
type AnyGroup = { key?: string; visibleWhen?: { source?: string } };
56+
type AnyObject = { name?: string; actions?: AnyAction[]; fieldGroups?: AnyGroup[] };
5257

5358
// Every exported platform object, keyed by machine name (object.name).
5459
const objectsByName = new Map<string, AnyObject>();
@@ -138,8 +143,20 @@ function carriesGateConjunct(source: string, gate: string): boolean {
138143
return conjuncts(source).some((conjunct) => conjunct === gate);
139144
}
140145

141-
/** Resolve `<object>.actions.<action>[.params.<name|field>]` to its `visible`. */
146+
/**
147+
* Resolve `<object>.actions.<action>[.params.<name|field>]` to its `visible`,
148+
* or `<object>.fieldGroups.<key>` to that group's `visibleWhen`.
149+
*/
142150
function resolveGatedInput(path: string): { visibleSource: string | undefined } {
151+
const groupMatch = /^([a-z0-9_]+)\.fieldGroups\.([a-z0-9_]+)$/.exec(path);
152+
if (groupMatch) {
153+
const [, objectName, groupKey] = groupMatch;
154+
const object = objectsByName.get(objectName);
155+
expect(object, `object exists: ${path}`).toBeDefined();
156+
const group = (object!.fieldGroups ?? []).find((g) => g.key === groupKey);
157+
expect(group, `field group exists: ${path}`).toBeDefined();
158+
return { visibleSource: group!.visibleWhen?.source };
159+
}
143160
const match = /^([a-z0-9_]+)\.actions\.([a-z0-9_]+)(?:\.params\.([A-Za-z0-9_]+))?$/.exec(path);
144161
expect(match, `path grammar: ${path}`).not.toBeNull();
145162
const [, objectName, actionName, paramName] = match!;
@@ -219,6 +236,11 @@ describe('feature-gate completeness guard (#2874)', () => {
219236
}
220237
}
221238
}
239+
for (const group of object.fieldGroups ?? []) {
240+
for (const m of (group.visibleWhen?.source ?? '').matchAll(/features\.([A-Za-z0-9_]+)/g)) {
241+
referencedInputs.push([`${objectName}.fieldGroups.${group.key}`, m[1]]);
242+
}
243+
}
222244
}
223245

224246
it('finds the gated surface (guards the walker itself)', () => {

‎packages/spec/src/kernel/public-auth-features.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,8 @@ describe('PUBLIC_AUTH_FEATURES registry', () => {
5757
expect(hasGates !== hasExempt, 'exactly one of gatedInputs / exempt must be set').toBe(true);
5858
});
5959

60-
it('gatedInputs paths follow the <object>.actions.<action>[.params.<name>] grammar', () => {
61-
const PATH = /^[a-z][a-z0-9_]*\.actions\.[a-z][a-z0-9_]*(\.params\.[A-Za-z][A-Za-z0-9_]*)?$/;
60+
it('gatedInputs paths follow the <object>.actions.<action>[.params.<name>] | <object>.fieldGroups.<key> grammar', () => {
61+
const PATH = /^[a-z][a-z0-9_]*\.(actions\.[a-z][a-z0-9_]*(\.params\.[A-Za-z][A-Za-z0-9_]*)?|fieldGroups\.[a-z_][a-z0-9_]*)$/;
6262
for (const [name, entry] of entries) {
6363
for (const path of entry.gatedInputs ?? []) {
6464
expect(path, `${name}: ${path}`).toMatch(PATH);

‎packages/spec/src/kernel/public-auth-features.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,10 +75,12 @@ export type PublicAuthFeatureEntry = {
7575
semantics: PublicAuthFeatureSemantics;
7676
/**
7777
* Spec inputs gated on this flag. Path grammar:
78-
* `<object>.actions.<action>` or `<object>.actions.<action>.params.<name|field>`.
78+
* `<object>.actions.<action>`, `<object>.actions.<action>.params.<name|field>`,
79+
* or `<object>.fieldGroups.<key>` for an object's field group (whose
80+
* predicate slot is `visibleWhen`).
7981
* The platform-objects completeness guard resolves each path and asserts the
80-
* target's `visible` predicate carries {@link featureGatePredicate} as a
81-
* conjunct. A param path resolves to the FIRST param on that name or field;
82+
* target's `visible` (a field group's `visibleWhen`) predicate carries
83+
* {@link featureGatePredicate} as a conjunct. A param path resolves to the FIRST param on that name or field;
8284
* further params on the same field that reference the flag are booked by the
8385
* same path, whatever their gate (see `phoneNumber`).
8486
* Mutually exclusive with `exempt`.
@@ -159,6 +161,9 @@ export const PUBLIC_AUTH_FEATURES = {
159161
'sys_organization.actions.delete_organization',
160162
'sys_organization.actions.set_active_organization',
161163
'sys_organization.actions.leave_organization',
164+
// Parent Organization and Sort Order: they order and group organizations
165+
// against each other, so Edit organization hides them on one organization.
166+
'sys_organization.fieldGroups.group_structure',
162167
],
163168
notes:
164169
'Reflects ACTUAL multi-tenancy capability (the tenancy posture enforces ' +

0 commit comments

Comments
 (0)