diff --git a/.changeset/39336-inline-option-value-repeated.md b/.changeset/39336-inline-option-value-repeated.md new file mode 100644 index 00000000000..bae3c56563a --- /dev/null +++ b/.changeset/39336-inline-option-value-repeated.md @@ -0,0 +1,25 @@ +--- +'@objectstack/spec': minor +--- + +fix(spec)!: a field whose inline `options` declare one value twice is refused at every author door, as a shared picklist with a repeated value already was + +Clause-②: no (narrowing) +Metadata-protocol: narrowed +Skills-docs: none — `skills/objectstack-data/references/examples-objects.md` teaches inline select options and already declares each value once; the refusal names the value, both entries and the fix + + + +**BREAKING** accept-set narrowing. FROM a field (on an object or an object extension, any type that takes `options`) whose `options` declare the same `value` in two entries saving, publishing and passing `os validate` / `os build`, TO that field refused by the field schema at every door: the metadata save (draft or active) and publish answer `422 INVALID_METADATA` with an issue at `fields.NAME.options.INDEX.value`, and `os validate` / `os build` report the same issue. The message reads `This field's \`options\` would carry the value 'a' twice: it is declared by option 0 and again by option 1.`, worded as the shared-picklist refusal is. + +Why. A record stores an option's value, and every reader that shows the record maps the stored value back to one option, so a repeated value left its label and colour ambiguous in lists, chips and reports. A shared `picklist` whose options repeat a value was refused at registration; the same list written inline on the field passed every door silently. The `Field.select(['In Progress', 'in progress'])` string form, whose two labels derive one value, is refused the same way. + +A stored object whose body carries the repeat still registers at boot and is served badged invalid; it is refused at its next save or publish until the repeat is removed. A stored object extension row carrying the repeat is not registered at boot (the loader logs and skips it), so the fields it adds are absent until the row is fixed: before upgrading, run `os validate` for packaged extensions and read each runtime-authored extension's `_diagnostics` on the metadata read. No conversion rewrites it (which label the author meant is not recorded); the ADR-0087 semantic entry `field-option-value-repeated-refused` carries the rewrite to the upgrade guide. + +## FROM → TO + +| FROM | TO | +|:---|:---| +| `options: [{ value: 'a', label: 'A' }, { value: 'a', label: 'A2' }]` | `options: [{ value: 'a', label: 'A' }, { value: 'a2', label: 'A2' }]` | + +One-line fix: declare each option value once; remove the repeated entry, or give it a value of its own. diff --git a/packages/metadata-protocol/src/protocol.option-value-repeated-refusal.test.ts b/packages/metadata-protocol/src/protocol.option-value-repeated-refusal.test.ts new file mode 100644 index 00000000000..0398c2918b2 --- /dev/null +++ b/packages/metadata-protocol/src/protocol.option-value-repeated-refusal.test.ts @@ -0,0 +1,99 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The object save door refuses a field whose inline `options` declare one + * `value` twice, the verdict a shared `picklist` with a repeated value meets + * at registration. The rule lives in the field's spec parse + * (`findRepeatedOptionValue`), and `saveMetaItem` parses with `ObjectSchema`, + * so the door answers `422 INVALID_METADATA` located at the repeated entry and + * stores nothing: the same refusal `os validate` and `os build` meet, from the + * same rule. + */ +// 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, type EngineFindOneQueryInput } from '@objectstack/metadata-core'; +import { ObjectStackProtocolImplementation } from './protocol.js'; + +const TEST_PKG = 'test_pkg'; + +/** The engine surface the repository write path touches (as the container-issue-descent harness). */ +function makeProtocol() { + const rows = new Map>(); + let nextId = 0; + const engine: any = { + async findOne(object: string, query?: EngineFindOneQueryInput) { + assertEngineFindOnePredicate(object, query); return null; }, + async find() { return []; }, + async insert(table: string, data: Record) { + nextId += 1; + if (table === 'sys_metadata') rows.set(`${data.type}|${data.name}`, data); + return { id: `r_${nextId}` }; + }, + async update(_t: string, data: Record, opts?: Record) { + assertEngineUpdateDispatch(data, opts); + return { id: null }; + }, + async delete(_t: string, opts?: Record) { + assertEngineDeleteDispatch(opts); + return { deleted: 0 }; + }, + // [#38174] a create names an installed writable package (ADR-0070 D1). + registry: { registerItem: () => {}, registerObject: () => {}, getPackage: (id: string) => (id === TEST_PKG ? { manifest: { id } } : undefined) }, + }; + const protocol: any = new ObjectStackProtocolImplementation(engine, () => new Map()); + return { protocol, rows }; +} + +async function rejection(promise: Promise): Promise { + try { + await promise; + } catch (err) { + return err; + } + throw new Error('expected the save to be rejected, but it resolved'); +} + +const objectWith = (options: Array>) => ({ + name: 'repairs_probe_dup', + label: 'Dup', + sharingModel: 'private', + fields: { + name: { type: 'text', label: 'Name' }, + s: { type: 'select', label: 'S', options }, + }, +}); + +describe('the save door refuses inline options that repeat a value', () => { + it.each(['publish', 'draft'] as const)('a %s save of the card repro answers 422 INVALID_METADATA at the repeated entry, and nothing is stored', async (mode) => { + const { protocol, rows } = makeProtocol(); + + const err = await rejection(protocol.saveMetaItem({ + type: 'object', + name: 'repairs_probe_dup', + packageId: TEST_PKG, + mode, + item: objectWith([{ value: 'a', label: 'A' }, { value: 'a', label: 'A2' }]), + })); + + expect(err.code).toBe('INVALID_METADATA'); + expect(err.status).toBe(422); + expect(err.issues).toEqual([expect.objectContaining({ path: 'fields.s.options.1.value', code: 'custom' })]); + expect(err.issues[0].message.startsWith("This field's `options` would carry the value 'a' twice")).toBe(true); + expect(rows.size).toBe(0); + }); + + it('control: the same object with distinct values saves', async () => { + const { protocol, rows } = makeProtocol(); + + const result = await protocol.saveMetaItem({ + type: 'object', + name: 'repairs_probe_dup', + packageId: TEST_PKG, + item: objectWith([{ value: 'a', label: 'A' }, { value: 'b', label: 'A2' }]), + }); + + expect(result.success).toBe(true); + expect(rows.size).toBe(1); + }); +}); diff --git a/packages/spec/src/data/field-option-value-repeated.test.ts b/packages/spec/src/data/field-option-value-repeated.test.ts new file mode 100644 index 00000000000..f743aaa6989 --- /dev/null +++ b/packages/spec/src/data/field-option-value-repeated.test.ts @@ -0,0 +1,106 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A field's inline `options` carry each value once, the rule a shared + * `picklist` has always been held to at registration. The refusal lives on + * the field's schema door, so every door that parses a field map (an object, + * an object extension; the metadata save, publish, `os build`, + * `os validate`) refuses the repeat alike. + * + * Value rule, so the refusal is a full `safeParse` failure located at the + * repeated entry's `value`, and every control is a full `safeParse` success. + */ + +import { describe, expect, it } from 'vitest'; +import { Field, FieldSchema } from './field.zod'; +import { ObjectSchema } from './object.zod'; +import { findRepeatedOptionValue } from './option-values-distinct'; +import { ObjectStackDefinitionSchema } from '../stack.zod'; + +type Issue = { code: string; path: PropertyKey[]; message: string }; + +function repeatIssues(result: { success: boolean; error?: { issues: Issue[] } }): Issue[] { + if (result.success) return []; + return (result.error?.issues ?? []).filter((issue) => issue.message.includes('twice')); +} + +describe('inline options with a repeated value', () => { + it('a select whose options repeat a value is refused at the repeated entry', () => { + const result = FieldSchema.safeParse({ + type: 'select', + label: 'S', + options: [{ value: 'a', label: 'A' }, { value: 'b', label: 'B' }, { value: 'a', label: 'A2' }], + }); + expect(result.success).toBe(false); + const issues = repeatIssues(result as never); + expect(issues).toHaveLength(1); + expect(issues[0].code).toBe('custom'); + expect(issues[0].path).toEqual(['options', 2, 'value']); + expect(issues[0].message.split(':')[0]).toBe("This field's `options` would carry the value 'a' twice"); + }); + + it.each(['radio', 'multiselect', 'checkboxes'] as const)('a %s field takes the same verdict', (type) => { + const result = FieldSchema.safeParse({ + type, + label: 'S', + options: [{ value: 'x', label: 'X' }, { value: 'x', label: 'X again' }], + }); + expect(repeatIssues(result as never).map((issue) => issue.path)).toEqual([['options', 1, 'value']]); + }); + + it('the card repro (an object with a repeated inline select value) is refused at the object door', () => { + const result = ObjectSchema.safeParse({ + name: 'repairs_probe_dup', + label: 'Dup', + sharingModel: 'private', + fields: { + name: { type: 'text', label: 'Name' }, + s: { type: 'select', label: 'S', options: [{ value: 'a', label: 'A' }, { value: 'a', label: 'A2' }] }, + }, + }); + expect(result.success).toBe(false); + expect((result as never as { error: { issues: Issue[] } }).error.issues).toHaveLength(1); + expect(repeatIssues(result as never).map((issue) => issue.path)).toEqual([['fields', 's', 'options', 1, 'value']]); + }); + + it('the stack parse `os validate` / `os build` run refuses it too, in an object and in an object extension', () => { + const repeated = { type: 'select', label: 'S', options: [{ value: 'a', label: 'A' }, { value: 'a', label: 'A2' }] }; + const result = ObjectStackDefinitionSchema.safeParse({ + manifest: { id: 'com.example.probe', name: 'Probe', version: '1.0.0', type: 'app' }, + objects: [{ name: 'probe', label: 'Probe', fields: { s: repeated } }], + objectExtensions: [{ extend: 'probe', fields: { t: repeated } }], + }); + expect(result.success).toBe(false); + expect(repeatIssues(result as never).map((issue) => issue.path.slice(-4))).toEqual([ + ['s', 'options', 1, 'value'], + ['t', 'options', 1, 'value'], + ]); + }); + + it('the `Field.select` builder string form refuses two labels that derive one value', () => { + expect(() => ObjectSchema.parse({ + name: 'probe', + label: 'Probe', + fields: { s: Field.select(['In Progress', 'in progress'], { label: 'S' }) }, + })).toThrow(/would carry the value 'in_progress' twice/); + }); + + it('controls: distinct values parse, the same label on two values parses', () => { + expect(FieldSchema.safeParse({ + type: 'select', + label: 'S', + options: [{ value: 'a', label: 'Same' }, { value: 'b', label: 'Same' }], + }).success).toBe(true); + expect(FieldSchema.safeParse({ + type: 'select', + label: 'S', + options: [{ value: 'a', label: 'A' }, { value: 'b', label: 'B' }], + }).success).toBe(true); + }); + + it('findRepeatedOptionValue names the first repeat in list order and skips value-less entries', () => { + expect(findRepeatedOptionValue([{ value: 'a' }, {}, { value: 'b' }, { value: 'b' }, { value: 'a' }])) + .toEqual({ value: 'b', firstIndex: 2, secondIndex: 3 }); + expect(findRepeatedOptionValue([{ value: 'a' }, null, { value: 'b' }])).toBeUndefined(); + }); +}); diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index f69db3a51a0..19bc7d3c3cb 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -20,6 +20,7 @@ import { ConditionalFormattingRuleSchema } from '../shared/conditional-formattin import { FilterConditionSchema } from './filter.zod'; import { fieldKeyGuidanceAsStrictOptions, fieldSchemaAliases, SELECT_OPTION_ALIASES } from './field-key-aliases'; import { DEFAULT_AUTONUMBER_FORMAT } from './autonumber-format'; +import { findRepeatedOptionValue, repeatedOptionValueMessage } from './option-values-distinct'; // #7127 — the `defaultValue` authoring gate: shape discrimination (literal / // runtime token / CEL envelope), the per-token × per-type table, and the // shared literal-vs-stored-contract check. `default-value-shape` reaches @@ -3811,6 +3812,19 @@ export const FieldSchema = lazySchema(() => { } } + // An inline option list carries each value once, as a shared `picklist` + // must (`option-values-distinct.ts` says why, and names the doors). + if (Array.isArray(field.options)) { + const repeat = findRepeatedOptionValue(field.options); + if (repeat) { + ctx.addIssue({ + code: 'custom', + path: ['options', repeat.secondIndex, 'value'], + message: repeatedOptionValueMessage(repeat), + }); + } + } + // [#23809] An option's lifecycle `kind` says where ONE record stands in its // life, so it is honest only on a field holding one option code per record: // a `select` / `radio` that is not `multiple: true`. On any other field's diff --git a/packages/spec/src/data/option-values-distinct.ts b/packages/spec/src/data/option-values-distinct.ts new file mode 100644 index 00000000000..cd43f26453e --- /dev/null +++ b/packages/spec/src/data/option-values-distinct.ts @@ -0,0 +1,64 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * One option list, one entry per stored value. + * + * A record stores an option's `value`; every reader that shows the record + * (lists, chips, reports, a stage renderer) maps the stored value back to + * its option. Two entries for one value make that map + * ambiguous: which label, which colour, which `kind`. A shared `picklist` + * whose options repeat a value has always been refused at registration + * (`findDuplicatePicklistValue` in `@objectstack/objectql`). A field's inline + * `options` is the same list, so it takes the same verdict, here at the + * field's schema door, which every author door parses through: the metadata + * save (draft or active), publish, `os build` and `os validate`. + * + * Values compare by their string form, the form the record validator matches + * a written value against (`SelectOptionValueSchema` already holds a value to + * one lowercase spelling, so no case folding is needed). + */ + +/** An option entry as the field door sees it before its own shape is judged. */ +interface OptionLike { + value?: unknown; +} + +/** The first value two entries of one option list both declare, with both positions. */ +export interface RepeatedOptionValue { + value: string; + firstIndex: number; + secondIndex: number; +} + +/** + * The first value an option list declares twice, in list order, or + * `undefined` when every value is distinct. Entries without a `value` (a + * shape the option schema refuses on its own) are skipped. + */ +export function findRepeatedOptionValue(options: readonly unknown[]): RepeatedOptionValue | undefined { + const seen = new Map(); + for (let index = 0; index < options.length; index += 1) { + const option = options[index] as OptionLike | null | undefined; + if (!option || typeof option !== 'object' || option.value === undefined) continue; + const value = String(option.value); + const firstIndex = seen.get(value); + if (firstIndex !== undefined) return { value, firstIndex, secondIndex: index }; + seen.set(value, index); + } + return undefined; +} + +/** + * The refusal for a field whose inline `options` repeat a value. Worded as + * the shared-picklist refusal is (the list "would carry the value twice", + * remove it or give the new option a value of its own), so an author meets + * one rule whichever of the two option sources they wrote. + */ +export function repeatedOptionValueMessage(repeat: RepeatedOptionValue): string { + return ( + `This field's \`options\` would carry the value '${repeat.value}' twice: it is declared by option ` + + `${repeat.firstIndex} and again by option ${repeat.secondIndex}. A stored value maps back to exactly ` + + 'one option, so a repeated value leaves its label (and colour) ambiguous wherever the record is shown. ' + + 'Remove the repeated value, or give the new option a value of its own.' + ); +} diff --git a/packages/spec/src/migrations/entries/semantic/19.field-option-value-repeated-refused.ts b/packages/spec/src/migrations/entries/semantic/19.field-option-value-repeated-refused.ts new file mode 100644 index 00000000000..2d27878eea7 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.field-option-value-repeated-refused.ts @@ -0,0 +1,36 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// A field's inline `options` that declare one `value` twice are refused at +// the field's schema door (`data/option-values-distinct.ts`), the rule a +// shared `picklist` was already held to at registration. It narrows what the +// metadata save, publish, `os build` and `os validate` accept; no key is +// removed, so there is no tombstone. Measured first-party exposure at this +// change: zero — no example app or platform object repeats an option value. +// Not converted: which of the two labels the author meant is a judgement. +export const entry: SemanticMigration = { + id: 'field-option-value-repeated-refused', + surface: + 'objects[].fields[].options and objectExtensions[].fields[].options, on any field type that takes ' + + 'options, when two entries declare the same `value`; also the `field` a `FieldWidgetPropsSchema` ' + + 'parse carries, which is the same field schema.', + replacement: + 'One entry per value: remove the repeated entry, or give it a value of its own. The refusal names the ' + + 'value and the positions of both entries.', + reason: + 'A record stores an option\'s value, and every reader that shows the record (lists, chips, reports, ' + + 'a stage renderer) maps that value back to one option. Two entries for one value left its label ' + + 'and colour ambiguous. A shared picklist with a repeated value was already refused at registration; ' + + 'the same list written inline on the field passed every door. No rewrite can choose between the two ' + + 'labels, so the author decides.', + acceptanceCriteria: + 'Every option list in the stack declares each value once, and `os validate` passes. A field whose ' + + '`options` repeat a value is refused at parse with an issue at `fields.NAME.options.INDEX.value` that ' + + 'names the value, and the metadata save and publish of such an object are refused. A stored object ' + + 'whose body carries the repeat still registers at boot and is served badged invalid, and is refused at ' + + 'its next save or publish until the repeat is removed. A stored object extension row carrying the ' + + 'repeat is not registered at boot (the loader logs and skips it), so the fields it adds are absent ' + + 'until the row is fixed.', + 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 4481d5749f6..495d0d9f2b3 100644 --- a/packages/spec/src/migrations/semantic-relevance-coverage-38929.test.ts +++ b/packages/spec/src/migrations/semantic-relevance-coverage-38929.test.ts @@ -293,6 +293,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-option-value-repeated-refused', 'field-precision-zero-refused', 'lookup-depends-on-param-computed-field-refused', 'lookup-depends-on-param-computed-field-refused-on-tree', diff --git a/packages/spec/src/migrations/semantic-relevance.test.ts b/packages/spec/src/migrations/semantic-relevance.test.ts index 2c659a0f946..77b6df0cc4f 100644 --- a/packages/spec/src/migrations/semantic-relevance.test.ts +++ b/packages/spec/src/migrations/semantic-relevance.test.ts @@ -83,6 +83,7 @@ const EXPECTED_RELEVANCE: Readonly> = { '19:compose-stacks-job-name-across-packages-refused': ['jobs'], '19:field-group-shadowed-six-highlights': ['objects', 'objectExtensions'], '19:field-inline-edit-boolean-retired': ['objects', 'objectExtensions'], + '19:field-option-value-repeated-refused': ['objects', 'objectExtensions'], '19:field-precision-zero-refused': ['objects', 'objectExtensions'], '19:flow-concurrent-branch-durable-pause-refused': ['flows'], '19:flow-condition-bare-ordering-before-record-date-arithmetic-refused': ['flows'], diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 86a1d4b2e76..85334ad87e9 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -1666,6 +1666,21 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/metadata-protocol/src/protocol.option-value-repeated-refusal.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/protocol.option-value-repeated-refusal.test.ts", + "verb": "findOne", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/protocol.option-value-repeated-refusal.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/metadata-protocol/src/protocol.org-scoped-write-refused.test.ts", "verb": "delete",