diff --git a/.changeset/35401-user-actions-transfer.md b/.changeset/35401-user-actions-transfer.md new file mode 100644 index 00000000000..b4295cae56b --- /dev/null +++ b/.changeset/35401-user-actions-transfer.md @@ -0,0 +1,27 @@ +--- +'@objectstack/spec': minor +'@objectstack/platform-objects': minor +'@objectstack/metadata-core': minor +--- + +feat(spec): `userActions.transfer`, the per-object switch for the Change Owner action, and its structural eligibility + +Clause-②: yes (widening) +Metadata-protocol: added + +An object can now say whether it offers the Change Owner action. The action is not meant for every record that happens to carry an `owner_id`: line items, invoices and other details get one injected too, and an admin holding `modifyAllRecords` would otherwise see the action everywhere. + +- **Structural eligibility (derived, never overridable).** `isTransferEligible(def)` from `@objectstack/spec/data` answers true only when the platform injects the object's reassignable `owner_id` (`resolveInjectedSystemColumns(def).owner`), an owner is provable for it, and the object does not declare that field `readonly: true` (in either `fields` shape, record or array). So `ownership: 'business_unit' | 'org' | 'none'`, every `managedBy` object, every `sys_*` object and `systemFields: false` never offer the action, and neither does an `external` object whose owner is unprovable (`isOwnerAnchorUnprovable`: it neither declares `owner_id` nor maps a remote column onto it in `external.columnMap`). `transferIneligibilityReason(def)` names the structural fact when the answer is no, and, where the object can be made eligible, the change that does it (drop `readonly` from `owner_id`, set `ownership` to `user`, declare or map the external owner). +- **The switch.** `userActions.transfer` takes the same shape as the CRUD entries beside it: a boolean, or `{ enabled, visibleWhen, disabledWhen }` whose CEL predicates read the record the action acts on. Omitted, it is on for `sharingModel` `private`, `public_read` and `public_read_write`, and for an object that declares no `sharingModel` (a custom object then resolves to `private`); it is off for a `controlled_by_parent` detail. Authors override both ways: `transfer: true` on a detail with a real owner, `transfer: false` where the owner is the actor by rule. +- **The one resolution.** `resolveUserActionTransfer(def)` returns `{ enabled, predicates? }`: structural eligibility first, then the switch, then the `sharingModel` default. It is the answer the Change Owner endpoint and the console action will read once they ship, each still asking the caller's own transfer verdict per record; neither exists in this release. +- **Refused at parse.** `transfer: true` or `{ enabled: true }` on an object that is not eligible is refused at `userActions.transfer`, with the structural reason and its remedy in the message. Closing the switch there (`false`) is accepted. `changeOwner` and `reassign` under `userActions` are refused with a pointer to `transfer`. + +The switch gates the dedicated action, not the raw write: a plain `owner_id` update stays governed by `allowTransfer` alone, so import mappings and hooks are unaffected. To block every change of owner, declare `owner_id` `readonly`. + +The Studio object form gains a Change Owner row under User Actions, with its label and help text translated in every shipped locale. + +The served object document classifies `userActions.transfer` beside the four CRUD entries: for a caller who cannot read a field, a `transfer` predicate that names it is removed and the switch with its other predicate stays, as for `edit` and `delete`, instead of the whole entry being dropped. + +Nothing reads the switch at runtime yet. The Change Owner endpoint and the console action come in follow-up changes, so the liveness ledger grades `userActions.transfer` `planned` and `os lint` / `os validate` warn an author who sets it to `true` or uses the object form that nothing honours it yet. The key is new, so no stored object carries it and nothing needs migrating. + +**Existing objects that set `userActions.exportCsv: true` get a new warning.** Drilling `userActions` showed that no export menu reads `exportCsv`: setting it to `false` does not hide CSV export, which follows the view's `exportOptions` and the object's effective API operations. The ledger now grades it `dead`, so `exportCsv: true` raises a `liveness-dead-property` warning at `os lint` / `os validate`, and the hint says to remove it (`exportCsv: false` is not flagged). It is a warning, not a refusal: every stored object still loads. A follow-up (#35619) either makes the export menus honour the key or removes it. diff --git a/content/docs/references/api/metadata.mdx b/content/docs/references/api/metadata.mdx index 32a1efab39f..63baeb2d962 100644 --- a/content/docs/references/api/metadata.mdx +++ b/content/docs/references/api/metadata.mdx @@ -941,7 +941,7 @@ Metadata query with filtering, sorting, and pagination | **isSystem** | `boolean` | optional (default: `false`) | Is system object (protected from deletion; defaults its org-wide sharing to public when no sharingModel is set — plugin-sharing) | | **managedBy** | `Enum<'platform' \| 'config' \| 'system-data' \| 'engine-owned' \| 'append-only' \| …>` | optional | Lifecycle bucket — platform (user CRUD) \| config (admin authored) \| system-data (platform-defined schema, admin/user-writable data) \| engine-owned (engine owns the lifecycle, no user writes) \| append-only (audit) \| synced (rows copied by a pull from a connector or federated source; read-only to members, and userActions cannot open a write) \| better-auth (identity). UI clients honour the resolved affordance matrix. | | **ownership** | `Enum<'user' \| 'business_unit' \| 'org' \| 'none'>` | optional | Record-ownership model: user (default — injects reassignable owner_id plus owning_business_unit_id) \| business_unit (unit-owned: owning_business_unit_id only, no owner_id) \| org \| none (no per-record owner, neither anchor). Distinct from the package own/extend contribution kind. | -| **userActions** | `{ create?: boolean \| object; import?: boolean \| object; edit?: boolean \| object; delete?: boolean \| object; … }` | optional | Per-object override of the resolved CRUD affordance matrix. | +| **userActions** | `{ create?: boolean \| object; import?: boolean \| object; edit?: boolean \| object; delete?: boolean \| object; … }` | optional | Per-object override of the resolved CRUD affordance matrix, plus the Change Owner switch (transfer). | | **systemFields** | `false \| { tenant?: boolean; audit?: boolean }` | optional | Opt out of, or selectively disable, registry-level system-field auto-injection. | | **datasource** | `string` | optional (default: `"default"`) | Target Datasource ID. "default" is the primary DB. | | **external** | `{ remoteName?: string; remoteSchema?: string; writable?: boolean; columnMap?: Record; … }` | optional | Remote table binding for federated (external) objects. | diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 42cd92f8f70..1e9438350fe 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -153,7 +153,7 @@ const result = ApiMethod.parse(data); | **isSystem** | `boolean` | optional (default: `false`) | Is system object (protected from deletion; defaults its org-wide sharing to public when no sharingModel is set — plugin-sharing) | | **managedBy** | `Enum<'platform' \| 'config' \| 'system-data' \| 'engine-owned' \| 'append-only' \| 'synced' \| 'better-auth'>` | optional | Lifecycle bucket — platform (user CRUD) \| config (admin authored) \| system-data (platform-defined schema, admin/user-writable data) \| engine-owned (engine owns the lifecycle, no user writes) \| append-only (audit) \| synced (rows copied by a pull from a connector or federated source; read-only to members, and userActions cannot open a write) \| better-auth (identity). UI clients honour the resolved affordance matrix. | | **ownership** | `Enum<'user' \| 'business_unit' \| 'org' \| 'none'>` | optional | Record-ownership model: user (default — injects reassignable owner_id plus owning_business_unit_id) \| business_unit (unit-owned: owning_business_unit_id only, no owner_id) \| org \| none (no per-record owner, neither anchor). Distinct from the package own/extend contribution kind. | -| **userActions** | `{ create?: boolean \| object; import?: boolean \| object; edit?: boolean \| object; delete?: boolean \| object; … }` | optional | Per-object override of the resolved CRUD affordance matrix. | +| **userActions** | `{ create?: boolean \| object; import?: boolean \| object; edit?: boolean \| object; delete?: boolean \| object; … }` | optional | Per-object override of the resolved CRUD affordance matrix, plus the Change Owner switch (transfer). | | **systemFields** | `false \| { tenant?: boolean; audit?: boolean }` | optional | Opt out of, or selectively disable, registry-level system-field auto-injection. | | **datasource** | `string` | optional (default: `"default"`) | Target Datasource ID. "default" is the primary DB. | | **external** | `{ remoteName?: string; remoteSchema?: string; writable?: boolean; columnMap?: Record; … }` | optional | Remote table binding for federated (external) objects. | @@ -205,6 +205,7 @@ const result = ApiMethod.parse(data); | **edit** | `boolean \| { enabled?: boolean; visibleWhen?: string \| object; disabledWhen?: string \| object }` | optional | Allow inline / form edit of existing rows. Boolean, or an object adding per-record visibleWhen/disabledWhen CEL predicates. | | **delete** | `boolean \| { enabled?: boolean; visibleWhen?: string \| object; disabledWhen?: string \| object }` | optional | Show row-level delete + bulk delete. Boolean, or an object adding per-record visibleWhen/disabledWhen CEL predicates. | | **exportCsv** | `boolean` | optional | Show CSV export entry. | +| **transfer** | `boolean \| { enabled?: boolean; visibleWhen?: string \| object; disabledWhen?: string \| object }` | optional | Offer the Change Owner action (single and bulk) on records of this object. Boolean, or an object adding per-record visibleWhen/disabledWhen CEL predicates. Omitted: on, except off on a controlled_by_parent detail. Offered only where the platform injects a reassignable owner_id that is provable and not declared readonly (ownership user or omitted, no managedBy, not a sys_ object; an external object declares owner_id or maps a remote column onto it); enabled: true elsewhere is refused. Gates the action, not a plain owner_id write. Resolved by resolveUserActionTransfer. | ### Nested Shape: `Object.systemFields` diff --git a/content/docs/references/system/migration.mdx b/content/docs/references/system/migration.mdx index c05dee8df8b..e6522bfc305 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -332,7 +332,7 @@ Create a new object | **isSystem** | `boolean` | optional (default: `false`) | Is system object (protected from deletion; defaults its org-wide sharing to public when no sharingModel is set — plugin-sharing) | | **managedBy** | `Enum<'platform' \| 'config' \| 'system-data' \| 'engine-owned' \| 'append-only' \| …>` | optional | Lifecycle bucket — platform (user CRUD) \| config (admin authored) \| system-data (platform-defined schema, admin/user-writable data) \| engine-owned (engine owns the lifecycle, no user writes) \| append-only (audit) \| synced (rows copied by a pull from a connector or federated source; read-only to members, and userActions cannot open a write) \| better-auth (identity). UI clients honour the resolved affordance matrix. | | **ownership** | `Enum<'user' \| 'business_unit' \| 'org' \| 'none'>` | optional | Record-ownership model: user (default — injects reassignable owner_id plus owning_business_unit_id) \| business_unit (unit-owned: owning_business_unit_id only, no owner_id) \| org \| none (no per-record owner, neither anchor). Distinct from the package own/extend contribution kind. | -| **userActions** | `{ create?: boolean \| object; import?: boolean \| object; edit?: boolean \| object; delete?: boolean \| object; … }` | optional | Per-object override of the resolved CRUD affordance matrix. | +| **userActions** | `{ create?: boolean \| object; import?: boolean \| object; edit?: boolean \| object; delete?: boolean \| object; … }` | optional | Per-object override of the resolved CRUD affordance matrix, plus the Change Owner switch (transfer). | | **systemFields** | `false \| { tenant?: boolean; audit?: boolean }` | optional | Opt out of, or selectively disable, registry-level system-field auto-injection. | | **datasource** | `string` | optional (default: `"default"`) | Target Datasource ID. "default" is the primary DB. | | **external** | `{ remoteName?: string; remoteSchema?: string; writable?: boolean; columnMap?: Record; … }` | optional | Remote table binding for federated (external) objects. | @@ -633,7 +633,7 @@ Create a new object | **isSystem** | `boolean` | optional (default: `false`) | Is system object (protected from deletion; defaults its org-wide sharing to public when no sharingModel is set — plugin-sharing) | | **managedBy** | `Enum<'platform' \| 'config' \| 'system-data' \| 'engine-owned' \| 'append-only' \| …>` | optional | Lifecycle bucket — platform (user CRUD) \| config (admin authored) \| system-data (platform-defined schema, admin/user-writable data) \| engine-owned (engine owns the lifecycle, no user writes) \| append-only (audit) \| synced (rows copied by a pull from a connector or federated source; read-only to members, and userActions cannot open a write) \| better-auth (identity). UI clients honour the resolved affordance matrix. | | **ownership** | `Enum<'user' \| 'business_unit' \| 'org' \| 'none'>` | optional | Record-ownership model: user (default — injects reassignable owner_id plus owning_business_unit_id) \| business_unit (unit-owned: owning_business_unit_id only, no owner_id) \| org \| none (no per-record owner, neither anchor). Distinct from the package own/extend contribution kind. | -| **userActions** | `{ create?: boolean \| object; import?: boolean \| object; edit?: boolean \| object; delete?: boolean \| object; … }` | optional | Per-object override of the resolved CRUD affordance matrix. | +| **userActions** | `{ create?: boolean \| object; import?: boolean \| object; edit?: boolean \| object; delete?: boolean \| object; … }` | optional | Per-object override of the resolved CRUD affordance matrix, plus the Change Owner switch (transfer). | | **systemFields** | `false \| { tenant?: boolean; audit?: boolean }` | optional | Opt out of, or selectively disable, registry-level system-field auto-injection. | | **datasource** | `string` | optional (default: `"default"`) | Target Datasource ID. "default" is the primary DB. | | **external** | `{ remoteName?: string; remoteSchema?: string; writable?: boolean; columnMap?: Record; … }` | optional | Remote table binding for federated (external) objects. | diff --git a/packages/metadata-core/src/object-schema-fls-references.test.ts b/packages/metadata-core/src/object-schema-fls-references.test.ts index 14e9ee4c6d4..958f03610ec 100644 --- a/packages/metadata-core/src/object-schema-fls-references.test.ts +++ b/packages/metadata-core/src/object-schema-fls-references.test.ts @@ -173,13 +173,24 @@ describe('[ADR-0106 D1] references to a denied field — object level', () => { lifecycle: { class: 'record', ttl: { field: 'secret_score', expireAfter: '30d' } }, publicSharing: { enabled: true, redactFields: ['secret_score', 'title'], eligibility: 'record.secret_score > 0' }, external: { remoteName: 't', columnMap: { SCORE: 'secret_score', TITLE: 'title' } }, - userActions: { edit: { enabled: true, disabledWhen: 'record.secret_score > 5' }, delete: false }, + userActions: { + edit: { enabled: true, disabledWhen: 'record.secret_score > 5' }, + delete: false, + transfer: { enabled: true, visibleWhen: 'record.secret_score > 0', disabledWhen: 'record.title == ""' }, + }, }); expect(served.tenancy).toEqual({ enabled: true }); expect(served.lifecycle).toEqual({ class: 'record' }); expect(served.publicSharing).toEqual({ enabled: true, redactFields: ['title'] }); expect(served.external).toEqual({ remoteName: 't', columnMap: { TITLE: 'title' } }); - expect(served.userActions).toEqual({ edit: { enabled: true }, delete: false }); + // `transfer` is a CRUD flag like `edit`: the predicate reading the denied + // field goes, the switch and the readable predicate stay (the unclassified + // fail-safe would drop the whole entry instead). + expect(served.userActions).toEqual({ + edit: { enabled: true }, + delete: false, + transfer: { enabled: true, disabledWhen: 'record.title == ""' }, + }); }); it('filters a list view\'s columns, and drops a view whose filter reads the denied field', () => { diff --git a/packages/metadata-core/src/object-schema-fls-references.ts b/packages/metadata-core/src/object-schema-fls-references.ts index 6693ad2a932..f46434c7d2a 100644 --- a/packages/metadata-core/src/object-schema-fls-references.ts +++ b/packages/metadata-core/src/object-schema-fls-references.ts @@ -802,7 +802,9 @@ export const OBJECT_REFERENCE_POSITIONS: Readonly> = { // when it mentions a denied field: server policy the caller cannot evaluate. membershipKeys: recordOf(ruleEntry), // Blocks. - userActions: block({ create: crudFlag, import: crudFlag, edit: crudFlag, delete: crudFlag, exportCsv: keep }), + // `transfer` (the Change Owner switch) is the same boolean-or-predicates union + // as the four CRUD flags, so it takes their disposition. + userActions: block({ create: crudFlag, import: crudFlag, edit: crudFlag, delete: crudFlag, exportCsv: keep, transfer: crudFlag }), external: block({ remoteName: keep, remoteSchema: keep, writable: keep, introspectedAt: keep, ignoreColumns: keep, columnMap, diff --git a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index 16f18cf9f14..80a4be47550 100644 --- a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts @@ -427,7 +427,7 @@ export const arMetadataForms: NonNullable = { }, userActions: { label: "إجراءات المستخدم", - helpText: "الإدخالات العامة (جديد، استيراد، تحرير، حذف، تصدير) التي تعرضها عملاء الواجهة على سجلات هذا الكائن، متجاوزةً الإعداد الافتراضي لـ managedBy إدخالًا بإدخال. الإدخال غير المعيَّن يُبقي ذلك الإعداد الافتراضي: platform يعرض الخمسة كلها؛ والقيمتان config، system-data تعرضانها كلها عدا الاستيراد؛ والقيم engine-owned، append-only، better-auth تعرض التصدير فقط. المفتاح الذي لم يُلمس لا يكتب شيئًا، لذا يظهر متوقفًا حتى حيث يعرض الإعداد الافتراضي الإدخال. في كائن engine-owned أو append-only، يتيح تشغيل إدخال للمستخدمين أيضًا إجراء تلك الكتابة عبر واجهة البيانات. ولا يزال المستخدمون بحاجة إلى الإذن المطابق." + helpText: "الإدخالات العامة (جديد، استيراد، تحرير، حذف، تصدير) التي تعرضها عملاء الواجهة على سجلات هذا الكائن، متجاوزةً الإعداد الافتراضي لـ managedBy إدخالًا بإدخال. الإدخال غير المعيَّن يُبقي ذلك الإعداد الافتراضي: platform يعرض الخمسة كلها؛ والقيمتان config، system-data تعرضانها كلها عدا الاستيراد؛ والقيم engine-owned، append-only، better-auth تعرض التصدير فقط. المفتاح الذي لم يُلمس لا يكتب شيئًا، لذا يظهر متوقفًا حتى حيث يعرض الإعداد الافتراضي الإدخال. في كائن engine-owned أو append-only، يتيح تشغيل إدخال للمستخدمين أيضًا إجراء تلك الكتابة عبر واجهة البيانات. ولا يزال المستخدمون بحاجة إلى الإذن المطابق. تغيير المالك ليس جزءًا من هذه المصفوفة: إعداده الافتراضي يتبع نموذج المشاركة (انظر إدخاله)." }, "userActions.create": { label: "إنشاء", @@ -449,6 +449,10 @@ export const arMetadataForms: NonNullable = { label: "تصدير CSV", helpText: "إدخال التصدير إلى CSV. عند عدم التعيين: يظهر، لأن كل فئات managedBy تتيح التصدير." }, + "userActions.transfer": { + label: "تغيير المالك", + helpText: "إجراء تغيير المالك، فرديًا وجماعيًا: التشغيل يعرضه والإيقاف يخفيه. غير مُعيَّن: مُشغَّل، إلا أنه مُوقَف على كائن تفاصيل controlled_by_parent. يُعرض فقط على كائن لسجلاته مالك قابل لإعادة التعيين (ownership بقيمة user أو غير مُعيَّن، بلا managedBy، ليس كائن sys_، وowner_id ليس للقراءة فقط، وعلى كائن خارجي يكون owner_id مُعرَّفًا أو مربوطًا)؛ وتشغيله على أي كائن آخر مرفوض. يتحكم في الإجراء فقط، لا في التعديل العادي لـ owner_id. يُحرَّر كائن {enabled, visibleWhen, disabledWhen} المخزَّن مفتاحًا تلو الآخر؛ اكتب واحدًا في المصدر لتقييد الإجراء بكل سجل." + }, editMode: { label: "وضع التحرير", helpText: "نية تفاعل التحرير لسجلات هذا الكائن. عند الغياب، يختار العارض إعداده الافتراضي. نية عابرة للعارضات، وليست تنسيقًا." diff --git a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index 720eb0354bf..018b6e38ab8 100644 --- a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts @@ -427,7 +427,7 @@ export const deMetadataForms: NonNullable = { }, userActions: { label: "Benutzeraktionen", - helpText: "Welche allgemeinen Einträge (Neu, Importieren, Bearbeiten, Löschen, Exportieren) Oberflächen-Clients für die Datensätze dieses Objekts anbieten; überschreibt den Standard von managedBy Eintrag für Eintrag. Ein nicht gesetzter Eintrag behält diesen Standard: platform bietet alle fünf an; config und system-data alle außer Importieren; engine-owned, append-only und better-auth nur Exportieren. Ein unberührter Schalter schreibt nichts und wird daher als aus angezeigt, auch wo der Standard den Eintrag anbietet. Bei einem Objekt vom Typ engine-owned oder append-only erlaubt das Einschalten eines Eintrags Benutzern auch diesen Schreibvorgang über die Daten-API. Benutzer benötigen weiterhin die passende Berechtigung." + helpText: "Welche allgemeinen Einträge (Neu, Importieren, Bearbeiten, Löschen, Exportieren) Oberflächen-Clients für die Datensätze dieses Objekts anbieten; überschreibt den Standard von managedBy Eintrag für Eintrag. Ein nicht gesetzter Eintrag behält diesen Standard: platform bietet alle fünf an; config und system-data alle außer Importieren; engine-owned, append-only und better-auth nur Exportieren. Ein unberührter Schalter schreibt nichts und wird daher als aus angezeigt, auch wo der Standard den Eintrag anbietet. Bei einem Objekt vom Typ engine-owned oder append-only erlaubt das Einschalten eines Eintrags Benutzern auch diesen Schreibvorgang über die Daten-API. Benutzer benötigen weiterhin die passende Berechtigung. „Inhaber ändern“ gehört nicht zu dieser Matrix: sein Standard folgt dem Freigabemodell (siehe seinen Eintrag)." }, "userActions.create": { label: "Anlegen", @@ -449,6 +449,10 @@ export const deMetadataForms: NonNullable = { label: "CSV exportieren", helpText: "Der Eintrag für den CSV-Export. Nicht gesetzt: angezeigt, da jede managedBy-Gruppe den Export anbietet." }, + "userActions.transfer": { + label: "Inhaber ändern", + helpText: "Die Aktion „Inhaber ändern“, einzeln und als Massenaktion: ein bietet sie an, aus blendet sie aus. Nicht gesetzt: ein, außer aus auf einem controlled_by_parent-Detailobjekt. Nur auf einem Objekt angeboten, dessen Datensätze einen neu zuweisbaren Inhaber haben (ownership user oder nicht gesetzt, kein managedBy, kein sys_-Objekt, owner_id nicht schreibgeschützt und auf einem externen Objekt deklariert oder zugeordnet); das Einschalten auf jedem anderen Objekt wird abgelehnt. Es steuert nur die Aktion, nicht eine einfache Bearbeitung von owner_id. Ein gespeichertes Objekt {enabled, visibleWhen, disabledWhen} wird Schlüssel für Schlüssel bearbeitet; schreiben Sie eines im Quelltext, um die Aktion von jedem Datensatz abhängig zu machen." + }, editMode: { label: "Bearbeitungsmodus", helpText: "Absicht der Bearbeitungsinteraktion für Datensätze dieses Objekts. Fehlt sie, wählt der Renderer seinen eigenen Standard. Rendererübergreifende Absicht, keine Gestaltung." diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index d34ba687bf3..1e70401ec93 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -427,7 +427,7 @@ export const enMetadataForms: NonNullable = { }, userActions: { label: "User Actions", - helpText: "Which generic entries (New, Import, Edit, Delete, Export) UI clients offer on this object's records, overriding the managedBy default one entry at a time. An unset entry keeps that default: platform offers all five; config and system-data all but Import; engine-owned, append-only and better-auth only Export. An untouched switch writes nothing, so it reads off even where the default offers the entry. On an engine-owned or append-only object, turning an entry on also lets users make that write through the data API. Users still need the matching permission." + helpText: "Which generic entries (New, Import, Edit, Delete, Export) UI clients offer on this object's records, overriding the managedBy default one entry at a time. An unset entry keeps that default: platform offers all five; config and system-data all but Import; engine-owned, append-only and better-auth only Export. An untouched switch writes nothing, so it reads off even where the default offers the entry. On an engine-owned or append-only object, turning an entry on also lets users make that write through the data API. Users still need the matching permission. Change Owner is not part of that matrix: its default follows the sharing model (see its entry)." }, "userActions.create": { label: "Create", @@ -449,6 +449,10 @@ export const enMetadataForms: NonNullable = { label: "Export CSV", helpText: "The CSV export entry. Unset: shown, since every managedBy bucket offers export." }, + "userActions.transfer": { + label: "Change Owner", + helpText: "The Change Owner action, single and bulk: on offers it, off hides it. Unset: on, except off on a controlled_by_parent detail. Offered only on an object whose records have a reassignable owner (ownership user or unset, no managedBy, not a sys_ object, owner_id not readonly and, on an external object, declared or mapped); turning it on anywhere else is refused. It gates the action only, not a plain edit of owner_id. A stored {enabled, visibleWhen, disabledWhen} object is edited key by key; write one in source to gate the action on each record." + }, editMode: { label: "Edit Mode", helpText: "Edit-interaction intent for records of this object. Absent, the renderer picks its own default. Cross-renderer intent, not styling." diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index 0666f3ea388..5207cbe7c62 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -427,7 +427,7 @@ export const esESMetadataForms: NonNullable = }, userActions: { label: "Acciones de usuario", - helpText: "Qué entradas genéricas (Nuevo, Importar, Editar, Eliminar, Exportar) ofrecen los clientes de UI en los registros de este objeto, sustituyendo el valor predeterminado de managedBy entrada por entrada. Una entrada sin definir mantiene ese valor predeterminado: platform ofrece las cinco; config y system-data todas salvo Importar; engine-owned, append-only y better-auth solo Exportar. Un interruptor que no se ha tocado no escribe nada, así que aparece desactivado aunque el valor predeterminado ofrezca la entrada. En un objeto engine-owned o append-only, activar una entrada también permite a los usuarios hacer esa escritura a través de la API de datos. Los usuarios siguen necesitando el permiso correspondiente." + helpText: "Qué entradas genéricas (Nuevo, Importar, Editar, Eliminar, Exportar) ofrecen los clientes de UI en los registros de este objeto, sustituyendo el valor predeterminado de managedBy entrada por entrada. Una entrada sin definir mantiene ese valor predeterminado: platform ofrece las cinco; config y system-data todas salvo Importar; engine-owned, append-only y better-auth solo Exportar. Un interruptor que no se ha tocado no escribe nada, así que aparece desactivado aunque el valor predeterminado ofrezca la entrada. En un objeto engine-owned o append-only, activar una entrada también permite a los usuarios hacer esa escritura a través de la API de datos. Los usuarios siguen necesitando el permiso correspondiente. Cambiar propietario no forma parte de esa matriz: su valor predeterminado sigue el modelo de uso compartido (vea su entrada)." }, "userActions.create": { label: "Crear", @@ -449,6 +449,10 @@ export const esESMetadataForms: NonNullable = label: "Exportar CSV", helpText: "La entrada de exportación CSV. Sin definir: se muestra, porque todas las categorías de managedBy ofrecen la exportación." }, + "userActions.transfer": { + label: "Cambiar propietario", + helpText: "La acción Cambiar propietario, individual y masiva: activada la ofrece, desactivada la oculta. Sin definir: activada, salvo desactivada en un objeto de detalle controlled_by_parent. Solo se ofrece en un objeto cuyos registros tienen un propietario reasignable (ownership user o sin definir, sin managedBy, no es un objeto sys_, owner_id no es de solo lectura y, en un objeto externo, está declarado o mapeado); activarla en cualquier otro objeto se rechaza. Solo controla la acción, no una edición directa de owner_id. Un objeto {enabled, visibleWhen, disabledWhen} almacenado se edita clave por clave; escriba uno en el código fuente para condicionar la acción a cada registro." + }, editMode: { label: "Modo de edición", helpText: "Intención de interacción al editar registros de este objeto. Si se omite, el renderizador elige su propio valor predeterminado. Es una intención entre renderizadores, no un estilo." diff --git a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts index 2e47bd7c82d..f878de5e1b6 100644 --- a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts @@ -427,7 +427,7 @@ export const frMetadataForms: NonNullable = { }, userActions: { label: "Actions utilisateur", - helpText: "Les entrées génériques (Nouveau, Importer, Modifier, Supprimer, Exporter) que les clients d’interface proposent sur les enregistrements de cet objet, en remplaçant la valeur par défaut de managedBy entrée par entrée. Une entrée non définie conserve cette valeur par défaut : platform propose les cinq ; config et system-data toutes sauf Importer ; engine-owned, append-only et better-auth uniquement Exporter. Un interrupteur non modifié n’écrit rien : il apparaît donc désactivé même là où la valeur par défaut propose l’entrée. Sur un objet engine-owned ou append-only, activer une entrée permet aussi aux utilisateurs d’effectuer cette écriture via l’API de données. Les utilisateurs ont toujours besoin de l’autorisation correspondante." + helpText: "Les entrées génériques (Nouveau, Importer, Modifier, Supprimer, Exporter) que les clients d’interface proposent sur les enregistrements de cet objet, en remplaçant la valeur par défaut de managedBy entrée par entrée. Une entrée non définie conserve cette valeur par défaut : platform propose les cinq ; config et system-data toutes sauf Importer ; engine-owned, append-only et better-auth uniquement Exporter. Un interrupteur non modifié n’écrit rien : il apparaît donc désactivé même là où la valeur par défaut propose l’entrée. Sur un objet engine-owned ou append-only, activer une entrée permet aussi aux utilisateurs d’effectuer cette écriture via l’API de données. Les utilisateurs ont toujours besoin de l’autorisation correspondante. Changer de propriétaire ne fait pas partie de cette matrice : sa valeur par défaut suit le modèle de partage (voir son entrée)." }, "userActions.create": { label: "Créer", @@ -449,6 +449,10 @@ export const frMetadataForms: NonNullable = { label: "Exporter en CSV", helpText: "L’entrée d’export CSV. Non défini : affichée, puisque chaque catégorie managedBy propose l’export." }, + "userActions.transfer": { + label: "Changer de propriétaire", + helpText: "L’action Changer de propriétaire, unitaire et en masse : activée, elle est proposée ; désactivée, elle est masquée. Non défini : activée, sauf désactivée sur un objet de détail controlled_by_parent. Proposée uniquement sur un objet dont les enregistrements ont un propriétaire réattribuable (ownership user ou non défini, sans managedBy, pas un objet sys_, owner_id non en lecture seule et, sur un objet externe, déclaré ou mappé) ; l’activer sur tout autre objet est refusé. Elle ne contrôle que l’action, pas une simple modification de owner_id. Un objet {enabled, visibleWhen, disabledWhen} enregistré se modifie clé par clé ; écrivez-en un dans le source pour conditionner l’action à chaque enregistrement." + }, editMode: { label: "Mode de modification", helpText: "Intention d’interaction de modification pour les enregistrements de cet objet. En l’absence de valeur, le moteur de rendu choisit sa propre valeur par défaut. Intention commune à tous les moteurs de rendu, et non un style." diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index 63371ee0c03..199daa412d8 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -427,7 +427,7 @@ export const jaJPMetadataForms: NonNullable = }, userActions: { label: "ユーザー操作", - helpText: "UI クライアントがこのオブジェクトのレコードで提供する汎用の入口(新規、インポート、編集、削除、エクスポート)を、managedBy の既定から 1 項目ずつ上書きします。未設定の項目は既定のままで、platform は 5 つすべて、config と system-data はインポート以外すべて、engine-owned、append-only、better-auth はエクスポートのみを提供します。一度も操作していないスイッチは何も書き込まないため、既定で提供される項目でもオフと表示されます。engine-owned または append-only のオブジェクトでは、項目をオンにすると、ユーザーはその書き込みをデータ API 経由でも行えるようになります。ユーザーには引き続き対応する権限が必要です。" + helpText: "UI クライアントがこのオブジェクトのレコードで提供する汎用の入口(新規、インポート、編集、削除、エクスポート)を、managedBy の既定から 1 項目ずつ上書きします。未設定の項目は既定のままで、platform は 5 つすべて、config と system-data はインポート以外すべて、engine-owned、append-only、better-auth はエクスポートのみを提供します。一度も操作していないスイッチは何も書き込まないため、既定で提供される項目でもオフと表示されます。engine-owned または append-only のオブジェクトでは、項目をオンにすると、ユーザーはその書き込みをデータ API 経由でも行えるようになります。ユーザーには引き続き対応する権限が必要です。所有者の変更はこのマトリクスに含まれません。既定は共有モデルに従います(その項目を参照)。" }, "userActions.create": { label: "作成", @@ -449,6 +449,10 @@ export const jaJPMetadataForms: NonNullable = label: "CSV エクスポート", helpText: "CSV エクスポートの入口。未設定の場合は表示されます。どの managedBy 区分でも既定でエクスポートが提供されるためです。" }, + "userActions.transfer": { + label: "所有者の変更", + helpText: "所有者の変更アクション(単一および一括)。オンで提供、オフで非表示。未設定の場合はオンですが、controlled_by_parent の詳細オブジェクトではオフです。レコードに再割り当て可能な所有者があるオブジェクト(ownership が user または未設定、managedBy なし、sys_ オブジェクトでない、owner_id が読み取り専用でなく、外部オブジェクトでは宣言またはマッピングされている)でのみ提供されます。それ以外のオブジェクトでオンにすると拒否されます。制御するのはアクションのみで、owner_id の通常の編集は対象外です。保存済みの {enabled, visibleWhen, disabledWhen} オブジェクトはキーごとに編集されます。各レコードでアクションを制御するにはソースに記述してください。" + }, editMode: { label: "編集の開き方", helpText: "このオブジェクトのレコードを編集するときの操作意図。未設定ならレンダラー側の既定に従います。スタイルではなく、レンダラー横断の意図表明です。" diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index 119caa20a0b..19ce1e15175 100644 --- a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts @@ -427,7 +427,7 @@ export const koMetadataForms: NonNullable = { }, userActions: { label: "사용자 작업", - helpText: "UI 클라이언트가 이 객체의 레코드에서 제공하는 일반 항목(새로 만들기, 가져오기, 편집, 삭제, 내보내기)으로, managedBy 기본값을 항목별로 재정의합니다. 설정하지 않은 항목은 기본값을 유지합니다. platform은 다섯 가지 모두, config와 system-data는 가져오기를 제외한 모두, engine-owned, append-only, better-auth는 내보내기만 제공합니다. 건드리지 않은 스위치는 아무것도 쓰지 않으므로 기본값이 항목을 제공하는 경우에도 꺼진 것으로 표시됩니다. engine-owned 또는 append-only 객체에서 항목을 켜면 사용자가 데이터 API로도 해당 쓰기를 할 수 있습니다. 사용자에게는 여전히 해당 권한이 필요합니다." + helpText: "UI 클라이언트가 이 객체의 레코드에서 제공하는 일반 항목(새로 만들기, 가져오기, 편집, 삭제, 내보내기)으로, managedBy 기본값을 항목별로 재정의합니다. 설정하지 않은 항목은 기본값을 유지합니다. platform은 다섯 가지 모두, config와 system-data는 가져오기를 제외한 모두, engine-owned, append-only, better-auth는 내보내기만 제공합니다. 건드리지 않은 스위치는 아무것도 쓰지 않으므로 기본값이 항목을 제공하는 경우에도 꺼진 것으로 표시됩니다. engine-owned 또는 append-only 객체에서 항목을 켜면 사용자가 데이터 API로도 해당 쓰기를 할 수 있습니다. 사용자에게는 여전히 해당 권한이 필요합니다. 소유자 변경은 이 매트릭스에 포함되지 않습니다. 기본값은 공유 모델을 따릅니다(해당 항목 참조)." }, "userActions.create": { label: "만들기", @@ -449,6 +449,10 @@ export const koMetadataForms: NonNullable = { label: "CSV 내보내기", helpText: "CSV 내보내기 항목입니다. 설정하지 않으면 표시됩니다. 모든 managedBy 버킷이 내보내기를 제공하기 때문입니다." }, + "userActions.transfer": { + label: "소유자 변경", + helpText: "소유자 변경 작업(단건 및 일괄): 켜면 제공하고 끄면 숨깁니다. 설정하지 않으면 켜짐이며, controlled_by_parent 상세 개체에서는 꺼짐입니다. 레코드에 재할당 가능한 소유자가 있는 개체(ownership이 user이거나 미설정, managedBy 없음, sys_ 개체 아님, owner_id가 읽기 전용 아님, 외부 개체에서는 owner_id가 선언되거나 매핑됨)에서만 제공됩니다. 다른 개체에서 켜면 거부됩니다. 작업만 제어하며 owner_id의 일반 편집에는 영향을 주지 않습니다. 저장된 {enabled, visibleWhen, disabledWhen} 개체는 키별로 편집됩니다. 레코드마다 작업을 제어하려면 소스에 작성하세요." + }, editMode: { label: "편집 모드", helpText: "이 객체 레코드의 편집 상호 작용 의도입니다. 없으면 렌더러가 자체 기본값을 고릅니다. 스타일이 아니라 렌더러 간 공통 의도입니다." diff --git a/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts index ba6f40099d1..d50e714d720 100644 --- a/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts @@ -952,10 +952,14 @@ describe('#19403 round 8 — the population, DERIVED from the form and a shape', // `writeRequiresMasterRead` toggle (ADR-0055 §3 as amended) — a label and // a help text, two leaves, all six translated leaves authored by the same // card. `advanced` reads 102 → 104; `capabilities` is untouched. - expect(PANEL_LEAVES.length).toBe(115); + // 117 since the `userActions` composite offers `transfer`, the Change Owner + // switch (ruling 7000907189 point 1) — a label and a help text, two leaves, + // all translated leaves authored by the same card. `advanced` reads + // 104 → 106; `capabilities` is untouched. + expect(PANEL_LEAVES.length).toBe(117); expect(PANEL_LEAVES.every((l) => l.prop === 'label' || l.prop === 'helpText')).toBe(true); expect(PANEL_LEAVES.filter((l) => l.section === 'capabilities').length).toBe(11); - expect(PANEL_LEAVES.filter((l) => l.section === 'advanced').length).toBe(104); + expect(PANEL_LEAVES.filter((l) => l.section === 'advanced').length).toBe(106); }); it('⭐ DARK, OUTWARD — the open sections are excluded, and `fields.placeholder` is the one that proves it', () => { diff --git a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts index f5cb0f238c8..bc503d7d88f 100644 --- a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts @@ -1289,7 +1289,10 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // 744 since #34575: the hook form offers the `texts` record and its // `message` / `params` entry fields — three row labels, authored in all // three locales. - expect(translated.length, `${locale} positive control`).toBe(744); + // 745 since the object form's `userActions` composite offers `transfer` + // (the Change Owner switch, ruling 7000907189 point 1) — one row label, + // authored in all three locales. + expect(translated.length, `${locale} positive control`).toBe(745); } // ⭐ DARK — the blindness, executable. On a synthetic two-locale catalog the // all-three predicate returns 0 while the per-locale one returns 1, so the diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index dea2e09a05d..09b27377c8d 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts @@ -427,7 +427,7 @@ export const ptBRMetadataForms: NonNullable = }, userActions: { label: "Ações do usuário", - helpText: "Quais entradas genéricas (Novo, Importar, Editar, Excluir, Exportar) os clientes de interface oferecem nos registros deste objeto, substituindo o padrão do managedBy uma entrada por vez. Uma entrada não definida mantém esse padrão: platform oferece as cinco; config e system-data todas menos Importar; engine-owned, append-only e better-auth apenas Exportar. Um interruptor não tocado não grava nada, portanto aparece desativado mesmo onde o padrão oferece a entrada. Em um objeto engine-owned ou append-only, ativar uma entrada também permite que os usuários façam essa gravação pela API de dados. Os usuários ainda precisam da permissão correspondente." + helpText: "Quais entradas genéricas (Novo, Importar, Editar, Excluir, Exportar) os clientes de interface oferecem nos registros deste objeto, substituindo o padrão do managedBy uma entrada por vez. Uma entrada não definida mantém esse padrão: platform oferece as cinco; config e system-data todas menos Importar; engine-owned, append-only e better-auth apenas Exportar. Um interruptor não tocado não grava nada, portanto aparece desativado mesmo onde o padrão oferece a entrada. Em um objeto engine-owned ou append-only, ativar uma entrada também permite que os usuários façam essa gravação pela API de dados. Os usuários ainda precisam da permissão correspondente. Alterar proprietário não faz parte dessa matriz: seu padrão segue o modelo de compartilhamento (veja sua entrada)." }, "userActions.create": { label: "Criar", @@ -449,6 +449,10 @@ export const ptBRMetadataForms: NonNullable = label: "Exportar CSV", helpText: "A entrada de exportação CSV. Não definido: exibida, pois todas as categorias do managedBy oferecem exportação." }, + "userActions.transfer": { + label: "Alterar proprietário", + helpText: "A ação Alterar proprietário, individual e em massa: ativada, é oferecida; desativada, fica oculta. Não definida: ativada, exceto desativada em um objeto de detalhe controlled_by_parent. Oferecida apenas em um objeto cujos registros têm um proprietário reatribuível (ownership user ou não definido, sem managedBy, não é um objeto sys_, owner_id não é somente leitura e, em um objeto externo, está declarado ou mapeado); ativá-la em qualquer outro objeto é recusado. Controla apenas a ação, não uma edição simples de owner_id. Um objeto {enabled, visibleWhen, disabledWhen} armazenado é editado chave por chave; escreva um no código-fonte para condicionar a ação a cada registro." + }, editMode: { label: "Modo de edição", helpText: "Intenção de interação de edição para os registros deste objeto. Ausente, o renderizador escolhe seu próprio padrão. Intenção entre renderizadores, não estilo." diff --git a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index 0397923e065..a58a356d74c 100644 --- a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts @@ -427,7 +427,7 @@ export const ruMetadataForms: NonNullable = { }, userActions: { label: "Действия пользователя", - helpText: "Какие общие пункты (Создать, Импорт, Изменить, Удалить, Экспорт) клиенты интерфейса предлагают для записей этого объекта, переопределяя значение managedBy по умолчанию по одному пункту. Незаданный пункт сохраняет значение по умолчанию: platform предлагает все пять; config и system-data — все, кроме импорта; engine-owned, append-only и better-auth — только экспорт. Нетронутый переключатель ничего не записывает, поэтому выглядит выключенным даже там, где пункт предлагается по умолчанию. Для объекта engine-owned или append-only включение пункта также позволяет пользователям выполнять эту запись через API данных. Пользователям по-прежнему нужно соответствующее разрешение." + helpText: "Какие общие пункты (Создать, Импорт, Изменить, Удалить, Экспорт) клиенты интерфейса предлагают для записей этого объекта, переопределяя значение managedBy по умолчанию по одному пункту. Незаданный пункт сохраняет значение по умолчанию: platform предлагает все пять; config и system-data — все, кроме импорта; engine-owned, append-only и better-auth — только экспорт. Нетронутый переключатель ничего не записывает, поэтому выглядит выключенным даже там, где пункт предлагается по умолчанию. Для объекта engine-owned или append-only включение пункта также позволяет пользователям выполнять эту запись через API данных. Пользователям по-прежнему нужно соответствующее разрешение. «Сменить владельца» не входит в эту матрицу: его значение по умолчанию следует модели общего доступа (см. его пункт)." }, "userActions.create": { label: "Создание", @@ -449,6 +449,10 @@ export const ruMetadataForms: NonNullable = { label: "Экспорт CSV", helpText: "Пункт экспорта CSV. Если не задано: показывается, поскольку экспорт предлагают все категории managedBy." }, + "userActions.transfer": { + label: "Сменить владельца", + helpText: "Действие «Сменить владельца», одиночное и массовое: включено — предлагается, выключено — скрыто. Не задано: включено, кроме объекта-детали controlled_by_parent, где выключено. Предлагается только на объекте, у записей которого есть переназначаемый владелец (ownership user или не задано, без managedBy, не объект sys_, owner_id не только для чтения, а на внешнем объекте объявлен или сопоставлен); включение на любом другом объекте отклоняется. Управляет только действием, а не обычным изменением owner_id. Сохранённый объект {enabled, visibleWhen, disabledWhen} редактируется по ключам; задайте его в исходном коде, чтобы управлять действием для каждой записи." + }, editMode: { label: "Режим редактирования", helpText: "Намерение по взаимодействию при редактировании записей этого объекта. Если отсутствует, отрисовщик выбирает своё значение по умолчанию. Намерение для всех отрисовщиков, а не оформление." diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index 6e820738da2..d3a97434148 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -427,7 +427,7 @@ export const zhCNMetadataForms: NonNullable = }, userActions: { label: "用户操作", - helpText: "UI 客户端在本对象的记录上提供哪些通用入口(新建、导入、编辑、删除、导出),逐项覆盖 managedBy 的默认值。未设置的入口保持该默认值:platform 提供全部五项;config 和 system-data 提供除导入外的全部;engine-owned、append-only 和 better-auth 只提供导出。未改动过的开关不写入任何值,所以即使默认提供该入口,它也显示为关闭。在 engine-owned 或 append-only 对象上,打开某个入口还会允许用户通过数据 API 执行该写入。用户仍需要相应的权限。" + helpText: "UI 客户端在本对象的记录上提供哪些通用入口(新建、导入、编辑、删除、导出),逐项覆盖 managedBy 的默认值。未设置的入口保持该默认值:platform 提供全部五项;config 和 system-data 提供除导入外的全部;engine-owned、append-only 和 better-auth 只提供导出。未改动过的开关不写入任何值,所以即使默认提供该入口,它也显示为关闭。在 engine-owned 或 append-only 对象上,打开某个入口还会允许用户通过数据 API 执行该写入。用户仍需要相应的权限。更改负责人不属于该矩阵:其默认值取决于共享模型(见其条目)。" }, "userActions.create": { label: "新建", @@ -449,6 +449,10 @@ export const zhCNMetadataForms: NonNullable = label: "导出 CSV", helpText: "CSV 导出入口。未设置:显示,因为每个 managedBy 类别默认都提供导出。" }, + "userActions.transfer": { + label: "更改负责人", + helpText: "更改负责人操作(单条与批量):开启即提供,关闭即隐藏。未设置时开启,但 controlled_by_parent 明细对象默认关闭。仅在记录有可重新分配负责人的对象上提供(ownership 为 user 或未设置、无 managedBy、不是 sys_ 对象、owner_id 未设为只读,外部对象上 owner_id 已声明或已映射);在其他对象上开启会被拒绝。它只控制该操作,不影响直接编辑 owner_id。已存储的 {enabled, visibleWhen, disabledWhen} 对象逐键编辑;在源码中写一个即可按每条记录控制该操作。" + }, editMode: { label: "编辑方式", helpText: "该对象记录的编辑交互意图。留空则由渲染端自行选择默认方式。这是跨渲染端的意图声明,不是样式。" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index ad8ce45755d..2b69556f0c7 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts @@ -427,7 +427,7 @@ export const zhHantMetadataForms: NonNullable }, userActions: { label: "使用者操作", - helpText: "UI 用戶端在本物件的記錄上提供哪些通用入口(新增、匯入、編輯、刪除、匯出),逐項覆寫 managedBy 的預設值。未設定的入口保持該預設值:platform 提供全部五項;config 和 system-data 提供除匯入外的全部;engine-owned、append-only 和 better-auth 只提供匯出。未改動過的開關不寫入任何值,所以即使預設提供該入口,它也顯示為關閉。在 engine-owned 或 append-only 物件上,開啟某個入口還會允許使用者透過資料 API 執行該寫入。使用者仍需要相應的權限。" + helpText: "UI 用戶端在本物件的記錄上提供哪些通用入口(新增、匯入、編輯、刪除、匯出),逐項覆寫 managedBy 的預設值。未設定的入口保持該預設值:platform 提供全部五項;config 和 system-data 提供除匯入外的全部;engine-owned、append-only 和 better-auth 只提供匯出。未改動過的開關不寫入任何值,所以即使預設提供該入口,它也顯示為關閉。在 engine-owned 或 append-only 物件上,開啟某個入口還會允許使用者透過資料 API 執行該寫入。使用者仍需要相應的權限。變更負責人不屬於該矩陣:其預設值取決於共用模型(見其條目)。" }, "userActions.create": { label: "新增", @@ -449,6 +449,10 @@ export const zhHantMetadataForms: NonNullable label: "匯出 CSV", helpText: "CSV 匯出入口。未設定:顯示,因為每個 managedBy 類別預設都提供匯出。" }, + "userActions.transfer": { + label: "變更負責人", + helpText: "變更負責人操作(單筆與批次):開啟即提供,關閉即隱藏。未設定時開啟,但 controlled_by_parent 明細物件預設關閉。僅在記錄有可重新指派負責人的物件上提供(ownership 為 user 或未設定、無 managedBy、不是 sys_ 物件、owner_id 未設為唯讀,外部物件上 owner_id 已宣告或已對應);在其他物件上開啟會被拒絕。它只控制該操作,不影響直接編輯 owner_id。已儲存的 {enabled, visibleWhen, disabledWhen} 物件逐鍵編輯;在原始碼中寫一個即可按每筆記錄控制該操作。" + }, editMode: { label: "編輯方式", helpText: "該物件記錄的編輯互動意圖。留空則由呈現端自行選擇預設方式。這是跨呈現端的意圖宣告,不是樣式。" diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index ba883cf2404..67cf4064aea 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -906,6 +906,7 @@ "UnknownAuthoringKeyFinding (interface)", "UnknownImportMappingTarget (interface)", "UnorderedPaginationConformanceCase (interface)", + "UserActionTransferResolution (interface)", "VALID_AST_OPERATORS (const)", "VALUE_DOMAIN_FIELD_TYPES (const)", "VALUE_ROUNDTRIP_CASES (const)", @@ -1055,6 +1056,7 @@ "isTenantCurrencyAmount (function)", "isTextFilterOperator (function)", "isTitleEligible (function)", + "isTransferEligible (function)", "isUnboundedAbove (function)", "isUniqueDeclared (function)", "isVirtualSearchField (function)", @@ -1126,6 +1128,7 @@ "resolveRecordDisplayName (function)", "resolveSearchFieldResolution (function)", "resolveSearchFields (function)", + "resolveUserActionTransfer (function)", "seedFile (function)", "sequenceWidth (function)", "storedHomeAmountSourceOf (function)", @@ -1137,6 +1140,7 @@ "summaryFunctionReadsField (function)", "textComparandRefusalReason (function)", "textOperatorDoorVerdict (function)", + "transferIneligibilityReason (function)", "undeclaredActionRefusalAtRun (function)", "undeclaredActionRefusalCodeAtSave (function)", "undeclaredActionRefusalReasonAtRun (function)", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 6ce59e36a38..e1fc64d2ece 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -892,6 +892,7 @@ "UnknownAuthoringKeyFinding": "src/data/authoring-key-lint.ts#UnknownAuthoringKeyFinding (interface)", "UnknownImportMappingTarget": "src/data/import-mapping-target.ts#UnknownImportMappingTarget (interface)", "UnorderedPaginationConformanceCase": "src/data/pagination-conformance.ts#UnorderedPaginationConformanceCase (interface)", + "UserActionTransferResolution": "src/data/user-action-transfer.ts#UserActionTransferResolution (interface)", "VALID_AST_OPERATORS": "src/data/filter.zod.ts#VALID_AST_OPERATORS (const)", "VALUE_DOMAIN_FIELD_TYPES": "src/data/field.zod.ts#VALUE_DOMAIN_FIELD_TYPES (const)", "VALUE_ROUNDTRIP_CASES": "src/data/value-roundtrip-conformance.ts#VALUE_ROUNDTRIP_CASES (const)", @@ -1041,6 +1042,7 @@ "isTenantCurrencyAmount": "src/data/record-currency-path.ts#isTenantCurrencyAmount (function)", "isTextFilterOperator": "src/data/filter-text-operator-declared-type.ts#isTextFilterOperator (function)", "isTitleEligible": "src/data/display-name.ts#isTitleEligible (function)", + "isTransferEligible": "src/data/user-action-transfer.ts#isTransferEligible (function)", "isUnboundedAbove": "src/data/calendar-day.ts#isUnboundedAbove (function)", "isUniqueDeclared": "src/data/field.zod.ts#isUniqueDeclared (function)", "isVirtualSearchField": "src/data/search-fields.ts#isVirtualSearchField (function)", @@ -1112,6 +1114,7 @@ "resolveRecordDisplayName": "src/data/display-name.ts#resolveRecordDisplayName (function)", "resolveSearchFieldResolution": "src/data/search-fields.ts#resolveSearchFieldResolution (function)", "resolveSearchFields": "src/data/search-fields.ts#resolveSearchFields (function)", + "resolveUserActionTransfer": "src/data/user-action-transfer.ts#resolveUserActionTransfer (function)", "seedFile": "src/data/seed-file.zod.ts#seedFile (function)", "sequenceWidth": "src/data/autonumber-format.ts#sequenceWidth (function)", "storedHomeAmountSourceOf": "src/data/record-currency-path.ts#storedHomeAmountSourceOf (function)", @@ -1123,6 +1126,7 @@ "summaryFunctionReadsField": "src/data/field.zod.ts#summaryFunctionReadsField (function)", "textComparandRefusalReason": "src/data/filter-text-comparand.ts#textComparandRefusalReason (function)", "textOperatorDoorVerdict": "src/data/filter-text-operator-declared-type.ts#textOperatorDoorVerdict (function)", + "transferIneligibilityReason": "src/data/user-action-transfer.ts#transferIneligibilityReason (function)", "undeclaredActionRefusalAtRun": "src/data/hook-refusal-codes.ts#undeclaredActionRefusalAtRun (function)", "undeclaredActionRefusalCodeAtSave": "src/data/hook-refusal-codes.ts#undeclaredActionRefusalCodeAtSave (function)", "undeclaredActionRefusalReasonAtRun": "src/data/hook-refusal-codes.ts#undeclaredActionRefusalReasonAtRun (function)", diff --git a/packages/spec/liveness/object.json b/packages/spec/liveness/object.json index 758ac2330bd..bc011b7d35c 100644 --- a/packages/spec/liveness/object.json +++ b/packages/spec/liveness/object.json @@ -229,7 +229,45 @@ }, "userActions": { "status": "live", - "note": "objectui ObjectGrid per-object CRUD." + "verifiedAt": "2026-11-19", + "evidence": "packages/spec/src/data/object.zod.ts#resolveCrudAffordances (collapses `obj.userActions` onto the managedBy bucket's default row, the one resolution of the five CRUD entries); ui/packages/core/src/utils/managedBy.ts#resolveEffectiveCrudAffordances (hands the object's `userActions` to it and intersects the answer with the server's effective API operations)", + "note": "Drilled 2026-11-19 when `transfer` (the Change Owner switch, ruling 7000907189 point 1, card #35401) landed beside the five CRUD entries with a different verdict: the container used to carry one blanket `live` (\"objectui ObjectGrid per-object CRUD.\") and was recorded in undrilled-containers.baseline.json, so its children had no verdict of their own. Each child below is graded by its own reader, measured at this tree: create/import/edit/delete read through resolveCrudAffordances by the server write guard, the apiMethods reconciliation, the /me/permissions clamp and the console's affordance rows; exportCsv by nothing past the resolver (see its row); transfer by nothing yet (planned).", + "children": { + "create": { + "status": "live", + "verifiedAt": "2026-11-19", + "evidence": "packages/plugins/plugin-security/src/system-write-guard.ts#assertEngineOwnedWriteAllowed (a user-context `insert` on an engine-owned bucket needs the resolved `create`); packages/spec/src/data/managed-api-affordance.ts#checkManagedApiMethodAffordances, applied by packages/objectql/src/registry-top-level.ts#reconcileManagedApiMethods (strips an apiMethods `create` the resolved affordance does not grant); packages/core/src/security/effective-object-permissions.ts#clampManagedObjectWrites (the /me/permissions clamp reads `userActions.create`); ui/packages/core/src/utils/affordanceGrants.ts#resolveAffordance (the `listNew`, `relatedNew`, `gridAddRow` and form rows read the resolved `create` and `createPredicates`); ui/packages/app-shell/src/views/objectViewToolbarAffordances.ts#useObjectViewToolbarAffordances (evaluates `createPredicates` once per toolbar)" + }, + "import": { + "status": "live", + "verifiedAt": "2026-11-19", + "evidence": "ui/packages/core/src/utils/affordanceGrants.ts#resolveAffordance (the `listImport` row reads the resolved `import` and `importPredicates`); ui/packages/app-shell/src/views/objectViewToolbarAffordances.ts#useObjectViewToolbarAffordances (gates the CSV import entry on that verdict and evaluates `importPredicates` once per toolbar)" + }, + "edit": { + "status": "live", + "verifiedAt": "2026-11-19", + "evidence": "packages/plugins/plugin-security/src/system-write-guard.ts#assertEngineOwnedWriteAllowed (a user-context `update`, `upsert` or `transfer` on an engine-owned bucket needs the resolved `edit`); packages/spec/src/data/managed-api-affordance.ts#checkManagedApiMethodAffordances (apiMethods `update` against the resolved `edit`); packages/core/src/security/effective-object-permissions.ts#clampManagedObjectWrites (reads `userActions.edit`); ui/packages/core/src/utils/affordanceGrants.ts#resolveAffordance (the `rowEdit`, `recordEdit`, `listInlineEdit` and form rows read the resolved `edit` and `editPredicates`); ui/packages/plugin-grid/src/ObjectGrid.tsx#ObjectGrid (per-row edit verdict and `editPredicates`)" + }, + "delete": { + "status": "live", + "verifiedAt": "2026-11-19", + "evidence": "packages/plugins/plugin-security/src/system-write-guard.ts#assertEngineOwnedWriteAllowed (a user-context `delete`, `purge` or `restore` on an engine-owned bucket needs the resolved `delete`); packages/spec/src/data/managed-api-affordance.ts#checkManagedApiMethodAffordances (apiMethods `delete` against the resolved `delete`); packages/core/src/security/effective-object-permissions.ts#clampManagedObjectWrites (reads `userActions.delete`); ui/packages/core/src/utils/affordanceGrants.ts#resolveAffordance (the `rowDelete`, `recordDelete`, `listBulkDelete` and related-list rows read the resolved `delete` and `deletePredicates`); ui/packages/plugin-grid/src/ObjectGrid.tsx#ObjectGrid (per-row delete verdict and `objectDeletePredicates`)" + }, + "exportCsv": { + "status": "dead", + "verifiedAt": "2026-11-19", + "authorHint": "Remove it: no export menu reads it, so it neither shows nor hides CSV export. The export entry follows the view's exportOptions and the object's effective API operations.", + "note": "Measured 2026-11-19 while drilling this container, by closing the call graph by hand: the key's only reader is packages/spec/src/data/object.zod.ts#resolveCrudAffordances, which copies it onto `CrudAffordances.exportCsv`, and nothing reads that bit. Server side: plugin-security's WRITE_OP_AFFORDANCE and the spec's MANAGED_WRITE_VERB_AFFORDANCE map only create/edit/delete, and core's clampManagedObjectWrites reads only create/edit/delete. Console side: ui/packages/core/src/utils/managedBy.ts#resolveEffectiveCrudAffordances only ANDs the bit with the effective `export` operation, AFFORDANCE_GRANTS has no export row (its `crud` column is create/import/edit/delete), and the export menus (ui/packages/plugin-grid/src/ObjectGrid.tsx `exportEnabled`, ui/packages/plugin-list/src/ListView.tsx `exportPermitted`, ui/packages/plugin-detail/src/RelatedList.tsx, ui/packages/plugin-report/src/ReportExport.tsx) gate on `exportOptions`, `operations.export`, `allowExport` and the effective `export` operation, never on it. `git grep exportCsv` over packages/ and ui/ at this tree returns the declaration, the resolver, the form row, the FLS table (`keep`) and tests only. So `exportCsv: false` does not hide the export entry. Its blanket `live` came from the container's undrilled verdict; drilling may not fan that out (README, Granularity). Enforce-or-remove (ADR-0049) is owed: wire the console export menus to the resolved bit, or retire the key." + }, + "transfer": { + "status": "planned", + "verifiedAt": "2026-11-19", + "authorWarn": true, + "authorHint": "Keep it, but nothing reads it yet: the Change Owner action it turns on or off ships in a later release, so until then no endpoint or console button honours this switch.", + "evidence": "packages/spec/src/data/object.zod.ts#refuseIneligibleUserActionTransfer (the parse REFUSAL, live: `transfer: true` or `{ enabled: true }` on an object that is not structurally eligible is refused at `userActions.transfer`, naming the reason); packages/spec/src/data/user-action-transfer.ts#resolveUserActionTransfer (the one resolution: eligibility via isTransferEligible, then the switch, then the sharingModel default), which no runtime calls yet", + "note": "PLANNED RECORD (ruling 7000907189 point 1, spec card #35401): the per-object Change Owner switch, the union its four CRUD siblings take, with a sharingModel-derived default (on, except off on a controlled_by_parent detail) and a structural eligibility no switch can widen (packages/spec/src/data/user-action-transfer.ts#isTransferEligible: the injected owner_id, an owner provable on an external object, owner_id not readonly). READ BY NOTHING YET: the server's Change Owner endpoint (card #35402) and the console's action (card #35403) are its readers, both Blocked-by #35401. Flip to `live` on the commit that lands the first of them, citing it, and drop `authorWarn` / `authorHint` in the same edit." + } + } }, "systemFields": { "status": "live", diff --git a/packages/spec/liveness/state-counts/object.md b/packages/spec/liveness/state-counts/object.md index 54159b1baea..f7694a6959c 100644 --- a/packages/spec/liveness/state-counts/object.md +++ b/packages/spec/liveness/state-counts/object.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `object` | 80 | 0 | 0 | 1 | 1 | 82 | +| `object` | 83 | 0 | 0 | 2 | 2 | 87 | diff --git a/packages/spec/scripts/liveness/undrilled-containers.baseline.json b/packages/spec/scripts/liveness/undrilled-containers.baseline.json index 11bafae87b8..e10a38260ff 100644 --- a/packages/spec/scripts/liveness/undrilled-containers.baseline.json +++ b/packages/spec/scripts/liveness/undrilled-containers.baseline.json @@ -102,7 +102,6 @@ "object/indexes", "object/lifecycle", "object/publicSharing", - "object/userActions", "page/aria", "page/interfaceConfig", "page/regions", diff --git a/packages/spec/src/data/index.ts b/packages/spec/src/data/index.ts index b32ed5b7492..e58569f5c5a 100644 --- a/packages/spec/src/data/index.ts +++ b/packages/spec/src/data/index.ts @@ -414,6 +414,13 @@ export * from './record-surface'; // to one but cannot load a runtime. export * from './injected-system-columns'; +// [ruling 7000907189 point 1] Which objects offer the Change Owner action: the +// structural test (`isTransferEligible`) and the switch `userActions.transfer` +// resolved onto its sharingModel default (`resolveUserActionTransfer`) — the one +// answer the server's Change Owner endpoint (#35402) and the console's action +// (#35403) will read; neither exists yet. +export * from './user-action-transfer'; + // injected-system-column DEFINITIONS + the #7865 provenance marker (#8116) — // WHAT each injected column looks like, and whether storage actually backs it // on a given object (`external` objects register anchors the platform never diff --git a/packages/spec/src/data/object.form.ts b/packages/spec/src/data/object.form.ts index 4a7f7066fcf..b416e4bfe00 100644 --- a/packages/spec/src/data/object.form.ts +++ b/packages/spec/src/data/object.form.ts @@ -713,7 +713,7 @@ export const objectForm = defineForm({ // #19332 (flight G2b of ruling record 5861442317) — the per-entry override // of the matrix `managedBy` above resolves (`resolveCrudAffordances`), // so it sits directly under it. A composite with declared sub-rows over - // all five keys of the strict block (its alias and guidance words — + // all six keys of the strict block (its alias and guidance words — // `new`, `export`, the VIEW block's `sort`, … — are refusals, not keys). // // `create` / `import` / `edit` / `delete` are each a UNION — a boolean, @@ -724,7 +724,9 @@ export const objectForm = defineForm({ // new entry (the first arm) renders a switch, and a stored object // renders its three keys, whose edits merge into it. The object arm is // therefore written in source and edited here once stored. `exportCsv` is - // a plain boolean, the `enable` toggles' face. + // a plain boolean, the `enable` toggles' face. `transfer` (the Change Owner + // switch, ruling 7000907189 point 1) is the same union as the four CRUD + // entries, so it takes their `json` face. // // A switch reads `false` for an unset entry, which is not what the // resolved default says for most buckets, so the composite's help text @@ -732,13 +734,14 @@ export const objectForm = defineForm({ { field: 'userActions', type: 'composite', - helpText: 'Which generic entries (New, Import, Edit, Delete, Export) UI clients offer on this object\'s records, overriding the managedBy default one entry at a time. An unset entry keeps that default: platform offers all five; config and system-data all but Import; engine-owned, append-only and better-auth only Export. An untouched switch writes nothing, so it reads off even where the default offers the entry. On an engine-owned or append-only object, turning an entry on also lets users make that write through the data API. Users still need the matching permission.', + helpText: 'Which generic entries (New, Import, Edit, Delete, Export) UI clients offer on this object\'s records, overriding the managedBy default one entry at a time. An unset entry keeps that default: platform offers all five; config and system-data all but Import; engine-owned, append-only and better-auth only Export. An untouched switch writes nothing, so it reads off even where the default offers the entry. On an engine-owned or append-only object, turning an entry on also lets users make that write through the data API. Users still need the matching permission. Change Owner is not part of that matrix: its default follows the sharing model (see its entry).', fields: [ { field: 'create', label: 'Create', widget: 'json', helpText: 'The New button: on shows it, off hides it. A stored {enabled, visibleWhen, disabledWhen} object is edited key by key; write one in source to gate the button on the record in scope, evaluated once per toolbar (the host record on a related list).' }, { field: 'import', label: 'Import', widget: 'json', helpText: 'The CSV import entry: on shows it, off hides it. A stored {enabled, visibleWhen, disabledWhen} object is edited key by key; write one in source to gate the entry on the record in scope, evaluated once per toolbar.' }, { field: 'edit', label: 'Edit', widget: 'json', helpText: 'Editing existing records, inline and in the form: on offers it, off hides it. A stored {enabled, visibleWhen, disabledWhen} object is edited key by key; write one in source to gate each row on its own record.' }, { field: 'delete', label: 'Delete', widget: 'json', helpText: 'Row and bulk delete: on offers it, off hides it. A stored {enabled, visibleWhen, disabledWhen} object is edited key by key; write one in source to gate each row on its own record.' }, { field: 'exportCsv', label: 'Export CSV', type: 'boolean', helpText: 'The CSV export entry. Unset: shown, since every managedBy bucket offers export.' }, + { field: 'transfer', label: 'Change Owner', widget: 'json', helpText: 'The Change Owner action, single and bulk: on offers it, off hides it. Unset: on, except off on a controlled_by_parent detail. Offered only on an object whose records have a reassignable owner (ownership user or unset, no managedBy, not a sys_ object, owner_id not readonly and, on an external object, declared or mapped); turning it on anywhere else is refused. It gates the action only, not a plain edit of owner_id. A stored {enabled, visibleWhen, disabledWhen} object is edited key by key; write one in source to gate the action on each record.' }, ], }, { field: 'editMode', type: 'select', helpText: "Edit-interaction intent for records of this object. Absent, the renderer picks its own default. Cross-renderer intent, not styling.", options: [ diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index aa4d6db8f86..70b2ca2e4bb 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -63,6 +63,10 @@ import { resolveInjectedSystemColumns } from './injected-system-columns'; // registry injects is judged by its type as a declared one is. The same cycle // as above, one module further: nothing here is called while a module evaluates. import { injectedSystemColumnDefs } from './injected-system-column-provenance'; +// [ruling 7000907189 point 1] Change Owner's structural test, read by the +// `userActions.transfer` refusal. The same cycle as above, one module further +// (it reads `resolveInjectedSystemColumns`): called only at parse time. +import { transferIneligibilityReason } from './user-action-transfer'; import { BOOLEAN_VALUE_TYPES, CALENDAR_DATE_TYPES, @@ -3449,6 +3453,52 @@ function refuseWriteLockedUserActions( } } +/** + * [ruling 7000907189 point 1 · ADR-0049] `userActions.transfer` may open the + * Change Owner action only on an object that is structurally eligible for it + * (`transferIneligibilityReason`, `user-action-transfer.ts`): the platform + * injects its reassignable `owner_id`, an owner is provable for it (an + * ADR-0015 `external` object declares `owner_id` or maps a remote column onto + * it), and the object does not declare that field read-only. One located issue + * at `['userActions', 'transfer']` for a bare `true`, or the object form with + * `enabled: true`, on any other object — the structure keeps the action off + * there whatever the switch says, so the entry would be a key nothing honours. + * The reason clause carries its own arm's prescription where one exists (drop + * `readonly`, set `ownership`, declare or map the external owner); the message + * ends with the one every arm shares, removing the entry or setting it to + * false. Closing it (`false`) restates the structure and is accepted, as is a + * predicate-only object form, which opens nothing. + * + * Refused at parse on every door, not only at `create()`: the key is new, so no + * stored object carries it. Kept in the existing callback beside + * {@link refuseWriteLockedUserActions} so it adds no check node the JSON Schema + * projection would have to drop. + */ +function refuseIneligibleUserActionTransfer( + object: { name?: unknown; userActions?: unknown }, + ctx: z.RefinementCtx, +): void { + const userActions = object.userActions; + if (userActions === null || typeof userActions !== 'object') return; + const flag = (userActions as Record).transfer; + const opens = flag === true + || (flag !== null && typeof flag === 'object' && (flag as { enabled?: unknown }).enabled === true); + if (!opens) return; + const reason = transferIneligibilityReason(object); + if (reason === undefined) return; + const name = typeof object.name === 'string' && object.name.length > 0 ? object.name : 'this object'; + ctx.addIssue({ + code: 'custom', + path: ['userActions', 'transfer'], + message: + `Object '${name}' cannot offer the Change Owner action: ${reason}. ` + + 'userActions.transfer turns the action on or off only on an object whose records have a reassignable ' + + 'owner (the injected owner_id, on an object with ownership user or omitted, no managedBy and not a sys_ ' + + 'name, provable on an external object, and not declared readonly), so true here is a switch nothing ' + + 'honours. Otherwise remove the entry, or set it to false.', + }); +} + /** * [ruling A on the read half of #32442] `enable.aiReadable` is declared only * where it has a reader: a `sys_*` object outside the stored-metadata family. @@ -3727,6 +3777,15 @@ const ObjectSchemaBase = strictObject( * `create`/`import` evaluate it once per toolbar against the record in * scope (#7692). Read that schema's docblock for what `record.*` binds to * in each position — they are different records. + * + * `transfer` is the Change Owner switch (ruling 7000907189 point 1), and it + * sits outside the {@link managedBy} matrix: it takes the same union as the + * four CRUD flags, but its default derives from `sharingModel` (on, except + * off on a `controlled_by_parent` detail), and it can open the action only + * on an object that is structurally eligible for it — see + * `user-action-transfer.ts` (`isTransferEligible`, + * `resolveUserActionTransfer`). Nothing reads it at runtime yet: the Change + * Owner endpoint and the console action are cards #35402 and #35403. */ userActions: strictObject({ surface: "this object's `userActions` block", @@ -3744,6 +3803,8 @@ const ObjectSchemaBase = strictObject( update: 'edit', remove: 'delete', destroy: 'delete', + changeOwner: 'transfer', + reassign: 'transfer', }, guidance: { // Wrong-LAYER, and the trap is that the key name is right somewhere else. @@ -3757,27 +3818,27 @@ const ObjectSchemaBase = strictObject( sort: '`sort` is a VIEW `userActions` key, not an object one — the two blocks share a ' + 'name and nothing else. The object block governs CRUD affordances ' + - '(create/import/edit/delete/exportCsv); toolbar controls ' + + '(create/import/edit/delete/exportCsv) and the Change Owner action (transfer); toolbar controls ' + '(sort/search/filter/refresh/rowHeight/editInline) live on the view.', search: '`search` is a VIEW `userActions` key. This object block governs CRUD affordances ' + - 'only — put toolbar controls on the view that renders the records.', + 'and the Change Owner action (transfer) only — put toolbar controls on the view that renders the records.', filter: '`filter` is a VIEW `userActions` key. This object block governs CRUD affordances ' + - 'only — put toolbar controls on the view that renders the records.', + 'and the Change Owner action (transfer) only — put toolbar controls on the view that renders the records.', editInline: '`editInline` is a VIEW `userActions` key. The object-level `edit` flag decides ' + 'whether editing is offered AT ALL; how it is offered (inline vs form) is the ' + "view's call.", group: '`group` is a VIEW `userActions` key. This object block governs CRUD affordances ' + - 'only — put toolbar controls on the view that renders the records.', + 'and the Change Owner action (transfer) only — put toolbar controls on the view that renders the records.', hideFields: '`hideFields` is a VIEW `userActions` key. This object block governs CRUD ' + - 'affordances only — put toolbar controls on the view that renders the records.', + 'affordances and the Change Owner action (transfer) only — put toolbar controls on the view that renders the records.', rowColor: '`rowColor` is a VIEW `userActions` key. This object block governs CRUD ' + - 'affordances only — put toolbar controls on the view that renders the records.', + 'affordances and the Change Owner action (transfer) only — put toolbar controls on the view that renders the records.', clone: '`clone` is a CAPABILITY, not a user action — write `enable: { clone: false }`. ' + 'The `enable` block (ObjectCapabilities) is where record deep-cloning is governed.', @@ -3802,7 +3863,10 @@ const ObjectSchemaBase = strictObject( 'Show row-level delete + bulk delete. Boolean, or an object adding per-record visibleWhen/disabledWhen CEL predicates.', ), exportCsv: z.boolean().optional().describe('Show CSV export entry.'), - }).optional().describe('Per-object override of the resolved CRUD affordance matrix.'), + transfer: z.union([z.boolean(), RowCrudActionOverrideSchema]).optional().describe( + 'Offer the Change Owner action (single and bulk) on records of this object. Boolean, or an object adding per-record visibleWhen/disabledWhen CEL predicates. Omitted: on, except off on a controlled_by_parent detail. Offered only where the platform injects a reassignable owner_id that is provable and not declared readonly (ownership user or omitted, no managedBy, not a sys_ object; an external object declares owner_id or maps a remote column onto it); enabled: true elsewhere is refused. Gates the action, not a plain owner_id write. Resolved by resolveUserActionTransfer.', + ), + }).optional().describe('Per-object override of the resolved CRUD affordance matrix, plus the Change Owner switch (transfer).'), /** * System-field auto-injection control. @@ -4780,6 +4844,9 @@ const ObjectSchemaBase = strictObject( // [ADR-0153 D4] `userActions` opens no write verb on a `synced` object. See // the helper's docblock. refuseWriteLockedUserActions(object.name, object.managedBy, object.userActions, ctx); + // [ruling 7000907189 point 1 · ADR-0049] `userActions.transfer` opens Change + // Owner only on a structurally eligible object. See the helper's docblock. + refuseIneligibleUserActionTransfer(object, ctx); // [ADR-0154 D10] Each `lifecycle.seal.valueFields` name is a declared field. // See the helper's docblock. refuseUndeclaredSealValueFields(object.lifecycle, object.fields, ctx); diff --git a/packages/spec/src/data/user-action-transfer.test.ts b/packages/spec/src/data/user-action-transfer.test.ts new file mode 100644 index 00000000000..3ce2a4d461c --- /dev/null +++ b/packages/spec/src/data/user-action-transfer.test.ts @@ -0,0 +1,243 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect } from 'vitest'; +import { ObjectSchema } from './object.zod'; +import { + isTransferEligible, + resolveUserActionTransfer, + transferIneligibilityReason, +} from './user-action-transfer'; + +/** + * [ruling 7000907189 point 1] Which objects offer the Change Owner action: + * structural eligibility (derived, never overridable), the object switch + * `userActions.transfer` with its `sharingModel`-derived default, and the parse + * refusal of a switch that opens the action on an ineligible object (ADR-0049). + */ + +const TITLE = { title: { type: 'text', label: 'Title' } }; +const MASTER = { parent: { type: 'master_detail', reference: 'deal', required: true } }; +/** An ADR-0015 `external` object on a non-managed datasource: the remote database owns its storage. */ +const EXTERNAL = { datasource: 'legacy_crm', external: { remoteName: 'customers' } }; + +function objectWith(extra: Record, fields: Record = TITLE) { + return { name: 'deal_note', label: 'Probe', fields, ...extra }; +} + +function transferIssues(result: ReturnType) { + return result.success + ? [] + : result.error.issues.filter((i) => i.path.join('.') === 'userActions.transfer'); +} + +describe('isTransferEligible — the structural test', () => { + it('is eligible on an object whose ownership is user or omitted', () => { + expect(isTransferEligible(objectWith({}))).toBe(true); + expect(isTransferEligible(objectWith({ ownership: 'user' }))).toBe(true); + expect(transferIneligibilityReason(objectWith({}))).toBeUndefined(); + }); + + it.each(['business_unit', 'org', 'none'])('is never eligible under ownership: %s', (ownership) => { + const def = objectWith({ ownership }); + expect(isTransferEligible(def)).toBe(false); + expect(transferIneligibilityReason(def)).toContain(`ownership: '${ownership}'`); + }); + + it.each(['platform', 'config', 'system-data', 'engine-owned', 'append-only', 'synced', 'better-auth'])( + 'is never eligible on a managedBy: %s object', + (managedBy) => { + const def = objectWith({ managedBy }); + expect(isTransferEligible(def)).toBe(false); + expect(transferIneligibilityReason(def)).toContain(`managedBy: '${managedBy}'`); + }, + ); + + it('is never eligible on a sys_* object', () => { + const def = { ...objectWith({}), name: 'sys_custom_ledger' }; + expect(isTransferEligible(def)).toBe(false); + expect(transferIneligibilityReason(def)).toContain("'sys_'"); + }); + + it('is never eligible under systemFields: false', () => { + expect(isTransferEligible(objectWith({ systemFields: false }))).toBe(false); + }); + + it('is not eligible when owner_id is declared readonly, and is when it is declared writable', () => { + const pinned = objectWith({}, { ...TITLE, owner_id: { type: 'lookup', reference: 'sys_user', readonly: true } }); + expect(isTransferEligible(pinned)).toBe(false); + expect(transferIneligibilityReason(pinned)).toContain('owner_id readonly'); + const writable = objectWith({}, { ...TITLE, owner_id: { type: 'lookup', reference: 'sys_user', readonly: false } }); + expect(isTransferEligible(writable)).toBe(true); + }); + + it('reads a readonly owner_id in the array fields shape too', () => { + const pinned = { + name: 'deal_note', + label: 'Probe', + fields: [{ name: 'title', type: 'text' }, { name: 'owner_id', type: 'lookup', reference: 'sys_user', readonly: true }], + }; + expect(isTransferEligible(pinned)).toBe(false); + expect(transferIneligibilityReason(pinned)).toContain('owner_id readonly'); + const writable = { ...pinned, fields: [{ name: 'owner_id', type: 'lookup', reference: 'sys_user', readonly: false }] }; + expect(isTransferEligible(writable)).toBe(true); + }); + + it('is not eligible on an external object whose owner is unprovable, and is once the owner is declared or mapped', () => { + const unmapped = objectWith(EXTERNAL); + expect(isTransferEligible(unmapped)).toBe(false); + expect(transferIneligibilityReason(unmapped)).toContain('external object'); + expect(transferIneligibilityReason(unmapped)).toContain('external.columnMap'); + const mapped = objectWith({ ...EXTERNAL, external: { remoteName: 'customers', columnMap: { account_owner: 'owner_id' } } }); + expect(isTransferEligible(mapped)).toBe(true); + const declared = objectWith(EXTERNAL, { ...TITLE, owner_id: { type: 'lookup', reference: 'sys_user' } }); + expect(isTransferEligible(declared)).toBe(true); + // The structural arms still answer first: an external object with no owner tier + // is refused for that, not for an unprovable anchor. + expect(transferIneligibilityReason(objectWith({ ...EXTERNAL, ownership: 'none' }))).toContain("ownership: 'none'"); + }); + + it('carries each arm\'s own prescription in its reason', () => { + const pinned = objectWith({}, { ...TITLE, owner_id: { type: 'lookup', reference: 'sys_user', readonly: true } }); + expect(transferIneligibilityReason(pinned)).toContain('drop readonly from owner_id'); + expect(transferIneligibilityReason(objectWith({ ownership: 'none' }))).toContain("set ownership to 'user'"); + expect(transferIneligibilityReason(objectWith(EXTERNAL))).toContain('declare owner_id or map'); + expect(transferIneligibilityReason(objectWith({ managedBy: 'config' }))).not.toContain('to offer it'); + }); + + it('answers the same for a parsed schema as for the bare record', () => { + const parsed = ObjectSchema.parse(objectWith({ ownership: 'none' })); + expect(isTransferEligible(parsed)).toBe(false); + expect(isTransferEligible(ObjectSchema.parse(objectWith({})))).toBe(true); + }); + + it('answers false for input that is not an object definition', () => { + expect(isTransferEligible(null)).toBe(false); + expect(isTransferEligible('deal')).toBe(false); + }); +}); + +describe('resolveUserActionTransfer — the switch and its derived default', () => { + it.each([ + ['private', true], + ['public_read', true], + ['public_read_write', true], + ['controlled_by_parent', false], + ])('defaults to %s → %s when the switch is omitted', (sharingModel, enabled) => { + expect(resolveUserActionTransfer(objectWith({ sharingModel }))).toEqual({ enabled }); + }); + + it('defaults to on when sharingModel is omitted (a custom object resolves to private)', () => { + expect(resolveUserActionTransfer(objectWith({}))).toEqual({ enabled: true }); + }); + + it('turns the action on for a controlled_by_parent detail that opts in', () => { + const def = objectWith({ sharingModel: 'controlled_by_parent', userActions: { transfer: true } }, MASTER); + expect(resolveUserActionTransfer(def)).toEqual({ enabled: true }); + expect(resolveUserActionTransfer({ ...def, userActions: { transfer: { enabled: true } } })).toEqual({ enabled: true }); + }); + + it('turns the action off for a private object that opts out', () => { + expect(resolveUserActionTransfer(objectWith({ sharingModel: 'private', userActions: { transfer: false } }))) + .toEqual({ enabled: false }); + expect(resolveUserActionTransfer(objectWith({ userActions: { transfer: { enabled: false } } }))) + .toEqual({ enabled: false }); + }); + + it('carries the predicates of the object form, and a predicate-only form keeps the default', () => { + const def = objectWith({ userActions: { transfer: { visibleWhen: "record.status != 'converted'" } } }); + expect(resolveUserActionTransfer(def)).toEqual({ + enabled: true, + predicates: { visibleWhen: "record.status != 'converted'" }, + }); + const detail = objectWith( + { sharingModel: 'controlled_by_parent', userActions: { transfer: { disabledWhen: 'record.locked' } } }, + MASTER, + ); + expect(resolveUserActionTransfer(detail)).toEqual({ enabled: false, predicates: { disabledWhen: 'record.locked' } }); + }); + + it('keeps an ineligible object off whatever the switch says (a document that skipped the parse)', () => { + expect(resolveUserActionTransfer({ name: 'stock_item', ownership: 'none', userActions: { transfer: true } })) + .toEqual({ enabled: false }); + expect(resolveUserActionTransfer({ + name: 'stock_item', + managedBy: 'config', + userActions: { transfer: { enabled: true, visibleWhen: 'true' } }, + })).toEqual({ enabled: false }); + }); + + it('reads the parsed schema the same way', () => { + const parsed = ObjectSchema.parse(objectWith({ sharingModel: 'controlled_by_parent' }, MASTER)); + expect(resolveUserActionTransfer(parsed)).toEqual({ enabled: false }); + }); +}); + +describe('ObjectSchema — userActions.transfer at parse', () => { + it('accepts the switch both ways, and the object form, on an eligible object', () => { + for (const transfer of [true, false, { enabled: true, visibleWhen: 'record.amount > 0' }, { disabledWhen: 'record.locked' }]) { + const result = ObjectSchema.safeParse(objectWith({ userActions: { transfer } })); + expect(result.success, JSON.stringify(transfer)).toBe(true); + } + }); + + it('accepts transfer: true on a controlled_by_parent detail (an author opting a real owner in)', () => { + const result = ObjectSchema.safeParse( + objectWith({ sharingModel: 'controlled_by_parent', userActions: { transfer: true } }, MASTER), + ); + expect(result.success).toBe(true); + }); + + it.each([ + ['ownership: none', { ownership: 'none' }, "ownership: 'none'"], + ['ownership: business_unit', { ownership: 'business_unit' }, "ownership: 'business_unit'"], + ['managedBy: config', { managedBy: 'config' }, "managedBy: 'config'"], + ])('refuses transfer: true on an %s object, at userActions.transfer, naming the structural reason', (_label, extra, reason) => { + for (const transfer of [true, { enabled: true }]) { + const issues = transferIssues(ObjectSchema.safeParse(objectWith({ ...extra, userActions: { transfer } }))); + expect(issues).toHaveLength(1); + expect(issues[0]!.code).toBe('custom'); + expect(issues[0]!.message).toContain(reason); + } + }); + + it('refuses transfer: true on a sys_* object and where owner_id is declared readonly', () => { + const sys = ObjectSchema.safeParse({ ...objectWith({ userActions: { transfer: true } }), name: 'sys_custom_ledger' }); + expect(transferIssues(sys)).toHaveLength(1); + const pinned = ObjectSchema.safeParse(objectWith( + { userActions: { transfer: true } }, + { ...TITLE, owner_id: { type: 'lookup', reference: 'sys_user', readonly: true } }, + )); + expect(transferIssues(pinned)).toHaveLength(1); + expect(transferIssues(pinned)[0]!.message).toContain('owner_id readonly'); + expect(transferIssues(pinned)[0]!.message).toContain('drop readonly from owner_id'); + }); + + it('refuses transfer: true on an external object with no provable owner, and accepts it once mapped', () => { + for (const transfer of [true, { enabled: true }]) { + const issues = transferIssues(ObjectSchema.safeParse(objectWith({ ...EXTERNAL, userActions: { transfer } }))); + expect(issues).toHaveLength(1); + expect(issues[0]!.code).toBe('custom'); + expect(issues[0]!.message).toContain('no owner is provable'); + } + const mapped = ObjectSchema.safeParse(objectWith({ + ...EXTERNAL, + external: { remoteName: 'customers', columnMap: { account_owner: 'owner_id' } }, + userActions: { transfer: true }, + })); + expect(mapped.success, mapped.success ? '' : JSON.stringify(mapped.error.issues)).toBe(true); + }); + + it('accepts closing the switch, or a predicate-only form, on an ineligible object', () => { + for (const transfer of [false, { enabled: false }, { visibleWhen: 'record.amount > 0' }]) { + const result = ObjectSchema.safeParse(objectWith({ ownership: 'none', userActions: { transfer } })); + expect(result.success, JSON.stringify(transfer)).toBe(true); + } + }); + + it('refuses the near-miss spelling changeOwner with a pointer to transfer', () => { + const result = ObjectSchema.safeParse(objectWith({ userActions: { changeOwner: true } })); + expect(result.success).toBe(false); + const messages = result.success ? [] : result.error.issues.map((i) => i.message).join('\n'); + expect(messages).toContain('transfer'); + }); +}); diff --git a/packages/spec/src/data/user-action-transfer.ts b/packages/spec/src/data/user-action-transfer.ts new file mode 100644 index 00000000000..39882cc0459 --- /dev/null +++ b/packages/spec/src/data/user-action-transfer.ts @@ -0,0 +1,220 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { resolveInjectedSystemColumns } from './injected-system-columns'; +import { isOwnerAnchorUnprovable } from './injected-system-column-provenance'; +import type { RowCrudPredicates } from './object.zod'; + +/** + * Which objects offer the dedicated Change Owner action: the structural test, + * the object switch `userActions.transfer`, and the one resolution the server's + * Change Owner endpoint and the console's action will both read (maintainer + * ruling 7000907189, point 1). Neither reader exists yet — they are the server + * card #35402 and the console card #35403 — so nothing at runtime reads the + * switch today; the liveness ledger grades it `planned` and warns an author + * who sets it to `true` or uses the object form. + * + * ## Visibility is three facts, and only two live here + * + * The action shows on a record when the object is structurally eligible, the + * object's switch is on, and the caller holds the transfer verdict on that + * record. The third fact is the permission engine's (edit with `allowTransfer`, + * or `modifyAllRecords`, read from the explain engine's `transfer` operation); + * this module answers the first two, which are properties of the object, not of + * the caller. + * + * ## Structural eligibility (derived, never overridable) + * + * An object is eligible when the platform injects its reassignable owner column + * ({@link resolveInjectedSystemColumns}`(def).owner`), an owner is provable for + * it, and the object does not declare `owner_id` read-only. So + * `ownership: 'business_unit' | 'org' | 'none'`, every `managedBy` object, every + * `sys_*` object and `systemFields: false` never offer the action. An ADR-0015 + * `external` object whose owner anchor is unprovable + * ({@link isOwnerAnchorUnprovable}: the injected `owner_id` has no storage + * behind it and no `external.columnMap` entry maps a remote column onto it) has + * no owner to change either, so it does not offer the action; declaring + * `owner_id`, or mapping a remote column onto it, makes it eligible. A declared + * `readonly: true` on `owner_id` is how an author pins the owner: nothing moves + * it, so a Change Owner entry would only fail. + * + * ## The switch (`userActions.transfer`) + * + * The same shape as the CRUD entries beside it: a boolean, or + * `{ enabled, visibleWhen, disabledWhen }` whose predicates read the record the + * action acts on. Omitted, it derives from `sharingModel`: on for `private`, + * `public_read` and `public_read_write`, and for an object that declares no + * `sharingModel` (a custom object then resolves to `private`); off for a + * `controlled_by_parent` detail, whose access already follows its master. + * Authors override both ways — on for a detail with a real owner, off where the + * owner is the actor by rule. + * + * `enabled: true` (or a bare `true`) on an ineligible object is refused at parse + * (`ObjectSchema`'s refinement, ADR-0049: a key is enforced or not declared). + * Closing the switch there restates what the structure already says and is + * accepted. + * + * The switch gates the dedicated action — single, bulk and cascade — and not + * the raw write: a plain `owner_id` update stays governed by `allowTransfer` + * alone, so import mappings and hooks are unaffected (ruling point 2). An author + * who wants a hard block declares `owner_id` read-only. + * + * Tolerant of bare, un-parsed metadata records (the same contract as + * {@link resolveInjectedSystemColumns}), so a runtime reading a registered + * schema and an author-time tool reading a draft get the same answer. + */ + +type AnyRec = Record; + +const OWNER_FIELD = 'owner_id'; + +function asRecord(value: unknown): AnyRec | undefined { + return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as AnyRec) : undefined; +} + +/** + * Does the object declare its `owner_id` field `readonly: true`? Reads both + * registered `fields` shapes — the record shape (`fields: { owner_id: {...} }`) + * and the array shape (`fields: [{ name: 'owner_id', ... }]`) — as + * `readDeclaredFieldDef` in `injected-system-column-provenance.ts` does, so a + * pinned owner reads the same in either. + */ +function ownerFieldDeclaredReadonly(obj: AnyRec): boolean { + const fields = obj.fields; + if (Array.isArray(fields)) { + return fields.some((f) => { + const field = asRecord(f); + return field !== undefined && field.name === OWNER_FIELD && field.readonly === true; + }); + } + const record = asRecord(fields); + if (!record || !Object.prototype.hasOwnProperty.call(record, OWNER_FIELD)) return false; + return asRecord(record[OWNER_FIELD])?.readonly === true; +} + +/** + * Why `def` cannot offer the Change Owner action, as one clause naming the + * structural fact — or `undefined` when it is eligible. The ONE structural + * test: {@link isTransferEligible} is this answer's absence, and the parse + * refusal names the clause it returns. + * + * Where the object can be made eligible by changing its own declaration, the + * clause ends with that change (`to offer it, …`), so each arm carries its own + * prescription: drop `systemFields: false`, set `ownership` to `user`, declare + * or map an external owner, or drop `readonly` from `owner_id`. A `managedBy` + * or `sys_*` object has none — the action is not for it. + * + * The owner-column clauses follow {@link resolveInjectedSystemColumns}'s own + * order, so the reason named is the one that withheld the column; then whether + * an owner is provable ({@link isOwnerAnchorUnprovable}); then a pinned owner. + */ +export function transferIneligibilityReason(def: unknown): string | undefined { + // Fail closed: an unreadable definition offers nothing (an empty record would + // otherwise read as `ownership` omitted, the owner-bearing default). + const obj = asRecord(def); + if (!obj) return 'it is not an object definition'; + if (!resolveInjectedSystemColumns(obj).owner) { + const managedBy = obj.managedBy; + const name = typeof obj.name === 'string' ? obj.name : ''; + const ownership = obj.ownership; + if (obj.systemFields === false) { + return 'it declares systemFields: false, so the platform gives it no owner_id column; ' + + 'to offer it, drop systemFields: false'; + } + if (typeof managedBy === 'string' && managedBy.length > 0) { + return `it is managedBy: '${managedBy}', a platform-managed table with no per-record owner`; + } + if (managedBy !== undefined && managedBy !== null) { + return 'it declares managedBy, which makes it a platform-managed table with no per-record owner'; + } + if (name.startsWith('sys_')) { + return "it is a system object (its name starts with 'sys_'), which has no per-record owner"; + } + if (ownership === 'business_unit') { + return "it is owned by a business unit (ownership: 'business_unit'), not by a person, so it has no " + + "owner_id column; to offer it, set ownership to 'user' or omit it"; + } + if (typeof ownership === 'string') { + return `it declares ownership: '${ownership}', so its records have no per-record owner; ` + + "to offer it, set ownership to 'user' or omit it"; + } + return 'the platform gives it no owner_id column'; + } + if (isOwnerAnchorUnprovable(obj)) { + return 'it is an external object whose owner_id has no remote column behind it (it neither declares ' + + 'owner_id nor maps a remote column onto it in external.columnMap), so no owner is provable; ' + + 'to offer it, declare owner_id or map the remote owner column onto it in external.columnMap'; + } + if (ownerFieldDeclaredReadonly(obj)) { + return 'it declares owner_id readonly, which pins the owner so no change of owner can be made; ' + + 'to offer it, drop readonly from owner_id'; + } + return undefined; +} + +/** + * Is `def` structurally eligible for the Change Owner action — does the + * platform inject its reassignable `owner_id`, is an owner provable for it, and + * is that field not declared read-only? Derived from the object's own keys and + * never overridable: `userActions.transfer` turns the action on or off only on + * an eligible object, and cannot open it anywhere else. + */ +export function isTransferEligible(def: unknown): boolean { + return transferIneligibilityReason(def) === undefined; +} + +/** + * The object's Change Owner switch, resolved: structural eligibility first, + * then `userActions.transfer`, then the default `sharingModel` implies. + */ +export interface UserActionTransferResolution { + /** Whether the object offers the action at all. The caller's transfer verdict is still owed per record. */ + enabled: boolean; + /** + * CEL predicates over the record the action acts on, present only when the + * switch used the object form with at least one predicate (and the object is + * eligible). Kept as authored, for the canonical CEL row-predicate evaluator: + * `visibleWhen` false hides the action (fail-closed); `disabledWhen` true + * renders it disabled (fail-soft). + */ + predicates?: RowCrudPredicates; +} + +/** + * The switch's default when `userActions.transfer` is omitted: off on a + * `controlled_by_parent` detail, on for every other `sharingModel` and for none. + */ +function derivedTransferDefault(obj: AnyRec): boolean { + return obj.sharingModel !== 'controlled_by_parent'; +} + +/** + * Resolve whether `def` offers the Change Owner action, and with which + * per-record predicates. An ineligible object answers `{ enabled: false }` + * whatever its switch says; an eligible one collapses `userActions.transfer` + * (bare boolean or `{ enabled, visibleWhen, disabledWhen }`) onto the default + * `sharingModel` implies, the same collapse the CRUD entries take onto their + * `managedBy` default. + * + * The one resolution, for the two readers still to come (cards #35402 and + * #35403): the server's Change Owner endpoint will refuse an object this + * answers `enabled: false` for, and the console will show the action only where + * it answers `true` — both then asking the caller's transfer verdict per record. + */ +export function resolveUserActionTransfer(def: unknown): UserActionTransferResolution { + if (!isTransferEligible(def)) return { enabled: false }; + const obj = asRecord(def) ?? {}; + const base = derivedTransferDefault(obj); + const authored = asRecord(obj.userActions)?.transfer; + if (authored === undefined || authored === null) return { enabled: base }; + if (typeof authored === 'boolean') return { enabled: authored }; + const override = asRecord(authored); + if (!override) return { enabled: base }; + const enabled = typeof override.enabled === 'boolean' ? override.enabled : base; + const visibleWhen = override.visibleWhen as RowCrudPredicates['visibleWhen'] | null | undefined; + const disabledWhen = override.disabledWhen as RowCrudPredicates['disabledWhen'] | null | undefined; + if (visibleWhen == null && disabledWhen == null) return { enabled }; + const predicates: RowCrudPredicates = {}; + if (visibleWhen != null) predicates.visibleWhen = visibleWhen; + if (disabledWhen != null) predicates.disabledWhen = disabledWhen; + return { enabled, predicates }; +}