diff --git a/.changeset/33345-sweep-refusal-copy.md b/.changeset/33345-sweep-refusal-copy.md new file mode 100644 index 00000000000..14c2d20674c --- /dev/null +++ b/.changeset/33345-sweep-refusal-copy.md @@ -0,0 +1,17 @@ +--- +'@objectstack/spec': patch +'@objectstack/metadata-protocol': patch +'@objectstack/plugin-security': patch +'@objectstack/cli': patch +--- + +fix: four refusals say what the author can act on — the clone control by its console label, an empty or short unknown key, and an unknown CLI command + +Clause-②: no +Metadata-protocol: none + +Nothing new is accepted or refused; only the words change. + +- **Packaged permission sets.** The `ITEM_LOCKED` save refusal and the `NOT_OVERRIDABLE` lock refusals sent the admin to a "Clone" action. Studio's Access pillar and Setup label that control "New similar" ("新建类似" in a Chinese session), so the diagnostic and both end-user messages, in every language they ship, now name it that way. +- **Unknown keys.** A refusal naming an empty key printed it as empty backticks; it now says "an empty key (`""`)" and offers no rename. On a key of five characters or fewer, a "Did you mean" rename is offered only when the declared key is one edit away, counting a swap of two adjacent letters as one: `lable` → `label` is still offered, while a removed `aria` is no longer answered with `areas`. +- **CLI.** `os ` and `os ` still exit 2 without running anything, and now name the command as typed (`command environments frobnicate not found`) and end with the help that lists the real ones (`See more help with \`os environments --help\``). diff --git a/content/docs/ai/connect-mcp.mdx b/content/docs/ai/connect-mcp.mdx index 1e3541e96e5..ab862eeb48b 100644 --- a/content/docs/ai/connect-mcp.mdx +++ b/content/docs/ai/connect-mcp.mdx @@ -565,8 +565,11 @@ can reach is the **default exposure policy (v1)**: are exposed the same way, with `ai.requiresConfirmation: true`, and forward to their approvals routes as the caller. The approval service admits the submitter, and for recalling a pending request the administrator who may - override it; anyone else is refused (`FORBIDDEN`) and the request does not - move. A recalled request is closed: to send the record for approval again, + override it; anyone else is refused and the request does not move. A caller + who cannot read the request is answered `404 REQUEST_NOT_FOUND`, exactly as + for an id that names no request, so the refusal does not tell them the request + exists; one who can read it (a pending approver, say) is answered + `403 FORBIDDEN`. A recalled request is closed: to send the record for approval again, the agent uses the app's own submit action. Remind, request-info and comments are not exposed. diff --git a/content/docs/concepts/metadata-lifecycle.mdx b/content/docs/concepts/metadata-lifecycle.mdx index 9c22e795edd..22a42f0743a 100644 --- a/content/docs/concepts/metadata-lifecycle.mdx +++ b/content/docs/concepts/metadata-lifecycle.mdx @@ -223,7 +223,7 @@ See [ADR-0005](https://github.com/objectstack-ai/objectstack/blob/main/docs/adr/ | :--- | :--- | | `flow` | Declare an override from the base's paired `.custom`, or rename it (a write from any other package is told to rename: only the pair declares an override), or switch it off (`POST /api/v1/automation/:name/toggle`, body `{enabled: false}`). The declared override is armed in the base flow's place, keeps its one activation switch, and a run suspended on the base finishes on the version it started on (ADR-0146 D9). A copy under a new name is "New similar", the clone door `POST /api/v1/automation/:name/clone` (body `{name, label}`), which the removal refusal still names. A flow that holds a credential (an inbound hook's `secret`, an `http` node's `signingSecret`) is not cloned in one step: the clone door refuses it with `409`, because a copy would share the secret, and the copy is authored as a new flow with its own. The copy is written switched off, into the source package's paired customization package `.custom` (created on first use; a kernel package, of scope `system` or `cloud`, has no pair in this version, so a copy of a flow it ships answers the ensure door's `409` until the body names `package`), or into the writable package the body's optional `package` names; a flow no read-only package ships has no pair, so its clone names `package`. The answer's `packageId` says where the copy landed ([ADR-0146](https://github.com/objectstack-ai/objectstack/blob/main/docs/adr/0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md) D3, D4). | | `action` | Switch it off (`POST /api/v1/actions/_activation/:object/:action`, body `{enabled: false}`; `:object` is `global` for an object-less action). No clone is offered. | -| `permission` | Clone it under a new name: the "Clone" action on the permission set, or the clone door `POST /api/v1/security/permission-sets/:name/clone` (body `{name, label, package?}`) with a new name. The clone door copies the whole definition from the security catalog; a copy of a packaged set lands in the package's paired `.custom`, and a copy of a set a kernel package ships lands environment-wide (ADR-0146 D3/D6). | +| `permission` | Clone it under a new name: the "New similar" action on the permission set, or the clone door `POST /api/v1/security/permission-sets/:name/clone` (body `{name, label, package?}`) with a new name. The clone door copies the whole definition from the security catalog; a copy of a packaged set lands in the package's paired `.custom`, and a copy of a set a kernel package ships lands environment-wide (ADR-0146 D3/D6). | A permission set and a position also have a switch, outside the refusal: `POST /api/v1/security/_activation/:type/:name` (`:type` = `permission` or `position`), body `{enabled: false}`, switches one off for the deployment. The refusal does not name it: a packaged position's refusal keeps the managed seal's edit remedy. The audience anchors `everyone` and `guest` are not switchable. diff --git a/content/docs/permissions/authorization.mdx b/content/docs/permissions/authorization.mdx index 6337c1b2b3a..70ef1ea2fc7 100644 --- a/content/docs/permissions/authorization.mdx +++ b/content/docs/permissions/authorization.mdx @@ -281,7 +281,7 @@ only what it owns: of the write: `permission` declares `allowEnvironmentOverlay: false` (ADR-0005's security row — overlays of the authorization surface would create silent privilege drift), so no environment-scope overlay is minted, - and the refusal names the clone (the "Clone" action on the set, or + and the refusal names the clone (the "New similar" action on the set, or `POST /api/v1/security/permission-sets/:name/clone`). Narrowing the packaged set itself takes the channel ADR-0086 two-doors always named: **edit the package and re-publish**. (ADR-0094 D5's 2026-07-14 direction — translate diff --git a/packages/cli/package.json b/packages/cli/package.json index 1c544167ed5..c46e350329a 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -53,7 +53,8 @@ "glob": "**/*.js" }, "hooks": { - "preparse": "./dist/hooks/preparse/strip-arg-separator.js" + "preparse": "./dist/hooks/preparse/strip-arg-separator.js", + "command_not_found": "./dist/hooks/command-not-found/point-at-help.js" }, "topicSeparator": " ", "topics": { diff --git a/packages/cli/src/hooks/command-not-found/point-at-help.test.ts b/packages/cli/src/hooks/command-not-found/point-at-help.test.ts new file mode 100644 index 00000000000..5049fe34387 --- /dev/null +++ b/packages/cli/src/hooks/command-not-found/point-at-help.test.ts @@ -0,0 +1,52 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { readFileSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; +import hook, { commandNotFoundMessage, type CommandNotFoundConfig } from './point-at-help.js'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const PKG = resolve(HERE, '../../../package.json'); + +/** A command table with one topic (`environments`), one nested topic and one command under a topic. */ +const config: CommandNotFoundConfig = { + bin: 'os', + topicSeparator: ' ', + findTopic: (id) => ['environments', 'plugin', 'plugin:trust', 'migrate'].includes(id), + findCommand: (id) => ['migrate:plan', 'dev'].includes(id), +}; + +const refusal = async (id: string): Promise => { + try { + await (hook as unknown as (opts: { id: string; config: CommandNotFoundConfig }) => Promise)({ id, config }); + } catch (error) { + return error; + } + throw new Error('expected the hook to refuse'); +}; + +describe('an unknown command points at the help that lists the real ones', () => { + it('a topic-level unknown subcommand: the id as typed, and the topic\'s own help', async () => { + const error = await refusal('environments:frobnicate'); + expect(error.oclif?.exit).toBe(2); + expect(error.message).toBe('command environments frobnicate not found\nSee more help with `os environments --help`'); + }); + + it('a top-level unknown command points at the root help', async () => { + const error = await refusal('frobnicate'); + expect(error.oclif?.exit).toBe(2); + expect(error.message).toBe('command frobnicate not found\nSee more help with `os --help`'); + }); + + it('the deepest topic or command the typed words reached is the one named', () => { + expect(commandNotFoundMessage('plugin:trust:frobnicate', config)).toContain('`os plugin trust --help`'); + expect(commandNotFoundMessage('migrate:plan:frobnicate', config)).toContain('`os migrate plan --help`'); + expect(commandNotFoundMessage('nope:frobnicate', config)).toContain('`os --help`'); + }); + + it('is registered as the CLI\'s command_not_found hook, from the built tree', () => { + const manifest = JSON.parse(readFileSync(PKG, 'utf8')); + expect(manifest.oclif.hooks.command_not_found).toBe('./dist/hooks/command-not-found/point-at-help.js'); + }); +}); diff --git a/packages/cli/src/hooks/command-not-found/point-at-help.ts b/packages/cli/src/hooks/command-not-found/point-at-help.ts new file mode 100644 index 00000000000..6143c7f4866 --- /dev/null +++ b/packages/cli/src/hooks/command-not-found/point-at-help.ts @@ -0,0 +1,50 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { Errors, type Hook } from '@oclif/core'; + +/** + * An unknown command ends with a pointer to the help that lists the real ones. + * + * Without this hook oclif answers `os environments frobnicate` with one line, + * `command environments:frobnicate not found`, and nothing else: the id in its + * internal colon spelling (this CLI separates topics with a space) and no way + * forward. A wrong FLAG already ends with oclif's `See more help with --help`; + * a wrong command name did not, at the top level or under a topic. + * + * The answer is unchanged in kind — a hard error, exit 2, the command never + * runs, and no guess at what was meant (this CLI ships no not-found suggester; + * a typo is refused, not reinterpreted). Only the words change: the id is + * spelled the way it was typed, and the pointer names the help of the deepest + * topic or command the typed words did reach (`os environments --help`), or + * the root's (`os --help`) when the first word is already unknown. + */ + +/** The slice of oclif's `Config` the message reads. */ +export interface CommandNotFoundConfig { + bin: string; + topicSeparator: string; + findTopic(id: string): unknown; + findCommand(id: string): unknown; +} + +/** The refusal's text: what was not found, then where its siblings are listed. */ +export function commandNotFoundMessage(id: string, config: CommandNotFoundConfig): string { + const separator = config.topicSeparator || ':'; + const segments = id.split(':').filter((segment) => segment !== ''); + let reached: string[] = []; + for (let length = segments.length - 1; length > 0; length -= 1) { + const prefix = segments.slice(0, length).join(':'); + if (config.findTopic(prefix) || config.findCommand(prefix)) { + reached = segments.slice(0, length); + break; + } + } + const help = [config.bin, ...reached, '--help'].join(' '); + return `command ${segments.join(separator)} not found\nSee more help with \`${help}\``; +} + +const hook: Hook<'command_not_found'> = async function ({ id, config }) { + throw new Errors.CLIError(commandNotFoundMessage(id, config), { exit: 2 }); +}; + +export default hook; diff --git a/packages/metadata-protocol/src/packaged-base-regime.ts b/packages/metadata-protocol/src/packaged-base-regime.ts index 48ca870594a..90a3824304f 100644 --- a/packages/metadata-protocol/src/packaged-base-regime.ts +++ b/packages/metadata-protocol/src/packaged-base-regime.ts @@ -51,8 +51,10 @@ * the action-clone half is not chartered, so a clone route named here would * advertise one that does not exist; * - `permission` — the clone only (§8 item 3, the landed lock-and-clone - * machinery): the "Clone" action on the permission set, which posts the copy - * to `POST /data/sys_permission_set` under a new name. Spelled as + * machinery): the "New similar" action on the permission set — the label + * the console draws on that control in Studio's Access pillar and in Setup + * (`perm.clone.action`) — which posts the copy to the catalog's clone door, + * `POST /security/permission-sets/:name/clone`, under a new name. Spelled as * `plugin-security`'s own lock refusal spells that same path * (`packaged-permission-set-lock.ts`), so one condition reads one way at * every door; @@ -201,7 +203,7 @@ export const PACKAGED_BASE_REGIME: Readonly { // The clone route is the catalog's clone door: the data route of the // `sys_permission_set` object retired with it (C3 stage 8). expect(message).toContain( - 'Clone it under a new name to customize it (the "Clone" action on the permission set, ' + 'Clone it under a new name to customize it (the "New similar" action on the permission set, ' + 'or POST /api/v1/security/permission-sets/:name/clone with a new name).', ); expect(message).not.toContain('OS_METADATA_WRITABLE'); @@ -1265,7 +1267,7 @@ describe('[#20910] the repository doors name a Regime C type\'s sanctioned path, + 'operator-only where one install serves several organizations).'; // The clone route is the catalog's clone door: the data route of the // `sys_permission_set` object retired with it (C3 stage 8). - const PERMISSION_CLONE = 'Clone it under a new name to customize it (the "Clone" action on the permission set, ' + const PERMISSION_CLONE = 'Clone it under a new name to customize it (the "New similar" action on the permission set, ' + 'or POST /api/v1/security/permission-sets/:name/clone with a new name).'; const FLOW_PATHS = 'Clone it under a new name to customize it (POST /api/v1/automation/:name/clone, body {name, label}), ' + 'or switch it off (POST /api/v1/automation/:name/toggle, body {enabled: false}; ' diff --git a/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts b/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts index 7d7636294cb..5fb756f6945 100644 --- a/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts +++ b/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts @@ -429,3 +429,34 @@ describe('[#32780] a stored permission set in its package\'s registry slot is ne expect(classifyPackagedPermissionSet(N, ql)).toEqual({ status: 'packaged', packageId: CRM, packageIds: [CRM] }); }); }); + +// The control the refusal sends the admin to is named by the label the console +// draws on it: "New similar" (Studio's Access pillar and Setup, the console's +// `perm.clone.action`), "新建类似" in a Chinese session, Traditional included, +// and the English label in every language the console's designer strings do +// not ship. A sentence naming a "Clone" button points at a control that is not there. +describe('the lock refusals name the clone control by its console label', () => { + const LOCALES = ['en', 'zh-Hans', 'zh-Hant', 'ja', 'ko', 'es', 'fr', 'de', 'pt-BR', 'ru', 'ar']; + const CHINESE = new Set(['zh-Hans', 'zh-Hant']); + const refusals = (locale: string) => [ + new PackagedPermissionSetLockedError('crm_sales', 'com.example.crm', 'update', [locale]), + new PackagedPermissionSetProvenanceUnknownError('crm_sales', 'registry unavailable', [locale]), + ]; + + for (const locale of LOCALES) { + it(`${locale}: the guidance names the "${CHINESE.has(locale) ? '新建类似' : 'New similar'}" action`, () => { + for (const refusal of refusals(locale)) { + expect(refusal.code).toBe('NOT_OVERRIDABLE'); + expect(refusal.status).toBe(403); + expect(refusal.userMessage).toContain(CHINESE.has(locale) ? '新建类似' : 'New similar'); + expect(refusal.userMessage).not.toMatch(/Clone action|“克隆”|「複製」動作|「複製」アクション|Clonar|Cloner|„Klonen“|«Клонировать»|복제 작업/); + } + }); + } + + it('the diagnostic names the same control', () => { + const [locked] = refusals('en'); + expect(locked.message).toContain('the "New similar" action on the permission set, or POST /api/v1/security/permission-sets/crm_sales/clone'); + expect(locked.message).not.toContain('"Clone" action'); + }); +}); diff --git a/packages/plugins/plugin-security/src/packaged-permission-set-lock.ts b/packages/plugins/plugin-security/src/packaged-permission-set-lock.ts index bf6780d0388..b8625110b4b 100644 --- a/packages/plugins/plugin-security/src/packaged-permission-set-lock.ts +++ b/packages/plugins/plugin-security/src/packaged-permission-set-lock.ts @@ -296,72 +296,79 @@ export function classifyPackagedPermissionSet( * else `en` ({@link packagedSetUserMessage}). The write door states the two * locales (`MetadataAuthoringGateContext.userTextLocales`); a caller that * states none gets `en`, the text this refusal always carried. + * + * The control is named by the label the console draws on it, in that + * locale: "New similar" in Studio's Access pillar and in Setup alike, and + * "新建类似" for a Chinese session, Traditional included (the console's + * `perm.clone.action`; its designer strings ship `en` and `zh` only, so every + * other language shows the English label). A sentence naming a "Clone" button + * sent the admin looking for a control the console does not draw. */ type PackagedSetUserText = Readonly>; const LOCKED_USER_TEXT: PackagedSetUserText = { en: `This permission set is provided by an installed package and can't be edited here. Clone it instead ` - + `with the Clone action, then edit the clone. The clone is your organization's own permission set, ` + + `with the New similar action, then edit the clone. The clone is your organization's own permission set, ` + `and package upgrades keep reaching the original.`, - 'zh-Hans': '此权限集由已安装的软件包提供,不能在这里编辑。请使用“克隆”操作克隆它,然后编辑克隆出的权限集。' + 'zh-Hans': '此权限集由已安装的软件包提供,不能在这里编辑。请使用“新建类似”操作克隆它,然后编辑克隆出的权限集。' + '克隆出的权限集归贵组织所有,软件包升级仍会照常更新原权限集。', - 'zh-Hant': '此權限集由已安裝的套件提供,無法在這裡編輯。請使用「複製」動作複製它,然後編輯複製出的權限集。' + 'zh-Hant': '此權限集由已安裝的套件提供,無法在這裡編輯。請使用「新建类似」動作複製它,然後編輯複製出的權限集。' + '複製出的權限集歸貴組織所有,套件升級仍會照常更新原權限集。', ja: 'この権限セットはインストール済みのパッケージが提供しているため、ここでは編集できません。' - + '「複製」アクションで複製し、複製したほうを編集してください。複製した権限セットは組織独自のものになり、' + + '「New similar」アクションで複製し、複製したほうを編集してください。複製した権限セットは組織独自のものになり、' + 'パッケージのアップグレードは引き続き元の権限セットに適用されます。', - ko: '이 권한 집합은 설치된 패키지가 제공하므로 여기에서 편집할 수 없습니다. 복제 작업으로 복제한 다음 복제본을 ' + ko: '이 권한 집합은 설치된 패키지가 제공하므로 여기에서 편집할 수 없습니다. "New similar" 작업으로 복제한 다음 복제본을 ' + '편집하세요. 복제본은 조직 고유의 권한 집합이 되며, 패키지 업그레이드는 계속 원본에 적용됩니다.', es: 'Este conjunto de permisos lo proporciona un paquete instalado y no se puede editar aquí. Clónelo con la ' - + 'acción Clonar y edite el clon. El clon es un conjunto de permisos propio de su organización, y las ' + + 'acción «New similar» y edite el clon. El clon es un conjunto de permisos propio de su organización, y las ' + 'actualizaciones del paquete siguen llegando al original.', fr: 'Cet ensemble d’autorisations est fourni par un package installé et ne peut pas être modifié ici. ' - + 'Clonez-le avec l’action Cloner, puis modifiez le clone. Le clone appartient à votre organisation, et les ' + + 'Clonez-le avec l’action « New similar », puis modifiez le clone. Le clone appartient à votre organisation, et les ' + 'mises à jour du package continuent de s’appliquer à l’original.', de: 'Dieser Berechtigungssatz wird von einem installierten Paket bereitgestellt und kann hier nicht bearbeitet ' - + 'werden. Klonen Sie ihn mit der Aktion „Klonen“ und bearbeiten Sie den Klon. Der Klon gehört Ihrer ' + + 'werden. Klonen Sie ihn mit der Aktion „New similar“ und bearbeiten Sie den Klon. Der Klon gehört Ihrer ' + 'Organisation, und Paket-Upgrades erreichen weiterhin das Original.', 'pt-BR': 'Este conjunto de permissões é fornecido por um pacote instalado e não pode ser editado aqui. Clone-o ' - + 'com a ação Clonar e edite o clone. O clone é um conjunto de permissões da sua organização, e as ' + + 'com a ação "New similar" e edite o clone. O clone é um conjunto de permissões da sua organização, e as ' + 'atualizações do pacote continuam chegando ao original.', ru: 'Этот набор разрешений предоставлен установленным пакетом, и его нельзя изменить здесь. Клонируйте его ' - + 'действием «Клонировать» и измените клон. Клон принадлежит вашей организации, а обновления пакета ' + + 'действием «New similar» и измените клон. Клон принадлежит вашей организации, а обновления пакета ' + 'по-прежнему применяются к оригиналу.', - ar: 'مجموعة الأذونات هذه يوفرها حزمة مثبتة ولا يمكن تعديلها هنا. انسخها باستخدام إجراء النسخ، ثم عدّل النسخة. ' + ar: 'مجموعة الأذونات هذه يوفرها حزمة مثبتة ولا يمكن تعديلها هنا. انسخها باستخدام إجراء "New similar"، ثم عدّل النسخة. ' + 'النسخة مجموعة أذونات خاصة بمؤسستك، وتستمر ترقيات الحزمة في الوصول إلى المجموعة الأصلية.', }; const PROVENANCE_UNKNOWN_USER_TEXT: PackagedSetUserText = { en: `This permission set can't be saved right now, because the system couldn't confirm whether an installed ` + `package provides it. Try again in a moment. To customize a permission set that a package provides, ` - + `clone it with the Clone action and edit the clone.`, + + `clone it with the New similar action and edit the clone.`, 'zh-Hans': '此权限集暂时无法保存,因为系统无法确认它是否由已安装的软件包提供。请稍后重试。' - + '如需自定义由软件包提供的权限集,请使用“克隆”操作克隆它,然后编辑克隆出的权限集。', + + '如需自定义由软件包提供的权限集,请使用“新建类似”操作克隆它,然后编辑克隆出的权限集。', 'zh-Hant': '此權限集暫時無法儲存,因為系統無法確認它是否由已安裝的套件提供。請稍後再試。' - + '如需自訂由套件提供的權限集,請使用「複製」動作複製它,然後編輯複製出的權限集。', + + '如需自訂由套件提供的權限集,請使用「新建类似」動作複製它,然後編輯複製出的權限集。', ja: 'この権限セットは現在保存できません。インストール済みのパッケージが提供しているかどうかを確認できなかったためです。' + 'しばらくしてからもう一度お試しください。パッケージが提供する権限セットをカスタマイズするには、' - + '「複製」アクションで複製し、複製したほうを編集してください。', + + '「New similar」アクションで複製し、複製したほうを編集してください。', ko: '설치된 패키지가 이 권한 집합을 제공하는지 확인할 수 없어 지금은 저장할 수 없습니다. 잠시 후 다시 시도하세요. ' - + '패키지가 제공하는 권한 집합을 사용자 지정하려면 복제 작업으로 복제한 다음 복제본을 편집하세요.', + + '패키지가 제공하는 권한 집합을 사용자 지정하려면 "New similar" 작업으로 복제한 다음 복제본을 편집하세요.', es: 'Este conjunto de permisos no se puede guardar ahora, porque el sistema no pudo confirmar si lo proporciona ' + 'un paquete instalado. Vuelva a intentarlo en un momento. Para personalizar un conjunto de permisos que ' - + 'proporciona un paquete, clónelo con la acción Clonar y edite el clon.', + + 'proporciona un paquete, clónelo con la acción «New similar» y edite el clon.', fr: 'Cet ensemble d’autorisations ne peut pas être enregistré pour le moment, car le système n’a pas pu ' + 'confirmer s’il est fourni par un package installé. Réessayez dans un instant. Pour personnaliser un ' - + 'ensemble d’autorisations fourni par un package, clonez-le avec l’action Cloner et modifiez le clone.', + + 'ensemble d’autorisations fourni par un package, clonez-le avec l’action « New similar » et modifiez le clone.', de: 'Dieser Berechtigungssatz kann gerade nicht gespeichert werden, weil das System nicht bestätigen konnte, ' + 'ob ein installiertes Paket ihn bereitstellt. Versuchen Sie es gleich noch einmal. Um einen ' - + 'Berechtigungssatz anzupassen, den ein Paket bereitstellt, klonen Sie ihn mit der Aktion „Klonen“ und ' + + 'Berechtigungssatz anzupassen, den ein Paket bereitstellt, klonen Sie ihn mit der Aktion „New similar“ und ' + 'bearbeiten Sie den Klon.', 'pt-BR': 'Este conjunto de permissões não pode ser salvo agora, porque o sistema não conseguiu confirmar se um ' + 'pacote instalado o fornece. Tente novamente em instantes. Para personalizar um conjunto de permissões ' - + 'fornecido por um pacote, clone-o com a ação Clonar e edite o clone.', + + 'fornecido por um pacote, clone-o com a ação "New similar" e edite o clone.', ru: 'Этот набор разрешений сейчас нельзя сохранить: системе не удалось проверить, предоставлен ли он ' + 'установленным пакетом. Повторите попытку чуть позже. Чтобы настроить набор разрешений из пакета, ' - + 'клонируйте его действием «Клонировать» и измените клон.', + + 'клонируйте его действием «New similar» и измените клон.', ar: 'لا يمكن حفظ مجموعة الأذونات هذه الآن، لأن النظام لم يتمكن من التأكد مما إذا كانت حزمة مثبتة توفرها. ' - + 'حاول مرة أخرى بعد قليل. لتخصيص مجموعة أذونات توفرها حزمة، انسخها باستخدام إجراء النسخ ثم عدّل النسخة.', + + 'حاول مرة أخرى بعد قليل. لتخصيص مجموعة أذونات توفرها حزمة، انسخها باستخدام إجراء "New similar" ثم عدّل النسخة.', }; /** @@ -439,7 +446,7 @@ export class PackagedPermissionSetLockedError extends Error { `[Security] Permission set '${name}' is declared by ${by} and is locked — ` + `editing it here would silently fork it from the package, and the fork would win over ` + `every future upgrade with no signal. ` - + `Clone it instead (the "Clone" action on the permission set, or POST ` + + `Clone it instead (the "New similar" action on the permission set, or POST ` + `/api/v1/security/permission-sets/${name}/clone with a new name) and edit the clone — the clone is your organization's own set, and upgrades keep ` + `flowing to '${name}' untouched.`, ); diff --git a/packages/rest/src/rest-meta-packaged-action-permission-refusal.test.ts b/packages/rest/src/rest-meta-packaged-action-permission-refusal.test.ts index 5cc24818da8..358e7aeefc1 100644 --- a/packages/rest/src/rest-meta-packaged-action-permission-refusal.test.ts +++ b/packages/rest/src/rest-meta-packaged-action-permission-refusal.test.ts @@ -15,7 +15,7 @@ * `POST /api/v1/actions/_activation/:object/:action`) and no clone — the * action-clone half is not chartered; [#30065] its save names the declared * override from the base's paired `.custom` first (ADR-0146 D9 `action`); - * - a PERMISSION SET has its clone (§8 item 3, the "Clone" action, which posts + * - a PERMISSION SET has its clone (§8 item 3, the "New similar" action, which posts * to `POST /api/v1/data/sys_permission_set`) and no switch named here. * * The protocol-side pins are @@ -119,7 +119,7 @@ const expectRegimeC = (message: unknown, type: string, name: string, operation: const ACTION_SWITCH = 'it off (POST /api/v1/actions/_activation/:object_or_global/:action, body {enabled: false}'; // The route's spelling moved with C3 stage 8 (the retired object's data route // → the catalog's clone door), so the sentence is pinned up to it. -const PERMISSION_CLONE = 'Clone it under a new name to customize it (the "Clone" action on the permission set, ' +const PERMISSION_CLONE = 'Clone it under a new name to customize it (the "New similar" action on the permission set, ' + 'or POST /api/v1/'; describe('PUT / DELETE /api/v1/meta/action/:name on a packaged action — the refusal names the activation switch', () => { diff --git a/packages/spec/src/shared/strict-object.test.ts b/packages/spec/src/shared/strict-object.test.ts index ba9d797d0f6..7c4f5d13ba7 100644 --- a/packages/spec/src/shared/strict-object.test.ts +++ b/packages/spec/src/shared/strict-object.test.ts @@ -526,3 +526,50 @@ describe('eager construction with this module entered first', () => { ).toBe('ok'); }, 60_000); }); + +/** + * The rename channel on SHORT keys, and the key that is no spelling at all. + * Below six characters the budget is the floor of 2, which exists for a swap of + * two adjacent letters; two unrelated edits on a four-letter key are half the + * key, and answered a removed `aria` with the app's `areas`. + */ +describe('short and empty unknown keys', () => { + const Nav = lazySchema(() => + strictObject({ surface: 'this nav', history: 'h' }, { + name: z.string(), + areas: z.array(z.string()).optional(), + label: z.string().optional(), + id: z.string().optional(), + }), + ); + const messageFor = (body: Record) => { + const r = Nav.safeParse({ name: 'x', ...body }); + expect(r.success).toBe(false); + const issue = r.error!.issues[0]!; + expect(issue.code).toBe('unrecognized_keys'); + return issue.message; + }; + + it('a four-letter key two unrelated edits from a declared one gets no rename', () => { + const m = messageFor({ aria: { label: 'x' } }); + expect(m.startsWith('Unrecognized key(s) on this nav: `aria`.')).toBe(true); + expect(m).not.toContain('Did you mean'); + expect(m).not.toContain('`areas`'); + }); + + it('a swap of two adjacent letters on a short key is still answered', () => { + expect(messageFor({ lable: 'x' })).toContain('Did you mean `lable` → `label`?'); + expect(messageFor({ aeras: [] })).toContain('Did you mean `aeras` → `areas`?'); + }); + + it('a one-letter slip on a short key is still answered', () => { + expect(messageFor({ labl: 'x' })).toContain('Did you mean `labl` → `label`?'); + }); + + it('an empty key is named as one, and offered no rename', () => { + const m = messageFor({ '': 1 }); + expect(m.startsWith('Unrecognized key(s) on this nav: an empty key (`""`).')).toBe(true); + expect(m).not.toContain('``'); + expect(m).not.toContain('Did you mean'); + }); +}); diff --git a/packages/spec/src/shared/suggestions.zod.ts b/packages/spec/src/shared/suggestions.zod.ts index 0714d96e8c2..a4defaac58e 100644 --- a/packages/spec/src/shared/suggestions.zod.ts +++ b/packages/spec/src/shared/suggestions.zod.ts @@ -242,6 +242,65 @@ export function keySetMatches(set: KeySetGuidance, key: string): boolean { return set.keys instanceof RegExp ? key.search(set.keys) !== -1 : set.keys.includes(key); } +/** + * One unknown key as the refusal names it: in backticks, the spelling the + * author typed. An EMPTY key is spelled out, because backticks around nothing + * render as an empty code span (or as two stray backticks), and the author is + * left looking for a key the message never shows. + */ +function renderUnknownKey(key: string): string { + return key === '' ? 'an empty key (`""`)' : `\`${key}\``; +} + +/** + * Edit distance in which swapping two adjacent letters costs ONE edit (the + * optimal-string-alignment variant of Levenshtein). Used only by + * {@link shortKeyScreenedGuess}; scoring for every other length is + * {@link levenshteinDistance}, unchanged. + */ +function adjacentSwapDistance(a: string, b: string): number { + const rows: number[][] = []; + for (let i = 0; i <= a.length; i++) { + rows.push([i]); + for (let j = 1; j <= b.length; j++) rows[i]![j] = i === 0 ? j : 0; + } + for (let i = 1; i <= a.length; i++) { + for (let j = 1; j <= b.length; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + let best = Math.min(rows[i - 1]![j]! + 1, rows[i]![j - 1]! + 1, rows[i - 1]![j - 1]! + cost); + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + best = Math.min(best, rows[i - 2]![j - 2]! + 1); + } + rows[i]![j] = best; + } + } + return rows[a.length]![b.length]!; +} + +/** + * The rename guess for one unknown key, or `undefined`. + * + * Above five characters this is {@link findClosestMatches}' first answer, + * exactly as before. At five characters or fewer the budget is the floor of 2, + * not a third of the key, and the floor exists for one slip: a swap of two + * adjacent letters, which plain Levenshtein charges as two edits (`nmae` → + * `name`). The same 2 also admits two UNRELATED edits, which on a four-letter + * key is half of it — `aria` → `areas` (one substitution, one insertion), a + * removed accessibility key answered with the app's navigation areas. So a + * short key's guess must be one edit away counting a swap as one; the candidates + * are still ranked by {@link findClosestMatches}, and the first that passes wins. + */ +function shortKeyScreenedGuess( + key: string, + knownKeys: readonly string[], + maxDistance: number, +): string | undefined { + if (Math.floor(key.length / 3) >= 2) return findClosestMatches(key, knownKeys, maxDistance, 1)[0]; + const folded = foldForScoring(key); + return findClosestMatches(key, knownKeys, maxDistance, knownKeys.length) + .find((candidate) => adjacentSwapDistance(folded, foldForScoring(candidate)) <= 1); +} + /** Options for {@link strictUnknownKeyError}. */ export interface StrictUnknownKeyErrorOptions { /** Prose name of the authoring surface the key was written on (e.g. `'this permission set'`). */ @@ -410,9 +469,13 @@ export function strictUnknownKeyError(options: StrictUnknownKeyErrorOptions): z. } continue; } + // An empty key names nothing, so nothing is a spelling of it: every + // declared key of two letters or fewer sits inside the budget, and the + // first of them would be offered as the fix. + if (key === '') continue; const maxDistance = Math.max(2, Math.floor(key.length / 3)); const declared = aliases[aliasProbe(key)]; - const guessed = declared ? undefined : findClosestMatches(key, knownKeys, maxDistance, 1)[0]; + const guessed = declared ? undefined : shortKeyScreenedGuess(key, knownKeys, maxDistance); // Screen the GUESS, never the declaration. `findClosestMatches` ranks by // edit distance and nothing else, so on a shape declaring both ends of a // range it answers a key that names neither end with whichever end is @@ -441,7 +504,7 @@ export function strictUnknownKeyError(options: StrictUnknownKeyErrorOptions): z. // an AI — reads the front of that line and acts on it, so the prescription // has to be there. Nothing is dropped or made conditional: the sentence is // still emitted verbatim, once per message, just last (#5955). - let message = `Unrecognized key(s) on ${surface}: ${keys.map((k) => `\`${k}\``).join(', ')}.`; + let message = `Unrecognized key(s) on ${surface}: ${keys.map(renderUnknownKey).join(', ')}.`; if (renames.length) message += ` Did you mean ${renames.join(', ')}?`; if (prescriptions.length) message += `\n${prescriptions.map((p) => ` • ${p}`).join('\n')}`; // The last fix channel, still ahead of `history`: where an aged-out