From b865e8f7d08f7db16e24a604e84f8a193f92b886 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 01:58:10 +0000 Subject: [PATCH 1/3] test(lint,metadata-protocol): pin the field-rule option-label refusal (red) A field's requiredWhen, readonlyWhen and visibleWhen, and an option's visibleWhen, that compare a choice field with an option label save today and never apply. Pins at the lint rule (each slot, negated comparands, extensions, the build/door parity, what is not judged) and at the real saveMetaItem door on object and object_extension writes. Red until the rule lands. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvqcHrQpENbRP7eLfU --- ...date-validation-rule-option-labels.test.ts | 225 +++++++++++++++ ...tocol.field-rule-option-label-gate.test.ts | 257 ++++++++++++++++++ 2 files changed, 482 insertions(+) create mode 100644 packages/metadata-protocol/src/protocol.field-rule-option-label-gate.test.ts diff --git a/packages/lint/src/validate-validation-rule-option-labels.test.ts b/packages/lint/src/validate-validation-rule-option-labels.test.ts index 87bb922bcea..8c8a814cdbe 100644 --- a/packages/lint/src/validate-validation-rule-option-labels.test.ts +++ b/packages/lint/src/validate-validation-rule-option-labels.test.ts @@ -20,6 +20,7 @@ import { describe, expect, it } from 'vitest'; import { runAuthoringRules } from './authoring-rules.js'; import { runRuntimeAuthoringRules, runtimeAuthoringRulesFor } from './runtime-gate.js'; import { + FIELD_RULE_OPTION_LABEL, VALIDATION_CONDITION_OPTION_LABEL, validateValidationRuleOptionLabels, } from './validate-validation-rule-option-labels.js'; @@ -251,3 +252,227 @@ describe('#39441 — a stored object the publish door already holds', () => { expect(labelFindings(atObjectDoor(ticket([rule(VALUE)]), [sibling]).errors)).toEqual([]); }); }); + +/** + * [#39722] The same reading over a field's own rules, reported as + * `field-rule-option-label`: a field's `requiredWhen`, `readonlyWhen` and + * `visibleWhen`, and each option's `visibleWhen`. The server evaluates each of + * them against the stored row merged with the payload (`rule-validator.ts`), + * where a choice field holds the option VALUE, so a label comparand never + * equals it. Same module and registry entry as the validation-rule check; the + * protocol-level half is + * `packages/metadata-protocol/src/protocol.field-rule-option-label-gate.test.ts`. + */ +describe('#39722 — a field rule comparing a choice field with an option label', () => { + const PRIORITY = { + type: 'select', + label: 'Priority', + options: [{ label: 'Urgent', value: 'urgent' }, { label: 'Low', value: 'low' }], + }; + + /** `sharingModel` keeps `security-owd-unset` quiet, so a refusal is this rule's. */ + const fxTicket = (fields: Record) => ({ + name: 'fx_ticket', + label: 'Ticket', + sharingModel: 'private', + fields: { name: { type: 'text', label: 'Name' }, priority: PRIORITY, ...fields }, + }); + + const note = (rules: Record) => ({ note: { type: 'text', label: 'Note', ...rules } }); + + const fieldLabelFindings = (fs: readonly T[]): T[] => + fs.filter((f) => f.rule === FIELD_RULE_OPTION_LABEL); + + const atFieldObjectDoor = (item: unknown, objects: unknown[] = []) => + runRuntimeAuthoringRules({ type: 'object', item, context: { objects } }); + + const atFieldBuild = (stack: Record) => + fieldLabelFindings(runAuthoringRules('build', { normalized: stack, parsed: stack })); + + const dumpField = (r: unknown) => JSON.stringify(r, null, 2); + + describe('#39722 — the doors that save fields run the label check on field rules', () => { + it('rides the #39441 entry: on the object and object_extension publish doors, and on all three CLI commands', () => { + for (const type of ['object', 'object_extension']) { + expect(runtimeAuthoringRulesFor(type).map((r) => r.name)).toContain('validateValidationRuleOptionLabels'); + } + for (const command of ['build', 'validate', 'lint'] as const) { + const stack = { objects: [fxTicket(note({ requiredWhen: "record.priority == 'Urgent'" }))] }; + expect(fieldLabelFindings(runAuthoringRules(command, { normalized: stack, parsed: stack }))).toHaveLength(1); + } + }); + + it('⭐ each of the four slots comparing a choice field with an option label is REFUSED at the object door, naming the value', () => { + const body = fxTicket({ + ...note({ + requiredWhen: "record.priority == 'Urgent'", + readonlyWhen: "record.priority != 'Low'", + visibleWhen: "record.priority in ['Urgent']", + }), + channel: { + type: 'select', + label: 'Channel', + options: [ + { label: 'Phone', value: 'phone', visibleWhen: "'Urgent' == record.priority" }, + { label: 'Mail', value: 'mail' }, + ], + }, + }); + const result = atFieldObjectDoor(body); + + const errs = fieldLabelFindings(result.errors); + expect(errs.map((f) => [f.where, f.path]), dumpField(result)).toEqual([ + ["object 'fx_ticket' · field 'note' requiredWhen", 'objects.fx_ticket.fields.note.requiredWhen'], + ["object 'fx_ticket' · field 'note' readonlyWhen", 'objects.fx_ticket.fields.note.readonlyWhen'], + ["object 'fx_ticket' · field 'note' visibleWhen", 'objects.fx_ticket.fields.note.visibleWhen'], + ["object 'fx_ticket' · field 'channel' · option 'phone' visibleWhen", 'objects.fx_ticket.fields.channel.options[0].visibleWhen'], + ]); + for (const f of errs) { + expect(f.severity).toBe('error'); + expect(f.message).toContain("compares 'fx_ticket.priority' with '"); + expect(f.hint).toMatch(/^Compare with the option's value: write '(urgent|low)' in place of '(Urgent|Low)'$/); + } + // Each slot names what the label does to it, in both directions. + expect(errs[0]!.message).toContain('the field is never required'); + expect(errs[1]!.message).toContain('the field is never locked'); + expect(errs[2]!.message).toContain('the field is never shown'); + expect(errs[3]!.message).toContain('the option is never offered'); + }); + + it('⭐ an object_extension publish whose added field compares the target\'s choice field with a label is REFUSED at the entry', () => { + const entry = { extend: 'fx_ticket', fields: note({ requiredWhen: "previous.priority == 'Low'" }) }; + const result = runRuntimeAuthoringRules({ + type: 'object_extension', + item: entry, + context: { objects: [fxTicket({})] }, + }); + + const errs = fieldLabelFindings(result.errors); + expect(errs, dumpField(result)).toHaveLength(1); + expect(errs[0]).toMatchObject({ + severity: 'error', + rule: FIELD_RULE_OPTION_LABEL, + where: "object 'fx_ticket' · objectExtensions[0] · field 'note' requiredWhen", + path: 'objectExtensions[0].fields.note.requiredWhen', + }); + expect(errs[0]!.hint).toContain("write 'low' in place of 'Low'"); + }); + + it('an extension write is not charged with a label the target\'s own stored field rule carries', () => { + const entry = { extend: 'fx_ticket', fields: note({ requiredWhen: "record.priority == 'urgent'" }) }; + const stored = fxTicket({ other: { type: 'text', label: 'Other', readonlyWhen: "record.priority == 'Urgent'" } }); + const result = runRuntimeAuthoringRules({ type: 'object_extension', item: entry, context: { objects: [stored] } }); + expect(fieldLabelFindings(result.errors), dumpField(result)).toEqual([]); + }); + + it('the build refuses the same field rule with the door\'s finding (rule, location, message, hint)', () => { + const body = fxTicket(note({ readonlyWhen: "record.priority == 'Urgent'" })); + const door = fieldLabelFindings(atFieldObjectDoor(body).errors); + expect(door).toHaveLength(1); + expect(atFieldBuild({ objects: [body] })).toEqual(door); + }); + + it('a field rule finding never carries the validation-rule id, and a validation-rule finding never this one', () => { + const body = { + ...fxTicket(note({ requiredWhen: "record.priority == 'Urgent'" })), + validations: [{ name: 'v', type: 'script', condition: "record.priority == 'Urgent'", message: 'm' }], + }; + const ids = validateValidationRuleOptionLabels({ objects: [body] }).map((f) => `${f.rule} ${f.path}`); + expect(ids).toEqual([ + `${VALIDATION_CONDITION_OPTION_LABEL} objects.fx_ticket.validations.v.condition`, + `${FIELD_RULE_OPTION_LABEL} objects.fx_ticket.fields.note.requiredWhen`, + ]); + }); + }); + + describe('#39722 — what is refused and what saves', () => { + it('the VALUE comparand saves, in every slot', () => { + const body = fxTicket({ + ...note({ + requiredWhen: "record.priority == 'urgent'", + readonlyWhen: "record.priority != 'low'", + visibleWhen: "record.priority in ['urgent']", + }), + channel: { type: 'select', label: 'Channel', options: [{ label: 'Phone', value: 'phone', visibleWhen: "record.priority == 'urgent'" }] }, + }); + expect(fieldLabelFindings(atFieldObjectDoor(body).errors)).toEqual([]); + expect(atFieldBuild({ objects: [body] })).toEqual([]); + }); + + it('⭐ the negated comparands are refused with the opposite consequence named', () => { + const cases: Array<[string, string]> = [ + ['requiredWhen', 'required on every write'], + ['readonlyWhen', 'locked on every row'], + ['visibleWhen', 'shown on every row'], + ]; + for (const [slot, consequence] of cases) { + const errs = fieldLabelFindings(atFieldObjectDoor(fxTicket(note({ [slot]: "record.priority != 'Urgent'" }))).errors); + expect(errs, slot).toHaveLength(1); + expect(errs[0]!.message, slot).toContain(consequence); + } + }); + + it('a `parent.F` read is not judged: it is another object\'s field', () => { + const body = fxTicket(note({ readonlyWhen: "parent.priority == 'Urgent'", requiredWhen: "parent.priority != 'Low'" })); + expect(fieldLabelFindings(atFieldObjectDoor(body).errors)).toEqual([]); + }); + + it('a non-choice field compared with the same text is untouched', () => { + expect(fieldLabelFindings(atFieldObjectDoor(fxTicket(note({ requiredWhen: "record.name == 'Urgent'" }))).errors)).toEqual([]); + }); + + it('a label that is also some option\'s value, a readonly choice field, a picklist-bound one and a non-CEL dialect are not judged', () => { + const body = fxTicket({ + tier: { type: 'radio', label: 'Tier', options: [{ label: 'gold', value: 'silver' }, { label: 'Silver', value: 'gold' }] }, + stage: { type: 'select', label: 'Stage', readonly: true, options: [{ label: 'Done', value: 'done' }] }, + region: { type: 'select', label: 'Region', picklist: 'regions', options: [{ label: 'North', value: 'north' }] }, + a: { type: 'text', label: 'A', requiredWhen: "record.tier == 'gold'" }, + b: { type: 'text', label: 'B', requiredWhen: "record.stage == 'Done'" }, + c: { type: 'text', label: 'C', requiredWhen: "record.region == 'North'" }, + d: { type: 'text', label: 'D', requiredWhen: { dialect: 'js', source: "record.priority == 'Urgent'" } }, + }); + expect(fieldLabelFindings(validateValidationRuleOptionLabels({ objects: [body] }))).toEqual([]); + }); + + it('the CEL envelope spelling is judged as the bare string is', () => { + const body = fxTicket(note({ requiredWhen: { dialect: 'cel', source: "record.priority == 'Urgent'" } })); + expect(fieldLabelFindings(validateValidationRuleOptionLabels({ objects: [body] })).map((f) => f.path)).toEqual([ + 'objects.fx_ticket.fields.note.requiredWhen', + ]); + }); + + it('the array spelling of `fields` is located by each field\'s name', () => { + const body = { + name: 'fx_ticket', + label: 'Ticket', + sharingModel: 'private', + fields: [{ name: 'priority', ...PRIORITY }, { name: 'note', type: 'text', label: 'Note', readonlyWhen: "record.priority == 'Low'" }], + }; + expect(fieldLabelFindings(validateValidationRuleOptionLabels({ objects: [body] })).map((f) => f.path)).toEqual([ + 'objects.fx_ticket.fields.note.readonlyWhen', + ]); + }); + }); + + describe('#39722 — a stored object the publish door already holds', () => { + /** + * The door's standing differential (`runtime-gate.ts`, "What 'added' + * means"): a finding located on the WRITTEN item is this write's whatever its + * stored self held. A field rule has no `active: false`; writing the value or + * dropping the predicate is the way to republish. + */ + it('a re-publish that leaves the label field rule unchanged is judged; writing the value republishes clean', () => { + const stored = fxTicket(note({ requiredWhen: "record.priority == 'Urgent'" })); + const relabelled = { ...fxTicket(note({ requiredWhen: "record.priority == 'Urgent'" })), label: 'Support Ticket' }; + expect(fieldLabelFindings(atFieldObjectDoor(relabelled, [stored]).errors)).toHaveLength(1); + + const fixed = { ...fxTicket(note({ requiredWhen: "record.priority == 'urgent'" })), label: 'Support Ticket' }; + expect(fieldLabelFindings(atFieldObjectDoor(fixed, [stored]).errors)).toEqual([]); + }); + + it('another stored object\'s label field rule is never charged to this write', () => { + const sibling = { ...fxTicket(note({ requiredWhen: "record.priority == 'Urgent'" })), name: 'fx_other' }; + expect(fieldLabelFindings(atFieldObjectDoor(fxTicket({}), [sibling]).errors)).toEqual([]); + }); + }); +}); diff --git a/packages/metadata-protocol/src/protocol.field-rule-option-label-gate.test.ts b/packages/metadata-protocol/src/protocol.field-rule-option-label-gate.test.ts new file mode 100644 index 00000000000..203febbd761 --- /dev/null +++ b/packages/metadata-protocol/src/protocol.field-rule-option-label-gate.test.ts @@ -0,0 +1,257 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#39722] The object save door refuses a field rule that compares a choice + * field with an option LABEL, naming the value to write + * (`field-rule-option-label`, `@objectstack/lint` + * `validate-validation-rule-option-labels.ts`). The slots: a field's + * `requiredWhen`, `readonlyWhen` and `visibleWhen`, and each option's + * `visibleWhen`. No code here moves: the rule rides the registry entry that + * already declares `object` and `object_extension`, the entry this door + * filters. The rule's reach (each slot, negated comparands, extensions, what is + * not judged) is pinned beside it in `@objectstack/lint`; this file pins the + * real door's envelope, through `saveMetaItem`, on both write types. + * + * Measured on `origin/main` before the rule: each body below saved, and the + * field rule never applied, because a choice field stores the option value and + * the server evaluates the rule against the stored row (`rule-validator.ts`). + * + * Harness: the stateful `sys_metadata` double of + * `protocol.unknown-picklist-binding-refusal.test.ts`, kept local, with a + * registry whose live object universe the test states. + * + * ⚠️ This package reaches `@objectstack/lint` through its built `dist/`. + */ +// Pays the lint root's first load at collection, never inside a clocked case. +import './lint-root-preload.testkit.js'; +import { describe, expect, it } from 'vitest'; +import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; +import { ObjectStackProtocolImplementation } from './protocol.js'; + +interface Row { + id: string; + type: string; + name: string; + organization_id: string | null; + package_id: string | null; + state: string; + metadata: string; +} + +const PKG = 'app.fieldruleprobe'; +const RULE_ID = 'field-rule-option-label'; + +/** ADR-0048 overlay key — (type, name, org, state, package_id). */ +const keyOf = (w: Record) => + `${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}|${w.package_id ?? '__nopkg__'}`; + +/** Top-level eq + `$or` + `$in` + explicit-NULL, the subset these paths emit. */ +function matchesWhere(r: Row, where: Record): boolean { + for (const [k, v] of Object.entries(where)) { + if (k === '$or') { + if (!(v as Array>).some((c) => matchesWhere(r, c))) return false; + continue; + } + if (v === undefined) continue; + const actual = (r as unknown as Record)[k]; + if (v !== null && typeof v === 'object' && Array.isArray((v as { $in?: unknown }).$in)) { + if (!(v as { $in: unknown[] }).$in.includes(actual)) return false; + continue; + } + if (v === null ? actual !== null && actual !== undefined : actual !== v) return false; + } + return true; +} + +/** A protocol over a stateful double; `objects` is the live object universe the registry serves. */ +function makeSession(objects: Array> = []) { + const rows = new Map(); + const history: Array> = []; + let nextId = 0; + const findRow = (w: Record): { key: string; row: Row } | null => { + if (w.id !== undefined) { + for (const [k, r] of rows) if (r.id === w.id) return { key: k, row: r }; + return null; + } + for (const [k, r] of rows) if (matchesWhere(r, w)) return { key: k, row: r }; + return null; + }; + const registry: any = { + registerItem: () => {}, + registerObject: () => {}, + listItems: (type: string) => (type === 'object' ? objects : []), + getItem: () => undefined, + getAllObjects: () => objects, + // The objects an `object_extension` may extend. + getObject: (name: string) => objects.find((o) => o.name === name), + // An installed authored base that declares no namespace. + getPackage: (id: string) => (id === PKG ? { manifest: { id } } : undefined), + getArtifactItem: () => undefined, + isPackageDisabled: () => false, + }; + const engine: any = { + async findOne(table: string, o: { where: Record }) { + assertEngineFindOnePredicate(table, o); + if (table === 'sys_metadata_history') { + return history.find((h) => Object.entries(o.where).every(([k, v]) => { + if (k.startsWith('$')) throw new Error(`history double: unsupported operator ${k}`); + return v === undefined || h[k] === v; + })) ?? null; + } + if (table !== 'sys_metadata') return null; + return findRow(o.where)?.row ?? null; + }, + async find(table: string, o?: { where?: Record; limit?: number }) { + if (table !== 'sys_metadata') return []; + // `check:objectql-double-limit` — the caller's bound, applied after the filter. + const matched = Array.from(rows.values()).filter((r) => matchesWhere(r, o?.where ?? {})); + return typeof o?.limit === 'number' ? matched.slice(0, o.limit) : matched; + }, + async insert(table: string, data: Record) { + nextId += 1; + if (table === 'sys_metadata_history') { + history.push({ ...data, id: `h_${nextId}` }); + return { id: `h_${nextId}` }; + } + if (table !== 'sys_metadata') return { id: 'side_effect_skip' }; + const row = { ...(data as unknown as Row), id: `r_${nextId}` }; + rows.set(keyOf(data), row); + return { id: row.id }; + }, + async update(_t: string, data: Record, o: { where: Record }) { + assertEngineUpdateDispatch(data, o); + const found = findRow(o.where); + if (!found) return { id: null }; + const merged = { ...found.row, ...(data as unknown as Row) }; + rows.delete(found.key); + rows.set(keyOf(merged), merged); + return { id: found.row.id }; + }, + async delete(_t: string, o: { where: Record }) { + assertEngineDeleteDispatch(o); + const found = findRow(o.where); + if (!found) return { deleted: 0 }; + rows.delete(found.key); + return { deleted: 1 }; + }, + async transaction(cb: (ctx: any, info: { owned: boolean }) => Promise): Promise { + return cb(undefined, { owned: true }); + }, + async syncObjectSchema() { return true; }, + registry, + }; + const protocol = new ObjectStackProtocolImplementation(engine, () => new Map()) as any; + return { protocol, rows }; +} + +const refusalOf = (run: Promise) => run.then(() => null, (e: any) => e); + +/** The stored rows of one item, as `type|state`. */ +const stored = (rows: Map, name: string) => + [...rows.values()].filter((r) => r.name === name).map((r) => `${r.type}|${r.state}`).sort(); + +/** A schema-valid ticket whose `note` field carries `rules`. */ +const fxTicket = (rules: Record = {}) => ({ + name: 'fx_ticket', + label: 'Ticket', + sharingModel: 'private', + fields: { + name: { type: 'text', label: 'Name' }, + priority: { + type: 'select', + label: 'Priority', + options: [{ label: 'Urgent', value: 'urgent' }, { label: 'Low', value: 'low' }], + }, + note: { type: 'text', label: 'Note', ...rules }, + }, +}); + +const expectRefusal = (err: any, paths: string[], hint: string) => { + expect({ code: err?.code, status: err?.status }, String(err?.stack ?? err)).toEqual({ code: 'INVALID_METADATA', status: 422 }); + const issues = (err.issues ?? []).filter((i: any) => i.rule === RULE_ID); + expect(issues.map((i: any) => i.path), `issues: ${JSON.stringify(err.issues)}`).toEqual(paths); + for (const issue of issues) { + expect(issue.severity).toBe('error'); + expect(issue.hint).toContain(hint); + } +}; + +describe('[#39722] the object save door — a field rule comparing an option label', () => { + it.each([ + ['requiredWhen', "record.priority == 'Urgent'"], + ['readonlyWhen', "record.priority != 'Urgent'"], + ['visibleWhen', "record.priority in ['Urgent']"], + ])('an active save whose `%s` compares the label is REFUSED 422 naming the value, and nothing lands', async (slot, source) => { + const { protocol, rows } = makeSession(); + + const err = await refusalOf(protocol.saveMetaItem({ + packageId: PKG, type: 'object', name: 'fx_ticket', item: fxTicket({ [slot]: source }), + })); + + expectRefusal(err, [`objects.fx_ticket.fields.note.${slot}`], "write 'urgent' in place of 'Urgent'"); + expect(stored(rows, 'fx_ticket')).toEqual([]); + }); + + it('an option `visibleWhen` comparing the label is REFUSED at its option, and nothing lands', async () => { + const { protocol, rows } = makeSession(); + const item = fxTicket(); + (item.fields as Record).channel = { + type: 'select', + label: 'Channel', + options: [{ label: 'Phone', value: 'phone', visibleWhen: "record.priority == 'Low'" }], + }; + + const err = await refusalOf(protocol.saveMetaItem({ packageId: PKG, type: 'object', name: 'fx_ticket', item })); + + expectRefusal(err, ['objects.fx_ticket.fields.channel.options[0].visibleWhen'], "write 'low' in place of 'Low'"); + expect(stored(rows, 'fx_ticket')).toEqual([]); + }); + + it('the same field rule written with the option VALUE saves, and the row lands', async () => { + const { protocol, rows } = makeSession(); + + const result = await protocol.saveMetaItem({ + packageId: PKG, type: 'object', name: 'fx_ticket', item: fxTicket({ requiredWhen: "record.priority == 'urgent'" }), + }); + + expect(result.success).toBe(true); + expect(stored(rows, 'fx_ticket')).toEqual(['object|active']); + }); + + it('a DRAFT save of the label field rule is not judged by this rule', async () => { + const { protocol, rows } = makeSession(); + + const result = await protocol.saveMetaItem({ + packageId: PKG, type: 'object', name: 'fx_ticket', mode: 'draft', item: fxTicket({ requiredWhen: "record.priority == 'Urgent'" }), + }); + + expect(result.success).toBe(true); + expect(stored(rows, 'fx_ticket')).toEqual(['object|draft']); + }); +}); + +describe('[#39722] the object_extension save door — an added field\'s rule comparing the target\'s option label', () => { + it('an active save is REFUSED 422 at the entry, naming the value, and nothing lands', async () => { + const { protocol, rows } = makeSession([fxTicket()]); + + const err = await refusalOf(protocol.saveMetaItem({ + packageId: PKG, type: 'object_extension', name: 'fx_ticket', + item: { extend: 'fx_ticket', fields: { escalation: { type: 'text', label: 'Escalation', readonlyWhen: "record.priority == 'Urgent'" } } }, + })); + + expectRefusal(err, ['objectExtensions[0].fields.escalation.readonlyWhen'], "write 'urgent' in place of 'Urgent'"); + expect(stored(rows, 'fx_ticket')).toEqual([]); + }); + + it('the same entry written with the option VALUE saves', async () => { + const { protocol, rows } = makeSession([fxTicket()]); + + const result = await protocol.saveMetaItem({ + packageId: PKG, type: 'object_extension', name: 'fx_ticket', + item: { extend: 'fx_ticket', fields: { escalation: { type: 'text', label: 'Escalation', readonlyWhen: "record.priority == 'urgent'" } } }, + }); + + expect(result.success).toBe(true); + expect(stored(rows, 'fx_ticket')).toEqual(['object_extension|active']); + }); +}); From 0156426389e25d2ba51dd1faa73052405ad7a73f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 02:00:17 +0000 Subject: [PATCH 2/3] fix(lint)!: refuse a field rule that compares a choice field with an option label A field's requiredWhen, readonlyWhen and visibleWhen, and an option's visibleWhen, are evaluated against the stored record, where a choice field holds the option value; a label comparand never matches, so the rule never applies (or, negated, applies to every record). The option-label rule now judges these slots with the same reading and reports them as field-rule-option-label at os validate, os build, os lint and the object / object_extension publish door. parent.F reads are not judged. ADR-0087 semantic entry field-rule-option-label-refused with its relevance rows. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvqcHrQpENbRP7eLfU --- .changeset/39722-field-rule-option-label.md | 25 +++ packages/lint/src/authoring-rules.ts | 6 + packages/lint/src/index.ts | 5 +- packages/lint/src/rule-explanations.ts | 2 + .../publish-time-inert-refusals.ts | 24 +++ .../validate-validation-rule-option-labels.ts | 155 +++++++++++++++++- .../19.field-rule-option-label-refused.ts | 39 +++++ .../semantic-relevance-coverage-38929.test.ts | 1 + .../src/migrations/semantic-relevance.test.ts | 1 + 9 files changed, 251 insertions(+), 7 deletions(-) create mode 100644 .changeset/39722-field-rule-option-label.md create mode 100644 packages/spec/src/migrations/entries/semantic/19.field-rule-option-label-refused.ts diff --git a/.changeset/39722-field-rule-option-label.md b/.changeset/39722-field-rule-option-label.md new file mode 100644 index 00000000000..b4d4844cc97 --- /dev/null +++ b/.changeset/39722-field-rule-option-label.md @@ -0,0 +1,25 @@ +--- +'@objectstack/lint': minor +'@objectstack/spec': minor +--- + +fix(lint)!: a field rule (`requiredWhen`, `readonlyWhen`, `visibleWhen`, an option's `visibleWhen`) that compares a choice field with an option label, where the record holds the option's value, is refused at validate, build and publish + +Clause-②: yes (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** accept-set narrowing. A `select`, `radio`, `multiselect` or `checkboxes` field stores the option's value (`urgent`), never its label (`Urgent`), and a field's rules are evaluated against the stored record. So a field rule comparing the field with a label never applied: a `requiredWhen` of `record.priority == 'Urgent'` never required the field, a `readonlyWhen` never locked it, a `visibleWhen` never showed it (nor, on a required field, required it), and an option's `visibleWhen` never offered the option, so a write picking it was refused. Written with `!=` or a negated `in`, each held on every record. All published with no finding. + +- **Now:** `os validate`, `os build` and `os lint` report `field-rule-option-label` as an error, and the metadata publish door refuses an `object` or `object_extension` publish carrying it with `422 INVALID_METADATA`. The finding names the field, the label written and the value to write. Judged in a field's `requiredWhen`, `readonlyWhen` and `visibleWhen` and in each option's `visibleWhen`, on the object's own fields and on the fields an object extension adds, for a field read as `record.FIELD` or `previous.FIELD`. The spellings reached: `FIELD == 'L'`, `FIELD != 'L'`, `'L' == FIELD`, `'L' != FIELD`, and each member of `FIELD in [...]` (negated or not). New export: `FIELD_RULE_OPTION_LABEL` from `@objectstack/lint`. +- **Not refused:** a `parent.FIELD` read (the master record's field), the membership spelling `'L' in FIELD` on a `multiselect` or `checkboxes` field, a label that is also some option's value, a literal that is neither a label nor a value, a `readonly` field, a field bound to a shared picklist or declared by two object extensions, a label holding a quote or a backslash, and a predicate in a dialect other than CEL. +- **Stored metadata:** a stored object or extension carrying the shape still loads and its rule evaluates as before. Its next publish is refused until the predicate compares the option value or is dropped. + +| Before (refused now) | After | +|:--|:--| +| `requiredWhen: "record.priority == 'Urgent'"` | `requiredWhen: "record.priority == 'urgent'"` | +| `readonlyWhen: "record.priority != 'Urgent'"` | `readonlyWhen: "record.priority != 'urgent'"` | +| `options: [{ value: 'phone', label: 'Phone', visibleWhen: "record.priority == 'Low'" }]` | `options: [{ value: 'phone', label: 'Phone', visibleWhen: "record.priority == 'low'" }]` | + +Fix: rewrite the label literal to the option's value, as the refusal names it. diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index f23aad07f91..f739a287d94 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -3512,6 +3512,12 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ // carries, and the target's own rules the door's live objects carry are // judged in the baseline too, so an extension write is charged with its // entry's rules alone. A rule switched off (`active: false`) is not judged. + // + // [#39722] The same entry judges a field's own rules with the same reading, + // under its own id (`field-rule-option-label`): a field's `requiredWhen`, + // `readonlyWhen` and `visibleWhen` and each option's `visibleWhen`, on an + // object's fields and on the fields an extension entry adds. One entry, so + // the doors and commands above are its doors and commands too. { name: 'validateValidationRuleOptionLabels', tier: 'gating', diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index b8c030641b5..0037c5252e6 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -1033,10 +1033,13 @@ export type { // #39441 — a validation rule's predicate comparing a choice field with an // option LABEL where the record holds the value (never fires, or refuses -// every write when negated). +// every write when negated). #39722 — the same comparand in a field's own +// rule (`requiredWhen`, `readonlyWhen`, `visibleWhen`, an option's +// `visibleWhen`), reported under its own id by the same rule. export { validateValidationRuleOptionLabels, VALIDATION_CONDITION_OPTION_LABEL, + FIELD_RULE_OPTION_LABEL, } from './validate-validation-rule-option-labels.js'; export type { ValidationRuleOptionLabelFinding } from './validate-validation-rule-option-labels.js'; diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 1f2c9efbe0b..bb4971468fd 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -435,6 +435,7 @@ import { FLOW_TRIGGER_OBJECT_MISSING_EXPLANATION, FLOW_CONDITION_OPTION_LABEL_EXPLANATION, VALIDATION_CONDITION_OPTION_LABEL_EXPLANATION, + FIELD_RULE_OPTION_LABEL_EXPLANATION, FLOW_TIME_RELATIVE_SHADOWED_EXPLANATION, FLOW_TIME_RELATIVE_KEY_MISPLACED_EXPLANATION, FLOW_TIME_RELATIVE_DATE_FIELD_INVALID_EXPLANATION, @@ -734,6 +735,7 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [FLOW_TRIGGER_OBJECT_MISSING_EXPLANATION.rule]: FLOW_TRIGGER_OBJECT_MISSING_EXPLANATION, [FLOW_CONDITION_OPTION_LABEL_EXPLANATION.rule]: FLOW_CONDITION_OPTION_LABEL_EXPLANATION, [VALIDATION_CONDITION_OPTION_LABEL_EXPLANATION.rule]: VALIDATION_CONDITION_OPTION_LABEL_EXPLANATION, + [FIELD_RULE_OPTION_LABEL_EXPLANATION.rule]: FIELD_RULE_OPTION_LABEL_EXPLANATION, [FLOW_TIME_RELATIVE_SHADOWED_EXPLANATION.rule]: FLOW_TIME_RELATIVE_SHADOWED_EXPLANATION, [FLOW_TIME_RELATIVE_KEY_MISPLACED_EXPLANATION.rule]: FLOW_TIME_RELATIVE_KEY_MISPLACED_EXPLANATION, [FLOW_TIME_RELATIVE_DATE_FIELD_INVALID_EXPLANATION.rule]: FLOW_TIME_RELATIVE_DATE_FIELD_INVALID_EXPLANATION, diff --git a/packages/lint/src/rule-explanations/publish-time-inert-refusals.ts b/packages/lint/src/rule-explanations/publish-time-inert-refusals.ts index c00351eead4..f6c9307002d 100644 --- a/packages/lint/src/rule-explanations/publish-time-inert-refusals.ts +++ b/packages/lint/src/rule-explanations/publish-time-inert-refusals.ts @@ -119,6 +119,30 @@ export const VALIDATION_CONDITION_OPTION_LABEL_EXPLANATION: RuleExplanation = { ], }; +export const FIELD_RULE_OPTION_LABEL_EXPLANATION: RuleExplanation = { + rule: 'field-rule-option-label', + covers: 'why field rules use option values', + paragraphs: [ + 'A select, radio, multiselect or checkboxes field stores the option\'s `value`, never its `label`, and a ' + + 'field\'s rules are evaluated against the record as stored (the server on every write, the form against ' + + 'the values it holds). A rule that compares the field with a quoted label (`record.priority == \'Urgent\'` ' + + 'where the option is `{ value: \'urgent\', label: \'Urgent\' }`) is false on every record: a ' + + '`requiredWhen` never requires the field, a `readonlyWhen` never locks it, a `visibleWhen` never shows it ' + + '(and so, on a required field, never requires it), and an option\'s `visibleWhen` never offers the option, ' + + 'so every write that picks it is refused. Written with `!=` or a negated `in`, it is true on every record.', + 'Reported in a field\'s `requiredWhen`, `readonlyWhen` and `visibleWhen` and in each option\'s ' + + '`visibleWhen`, on the object\'s own fields and on the fields an object extension adds. Only when the label ' + + 'is the comparand of that field: `F == \'L\'`, `F != \'L\'`, `\'L\' == F`, `\'L\' != F`, or a member ' + + 'of `F in [...]`, with `F` read as `record.F` or `previous.F`. The membership spelling `\'L\' in F` on a ' + + 'multiselect or checkboxes field is not read.', + 'Not reported: a `parent.F` read (the master record\'s field, another object\'s options), a label that is ' + + 'also some option\'s value, a literal that is neither a label nor a value (a stored value may lie outside ' + + 'the options), a readonly field, a field whose options come from a shared picklist or that two object ' + + 'extensions both declare, a label holding a quote or a backslash, and a predicate in a dialect other than ' + + 'CEL. Write the option\'s value in place of the label.', + ], +}; + export const FLOW_TIME_RELATIVE_SHADOWED_EXPLANATION: RuleExplanation = { rule: 'flow-time-relative-shadowed', covers: 'which trigger wins on a start with both', diff --git a/packages/lint/src/validate-validation-rule-option-labels.ts b/packages/lint/src/validate-validation-rule-option-labels.ts index b56327a2ed8..9926e7a779e 100644 --- a/packages/lint/src/validate-validation-rule-option-labels.ts +++ b/packages/lint/src/validate-validation-rule-option-labels.ts @@ -51,16 +51,44 @@ * values outside the options (`createMissingOptions`, a retired option rows * still hold), so such a literal may match real records. The ruling did not * choose that wider refusal. + * + * ## [#39722] A field's own rules — `field-rule-option-label` + * + * The same mistake in the predicates a FIELD carries: its `requiredWhen`, + * `readonlyWhen` and `visibleWhen`, and each option's `visibleWhen`. The + * server evaluates every one of them against the stored row merged with the + * write (`rule-validator.ts`: `requiredWhen` and `readonlyWhen` always, + * an option's `visibleWhen` on a write that picks it, a field's own + * `visibleWhen` on a `required` field), and the form evaluates them against + * the values it holds, which are option values too. So a label comparand + * never equals the field: with `==` or `in` the field is never required, + * never locked, never shown, the option never offered (and a write picking it + * refused); with `!=` or a negated `in` the opposite holds on every row. + * + * Its own id, so the refusal names the kind of rule it judged; the same + * reading, exclusions and roots as above (`record.F`, `previous.F`; the field + * rule binds the same two for the record's own fields). Judged on the fields + * of each object and on the fields each `objectExtensions` entry adds + * ({@link objectExtensionsByTarget}, the entries the stack itself carries). + * Not judged, beyond the list above: a `parent.F` read, which is the master + * record's field, another object's options; and the display-only predicates + * outside a field (`fieldGroups[].visibleWhen`, an object's + * `uiReadonlyWhen`). A field rule has no `active: false`: writing the value or + * dropping the predicate is the way out for a stored object. */ import { indexSelectOptions, optionLabelComparisons, type FieldReads, type SelectOptions } from './flow-select-options.js'; +import { objectExtensionsByTarget, recordsOf } from './object-graph.js'; import { MAX_RULE_NESTING_DEPTH, walkObjectValidationRules } from './validate-rule-compilability.js'; export const VALIDATION_CONDITION_OPTION_LABEL = 'validation-condition-option-label'; +/** [#39722] The same comparand in a field's own rule (`requiredWhen`, `readonlyWhen`, `visibleWhen`, an option's `visibleWhen`). */ +export const FIELD_RULE_OPTION_LABEL = 'field-rule-option-label'; + export interface ValidationRuleOptionLabelFinding { severity: 'error'; - rule: typeof VALIDATION_CONDITION_OPTION_LABEL; + rule: typeof VALIDATION_CONDITION_OPTION_LABEL | typeof FIELD_RULE_OPTION_LABEL; where: string; path: string; message: string; @@ -117,16 +145,27 @@ function branchesOf(rule: AnyRec, depth = 0): AnyRec[] { /** * Refuse every validation-rule predicate that compares a choice field of the - * rule's object with one of that field's option labels. Pure - * `(stack) => findings`; never throws. + * rule's object with one of that field's option labels, and (#39722) every + * field-rule predicate that compares a choice field of the field's object the + * same way. Pure `(stack) => findings`; never throws. */ export function validateValidationRuleOptionLabels(stack: unknown): ValidationRuleOptionLabelFinding[] { const findings: ValidationRuleOptionLabelFinding[] = []; if (!stack || typeof stack !== 'object' || Array.isArray(stack)) return findings; - const walked = walkObjectValidationRules(stack); - if (walked.length === 0) return findings; const optionFields = writableOptionFields(stack as AnyRec); if (optionFields.size === 0) return findings; + judgeValidationRules(stack, optionFields, findings); + judgeFieldRules(stack as AnyRec, optionFields, findings); + return findings; +} + +/** The #39441 half: every validation-rule predicate. */ +function judgeValidationRules( + stack: unknown, + optionFields: Map>, + findings: ValidationRuleOptionLabelFinding[], +): void { + const walked = walkObjectValidationRules(stack); // A switched-off rule silences itself and the branches under it, keyed on // the walked records themselves, never on their path: the path is built from @@ -164,5 +203,109 @@ export function validateValidationRuleOptionLabels(stack: unknown): ValidationRu } } } - return findings; +} + +/** + * [#39722] What a label comparand does to each field-rule slot: with `==` or + * `in` (never true), then with `!=` or a negated `in` (always true). + */ +const FIELD_RULE_CONSEQUENCE = { + requiredWhen: ['the field is never required', 'it is required on every write'], + readonlyWhen: ['the field is never locked', 'it is locked on every row'], + visibleWhen: ['the field is never shown (nor, on a required field, required)', 'it is shown on every row'], + 'option visibleWhen': ['the option is never offered and a write that picks it is refused', 'it is offered on every row'], +} as const; + +type FieldRuleSlot = keyof typeof FIELD_RULE_CONSEQUENCE; + +/** The three slots a field carries on itself, read literally. */ +const FIELD_SLOTS = ['requiredWhen', 'readonlyWhen', 'visibleWhen'] as const; + +/** One field an author declared, with the location strings a finding needs. */ +interface FieldSite { + objectName: string; + field: AnyRec; + where: string; + basePath: string; +} + +/** + * Every field an author declared: each object's own, then those each + * `objectExtensions` entry the stack carries adds (located at the entry, as + * the validation-rule walk locates the rules an entry adds). + */ +function walkFieldSites(stack: AnyRec): FieldSite[] { + const sites: FieldSite[] = []; + for (const obj of recordsOf(stack.objects)) { + if (typeof obj.name !== 'string' || !obj.name) continue; + for (const field of recordsOf(obj.fields)) { + const fname = typeof field.name === 'string' ? field.name : '?'; + sites.push({ + objectName: obj.name, + field, + where: `object '${obj.name}' · field '${fname}'`, + basePath: `objects.${obj.name}.fields.${fname}`, + }); + } + } + for (const [target, entries] of objectExtensionsByTarget(stack)) { + for (const { path, fields, stored } of entries) { + if (stored) continue; + for (const field of fields) { + const fname = typeof field.name === 'string' ? field.name : '?'; + sites.push({ + objectName: target, + field, + where: `object '${target}' · ${path} · field '${fname}'`, + basePath: `${path}.fields.${fname}`, + }); + } + } + } + return sites; +} + +/** The #39722 half: every predicate a field carries. */ +function judgeFieldRules( + stack: AnyRec, + optionFields: Map>, + findings: ValidationRuleOptionLabelFinding[], +): void { + const judge = (src: string | undefined, options: ReadonlyMap, objectName: string, slot: FieldRuleSlot, where: string, path: string) => { + if (!src) return; + const [never, always] = FIELD_RULE_CONSEQUENCE[slot]; + for (const hit of optionLabelComparisons(src, options, VALIDATION_RULE_READS)) { + findings.push({ + severity: 'error', + rule: FIELD_RULE_OPTION_LABEL, + where, + path, + message: + `compares '${objectName}.${hit.field}' with '${hit.label}', which is that option's label; the field ` + + `stores the option's value '${hit.value}', not its label: compared with \`==\` or \`in\` ${never}, and ` + + `with \`!=\` or a negated \`in\` ${always}`, + hint: `Compare with the option's value: write '${hit.value}' in place of '${hit.label}'`, + }); + } + }; + for (const { objectName, field, where, basePath } of walkFieldSites(stack)) { + const options = optionFields.get(objectName); + if (!options) continue; + for (const slot of FIELD_SLOTS) { + judge(celSourceOf(field[slot]), options, objectName, slot, `${where} ${slot}`, `${basePath}.${slot}`); + } + if (!Array.isArray(field.options)) continue; + field.options.forEach((option: unknown, i: number) => { + if (!isRec(option)) return; + const label = typeof option.value === 'string' ? option.value : String(i); + judge( + celSourceOf(option.visibleWhen), + options, + objectName, + 'option visibleWhen', + `${where} · option '${label}' visibleWhen`, + `${basePath}.options[${i}].visibleWhen`, + ); + }); + } } diff --git a/packages/spec/src/migrations/entries/semantic/19.field-rule-option-label-refused.ts b/packages/spec/src/migrations/entries/semantic/19.field-rule-option-label-refused.ts new file mode 100644 index 00000000000..e16e874cd42 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.field-rule-option-label-refused.ts @@ -0,0 +1,39 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// A field rule whose predicate compares a choice field with one of its option +// labels is now refused (#39722), the field-rule sibling of +// validation-condition-option-label-refused. A structured TODO, not a D2 +// conversion: the label maps to one value, but whether a rule that never +// applied (or, negated, applied to every record) should start applying now is +// the author's call, so the platform does not rewrite it. +export const entry: SemanticMigration = { + id: 'field-rule-option-label-refused', + surface: + 'objects[].fields and objectExtensions[].fields: a field\'s requiredWhen, readonlyWhen or visibleWhen, or an ' + + 'option\'s visibleWhen, that compares a select, radio, multiselect or checkboxes field of the same object, ' + + 'read as record.FIELD or previous.FIELD, with one of its option LABELS where the field stores the option VALUE ' + + '(requiredWhen: record.priority == \'Urgent\' for the option { value: \'urgent\', label: \'Urgent\' }), as ' + + 'FIELD == \'L\', FIELD != \'L\', \'L\' == FIELD, \'L\' != FIELD or a member of FIELD in [...]. Not the shape: ' + + 'a parent.FIELD read, the membership spelling \'L\' in FIELD, a label that is also some option\'s value, a ' + + 'literal that is neither, a readonly field, a field bound to a shared picklist, a field two object extensions ' + + 'both declare, a label holding a quote or a backslash, a predicate in a dialect other than CEL', + replacement: + 'Write the option\'s value in place of its label (record.priority == \'urgent\'), as the refusal names it; or ' + + 'drop the predicate', + reason: + 'A choice field stores the option value and the server evaluates a field rule against the stored record, so a ' + + 'label never equals the field: compared with == or in, a requiredWhen never requires the field, a readonlyWhen ' + + 'never locks it, a visibleWhen never shows it (nor, on a required field, requires it) and an option\'s ' + + 'visibleWhen never offers the option, so a write picking it is refused; with != or a negated in, each holds ' + + 'on every record. All published with no finding. os validate, os build, os lint and the metadata publish ' + + 'door (422 INVALID_METADATA on an object or object extension write) now refuse it as field-rule-option-label, ' + + 'naming the field, the label and the value. No conversion is registered: writing the value makes a rule that ' + + 'never applied start applying, which only the author can decide. ADR-0078 / ADR-0087.', + acceptanceCriteria: + 'os validate and os build report no field-rule-option-label finding. A stored object or extension carrying the ' + + 'shape still loads and its rule evaluates as before; its next publish is refused until the predicate compares ' + + 'the option value or is dropped.', + relevantWhen: { kind: 'stack-declares', keys: ['objects', 'objectExtensions'] }, +}; diff --git a/packages/spec/src/migrations/semantic-relevance-coverage-38929.test.ts b/packages/spec/src/migrations/semantic-relevance-coverage-38929.test.ts index 4f09fca21e8..4cfe9d456f8 100644 --- a/packages/spec/src/migrations/semantic-relevance-coverage-38929.test.ts +++ b/packages/spec/src/migrations/semantic-relevance-coverage-38929.test.ts @@ -302,6 +302,7 @@ const LIST_VIEW = [ const FORM_VIEW = ['internal-record-forms-not-loaded', 'ui-form-view-modal-size-retired', 'ui-form-view-subforms-retired']; const FIELD = [ 'field-inline-edit-boolean-retired', + 'field-rule-option-label-refused', 'field-option-value-repeated-refused', 'field-precision-zero-refused', 'lookup-depends-on-param-computed-field-refused', diff --git a/packages/spec/src/migrations/semantic-relevance.test.ts b/packages/spec/src/migrations/semantic-relevance.test.ts index 60aa9668468..10055456a01 100644 --- a/packages/spec/src/migrations/semantic-relevance.test.ts +++ b/packages/spec/src/migrations/semantic-relevance.test.ts @@ -85,6 +85,7 @@ const EXPECTED_RELEVANCE: Readonly> = { '19:field-inline-edit-boolean-retired': ['objects', 'objectExtensions'], '19:field-option-value-repeated-refused': ['objects', 'objectExtensions'], '19:field-precision-zero-refused': ['objects', 'objectExtensions'], + '19:field-rule-option-label-refused': ['objects', 'objectExtensions'], '19:flow-concurrent-branch-durable-pause-refused': ['flows'], '19:flow-condition-bare-ordering-before-record-date-arithmetic-refused': ['flows'], '19:flow-condition-date-number-ordering-refused': ['flows'], From 9e09ecb01bd32e73d8118747c47a0991c3eae8c9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 03:33:57 +0000 Subject: [PATCH 3/3] test(metadata-protocol): fold the field-rule option-label door pins into the shared harness The real-door pins for field-rule-option-label move into protocol.runtime-authoring-gate.test.ts as a top-level describe that reuses its makeProtocol / makeStubEngine harness, beside the validation-rule block, and the separate file with its own copy of the sys_metadata double is deleted. Same cases: the three field slots and an option's visibleWhen refused 422 at the object door, the value control, the draft control, and the object_extension refusal and control. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvqcHrQpENbRP7eLfU --- ...date-validation-rule-option-labels.test.ts | 4 +- ...tocol.field-rule-option-label-gate.test.ts | 257 ------------------ .../protocol.runtime-authoring-gate.test.ts | 129 +++++++++ 3 files changed, 131 insertions(+), 259 deletions(-) delete mode 100644 packages/metadata-protocol/src/protocol.field-rule-option-label-gate.test.ts diff --git a/packages/lint/src/validate-validation-rule-option-labels.test.ts b/packages/lint/src/validate-validation-rule-option-labels.test.ts index 8c8a814cdbe..a6f559b6ea9 100644 --- a/packages/lint/src/validate-validation-rule-option-labels.test.ts +++ b/packages/lint/src/validate-validation-rule-option-labels.test.ts @@ -260,8 +260,8 @@ describe('#39441 — a stored object the publish door already holds', () => { * them against the stored row merged with the payload (`rule-validator.ts`), * where a choice field holds the option VALUE, so a label comparand never * equals it. Same module and registry entry as the validation-rule check; the - * protocol-level half is - * `packages/metadata-protocol/src/protocol.field-rule-option-label-gate.test.ts`. + * protocol-level half is the #39722 block of + * `packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts`. */ describe('#39722 — a field rule comparing a choice field with an option label', () => { const PRIORITY = { diff --git a/packages/metadata-protocol/src/protocol.field-rule-option-label-gate.test.ts b/packages/metadata-protocol/src/protocol.field-rule-option-label-gate.test.ts deleted file mode 100644 index 203febbd761..00000000000 --- a/packages/metadata-protocol/src/protocol.field-rule-option-label-gate.test.ts +++ /dev/null @@ -1,257 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * [#39722] The object save door refuses a field rule that compares a choice - * field with an option LABEL, naming the value to write - * (`field-rule-option-label`, `@objectstack/lint` - * `validate-validation-rule-option-labels.ts`). The slots: a field's - * `requiredWhen`, `readonlyWhen` and `visibleWhen`, and each option's - * `visibleWhen`. No code here moves: the rule rides the registry entry that - * already declares `object` and `object_extension`, the entry this door - * filters. The rule's reach (each slot, negated comparands, extensions, what is - * not judged) is pinned beside it in `@objectstack/lint`; this file pins the - * real door's envelope, through `saveMetaItem`, on both write types. - * - * Measured on `origin/main` before the rule: each body below saved, and the - * field rule never applied, because a choice field stores the option value and - * the server evaluates the rule against the stored row (`rule-validator.ts`). - * - * Harness: the stateful `sys_metadata` double of - * `protocol.unknown-picklist-binding-refusal.test.ts`, kept local, with a - * registry whose live object universe the test states. - * - * ⚠️ This package reaches `@objectstack/lint` through its built `dist/`. - */ -// Pays the lint root's first load at collection, never inside a clocked case. -import './lint-root-preload.testkit.js'; -import { describe, expect, it } from 'vitest'; -import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; -import { ObjectStackProtocolImplementation } from './protocol.js'; - -interface Row { - id: string; - type: string; - name: string; - organization_id: string | null; - package_id: string | null; - state: string; - metadata: string; -} - -const PKG = 'app.fieldruleprobe'; -const RULE_ID = 'field-rule-option-label'; - -/** ADR-0048 overlay key — (type, name, org, state, package_id). */ -const keyOf = (w: Record) => - `${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}|${w.package_id ?? '__nopkg__'}`; - -/** Top-level eq + `$or` + `$in` + explicit-NULL, the subset these paths emit. */ -function matchesWhere(r: Row, where: Record): boolean { - for (const [k, v] of Object.entries(where)) { - if (k === '$or') { - if (!(v as Array>).some((c) => matchesWhere(r, c))) return false; - continue; - } - if (v === undefined) continue; - const actual = (r as unknown as Record)[k]; - if (v !== null && typeof v === 'object' && Array.isArray((v as { $in?: unknown }).$in)) { - if (!(v as { $in: unknown[] }).$in.includes(actual)) return false; - continue; - } - if (v === null ? actual !== null && actual !== undefined : actual !== v) return false; - } - return true; -} - -/** A protocol over a stateful double; `objects` is the live object universe the registry serves. */ -function makeSession(objects: Array> = []) { - const rows = new Map(); - const history: Array> = []; - let nextId = 0; - const findRow = (w: Record): { key: string; row: Row } | null => { - if (w.id !== undefined) { - for (const [k, r] of rows) if (r.id === w.id) return { key: k, row: r }; - return null; - } - for (const [k, r] of rows) if (matchesWhere(r, w)) return { key: k, row: r }; - return null; - }; - const registry: any = { - registerItem: () => {}, - registerObject: () => {}, - listItems: (type: string) => (type === 'object' ? objects : []), - getItem: () => undefined, - getAllObjects: () => objects, - // The objects an `object_extension` may extend. - getObject: (name: string) => objects.find((o) => o.name === name), - // An installed authored base that declares no namespace. - getPackage: (id: string) => (id === PKG ? { manifest: { id } } : undefined), - getArtifactItem: () => undefined, - isPackageDisabled: () => false, - }; - const engine: any = { - async findOne(table: string, o: { where: Record }) { - assertEngineFindOnePredicate(table, o); - if (table === 'sys_metadata_history') { - return history.find((h) => Object.entries(o.where).every(([k, v]) => { - if (k.startsWith('$')) throw new Error(`history double: unsupported operator ${k}`); - return v === undefined || h[k] === v; - })) ?? null; - } - if (table !== 'sys_metadata') return null; - return findRow(o.where)?.row ?? null; - }, - async find(table: string, o?: { where?: Record; limit?: number }) { - if (table !== 'sys_metadata') return []; - // `check:objectql-double-limit` — the caller's bound, applied after the filter. - const matched = Array.from(rows.values()).filter((r) => matchesWhere(r, o?.where ?? {})); - return typeof o?.limit === 'number' ? matched.slice(0, o.limit) : matched; - }, - async insert(table: string, data: Record) { - nextId += 1; - if (table === 'sys_metadata_history') { - history.push({ ...data, id: `h_${nextId}` }); - return { id: `h_${nextId}` }; - } - if (table !== 'sys_metadata') return { id: 'side_effect_skip' }; - const row = { ...(data as unknown as Row), id: `r_${nextId}` }; - rows.set(keyOf(data), row); - return { id: row.id }; - }, - async update(_t: string, data: Record, o: { where: Record }) { - assertEngineUpdateDispatch(data, o); - const found = findRow(o.where); - if (!found) return { id: null }; - const merged = { ...found.row, ...(data as unknown as Row) }; - rows.delete(found.key); - rows.set(keyOf(merged), merged); - return { id: found.row.id }; - }, - async delete(_t: string, o: { where: Record }) { - assertEngineDeleteDispatch(o); - const found = findRow(o.where); - if (!found) return { deleted: 0 }; - rows.delete(found.key); - return { deleted: 1 }; - }, - async transaction(cb: (ctx: any, info: { owned: boolean }) => Promise): Promise { - return cb(undefined, { owned: true }); - }, - async syncObjectSchema() { return true; }, - registry, - }; - const protocol = new ObjectStackProtocolImplementation(engine, () => new Map()) as any; - return { protocol, rows }; -} - -const refusalOf = (run: Promise) => run.then(() => null, (e: any) => e); - -/** The stored rows of one item, as `type|state`. */ -const stored = (rows: Map, name: string) => - [...rows.values()].filter((r) => r.name === name).map((r) => `${r.type}|${r.state}`).sort(); - -/** A schema-valid ticket whose `note` field carries `rules`. */ -const fxTicket = (rules: Record = {}) => ({ - name: 'fx_ticket', - label: 'Ticket', - sharingModel: 'private', - fields: { - name: { type: 'text', label: 'Name' }, - priority: { - type: 'select', - label: 'Priority', - options: [{ label: 'Urgent', value: 'urgent' }, { label: 'Low', value: 'low' }], - }, - note: { type: 'text', label: 'Note', ...rules }, - }, -}); - -const expectRefusal = (err: any, paths: string[], hint: string) => { - expect({ code: err?.code, status: err?.status }, String(err?.stack ?? err)).toEqual({ code: 'INVALID_METADATA', status: 422 }); - const issues = (err.issues ?? []).filter((i: any) => i.rule === RULE_ID); - expect(issues.map((i: any) => i.path), `issues: ${JSON.stringify(err.issues)}`).toEqual(paths); - for (const issue of issues) { - expect(issue.severity).toBe('error'); - expect(issue.hint).toContain(hint); - } -}; - -describe('[#39722] the object save door — a field rule comparing an option label', () => { - it.each([ - ['requiredWhen', "record.priority == 'Urgent'"], - ['readonlyWhen', "record.priority != 'Urgent'"], - ['visibleWhen', "record.priority in ['Urgent']"], - ])('an active save whose `%s` compares the label is REFUSED 422 naming the value, and nothing lands', async (slot, source) => { - const { protocol, rows } = makeSession(); - - const err = await refusalOf(protocol.saveMetaItem({ - packageId: PKG, type: 'object', name: 'fx_ticket', item: fxTicket({ [slot]: source }), - })); - - expectRefusal(err, [`objects.fx_ticket.fields.note.${slot}`], "write 'urgent' in place of 'Urgent'"); - expect(stored(rows, 'fx_ticket')).toEqual([]); - }); - - it('an option `visibleWhen` comparing the label is REFUSED at its option, and nothing lands', async () => { - const { protocol, rows } = makeSession(); - const item = fxTicket(); - (item.fields as Record).channel = { - type: 'select', - label: 'Channel', - options: [{ label: 'Phone', value: 'phone', visibleWhen: "record.priority == 'Low'" }], - }; - - const err = await refusalOf(protocol.saveMetaItem({ packageId: PKG, type: 'object', name: 'fx_ticket', item })); - - expectRefusal(err, ['objects.fx_ticket.fields.channel.options[0].visibleWhen'], "write 'low' in place of 'Low'"); - expect(stored(rows, 'fx_ticket')).toEqual([]); - }); - - it('the same field rule written with the option VALUE saves, and the row lands', async () => { - const { protocol, rows } = makeSession(); - - const result = await protocol.saveMetaItem({ - packageId: PKG, type: 'object', name: 'fx_ticket', item: fxTicket({ requiredWhen: "record.priority == 'urgent'" }), - }); - - expect(result.success).toBe(true); - expect(stored(rows, 'fx_ticket')).toEqual(['object|active']); - }); - - it('a DRAFT save of the label field rule is not judged by this rule', async () => { - const { protocol, rows } = makeSession(); - - const result = await protocol.saveMetaItem({ - packageId: PKG, type: 'object', name: 'fx_ticket', mode: 'draft', item: fxTicket({ requiredWhen: "record.priority == 'Urgent'" }), - }); - - expect(result.success).toBe(true); - expect(stored(rows, 'fx_ticket')).toEqual(['object|draft']); - }); -}); - -describe('[#39722] the object_extension save door — an added field\'s rule comparing the target\'s option label', () => { - it('an active save is REFUSED 422 at the entry, naming the value, and nothing lands', async () => { - const { protocol, rows } = makeSession([fxTicket()]); - - const err = await refusalOf(protocol.saveMetaItem({ - packageId: PKG, type: 'object_extension', name: 'fx_ticket', - item: { extend: 'fx_ticket', fields: { escalation: { type: 'text', label: 'Escalation', readonlyWhen: "record.priority == 'Urgent'" } } }, - })); - - expectRefusal(err, ['objectExtensions[0].fields.escalation.readonlyWhen'], "write 'urgent' in place of 'Urgent'"); - expect(stored(rows, 'fx_ticket')).toEqual([]); - }); - - it('the same entry written with the option VALUE saves', async () => { - const { protocol, rows } = makeSession([fxTicket()]); - - const result = await protocol.saveMetaItem({ - packageId: PKG, type: 'object_extension', name: 'fx_ticket', - item: { extend: 'fx_ticket', fields: { escalation: { type: 'text', label: 'Escalation', readonlyWhen: "record.priority == 'urgent'" } } }, - }); - - expect(result.success).toBe(true); - expect(stored(rows, 'fx_ticket')).toEqual(['object_extension|active']); - }); -}); diff --git a/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts b/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts index 28220647356..712285f5e18 100644 --- a/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts +++ b/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts @@ -6093,3 +6093,132 @@ describe('runtime authoring gate on OBJECT writes — a validation rule comparin }); }); }); + +/** + * [#39722] The object and object_extension save doors refuse a FIELD rule that + * compares a choice field with an option LABEL, naming the value to write + * (`field-rule-option-label`, the same `@objectstack/lint` module and registry + * entry as the #39441 block above). The slots: a field's `requiredWhen`, + * `readonlyWhen` and `visibleWhen`, and each option's `visibleWhen`. No code + * here moves; the rule's reach (each slot, negated comparands, extensions, + * what is not judged) is pinned beside it in `@objectstack/lint`, and this + * block pins the real door's envelope on both write types. + * + * Measured on `origin/main` before the rule: each refused body below saved, + * and the field rule never applied, because a choice field stores the option + * value and the server evaluates the rule against the stored row. + * + * ⚠️ This package reaches `@objectstack/lint` through its built `dist/`. + */ +describe('runtime authoring gate on OBJECT and OBJECT_EXTENSION writes — a field rule comparing an option label (#39722)', () => { + const RULE_ID = 'field-rule-option-label'; + /** A ticket whose `note` field carries `rules`. */ + const fxTicket = (rules: Record = {}) => ({ + name: 'fx_ticket', + label: 'Ticket', + sharingModel: 'private', + fields: { + name: { type: 'text', label: 'Name' }, + priority: { + type: 'select', + label: 'Priority', + options: [{ label: 'Urgent', value: 'urgent' }, { label: 'Low', value: 'low' }], + }, + note: { type: 'text', label: 'Note', ...rules } as Record, + } as Record, + }); + /** The stored rows named `fx_ticket`, as `type|state`. */ + const ticketRows = (rows: Map) => + Array.from(rows.values()).filter((r) => r.name === 'fx_ticket').map((r) => `${r.type}|${r.state}`).sort(); + /** A protocol whose live object universe is `objects` (the target an extension write extends). */ + const hostWith = (objects: Array>) => { + const { engine, rows } = makeStubEngine(); + engine.registry.listItems = (type: string) => (type === 'object' ? objects : []); + engine.registry.getObject = (name: string) => objects.find((o) => o.name === name); + const protocol = new ObjectStackProtocolImplementation(engine, () => new Map(), 'env_test') as any; + return { protocol, rows }; + }; + const expectRefusal = (err: any, paths: string[], hint: string) => { + expect({ code: err?.code, status: err?.status }, String(err?.stack ?? err)).toEqual({ code: 'INVALID_METADATA', status: 422 }); + const issues = (err.issues ?? []).filter((i: any) => i.rule === RULE_ID); + expect(issues.map((i: any) => i.path), `issues: ${JSON.stringify(err.issues)}`).toEqual(paths); + for (const issue of issues) { + expect(issue.severity).toBe('error'); + expect(issue.hint).toContain(hint); + } + }; + const saveObject = (protocol: any, item: unknown, extra: Record = {}) => + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_ticket', item, ...extra }); + const saveExtension = (protocol: any, item: unknown) => + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object_extension', name: 'fx_ticket', item }); + + it.each([ + ['requiredWhen', "record.priority == 'Urgent'"], + ['readonlyWhen', "record.priority != 'Urgent'"], + ['visibleWhen', "record.priority in ['Urgent']"], + ])('an active object save whose `%s` compares the label is REFUSED 422 naming the value, and nothing lands', async (slot, source) => { + const { protocol, rows } = makeProtocol(); + + const err = await saveObject(protocol, fxTicket({ [slot]: source })).catch((e: any) => e); + + expectRefusal(err, [`objects.fx_ticket.fields.note.${slot}`], "write 'urgent' in place of 'Urgent'"); + expect(ticketRows(rows)).toEqual([]); + }); + + it('an option `visibleWhen` comparing the label is REFUSED at its option, and nothing lands', async () => { + const { protocol, rows } = makeProtocol(); + const item = fxTicket(); + item.fields.channel = { + type: 'select', + label: 'Channel', + options: [{ label: 'Phone', value: 'phone', visibleWhen: "record.priority == 'Low'" }], + }; + + const err = await saveObject(protocol, item).catch((e: any) => e); + + expectRefusal(err, ['objects.fx_ticket.fields.channel.options[0].visibleWhen'], "write 'low' in place of 'Low'"); + expect(ticketRows(rows)).toEqual([]); + }); + + it('the same field rule written with the option VALUE saves, and the row lands', async () => { + const { protocol, rows } = makeProtocol(); + + const result = await saveObject(protocol, fxTicket({ requiredWhen: "record.priority == 'urgent'" })); + + expect(result.success).toBe(true); + expect(ticketRows(rows)).toEqual(['object|active']); + }); + + it('a DRAFT save of the label field rule is not judged by this rule', async () => { + const { protocol, rows } = makeProtocol(); + + const result = await saveObject(protocol, fxTicket({ requiredWhen: "record.priority == 'Urgent'" }), { mode: 'draft' }); + + expect(result.success).toBe(true); + expect(ticketRows(rows)).toEqual(['object|draft']); + }); + + it('an active object_extension save whose added field compares the target\'s label is REFUSED 422 at the entry, and nothing lands', async () => { + const { protocol, rows } = hostWith([fxTicket()]); + + const err = await saveExtension(protocol, { + extend: 'fx_ticket', + fields: { escalation: { type: 'text', label: 'Escalation', readonlyWhen: "record.priority == 'Urgent'" } }, + }).catch((e: any) => e); + + expectRefusal(err, ['objectExtensions[0].fields.escalation.readonlyWhen'], "write 'urgent' in place of 'Urgent'"); + expect(ticketRows(rows)).toEqual([]); + }); + + it('the same extension entry written with the option VALUE saves', async () => { + const { protocol, rows } = hostWith([fxTicket()]); + + const result = await saveExtension(protocol, { + extend: 'fx_ticket', + fields: { escalation: { type: 'text', label: 'Escalation', readonlyWhen: "record.priority == 'urgent'" } }, + }); + + expect(result.success).toBe(true); + expect(ticketRows(rows)).toEqual(['object_extension|active']); + }); +});