diff --git a/.changeset/39661-pair-rule-suffix-app-shell.md b/.changeset/39661-pair-rule-suffix-app-shell.md new file mode 100644 index 00000000000..7de15cca202 --- /dev/null +++ b/.changeset/39661-pair-rule-suffix-app-shell.md @@ -0,0 +1,14 @@ +--- +'@object-ui/app-shell': minor +--- + +feat(studio)!: a customer rule on an installed object is named with the `__c` suffix + +Clause-②: yes (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** for a Studio user adding a validation rule to an installed object: the name Studio mints (`validation_3`) or reads off the message (`too_big`) now ends in `__c` (`validation_3__c`, `too_big__c`), the spelling the extension door requires; a package rule's name stays refused. A rule saved before with an unsuffixed name keeps running, and its extension's next save is refused until it is renamed. A rule saved before under a package rule's name does not run: the Validations tab lists the package's rule as the package's and the customer's copy beside it, named as taken, until it is renamed or deleted. + +**Migration (FROM → TO):** a validation rule a `.custom` package's object extension adds, FROM `NAME` TO `NAME__c` (`credit_check` → `credit_check__c`); a rule already ending in `__c` that a package also ships takes another name of its own ending in `__c`; a rule whose only purpose was to switch off or reword a package rule is deleted (a customer rule never replaces or switches off a package rule). Rename it in Studio's Validations tab or through `PUT /api/v1/meta/object_extension/OBJECT?package=BASE.custom`, then publish. The upgrade notice is `pair-validation-rule-suffix` (`os migrate meta`). diff --git a/.changeset/39661-pair-rule-suffix-cli.md b/.changeset/39661-pair-rule-suffix-cli.md new file mode 100644 index 00000000000..c8588d6b3ff --- /dev/null +++ b/.changeset/39661-pair-rule-suffix-cli.md @@ -0,0 +1,14 @@ +--- +'@objectstack/cli': minor +--- + +feat(cli)!: `os validate` and `os build` refuse a `.custom` package's validation rule under another package's rule name, or without the `__c` suffix + +Clause-②: yes (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** for a project whose `.custom` package's `objectExtensions[].validations` name a rule without the `__c` suffix, or with the name of a rule another package of the artifact ships for the object: `os validate` and `os build` passed it; they now exit 1 with the save door's own sentence, located at `objectExtensions[N].validations[M].name` (prefixed `packages[J].manifest.` in a multi-package artifact), and `os build` writes no artifact. + +**Migration (FROM → TO):** a validation rule a `.custom` package's object extension adds, FROM `NAME` TO `NAME__c` (`credit_check` → `credit_check__c`); a rule already ending in `__c` that a package also ships takes another name of its own ending in `__c`; a rule whose only purpose was to switch off or reword a package rule is deleted (a customer rule never replaces or switches off a package rule). Rename it in Studio's Validations tab or through `PUT /api/v1/meta/object_extension/OBJECT?package=BASE.custom`, then publish. The upgrade notice is `pair-validation-rule-suffix` (`os migrate meta`). diff --git a/.changeset/39661-pair-rule-suffix-metadata-protocol.md b/.changeset/39661-pair-rule-suffix-metadata-protocol.md new file mode 100644 index 00000000000..2516f7618bd --- /dev/null +++ b/.changeset/39661-pair-rule-suffix-metadata-protocol.md @@ -0,0 +1,14 @@ +--- +'@objectstack/metadata-protocol': minor +--- + +feat(metadata-protocol)!: the `object_extension` save door refuses a `.custom` package's validation rule under a package rule's name, or without the `__c` suffix + +Clause-②: yes (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** for a caller saving, publishing or restoring an `object_extension` item into a `.custom` package (Studio, `PUT /api/v1/meta/object_extension/OBJECT?package=BASE.custom`, the MCP and AI draft doors): a validation rule whose name is the name of a rule another package ships for the target, or does not end in `__c`, answered 200; it now answers `400 VALIDATION_ERROR`, one issue per rule at `validations[N].name`, the sentence naming the rule and the fix. An extension of the `.custom` package's own object, and any package that is not `.custom`, are not judged. The judge is exported as `judgePairValidationRuleNames` (with `pairValidationRuleNameRefusalError`), the one `os validate` and `os build` ask. + +**Migration (FROM → TO):** a validation rule a `.custom` package's object extension adds, FROM `NAME` TO `NAME__c` (`credit_check` → `credit_check__c`); a rule already ending in `__c` that a package also ships takes another name of its own ending in `__c`; a rule whose only purpose was to switch off or reword a package rule is deleted (a customer rule never replaces or switches off a package rule). Rename it in Studio's Validations tab or through `PUT /api/v1/meta/object_extension/OBJECT?package=BASE.custom`, then publish. The upgrade notice is `pair-validation-rule-suffix` (`os migrate meta`). diff --git a/.changeset/39661-pair-rule-suffix-objectql.md b/.changeset/39661-pair-rule-suffix-objectql.md new file mode 100644 index 00000000000..1d7c9e05d6f --- /dev/null +++ b/.changeset/39661-pair-rule-suffix-objectql.md @@ -0,0 +1,14 @@ +--- +'@objectstack/objectql': minor +--- + +feat(objectql)!: a `.custom` package's validation rule never replaces or switches off a package rule in the registry fold + +Clause-②: yes (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** for a deployment that stored a `.custom` extension rule under a package rule's name: the fold merged it by name as it merges two vendor packages, so it replaced the package's rule, condition included, and `active: false` switched it off; a package version that later shipped a rule under a name the customer had used was replaced the same way. Now the stored copy is left out, the package's rule is enforced, and the boot log names the copy once at `error` (`[pair_validation_rule_name_held]`) with the rename; nothing throws. Between two vendor packages a later package's same-named rule still replaces the earlier one (ADR-0029 D9.2a, unchanged). + +**Migration (FROM → TO):** a validation rule a `.custom` package's object extension adds, FROM `NAME` TO `NAME__c` (`credit_check` → `credit_check__c`); a rule already ending in `__c` that a package also ships takes another name of its own ending in `__c`; a rule whose only purpose was to switch off or reword a package rule is deleted (a customer rule never replaces or switches off a package rule). Rename it in Studio's Validations tab or through `PUT /api/v1/meta/object_extension/OBJECT?package=BASE.custom`, then publish. The upgrade notice is `pair-validation-rule-suffix` (`os migrate meta`). diff --git a/.changeset/39661-pair-rule-suffix-spec.md b/.changeset/39661-pair-rule-suffix-spec.md new file mode 100644 index 00000000000..1b5a5034ae6 --- /dev/null +++ b/.changeset/39661-pair-rule-suffix-spec.md @@ -0,0 +1,14 @@ +--- +'@objectstack/spec': minor +--- + +feat(spec)!: `EXTENSION_FIELD_SUFFIX` (`__c`) is the one customer suffix for a validation rule a `.custom` package adds too, and the `pair-validation-rule-suffix` upgrade notice is registered + +Clause-②: yes (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** for a customer whose `.custom` package's object extension adds validation rules to another package's object: each rule name now ends in `__c` and may not be the name of a rule a package ships for that object (ruling 7411414171). `EXTENSION_FIELD_SUFFIX` and `isExtensionFieldName` (`@objectstack/spec/data`) are the one spelling of that suffix for extension fields, picklist extension values and these rules; no second constant. The protocol-19 upgrade notice `pair-validation-rule-suffix` lists the change for `os migrate meta`. + +**Migration (FROM → TO):** a validation rule a `.custom` package's object extension adds, FROM `NAME` TO `NAME__c` (`credit_check` → `credit_check__c`); a rule already ending in `__c` that a package also ships takes another name of its own ending in `__c`; a rule whose only purpose was to switch off or reword a package rule is deleted (a customer rule never replaces or switches off a package rule). Rename it in Studio's Validations tab or through `PUT /api/v1/meta/object_extension/OBJECT?package=BASE.custom`, then publish. The upgrade notice is `pair-validation-rule-suffix` (`os migrate meta`). diff --git a/content/docs/data-modeling/object-extensions.mdx b/content/docs/data-modeling/object-extensions.mdx index 8fe0d270fe0..1810e7c9dc2 100644 --- a/content/docs/data-modeling/object-extensions.mdx +++ b/content/docs/data-modeling/object-extensions.mdx @@ -64,8 +64,8 @@ check that spelling first. |:---|:---| | `fields` | **Additive.** Merged into the target's field map. A name the target already has is **replaced**, not merged — never in a `.custom` package, whose added fields all end in `__c`. | | `fieldPatches` | **Applied, field by field.** Changes the *display* of one of the target's own fields — never one an extension adds — without replacing it — [below](#relabelling-a-vendor-field). | -| `validations` | **Concatenated.** Your rules run alongside the owner's; neither replaces the other. | -| `indexes` | **Concatenated**, same as validations. | +| `validations` | **Added by name.** Your rules run beside the owner's. Between two vendor packages, a later package's rule replaces an earlier rule of the same name. In a `.custom` package, the rules you add run beside the package's rules: each name ends in `__c` and may not be the name of a package's rule. Save and `os validate` refuse either mistake, and a stored rule under a package rule's name does not run: the package's rule does. | +| `indexes` | **Concatenated.** Your indexes are added to the owner's. | | `label` | Replaces the target's label — with one exception, [below](#extensions-and-tenant-customization). A new `label` with no `pluralLabel` beside it also takes the target's plural off, since that plural names the old label: the object is served as one that declares no plural, and lists title it by its label. Set `pluralLabel` too to serve one. A plural the tenant set stays. | | `pluralLabel` | Same as `label`. | | `description` | Same as `label`. | diff --git a/packages/cli/src/commands/compile.ts b/packages/cli/src/commands/compile.ts index 03dc36bb399..f11bd1e19f9 100644 --- a/packages/cli/src/commands/compile.ts +++ b/packages/cli/src/commands/compile.ts @@ -104,7 +104,7 @@ import { findExtensionFieldSuffixRefusals } from '../utils/extension-field-suffi // [ADR-0146 D10] …and the arrangement of an extended object, the paired // `.custom` package's alone: the same walk and the same doors' judge // (`judgeExtensionArrangement`). -import { findExtensionArrangementRefusals } from '../utils/extension-arrangement.js'; +import { findExtensionArrangementRefusals, findPairValidationRuleNameRefusals } from '../utils/extension-arrangement.js'; // [#29051] An undeclared top-level flow cycle — the walk `os validate` step // 3a-vii runs, over the automation engine's own judge. @@ -1039,6 +1039,27 @@ export default class Compile extends Command { this.exit(1); } + // 3b-iii-bis-3. [ruling 7411414171 (B)] A validation rule a `.custom` + // package's extension adds ends in `__c` and carries no rule name + // another package of the artifact ships for the object — the SAME + // call `os validate` makes at its step 3a-iv-ter, the save door's own + // judge (`judgePairValidationRuleNames`); no artifact is written. + const pairRuleRefusals = findPairValidationRuleNameRefusals(result.data as Record); + if (pairRuleRefusals.length > 0) { + if (flags.json) { + await emitJson({ success: false, errors: pairRuleRefusals, warnings: warningsSoFar(), conversions: conversionNotices }, 0, { compact: true }); + this.exit(1); + } + const n = pairRuleRefusals.length; + console.log(''); + printError(`${n} validation rule${n > 1 ? 's' : ''} a \`.custom\` package adds ${n > 1 ? 'are' : 'is'} named against the customer rule naming (\`__c\`, no package rule's name)`); + printBulletList( + pairRuleRefusals.map((r) => `${r.path} [${r.code}] ${r.message}`), + { noun: 'validation-rule name refusal(s)', remedy: JSON_FULL_LIST_REMEDY }, + ); + this.exit(1); + } + // 3b-iii-ter. [#28893] Flow region shape (ADR-0031) is judged by the // rule table at step 3b since #29049 (`flow-region-shape-invalid`), // the same verdict `os validate` and `os lint` give. diff --git a/packages/cli/src/commands/validate.ts b/packages/cli/src/commands/validate.ts index 46d7f72639a..b02f71598e2 100644 --- a/packages/cli/src/commands/validate.ts +++ b/packages/cli/src/commands/validate.ts @@ -96,7 +96,7 @@ import { findNamespaceAddressLiteralRefusals } from '../utils/namespace-address- // door's own judge, walked over the artifact's packages. import { findOverrideDeclarationRefusals, overrideRefusalLine } from '../utils/override-declarations.js'; import { findExtensionFieldSuffixRefusals } from '../utils/extension-field-suffix.js'; -import { findExtensionArrangementRefusals } from '../utils/extension-arrangement.js'; +import { findExtensionArrangementRefusals, findPairValidationRuleNameRefusals } from '../utils/extension-arrangement.js'; // [ADR-0146 D10, second rule] The field-patch target check's walk; the verdict // is the marketplace install door's own judge. import { findFieldPatchTargetRefusals } from '../utils/field-patch-targets.js'; @@ -986,6 +986,34 @@ export default class Validate extends Command { this.exit(1); } + // 3a-iv-ter. [ruling 7411414171 (B)] A validation rule a `.custom` + // package's extension adds ends in `__c` and carries no rule name + // another package of the artifact ships for the object. The verdict + // is the `object_extension` save door's own + // (`judgePairValidationRuleNames`), so the sentence is the door's; see + // `utils/extension-arrangement.ts`. + const pairRuleRefusals = findPairValidationRuleNameRefusals(result.data as Record); + if (pairRuleRefusals.length > 0) { + if (flags.json) { + await emitJson({ + valid: false, + errors: pairRuleRefusals, + warnings: warningsSoFar(), + conversions: conversionNotices, + duration: timer.elapsed(), + }); + this.exit(1); + } + const n = pairRuleRefusals.length; + console.log(''); + printError(`${n} validation rule${n > 1 ? 's' : ''} a \`.custom\` package adds ${n > 1 ? 'are' : 'is'} named against the customer rule naming (\`__c\`, no package rule's name)`); + printBulletList( + pairRuleRefusals.map((r) => `${r.path} [${r.code}] ${r.message}`), + { noun: 'validation-rule name refusal(s)', remedy: JSON_FULL_LIST_REMEDY }, + ); + this.exit(1); + } + // 3a-v. [ADR-0146 D10, second rule] The field-patch target check, at // author time: an object extension's `fieldPatches` naming a field // its target does not have, or an option value the field does not diff --git a/packages/cli/src/utils/extension-arrangement.test.ts b/packages/cli/src/utils/extension-arrangement.test.ts index 124910a2a26..89f115310bd 100644 --- a/packages/cli/src/utils/extension-arrangement.test.ts +++ b/packages/cli/src/utils/extension-arrangement.test.ts @@ -12,8 +12,8 @@ */ import { describe, expect, it } from 'vitest'; -import { judgeExtensionArrangement } from '@objectstack/metadata-protocol'; -import { findExtensionArrangementRefusals } from './extension-arrangement.js'; +import { judgeExtensionArrangement, judgePairValidationRuleNames } from '@objectstack/metadata-protocol'; +import { findExtensionArrangementRefusals, findPairValidationRuleNameRefusals } from './extension-arrangement.js'; const VENDOR = 'com.acme.partner'; const PAIR = 'com.acme.crm.custom'; @@ -61,3 +61,49 @@ describe('ADR-0146 D10 — the walk os validate and os build hand the arrangemen expect(findExtensionArrangementRefusals({ objectExtensions: extensions })).toEqual([]); }); }); + +/** + * [ruling 7411414171 (B)] `findPairValidationRuleNameRefusals` — the packages + * `os validate` and `os build` hand the save door's rule-name judge, and the + * package rules it reads off the artifact. Every row's message is the judge's. + */ +describe('ruling 7411414171 — the walk os validate and os build hand the rule-name judge', () => { + const BASE = 'com.acme.crm'; + const rule = (name: string) => ({ type: 'script', name, message: 'No.', condition: 'record.amount > 1' }); + const account = { name: 'crm_account', fields: {}, validations: [rule('credit_cap')] }; + + it('a `.custom` stack: an unsuffixed rule is refused under the stack\'s id, the message the judge\'s', () => { + const ext = [{ extend: 'crm_account', validations: [rule('big_deal'), rule('big_deal__c')] }]; + const rows = findPairValidationRuleNameRefusals({ manifest: { id: PAIR }, objectExtensions: ext }); + const judged = judgePairValidationRuleNames({ packageId: PAIR, objectExtensions: ext }); + expect(rows).toEqual([{ + path: 'objectExtensions[0].validations[0].name', code: 'VALIDATION_ERROR', rule: 'unsuffixed_in_pair', + packageId: PAIR, message: judged[0]!.message, + }]); + }); + + it('a `packages[]` artifact: a pair rule named like another package\'s rule for the object is refused, naming it', () => { + const rows = findPairValidationRuleNameRefusals({ + manifest: { id: BASE }, + packages: [ + { manifest: { id: BASE, objects: [account] } }, + { manifest: { id: PAIR, objectExtensions: [{ extend: 'crm_account', validations: [rule('credit_cap')] }] } }, + ], + }); + expect(rows.map((r) => [r.path, r.rule, r.packageId])).toEqual([ + ['packages[1].manifest.objectExtensions[0].validations[0].name', 'held_by_package', PAIR], + ]); + expect(rows[0]!.message).toContain(`package '${BASE}'`); + }); + + it('CONTROL: a plain package, and a `.custom` package\'s own object, are not judged', () => { + expect(findPairValidationRuleNameRefusals({ + manifest: { id: VENDOR }, objectExtensions: [{ extend: 'crm_account', validations: [rule('big_deal')] }], + })).toEqual([]); + expect(findPairValidationRuleNameRefusals({ + manifest: { id: PAIR }, + objects: [{ name: 'crm_note', fields: {} }], + objectExtensions: [{ extend: 'crm_note', validations: [rule('big_deal')] }], + })).toEqual([]); + }); +}); diff --git a/packages/cli/src/utils/extension-arrangement.ts b/packages/cli/src/utils/extension-arrangement.ts index 2097c0d1b9a..ba488b39496 100644 --- a/packages/cli/src/utils/extension-arrangement.ts +++ b/packages/cli/src/utils/extension-arrangement.ts @@ -14,9 +14,16 @@ * `findExtensionFieldSuffixRefusals` (`./extension-field-suffix.ts`) takes. A * stack naming no package id is not judged, as the judge skips a write bound * to no package. + * + * [ruling 7411414171 (B)] {@link findPairValidationRuleNameRefusals} hands the + * same packages to the save door's rule-name judge + * (`judgePairValidationRuleNames`): a validation rule a `.custom` package's + * extension adds ends in `__c`, and carries no rule name another package of + * the artifact ships for the object. */ -import { judgeExtensionArrangement } from '@objectstack/metadata-protocol'; +import { judgeExtensionArrangement, judgePairValidationRuleNames } from '@objectstack/metadata-protocol'; +import { isCustomizationPackage } from '@objectstack/spec/kernel'; import { artifactPackages } from './artifact-packages.js'; @@ -51,3 +58,88 @@ export function findExtensionArrangementRefusals(parsed: Record path: r.path, code: 'VALIDATION_ERROR' as const, key: r.key, packageId: r.packageId, message: r.message, }))); } + +/** One refused rule name, located. `message` is the save door's sentence, verbatim. */ +export interface PairValidationRuleNameRefusalRow { + /** Where the name sits in the parsed stack, e.g. `packages[1].manifest.objectExtensions[0].validations[0].name`. */ + path: string; + /** The code the save door refuses the same rule with. */ + code: 'VALIDATION_ERROR'; + /** `held_by_package` or `unsuffixed_in_pair`. */ + rule: string; + /** The package the extension is declared in. */ + packageId: string; + message: string; +} + +/** The names of the objects a package body declares: an array of `{ name }`, or a record keyed by name. */ +function objectNamesOf(objects: unknown): Set { + const out = new Set(); + if (Array.isArray(objects)) { + for (const o of objects) if (isRecord(o) && typeof o.name === 'string') out.add(o.name); + } else if (isRecord(objects)) { + for (const [key, o] of Object.entries(objects)) out.add(isRecord(o) && typeof o.name === 'string' ? o.name : key); + } + return out; +} + +/** The rules a package body ships for `object`: its own object's, then its extensions'. */ +function ruleNamesFor(body: Record, object: string): string[] { + const names: string[] = []; + const collect = (rules: unknown) => { + if (!Array.isArray(rules)) return; + for (const r of rules) if (isRecord(r) && typeof r.name === 'string' && r.name !== '') names.push(r.name); + }; + const objects = body.objects; + if (Array.isArray(objects)) { + for (const o of objects) if (isRecord(o) && o.name === object) collect(o.validations); + } else if (isRecord(objects)) { + for (const [key, o] of Object.entries(objects)) { + if (isRecord(o) && (o.name ?? key) === object) collect(o.validations); + } + } + if (Array.isArray(body.objectExtensions)) { + for (const e of body.objectExtensions) if (isRecord(e) && e.extend === object) collect(e.validations); + } + return names; +} + +/** + * [ruling 7411414171 (B)] Every validation rule name a `.custom` package's + * object extension adds that the `object_extension` save door refuses: one + * whose name does not end in `__c`, or that carries the name of a rule another + * package of this artifact ships for the same object. The verdict is + * `@objectstack/metadata-protocol`'s `judgePairValidationRuleNames`, the save + * door's own, so the sentence is the door's. The package rules are the ones + * the artifact carries: a base the stack only depends on is not read here, and + * its names are judged at the save door and the fold. + */ +export function findPairValidationRuleNameRefusals(parsed: Record): PairValidationRuleNameRefusalRow[] { + const entries = artifactPackages(parsed); + const subjects = entries.length > 0 + ? entries.map(({ index, id, body }) => ({ id, body, at: `packages[${index}].manifest.` })) + : [{ + id: isRecord(parsed.manifest) ? (parsed.manifest.id as string | undefined) : undefined, + body: parsed, + at: '', + }]; + return subjects.flatMap(({ id, body, at }) => { + const own = objectNamesOf(body.objects); + return judgePairValidationRuleNames({ + packageId: id, + objectExtensions: body.objectExtensions, + ownsObject: (object) => own.has(object), + packageRulesOf: (object) => { + const held = new Map(); + for (const other of entries) { + if (other.id === id || isCustomizationPackage(other.id)) continue; + for (const name of ruleNamesFor(other.body, object)) if (!held.has(name)) held.set(name, other.id); + } + return held; + }, + at, + }).map((r) => ({ + path: r.path, code: 'VALIDATION_ERROR' as const, rule: r.rule, packageId: r.packageId, message: r.message, + })); + }); +} diff --git a/packages/cli/test/validate-build-gate-parity.test.ts b/packages/cli/test/validate-build-gate-parity.test.ts index de7d161bb68..a880e3263d2 100644 --- a/packages/cli/test/validate-build-gate-parity.test.ts +++ b/packages/cli/test/validate-build-gate-parity.test.ts @@ -234,6 +234,12 @@ const SHARED_NON_REGISTRY_GATES: readonly string[] = [ // rule is handed does not carry. Both doors make the call, beside the // `__c` reservation's. 'findExtensionArrangementRefusals', + // [ruling 7411414171 (B)] A validation rule a `.custom` package's extension + // adds ends in `__c` and carries no rule name another package of the + // artifact ships, judged by the save door's own + // `judgePairValidationRuleNames`. Not a registry rule, for the reason the + // two rows above give: the verdict turns on the declaring package's id. + 'findPairValidationRuleNameRefusals', // [#29051] An undeclared cycle in a flow's top-level graph (ADR-0044), // judged by the automation engine's own registration judge // (`findUndeclaredFlowCycle`, `@objectstack/metadata-core`), which the diff --git a/packages/cli/test/validate-pair-validation-rule-name-39661.test.ts b/packages/cli/test/validate-pair-validation-rule-name-39661.test.ts new file mode 100644 index 00000000000..b50148921a5 --- /dev/null +++ b/packages/cli/test/validate-pair-validation-rule-name-39661.test.ts @@ -0,0 +1,136 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #39661, ruling 7411414171 (B) — `os validate` refuses what the + * `object_extension` save door refuses: a validation rule a `.custom` + * package's object extension adds whose name does not end in `__c`, or that + * carries the name of a rule another package of the artifact ships for the + * same object. The verdict is the save door's own judge, so the sentence is + * the door's. Pinned at the command: each case exits 1 with the rule's + * `name` path on `errors`; the suffixed rule validates clean. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { execFile } from 'node:child_process'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { childEnv } from './helpers/serve-process.js'; +import { linkSpec } from './helpers/define-stack-fixture.js'; + +const HERE = resolve(fileURLToPath(import.meta.url), '..'); +const CLI = resolve(HERE, '../bin/run-dev.js'); +const TSX = resolve(HERE, '../../../node_modules/.bin/tsx'); + +/** A `.custom` stack extending the base's `crm_account` with one rule named `rule`. */ +const pairStack = (rule: string) => ` +import { defineStack } from '@objectstack/spec'; + +export default defineStack({ + manifest: { + id: 'com.acme.crm.custom', name: 'crm-custom', version: '1.0.0', type: 'app', namespace: 'crm_custom', + dependencies: { 'com.acme.crm': '^1.0.0' }, + }, + objectExtensions: [ + { extend: 'crm_account', validations: [ + { type: 'script', name: '${rule}', message: 'Too big.', condition: 'record.amount > 100' }, + ] }, + ], +}, { strict: false }); +`; + +/** A two-package artifact: the base ships `credit_cap`, and its `.custom` pair adds a rule of the same name. */ +const SAME_NAME_ARTIFACT = ` +import { defineStack } from '@objectstack/spec'; + +const account = { + name: 'crm_account', label: 'Account', sharingModel: 'private', + fields: { amount: { type: 'number', label: 'Amount', required: true } }, + validations: [{ type: 'script', name: 'credit_cap', message: 'Over the cap.', condition: 'record.amount > 100' }], +}; +const baseManifest = { id: 'com.acme.crm', name: 'crm', version: '1.0.0', type: 'app', namespace: 'crm' }; +const pairManifest = { + id: 'com.acme.crm.custom', name: 'crm-custom', version: '1.0.0', type: 'module', namespace: 'crm_custom', + dependencies: { 'com.acme.crm': '^1.0.0' }, +}; +const extension = { + extend: 'crm_account', + validations: [{ type: 'script', name: 'credit_cap', message: 'Off.', condition: 'record.amount > 100', active: false }], +}; + +export default defineStack({ + manifest: baseManifest, + objects: [account], + packages: [ + { manifest: { ...baseManifest, objects: [account] } }, + { manifest: { ...pairManifest, objectExtensions: [extension] } }, + ], +}, { strict: false }); +`; + +interface Run { + code: number; + stdout: string; + stderr: string; +} + +function runValidate(cwd: string, json = true): Promise { + return new Promise((resolvePromise) => { + execFile( + TSX, + [CLI, 'validate', ...(json ? ['--json'] : [])], + // `childEnv()`, never a bulk `process.env` copy (check:cli-test-child-env). + { cwd, maxBuffer: 16 * 1024 * 1024, env: childEnv({ NO_COLOR: '1' }) }, + (err, stdout, stderr) => { + resolvePromise({ + code: err ? (typeof (err as { code?: unknown }).code === 'number' ? (err as unknown as { code: number }).code : 1) : 0, + stdout: String(stdout), + stderr: String(stderr), + }); + }, + ); + }); +} + +const dirs: Record<'unsuffixed' | 'sameName' | 'suffixed', string> = { unsuffixed: '', sameName: '', suffixed: '' }; + +beforeAll(() => { + const make = (key: keyof typeof dirs, source: string) => { + dirs[key] = mkdtempSync(join(tmpdir(), `os-validate-pair-rule-${key}-`)); + writeFileSync(join(dirs[key], 'objectstack.config.ts'), source); + linkSpec(dirs[key]); + }; + make('unsuffixed', pairStack('big_deal')); + make('sameName', SAME_NAME_ARTIFACT); + make('suffixed', pairStack('big_deal__c')); +}); + +afterAll(() => { + for (const dir of Object.values(dirs)) if (dir) rmSync(dir, { recursive: true, force: true }); +}); + +describe('#39661 — `os validate` refuses the pair rule names the save door refuses', () => { + it('an unsuffixed rule in a `.custom` package\'s extension exits 1, the rule\'s name path on `errors`', async () => { + const run = await runValidate(dirs.unsuffixed); + expect(run.code, run.stdout + run.stderr).toBe(1); + const payload = JSON.parse(run.stdout) as { valid: boolean; errors: Array> }; + expect(payload.valid).toBe(false); + expect(payload.errors.map((e) => [e.path, e.code, e.packageId])).toEqual([ + ['objectExtensions[0].validations[0].name', 'VALIDATION_ERROR', 'com.acme.crm.custom'], + ]); + expect(String(payload.errors[0]!.message)).toContain('big_deal__c'); + }, 120_000); + + it('a rule named like another package\'s rule for the object exits 1, printed without `--json`', async () => { + const run = await runValidate(dirs.sameName, false); + expect(run.code, run.stdout + run.stderr).toBe(1); + expect(run.stdout + run.stderr).toContain('packages[1].manifest.objectExtensions[0].validations[0].name [VALIDATION_ERROR]'); + }, 120_000); + + it('CONTROL — a suffixed rule of its own name validates clean', async () => { + const run = await runValidate(dirs.suffixed); + expect(run.code, run.stdout + run.stderr).toBe(0); + expect((JSON.parse(run.stdout) as { valid: boolean }).valid).toBe(true); + }, 120_000); +}); diff --git a/packages/metadata-protocol/src/index.ts b/packages/metadata-protocol/src/index.ts index fd43dd623aa..d599b3fe1a3 100644 --- a/packages/metadata-protocol/src/index.ts +++ b/packages/metadata-protocol/src/index.ts @@ -67,6 +67,10 @@ export { judgeExtensionFieldSuffix, extensionFieldSuffixRefusalError, objectBody // `relatedLists`, asked by the save doors here and by `os validate` / // `os build` and the marketplace install outside. export { judgeExtensionArrangement, extensionArrangementRefusalError, type ExtensionArrangementRefusal, type ExtensionArrangementSubject } from './protocol-extension-arrangement.js'; +// [ruling 7411414171] A validation rule a `.custom` package's extension adds +// ends in `__c` and carries no package rule's name: one judge, asked by the +// `object_extension` save doors here and by `os validate` / `os build`. +export { judgePairValidationRuleNames, pairValidationRuleNameRefusalError, type PairValidationRuleNameRefusal, type PairValidationRuleNameRule, type PairValidationRuleNameSubject } from './protocol-object-extension-item.js'; // [ADR-0146 D10, second rule] An extension's `fields` entry re-declaring an // owner's field beyond the display-property whitelist: one judge, asked by the // save doors here and by `os validate` and the marketplace install outside. diff --git a/packages/metadata-protocol/src/protocol-object-extension-item.ts b/packages/metadata-protocol/src/protocol-object-extension-item.ts index e36c0275bdf..80fc99df2c8 100644 --- a/packages/metadata-protocol/src/protocol-object-extension-item.ts +++ b/packages/metadata-protocol/src/protocol-object-extension-item.ts @@ -35,8 +35,8 @@ */ import { z } from 'zod'; -import { ObjectExtensionSchema } from '@objectstack/spec/data'; -import { MetadataProtectionFields } from '@objectstack/spec/kernel'; +import { EXTENSION_FIELD_SUFFIX, ObjectExtensionSchema, isExtensionFieldName } from '@objectstack/spec/data'; +import { MetadataProtectionFields, isCustomizationPackage } from '@objectstack/spec/kernel'; import { closureDependencyRemedy, narrowObjectsToPackageClosure } from '@objectstack/lint/runtime'; import type { RuntimePackageScope } from '@objectstack/lint/runtime'; import { judgeExtensionFieldSuffix, extensionFieldSuffixRefusalError } from './protocol-extension-field-suffix.js'; @@ -178,6 +178,12 @@ export interface ObjectExtensionItemSubject { * target's pairs (`pairsOf` of the owner `getObjectOwner` answers, over * the registry's installed manifests), it is refused naming the pair. A * registry without `getObjectOwner` leaves the pair unasked. + * 9. Ruling 7411414171 (B): in a `.custom` package, a validation rule the + * extension adds may not carry the name of a rule another package ships + * for the target (the owner's and every other contributor's, as + * `getObjectContributors` lists them), and its name ends in `__c` + * ({@link judgePairValidationRuleNames}). The suffix needs no registry; + * the package rules are read where the registry lists the contributors. * * Whether the package is writable is the door's own refusal * (`WRITABLE_PACKAGE_REQUIRED`), asked before any of this. @@ -276,9 +282,170 @@ export function objectExtensionItemRefusal( }) .map((r) => ({ ...r, path: r.path.slice('objectExtensions[0].'.length) })); if (arrangement.length > 0) return extensionArrangementRefusalError(arrangement); + + // 9. + const ruleNames = judgePairValidationRuleNames({ + packageId: binding, + objectExtensions: [item], + packageRulesOf: () => packageRuleHolders(registry?.getObjectContributors?.(target), binding), + ownsObject: () => (ownerContributor?.packageId ?? owner) === binding, + }).map((r) => ({ ...r, path: r.path.slice('objectExtensions[0].'.length) })); + if (ruleNames.length > 0) return pairValidationRuleNameRefusalError(ruleNames); return undefined; } +/** + * The rules other packages ship for an object, by name, each with the package + * that holds it: every contributor's `validations` (in the registry's order) + * except the writing package's own and a `.custom` package's, which are the + * customer's layer, not a package's. + */ +function packageRuleHolders( + contributors: ReadonlyArray<{ packageId: string; definition?: unknown }> | undefined, + binding: string, +): ReadonlyMap { + const out = new Map(); + for (const contributor of contributors ?? []) { + if (contributor.packageId === binding || isCustomizationPackage(contributor.packageId)) continue; + const rules = isRecord(contributor.definition) ? contributor.definition.validations : undefined; + if (!Array.isArray(rules)) continue; + for (const rule of rules) { + const name = isRecord(rule) ? rule.name : undefined; + if (typeof name === 'string' && name !== '' && !out.has(name)) out.set(name, contributor.packageId); + } + } + return out; +} + +/** Why a validation rule a `.custom` package's extension adds is refused. */ +export type PairValidationRuleNameRule = 'held_by_package' | 'unsuffixed_in_pair'; + +/** One refused rule name, located. */ +export interface PairValidationRuleNameRefusal { + rule: PairValidationRuleNameRule; + /** Where the name sits in the judged body, e.g. `objectExtensions[0].validations[1].name`. */ + path: string; + /** The extension's `extend` target. */ + object: string; + /** The rule name as written. */ + name: string; + /** The package the body is written into. */ + packageId: string; + /** `held_by_package`: the package whose rule holds the name, when known. */ + holder?: string; + /** The door's sentence: what is wrong, then the prescription. */ + message: string; +} + +/** What a door hands {@link judgePairValidationRuleNames}. */ +export interface PairValidationRuleNameSubject { + /** The package the body is written into. Not a `.custom` package id ⇒ not judged. */ + packageId: string | null | undefined; + /** The package's `objectExtensions` entries. */ + objectExtensions?: unknown; + /** + * The rules other packages ship for `object`, by name, each with the + * package that holds it. Absent, or answering `undefined` ⇒ only the + * suffix is judged. + */ + packageRulesOf?: (object: string) => ReadonlyMap | undefined; + /** Whether the package owns `object`: an extension of its own object adds the package's own rules, not judged. */ + ownsObject?: (object: string) => boolean; + /** Prefix of every reported path, e.g. `packages[1].manifest.`. */ + at?: string; +} + +/** `held_by_package`'s sentence. Prescription first: a 4xx message crosses the REST boundary capped at 500 characters. */ +function heldByPackageMessage(name: string, object: string, packageId: string, holder: string | undefined): string { + const fix = isExtensionFieldName(name) + ? `give it a name of its own ending in \`${EXTENSION_FIELD_SUFFIX}\`` + : `name it '${name}${EXTENSION_FIELD_SUFFIX}'`; + return `Validation rule '${name}' on object '${object}' in package '${packageId}': ${fix}. The name is held by ` + + `${holder ? `a rule of package '${holder}'` : 'a package rule'}, and a customer rule never replaces or ` + + 'switches off a package rule.'; +} + +/** `unsuffixed_in_pair`'s sentence. */ +function unsuffixedInPairMessage(name: string, object: string, packageId: string): string { + return `Validation rule '${name}' on object '${object}' in package '${packageId}': name it ` + + `'${name}${EXTENSION_FIELD_SUFFIX}'. A rule a \`.custom\` package adds ends in \`${EXTENSION_FIELD_SUFFIX}\`, ` + + 'so a package\'s next version can never take its name.'; +} + +/** + * Ruling 7411414171 (B) — the names of the validation rules a customer's + * `.custom` package adds to another package's object, judged. The ONE judge: + * the `object_extension` save, publish and restore gate + * ({@link objectExtensionItemRefusal}) and `os validate` / `os build` + * (`@objectstack/cli`) ask it, so every door says the same sentence. + * + * In a `.custom` package ({@link isCustomizationPackage}), for each rule an + * `objectExtensions` entry adds to an object the package does not own: + * + * - `held_by_package` — the name is one + * {@link PairValidationRuleNameSubject.packageRulesOf} lists: refused, + * since the registry fold never lets a customer rule replace or switch off + * a package rule (the package's rule runs, and this one would not); + * - `unsuffixed_in_pair` — the name does not end in `__c` + * (`EXTENSION_FIELD_SUFFIX`, the customer suffix of extension fields and + * picklist values): refused, so a package's next version can never take + * it. + * + * One row per refused rule, `held_by_package` when both hold. A package that + * is not `.custom`, a body bound to no package, and a rule with no string + * name are not judged. Pure: no I/O, no throw. + */ +export function judgePairValidationRuleNames(subject: PairValidationRuleNameSubject): PairValidationRuleNameRefusal[] { + const { packageId } = subject; + if (typeof packageId !== 'string' || !isCustomizationPackage(packageId)) return []; + const extensions = subject.objectExtensions; + if (!Array.isArray(extensions)) return []; + const at = subject.at ?? ''; + const out: PairValidationRuleNameRefusal[] = []; + extensions.forEach((extension, i) => { + if (!isRecord(extension) || typeof extension.extend !== 'string') return; + const object = extension.extend; + if (subject.ownsObject?.(object) === true) return; + const rules = extension.validations; + if (!Array.isArray(rules)) return; + const held = subject.packageRulesOf?.(object); + rules.forEach((rule, j) => { + const name = isRecord(rule) ? rule.name : undefined; + if (typeof name !== 'string' || name === '') return; + const path = `${at}objectExtensions[${i}].validations[${j}].name`; + if (held?.has(name)) { + const holder = held.get(name); + out.push({ + rule: 'held_by_package', path, object, name, packageId, + ...(holder ? { holder } : {}), + message: heldByPackageMessage(name, object, packageId, holder), + }); + } else if (!isExtensionFieldName(name)) { + out.push({ + rule: 'unsuffixed_in_pair', path, object, name, packageId, + message: unsuffixedInPairMessage(name, object, packageId), + }); + } + }); + }); + return out; +} + +/** The active doors' envelope for {@link judgePairValidationRuleNames}' rows: `VALIDATION_ERROR` / 400, one issue per rule. */ +export function pairValidationRuleNameRefusalError( + refusals: readonly PairValidationRuleNameRefusal[], +): Error & { code: 'VALIDATION_ERROR'; status: 400; issues: MetadataIssueEntry[] } { + const [first] = refusals; + const more = refusals.length - 1; + const err = new Error( + `${first!.message}${more > 0 ? ` (${more} more rule${more === 1 ? '' : 's'} in \`issues\`.)` : ''}`, + ) as Error & { code: 'VALIDATION_ERROR'; status: 400; issues: MetadataIssueEntry[] }; + err.code = 'VALIDATION_ERROR'; + err.status = 400; + err.issues = refusals.map((r) => ({ path: r.path, message: r.message, code: 'custom' })); + return err; +} + /** * The body a sync registers for a stored `object_extension` row: the WHOLE * parsed body (`ObjectExtensionSchema`: its defaults, such as `priority`, and diff --git a/packages/metadata-protocol/src/protocol-pair-validation-rule-name-39661.test.ts b/packages/metadata-protocol/src/protocol-pair-validation-rule-name-39661.test.ts new file mode 100644 index 00000000000..873ffee399a --- /dev/null +++ b/packages/metadata-protocol/src/protocol-pair-validation-rule-name-39661.test.ts @@ -0,0 +1,106 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #39661, ruling 7411414171 (B) — the save, publish and restore gate of an + * `object_extension` item (`objectExtensionItemRefusal`) refuses a validation + * rule a customization pair's extension adds when it carries a package rule's + * name, or when its name does not end in the customer suffix `__c` + * (`EXTENSION_FIELD_SUFFIX`, the one ruled for picklist values on #39536). + * HTTP, MCP and the AI authoring doors all save through this gate. + * + * Envelope: `VALIDATION_ERROR` / 400, one issue per refused rule, located at + * the rule's `name`; the sentence names the rule and the fix. + */ + +import './lint-root-preload.testkit.js'; +import { describe, expect, it } from 'vitest'; +import { objectExtensionItemRefusal } from './protocol-object-extension-item.js'; + +const BASE = 'com.acme.crm'; +const PAIR = 'com.acme.crm.custom'; +const PARTNER = 'com.partner.crm-ext'; +const TARGET = 'crm_account'; + +const rule = (name: string, extra: Record = {}) => ({ + type: 'script', name, message: 'No.', condition: 'record.amount > 100', ...extra, +}); + +/** A registry that knows the target, its packaged owner and one code extender. */ +function registry(owner: string = BASE, ownerRules: unknown[] = [rule('credit_cap'), rule('vendor_kept__c')]) { + const ownerDef = { name: TARGET, _packageId: owner, validations: ownerRules }; + const partnerDef = { name: TARGET, _packageId: PARTNER, validations: [rule('partner_check')] }; + return { + getObject: (name: string) => (name === TARGET ? { name: TARGET, _packageId: owner } : undefined), + getObjectOwner: (name: string) => (name === TARGET ? { packageId: owner, definition: ownerDef } : undefined), + getObjectContributors: (name: string) => (name === TARGET + ? [ + { packageId: owner, ownership: 'own', definition: ownerDef }, + { packageId: PARTNER, ownership: 'extend', definition: partnerDef }, + ] + : []), + }; +} + +type Refusal = Error & { code?: string; status?: number; issues?: Array<{ path: string; message: string }> }; + +const ask = (binding: string, rules: unknown[], reg: ReturnType | undefined = registry()) => + objectExtensionItemRefusal('object_extension', { + item: { extend: TARGET, validations: rules }, + name: TARGET, + binding, + registry: reg, + scope: undefined, + }) as Refusal | undefined; + +describe('#39661 — the pair\'s extension may not carry a package rule\'s name', () => { + it('a pair rule named like the owner\'s rule is refused, located at its name, naming the rule and the fix', () => { + const err = ask(PAIR, [rule('credit_cap', { active: false })]); + expect(err?.code).toBe('VALIDATION_ERROR'); + expect(err?.status).toBe(400); + expect(err?.issues?.map((i) => i.path)).toEqual(['validations[0].name']); + expect(err?.message).toContain("'credit_cap'"); + expect(err?.message).toContain('credit_cap__c'); + }); + + it('a pair rule named like a code extender\'s rule is refused the same way', () => { + const err = ask(PAIR, [rule('partner_check')]); + expect(err?.status).toBe(400); + expect(err?.issues?.map((i) => i.path)).toEqual(['validations[0].name']); + }); + + it('a suffixed name a package rule already holds is refused too', () => { + const err = ask(PAIR, [rule('vendor_kept__c')]); + expect(err?.status).toBe(400); + expect(err?.issues?.map((i) => i.path)).toEqual(['validations[0].name']); + }); +}); + +describe('#39661 — a customer rule\'s name ends in `__c`', () => { + it('an unsuffixed pair rule is refused, located at its name, prescribing the suffixed spelling', () => { + const err = ask(PAIR, [rule('credit_cap__c'), rule('big_deal')]); + expect(err?.code).toBe('VALIDATION_ERROR'); + expect(err?.status).toBe(400); + expect(err?.issues?.map((i) => i.path)).toEqual(['validations[1].name']); + expect(err?.message).toContain("'big_deal'"); + expect(err?.message).toContain('big_deal__c'); + }); + + it('it is refused with no registry to read too (the suffix needs none)', () => { + const err = ask(PAIR, [rule('big_deal')], undefined); + expect(err?.status).toBe(400); + }); +}); + +describe('#39661 — controls', () => { + it('suffixed pair rules of names of their own are admitted', () => { + expect(ask(PAIR, [rule('credit_cap__c'), rule('big_deal__c')])).toBeUndefined(); + }); + + it('a plain package\'s stored extension is not judged by the pair rule', () => { + expect(ask('com.other.dev', [rule('big_deal')])).toBeUndefined(); + }); + + it('an extension of the pair\'s own object is not judged: its rules are the pair\'s own', () => { + expect(ask(PAIR, [rule('big_deal')], registry(PAIR, [rule('credit_cap')]))).toBeUndefined(); + }); +}); diff --git a/packages/objectql/src/registry-object-registration.ts b/packages/objectql/src/registry-object-registration.ts index c1ba9dfbda9..bcc4ec82009 100644 --- a/packages/objectql/src/registry-object-registration.ts +++ b/packages/objectql/src/registry-object-registration.ts @@ -57,6 +57,8 @@ import { applyExtensionPlacements, fieldGroupKeysOf, placementContributorsOf } f import type { ExtensionPlacementNote } from './registry-extension-placement.js'; import { applyCustomArrangement, relatedListsArrangementOf, rememberRelatedListsArrangement } from './registry-custom-arrangement.js'; import { applyProtection } from '@objectstack/spec/shared'; +import { isCustomizationPackage } from '@objectstack/spec/kernel'; +import { packageRuleHoldersOf, reportHeldPairRules } from './registry-pair-validation-rules.js'; import { isObjectLessActionKey, standaloneActionOwnerKey } from './action-governance.js'; import { recordCurrencyFollowRefusal, recordCurrencySummaryRefusal } from './record-currency-aggregate-door.js'; import { recordUnitSummaryRefusal } from './record-unit-aggregate-door.js'; @@ -894,7 +896,7 @@ export class ObjectRegistrationFacet { * {@link foldObjectExtendersOnto} can apply it to a body that never came * from this registry without growing a second copy of the merge. */ - static foldExtendersOntoDefinition(this: Pick, contributors: ObjectContributor[], baseDefinition: ServiceObject, layer: ServedObjectLayer = 'served'): ServiceObject { + static foldExtendersOntoDefinition(this: Pick, contributors: ObjectContributor[], baseDefinition: ServiceObject, layer: ServedObjectLayer = 'served'): ServiceObject { // [ADR-0029 D9.2a] Computed ONCE, over the base the fold starts from — never // re-derived from the running `merged`, which would make an extender's own // scalar look "authored" to the next extender and silently invert @@ -931,6 +933,10 @@ export class ObjectRegistrationFacet { // [ADR-0162 D1] A tenant overlay base may add closed values of its own // and may not shorten the package's list, or break a field it names. if (owner && owner !== baseDefinition) merged = withPackagedClosedStates(owner, merged); + // [ruling 7411414171 (B)] The rule names the packages ship for this + // object: a `.custom` package's extension never replaces or switches off + // one of them. Computed once, over the contributors, as the sets above are. + const packaged = packageRuleHoldersOf(contributors); // [#28835] Each extension's `fields` as the merge took them, in fold order. const folded: FoldedExtensionFields[] = []; for (const contrib of contributors) { @@ -956,7 +962,9 @@ export class ObjectRegistrationFacet { : extension; // [ADR-0162 D1] An extension's redeclaration of a field the served // `closedStates` names is refused where it would break the declaration. - merged = mergeObjectDefinitions(merged, withoutClosedStateFieldBreaches(merged, admitted, contrib.packageId), tenantAuthored, tenantRules, tenantPatched, ownFields); + const customerLayer = isCustomizationPackage(contrib.packageId) && packaged.size > 0; + merged = mergeObjectDefinitions(merged, withoutClosedStateFieldBreaches(merged, admitted, contrib.packageId), tenantAuthored, tenantRules, tenantPatched, ownFields, customerLayer ? new Set(packaged.keys()) : undefined); + if (customerLayer) reportHeldPairRules.call(this, String(baseDefinition.name ?? extension.name ?? ''), contrib, packaged); // [#28809] …and the same judge once more, over the admitted patches // against the owner's fields as MERGED, which only names: an admitted // option an earlier layer left out (an extension's `fields` diff --git a/packages/objectql/src/registry-pair-validation-rule-name-39661.test.ts b/packages/objectql/src/registry-pair-validation-rule-name-39661.test.ts new file mode 100644 index 00000000000..54e5ecc5775 --- /dev/null +++ b/packages/objectql/src/registry-pair-validation-rule-name-39661.test.ts @@ -0,0 +1,171 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #39661, ruling 7411414171 (B) — a validation rule the customization pair's + * object extension adds never replaces or switches off a package's rule. + * + * The pair's extension is the customer's layer (ADR-0146 D10): its stored row + * registers as an `extend` contributor carrying `_provenance: 'org'` + * (`registrableObjectExtension`). Before this card the fold merged its rules + * BY NAME exactly as it merges two code layers (ADR-0029 D9.2a), so a pair + * rule bearing a package rule's name replaced that rule whole, and + * `active: false` turned it off. What is pinned here: + * + * 1. a stored pair rule under a package rule's name does not change the + * condition the object enforces, `active: false` and a changed condition + * alike: the package's rule runs, and the copy is reported once (no throw), + * as ruling 6545641964 has the object door's load path do; + * 2. the vendor-upgrade case: a package version that adds a rule under a name + * the pair already holds (unsuffixed, from before the suffix rule) runs + * the package's rule; + * 3. a suffixed pair rule runs beside the package's rule; + * 4. CONTROL: between two code layers a later layer's same-named rule still + * replaces the earlier one (D9.2a, unchanged). + */ + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { SchemaRegistry } from './registry.js'; +import { ObjectQL } from './index.js'; + +const OBJ = 'crm_account'; +const BASE = 'com.acme.crm'; +const PAIR = 'com.acme.crm.custom'; +const PARTNER = 'com.partner.crm-ext'; + +const CAP = 'record.amount > 100'; +const fields = { + amount: { type: 'number', label: 'Amount' }, + note: { type: 'text', label: 'Note' }, +}; +const packageRule = (overrides: Record = {}) => ({ + type: 'script', + name: 'credit_cap', + message: 'The amount is over the credit cap.', + condition: CAP, + ...overrides, +}); +const ownerBody = (rules: unknown[] = [packageRule()]) => ({ name: OBJ, label: 'Account', fields, validations: rules }); +/** The pair's stored row as the sync registers it (`registrableObjectExtension`). */ +const pairRow = (rules: unknown[]) => ({ extend: OBJ, validations: rules, _provenance: 'org' }); + +function registryWith(pairRules: unknown[], owner: unknown[] = [packageRule()]) { + const registry = new SchemaRegistry({ multiTenant: false }); + registry.logLevel = 'silent'; + registry.registerObject(ownerBody(owner) as never, BASE, undefined, 'own'); + registry.registerObjectExtension(pairRow(pairRules) as never, PAIR); + return registry; +} + +const servedRules = (registry: SchemaRegistry) => + ((registry.getObject(OBJ) as unknown as { validations?: Array> }).validations ?? []).map((r) => ({ + name: r.name, condition: r.condition, ...(r.active === undefined ? {} : { active: r.active }), + })); + +function makeDriver() { + const rows = new Map(); + return { + name: 'com.objectstack.driver.memory.pair-rule', + version: '1.0.0', + async connect() { /* noop */ }, + async disconnect() { /* noop */ }, + async initObjects() { /* noop */ }, + async find() { return [...rows.values()]; }, + async findOne() { return null; }, + async count() { return rows.size; }, + async create(_o: string, data: Record) { rows.set(String(data.id), data); return data; }, + async update(_o: string, data: unknown) { return data; }, + async delete() { return false; }, + } as never; +} + +/** Boot an engine with the package's object and the pair's row; answer whether an insert of `record` is refused. */ +async function insertRefused(pairRules: unknown[], record: Record): Promise { + const engine = new ObjectQL(); + engine.registerDriver(makeDriver(), true); + await engine.init(); + try { + engine.registry.registerObject(ownerBody() as never, BASE, undefined, 'own'); + engine.registry.registerObjectExtension(pairRow(pairRules) as never, PAIR); + try { + await engine.insert(OBJ, record); + return false; + } catch { + return true; + } + } finally { + await engine.destroy(); + } +} + +afterEach(() => { vi.restoreAllMocks(); }); + +describe('#39661 — a stored pair rule under a package rule\'s name does not change the condition the object enforces', () => { + it('`active: false` on a same-named pair rule does not switch the package rule off', () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + const registry = registryWith([packageRule({ active: false, message: 'Off.' })]); + expect(servedRules(registry)).toEqual([{ name: 'credit_cap', condition: CAP }]); + }); + + it('a same-named pair rule with its own condition does not replace the package rule', () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + const registry = registryWith([packageRule({ condition: 'record.amount > 1000000' })]); + expect(servedRules(registry)).toEqual([{ name: 'credit_cap', condition: CAP }]); + }); + + it('the engine still refuses what the package rule refuses, with the pair\'s switched-off copy stored', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + expect(await insertRefused([packageRule({ active: false })], { id: 'a1', amount: 500 })).toBe(true); + // CONTROL: a record the package rule admits is admitted. + expect(await insertRefused([packageRule({ active: false })], { id: 'a2', amount: 5 })).toBe(false); + }); + + it('the stored copy is reported once, at error, naming the rule, the object and the pair; nothing throws', () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => {}); + const registry = registryWith([packageRule({ active: false })]); + registry.getObject(OBJ); + registry.getObject(OBJ); + const lines = error.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('credit_cap') && l.includes(PAIR)); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain(OBJ); + }); +}); + +describe('#39661 — the vendor-upgrade collision', () => { + it('a package version that adds a rule the pair already holds runs the package\'s rule', () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + const pairOld = { type: 'script', name: 'fresh_rule', message: 'Customer.', condition: 'record.note == "x"' }; + const registry = registryWith([pairOld]); + expect(servedRules(registry)).toEqual([ + { name: 'credit_cap', condition: CAP }, + { name: 'fresh_rule', condition: 'record.note == "x"' }, + ]); + // The upgrade: the package's next version ships `fresh_rule` itself. + const upgraded = { type: 'script', name: 'fresh_rule', message: 'Vendor.', condition: 'record.amount < 0' }; + registry.registerObject(ownerBody([packageRule(), upgraded]) as never, BASE, undefined, 'own'); + expect(servedRules(registry)).toEqual([ + { name: 'credit_cap', condition: CAP }, + { name: 'fresh_rule', condition: 'record.amount < 0' }, + ]); + }); +}); + +describe('#39661 — what stays', () => { + it('a suffixed pair rule runs beside the package rule', () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => {}); + const own = { type: 'script', name: 'credit_cap__c', message: 'Ours.', condition: 'record.amount > 50' }; + const registry = registryWith([own]); + expect(servedRules(registry)).toEqual([ + { name: 'credit_cap', condition: CAP }, + { name: 'credit_cap__c', condition: 'record.amount > 50' }, + ]); + expect(error.mock.calls.filter((c) => String(c[0]).includes(PAIR))).toEqual([]); + }); + + it('CONTROL (ADR-0029 D9.2a): between two code layers a later layer\'s same-named rule replaces the earlier one', () => { + const registry = new SchemaRegistry({ multiTenant: false }); + registry.logLevel = 'silent'; + registry.registerObject(ownerBody() as never, BASE, undefined, 'own'); + registry.registerObject({ name: OBJ, validations: [packageRule({ condition: 'record.amount > 7' })] } as never, PARTNER, undefined, 'extend'); + expect(servedRules(registry)).toEqual([{ name: 'credit_cap', condition: 'record.amount > 7' }]); + }); +}); diff --git a/packages/objectql/src/registry-pair-validation-rules.ts b/packages/objectql/src/registry-pair-validation-rules.ts new file mode 100644 index 00000000000..46e0e32a4a0 --- /dev/null +++ b/packages/objectql/src/registry-pair-validation-rules.ts @@ -0,0 +1,75 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ruling 7411414171 (B)] A validation rule a customer's `.custom` package + * adds to another package's object never replaces or switches off a package + * rule. The fold (`ObjectRegistrationFacet.foldExtendersOntoDefinition`) + * reads the package rules' names here, hands them to the by-name merge + * (`mergeValidationsByName`, which leaves the customer's copy out), and names + * each stored copy once. Between two code layers the D9.2a replacement is + * unchanged. The save door (`objectExtensionItemRefusal`) and `os validate` + * refuse such a rule before it is stored; this is the load path, which never + * refuses (ruling 6545641964). + */ + +import { EXTENSION_FIELD_SUFFIX, isExtensionFieldName } from '@objectstack/spec/data'; +import { isCustomizationPackage } from '@objectstack/spec/kernel'; +import { stableStringify, validationRuleName, type ObjectContributor } from './registry-top-level.js'; + +/** + * [ruling 7411414171 (B)] The validation rules the packages ship for an + * object, by name, each with the package that ships it: the owner's and every + * extender's, in fold order, except a `.custom` package's (the customer's + * layer). The first package to name a rule holds it. + */ +export function packageRuleHoldersOf(contributors: readonly ObjectContributor[]): Map { + const out = new Map(); + for (const contrib of contributors) { + if (contrib.ownership !== 'own' && contrib.ownership !== 'extend') continue; + if (typeof contrib.packageId === 'string' && isCustomizationPackage(contrib.packageId)) continue; + const rules = contrib.definition?.validations; + if (!Array.isArray(rules)) continue; + for (const rule of rules) { + const name = validationRuleName(rule); + if (name !== undefined && !out.has(name)) out.set(name, contrib.packageId); + } + } + return out; +} + +/** + * [ruling 7411414171 (B); ruling 6545641964] Say, once per stored copy, that a + * `.custom` package's extension carries a validation rule under a name a + * package ships. The fold has left the copy out and runs the package's rule; + * the customer's rule does not run while the object serves normally, so this + * is an `error` with its consequence and its fix. Reported, never refused: a + * package upgrade can take a name a stored extension already holds, and + * refusing it would drop the customer's layer at boot. + */ +export function reportHeldPairRules( + this: { readonly reportedRuleCopyChanges: Set }, + objectName: string, + contrib: ObjectContributor, + packaged: ReadonlyMap, +): void { + const rules = contrib.definition?.validations; + if (!Array.isArray(rules)) return; + for (const rule of rules) { + const ruleName = validationRuleName(rule); + if (ruleName === undefined || !packaged.has(ruleName)) continue; + const key = `pair-rule|${objectName}|${contrib.packageId}|${ruleName}|${stableStringify(rule)}`; + if (this.reportedRuleCopyChanges.has(key)) continue; + this.reportedRuleCopyChanges.add(key); + const holder = packaged.get(ruleName); + const rename = isExtensionFieldName(ruleName) + ? `another name of its own ending in \`${EXTENSION_FIELD_SUFFIX}\`` + : `"${ruleName}${EXTENSION_FIELD_SUFFIX}"`; + console.error( + `[Registry] [pair_validation_rule_name_held] Object "${objectName}": the customization package ` + + `"${contrib.packageId}" adds validation rule "${ruleName}", a name ${holder ? `package "${holder}"` : 'a package'} ` + + 'ships a rule under. A customer rule never replaces or switches off a package rule, so the package\'s rule ' + + 'is enforced and the customization\'s copy does not run, while the object serves normally. To keep the ' + + `customer's rule, rename it to ${rename} and save the extension again.`, + ); + } +} diff --git a/packages/objectql/src/registry-top-level.ts b/packages/objectql/src/registry-top-level.ts index 5cffdd711f6..c6a4f75430e 100644 --- a/packages/objectql/src/registry-top-level.ts +++ b/packages/objectql/src/registry-top-level.ts @@ -921,12 +921,25 @@ function withTenantRuleSettings(packaged: R, settings: TenantRuleSettings | u * `tenantRules` (the fold's base is a tenant overlay), the rule carries the * tenant's `message` and `active` for its name; its condition stays the * later layer's. + * + * [ruling 7411414171 (B)] With `packagedNames` (the extension is a `.custom` + * package's, the customer's layer), a rule of a name a package ships never + * replaces or switches off that rule: it is left out, and the package's rule + * runs as the code layers fold it. Its other rules add as above. Between two + * code layers (no `packagedNames`) the replacement is unchanged. */ function mergeValidationsByName( base: readonly unknown[] | undefined, extension: readonly unknown[], tenantRules: ReadonlyMap | undefined, + packagedNames?: ReadonlySet, ): unknown[] { + if (packagedNames && packagedNames.size > 0) { + extension = extension.filter((rule) => { + const name = validationRuleName(rule); + return name === undefined || !packagedNames.has(name); + }); + } const names = new Set(); for (const rule of extension) { const name = validationRuleName(rule); diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index 6775d1b237d..1c97b20c4b2 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -204,7 +204,7 @@ export { * - `validations` are merged BY NAME ({@link mergeValidationsByName}, * [ADR-0029 D9.2a, 2026-10-30 note]): rules of different names add, and a * rule of a name already folded replaces it — with `tenantRules`, carrying - * the tenant's `message` and `active`, never the tenant's condition. + * the tenant's `message` and `active`, never its condition (`packagedRuleNames`: see there). * - The three {@link OBJECT_FOLD_SCALAR_KEYS} (`label`, `pluralLabel`, * `description`) are overridden last-writer-wins, subject to the * `tenantAuthored` yield rule below. [#30391] A `label` that renames the @@ -267,7 +267,7 @@ function mergeObjectDefinitions( tenantAuthored?: ReadonlySet, tenantRules?: ReadonlyMap, tenantPatched?: ReadonlySet, - ownFields?: ReadonlySet, + ownFields?: ReadonlySet, packagedRuleNames?: ReadonlySet, ): ServiceObject { const merged = { ...base }; @@ -281,7 +281,7 @@ function mergeObjectDefinitions( merged.validations = mergeValidationsByName( base.validations, extension.validations, - tenantRules, + tenantRules, packagedRuleNames, ) as ServiceObject['validations']; } diff --git a/packages/runtime/src/domains/meta-object-extension-item.test.ts b/packages/runtime/src/domains/meta-object-extension-item.test.ts index c22175ed794..02ef8f0a63c 100644 --- a/packages/runtime/src/domains/meta-object-extension-item.test.ts +++ b/packages/runtime/src/domains/meta-object-extension-item.test.ts @@ -196,11 +196,11 @@ describe('[#28574] a writable pair saves and publishes an extension of the base\ // [#33154] `record.`-scoped, as a rule declared on the account must be: // the door now judges an extension's rules by the object's own rule // pass, which refuses the bare `region__c` this fixture used to carry. - const rule = { name: 'region_required', type: 'script', condition: 'record.region__c == null', message: 'Region is required', events: ['insert'] }; + const rule = { name: 'region_required__c', type: 'script', condition: 'record.region__c == null', message: 'Region is required', events: ['insert'] }; await rig.saveAndPublish(PAIR, regionBody({ validations: [rule] })); const names = ((rig.engine.registry.getObject(TARGET) as any)?.validations ?? []).map((v: any) => v?.name); - expect(names).toContain('region_required'); + expect(names).toContain('region_required__c'); }, 60_000); it('a boot re-reads the stored row and registers it the same way', async () => { @@ -644,7 +644,7 @@ describe('[#33216] the publish door judges the one-hop leaf through a lookup the extend: TARGET, fields: { ...MANAGER }, validations: [{ - name: 'long_day', type: 'conditional', message: 'Refused.', + name: 'long_day__c', type: 'conditional', message: 'Refused.', when: 'record.manager__c != null', then: { name: 'hours', type: 'script', condition: `record.manager__c.${leaf} > 12`, message: 'Refused.' }, }], @@ -669,7 +669,7 @@ describe('[#33216] the publish door judges the one-hop leaf through a lookup the [ 'a rule', ruleBody, - "object 'crm_account' · objectExtensions[0] · validation rule 'long_day' then → 'hours'", + "object 'crm_account' · objectExtensions[0] · validation rule 'long_day__c' then → 'hours'", 'objectExtensions[0].validations[0].then.condition', ], [ @@ -817,8 +817,8 @@ describe('[#33217] the publish door judges an extension\'s `format` regex and `j fields: { code__c: { type: 'text', label: 'Code' }, config__c: { type: 'json', label: 'Config' } }, validations: [rule], }); - const BAD_REGEX = { name: 'code_shape', type: 'format', field: 'code__c', regex: '([', message: 'Refused.' }; - const BAD_SCHEMA = { name: 'config_shape', type: 'json_schema', field: 'config__c', schema: { type: 'not-a-type' }, message: 'Refused.' }; + const BAD_REGEX = { name: 'code_shape__c', type: 'format', field: 'code__c', regex: '([', message: 'Refused.' }; + const BAD_SCHEMA = { name: 'config_shape__c', type: 'json_schema', field: 'config__c', schema: { type: 'not-a-type' }, message: 'Refused.' }; const ARTIFACT_IDS = ['validation-rule-regex-uncompilable', 'validation-rule-json-schema-uncompilable']; const atBuild = (item: unknown) => { const stack = { objects: baseManifest().objects, objectExtensions: [item] }; @@ -855,14 +855,14 @@ describe('[#33217] the publish door judges an extension\'s `format` regex and `j it('⭐ CONTROL — a valid regex and a valid schema publish and are served on the account', async () => { const body = { - ...ruleBody({ name: 'code_ok', type: 'format', field: 'code__c', regex: '^[A-Z]{3}$', message: 'Refused.' }), + ...ruleBody({ name: 'code_ok__c', type: 'format', field: 'code__c', regex: '^[A-Z]{3}$', message: 'Refused.' }), }; - body.validations.push({ name: 'config_ok', type: 'json_schema', field: 'config__c', schema: { type: 'object' }, message: 'Refused.' } as any); + body.validations.push({ name: 'config_ok__c', type: 'json_schema', field: 'config__c', schema: { type: 'object' }, message: 'Refused.' } as any); expect(atBuild(body)).toEqual([]); const rig = await boot(); await rig.saveAndPublish(PAIR, body); - expect(servedRules(rig)).toEqual(expect.arrayContaining(['code_ok', 'config_ok'])); + expect(servedRules(rig)).toEqual(expect.arrayContaining(['code_ok__c', 'config_ok__c'])); expect(await rig.rows()).toEqual([{ name: TARGET, package_id: PAIR, state: 'active' }]); }, 60_000); }); @@ -1073,7 +1073,7 @@ describe('an unchanged owner object re-saved at the public door while an extensi describe('[ADR-0146 D10] a validation rule in the pair\'s extension runs on record save, and outlasts a reinstall and a restart', () => { // Studio's Validations tab of an installed object writes a customer's rule // here (`pairValidations.ts` in app-shell): the pair's extension, never the base. - const RULE = { name: 'no_blocked', type: 'script', condition: "record.name == 'Blocked'", message: 'Blocked is not a name', events: ['insert', 'update'] }; + const RULE = { name: 'no_blocked__c', type: 'script', condition: "record.name == 'Blocked'", message: 'Blocked is not a name', events: ['insert', 'update'] }; const insert = async (engine: ObjectQL, name: string) => { try { await engine.insert(TARGET, { name, organization_id: 'org_1' }, { context: { isSystem: true } }); diff --git a/packages/runtime/src/domains/packages-disable-module-extension-fields.test.ts b/packages/runtime/src/domains/packages-disable-module-extension-fields.test.ts index f15a222f239..0341212980b 100644 --- a/packages/runtime/src/domains/packages-disable-module-extension-fields.test.ts +++ b/packages/runtime/src/domains/packages-disable-module-extension-fields.test.ts @@ -103,7 +103,7 @@ const RULE_SWITCHED_OFF = 'qx_credit_switched_off'; const RULE_VISIT_HOP = 'qx_visit_account_credit'; /** The app's paired customization package, where a tenant-written rule lives. */ const PAIR = `${APP}.custom`; -const RULE_TENANT = 'qx_credit_tenant_cap'; +const RULE_TENANT = 'qx_credit_tenant_cap__c'; /** * [#30379 contract review] A fifth, ENABLED module folded AFTER {@link RULES} * (priority 300) that redeclares two of its rules by name: one copy that no diff --git a/packages/spec/src/data/field-customization.ts b/packages/spec/src/data/field-customization.ts index 486aa8e3a74..55c560fc129 100644 --- a/packages/spec/src/data/field-customization.ts +++ b/packages/spec/src/data/field-customization.ts @@ -33,11 +33,18 @@ */ /** - * The suffix that reserves a field name to the customer's layer: a customer's + * The suffix that reserves a name to the customer's layer: a customer's * field on `crm_account` is `region__c`, so a vendor's next version can never * take that name (ADR-0146 D10). A field one vendor package adds to another * vendor's object keeps the plain spelling; the suffix names the customer's * layer and nothing else. + * + * The one spelling of that suffix for every name the customer's layer adds to + * a vendor's metadata, never re-spelled: an extension field, a value a + * customer's picklist extension adds (ruling 7406020670), and a validation + * rule a `.custom` package's object extension adds (ruling 7411414171), which + * may not carry a package rule's name either. {@link isExtensionFieldName} + * judges the spelling for each of them. */ export const EXTENSION_FIELD_SUFFIX = '__c'; diff --git a/packages/spec/src/migrations/entries/semantic/19.pair-validation-rule-suffix.ts b/packages/spec/src/migrations/entries/semantic/19.pair-validation-rule-suffix.ts new file mode 100644 index 00000000000..399f14f6de1 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.pair-validation-rule-suffix.ts @@ -0,0 +1,53 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// Ruling 7411414171 (B): a narrowing of the names a customer's `.custom` +// package may give the validation rules its object extension adds to another +// package's object, and of what the registry fold does with a stored one. The +// fold used to merge such a rule BY NAME as it merges two code layers (ADR-0029 +// D9.2a), so a rule bearing a package rule's name replaced that rule whole and +// `active: false` switched it off; the save door (the HTTP, MCP and AI doors) and +// `os validate` admitted it. Now a customer rule ends +// in `__c` (`EXTENSION_FIELD_SUFFIX`, the customer suffix of extension fields +// and picklist values) and carries no package rule's name, refused at the +// `object_extension` save, publish and restore doors and at `os validate` / +// `os build`; a stored copy under a package rule's name is left out of the fold +// and reported once, and the package's rule runs (ruling 6545641964's load +// path). Code-layer replacement between two vendor packages is unchanged. No +// key is added or removed, so no tombstone; no D2 conversion: a stored row +// carries no package id the conversion layer can read, so it cannot tell a +// `.custom` row from a vendor's, and the rename is the row's owner's to save. +// No relevance question: the package-rule half turns on what the installed +// packages ship, and the rows it governs are a deployment's stored ones. +export const entry: SemanticMigration = { + id: 'pair-validation-rule-suffix', + surface: + 'A validation rule a `.custom` package\'s object extension adds to another package\'s object (Studio\'s ' + + 'Validations tab on an installed object, `PUT /api/v1/meta/object_extension/OBJECT?package=BASE.custom`, the ' + + 'MCP and AI draft doors, or `objectExtensions[].validations` of a `.custom` package\'s source) whose `name` does ' + + 'not end in `__c`, e.g. `credit_check`, or is the name of a rule a package ships for that object, e.g. ' + + '`{ extend: \'crm_account\', validations: [{ name: \'credit_cap\', active: false, … }] }` where the package ' + + 'ships `credit_cap`.', + replacement: + 'FROM a rule named `NAME` TO the same rule named `NAME__c` (`credit_check` → `credit_check__c`); a rule already ' + + 'ending in `__c` that a package also ships takes another name of its own ending in `__c`. A rule that only ' + + 'switched off or reworded a package rule is deleted: a customer rule never replaces or switches off a package ' + + 'rule.', + reason: + 'The registry merged a `.custom` extension\'s rules by name, the way two vendor packages merge, so a customer ' + + 'rule bearing a package rule\'s name replaced it, condition included, and `active: false` turned it off; and a ' + + 'package version that later shipped a rule under a name a customer had used was replaced the same way. Now the ' + + 'save, publish and restore doors answer `400 VALIDATION_ERROR` at `validations[N].name`, `os validate` and ' + + '`os build` exit 1 with the same sentence, and a stored rule under a package rule\'s name is not run: the ' + + 'package\'s rule is, and the boot log names the stored copy once ' + + '(`[pair_validation_rule_name_held]`). A stored unsuffixed rule of a name no package ships still runs, and its ' + + 'extension\'s next save is refused until it is renamed. The rename is the row\'s owner\'s to make: a stored ' + + 'row carries no package id the conversion layer reads, and other references to the rule name (a translation ' + + 'key, a report) move with it.', + acceptanceCriteria: + 'Every validation rule in each `.custom` package\'s object extensions ends in `__c` and is not the name of a ' + + 'rule the extended object\'s packages ship: `os validate` exits 0, saving each such extension through ' + + '`PUT /api/v1/meta/object_extension/OBJECT?package=BASE.custom` answers 200, and the boot log carries no ' + + '`[pair_validation_rule_name_held]` line.', +}; 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..17d8fe132ae 100644 --- a/packages/spec/src/migrations/semantic-relevance-coverage-38929.test.ts +++ b/packages/spec/src/migrations/semantic-relevance-coverage-38929.test.ts @@ -171,6 +171,10 @@ const STAYS_LISTED: Readonly; - /** objectstack#39471 — the rule names the published extension declares. */ - publishedRules: ReadonlySet; + /** objectstack#39471 — the rules the published extension declares, by name. */ + publishedRules: ReadonlyMap; } | null>(null); const [extDirty, setExtDirty] = React.useState(false); const [extHasDraft, setExtHasDraft] = React.useState(false); @@ -940,7 +940,7 @@ export function DataPillar({ for: name, body: draft ?? published ?? { extend: name }, published: new Set(extensionFieldNames(published)), - publishedRules: new Set(ruleNamesOf(published?.validations)), + publishedRules: rulesByName(published?.validations), }); setExtHasDraft(draft !== null); } catch (e) { diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectValidationsPanel.test.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectValidationsPanel.test.tsx index 23dcc787279..4201afe34da 100644 --- a/ui/packages/app-shell/src/views/studio-design/ObjectValidationsPanel.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/ObjectValidationsPanel.test.tsx @@ -171,9 +171,10 @@ describe('an installed object: the package rules read-only beside the customer r fireEvent.click(screen.getByText('New')); fireEvent.click(screen.getByRole('button', { name: 'Advanced' })); fireEvent.click(screen.getByRole('button', { name: 'Condition — reject the save when it is true' })); - // `validation_2` is the package's: the new rule is named past it. + // `validation_2` is the package's: the new rule is named past it, with + // the customer suffix (objectstack#39661). expect(screen.getAllByText('validation_2')).toHaveLength(1); - expect(screen.getByText('validation_3')).toBeInTheDocument(); + expect(screen.getByText('validation_3__c')).toBeInTheDocument(); }); it('typing a package rule’s name into a customer rule is refused, and nothing is written', () => { @@ -198,3 +199,144 @@ describe('an installed object: the package rules read-only beside the customer r expect(screen.getByDisplayValue('金额不能为负')).toBeEnabled(); }); }); + +/** + * objectstack#39661 (ruling 7411414171, B) — on an installed object every name + * the panel derives for a customer rule ends in `__c`, the customer suffix the + * extension door requires, so a package's next version can never take it. + * The minted name and the name read off the message both carry it. + */ +describe('an installed object: a customer rule’s derived name ends in __c (objectstack#39661)', () => { + const packageRule = { + type: 'script', + name: 'validation_2', + message: 'Package says no', + condition: 'record.amount > 100', + }; + const customer = { + fields: draft.fields, + validations: [{ type: 'script', name: 'no_negative__c', message: '金额不能为负', condition: 'record.amount < 0' }], + }; + + function PairHarness({ onPatch }: { onPatch: (p: Record) => void }) { + const [d, setD] = React.useState>(customer); + return ( + { + onPatch(p); + setD((prev) => ({ ...prev, ...p })); + }} + packageRules={[packageRule]} + /> + ); + } + const addCondition = () => { + fireEvent.click(screen.getByText('New')); + fireEvent.click(screen.getByRole('button', { name: 'Advanced' })); + fireEvent.click(screen.getByRole('button', { name: 'Condition — reject the save when it is true' })); + }; + const nameBox = () => screen.getByRole('textbox', { name: /API name/ }) as HTMLInputElement; + const messageBox = () => screen.getByRole('textbox', { name: /Error message/ }) as HTMLInputElement; + + it('the minted name of a new rule ends in __c', () => { + render( {}} />); + addCondition(); + expect(nameBox().value).toBe('validation_3__c'); + }); + + it('the name read off the message ends in __c, and follows the message', () => { + render( {}} />); + addCondition(); + fireEvent.change(messageBox(), { target: { value: 'Too big' } }); + expect(nameBox().value).toBe('too_big__c'); + fireEvent.change(messageBox(), { target: { value: 'Way too big' } }); + expect(nameBox().value).toBe('way_too_big__c'); + }); + + it('CONTROL: on an object of the customer’s own, a minted name carries no suffix', () => { + render( {}} />); + addCondition(); + expect(nameBox().value).toBe('validation_3'); + }); +}); + +/** + * objectstack#39661 (ruling 7411414171, B) — a customer rule under a name a + * package rule holds does not run: the registry leaves the copy out and runs + * the package's rule. The panel lists the package's rule as the package's + * (read-only, its name refused) and lists the customer's copy beside it, named + * as taken, never as a live rule of the customer's; renaming the copy frees it. + */ +describe('an installed object: a customer copy under a package rule’s name is held (objectstack#39661)', () => { + const packageRule = { + type: 'script', + name: 'credit_check', + message: 'Package says no', + condition: 'record.amount > 100', + }; + const heldCopy = { ...packageRule, message: 'Mine now', active: false }; + const freeRule = { type: 'script', name: 'no_negative__c', message: '金额不能为负', condition: 'record.amount < 0' }; + const customer = { fields: draft.fields, validations: [heldCopy, freeRule] }; + + function HeldHarness({ onPatch }: { onPatch: (p: Record) => void }) { + const [d, setD] = React.useState>(customer); + return ( + { + onPatch(p); + setD((prev) => ({ ...prev, ...p })); + }} + packageRules={[packageRule]} + /> + ); + } + + it('lists the package’s rule as the package’s and the customer’s copy as held, each in its own row', () => { + render( {}} />); + const fromPackage = screen.getAllByTestId('rule-from-package'); + expect(fromPackage).toHaveLength(1); + expect(fromPackage[0].closest('button')).toHaveTextContent('Package says no'); + const held = screen.getAllByTestId('rule-held-by-package'); + expect(held).toHaveLength(1); + expect(held[0]).toHaveTextContent('credit_check'); + expect(held[0].closest('button')).toHaveTextContent('Mine now'); + // CONTROL: the customer's free rule carries neither mark. + const free = screen.getByText('no_negative__c').closest('button')!; + expect(within(free).queryByTestId('rule-held-by-package')).toBeNull(); + expect(within(free).queryByTestId('rule-from-package')).toBeNull(); + }); + + it('selecting each row opens that rule: the package’s read-only, the customer’s copy editable and named as taken', () => { + render( {}} />); + // Selected first: the package's rule, read-only. + expect(screen.getByDisplayValue('Package says no')).toBeDisabled(); + fireEvent.click(screen.getByTestId('rule-held-by-package').closest('button')!); + expect(screen.getByDisplayValue('Mine now')).toBeEnabled(); + expect(screen.queryByDisplayValue('Package says no')).toBeNull(); + expect(screen.getByTestId('rule-held-copy')).toHaveTextContent('credit_check'); + fireEvent.click(screen.getByTestId('rule-from-package').closest('button')!); + expect(screen.getByDisplayValue('Package says no')).toBeDisabled(); + }); + + it('renaming the held copy to a free name writes it and frees it; the package’s name stays refused', () => { + const onPatch = vi.fn(); + render(); + fireEvent.click(screen.getByTestId('rule-held-by-package').closest('button')!); + const nameInput = screen.getByDisplayValue('credit_check'); + fireEvent.change(nameInput, { target: { value: 'credit_check__c' } }); + expect(onPatch).toHaveBeenLastCalledWith({ + validations: [expect.objectContaining({ name: 'credit_check__c', message: 'Mine now' }), freeRule], + }); + expect(screen.queryByTestId('rule-held-by-package')).toBeNull(); + expect(screen.queryByTestId('rule-held-copy')).toBeNull(); + // The package's rule is untouched and still listed as the package's. + expect(screen.getAllByTestId('rule-from-package')).toHaveLength(1); + // Typing the package's name back is refused, and nothing is written. + const calls = onPatch.mock.calls.length; + fireEvent.change(screen.getByDisplayValue('credit_check__c'), { target: { value: 'credit_check' } }); + expect(screen.getByTestId('rule-name-taken')).toHaveTextContent('credit_check'); + expect(onPatch.mock.calls.length).toBe(calls); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectValidationsPanel.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectValidationsPanel.tsx index 4fa427ca323..1c7e1a3ab60 100644 --- a/ui/packages/app-shell/src/views/studio-design/ObjectValidationsPanel.tsx +++ b/ui/packages/app-shell/src/views/studio-design/ObjectValidationsPanel.tsx @@ -88,9 +88,14 @@ * base's paired `.custom` package, `pairValidations.ts`) and the package's * own rules as `packageRules`. The package's rules are listed first, marked as * the package's, and open read-only, whatever `disabled` says. A new rule, a - * derived name or a typed one never takes a name a package rule holds: the - * registry merges an extension's rules by name, so that name would replace the - * package's rule (or, with `active: false`, turn it off), which is not offered. + * derived name or a typed one never takes a name a package rule holds, and a + * name the panel derives ends in `__c` (objectstack#39661): the extension door + * refuses a customer rule under a package rule's name or without the suffix, + * and the registry never lets one replace or switch off a package rule. A + * customer rule already stored under a package rule's name is held, not run: + * it is listed beside the package's rule, named as taken, and stays editable so + * it can be renamed or deleted. The two share a name, so a package rule is + * selected by a key of its own ({@link PACKAGE_RULE_KEY}). */ import React from 'react'; @@ -119,6 +124,10 @@ import { ScriptValidationSchema, type ScriptValidationParsed } from '@objectstac import { VALIDATION_PRESETS, type PresetPlan, type ValidationPreset } from './validationPresets.js'; import { romanizeHan, useWhenRomanizerLands } from '../metadata-admin/romanizeHan.js'; import { StudioEmptyState, StudioEmptyStateAction } from './StudioEmptyState.js'; +import { customerRuleSuffix } from './pairValidations.js'; + +/** objectstack#39661 — the selection key of a package rule is its name behind this prefix, never a rule name's spelling. */ +const PACKAGE_RULE_KEY = 'package:'; /** * objectui#11781 — the look a disabled control takes: the pair the @@ -358,11 +367,11 @@ function readRules(input: unknown): ValidationRuleDraft[] { return input.filter((r): r is ValidationRuleDraft => !!r && typeof r === 'object'); } -function nextRuleName(existing: string[]): string { +function nextRuleName(existing: string[], suffix = ''): string { let i = existing.length + 1; - let name = `validation_${i}`; + let name = `validation_${i}${suffix}`; const taken = new Set(existing); - while (taken.has(name)) name = `validation_${++i}`; + while (taken.has(name)) name = `validation_${++i}${suffix}`; return name; } @@ -378,11 +387,11 @@ const DERIVED_RULE_NAME_MAX = 48; * romanisation, or a Chinese message typed before the dictionary landed, * keeps the minted name here. */ -function ruleNameFromMessage(message: string, taken: ReadonlySet): string | null { +function ruleNameFromMessage(message: string, taken: ReadonlySet, suffix = ''): string | null { const base = toFieldNameOrEmpty(romanizeHan(message)).slice(0, DERIVED_RULE_NAME_MAX).replace(/_+$/, ''); if (!base) return null; - let name = base; - for (let i = 2; taken.has(name); i++) name = `${base}_${i}`; + let name = `${base}${suffix}`; + for (let i = 2; taken.has(name); i++) name = `${base}_${i}${suffix}`; return name; } @@ -996,6 +1005,11 @@ export function ObjectValidationsPanel({ // objectstack#39471 — the package's rules, read-only, and the names they hold. const locked = React.useMemo(() => readRules(packageRules), [packageRules]); const lockedNames = React.useMemo(() => new Set(locked.map((r) => r.name ?? '')), [locked]); + // objectstack#39661 — a customer rule under a package rule's name is held: the package's runs. + const isHeld = (r: ValidationRuleDraft) => !locked.includes(r) && lockedNames.has(r.name ?? ''); + const keyOf = (r: ValidationRuleDraft) => (locked.includes(r) ? `${PACKAGE_RULE_KEY}${r.name ?? ''}` : (r.name ?? null)); + // objectstack#39661 — on an installed object every derived name ends in `__c`. + const suffix = customerRuleSuffix(packageRules !== undefined); const [nameTaken, setNameTaken] = React.useState(null); const listed = React.useMemo(() => [...locked, ...rules, ...unsaved], [locked, rules, unsaved]); const [selected, setSelected] = React.useState(() => focus?.name ?? null); @@ -1008,7 +1022,7 @@ export function ObjectValidationsPanel({ // Default to the first rule so the detail pane isn't a dead "pick one" empty // state whenever rules already exist. Falls back automatically when `selected` // no longer matches the current rule list (deleted, or the object switched). - const effectiveSelected = listed.some((r) => r.name === selected) ? selected : (listed[0]?.name ?? null); + const effectiveSelected = listed.some((r) => keyOf(r) === selected) ? selected : (listed[0] ? keyOf(listed[0]) : null); const fields = React.useMemo( () => @@ -1147,7 +1161,7 @@ export function ObjectValidationsPanel({ const derivedNames = React.useRef(new Set()); const patchMessage = (name: string, message: string) => { const next = derivedNames.current.has(name) - ? ruleNameFromMessage(message, new Set(listed.map((r) => r.name ?? '').filter((n) => n !== name))) + ? ruleNameFromMessage(message, new Set(listed.map((r) => r.name ?? '').filter((n) => n !== name)), suffix) : null; if (!next || next === name) { patchRule(name, { message }); @@ -1180,7 +1194,7 @@ export function ObjectValidationsPanel({ }; const addRule = (type: RuleType) => { - placeNewRule(newRule(type, nextRuleName(listed.map((r) => r.name ?? '')), firstField)); + placeNewRule(newRule(type, nextRuleName(listed.map((r) => r.name ?? ''), suffix), firstField)); }; /** @@ -1191,7 +1205,7 @@ export function ObjectValidationsPanel({ const addPreset = (preset: ValidationPreset, plan: Extract) => { const taken = listed.map((r) => r.name ?? ''); const rule: ValidationRuleDraft = { - ...newRule(preset.type, ruleNameFromMessage(plan.message, new Set(taken)) ?? nextRuleName(taken), firstField), + ...newRule(preset.type, ruleNameFromMessage(plan.message, new Set(taken), suffix) ?? nextRuleName(taken, suffix), firstField), message: plan.message, }; if (plan.fields) rule.fields = plan.fields; @@ -1206,9 +1220,10 @@ export function ObjectValidationsPanel({ if (selected === name) setSelected(null); }; - const sel = listed.find((r) => r.name === effectiveSelected) ?? null; + const sel = listed.find((r) => keyOf(r) === effectiveSelected) ?? null; // objectstack#39471 — a package rule opens read-only, whatever `disabled` says. const selLocked = sel !== null && locked.includes(sel); + const selHeld = sel !== null && isHeld(sel); const editorDisabled = disabled || selLocked; const selType = (typeof sel?.type === 'string' ? sel.type : 'script') as RuleType; const selUnsaved = sel !== null && isUnsaved(sel.name); @@ -1221,7 +1236,7 @@ export function ObjectValidationsPanel({ useWhenRomanizerLands(() => { if (disabled || !sel?.name || !sel.message || !derivedNames.current.has(sel.name)) return; const taken = new Set(listed.map((r) => r.name ?? '').filter((n) => n !== sel.name)); - const next = ruleNameFromMessage(sel.message, taken); + const next = ruleNameFromMessage(sel.message, taken, suffix); if (next && next !== sel.name) patchMessage(sel.name, sel.message); }, sel?.message ?? ''); @@ -1229,7 +1244,7 @@ export function ObjectValidationsPanel({ // type-specific keys — a state_machine's `transitions`, a format's `regex` — // don't linger on the new shape) while carrying the shared fields across. const changeType = (name: string, nextType: RuleType) => { - const cur = listed.find((r) => r.name === name); + const cur = [...rules, ...unsaved].find((r) => r.name === name); if (!cur) return; const unsavedRule = isUnsaved(name); // An existing rule is reshaped into a VALID skeleton (it is in the draft); @@ -1425,15 +1440,15 @@ export function ObjectValidationsPanel({
{listed.map((r) => (