diff --git a/.changeset/transfer-cascade-lint.md b/.changeset/transfer-cascade-lint.md new file mode 100644 index 00000000000..ce22dba2cd4 --- /dev/null +++ b/.changeset/transfer-cascade-lint.md @@ -0,0 +1,21 @@ +--- +'@objectstack/lint': minor +'@objectstack/spec': minor +--- + +feat(lint): refuse a `transferBehavior: 'cascade'` the Change Owner action can never offer + +Clause-②: no (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** for a stack that declares one of these cascades: `os validate`, `os build` and `os lint` now refuse it where they accepted it before. Fix it as below; the runtime never ran such a cascade, so no data changes. + +`os validate`, `os build` and `os lint` now refuse three `transferBehavior: 'cascade'` declarations that parsed and then did nothing, because the Change Owner endpoint re-judges every relationship and never offers them. Each is an `error`, with the fix named: + +- `transfer-cascade-parent-without-change-owner`: the reference points at a parent in the stack that does not offer Change Owner (`ownership: 'business_unit' | 'org' | 'none'`, any `managedBy`, a pinned or unprovable owner, or `userActions.transfer` off, by the author or by the `controlled_by_parent` default). A `sys_` parent stays the field parse's refusal. +- `transfer-cascade-extension-child-ineligible`: an object extension's field (`objectExtensions[].fields`) declares the cascade on an object that cannot take one. `ObjectSchema` already refused this on a field the object declares itself; an extension's field skipped that parse. A `fieldPatches` entry cannot carry the key at all. +- `transfer-cascade-child-update-unexposed`: the child's `enable` block does not serve `update` (`apiEnabled: false`, or `apiMethods` without update). + +Fix: set the field's `transferBehavior` to `'none'` or remove it, or change the object the message names (offer Change Owner on the parent, or open update on the child). The verdicts come from the spec predicates the runtime reads (`resolveUserActionTransfer`, `transferCascadeIneligibilityReason`, `apiExposureDenialReason`); the runtime is unchanged. New exports: `validateTransferCascades` and the three rule id constants. Not yet run at the runtime publish gate (follow-up #37397). Migration entry `transfer-cascade-never-offered-refused` (`@objectstack/spec`) carries the same fix for `os migrate meta` and the upgrade guide. diff --git a/content/docs/api/data-api.mdx b/content/docs/api/data-api.mdx index 865725b5591..b7ba34789cb 100644 --- a/content/docs/api/data-api.mdx +++ b/content/docs/api/data-api.mdx @@ -572,6 +572,12 @@ object's cascade candidates (see the route below) is refused `400 VALIDATION_ERROR` before anything is written. `'cascade'` on a multi-value reference (`multiple: true`) is refused when the metadata is saved: a record there points at several parents, so no single Change Owner decides its owner. +`os validate`, `os build` and `os lint` also refuse a `'cascade'` that Change +Owner could never offer: one pointing at a parent in the stack that does not +offer Change Owner, one an object extension adds to an object that cannot take +a cascade, and one on a child whose `enable` block does not serve `update` +(`os explain transfer-cascade-parent-without-change-owner` and its two +siblings say why). The answer gains one outcome per named relationship: diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 919d3d6285e..4c4d750bb2e 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -937,7 +937,7 @@ os compile --json # JSON output for CI pipelines → Normalizing stack definition... → Lowering inline handlers... → Validating protocol compliance... - → Running author-time rules (79)... + → Running author-time rules (80)... → Checking that every required capability has a provider installable in this edition... → Collecting package docs (ADR-0046)... 0 collected → Writing artifact... diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index 9b70c57abe8..ed40bb89b71 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -867,7 +867,7 @@ A clean run walks the registry and reports timing: Config: /path/to/support-desk/objectstack.config.ts Load time: 21ms → Validating against ObjectStack Protocol... - → Running author-time rules (79)... + → Running author-time rules (80)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/content/docs/getting-started/build-with-claude-code.mdx b/content/docs/getting-started/build-with-claude-code.mdx index 7f53195af9e..8165bd3a42c 100644 --- a/content/docs/getting-started/build-with-claude-code.mdx +++ b/content/docs/getting-started/build-with-claude-code.mdx @@ -311,7 +311,7 @@ visible: 'status != "resolved"' ◆ Validate ──────────────────────────────────────── → Validating against ObjectStack Protocol... - → Running author-time rules (79)... + → Running author-time rules (80)... ✗ Author-time rules failed (1 issue) • stack · action 'resolve_ticket' visible: bare reference `status` — a diff --git a/content/docs/ui/react-pages.mdx b/content/docs/ui/react-pages.mdx index 2c196df8b2e..d8c8b9be510 100644 --- a/content/docs/ui/react-pages.mdx +++ b/content/docs/ui/react-pages.mdx @@ -404,7 +404,7 @@ objectstack validate ──────────────────────────────────────── → Loading configuration... → Validating against ObjectStack Protocol... - → Running author-time rules (79)... + → Running author-time rules (80)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/packages/core/src/security/second-object-read-exposure.pin.test.ts b/packages/core/src/security/second-object-read-exposure.pin.test.ts index 3ed1502d69b..18e9ea11069 100644 --- a/packages/core/src/security/second-object-read-exposure.pin.test.ts +++ b/packages/core/src/security/second-object-read-exposure.pin.test.ts @@ -307,6 +307,11 @@ const CALLERS: Record = { kind: 'not-a-served-read', reason: 'authoring-time static analysis of metadata; reads no record', }, + // [#36714] A `transferBehavior: 'cascade'` judged against the parent's declared Change Owner switch. + 'packages/lint/src/validate-transfer-cascades.ts': { + kind: 'not-a-served-read', + reason: 'authoring-time static analysis of metadata; reads no record', + }, // [#35146] The post-publish build probes' two landed-data checks. 'packages/metadata-protocol/src/build-probes.ts': { kind: 'not-a-served-read', diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 4f3cbcedc0b..d37882c6455 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -101,6 +101,7 @@ import { runStackExpressionPasses } from './validate-expressions.js'; import { validateListViewMode } from './validate-list-view-mode.js'; import { validateFunctionalCompleteness } from './validate-functional-completeness.js'; import { validateManagedApiMethods } from './validate-managed-api-methods.js'; +import { validateTransferCascades } from './validate-transfer-cascades.js'; import { validateViewContainers } from './validate-view-containers.js'; import { validateWidgetBindings } from './validate-widget-bindings.js'; import { validateDatasetMeasureAggregates } from './validate-dataset-measure-aggregates.js'; @@ -996,6 +997,36 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ runtimeTypes: ['object'], run: (stack) => validateManagedApiMethods(stack), }, + // [ruling 7000907189 point 4 · ADR-0049] A `transferBehavior: 'cascade'` + // the Change Owner action can never offer: the parent does not offer Change + // Owner, an extension's field cascades onto an object that cannot take a + // cascade (the `ObjectSchema` refinement judges only the object's own + // fields), or the child's declared exposure does not serve `update`. The + // runtime re-judges each relationship and offers none of these, silently; + // this puts the same verdicts, from the same spec predicates, where the + // author is. Gating for the `validateManagedApiMethods` reason above: the + // verdict is decidable from the stack, and the declaration is a key nothing + // honours. + { + name: 'validateTransferCascades', + tier: 'gating', + input: 'parsed', + commands: ALL, + source: 'packages/lint/src/validate-transfer-cascades.ts', + surfaces: CLI_ONLY, + // The crossing is follow-up #37397. The number lives in this comment, not in the string below: a + // string literal under packages/ carries no tracker number (`pnpm check:doc-authoring`). + surfaceReason: + 'Not yet crossed, pending a measurement: at the runtime publish gate the snapshot\'s objects are the ' + + 'registry\'s served definitions, which carry the injected system columns (owner_id among them) as ' + + 'declared fields, and the Change Owner eligibility predicate this rule reads judges a declared ' + + 'owner_id (its readonly flag, and on an external object whether it is declared at all). Judging ' + + 'served definitions with it is unmeasured, and a false 422 on the only door a Studio or MCP author ' + + 'has is worse than the gap. Crossing owes that measurement, or reading the served objects back to ' + + 'their authored shape as lintDuplicateFieldLabels does at the object_extension door, and its own ' + + 'rollout decision; never a bare `runtimeTypes` edit.', + run: (stack) => validateTransferCascades(stack), + }, // A view container in `views: []` that registers zero views: nothing appears // in the Console, and the schema step cannot tell it from an intentionally // empty one. The FLAT-list-view arm no longer needs this tier — `ViewSchema` diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 8880a48921c..6714de88f86 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -545,6 +545,18 @@ export type { MembershipKeyOwners, } from './validate-membership-key-declarations.js'; +// [ruling 7000907189 point 4 · ADR-0049] A `transferBehavior: 'cascade'` the +// Change Owner action can never offer: a parent without Change Owner, an +// extension's field on an object that cannot take a cascade, a child whose +// declared exposure does not serve `update`. +export { + validateTransferCascades, + TRANSFER_CASCADE_PARENT_WITHOUT_CHANGE_OWNER, + TRANSFER_CASCADE_EXTENSION_CHILD_INELIGIBLE, + TRANSFER_CASCADE_CHILD_UPDATE_UNEXPOSED, +} from './validate-transfer-cascades.js'; +export type { TransferCascadeFinding } from './validate-transfer-cascades.js'; + export { validateDashboardActionRefs, DASHBOARD_ACTION_TARGET_UNDEFINED, diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 34b8b040634..5a25e8a6b2c 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -6611,6 +6611,79 @@ const FIELD_LABEL_DUPLICATE_EXPLANATION: RuleExplanation = { ], }; +// ── Change Owner cascades that can never run (`validate-transfer-cascades.ts`) ── + +/** What every transfer-cascade id shares: where the verdict comes from and why it refuses. */ +const TRANSFER_CASCADE_SHARED = + 'A `transferBehavior: \'cascade\'` on a lookup or master_detail field asks a Change Owner of the ' + + 'referenced (parent) record to move the records here that point at it, and that the parent\'s previous ' + + 'owner holds, to the new owner too. The Change Owner endpoint re-judges every relationship on every call ' + + 'and offers only the ones that can act, so nothing wrong happens at run time; but a declaration it never ' + + 'offers is a key nothing honours (ADR-0049), and the author would never be told. The verdicts come from ' + + 'the same spec predicates the endpoint reads (`resolveUserActionTransfer`, ' + + '`transferCascadeIneligibilityReason`, `apiExposureDenialReason` in `@objectstack/spec/data`), on the ' + + 'objects as the registry serves them, every object extension\'s fields folded in. An object this stack ' + + 'does not declare cannot be judged, on either side of the relationship, and is skipped.'; + +/** + * Where these ids run, and what the field parse already refuses. The runtime publish gate crossing is + * follow-up #37397; the number stays in this comment, since an author is shown the text and it carries no + * tracker number (`rule-explanations.test.ts`, `pnpm check:doc-authoring`). + */ +const TRANSFER_CASCADE_SCOPE = + 'Judged by `os validate`, `os build` and `os lint`, not yet at the runtime publish gate (its objects are ' + + 'served definitions carrying the injected owner_id, which the eligibility predicate reads; crossing ' + + 'waits on a measurement). The field parse refuses the other shapes with their own prescription: ' + + '`transferBehavior` off a lookup or master_detail field, `\'cascade\'` on a multi-value reference or ' + + 'on a reference to a `sys_` object; and `ObjectSchema` refuses a cascade on a field the object declares ' + + 'itself when the object cannot take one. Those are not reported again here.'; + +const TRANSFER_CASCADE_PARENT_WITHOUT_CHANGE_OWNER_EXPLANATION: RuleExplanation = { + rule: 'transfer-cascade-parent-without-change-owner', + covers: 'why a cascade needs a parent that offers Change Owner', + paragraphs: [ + TRANSFER_CASCADE_SHARED, + 'The cascade runs inside a Change Owner of the parent and nowhere else, and the endpoint refuses the ' + + 'whole call on an object that does not offer the action. A parent does not offer it when it is not ' + + 'structurally eligible (ownership `business_unit`, `org` or `none`, any `managedBy`, ' + + '`systemFields: false`, an `owner_id` declared readonly, an external object with no provable owner) or ' + + 'when its `userActions.transfer` is off, by the author or by the `controlled_by_parent` default. The ' + + 'message names which; where the parent can be changed to offer the action, the reason ends with that ' + + 'change. Otherwise the fix is on the field: set it to `none` or remove it.', + TRANSFER_CASCADE_SCOPE, + ], +}; + +const TRANSFER_CASCADE_EXTENSION_CHILD_INELIGIBLE_EXPLANATION: RuleExplanation = { + rule: 'transfer-cascade-extension-child-ineligible', + covers: 'why an extension field cannot cascade onto this object', + paragraphs: [ + TRANSFER_CASCADE_SHARED, + 'A cascade moves the records of the object that declares the field, by the same Change Owner action, ' + + 'so that object must offer the action itself: structurally eligible, not a `controlled_by_parent` ' + + 'detail (its access already follows its master), and its `userActions.transfer` not off. `ObjectSchema` ' + + 'refuses a cascade on a field the object declares itself, but a field an object extension ' + + '(`objectExtensions[].fields`) adds never passes through that parse, so this rule judges it on the ' + + 'extended object. An extension\'s `fieldPatches` cannot carry `transferBehavior` at all: a patch sets ' + + 'display properties only, and its schema refuses the key.', + TRANSFER_CASCADE_SCOPE, + ], +}; + +const TRANSFER_CASCADE_CHILD_UPDATE_UNEXPOSED_EXPLANATION: RuleExplanation = { + rule: 'transfer-cascade-child-update-unexposed', + covers: 'why a cascading object must serve update', + paragraphs: [ + TRANSFER_CASCADE_SHARED, + 'The cascade reads and writes the child\'s rows as a second object of the call, each move the caller\'s ' + + 'own update, so the child is asked its own declared API exposure for `update`, the operation the data ' + + 'route judges. An object with `enable.apiEnabled: false`, or an `enable.apiMethods` list that does not ' + + 'grant update, is left out of the cascades Change Owner offers. Either open update on the child or set ' + + 'the field to `none`.', + TRANSFER_CASCADE_SCOPE, + ], +}; + // ── Publish-time refusals of metadata that parses and does nothing ────────── // (`validate-flow-node-executors.ts`, `lint-flow-patterns.ts`, // `validate-inert-object-declarations.ts`, `validate-action-object-binding.ts`) @@ -7074,6 +7147,9 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [STORED_EXPRESSION_CROSS_RECORD_INPUT_EXPLANATION.rule]: STORED_EXPRESSION_CROSS_RECORD_INPUT_EXPLANATION, [STORED_EXPRESSION_VOLATILE_INPUT_EXPLANATION.rule]: STORED_EXPRESSION_VOLATILE_INPUT_EXPLANATION, [FIELD_LABEL_DUPLICATE_EXPLANATION.rule]: FIELD_LABEL_DUPLICATE_EXPLANATION, + [TRANSFER_CASCADE_PARENT_WITHOUT_CHANGE_OWNER_EXPLANATION.rule]: TRANSFER_CASCADE_PARENT_WITHOUT_CHANGE_OWNER_EXPLANATION, + [TRANSFER_CASCADE_EXTENSION_CHILD_INELIGIBLE_EXPLANATION.rule]: TRANSFER_CASCADE_EXTENSION_CHILD_INELIGIBLE_EXPLANATION, + [TRANSFER_CASCADE_CHILD_UPDATE_UNEXPOSED_EXPLANATION.rule]: TRANSFER_CASCADE_CHILD_UPDATE_UNEXPOSED_EXPLANATION, [FLOW_NODE_TYPE_NO_EXECUTOR_EXPLANATION.rule]: FLOW_NODE_TYPE_NO_EXECUTOR_EXPLANATION, [FLOW_APPROVAL_DECISION_UNROUTED_EXPLANATION.rule]: FLOW_APPROVAL_DECISION_UNROUTED_EXPLANATION, [FLOW_HTTP_TIMEOUT_MISSING_EXPLANATION.rule]: FLOW_HTTP_TIMEOUT_MISSING_EXPLANATION, diff --git a/packages/lint/src/validate-transfer-cascades-36714.test.ts b/packages/lint/src/validate-transfer-cascades-36714.test.ts new file mode 100644 index 00000000000..edf08db0d0f --- /dev/null +++ b/packages/lint/src/validate-transfer-cascades-36714.test.ts @@ -0,0 +1,224 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { ObjectExtensionSchema, ObjectSchema } from '@objectstack/spec/data'; + +import { + TRANSFER_CASCADE_CHILD_UPDATE_UNEXPOSED, + TRANSFER_CASCADE_EXTENSION_CHILD_INELIGIBLE, + TRANSFER_CASCADE_PARENT_WITHOUT_CHANGE_OWNER, + validateTransferCascades, +} from './validate-transfer-cascades.js'; +import { AUTHORING_COMMANDS, AUTHORING_RULES } from './authoring-rules.js'; + +/** + * [ruling 7000907189 point 4 · ADR-0049] The three `transferBehavior: 'cascade'` + * declarations that parse and that the Change Owner action can never offer: + * a parent without Change Owner, an extension's field on an object that + * cannot take a cascade, a child whose declared exposure does not serve + * `update`. Every fixture is a full `ObjectSchema` / `ObjectExtensionSchema` + * parse, so each refusal here is one the parse lets through. + */ + +const TITLE = { title: { type: 'text', label: 'Title' } }; +const CASCADE_TO = (reference: string) => ({ type: 'lookup', label: 'Parent', reference, transferBehavior: 'cascade' }); +const MASTER_OF = (reference: string) => ({ type: 'master_detail', label: 'Master', reference, required: true }); + +function object(name: string, extra: Record = {}, fields: Record = TITLE) { + const result = ObjectSchema.safeParse({ name, label: name, fields, ...extra }); + expect(result.success, result.success ? '' : JSON.stringify(result.error.issues)).toBe(true); + return result.success ? result.data : {}; +} + +function extension(extend: string, fields: Record) { + const result = ObjectExtensionSchema.safeParse({ extend, fields }); + expect(result.success, result.success ? '' : JSON.stringify(result.error.issues)).toBe(true); + return result.success ? result.data : {}; +} + +/** A child `deal_note` cascading to `parent`, beside the parent as declared. */ +function childOf(parent: unknown, childExtra: Record = {}) { + return { + objects: [parent, object('deal_note', childExtra, { ...TITLE, deal: CASCADE_TO('deal') })], + }; +} + +const rulesOf = (stack: unknown) => validateTransferCascades(stack).map((f) => f.rule); + +describe('case 1 — the parent does not offer Change Owner', () => { + it.each([ + ['ownership: org', { ownership: 'org' }, "ownership: 'org'"], + ['ownership: none', { ownership: 'none' }, "ownership: 'none'"], + ['managedBy: config', { managedBy: 'config' }, "managedBy: 'config'"], + ['userActions.transfer: false', { userActions: { transfer: false } }, 'userActions.transfer is off'], + ])('refuses a cascade to a parent with %s, naming why and what to change', (_label, extra, reason) => { + const findings = validateTransferCascades(childOf(object('deal', extra))); + expect(findings).toHaveLength(1); + const [f] = findings; + expect(f!.severity).toBe('error'); + expect(f!.rule).toBe(TRANSFER_CASCADE_PARENT_WITHOUT_CHANGE_OWNER); + expect(f!.where).toBe('field "deal_note.deal"'); + expect(f!.path).toBe('objects[1].fields.deal.transferBehavior'); + expect(f!.message).toContain("'deal' does not offer Change Owner"); + expect(f!.message).toContain(reason); + expect(f!.hint).toContain("Set transferBehavior to 'none' or remove it"); + }); + + it('refuses a cascade to a controlled_by_parent parent left at its default', () => { + const parent = object('deal', { sharingModel: 'controlled_by_parent' }, { ...TITLE, account: MASTER_OF('account') }); + const findings = validateTransferCascades({ objects: [object('account'), ...childOf(parent).objects] }); + expect(findings.map((f) => f.rule)).toEqual([TRANSFER_CASCADE_PARENT_WITHOUT_CHANGE_OWNER]); + expect(findings[0]!.message).toContain('controlled_by_parent detail'); + }); + + it('accepts a cascade to a parent that offers Change Owner', () => { + expect(rulesOf(childOf(object('deal')))).toEqual([]); + expect(rulesOf(childOf(object('deal', { ownership: 'user' })))).toEqual([]); + expect(rulesOf(childOf(object('deal', { userActions: { transfer: true } })))).toEqual([]); + }); + + it('does not judge a parent the stack does not declare', () => { + expect(rulesOf({ objects: [object('deal_note', {}, { ...TITLE, deal: CASCADE_TO('deal') })] })).toEqual([]); + }); + + it('leaves a sys_ parent to the field parse, which refuses it there', () => { + const field = { type: 'lookup', label: 'Ledger', reference: 'sys_ledger', transferBehavior: 'cascade' }; + expect(ObjectSchema.safeParse({ name: 'deal_note', label: 'n', fields: { ledger: field } }).success).toBe(false); + // A stack that reached lint unparsed, with the sys_ object declared and off, still reads nothing here. + const stack = { objects: [{ name: 'sys_ledger', fields: {} }, { name: 'deal_note', fields: { ledger: field } }] }; + expect(rulesOf(stack)).toEqual([]); + }); + + it('judges a cascade field an extension adds as well', () => { + const stack = { + objects: [object('deal', { ownership: 'none' }), object('deal_note')], + objectExtensions: [extension('deal_note', { deal: CASCADE_TO('deal') })], + }; + const findings = validateTransferCascades(stack); + expect(findings.map((f) => f.rule)).toEqual([TRANSFER_CASCADE_PARENT_WITHOUT_CHANGE_OWNER]); + expect(findings[0]!.path).toBe('objectExtensions[0].fields.deal.transferBehavior'); + }); +}); + +describe('case 2 — an extension field cascades onto an object that cannot take a cascade', () => { + it.each([ + ['ownership: none', { ownership: 'none' }, {}, "ownership: 'none'"], + ['a controlled_by_parent detail', { sharingModel: 'controlled_by_parent' }, { account: MASTER_OF('account') }, 'controlled_by_parent'], + ['userActions.transfer: false', { userActions: { transfer: false } }, {}, 'userActions.transfer is off'], + ])('refuses it on a target that is %s', (_label, extra, fields, reason) => { + const stack = { + objects: [object('account'), object('deal'), object('deal_note', extra, { ...TITLE, ...fields })], + objectExtensions: [extension('deal_note', { deal: CASCADE_TO('deal') })], + }; + const findings = validateTransferCascades(stack); + expect(findings).toHaveLength(1); + const [f] = findings; + expect(f!.severity).toBe('error'); + expect(f!.rule).toBe(TRANSFER_CASCADE_EXTENSION_CHILD_INELIGIBLE); + expect(f!.where).toBe('field "deal_note.deal"'); + expect(f!.path).toBe('objectExtensions[0].fields.deal.transferBehavior'); + expect(f!.message).toContain("'deal_note' cannot take a Change Owner cascade"); + expect(f!.message).toContain(reason); + expect(f!.hint).toContain("remove it from the extension's field"); + }); + + it('accepts it on a target that offers Change Owner', () => { + const stack = { + objects: [object('deal'), object('deal_note')], + objectExtensions: [extension('deal_note', { deal: CASCADE_TO('deal') })], + }; + expect(rulesOf(stack)).toEqual([]); + }); + + it('does not judge a target the stack does not declare', () => { + const stack = { objects: [object('deal')], objectExtensions: [extension('crm_note', { deal: CASCADE_TO('deal') })] }; + expect(rulesOf(stack)).toEqual([]); + }); + + it('reads extensions in the packages[] artifact shape', () => { + const stack = { + objects: [object('deal'), object('deal_note', { ownership: 'none' })], + packages: [{ manifest: { objectExtensions: [extension('deal_note', { deal: CASCADE_TO('deal') })] } }], + }; + const findings = validateTransferCascades(stack); + expect(findings.map((f) => f.rule)).toEqual([TRANSFER_CASCADE_EXTENSION_CHILD_INELIGIBLE]); + expect(findings[0]!.path).toBe('packages[0].manifest.objectExtensions[0].fields.deal.transferBehavior'); + }); + + it('has no fieldPatches arm to judge: a field patch cannot carry the key', () => { + const result = ObjectExtensionSchema.safeParse({ extend: 'deal_note', fieldPatches: { deal: { transferBehavior: 'cascade' } } }); + expect(result.success).toBe(false); + expect(result.success ? [] : result.error.issues.map((i) => i.code)).toContain('unrecognized_keys'); + }); + + it('leaves a field the object declares itself to the ObjectSchema refinement', () => { + // Unparsed (os lint never parses): the object-level half is the parse's, so no case-2 finding here. + const stack = { objects: [object('deal'), { name: 'deal_note', ownership: 'none', fields: { deal: CASCADE_TO('deal') } }] }; + expect(rulesOf(stack)).toEqual([]); + }); +}); + +describe('case 3 — the child\'s declared API exposure does not serve update', () => { + it('refuses it when enable.apiMethods leaves update out', () => { + const findings = validateTransferCascades(childOf(object('deal'), { enable: { apiMethods: ['get', 'list', 'create'] } })); + expect(findings).toHaveLength(1); + const [f] = findings; + expect(f!.severity).toBe('error'); + expect(f!.rule).toBe(TRANSFER_CASCADE_CHILD_UPDATE_UNEXPOSED); + expect(f!.path).toBe('objects[1].fields.deal.transferBehavior'); + expect(f!.message).toContain('enable.apiMethods does not include update'); + expect(f!.hint).toContain("add 'update' to enable.apiMethods of 'deal_note'"); + }); + + it('refuses it when enable.apiEnabled is false', () => { + const findings = validateTransferCascades(childOf(object('deal'), { enable: { apiEnabled: false } })); + expect(findings.map((f) => f.rule)).toEqual([TRANSFER_CASCADE_CHILD_UPDATE_UNEXPOSED]); + expect(findings[0]!.message).toContain('enable.apiEnabled is false'); + expect(findings[0]!.hint).toContain('turn enable.apiEnabled on'); + }); + + it('refuses it on an extension field\'s target too', () => { + const stack = { + objects: [object('deal'), object('deal_note', { enable: { apiMethods: ['get', 'list'] } })], + objectExtensions: [extension('deal_note', { deal: CASCADE_TO('deal') })], + }; + expect(rulesOf(stack)).toEqual([TRANSFER_CASCADE_CHILD_UPDATE_UNEXPOSED]); + }); + + it('accepts it when update is served (no enable block, or update granted)', () => { + expect(rulesOf(childOf(object('deal')))).toEqual([]); + expect(rulesOf(childOf(object('deal'), { enable: { apiMethods: ['get', 'list', 'update'] } }))).toEqual([]); + }); + + it('reports each failed case of one field, since each has its own fix', () => { + const stack = childOf(object('deal', { ownership: 'org' }), { enable: { apiMethods: ['get'] } }); + expect(rulesOf(stack)).toEqual([TRANSFER_CASCADE_PARENT_WITHOUT_CHANGE_OWNER, TRANSFER_CASCADE_CHILD_UPDATE_UNEXPOSED]); + }); +}); + +describe('scope and wiring', () => { + it('judges nothing on a field whose transferBehavior is none, absent, or a multi-value reference', () => { + const stack = { + objects: [ + object('deal', { ownership: 'none' }), + object('deal_note', { enable: { apiMethods: ['get'] } }, { + ...TITLE, + a: { type: 'lookup', label: 'A', reference: 'deal', transferBehavior: 'none' }, + b: { type: 'lookup', label: 'B', reference: 'deal' }, + }), + // Unparsed: the field parse refuses 'cascade' on a multi-value reference. + { name: 'deal_tag', fields: { c: { type: 'lookup', reference: 'deal', multiple: true, transferBehavior: 'cascade' } } }, + ], + }; + expect(rulesOf(stack)).toEqual([]); + }); + + it('runs as a gating rule on all three commands', () => { + const entry = AUTHORING_RULES.find((r) => r.name === 'validateTransferCascades'); + expect(entry).toBeDefined(); + expect(entry!.tier).toBe('gating'); + expect([...entry!.commands]).toEqual([...AUTHORING_COMMANDS]); + const findings = entry!.run(childOf(object('deal', { ownership: 'none' })) as Record, {}); + expect(findings.map((f) => f.rule)).toEqual([TRANSFER_CASCADE_PARENT_WITHOUT_CHANGE_OWNER]); + }); +}); diff --git a/packages/lint/src/validate-transfer-cascades.ts b/packages/lint/src/validate-transfer-cascades.ts new file mode 100644 index 00000000000..2a18297c8aa --- /dev/null +++ b/packages/lint/src/validate-transfer-cascades.ts @@ -0,0 +1,259 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [ruling 7000907189 point 4 · ADR-0049] A `transferBehavior: 'cascade'` +// declaration the Change Owner action can never offer, refused where the +// author is. +// +// The runtime is safe on its own: `transferCascadeRelations` +// (`@objectstack/core`'s `change-record-owner.ts`) re-judges every +// relationship on every call and offers only the ones that can act, and the +// endpoint refuses a whole call on a parent that does not offer Change Owner. +// What the runtime cannot do is tell the author, so three declarations parse +// and then do nothing — a key nothing honours, which ADR-0049 forbids: +// +// 1. {@link TRANSFER_CASCADE_PARENT_WITHOUT_CHANGE_OWNER} — the reference +// points at a parent in this stack that does not offer Change Owner +// (`ownership: 'org' | 'none' | 'business_unit'`, `managedBy`, a pinned or +// unprovable owner, or `userActions.transfer` off). The cascade runs only +// inside a Change Owner of the parent, so it never runs. Cross-object, so +// no field or object parse can judge it. A `sys_` parent is the field +// parse's (`FieldSchema` refuses `'cascade'` on a reference to one) and is +// not judged again here. +// 2. {@link TRANSFER_CASCADE_EXTENSION_CHILD_INELIGIBLE} — the field is added +// to its object through `ObjectExtensionSchema.fields`, and that object +// cannot take a Change Owner cascade. `ObjectSchema`'s refinement +// (`refuseIneligibleTransferCascades`) refuses the same declaration on a +// field the object declares itself, but an extension's field never passes +// through that parse. `fieldPatches` cannot carry the key at all: a patch +// sets display properties only, and its schema refuses `transferBehavior` +// as an unrecognized key, so there is nothing to walk there. +// 3. {@link TRANSFER_CASCADE_CHILD_UPDATE_UNEXPOSED} — the child's declared +// API exposure (`enable.apiEnabled` / `enable.apiMethods`) does not serve +// `update`. The cascade moves the child's rows as updates through the data +// door, so `transferCascadeRelations` leaves such a child out. +// +// All judgement lives in the SHARED predicates the runtime reads, imported +// from `@objectstack/spec/data`: `resolveUserActionTransfer` / +// `transferIneligibilityReason` (does the parent offer Change Owner — the +// endpoint's `changeOwnerOffReason` asks the same), `transferCascadeIneligibilityReason` +// (can the child take a cascade — the parse refinement and +// `transferCascadeRelations` ask the same) and `apiExposureDenialReason` (the +// exposure filter, whose boolean face `canServeApiOperation` is what +// `transferCascadeRelations` calls). This file is only the walk. If a verdict +// seems wrong, fix the predicate, never this walk. +// +// Objects are judged as the registry SERVES them (`objectsAsServed`: every +// `objectExtensions` field folded in), because `transferCascadeRelations` +// reads the registered, merged definitions. An object the stack does not +// declare (another package's) cannot be judged and is skipped, whichever side +// of the relationship it is on. +// +// Only the fields the runtime reads are judged: a single-value `lookup` or +// `master_detail` field. Any other type, a multi-value reference and a +// reference to a `sys_` object are refused by the field parse with their own +// prescription, so judging them here would report one mistake twice. + +import { + apiExposureDenialReason, + referenceTargetOf, + resolveUserActionTransfer, + transferCascadeIneligibilityReason, + transferIneligibilityReason, + type EnableLike, +} from '@objectstack/spec/data'; + +import { collectionEntries } from './collection-entries.js'; +import { objectExtensionsByTarget, objectsAsServed } from './object-graph.js'; + +/** Case 1: the referenced parent does not offer Change Owner. */ +export const TRANSFER_CASCADE_PARENT_WITHOUT_CHANGE_OWNER = 'transfer-cascade-parent-without-change-owner'; +/** Case 2: an extension's field declares a cascade on an object that cannot take one. */ +export const TRANSFER_CASCADE_EXTENSION_CHILD_INELIGIBLE = 'transfer-cascade-extension-child-ineligible'; +/** Case 3: the child's declared API exposure does not serve `update`. */ +export const TRANSFER_CASCADE_CHILD_UPDATE_UNEXPOSED = 'transfer-cascade-child-update-unexposed'; + +export interface TransferCascadeFinding { + /** + * Always `error`: each verdict is decidable from the stack's own + * declarations, and the declaration would ship as a key nothing honours + * (the `object/managed-api-method-unaffordable` precedent, and the parse's + * own refusal of the declaring object's half). + */ + severity: 'error'; + rule: + | typeof TRANSFER_CASCADE_PARENT_WITHOUT_CHANGE_OWNER + | typeof TRANSFER_CASCADE_EXTENSION_CHILD_INELIGIBLE + | typeof TRANSFER_CASCADE_CHILD_UPDATE_UNEXPOSED; + /** e.g. `field "deal_note.account"`. */ + where: string; + /** e.g. `objects[1].fields.account.transferBehavior`. */ + path: string; + message: string; + hint: string; +} + +type AnyRec = Record; + +const isRec = (v: unknown): v is AnyRec => !!v && typeof v === 'object' && !Array.isArray(v); + +/** One `transferBehavior: 'cascade'` declaration, where it was written. */ +interface CascadeSite { + /** The object whose records the cascade would move (the field's owner as served). */ + child: string; + field: string; + def: AnyRec; + /** Path of the field record itself, without `.transferBehavior`. */ + fieldPath: string; + /** Set when the field comes from an `objectExtensions` entry. */ + viaExtension: boolean; +} + +/** The field records of an authored `fields` value, each with its own path. */ +function fieldSites(fields: unknown, base: string): Array<{ name: string; def: AnyRec; path: string }> { + if (Array.isArray(fields)) { + return fields.flatMap((def, i) => + isRec(def) && typeof def.name === 'string' ? [{ name: def.name, def, path: `${base}[${i}]` }] : []); + } + if (!isRec(fields)) return []; + return Object.entries(fields).flatMap(([name, def]) => (isRec(def) ? [{ name, def, path: `${base}.${name}` }] : [])); +} + +/** The fields `transferCascadeRelations` reads: a single-value relationship declaring `'cascade'`. */ +function declaresCascade(def: AnyRec): boolean { + return def.transferBehavior === 'cascade' + && (def.type === 'lookup' || def.type === 'master_detail') + && def.multiple !== true; +} + +/** The parent a reference field points at, or `undefined` (an unreadable carrier included). */ +function parentOf(def: AnyRec): string | undefined { + try { + return referenceTargetOf(def); + } catch { + return undefined; + } +} + +/** + * Why `parent` does not offer Change Owner, or `undefined` when it does. The + * verdict is `resolveUserActionTransfer`'s; the clause names the structural + * reason (`transferIneligibilityReason`, which carries its own arm's + * prescription) or which switch keeps the action off. + */ +function parentOffReason(def: AnyRec): string | undefined { + if (resolveUserActionTransfer(def).enabled) return undefined; + const structural = transferIneligibilityReason(def); + if (structural !== undefined) return structural; + const authored = isRec(def.userActions) ? def.userActions.transfer : undefined; + if (authored !== undefined && authored !== null) { + return 'its userActions.transfer is off; to offer it, turn userActions.transfer on'; + } + return 'it is a controlled_by_parent detail, on which Change Owner is off unless it sets ' + + 'userActions.transfer to true'; +} + +/** Every cascade declaration of the stack: the objects' own fields, then the extensions' fields. */ +function cascadeSites(stack: AnyRec): CascadeSite[] { + const sites: CascadeSite[] = []; + for (const { rec, path } of collectionEntries(stack.objects, 'objects')) { + if (typeof rec.name !== 'string') continue; + for (const f of fieldSites(rec.fields, `${path}.fields`)) { + if (declaresCascade(f.def)) { + sites.push({ child: rec.name, field: f.name, def: f.def, fieldPath: f.path, viaExtension: false }); + } + } + } + for (const [target, entries] of objectExtensionsByTarget(stack)) { + for (const ext of entries) { + if (ext.stored) continue; + for (const def of ext.fields) { + if (typeof def.name !== 'string' || !declaresCascade(def)) continue; + sites.push({ child: target, field: def.name, def, fieldPath: `${ext.path}.fields.${def.name}`, viaExtension: true }); + } + } + } + return sites; +} + +/** + * Refuse each `transferBehavior: 'cascade'` declaration in the stack that the + * Change Owner action can never offer. One finding per case per field: the + * cases have different fixes, and a field can fail more than one. + */ +export function validateTransferCascades(stack: unknown): TransferCascadeFinding[] { + const out: TransferCascadeFinding[] = []; + if (!isRec(stack)) return out; + + const served = new Map(); + for (const obj of objectsAsServed(stack).objects) { + if (typeof obj.name === 'string') served.set(obj.name, obj); + } + + for (const site of cascadeSites(stack)) { + const where = `field "${site.child}.${site.field}"`; + const path = `${site.fieldPath}.transferBehavior`; + const declared = `Field '${site.field}' on '${site.child}' declares transferBehavior: 'cascade'`; + + const parent = parentOf(site.def); + const parentDef = parent !== undefined && !parent.startsWith('sys_') ? served.get(parent) : undefined; + const parentReason = parentDef !== undefined ? parentOffReason(parentDef) : undefined; + if (parent !== undefined && parentReason !== undefined) { + out.push({ + severity: 'error', + rule: TRANSFER_CASCADE_PARENT_WITHOUT_CHANGE_OWNER, + where, + path, + message: + `${declared} to '${parent}', but '${parent}' does not offer Change Owner: ${parentReason}. ` + + 'A cascade runs only inside a Change Owner of the parent, so it never runs.', + hint: + `Set transferBehavior to 'none' or remove it; or, if '${parent}' should offer Change Owner, ` + + 'change it as the reason says.', + }); + } + + const childDef = served.get(site.child); + if (childDef === undefined) continue; + + if (site.viaExtension) { + const childReason = transferCascadeIneligibilityReason(childDef); + if (childReason !== undefined) { + out.push({ + severity: 'error', + rule: TRANSFER_CASCADE_EXTENSION_CHILD_INELIGIBLE, + where, + path, + message: + `${declared} through an object extension, but '${site.child}' cannot take a Change Owner ` + + `cascade: ${childReason}. A cascade moves this object's records by the Change Owner action, so ` + + 'it acts only on an object that offers that action itself.', + hint: "Set transferBehavior to 'none' or remove it from the extension's field.", + }); + } + } + + const denial = apiExposureDenialReason( + isRec(childDef.enable) ? (childDef.enable as EnableLike) : undefined, + 'update', + ); + if (denial !== null) { + const exposure = denial === 'api-disabled' + ? 'its enable.apiEnabled is false' + : 'its enable.apiMethods does not include update'; + out.push({ + severity: 'error', + rule: TRANSFER_CASCADE_CHILD_UPDATE_UNEXPOSED, + where, + path, + message: + `${declared}, but '${site.child}' does not serve update through the data API: ${exposure}. ` + + "A cascade moves this object's records as updates through the data API, so Change Owner never " + + 'offers it.', + hint: denial === 'api-disabled' + ? `Set transferBehavior to 'none' or remove it; or turn enable.apiEnabled on for '${site.child}'.` + : `Set transferBehavior to 'none' or remove it; or add 'update' to enable.apiMethods of '${site.child}'.`, + }); + } + } + return out; +} diff --git a/packages/spec/src/migrations/entries/semantic/18.transfer-cascade-never-offered-refused.ts b/packages/spec/src/migrations/entries/semantic/18.transfer-cascade-never-offered-refused.ts new file mode 100644 index 00000000000..020d0fdfc0c --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.transfer-cascade-never-offered-refused.ts @@ -0,0 +1,44 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// [ruling 7000907189 point 4 · ADR-0049] A `transferBehavior: 'cascade'` the +// Change Owner action can never offer is refused at error by three +// @objectstack/lint rules (`validate-transfer-cascades.ts`): a parent that does +// not offer Change Owner, an object extension's field on an object that cannot +// take a cascade, a child whose declared exposure does not serve update. It +// narrows what `os validate` / `os build` / `os lint` accept; no key is removed, +// so there is no tombstone. Measured first-party exposure at this change: zero +// — no example app, platform object, skill or docs sample declares a cascade. +// Not converted: whether to drop the cascade or change the object is a judgement. +export const entry: SemanticMigration = { + id: 'transfer-cascade-never-offered-refused', + surface: + 'objects[].fields[].transferBehavior and objectExtensions[].fields[].transferBehavior set to cascade, on a ' + + 'lookup or master_detail field, loaded by os validate / os build / os lint, where the referenced parent is an ' + + 'object of the stack that does not offer Change Owner (ownership business_unit, org or none, any managedBy, ' + + 'systemFields false, an owner_id declared readonly, an external object with no provable owner, or ' + + 'userActions.transfer off, by the author or by the controlled_by_parent default); or where the field is added ' + + 'by an object extension to an object that cannot take a Change Owner cascade; or where the object holding the ' + + 'field declares an enable block that does not serve update (apiEnabled false, or apiMethods without update).', + replacement: + 'Set the field\'s transferBehavior to none or remove it; or change the object the finding names: make the ' + + 'parent offer Change Owner (the reason clause says how, where it can), make the extended object offer it, or ' + + 'add update to the child\'s enable.apiMethods (or turn enable.apiEnabled on). Refused at error as ' + + '`transfer-cascade-parent-without-change-owner`, `transfer-cascade-extension-child-ineligible` and ' + + '`transfer-cascade-child-update-unexposed`.', + reason: + 'The Change Owner endpoint re-judges every relationship on every call and offers only the ones that can act: ' + + 'it refuses the whole call on a parent that does not offer the action, and leaves out a child that cannot take ' + + 'a cascade or whose exposure does not serve update. So each such declaration parsed, deployed and never ran, ' + + 'and nothing told the author. The verdicts come from the spec predicates the endpoint reads ' + + '(resolveUserActionTransfer, transferCascadeIneligibilityReason, apiExposureDenialReason), so no stored row ' + + 'changes shape and nothing the runtime did changes. ObjectSchema already refused a cascade on a field the ' + + 'object declares itself when the object cannot take one; an extension\'s field skipped that parse. No ' + + 'first-party stack declares a cascade today. There is no mechanical rewrite: dropping the cascade and ' + + 'changing the object are different intents.', + acceptanceCriteria: + 'Load every stack (`os validate` or `os build`): no `transfer-cascade-parent-without-change-owner`, ' + + '`transfer-cascade-extension-child-ineligible` or `transfer-cascade-child-update-unexposed` finding. For a ' + + 'cascade kept, GET /api/v1/data/PARENT/change-owner/cascades lists the relationship.', +};