diff --git a/.changeset/39441-validation-condition-option-label.md b/.changeset/39441-validation-condition-option-label.md new file mode 100644 index 00000000000..a2504ad8a46 --- /dev/null +++ b/.changeset/39441-validation-condition-option-label.md @@ -0,0 +1,24 @@ +--- +'@objectstack/lint': minor +'@objectstack/spec': minor +--- + +fix(lint)!: a validation rule whose condition 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 validation rule's condition is evaluated against the stored record as written. So a rule comparing the field with a label never fired (`record.priority == 'Urgent'`, or `in [...]`), and its negated form refused every write, the records holding `urgent` included (`record.priority != 'Urgent'`, `!(record.priority in ['Urgent'])`). Both published with no finding. + +- **Now:** `os validate`, `os build` and `os lint` report `validation-condition-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 rule's `condition` and in a conditional rule's `when`, its `then` / `otherwise` branches included, on the object's own rules and on the rules 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). +- **Not refused:** 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 stored value may lie outside the options), a `readonly` field, a field bound to a shared picklist or declared by two object extensions, a label holding a quote or a backslash, a predicate in a dialect other than CEL, and a rule switched off with `active: false` (a different, active rule of the same name is still judged). +- **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 condition is fixed or the rule is switched off. + +| Before (refused now) | After | +|:--|:--| +| `condition: "record.priority == 'Urgent' && record.name == null"` | `condition: "record.priority == 'urgent' && record.name == null"` | +| `condition: "record.priority != 'Urgent'"` | `condition: "record.priority != 'urgent'"` | + +Fix: write the option's value in place of its label, as the refusal names it; or set `active: false` on the rule. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 3085d3d7513..03df7b15e9a 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -937,7 +937,7 @@ os compile --json # JSON output for CI pipelines → Normalizing stack definition... → Lowering inline handlers... → Validating protocol compliance... - → Running author-time rules (90)... + → Running author-time rules (91)... → Checking that every required capability has a provider installable in this edition... → Collecting package docs (ADR-0046)... 0 collected → Writing artifact... diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index 1b281b1f51b..dbf786ee226 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -874,7 +874,7 @@ A clean run walks the registry and reports timing: Config: /path/to/support-desk/objectstack.config.ts Load time: 21ms → Validating against ObjectStack Protocol... - → Running author-time rules (90)... + → Running author-time rules (91)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/content/docs/getting-started/build-with-claude-code.mdx b/content/docs/getting-started/build-with-claude-code.mdx index 41e2456f9af..5234952cb4b 100644 --- a/content/docs/getting-started/build-with-claude-code.mdx +++ b/content/docs/getting-started/build-with-claude-code.mdx @@ -378,7 +378,7 @@ visible: 'status != "resolved"' ◆ Validate ──────────────────────────────────────── → Validating against ObjectStack Protocol... - → Running author-time rules (90)... + → Running author-time rules (91)... ✗ Author-time rules failed (1 issue) • stack · action 'resolve_ticket' visible: bare reference `status` — a diff --git a/content/docs/ui/react-pages.mdx b/content/docs/ui/react-pages.mdx index 7142d727674..47b8fa867d0 100644 --- a/content/docs/ui/react-pages.mdx +++ b/content/docs/ui/react-pages.mdx @@ -404,7 +404,7 @@ objectstack validate ──────────────────────────────────────── → Loading configuration... → Validating against ObjectStack Protocol... - → Running author-time rules (90)... + → Running author-time rules (91)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index e0cfdb2c336..f23aad07f91 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -161,6 +161,7 @@ import { validateActionBodyCapabilities } from './validate-action-body-capabilit import { validateSeedRecordKeys } from './validate-seed-record-keys.js'; import { validateHookAndJobBodyCompiles } from './validate-hook-body-compiles.js'; import { validateRuleSchemaFormats } from './validate-rule-schema-formats.js'; +import { validateValidationRuleOptionLabels } from './validate-validation-rule-option-labels.js'; import { validateActionLocations } from './validate-action-locations.js'; import { validateObjectActionLayout } from './validate-object-action-layout.js'; import { validateActionObjectBinding } from './validate-action-object-binding.js'; @@ -3497,6 +3498,30 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ runtimeTypes: ['object', 'object_extension'], run: (stack) => validateRuleSchemaFormats(stack), }, + // [#39441] A validation rule's `condition` / `when` that compares a choice + // field with one of its option LABELS where the record holds the VALUE: the + // rule never fires (`==`, `in`) or refuses every write (`!=`, a negated + // `in`). Refused under the sharing-rule sibling's ruling (record + // 7403149741, option A: the label comparand only, the value named), at the + // flow rule's tier for the same mistake (`flow-condition-option-label`, + // `error`), with that rule's label reading (`flow-select-options.ts`) and + // the compile rule's validation-rule walk, so neither is a second copy. + // + // Runtime publish gate on `object` and `object_extension`, as its walk's + // other readers: the door judges the rules the written object or entry + // 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. + { + name: 'validateValidationRuleOptionLabels', + tier: 'gating', + input: 'parsed', + commands: ALL, + source: 'packages/lint/src/validate-validation-rule-option-labels.ts', + surfaces: CLI_AND_RUNTIME, + runtimeTypes: ['object', 'object_extension'], + run: (stack) => validateValidationRuleOptionLabels(stack), + }, // [#25189] The email half of #25082 (ruling `6335348115`, F1 A2): a hole an // email template's `bodyHtml` places where the mail renderer cannot encode // it for that placement is refused, naming the placement and the supported diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 3284bf232ca..2057277b57c 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -1030,6 +1030,15 @@ export type { WalkedValidationRule, } from './validate-rule-compilability.js'; +// #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). +export { + validateValidationRuleOptionLabels, + VALIDATION_CONDITION_OPTION_LABEL, +} from './validate-validation-rule-option-labels.js'; +export type { ValidationRuleOptionLabelFinding } from './validate-validation-rule-option-labels.js'; + // #5178 — the residual half #5029's `ajv-formats` registration does not close. // Under `strict: false` an UNRECOGNISED format name is logged once and the // keyword is DROPPED, so `format: 'emial'` leaves the rule declared, running on diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index fdc077a08df..1be059c57f0 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -433,6 +433,7 @@ import { FLOW_APPROVAL_DECISION_UNROUTED_EXPLANATION, FLOW_TRIGGER_OBJECT_MISSING_EXPLANATION, FLOW_CONDITION_OPTION_LABEL_EXPLANATION, + VALIDATION_CONDITION_OPTION_LABEL_EXPLANATION, FLOW_TIME_RELATIVE_SHADOWED_EXPLANATION, FLOW_TIME_RELATIVE_KEY_MISPLACED_EXPLANATION, FLOW_TIME_RELATIVE_DATE_FIELD_INVALID_EXPLANATION, @@ -730,6 +731,7 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [FLOW_HTTP_TIMEOUT_MISSING_EXPLANATION.rule]: FLOW_HTTP_TIMEOUT_MISSING_EXPLANATION, [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, [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 038c68c6bba..c00351eead4 100644 --- a/packages/lint/src/rule-explanations/publish-time-inert-refusals.ts +++ b/packages/lint/src/rule-explanations/publish-time-inert-refusals.ts @@ -97,6 +97,28 @@ export const FLOW_CONDITION_OPTION_LABEL_EXPLANATION: RuleExplanation = { ], }; +export const VALIDATION_CONDITION_OPTION_LABEL_EXPLANATION: RuleExplanation = { + rule: 'validation-condition-option-label', + covers: 'why validation rule conditions use option values', + paragraphs: [ + 'A select, radio, multiselect or checkboxes field stores the option\'s `value`, never its `label`, and a ' + + 'validation rule\'s condition is evaluated against the stored record as written. 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, so the rule never refuses a write. ' + + 'Written with `!=` or a negated `in`, it is true on every record, so the rule refuses every write.', + 'Reported in a rule\'s `condition` and in a conditional rule\'s `when`, its `then` and `otherwise` branches ' + + 'included, on the object\'s own rules and on the rules 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 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, a predicate ' + + 'in a dialect other than CEL, and a rule switched off with `active: false`. 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/runtime-gate.object-formula-writes.test.ts b/packages/lint/src/runtime-gate.object-formula-writes.test.ts index 6f8e3165689..fbdf828d6e0 100644 --- a/packages/lint/src/runtime-gate.object-formula-writes.test.ts +++ b/packages/lint/src/runtime-gate.object-formula-writes.test.ts @@ -364,7 +364,7 @@ describe('#33072 — the object_extension door judges an extension field\'s form it('`validateStackExpressions` is on the object_extension door, beside the vocabulary freeze', () => { // [#33217] And the two validation-rule artifact checks (regex, JSON schema). expect(runtimeAuthoringRulesFor('object_extension').map((r) => r.name)) - .toEqual(['validateStackExpressions', 'lintFieldReferenceShapes', 'lintOptionColors', 'lintDuplicateFieldLabels', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats']); + .toEqual(['validateStackExpressions', 'lintFieldReferenceShapes', 'lintOptionColors', 'lintDuplicateFieldLabels', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats', 'validateValidationRuleOptionLabels']); }); it('⭐ LIT — an extension formula calling an unregistered function (`sqrt`) is REFUSED, at the entry the build names', () => { @@ -422,7 +422,7 @@ describe('#33072 — the object_extension door judges an extension field\'s form const result = gateExtension(item); expect(result.errors, dump(result)).toEqual([]); expect(result.advisories, dump(result)).toEqual([]); - expect(result.rulesRun).toEqual(['validateStackExpressions', 'lintFieldReferenceShapes', 'lintOptionColors', 'lintDuplicateFieldLabels', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats']); + expect(result.rulesRun).toEqual(['validateStackExpressions', 'lintFieldReferenceShapes', 'lintOptionColors', 'lintDuplicateFieldLabels', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats', 'validateValidationRuleOptionLabels']); } }); diff --git a/packages/lint/src/runtime-gate.object-writes.test.ts b/packages/lint/src/runtime-gate.object-writes.test.ts index 631cfa77a37..ac7bd6a365b 100644 --- a/packages/lint/src/runtime-gate.object-writes.test.ts +++ b/packages/lint/src/runtime-gate.object-writes.test.ts @@ -214,6 +214,10 @@ describe('the object write door dispatches at the adjudicated scope (#4716)', () // `validate-action-body-capabilities.test.ts`. 'validateActionBodyCapabilities', 'validateRuleSchemaFormats', + // [#39441] A validation rule's predicate comparing a choice field with an + // option label: the object write carries the rules it judges. Door cases + // in `validate-validation-rule-option-labels.test.ts`. + 'validateValidationRuleOptionLabels', ]); }); @@ -600,6 +604,7 @@ describe('the object write door dispatches at the adjudicated scope (#4716)', () 'validateActionBodyCompiles', // see the roster pin above 'validateActionBodyCapabilities', // [#35143] — see the roster pin above 'validateRuleSchemaFormats', + 'validateValidationRuleOptionLabels', // [#39441] — see the roster pin above ]); }); diff --git a/packages/lint/src/validate-security-posture.runtime-surface.test.ts b/packages/lint/src/validate-security-posture.runtime-surface.test.ts index fc0d44db6b5..b908750fb91 100644 --- a/packages/lint/src/validate-security-posture.runtime-surface.test.ts +++ b/packages/lint/src/validate-security-posture.runtime-surface.test.ts @@ -585,7 +585,7 @@ describe('validateSecurityPosture at the runtime publish surface (#7576 → #830 expect(stackKeyForType('object_extension')).toBe('objectExtensions'); // [#33217] The validation-rule artifact checks (regex, JSON schema) cross on it too. expect(runtimeAuthoringRulesFor('object_extension').map((r) => r.name)) - .toEqual(['validateStackExpressions', 'lintFieldReferenceShapes', 'lintOptionColors', 'lintDuplicateFieldLabels', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats']); + .toEqual(['validateStackExpressions', 'lintFieldReferenceShapes', 'lintOptionColors', 'lintDuplicateFieldLabels', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats', 'validateValidationRuleOptionLabels']); const roleSelect = { type: 'select', label: 'Group Function', options: [{ value: 'l1', label: 'Tier 1' }] }; const refused = runRuntimeAuthoringRules({ @@ -600,7 +600,7 @@ describe('validateSecurityPosture at the runtime publish surface (#7576 → #830 // positional and names it. expect(refused.errors[0].path).toBe('objectExtensions[0].fields.role.name'); expect(refused.errors[0].where).toBe('field "sd_agent.role"'); - expect(refused.rulesRun).toEqual(['validateStackExpressions', 'lintFieldReferenceShapes', 'lintOptionColors', 'lintDuplicateFieldLabels', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats']); + expect(refused.rulesRun).toEqual(['validateStackExpressions', 'lintFieldReferenceShapes', 'lintOptionColors', 'lintDuplicateFieldLabels', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats', 'validateValidationRuleOptionLabels']); // The two labels the entry serves, at the same door. const labelled = runRuntimeAuthoringRules({ @@ -620,7 +620,7 @@ describe('validateSecurityPosture at the runtime publish surface (#7576 → #830 }); expect(clean.errors).toEqual([]); expect(clean.advisories).toEqual([]); - expect(clean.rulesRun).toEqual(['validateStackExpressions', 'lintFieldReferenceShapes', 'lintOptionColors', 'lintDuplicateFieldLabels', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats']); + expect(clean.rulesRun).toEqual(['validateStackExpressions', 'lintFieldReferenceShapes', 'lintOptionColors', 'lintDuplicateFieldLabels', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats', 'validateValidationRuleOptionLabels']); // Not a context row: the baseline carries no `objectExtensions`, and the // candidate holds exactly the written item. diff --git a/packages/lint/src/validate-validation-rule-option-labels.test.ts b/packages/lint/src/validate-validation-rule-option-labels.test.ts new file mode 100644 index 00000000000..87bb922bcea --- /dev/null +++ b/packages/lint/src/validate-validation-rule-option-labels.test.ts @@ -0,0 +1,253 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#39441] A validation rule whose predicate compares a choice field with one + * of its option LABELS is refused at every door that saves validation rules: + * the three CLI commands (`runAuthoringRules`) and the metadata publish door + * (`runRuntimeAuthoringRules`, the verdict `saveMetaItem` / `publishMetaItem` + * answer with a 422 on an `object` or `object_extension` write; the + * protocol-level half is the #39441 block of + * `packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts`). + * + * Measured first, with the rule validator (`evaluateValidationRules`) at + * `a92f1ed9`, options `Urgent → urgent`, `Low → low`: + * `record.priority == 'Urgent'` refused neither row (never fires); + * `record.priority != 'Urgent'` and `!(record.priority in ['Urgent'])` + * refused BOTH rows (fire on every write); the value spellings refused only + * the row they name. So the negated comparand is covered, with the same id. + */ +import { describe, expect, it } from 'vitest'; +import { runAuthoringRules } from './authoring-rules.js'; +import { runRuntimeAuthoringRules, runtimeAuthoringRulesFor } from './runtime-gate.js'; +import { + VALIDATION_CONDITION_OPTION_LABEL, + validateValidationRuleOptionLabels, +} from './validate-validation-rule-option-labels.js'; + +/** `sharingModel` keeps `security-owd-unset` quiet, so a refusal is this rule's. */ +const ticket = (validations: unknown[], extraFields: 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' }], + }, + ...extraFields, + }, + validations, +}); + +const rule = (condition: string, extra: Record = {}) => ({ + name: 'urgent_needs_name', + type: 'script', + condition, + message: 'An urgent ticket needs a name.', + ...extra, +}); + +const LABEL = "record.priority == 'Urgent' && record.name == null"; +const VALUE = "record.priority == 'urgent' && record.name == null"; + +const labelFindings = (fs: readonly T[]): T[] => + fs.filter((f) => f.rule === VALIDATION_CONDITION_OPTION_LABEL); + +const atObjectDoor = (item: unknown, objects: unknown[] = []) => + runRuntimeAuthoringRules({ type: 'object', item, context: { objects } }); + +const atBuild = (stack: Record) => + labelFindings(runAuthoringRules('build', { normalized: stack, parsed: stack })); + +const dump = (r: unknown) => JSON.stringify(r, null, 2); + +describe('#39441 — the doors that save validation rules run the label check', () => { + it('is 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: [ticket([rule(LABEL)])] }; + expect(labelFindings(runAuthoringRules(command, { normalized: stack, parsed: stack }))).toHaveLength(1); + } + }); + + it('⭐ an object publish whose rule compares a choice field with an option label is REFUSED, naming the value to write', () => { + const result = atObjectDoor(ticket([rule(LABEL)])); + + const errs = labelFindings(result.errors); + expect(errs, dump(result)).toHaveLength(1); + expect(errs[0]).toMatchObject({ + severity: 'error', + rule: VALIDATION_CONDITION_OPTION_LABEL, + where: "object 'fx_ticket' · validation 'urgent_needs_name'", + path: 'objects.fx_ticket.validations.urgent_needs_name.condition', + }); + // The named subjects: the field, the label written, the value to write. + expect(errs[0]!.message).toContain("'fx_ticket.priority'"); + expect(errs[0]!.message).toContain("'Urgent'"); + expect(errs[0]!.hint).toContain("write 'urgent' in place of 'Urgent'"); + }); + + it('⭐ an object_extension publish whose added rule compares the target\'s choice field with a label is REFUSED at the entry', () => { + const entry = { extend: 'fx_ticket', validations: [rule(LABEL)] }; + const result = runRuntimeAuthoringRules({ type: 'object_extension', item: entry, context: { objects: [ticket([])] } }); + + const errs = labelFindings(result.errors); + expect(errs, dump(result)).toHaveLength(1); + expect(errs[0]).toMatchObject({ + severity: 'error', + where: "object 'fx_ticket' · objectExtensions[0] · validation 'urgent_needs_name'", + path: 'objectExtensions[0].validations.urgent_needs_name.condition', + }); + expect(errs[0]!.hint).toContain("write 'urgent'"); + }); + + it('an extension write is not charged with a label the target\'s own stored rule carries', () => { + const entry = { extend: 'fx_ticket', validations: [rule(VALUE, { name: 'other' })] }; + const result = runRuntimeAuthoringRules({ + type: 'object_extension', + item: entry, + context: { objects: [ticket([rule(LABEL)])] }, + }); + expect(labelFindings(result.errors), dump(result)).toEqual([]); + }); + + it('the build refuses the same rule with the door\'s finding (rule, location, message, hint)', () => { + const body = ticket([rule(LABEL)]); + const door = labelFindings(atObjectDoor(body).errors); + const build = atBuild({ objects: [body] }); + expect(build).toEqual(door); + }); +}); + +describe('#39441 — what is refused and what saves', () => { + it('the VALUE comparand saves', () => { + expect(labelFindings(atObjectDoor(ticket([rule(VALUE)])).errors)).toEqual([]); + expect(atBuild({ objects: [ticket([rule(VALUE)])] })).toEqual([]); + }); + + it('a non-choice field compared with the same text is untouched', () => { + const body = ticket([rule("record.name == 'Urgent'")]); + expect(labelFindings(atObjectDoor(body).errors)).toEqual([]); + }); + + it('⭐ the negated comparands (`!=`, a negated `in`) are refused: measured, they refuse every write', () => { + for (const condition of [ + "record.priority != 'Urgent'", + "!(record.priority in ['Urgent', 'low'])", + "'Urgent' != record.priority", + ]) { + const errs = labelFindings(atObjectDoor(ticket([rule(condition)])).errors); + expect(errs, condition).toHaveLength(1); + expect(errs[0]!.message).toContain('refuses every write'); + } + }); + + it('a `previous.F` read, a `when`, and a nested branch are each judged at their own slot', () => { + const conditional = { + type: 'conditional', + name: 'gate', + when: "previous.priority == 'Low'", + message: 'x', + then: { type: 'script', name: 'child', condition: "record.priority in ['Urgent']", message: 'y' }, + }; + const paths = labelFindings(atObjectDoor(ticket([conditional])).errors).map((f) => f.path); + expect(paths).toEqual([ + 'objects.fx_ticket.validations.gate.when', + 'objects.fx_ticket.validations.gate.then.child.condition', + ]); + }); + + it('a label that is also some option\'s value, and a literal that is neither, are not refused', () => { + const fields = { + tier: { + type: 'radio', + label: 'Tier', + options: [{ label: 'gold', value: 'silver' }, { label: 'Silver', value: 'gold' }], + }, + }; + const body = ticket([rule("record.tier == 'gold'"), rule("record.priority == 'urgnet'", { name: 'typo' })], fields); + expect(labelFindings(atObjectDoor(body).errors)).toEqual([]); + }); + + it('a readonly choice field, a picklist-bound one and a CEL-less dialect are not judged', () => { + const fields = { + stage: { type: 'select', label: 'Stage', readonly: true, options: [{ label: 'Done', value: 'done' }] }, + region: { type: 'select', label: 'Region', picklist: 'regions', options: [{ label: 'North', value: 'north' }] }, + }; + const body = ticket([ + rule("record.stage == 'Done'", { name: 'a' }), + rule("record.region == 'North'", { name: 'b' }), + rule('x', { name: 'c', condition: { dialect: 'js', source: "record.priority == 'Urgent'" } }), + ], fields); + expect(validateValidationRuleOptionLabels({ objects: [body] })).toEqual([]); + }); + + it('a rule switched off (`active: false`) is not judged, nor any branch under it', () => { + const off = { + type: 'conditional', + name: 'gate', + active: false, + when: "record.priority == 'Urgent'", + message: 'x', + then: { type: 'script', name: 'child', condition: "record.priority == 'Low'", message: 'y' }, + }; + expect(labelFindings(atObjectDoor(ticket([rule(LABEL, { active: false }), off])).errors)).toEqual([]); + }); + + it('⭐ a live rule sharing a switched-off rule\'s name is still judged, and so are its branches', () => { + // `validations` is an array and nothing refuses a repeated name; the + // evaluator runs every member, so the second rule below refuses writes. + const top = ticket([rule(LABEL, { active: false }), rule("record.priority != 'Urgent'")]); + expect(labelFindings(atObjectDoor(top).errors).map((f) => f.path)).toEqual([ + 'objects.fx_ticket.validations.urgent_needs_name.condition', + ]); + + const gate = (extra: Record, child: string) => ({ + type: 'conditional', + name: 'gate', + when: 'true', + message: 'x', + then: { type: 'script', name: 'child', condition: child, message: 'y' }, + ...extra, + }); + const nested = ticket([gate({ active: false }, "record.priority == 'Low'"), gate({}, "record.priority == 'Urgent'")]); + const nestedHits = labelFindings(atObjectDoor(nested).errors); + expect(nestedHits.map((f) => f.path)).toEqual(['objects.fx_ticket.validations.gate.then.child.condition']); + expect(nestedHits[0]!.hint).toContain("write 'urgent' in place of 'Urgent'"); + + const entry = { extend: 'fx_ticket', validations: [rule(LABEL, { active: false }), rule(LABEL)] }; + const ext = runRuntimeAuthoringRules({ type: 'object_extension', item: entry, context: { objects: [ticket([])] } }); + expect(labelFindings(ext.errors).map((f) => f.path)).toEqual([ + 'objectExtensions[0].validations.urgent_needs_name.condition', + ]); + }); +}); + +describe('#39441 — 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 — "re-saving a row is writing it". So a publish of a + * stored object whose label rule is unchanged is judged like any other + * publish of it; the stored row itself keeps loading and evaluating. + * Switching the rule off is the one-key way to republish the object without + * writing the value. + */ + it('a re-publish that leaves the label rule unchanged is judged; switching the rule off republishes clean', () => { + const stored = ticket([rule(LABEL)]); + const relabelled = { ...ticket([rule(LABEL)]), label: 'Support Ticket' }; + expect(labelFindings(atObjectDoor(relabelled, [stored]).errors)).toHaveLength(1); + + const switchedOff = { ...ticket([rule(LABEL, { active: false })]), label: 'Support Ticket' }; + expect(labelFindings(atObjectDoor(switchedOff, [stored]).errors)).toEqual([]); + }); + + it('another stored object\'s label rule is never charged to this write', () => { + const sibling = { ...ticket([rule(LABEL)]), name: 'fx_other' }; + expect(labelFindings(atObjectDoor(ticket([rule(VALUE)]), [sibling]).errors)).toEqual([]); + }); +}); diff --git a/packages/lint/src/validate-validation-rule-option-labels.ts b/packages/lint/src/validate-validation-rule-option-labels.ts new file mode 100644 index 00000000000..b56327a2ed8 --- /dev/null +++ b/packages/lint/src/validate-validation-rule-option-labels.ts @@ -0,0 +1,168 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#39441] A validation rule whose predicate compares a choice field with one + * of its option LABELS, where the record holds the option's VALUE. + * + * A `select` / `radio` / `multiselect` / `checkboxes` field stores the option + * value (`urgent`), never its label (`Urgent`), and the rule validator + * evaluates a rule's CEL against the stored record as written. So a label + * comparand never equals the field (measured with `evaluateValidationRules` + * at `a92f1ed9`): `record.priority == 'Urgent'` is false on every record and + * the rule never refuses a write; `record.priority != 'Urgent'` and + * `!(record.priority in ['Urgent'])` are true on every record and the rule + * refuses EVERY write, the rows holding `urgent` included. Both saved with no + * finding at every door: the silently inert (or silently blocking) metadata + * ADR-0078 prohibits. Refused `error`, the tier of the flow rule for the same + * mistake (`flow-condition-option-label`), under the ruling on the sharing-rule + * sibling (record 7403149741, option A): the label comparand only, the refusal + * naming the value to write. + * + * ## The reading — shared, never a second matcher + * + * Which literals are labels, and which are comparands of the field, is + * `flow-select-options.ts`'s reading, the one `flow-condition-option-label` + * uses: {@link indexSelectOptions} (inline non-empty `options`, no shared + * `picklist`, no field two extensions tie on; a label that is also some + * option's value is never a label) and {@link optionLabelComparisons} + * (`F == 'L'`, `F != 'L'`, `'L' == F`, `'L' != F`, each member of + * `F in [...]`). The roots are the ones a validation predicate binds for the + * rule's own object: `record.F` and `previous.F`. A bare `F` is not a read + * there (the expression rule refuses it on its own), and `parent.F` is + * another object's field. + * + * Which rules exist, and where each sits, is the walk the compile rule reads + * ({@link walkObjectValidationRules}): an object's own `validations[]` and + * the ones an `objectExtensions` entry adds, every `conditional` branch + * flattened in. Judged on each: `condition` and `when`. + * + * ## Not judged + * + * - A `readonly` choice field: the record validator judges its value by shape + * only, so a stored label is possible and the comparison may hold. + * - A rule switched off (`active: false`), and every branch under it: the + * evaluator skips it, so it refuses nothing either way, and switching a + * rule off stays the one-key way out for a stored object that carries one. + * Keyed on the rule record, not its name: another, active rule of the same + * name is judged. + * - The membership spelling `'L' in record.F` on a `multiselect` / + * `checkboxes` field: not a comparand form the shared reading knows. + * - A literal that is neither a label nor a value: the spec admits stored + * 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. + */ + +import { indexSelectOptions, optionLabelComparisons, type FieldReads, type SelectOptions } from './flow-select-options.js'; +import { MAX_RULE_NESTING_DEPTH, walkObjectValidationRules } from './validate-rule-compilability.js'; + +export const VALIDATION_CONDITION_OPTION_LABEL = 'validation-condition-option-label'; + +export interface ValidationRuleOptionLabelFinding { + severity: 'error'; + rule: typeof VALIDATION_CONDITION_OPTION_LABEL; + where: string; + path: string; + message: string; + hint: string; +} + +type AnyRec = Record; + +/** The rows a validation predicate reads the object's fields on. */ +const VALIDATION_RULE_READS: FieldReads = Object.freeze({ roots: ['record', 'previous'], bare: false }); + +/** The two predicate slots a validation rule carries. */ +const PREDICATE_SLOTS = ['condition', 'when'] as const; + +/** A predicate's CEL source: the bare string, or a CEL envelope's `source`. */ +function celSourceOf(raw: unknown): string | undefined { + if (typeof raw === 'string') return raw; + if (raw && typeof raw === 'object' && !Array.isArray(raw)) { + const rec = raw as AnyRec; + if (typeof rec.dialect === 'string' && rec.dialect !== 'cel') return undefined; + if (typeof rec.source === 'string') return rec.source; + } + return undefined; +} + +/** The judgeable choice fields of each object, `readonly` ones left out. */ +function writableOptionFields(stack: AnyRec): Map> { + const out = new Map>(); + for (const [objectName, byField] of indexSelectOptions(stack)) { + const kept = new Map(); + for (const [field, options] of byField) if (!options.readonly && options.labels.size > 0) kept.set(field, options); + if (kept.size > 0) out.set(objectName, kept); + } + return out; +} + +const isRec = (v: unknown): v is AnyRec => !!v && typeof v === 'object' && !Array.isArray(v); + +/** + * Every branch under a rule, depth-first, `then` before `otherwise`: the order + * {@link walkObjectValidationRules} hands them in right after the rule. Capped + * at the walk's own depth, so a cyclic record ends; where the walk stopped + * sooner, the first entry it does not hand ends the silencing. + */ +function branchesOf(rule: AnyRec, depth = 0): AnyRec[] { + const out: AnyRec[] = []; + if (depth >= MAX_RULE_NESTING_DEPTH) return out; + for (const branch of ['then', 'otherwise'] as const) { + const nested = rule[branch]; + if (isRec(nested)) out.push(nested, ...branchesOf(nested, depth + 1)); + } + return out; +} + +/** + * 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. + */ +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; + + // 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 + // `name`, and a live rule sharing a switched-off rule's name is still live. + // The walk hands a rule, then its branches depth-first, so the silenced + // entries are exactly the ones that follow, in the order `branchesOf` lists. + let silenced: AnyRec[] = []; + for (const { rule, objectName, where, basePath } of walked) { + if (silenced.length > 0 && silenced[0] === rule) { + silenced.shift(); + continue; + } + silenced = []; + if (rule.active === false) { + silenced = branchesOf(rule); + continue; + } + const options = optionFields.get(objectName); + if (!options) continue; + for (const slot of PREDICATE_SLOTS) { + const src = celSourceOf(rule[slot]); + if (!src) continue; + for (const hit of optionLabelComparisons(src, options, VALIDATION_RULE_READS)) { + findings.push({ + severity: 'error', + rule: VALIDATION_CONDITION_OPTION_LABEL, + where: slot === 'when' ? `${where} when` : where, + path: `${basePath}.${slot}`, + 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\` the rule never ` + + `fires on a row holding a value, and with \`!=\` or a negated \`in\` it refuses every write that stores one`, + hint: `Compare with the option's value: write '${hit.value}' in place of '${hit.label}'`, + }); + } + } + } + return findings; +} 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 f0ce2c5e285..28220647356 100644 --- a/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts +++ b/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts @@ -5971,3 +5971,125 @@ describe('runtime authoring gate on a subflow call to an unknown flow (#35143)', expect(judge({ flows: [{ name: 'batch_child' }] }).error).toBeNull(); }); }); + +/** + * [#39441] The object save door refuses a validation rule that compares a + * choice field with an option LABEL, naming the value to write + * (`validation-condition-option-label`, `@objectstack/lint` + * `validate-validation-rule-option-labels.ts`). No code here moves: the rule + * declares `object` and `object_extension` in the registry this door filters. + * The rule's reach (negated comparands, `when`, nested branches, extensions, + * what is not judged) is pinned beside it in `@objectstack/lint`; this block + * pins the real door's envelope. + * + * ⚠️ This package reaches `@objectstack/lint` through its built `dist/`. + */ +describe('runtime authoring gate on OBJECT writes — a validation rule comparing an option label (#39441)', () => { + const RULE_ID = 'validation-condition-option-label'; + const fxTicket = (condition: string) => ({ + 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' }], + }, + }, + validations: [{ name: 'urgent_needs_name', type: 'script', condition, message: 'Name the urgent ticket.' }], + }); + const ticketRows = (rows: Map) => + Array.from(rows.values()).filter((r) => r.type === 'object' && r.name === 'fx_ticket'); + + it('REFUSES an active save comparing the label, 422 INVALID_METADATA naming the value, and nothing lands', async () => { + const { protocol, rows } = makeProtocol(); + + const err = await protocol + .saveMetaItem({ + packageId: TEST_PKG, + type: 'object', + name: 'fx_ticket', + item: fxTicket("record.priority == 'Urgent' && record.name == null"), + }) + .catch((e: any) => e); + + expect(err, 'the save resolved — the door still accepts the label').toBeInstanceOf(Error); + expect(err.status).toBe(422); + expect(err.code).toBe('INVALID_METADATA'); + const issue = err.issues.find((i: any) => i.rule === RULE_ID); + expect(issue, `issues: ${JSON.stringify(err.issues)}`).toBeDefined(); + expect(issue.severity).toBe('error'); + expect(issue.path).toBe('objects.fx_ticket.validations.urgent_needs_name.condition'); + expect(issue.hint).toContain("write 'urgent' in place of 'Urgent'"); + expect(ticketRows(rows)).toEqual([]); + }); + + it('the same rule written with the option VALUE saves, and the row lands', async () => { + const { protocol, rows } = makeProtocol(); + + const result = await protocol.saveMetaItem({ + packageId: TEST_PKG, + type: 'object', + name: 'fx_ticket', + item: fxTicket("record.priority == 'urgent' && record.name == null"), + }); + + expect(result.success).toBe(true); + expect(ticketRows(rows).map((r) => r.state)).toEqual(['active']); + }); + + /** + * A stored object already carrying the label rule (written before the + * check, by hand or by MCP). The door's standing mode (`runtime-gate.ts`, + * "Re-saving a row is writing it"): its next publish is judged even when + * the edit is unrelated; `active: false` on the rule is the exit that + * needs no value written; a draft is never judged (#4463 D1). + */ + describe('a stored object the door already holds with the label rule', () => { + const LABEL_RULE = "record.priority == 'Urgent' && record.name == null"; + const hostWith = (objects: unknown[]) => { + const { engine, rows } = makeStubEngine(); + engine.registry.listItems = (type: string) => (type === 'object' ? objects : []); + const protocol = new ObjectStackProtocolImplementation(engine, () => new Map(), 'env_test') as any; + return { protocol, rows }; + }; + const relabelled = (rule: Record = {}) => { + const item = fxTicket(LABEL_RULE); + return { ...item, label: 'Support Ticket', validations: [{ ...item.validations[0], ...rule }] }; + }; + const saveTicket = (protocol: any, item: unknown, extra: Record = {}) => + protocol.saveMetaItem({ packageId: TEST_PKG, type: 'object', name: 'fx_ticket', item, ...extra }); + + it('an unrelated publish (a relabel) is REFUSED on the unchanged rule, and nothing lands', async () => { + const { protocol, rows } = hostWith([fxTicket(LABEL_RULE)]); + + const err = await saveTicket(protocol, relabelled()).catch((e: any) => e); + + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); + const issue = err.issues.find((i: any) => i.rule === RULE_ID); + expect(issue, `issues: ${JSON.stringify(err.issues)}`).toBeDefined(); + expect(issue.path).toBe('objects.fx_ticket.validations.urgent_needs_name.condition'); + expect(ticketRows(rows)).toEqual([]); + }); + + it('the same publish with `active: false` on the rule lands, without the value written', async () => { + const { protocol, rows } = hostWith([fxTicket(LABEL_RULE)]); + + const result = await saveTicket(protocol, relabelled({ active: false })); + + expect(result.success).toBe(true); + expect(ticketRows(rows).map((r) => r.state)).toEqual(['active']); + }); + + it('a DRAFT save of the unchanged rule is not judged', async () => { + const { protocol, rows } = hostWith([fxTicket(LABEL_RULE)]); + + const result = await saveTicket(protocol, relabelled(), { mode: 'draft' }); + + expect(result.success).toBe(true); + expect(ticketRows(rows).map((r) => r.state)).toEqual(['draft']); + }); + }); +}); diff --git a/packages/spec/src/migrations/entries/semantic/19.validation-condition-option-label-refused.ts b/packages/spec/src/migrations/entries/semantic/19.validation-condition-option-label-refused.ts new file mode 100644 index 00000000000..50939838e03 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.validation-condition-option-label-refused.ts @@ -0,0 +1,37 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// A validation rule whose condition compares a choice field with one of its +// option labels is now refused (#39441). A structured TODO, not a D2 +// conversion: the label maps to one value, but whether a rule that never fired +// (or, negated, refused every write) should start enforcing now is the +// author's call, so the platform does not rewrite it. +export const entry: SemanticMigration = { + id: 'validation-condition-option-label-refused', + surface: + 'objects[].validations[] and objectExtensions[].validations[]: a condition or when predicate (a conditional ' + + 'rule\'s then / otherwise branches included) that compares a select, radio, multiselect or checkboxes field ' + + 'of the rule\'s object, read as record.FIELD or previous.FIELD, with one of its option LABELS where the field ' + + 'stores the option VALUE (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: ' + + '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, a rule with active: false', + replacement: + 'Write the option\'s value in place of its label (record.priority == \'urgent\'), as the refusal names it; or ' + + 'switch the rule off with active: false', + reason: + 'A choice field stores the option value and the rule validator evaluates the condition against the stored ' + + 'record as written, so a label never equals the field: compared with == or in the rule never fires, and with ' + + '!= or a negated in it refuses every write, the records holding the value included. Both 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 validation-condition-option-label, naming the field, the label and ' + + 'the value. No conversion is registered: writing the value makes a rule that never fired start refusing ' + + 'writes, which only the author can decide. ADR-0078 / ADR-0087.', + acceptanceCriteria: + 'os validate and os build report no validation-condition-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 ' + + 'condition compares the option value or the rule is switched off.', + 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 cc9ca670cf7..a3e31bba9fa 100644 --- a/packages/spec/src/migrations/semantic-relevance-coverage-38929.test.ts +++ b/packages/spec/src/migrations/semantic-relevance-coverage-38929.test.ts @@ -314,6 +314,7 @@ const ARRANGEMENT = [ 'object-extension-place-and-cross-package-lists', ]; const VALIDATION = [ + 'validation-condition-option-label-refused', 'validation-rule-message-template-holes', 'cel-list-equality-refused', 'publish-refuses-metadata-the-runtime-ignores', diff --git a/packages/spec/src/migrations/semantic-relevance.test.ts b/packages/spec/src/migrations/semantic-relevance.test.ts index 3cf60344a91..44f21a3d3ca 100644 --- a/packages/spec/src/migrations/semantic-relevance.test.ts +++ b/packages/spec/src/migrations/semantic-relevance.test.ts @@ -132,6 +132,7 @@ const EXPECTED_RELEVANCE: Readonly> = { '19:ui-action-type-ask-ai-retired': ['actions', 'objects', 'pages', 'dashboards'], '19:ui-form-view-modal-size-retired': ['views', 'viewItems', 'forms'], '19:ui-form-view-subforms-retired': ['views', 'viewItems', 'forms'], + '19:validation-condition-option-label-refused': ['objects', 'objectExtensions'], '19:validation-rule-message-template-holes': ['objects', 'objectExtensions', 'translations'], '19:view-bulk-actions-declared-on-the-action': ['views', 'objects', 'pages'], };