From 5bbad5fca75548a8dba100cc708572b4c32eb0ec Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:28:39 +0000 Subject: [PATCH 01/13] feat(spec): an action declares a refusal catalogue, the hook catalogue's twin ActionSchema.refusals keys by code the entry a hook's catalogue holds (one factory builds both), refuses a catalogue on an action that runs no js body, and refuses at save a code or reason the body throws literally that the catalogue does not declare. Translations sit beside the action's other copy: objects.OBJECT._actions.ACTION.refusals.CODE.message, or globalActions.ACTION.refusals.CODE.message for an object-less action. Claude-Session: https://claude.ai/code/session_01ADHkmP879Ku8wbNev27oyN Co-authored-by: Claude --- packages/spec/src/data/declared-entry.zod.ts | 338 +++++++++++++++++++ packages/spec/src/data/hook-refusal-codes.ts | 145 +++++++- packages/spec/src/data/hook.zod.ts | 210 +----------- packages/spec/src/system/i18n-resolver.ts | 33 ++ packages/spec/src/system/translation.zod.ts | 70 ++-- packages/spec/src/ui/action.zod.ts | 123 +++++++ 6 files changed, 686 insertions(+), 233 deletions(-) create mode 100644 packages/spec/src/data/declared-entry.zod.ts diff --git a/packages/spec/src/data/declared-entry.zod.ts b/packages/spec/src/data/declared-entry.zod.ts new file mode 100644 index 00000000000..956ef8d3b68 --- /dev/null +++ b/packages/spec/src/data/declared-entry.zod.ts @@ -0,0 +1,338 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The declared-entry factory: one sentence a declaration hands over in the + * source locale, keyed by name, translated whole, with `{{ }}` holes over the + * names it declares in `params`. Two kinds share it: + * + * - a **refusal** entry — `HookSchema.refusals` (#26170, maintainer ruling + * 6431311681 letter A; #33214, ruling 6879477573) and `ActionSchema.refusals` + * (#34273), keyed by code: `{ message, status?, reasons?, params? }`, read + * in the CALLER's locale when the code is thrown; + * - a **text** entry — `HookSchema.texts` (#34374, ruling 6913660232 + * parameter 7), keyed by snake_case key: `{ message, params? }`, read in + * the ORGANIZATION's language when the code asks for it (`ctx.text`). + * + * Both are built from the same core so they cannot drift: `message` (a + * trimmed, non-empty sentence), `params` (identifiers, each declared once), + * and one rule over every sentence of the entry — no `params`, plain text and + * a `{{ }}` hole is refused; with `params`, the closed-scope template rule over + * the declared names (`closedScopeTemplateRefusal`). The compile half of the + * same rule (logic, an unknown formatter, an empty hole, `currency` with no + * code) is `@objectstack/lint` `validate-hook-refusal-templates.ts`. + * + * Only the words differ per declaration — which subject the entry sits on, + * where its translation lives, who throws or asks for it. They are tables + * below, keyed by subject; a new subject is one row in a table, never a second + * transcription of the shape. Every sentence a row produces for `hook` is + * byte-identical to the schema it replaced, so the published JSON Schema and + * reference docs do not move. + * + * Not on any barrel: each entry schema is published by the declaration that + * carries it — {@link HookSchema}'s module exports `HookRefusalSchema` and + * `HookTextSchema`, `ui/action.zod.ts` exports `ActionRefusalSchema`. + */ + +import { z } from 'zod'; +import { lazySchema } from '../shared/lazy-schema'; +import { strictObject } from '../shared/strict-object'; +import { + ACTION_REFUSAL_MESSAGE_HOLE_REFUSED, + HOOK_REFUSAL_MESSAGE_HOLE_REFUSED, + HOOK_REFUSAL_MESSAGE_WITHOUT_HOLE, + HOOK_REFUSAL_PARAM_PATTERN, + HOOK_REFUSAL_REASON_PATTERN, + HOOK_TEXT_MESSAGE_HOLE_REFUSED, +} from './hook-refusal-codes'; +// [#33214] The closed-scope `{{ }}` judge a sentence with declared `params` is +// read by — the one the action copy slots and a bulk action's `confirmText` +// use, over the same hole grammar the flow `end` refusal renders. It imports +// nothing outside its own leaf. +import { closedScopeTemplateRefusal } from '../automation/flow-text-slot-template'; + +// ── The shared core ────────────────────────────────────────────────────────── + +/** How one subject's sentences are judged. */ +interface SentenceRule { + /** The slot a hole is judged in, as the refusal names it (e.g. A hook refusal `message`). */ + slot: string; + /** The refusal for a `{{ }}` hole in an entry that declares no `params`. */ + holeRefused: string; +} + +/** + * Why `message` is refused as a sentence of an entry declaring `params`, or + * `undefined`. No params: the plain-text rule (a hole is refused). Params: the + * closed-scope template rule over the declared names (a hole over a declared + * param only, a single-brace token prescribed its hole). + */ +function sentenceRefusal(rule: SentenceRule, message: string, params: readonly string[] | undefined): string | undefined { + if (!params || params.length === 0) { + return HOOK_REFUSAL_MESSAGE_WITHOUT_HOLE.test(message) ? undefined : rule.holeRefused; + } + return closedScopeTemplateRefusal(message, { slot: rule.slot, roots: params }); +} + +/** The entry's `params`: identifiers, the roots a `{{ }}` hole may name. */ +function paramsSchema(patternMessage: string, describe: string) { + return z.array(z.string().regex(HOOK_REFUSAL_PARAM_PATTERN, { message: patternMessage })).optional().describe(describe); +} + +/** + * The object-level check every entry runs: `params` names each root once, and + * the entry's own `message` plus every further sentence (`sentences`, path + * and text) follow the hole rule over those `params`. + */ +function refuseEntrySentences( + rule: SentenceRule, + entry: { message: string; params?: readonly string[] }, + further: ReadonlyArray<{ path: (string | number)[]; message: string }>, + ctx: z.RefinementCtx, +): void { + const params = entry.params; + if (params) { + const seen = new Set(); + params.forEach((name, i) => { + if (seen.has(name)) { + ctx.addIssue({ code: 'custom', path: ['params', i], message: `\`params\` names '${name}' twice — declare each once.` }); + } + seen.add(name); + }); + } + const own = sentenceRefusal(rule, entry.message, params); + if (own !== undefined) ctx.addIssue({ code: 'custom', path: ['message'], message: own }); + for (const sentence of further) { + const refusal = sentenceRefusal(rule, sentence.message, params); + if (refusal !== undefined) ctx.addIssue({ code: 'custom', path: sentence.path, message: refusal }); + } +} + +// ── Refusal entries ────────────────────────────────────────────────────────── + +/** The declarations a refusal catalogue sits on. */ +export type DeclaredRefusalSubject = 'hook' | 'action'; + +/** What a refusal entry's text says about its subject. */ +interface RefusalWords { + /** `hook` / `action`. */ + noun: DeclaredRefusalSubject; + /** The translation key of a code's message, as the describe text spells it. */ + messageKey: string; + /** The translation key of a reason's message, as the describe text spells it. */ + reasonKey: string; + /** Who throws the code, as the `code` guidance names it. */ + thrower: string; + /** The refusal for a `{{ }}` hole in an entry with no `params`. */ + holeRefused: string; +} + +const REFUSAL_WORDS: Record = { + hook: { + noun: 'hook', + messageKey: 'hooks..refusals..message', + reasonKey: 'hooks..refusals..reasons..message', + thrower: 'the body', + holeRefused: HOOK_REFUSAL_MESSAGE_HOLE_REFUSED, + }, + action: { + noun: 'action', + messageKey: + 'objects.._actions..refusals..message (globalActions..… for an object-less action)', + reasonKey: + 'objects.._actions..refusals..reasons..message ' + + '(globalActions..… for an object-less action)', + thrower: "the action's body", + holeRefused: ACTION_REFUSAL_MESSAGE_HOLE_REFUSED, + }, +}; + +/** + * One sentence under a declared refusal code (#33214, ruling 6879477573, + * S1): the sentence the user reads when the code is thrown with this reason. + * Its `{{ }}` holes are judged against the entry's `params`, like the entry's + * own message. Published only as part of an entry schema. + */ +function refusalReasonSchema(w: RefusalWords) { + return strictObject( + { + surface: `this ${w.noun} refusal reason`, + history: 'Closed from the day it was declared — a key this reason does not declare would be served nowhere.', + aliases: { text: 'message', description: 'message' }, + guidance: { + code: + 'A reason has no `code` of its own — it sits under the code it refines (`refusals.CODE.reasons.REASON`), and ' + + 'the wire code is that code.', + status: + 'A reason has no `status` of its own — the code it sits under decides the status. Declare a second code if ' + + 'the status differs.', + }, + }, + { + message: z.string().trim().min(1).describe( + `The sentence the user reads when the ${w.noun} throws this reason under its code — in the source locale, ` + + `translated through ${w.reasonKey} in the caller's locale; its {{ }} ` + + 'holes follow the entry\'s message rule', + ), + }, + ); +} + +/** + * One entry of a refusal catalogue (#26170): the sentence the user reads when + * the code is thrown, and the status the refusal is answered with. + * + * The message is handed over in the source locale and replaced whole by its + * translation — the validation-rule message's posture + * (`objects.._validations..message`). + * + * [#33214, ruling 6879477573] Two optional parts, both declared and counted: + * + * - `reasons` — further sentences under the SAME code, keyed by a snake_case + * reason. The code throws `{ code, reason }`; the runtime answers with the + * reason's sentence, the code's status and the code on the wire, unchanged. + * A reason the code does not declare is refused loudly, like a code. Under + * a code that declares no `reasons`, a thrown `reason` is not read, as before. + * - `params` — the names the entry's sentences may fill. The code throws + * `{ code, params: { NAME: value } }`, and each `{{ NAME }}` hole renders + * through the template engine the flow `end` refusal renders with. A hole + * over a name the entry does not declare is refused at parse; a hole + * holding logic, an unknown formatter, an empty hole and a `currency` + * formatter with no code (a refusal carries no default currency) are + * refused where the sentence is compiled — `os validate`, `compile` and the + * publish gate (`@objectstack/lint` `validate-hook-refusal-templates.ts`). + * An entry that declares no `params` is plain text and every `{{ }}` hole + * in it is refused, as before. + */ +export function declaredRefusalEntrySchema(subject: DeclaredRefusalSubject) { + const w = REFUSAL_WORDS[subject]; + const rule: SentenceRule = { slot: `A ${w.noun} refusal \`message\``, holeRefused: w.holeRefused }; + return lazySchema(() => strictObject( + { + surface: `this ${w.noun} refusal`, + history: 'Closed from the day it was declared — a key this entry does not declare would be served nowhere.', + aliases: { + text: 'message', reason: 'message', description: 'message', httpStatus: 'status', statusCode: 'status', + variants: 'reasons', messages: 'reasons', placeholders: 'params', parameters: 'params', variables: 'params', + }, + guidance: { + code: + '`code` is not a refusal key — the code is the entry\'s KEY in `refusals` ' + + `(\`refusals: { CLEAN_VERSION_REQUIRED: { message } }\`), and ${w.thrower} throws it.`, + title: + `A ${w.noun} refusal has no heading — the caller reads the \`message\` alone. Write the sentence in \`message\`.`, + }, + }, + { + message: z.string().trim().min(1).describe( + `The sentence the user reads when the ${w.noun} throws this code — in the source locale, translated whole through ` + + `${w.messageKey} in the caller's locale. With no params every {{ }} hole is refused; ` + + 'with params a hole is a path over one of them with an optional known formatter, and a hole over another name, ' + + 'a hole holding logic, an unknown formatter, an empty hole and a currency formatter with no code are refused', + ), + status: z.number().int().min(400).max(499).optional().describe( + 'HTTP status the refusal is answered with (4xx; a refusal is never a fault). Absent: 400. A status the ' + + 'body itself sets on the throw is not read — the catalogue decides', + ), + reasons: z.record( + z.string().regex(HOOK_REFUSAL_REASON_PATTERN, { + message: `A refusal reason is snake_case (e.g. plan_locked) — the reason the ${w.noun} throws beside the code`, + }), + lazySchema(() => refusalReasonSchema(w)), + ).optional().describe( + `Further sentences under this same code, keyed by the snake_case reason the ${w.noun} throws beside the code ` + + '({ code, reason }): { message }. The wire code and status stay this entry\'s. A reason not declared here ' + + 'is refused loudly. Absent: the code has the one sentence, and a thrown reason is not read', + ), + params: paramsSchema( + 'A refusal param is an identifier (e.g. state) — the root a {{ }} hole names', + 'The names this entry\'s sentences may fill: a {{ NAME }} or {{ NAME | formatter }} hole renders the value ' + + `the ${w.noun} throws in \`params\` ({ code, params: { NAME: value } }). A hole over any other name, logic, an ` + + 'unknown formatter, an empty hole and a currency formatter with no code are refused. Absent: the sentences ' + + 'are plain text and a {{ }} hole is refused', + ), + }, + ).superRefine((entry, ctx) => { + refuseEntrySentences( + rule, + entry, + Object.entries(entry.reasons ?? {}).map(([reason, sentence]) => ({ + path: ['reasons', reason, 'message'], + message: sentence.message, + })), + ctx, + ); + })); +} + +// ── Text entries ───────────────────────────────────────────────────────────── + +/** + * The declarations a text catalogue sits on. `hook` today (#34374 PR1); the + * action half of #34374 adds its row to {@link TEXT_WORDS}. + */ +export type DeclaredTextSubject = 'hook'; + +/** What a text entry's text says about its subject — each a whole sentence, so a row reads as it publishes. */ +interface TextWords { + /** The entry's `surface`. */ + surface: string; + /** The `locale` guidance: where the language comes from and where the translation lives. */ + localeGuidance: string; + /** `message`'s describe text. */ + messageDescribe: string; + /** The refusal for a `params` element that is not an identifier. */ + paramPatternMessage: string; + /** `params`'s describe text. */ + paramsDescribe: string; + /** How a sentence's holes are judged. */ + rule: SentenceRule; +} + +const TEXT_WORDS: Record = { + hook: { + surface: 'this hook text', + localeGuidance: + 'A hook text has no language of its own — the runtime picks the organization\'s language. Write the sentence ' + + 'in the source locale in `message` and translate it through `hooks.HOOK.texts.KEY.message`.', + messageDescribe: + 'The sentence the hook writes into a record — in the source locale, translated whole through ' + + 'hooks..texts..message in the organization\'s language when the hook asks for it (ctx.text). ' + + 'With no params every {{ }} hole is refused; with params a hole is a path over one of them with an optional ' + + 'known formatter', + paramPatternMessage: 'A text param is an identifier (e.g. lead) — the root a {{ }} hole names', + paramsDescribe: + 'The names this text may fill: a {{ NAME }} or {{ NAME | formatter }} hole renders the value the hook passes ' + + 'in ctx.text(KEY, { NAME: value }). A hole over any other name is refused at parse; a hole holding logic, an ' + + 'unknown formatter, an empty hole and a currency formatter with no code are refused where the text is compiled ' + + '(os validate, compile, the publish gate). Absent: the sentence is plain text and a {{ }} hole is refused', + rule: { slot: 'A hook text `message`', holeRefused: HOOK_TEXT_MESSAGE_HOLE_REFUSED }, + }, +}; + +/** + * One declared text (#34374, ruling 6913660232 parameter 7): a sentence the + * declaration writes into a record for people to read, picked in the + * ORGANIZATION's language when its code asks for it (`ctx.text(key, params)`). + * `{ message, params? }` — a refusal entry's core with no `status` or + * `reasons`: a text is written, never answered. + */ +export function declaredTextEntrySchema(subject: DeclaredTextSubject) { + const w = TEXT_WORDS[subject]; + return lazySchema(() => strictObject( + { + surface: w.surface, + history: 'Closed from the day it was declared — a key this entry does not declare would be served nowhere.', + aliases: { + text: 'message', template: 'message', value: 'message', description: 'message', + placeholders: 'params', parameters: 'params', variables: 'params', + }, + guidance: { locale: w.localeGuidance }, + }, + { + message: z.string().trim().min(1).describe(w.messageDescribe), + params: paramsSchema(w.paramPatternMessage, w.paramsDescribe), + }, + ).superRefine((entry, ctx) => { + refuseEntrySentences(w.rule, entry, [], ctx); + })); +} diff --git a/packages/spec/src/data/hook-refusal-codes.ts b/packages/spec/src/data/hook-refusal-codes.ts index 04f57a14941..843c8eeced5 100644 --- a/packages/spec/src/data/hook-refusal-codes.ts +++ b/packages/spec/src/data/hook-refusal-codes.ts @@ -254,11 +254,23 @@ export function undeclaredHookRefusalCodeAtSave( code: string, declared: readonly string[], at: 'body.source' | 'handler' = 'body.source', +): string { + return undeclaredRefusalCodeAtSave('hook', code, declared, at); +} + +/** [#34273] Which declaration a refusal catalogue sits on, as the sentences name it. */ +type RefusalSubject = 'hook' | 'action'; + +function undeclaredRefusalCodeAtSave( + subject: RefusalSubject, + code: string, + declared: readonly string[], + at: string, ): string { return ( - `\`${at}\` throws code '${code}', and this hook's \`refusals\` declares no such code ` - + `(declared: ${declaredList(declared)}). A hook that declares \`refusals\` refuses by code only, so the ` - + `throw is refused when the hook runs. Declare it under \`refusals.${code}\` with the message the user ` + `\`${at}\` throws code '${code}', and this ${subject}'s \`refusals\` declares no such code ` + + `(declared: ${declaredList(declared)}). A ${subject} that declares \`refusals\` refuses by code only, so the ` + + `throw is refused when the ${subject} runs. Declare it under \`refusals.${code}\` with the message the user ` + 'reads, or throw one of the declared codes.' ); } @@ -273,10 +285,18 @@ export function undeclaredHookRefusalCodeAtSave( export const HOOK_REFUSAL_MESSAGE_WITHOUT_HOLE = /^(?![\s\S]*\{\{[^{}]*\}\})[\s\S]*$/; /** The save-time refusal for a `{{ … }}` hole in a refusal message whose entry declares no `params`. */ -export const HOOK_REFUSAL_MESSAGE_HOLE_REFUSED = - 'A hook refusal `message` whose entry declares no `params` is plain text, and nothing fills a `{{ }}` hole: the ' - + 'caller would read the braces as written. Declare the name under the entry\'s `params` (`params: [\'state\']`) ' - + 'and throw it in the error\'s `params` (`{ code, params: { state } }`), or write the sentence without the hole.'; +export const HOOK_REFUSAL_MESSAGE_HOLE_REFUSED = refusalMessageHoleRefused('hook'); + +/** [#34273] The action twin of {@link HOOK_REFUSAL_MESSAGE_HOLE_REFUSED}. */ +export const ACTION_REFUSAL_MESSAGE_HOLE_REFUSED = refusalMessageHoleRefused('action'); + +function refusalMessageHoleRefused(subject: RefusalSubject): string { + return ( + `A ${subject} refusal \`message\` whose entry declares no \`params\` is plain text, and nothing fills a \`{{ }}\` hole: the ` + + 'caller would read the braces as written. Declare the name under the entry\'s `params` (`params: [\'state\']`) ' + + 'and throw it in the error\'s `params` (`{ code, params: { state } }`), or write the sentence without the hole.' + ); +} /** How a hook carrying `refusals` names the code that would answer it, for the sentence below. */ function refusalCarrier(language: string | undefined): string { @@ -305,11 +325,20 @@ export function undeclaredHookRefusalAtRun( hookName: string, code: string | undefined, declared: readonly string[], +): string { + return undeclaredRefusalAtRun('hook', hookName, code, declared); +} + +function undeclaredRefusalAtRun( + subject: RefusalSubject, + name: string, + code: string | undefined, + declared: readonly string[], ): string { const thrown = code === undefined ? 'threw no `code`' : `threw code '${code}'`; return ( - `hook '${hookName}' ${thrown}, and its \`refusals\` declares no such code (declared: ${declaredList(declared)}). ` - + 'A hook that declares `refusals` refuses by code only: throw an error whose `code` is one of the declared ' + `${subject} '${name}' ${thrown}, and its \`refusals\` declares no such code (declared: ${declaredList(declared)}). ` + + `A ${subject} that declares \`refusals\` refuses by code only: throw an error whose \`code\` is one of the declared ` + 'codes, or declare this one with the message the user reads.' ); } @@ -328,11 +357,21 @@ export function undeclaredHookRefusalReasonAtSave( reason: string, declared: readonly string[], at: 'body.source' | 'handler', +): string { + return undeclaredRefusalReasonAtSave('hook', code, reason, declared, at); +} + +function undeclaredRefusalReasonAtSave( + subject: RefusalSubject, + code: string, + reason: string, + declared: readonly string[], + at: string, ): string { return ( `\`${at}\` throws code '${code}' with reason '${reason}', and \`refusals.${code}.reasons\` declares no such ` + `reason (declared: ${reasonList(declared)}). A reason picks one of the code's declared sentences, so the ` - + `throw is refused when the hook runs. Declare it under \`refusals.${code}.reasons.${reason}\` with the ` + + `throw is refused when the ${subject} runs. Declare it under \`refusals.${code}.reasons.${reason}\` with the ` + 'message the user reads, or throw one of the declared reasons.' ); } @@ -347,9 +386,19 @@ export function undeclaredHookRefusalReasonAtRun( code: string, reason: string, declared: readonly string[], +): string { + return undeclaredRefusalReasonAtRun('hook', hookName, code, reason, declared); +} + +function undeclaredRefusalReasonAtRun( + subject: RefusalSubject, + name: string, + code: string, + reason: string, + declared: readonly string[], ): string { return ( - `hook '${hookName}' threw code '${code}' with reason '${reason}', and \`refusals.${code}.reasons\` declares ` + `${subject} '${name}' threw code '${code}' with reason '${reason}', and \`refusals.${code}.reasons\` declares ` + `no such reason (declared: ${reasonList(declared)}). A reason picks one of the code's declared sentences: ` + 'throw one of the declared reasons, or declare this one with the message the user reads.' ); @@ -443,3 +492,77 @@ export function undeclaredHookTextAtRun(hookName: string, key: string, declared: + 'declare it under `texts` with the sentence the record keeps, or ask for one of the declared keys.' ); } + +/* + * ── An action's refusal catalogue (#34273) ───────────────────────────────── + * + * `ActionSchema.refusals` is the hook catalogue's twin on an action: the same + * entry shape, the same literal reading of the code's throws at save, and the + * same run-time answer — the sentences below are the hook ones with the + * action named, built by the one subject-parameterised core above, so the two + * cannot drift. Where they differ is what an action runs: a sandboxed `js` + * `body` on a `script` action, or an inline `target` function `os build` + * lowers to one; and where its translation lives — beside the action's other + * copy, `objects.._actions..refusals.…` or, for an object-less + * action, `globalActions..refusals.…` (`actionRefusalMessageKey`). + */ + +/** The save-time refusal for a code an action's source throws literally that its `refusals` does not declare. */ +export function undeclaredActionRefusalCodeAtSave( + code: string, + declared: readonly string[], + at: 'body.source' | 'target' = 'body.source', +): string { + return undeclaredRefusalCodeAtSave('action', code, declared, at); +} + +/** The save-time refusal for a reason an action's source throws literally under a code that does not declare it. */ +export function undeclaredActionRefusalReasonAtSave( + code: string, + reason: string, + declared: readonly string[], + at: 'body.source' | 'target' = 'body.source', +): string { + return undeclaredRefusalReasonAtSave('action', code, reason, declared, at); +} + +/** The run-time fault for an action's throw its catalogue cannot answer: an undeclared code, or none. */ +export function undeclaredActionRefusalAtRun( + actionName: string, + code: string | undefined, + declared: readonly string[], +): string { + return undeclaredRefusalAtRun('action', actionName, code, declared); +} + +/** The run-time fault for a declared code an action threw with a reason the code does not declare. */ +export function undeclaredActionRefusalReasonAtRun( + actionName: string, + code: string, + reason: string, + declared: readonly string[], +): string { + return undeclaredRefusalReasonAtRun('action', actionName, code, reason, declared); +} + +/** + * The save-time refusal for a catalogue on an action whose code cannot throw a + * code: a type other than `script` (its `target` is a URL, page, flow or + * endpoint — a refused flow answers through its own `end` refusal), an + * `expression` body, or a `script` action with neither a body nor an inline + * `target` function. `os i18n` would demand its translations and nothing would + * serve them. + */ +export function actionRefusalsWithoutSandboxedBody(type: string, language: string | undefined): string { + const has = type !== 'script' + ? `\`type: '${type}'\`, which runs no code of the action's own` + : language !== undefined + ? `a \`${language}\` body` + : 'no `body` and no inline `target` function'; + return ( + "`refusals` is answered for a `type: 'script'` action's sandboxed `body` (`language: 'js'`) and for its inline " + + `\`target\` function (which \`os build\` lowers to a \`js\` body), and this action has ${has}: nothing it runs ` + + 'can throw a declared code, while `os i18n` still demanded its translations. Give the action a `js` body that ' + + 'throws the declared codes, or drop `refusals`.' + ); +} diff --git a/packages/spec/src/data/hook.zod.ts b/packages/spec/src/data/hook.zod.ts index f10091440e9..a57f8306aea 100644 --- a/packages/spec/src/data/hook.zod.ts +++ b/packages/spec/src/data/hook.zod.ts @@ -31,12 +31,7 @@ import type { IScopedContext } from '../contracts/scoped-context'; // reads too, so this schema's import graph is unchanged. import { HOOK_REFUSAL_CODE_PATTERN, - HOOK_REFUSAL_MESSAGE_HOLE_REFUSED, - HOOK_REFUSAL_MESSAGE_WITHOUT_HOLE, - HOOK_REFUSAL_PARAM_PATTERN, - HOOK_REFUSAL_REASON_PATTERN, HOOK_TEXT_KEY_PATTERN, - HOOK_TEXT_MESSAGE_HOLE_REFUSED, hookRefusalCodesThrownIn, hookRefusalReasonsThrownIn, hookRefusalsWithoutSandboxedBody, @@ -46,11 +41,9 @@ import { undeclaredHookRefusalReasonAtSave, undeclaredHookTextKeyAtSave, } from './hook-refusal-codes'; -// [#33214] The closed-scope `{{ }}` judge a refusal message with declared -// `params` is read by — the one the action copy slots and a bulk action's -// `confirmText` use, over the same hole grammar the flow `end` refusal -// renders. It imports nothing outside its own leaf. -import { closedScopeTemplateRefusal } from '../automation/flow-text-slot-template'; +// [#34273] One entry shape for a hook's and an action's refusal catalogue, and +// for a hook's declared texts (#34374) — the shared declared-entry factory. +import { declaredRefusalEntrySchema, declaredTextEntrySchema } from './declared-entry.zod'; /* * ── Unknown-key strictness (#4001 data step) ──────────────────────────────── @@ -372,151 +365,19 @@ function refuseUndeclaredLiteralTextKey( } } -/** - * One sentence under a declared refusal code (#33214, ruling 6879477573, - * S1): the sentence the user reads when the hook throws the code with this - * reason. Translated through `hooks..refusals..reasons..message`. - * Its `{{ }}` holes are judged against the entry's `params`, like the entry's - * own message. Not exported: it is published as part of {@link HookRefusalSchema}. - */ -const HookRefusalReasonSchema = lazySchema(() => strictObject( - { - surface: 'this hook refusal reason', - history: 'Closed from the day it was declared — a key this reason does not declare would be served nowhere.', - aliases: { text: 'message', description: 'message' }, - guidance: { - code: - 'A reason has no `code` of its own — it sits under the code it refines (`refusals.CODE.reasons.REASON`), and ' - + 'the wire code is that code.', - status: - 'A reason has no `status` of its own — the code it sits under decides the status. Declare a second code if ' - + 'the status differs.', - }, - }, - { - message: z.string().trim().min(1).describe( - 'The sentence the user reads when the hook throws this reason under its code — in the source locale, ' - + 'translated through hooks..refusals..reasons..message in the caller\'s locale; its {{ }} ' - + 'holes follow the entry\'s message rule', - ), - }, -)); - -/** The slot a refusal message's `{{ }}` holes are judged in, as a sentence names it. */ -const HOOK_REFUSAL_MESSAGE_SLOT = 'A hook refusal `message`'; - -/** - * Why `message` is refused as a sentence of an entry declaring `params`, or - * `undefined`. No params: the plain-text rule (a hole is refused). Params: the - * closed-scope template rule over the declared names (a hole over a declared - * param only, a single-brace token prescribed its hole). - */ -function hookRefusalMessageRefusal(message: string, params: readonly string[] | undefined): string | undefined { - if (!params || params.length === 0) { - return HOOK_REFUSAL_MESSAGE_WITHOUT_HOLE.test(message) ? undefined : HOOK_REFUSAL_MESSAGE_HOLE_REFUSED; - } - return closedScopeTemplateRefusal(message, { slot: HOOK_REFUSAL_MESSAGE_SLOT, roots: params }); -} - /** * One entry of a hook's refusal catalogue (#26170): the sentence the user * reads when the hook throws this entry's code, and the status the refusal is - * answered with. - * - * The message is handed over in the source locale and replaced whole by its - * translation, `hooks..refusals..message` — the validation-rule - * message's posture (`objects.._validations..message`). - * - * [#33214, ruling 6879477573] Two optional parts, both declared and counted: - * - * - `reasons` — further sentences under the SAME code, keyed by a snake_case - * reason. The hook throws `{ code, reason }`; the runtime answers with the - * reason's sentence, the code's status and the code on the wire, unchanged. - * A reason the code does not declare is refused loudly, like a code. Under - * a code that declares no `reasons`, a thrown `reason` is not read, as before. - * - `params` — the names the entry's sentences may fill. The hook throws - * `{ code, params: { NAME: value } }`, and each `{{ NAME }}` hole renders - * through the template engine the flow `end` refusal renders with. A hole - * over a name the entry does not declare is refused at parse; a hole - * holding logic, an unknown formatter, an empty hole and a `currency` - * formatter with no code (a hook refusal carries no default currency) are - * refused where the sentence is compiled — `os validate`, `compile` and the - * publish gate (`@objectstack/lint` `validate-hook-refusal-templates.ts`). - * An entry that declares no `params` is plain text and every `{{ }}` hole - * in it is refused, as before. + * answered with. The message is translated whole through + * `hooks..refusals..message`; `reasons` and `params` (#33214, + * ruling 6879477573) are documented on the shared factory + * (`declared-entry.zod.ts`), which builds `ActionSchema`'s catalogue + * entry (#34273) from the same rules, so the two cannot drift. */ -export const HookRefusalSchema = lazySchema(() => strictObject( - { - surface: 'this hook refusal', - history: 'Closed from the day it was declared — a key this entry does not declare would be served nowhere.', - aliases: { - text: 'message', reason: 'message', description: 'message', httpStatus: 'status', statusCode: 'status', - variants: 'reasons', messages: 'reasons', placeholders: 'params', parameters: 'params', variables: 'params', - }, - guidance: { - code: - '`code` is not a refusal key — the code is the entry\'s KEY in `refusals` ' - + '(`refusals: { CLEAN_VERSION_REQUIRED: { message } }`), and the body throws it.', - title: - 'A hook refusal has no heading — the caller reads the `message` alone. Write the sentence in `message`.', - }, - }, - { - message: z.string().trim().min(1).describe( - 'The sentence the user reads when the hook throws this code — in the source locale, translated whole through ' - + 'hooks..refusals..message in the caller\'s locale. With no params every {{ }} hole is refused; ' - + 'with params a hole is a path over one of them with an optional known formatter, and a hole over another name, ' - + 'a hole holding logic, an unknown formatter, an empty hole and a currency formatter with no code are refused', - ), - status: z.number().int().min(400).max(499).optional().describe( - 'HTTP status the refusal is answered with (4xx; a refusal is never a fault). Absent: 400. A status the ' - + 'body itself sets on the throw is not read — the catalogue decides', - ), - reasons: z.record( - z.string().regex(HOOK_REFUSAL_REASON_PATTERN, { - message: 'A refusal reason is snake_case (e.g. plan_locked) — the reason the hook throws beside the code', - }), - HookRefusalReasonSchema, - ).optional().describe( - 'Further sentences under this same code, keyed by the snake_case reason the hook throws beside the code ' - + '({ code, reason }): { message }. The wire code and status stay this entry\'s. A reason not declared here ' - + 'is refused loudly. Absent: the code has the one sentence, and a thrown reason is not read', - ), - params: z.array( - z.string().regex(HOOK_REFUSAL_PARAM_PATTERN, { - message: 'A refusal param is an identifier (e.g. state) — the root a {{ }} hole names', - }), - ).optional().describe( - 'The names this entry\'s sentences may fill: a {{ NAME }} or {{ NAME | formatter }} hole renders the value ' - + 'the hook throws in `params` ({ code, params: { NAME: value } }). A hole over any other name, logic, an ' - + 'unknown formatter, an empty hole and a currency formatter with no code are refused. Absent: the sentences ' - + 'are plain text and a {{ }} hole is refused', - ), - }, -).superRefine((entry, ctx) => { - const params = entry.params; - if (params) { - const seen = new Set(); - params.forEach((name, i) => { - if (seen.has(name)) { - ctx.addIssue({ code: 'custom', path: ['params', i], message: `\`params\` names '${name}' twice — declare each once.` }); - } - seen.add(name); - }); - } - const own = hookRefusalMessageRefusal(entry.message, params); - if (own !== undefined) ctx.addIssue({ code: 'custom', path: ['message'], message: own }); - for (const [reason, sentence] of Object.entries(entry.reasons ?? {})) { - const refusal = hookRefusalMessageRefusal(sentence.message, params); - if (refusal !== undefined) ctx.addIssue({ code: 'custom', path: ['reasons', reason, 'message'], message: refusal }); - } -})); +export const HookRefusalSchema = declaredRefusalEntrySchema('hook'); export type HookRefusal = z.input; -/** The slot a hook text's `{{ }}` holes are judged in, as a sentence names it. */ -const HOOK_TEXT_MESSAGE_SLOT = 'A hook text `message`'; - /** * One declared text of a hook (#34374, ruling 6913660232 parameter 7): a * sentence the hook writes into a record for people to read, picked in the @@ -533,56 +394,11 @@ const HOOK_TEXT_MESSAGE_SLOT = 'A hook text `message`'; * `os validate`, `compile` and the publish gate (`@objectstack/lint` * `validate-hook-refusal-templates.ts`, which judges `texts` beside * `refusals`). A translation whose holes do not render at run time is dropped - * for this `message`, filled. + * for this `message`, filled. Built by the shared declared-entry factory + * (`declared-entry.zod.ts`), the refusal entry's core with no `status` or + * `reasons`, which the action half of #34374 reuses. */ -export const HookTextSchema = lazySchema(() => strictObject( - { - surface: 'this hook text', - history: 'Closed from the day it was declared — a key this entry does not declare would be served nowhere.', - aliases: { - text: 'message', template: 'message', value: 'message', description: 'message', - placeholders: 'params', parameters: 'params', variables: 'params', - }, - guidance: { - locale: - 'A hook text has no language of its own — the runtime picks the organization\'s language. Write the sentence ' - + 'in the source locale in `message` and translate it through `hooks.HOOK.texts.KEY.message`.', - }, - }, - { - message: z.string().trim().min(1).describe( - 'The sentence the hook writes into a record — in the source locale, translated whole through ' - + 'hooks..texts..message in the organization\'s language when the hook asks for it (ctx.text). ' - + 'With no params every {{ }} hole is refused; with params a hole is a path over one of them with an optional ' - + 'known formatter', - ), - params: z.array( - z.string().regex(HOOK_REFUSAL_PARAM_PATTERN, { - message: 'A text param is an identifier (e.g. lead) — the root a {{ }} hole names', - }), - ).optional().describe( - 'The names this text may fill: a {{ NAME }} or {{ NAME | formatter }} hole renders the value the hook passes ' - + 'in ctx.text(KEY, { NAME: value }). A hole over any other name is refused at parse; a hole holding logic, an ' - + 'unknown formatter, an empty hole and a currency formatter with no code are refused where the text is compiled ' - + '(os validate, compile, the publish gate). Absent: the sentence is plain text and a {{ }} hole is refused', - ), - }, -).superRefine((entry, ctx) => { - const params = entry.params; - if (params) { - const seen = new Set(); - params.forEach((name, i) => { - if (seen.has(name)) { - ctx.addIssue({ code: 'custom', path: ['params', i], message: `\`params\` names '${name}' twice — declare each once.` }); - } - seen.add(name); - }); - } - const refusal = !params || params.length === 0 - ? (HOOK_REFUSAL_MESSAGE_WITHOUT_HOLE.test(entry.message) ? undefined : HOOK_TEXT_MESSAGE_HOLE_REFUSED) - : closedScopeTemplateRefusal(entry.message, { slot: HOOK_TEXT_MESSAGE_SLOT, roots: params }); - if (refusal !== undefined) ctx.addIssue({ code: 'custom', path: ['message'], message: refusal }); -})); +export const HookTextSchema = declaredTextEntrySchema('hook'); export type HookText = z.input; diff --git a/packages/spec/src/system/i18n-resolver.ts b/packages/spec/src/system/i18n-resolver.ts index 1b76faae1a6..76f38f13adf 100644 --- a/packages/spec/src/system/i18n-resolver.ts +++ b/packages/spec/src/system/i18n-resolver.ts @@ -4460,6 +4460,39 @@ export function hookTextMessageKey(hookName: string, key: string): string { return `hooks.${hookName}.texts.${key}.message`; } +/** + * Dot-notation i18n key for an action's declared refusal message (#34273, + * `ActionSchema.refusals`) — the hook twin of {@link hookRefusalMessageKey}, + * at the address every action translation is read at + * ({@link actionTranslationNode}): + * + * - a bound action: `objects.._actions..refusals..message`; + * - an object-less action: `globalActions..refusals..message`; + * + * and, given a declared reason under the code, + * `….refusals..reasons..message`. + * + * Used by the action body runner, which answers a throw of a declared code + * with this translation in the caller's locale (`ExecutionContext.locale`), + * the declared sentence on a miss. `objectName` is the action's OWN object — + * `objectName` on its declaration, or the object that declares it inline — + * never the object a caller routed it under, so a bound action never reads + * `globalActions` and an object-less one never reads an object's group. + */ +export function actionRefusalMessageKey( + objectName: string | undefined, + actionName: string, + code: string, + reason?: string, +): string { + const node = typeof objectName === 'string' && objectName.length > 0 + ? `objects.${objectName}._actions.${actionName}` + : `globalActions.${actionName}`; + return reason === undefined + ? `${node}.refusals.${code}.message` + : `${node}.refusals.${code}.reasons.${reason}.message`; +} + /** * Dot-notation i18n key for a screen's heading or body text — * `flows..screens..title` / `.description` (#22507). diff --git a/packages/spec/src/system/translation.zod.ts b/packages/spec/src/system/translation.zod.ts index bf3c2385df4..abf7bad6f91 100644 --- a/packages/spec/src/system/translation.zod.ts +++ b/packages/spec/src/system/translation.zod.ts @@ -329,6 +329,38 @@ const ActionPreflightTranslationSchema = lazySchema(() => strictObject({ .describe('Preflight panel field labels keyed by the literal field path declared in the action metadata (keys may contain dots)'), }).describe('Translations for an action preflight panel')); +/** + * The translations of a declared refusal catalogue, keyed by code — one shape + * for `hooks..refusals` (#26170, #33214) and an action's + * `….refusals` (#34273, under `objects.._actions.` or + * `globalActions.`), built by one factory so the two cannot drift. + */ +const refusalTranslationsSchema = (noun: 'hook' | 'action') => z.record(z.string(), strictObject({ + surface: `this ${noun} refusal translation`, + history: TRANSLATION_HISTORY, + // The spellings the refusal entry schema renames onto its own `message` and `reasons`. + aliases: { text: 'message', reason: 'message', description: 'message', variants: 'reasons', messages: 'reasons' }, +}, { + // The declared message's own form — plain text, or a template over the + // entry's declared `params`; an empty string is the untranslated + // skeleton slot `os i18n extract` writes (the declared message is served). + message: z.string().optional().describe( + `Translated refusal message of a ${noun}'s declared refusal code — served whole in the caller's locale in ` + + 'place of the declared message, its {{ }} holes (over the entry\'s declared params) filled after', + ), + // [#33214] A declared reason's sentence under the same code. + reasons: z.record(z.string(), strictObject({ + surface: `this ${noun} refusal reason translation`, + history: TRANSLATION_HISTORY, + aliases: { text: 'message', description: 'message' }, + }, { + message: z.string().optional().describe( + `Translated sentence of a declared reason under a ${noun}'s refusal code — served in place of the declared ` + + 'reason message, its {{ }} holes filled after', + ), + })).optional().describe("Reason translations keyed by the reason the code's `reasons` declares"), +})).optional().describe(`Refusal translations keyed by the code the ${noun}'s \`refusals\` declares`); + /** * Action translations — one shape, used at two addresses: an object's * `_actions.` and the top-level `globalActions.` (the same split @@ -352,6 +384,7 @@ const actionTranslationSchema = (surface: string) => strictObject({ cancelLabel: 'cancelText', parameters: 'params', args: 'params', inputs: 'params', result: 'resultDialog', dialog: 'resultDialog', + refusal: 'refusals', }, }, { label: z.string().optional().describe('Translated action label'), @@ -404,6 +437,13 @@ const actionTranslationSchema = (surface: string) => strictObject({ // fields the action declares. preflight: ActionPreflightTranslationSchema.optional() .describe('Translations for the action preflight panel'), + // [#34273] `ActionSchema.refusals` — one translated sentence per declared + // refusal code (and per declared reason under it), picked by the action + // body runner in the caller's locale through `actionRefusalMessageKey` + // (`system/i18n-resolver.ts`) before the refusal leaves the server, the + // declared sentence on a miss. Server-rendered like a hook refusal, so no + // client overlay reads it. + refusals: refusalTranslationsSchema('action'), }); /** @@ -680,6 +720,8 @@ export const ObjectTranslationDataSchema = lazySchema(() => strictObject({ * objects.._actions..params..options. * objects.._actions..resultDialog.* * objects.._actions..preflight.fields. + * objects.._actions..refusals..message (#34273, `ActionSchema.refusals`) + * objects.._actions..refusals..reasons..message */ _actions: z.record(z.string(), actionTranslationSchema('this object action translation')) .optional().describe('Action translations keyed by action name'), @@ -1209,6 +1251,8 @@ const appTranslationDataShape = () => ({ * globalActions..params..options. * globalActions..resultDialog.* * globalActions..preflight.fields. + * globalActions..refusals..message (#34273, `ActionSchema.refusals`) + * globalActions..refusals..reasons..message */ globalActions: z.record(z.string(), actionTranslationSchema('this global action translation')) .optional().describe('Global action translations keyed by action name'), @@ -2150,31 +2194,7 @@ const appTranslationDataShape = () => ({ + 'writes into records. Translate `refusals..message` or `texts..message`.', }, }, { - refusals: z.record(z.string(), strictObject({ - surface: 'this hook refusal translation', - history: TRANSLATION_HISTORY, - // The spellings `HookRefusalSchema` renames onto its own `message` and `reasons`. - aliases: { text: 'message', reason: 'message', description: 'message', variants: 'reasons', messages: 'reasons' }, - }, { - // The declared message's own form — plain text, or a template over the - // entry's declared `params`; an empty string is the untranslated - // skeleton slot `os i18n extract` writes (the declared message is served). - message: z.string().optional().describe( - "Translated refusal message of a hook's declared refusal code — served whole in the caller's locale in " - + 'place of the declared message, its {{ }} holes (over the entry\'s declared params) filled after', - ), - // [#33214] A declared reason's sentence under the same code. - reasons: z.record(z.string(), strictObject({ - surface: 'this hook refusal reason translation', - history: TRANSLATION_HISTORY, - aliases: { text: 'message', description: 'message' }, - }, { - message: z.string().optional().describe( - "Translated sentence of a declared reason under a hook's refusal code — served in place of the declared " - + 'reason message, its {{ }} holes filled after', - ), - })).optional().describe("Reason translations keyed by the reason the code's `reasons` declares"), - })).optional().describe("Refusal translations keyed by the code the hook's `refusals` declares"), + refusals: refusalTranslationsSchema('hook'), // [#34374] A declared text's sentence, picked in the organization's language. texts: z.record(z.string(), strictObject({ surface: 'this hook text translation', diff --git a/packages/spec/src/ui/action.zod.ts b/packages/spec/src/ui/action.zod.ts index 18c781bd295..e9c74b24f9e 100644 --- a/packages/spec/src/ui/action.zod.ts +++ b/packages/spec/src/ui/action.zod.ts @@ -36,6 +36,17 @@ import { } from './action-copy-template'; import { templateExpressionInput } from '../shared/typed-expression-input'; import { HookBodySchema } from '../data/hook-body.zod'; +// [#34273] An action's refusal catalogue: the hook catalogue's entry shape, +// code spelling, literal-throw reading and sentences — import-free leaves. +import { declaredRefusalEntrySchema } from '../data/declared-entry.zod'; +import { + HOOK_REFUSAL_CODE_PATTERN, + actionRefusalsWithoutSandboxedBody, + hookRefusalCodesThrownIn, + hookRefusalReasonsThrownIn, + undeclaredActionRefusalCodeAtSave, + undeclaredActionRefusalReasonAtSave, +} from '../data/hook-refusal-codes'; // [#25653] Import-free leaf, shared with `HookSchema`: the identity-assignment // set, the body-source reading and the refusal text. import { @@ -1459,6 +1470,60 @@ const actionObject = () => strictObject({ + "An action body runs as system, and its update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' is refused with PERMISSION_DENIED; an insert is not judged by this rule.", ), + /** + * The action's refusal catalogue (#34273) — the twin of + * `HookSchema.refusals` (#26170, ruling 6431311681 letter A; #33214, + * ruling 6879477573), entry for entry: every refusal the action's body may + * throw, keyed by the code it throws. + * + * refusals: { + * SIGN_IN_REQUIRED: { message: 'Sign in to rate this article.', status: 401 }, + * STAGE_LOCKED: { + * message: 'This stage change is not allowed.', + * params: ['stage'], + * reasons: { closed: { message: 'A {{ stage }} opportunity can no longer change stage.' } }, + * }, + * } + * + * The body refuses by code only — it throws an error carrying a declared + * `code`, optionally a declared `reason` and the `params` its sentence + * names — and the runtime answers with that entry: its `message` (or the + * reason's), translated in the caller's locale with the declared sentence + * as the fallback, its holes filled from `params`, marked as the end user's + * sentence (`userMessage`), and its `status`. The translation sits beside + * the action's other copy: `objects.._actions..refusals..message` + * (`….reasons..message`), or `globalActions..refusals.…` for + * an object-less action — the address every action translation is read at. + * + * A code the catalogue does not declare, a reason a code with `reasons` + * does not declare, or a throw with no code, is refused loudly: at save + * where the body's source names it literally, otherwise when it runs, as a + * fault naming the action and the code. An error a host call raised and + * the body let through unchanged (a `ctx.api` write refused by the engine, + * a hook's refusal under it) passes through as before, and so does a crash. + * + * Answered where an action runs code of its own: a `type: 'script'` + * action's sandboxed `js` body — which is also what `os build` lowers an + * inline `target` function to. Refused on every other action: another + * `type` (its `target` is a URL, page, flow or endpoint), an `expression` + * body, or no body. Absent: the action's throws are answered as they + * always were. + */ + refusals: z.record( + z.string().regex(HOOK_REFUSAL_CODE_PATTERN, { + message: 'A refusal code is SCREAMING_SNAKE (e.g. SIGN_IN_REQUIRED) — the error code the body throws', + }), + ActionRefusalSchema, + ).optional().describe( + 'Refusal catalogue keyed by the SCREAMING_SNAKE code the action\'s js body throws: { message, status?, reasons?, ' + + 'params? }. The body refuses by code only, optionally with a declared reason and params; the runtime answers with ' + + 'the declared message (translated through objects.._actions..refusals..message, or ' + + 'globalActions..refusals..message for an object-less action, ….reasons..message for a ' + + 'reason, in the caller\'s locale, holes filled from params) and status. A code not declared here, or a reason a ' + + 'code with reasons does not declare, is refused loudly — at save when the body throws it literally, otherwise at ' + + 'run time. Only a type: \'script\' action with a js body declares one', + ), + /** * The declarative single-record field write — the row-level counterpart of * a list view's `bulkActionDefs` `{ operation: 'update', patch }` (#14092, @@ -2498,6 +2563,63 @@ function refuseUnopenableOnSuccessNavigate( * performs no IO, and reads of the four objects stay legal, as at run time. * `HookSchema` carries the same check for a `runAs: 'system'` hook. */ +/** + * [#34273] One entry of an action's refusal catalogue (`ActionSchema.refusals`): + * the sentence the user reads when the action's body throws the entry's code, + * and the status the refusal is answered with. The same entry a hook's + * catalogue holds (`HookRefusalSchema`), built by the one factory so the two + * cannot drift; only its words name the action and its translation address. + */ +export const ActionRefusalSchema = declaredRefusalEntrySchema('action'); + +export type ActionRefusal = z.input; + +/** + * [#34273] The object-level check on an action's `refusals`, the twin of + * `HookSchema`'s: a catalogue nothing the action runs could answer is + * refused at `refusals`, and a code (or a reason under a code that declares + * `reasons`) the body's source throws literally that the catalogue does not + * declare is refused at `body.source`, one issue each. A code that arrives any + * other way is the run-time refusal's. + */ +function refuseUndeclaredLiteralActionRefusalCode( + data: { + type?: string; + body?: { language?: string; source?: unknown }; + refusals?: Record } | undefined>; + }, + ctx: z.core.$RefinementCtx, +): void { + if (!data.refusals) return; + const type = data.type ?? 'script'; + if (type !== 'script' || data.body?.language !== 'js') { + ctx.addIssue({ + code: 'custom', + path: ['refusals'], + message: actionRefusalsWithoutSandboxedBody(type, data.body?.language), + }); + return; + } + const source = data.body.source; + if (typeof source !== 'string') return; + const declared = Object.keys(data.refusals); + for (const code of hookRefusalCodesThrownIn(source)) { + if (Object.prototype.hasOwnProperty.call(data.refusals, code)) continue; + ctx.addIssue({ code: 'custom', path: ['body', 'source'], message: undeclaredActionRefusalCodeAtSave(code, declared) }); + } + for (const { code, reason } of hookRefusalReasonsThrownIn(source)) { + if (!Object.prototype.hasOwnProperty.call(data.refusals, code)) continue; + // Read only under a code that declares `reasons`, as on a hook. + const reasons = data.refusals[code]?.reasons; + if (!reasons || Object.prototype.hasOwnProperty.call(reasons, reason)) continue; + ctx.addIssue({ + code: 'custom', + path: ['body', 'source'], + message: undeclaredActionRefusalReasonAtSave(code, reason, Object.keys(reasons)), + }); + } +} + function refuseIdentityAssignmentBodyWrite( data: { type?: string; body?: { language?: string; source?: unknown } }, ctx: z.core.$RefinementCtx, @@ -2998,6 +3120,7 @@ export const ActionSchema = lazySchema(() => actionObject().refine((data) => { }).superRefine(refuseDeclarativeUpdateContradictions(ACTION_DECLARATIVE_UPDATE)) .superRefine(refuseInertOutcomeMessages) .superRefine(refuseIdentityAssignmentBodyWrite) + .superRefine(refuseUndeclaredLiteralActionRefusalCode) .superRefine(refusePreflightContradictions) // Grade gate first, feature gate last: `requiresFeature` composes onto // whatever `visible` it finds, so this order keeps `features.*` the final From 96e562a044177573e83b4deb65cd90bdcb49a714 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:32:59 +0000 Subject: [PATCH 02/13] wip(runtime,lint): answer an action body's throw against its refusal catalogue Claude-Session: https://claude.ai/code/session_01ADHkmP879Ku8wbNev27oyN Co-authored-by: Claude --- packages/lint/src/i18n-walk.ts | 41 +++++ packages/lint/src/validate-expressions.ts | 5 +- .../src/validate-hook-refusal-templates.ts | 79 ++++++++- packages/runtime/src/app-artifact-handlers.ts | 4 +- packages/runtime/src/app-plugin.ts | 2 + packages/runtime/src/sandbox/body-runner.ts | 19 ++- .../src/sandbox/hook-refusal-catalogue.ts | 152 +++++++++++++++--- 7 files changed, 274 insertions(+), 28 deletions(-) diff --git a/packages/lint/src/i18n-walk.ts b/packages/lint/src/i18n-walk.ts index 225c5f24cf3..1e36aa72fb6 100644 --- a/packages/lint/src/i18n-walk.ts +++ b/packages/lint/src/i18n-walk.ts @@ -140,7 +140,12 @@ * (see `authorWarnedTranslationGroups`) * hooks..refusals..message (#26170) * hooks..refusals..reasons..message (#33214) +<<<<<<< HEAD * hooks..texts..message (#34374) +======= + * objects.._actions..refusals..message (#34273; and + * globalActions..refusals..message, with `.reasons..message` under each) +>>>>>>> f0e42de65 (wip(runtime,lint): answer an action body's throw against its refusal catalogue) * positions..label / .description * permissions..label / .description * books..label / .description @@ -796,6 +801,40 @@ function pushActionOutcomeMessages( } } +/** + * [#34273] Emit `.refusals..message` for every entry an + * action's refusal catalogue declares (`ActionSchema.refusals`), and + * `….reasons..message` for each reason under it — seeded with the + * declared sentence, as {@link walkHookRefusals} seeds a hook's. The action + * body runner reads exactly that key (`actionRefusalMessageKey`) in the + * caller's locale, so each entry is one demand, under the action's own root: + * `objects.._actions.` or `globalActions.`. + */ +function pushActionRefusals( + out: ExpectedEntry[], + actionRoot: string[], + action: any, + kind: ExpectedEntry['source'], + objectName?: string, +): void { + const refusals = action?.refusals; + if (!refusals || typeof refusals !== 'object' || Array.isArray(refusals)) return; + for (const [code, entry] of Object.entries(refusals)) { + pushOptional(out, [...actionRoot, 'refusals', code, 'message'], inlineText(entry?.message), kind, { objectName }); + const reasons = entry?.reasons; + if (!reasons || typeof reasons !== 'object' || Array.isArray(reasons)) continue; + for (const [reason, sentence] of Object.entries(reasons)) { + pushOptional( + out, + [...actionRoot, 'refusals', code, 'reasons', reason, 'message'], + inlineText(sentence?.message), + kind, + { objectName }, + ); + } + } +} + function pushActionResultDialog( out: ExpectedEntry[], actionRoot: string[], @@ -1523,6 +1562,7 @@ export function collectExpectedEntries( pushActionParams(out, ['objects', objectName, '_actions', aname], action, 'action', objectName); pushActionResultDialog(out, ['objects', objectName, '_actions', aname], action, 'action', objectName); pushActionPreflight(out, ['objects', objectName, '_actions', aname], action, 'action', objectName); + pushActionRefusals(out, ['objects', objectName, '_actions', aname], action, 'action', objectName); } } @@ -1623,6 +1663,7 @@ export function collectExpectedEntries( pushActionParams(out, root, action, kind, objectName); pushActionResultDialog(out, root, action, kind, objectName); pushActionPreflight(out, root, action, kind, objectName); + pushActionRefusals(out, root, action, kind, objectName); } // ── Apps + navigation ──────────────────────────────────────────── diff --git a/packages/lint/src/validate-expressions.ts b/packages/lint/src/validate-expressions.ts index add3f7ac219..b1347352e34 100644 --- a/packages/lint/src/validate-expressions.ts +++ b/packages/lint/src/validate-expressions.ts @@ -117,7 +117,7 @@ import { bulkConfirmTemplateRoots } from '@objectstack/spec/ui'; // [#24814] An action's copy — `confirmText`, `successMessage`, `errorMessage` — // is a `template` slot too, judged in its own module by the same judge. import { actionCopyTemplateIssues } from './validate-action-copy-templates.js'; -import { hookRefusalTemplateIssues } from './validate-hook-refusal-templates.js'; +import { actionRefusalTemplateIssues, hookRefusalTemplateIssues } from './validate-hook-refusal-templates.js'; // [#15137] The `value`-role half. Same two published primitives the engine // composes at `registerFlow` (`AutomationEngine.valueEnvelopeRefusals`), in the // same order: the SHAPE rule lives in the spec's `FlowValueSlotSchema` (the @@ -4675,6 +4675,9 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression // pages' action rows off an object write. Errors since #25680, a holeless // `${…}` sentence included since #25709. issues.push(...actionCopyTemplateIssues(stack, { actions: !objectWrite, objects: true, pages: !objectWrite })); + // [#34273] An action refusal sentence over declared `params` — the hook + // refusal's compile half, on the same collections the copy pass reads. + issues.push(...actionRefusalTemplateIssues(stack, { actions: !objectWrite, objects: true })); return issues; } diff --git a/packages/lint/src/validate-hook-refusal-templates.ts b/packages/lint/src/validate-hook-refusal-templates.ts index a77a3ecd310..4a6ab2f3347 100644 --- a/packages/lint/src/validate-hook-refusal-templates.ts +++ b/packages/lint/src/validate-hook-refusal-templates.ts @@ -32,6 +32,10 @@ * this pass with the hook-`condition` walk it sits beside). An entry that * declares no `params` is plain text and the parse refuses every hole in it, * so it is not read here. + * + * [#34273] An action's refusal catalogue (`ActionSchema.refusals`) is the same + * entry, so {@link actionRefusalTemplateIssues} judges it by the same rules, + * on the action collections the action copy pass reads. */ import { validateExpression } from '@objectstack/formula'; @@ -51,19 +55,50 @@ function paramsOf(entry: AnyRec): string[] { } /** The refusal of an argument-less `currency` formatter in one hole, or `undefined`. */ -function currencyWithoutCode(holeText: string, inner: string): string | undefined { +function currencyWithoutCode(holeText: string, inner: string, noun: 'hook' | 'action'): string | undefined { const bar = inner.indexOf('|'); if (bar === -1) return undefined; const formatter = inner.slice(bar + 1).trim(); if (formatter !== 'currency') return undefined; const path = inner.slice(0, bar).trim() || 'amount'; return ( +<<<<<<< HEAD `\`${holeText}\` formats in the organization's default currency, which a hook sentence does not carry, so the ` +======= + `\`${holeText}\` formats in the organization's default currency, which a ${noun} refusal does not carry, so the ` +>>>>>>> f0e42de65 (wip(runtime,lint): answer an action body's throw against its refusal catalogue) + 'sentence would be served with its braces. Name the code in the hole: ' + `\`{{ ${path} | currency:EUR }}\`.` ); } +/** Every finding one refusal catalogue draws, each located at `owner` + the sentence's path. */ +function judgeCatalogue(issues: ExprIssue[], refusals: AnyRec, owner: string, noun: 'hook' | 'action'): void { + for (const [code, entry] of Object.entries(refusals)) { + if (!isRec(entry)) continue; + const params = paramsOf(entry); + if (params.length === 0) continue; + const sentences: Array<{ path: string; text: unknown }> = [{ path: `refusals.${code}.message`, text: entry.message }]; + if (isRec(entry.reasons)) { + for (const [reason, sentence] of Object.entries(entry.reasons)) { + sentences.push({ path: `refusals.${code}.reasons.${reason}.message`, text: isRec(sentence) ? sentence.message : undefined }); + } + } + for (const { path, text } of sentences) { + if (typeof text !== 'string') continue; + const where = `${owner} ${path}`; + const refuse = (message: string, source: string): void => { + issues.push({ where, message, source, severity: 'error' }); + }; + for (const m of text.matchAll(HOLE)) { + const refusal = currencyWithoutCode(m[0], m[1]!, noun); + if (refusal !== undefined) refuse(refusal, m[0]); + } + for (const e of validateExpression('template', text).errors) refuse(e.message, e.source); + } + } +} + /** * The findings for every hook sentence of `stack` whose entry declares * `params` — each refusal entry's `message` and `reasons[*].message`, and @@ -73,6 +108,7 @@ export function hookRefusalTemplateIssues(stack: AnyRec): ExprIssue[] { const issues: ExprIssue[] = []; for (const hook of recordsOf(stack.hooks)) { const hookName = typeof hook.name === 'string' ? hook.name : '?'; +<<<<<<< HEAD const sentences: Array<{ path: string; text: unknown }> = []; if (isRec(hook.refusals)) { for (const [code, entry] of Object.entries(hook.refusals)) { @@ -90,6 +126,47 @@ export function hookRefusalTemplateIssues(stack: AnyRec): ExprIssue[] { if (!isRec(entry) || paramsOf(entry).length === 0) continue; sentences.push({ path: `texts.${key}.message`, text: entry.message }); } +======= + if (!isRec(hook.refusals)) continue; + judgeCatalogue(issues, hook.refusals, `hook '${hookName}'`, 'hook'); + } + return issues; +} + +/** Which action collections one run judges — the publish gate narrows them per write type. */ +export interface ActionRefusalTemplateScope { + /** The stack's top-level `actions[]`. */ + readonly actions: boolean; + /** Each object's own `actions[]`. */ + readonly objects: boolean; +} + +/** + * [#34273] The same findings for an action's refusal catalogue + * (`ActionSchema.refusals`, the hook catalogue's twin), across the + * collections `scope` names. An action declared both top-level and on its + * object is judged once, at the first place it is met — the de-duplication + * the action copy pass applies. + */ +export function actionRefusalTemplateIssues(stack: AnyRec, scope: ActionRefusalTemplateScope): ExprIssue[] { + const issues: ExprIssue[] = []; + const seen = new Set(); + const judge = (owner: string, action: AnyRec, objectName?: string): void => { + const name = typeof action.name === 'string' ? action.name : '?'; + const bound = objectName ?? (typeof action.objectName === 'string' ? action.objectName : ''); + const key = `${bound}:${name}`; + if (seen.has(key)) return; + seen.add(key); + if (isRec(action.refusals)) judgeCatalogue(issues, action.refusals, `${owner} · action '${name}'`, 'action'); + }; + if (scope.actions) { + for (const action of recordsOf(stack.actions)) judge('stack', action); + } + if (scope.objects) { + for (const object of recordsOf(stack.objects)) { + const objectName = typeof object.name === 'string' ? object.name : undefined; + for (const action of recordsOf(object.actions)) judge(`object '${objectName ?? '?'}'`, action, objectName); +>>>>>>> f0e42de65 (wip(runtime,lint): answer an action body's throw against its refusal catalogue) } for (const { path, text } of sentences) { if (typeof text !== 'string') continue; diff --git a/packages/runtime/src/app-artifact-handlers.ts b/packages/runtime/src/app-artifact-handlers.ts index 39343709257..2fd78e09ce3 100644 --- a/packages/runtime/src/app-artifact-handlers.ts +++ b/packages/runtime/src/app-artifact-handlers.ts @@ -250,7 +250,7 @@ export interface AppArtifactHandlerBindingOptions { */ withholdHooksWithoutBody?: boolean; /** - * [#26170] The `i18n` service a hook's declared refusal is translated + * [#26170] The `i18n` service a hook's (and, #34273, an action's) declared refusal is translated * through, read at refusal time. Absent, a declared refusal is answered * with its declared message. */ @@ -483,6 +483,8 @@ export function bindAppArtifactHandlers( ql, logger, appId, + // [#34273] An action's declared refusal is translated as a hook's is. + i18n: options.i18n, getService: options.getService, originPackageId: handlerOwnerPackage(actionOwner), }); diff --git a/packages/runtime/src/app-plugin.ts b/packages/runtime/src/app-plugin.ts index 44ea0f4593d..951925471dd 100644 --- a/packages/runtime/src/app-plugin.ts +++ b/packages/runtime/src/app-plugin.ts @@ -964,6 +964,8 @@ export class AppPlugin implements Plugin { ql, logger: ctx.logger, appId: 'runtime-authored', + // [#34273] An action's declared refusal is translated as a hook's is. + i18n: hookRefusalI18nReader(ctx), getService: (name) => ctx.getService(name), })); if (installed !== false) { diff --git a/packages/runtime/src/sandbox/body-runner.ts b/packages/runtime/src/sandbox/body-runner.ts index d184049422d..c8d38918869 100644 --- a/packages/runtime/src/sandbox/body-runner.ts +++ b/packages/runtime/src/sandbox/body-runner.ts @@ -77,6 +77,7 @@ import { import { mapDataError } from '@objectstack/types'; import { inProcessHostSurface, + resolveActionRefusal, resolveHookRefusal, resolveInProcessHookRefusal, type HookRefusalI18nSource, @@ -91,9 +92,10 @@ interface FactoryOptions { appId: string; logger?: any; /** - * [#26170] Where a hook's declared refusal is translated: the `i18n` - * service, read at refusal time (see `resolveHookRefusal`). Absent, a - * declared refusal is answered with its declared message. + * [#26170] Where a hook's declared refusal — and, #34273, an action's — is + * translated: the `i18n` service, read at refusal time (see + * `resolveHookRefusal`, `resolveActionRefusal`). Absent, a declared refusal + * is answered with its declared message. */ i18n?: HookRefusalI18nSource; /** @@ -606,7 +608,7 @@ export function hookBodyRunnerFactory( export function actionBodyRunnerFactory( runner: ScriptRunner, opts: FactoryOptions, -): (action: { name: string; body?: unknown; object?: string; type?: string; timeoutMs?: number }) => +): (action: { name: string; body?: unknown; object?: string; type?: string; timeoutMs?: number; refusals?: unknown }) => | ((actionCtx: any) => Promise) | undefined { return (action) => { @@ -694,8 +696,13 @@ export function actionBodyRunnerFactory( warnDiscardedRecordWrites(result, action.name, action.object, opts); return result.value; } catch (err: any) { - logBodyThrow(opts, { kind: 'action', name: action.name }, err); - throw err; + // [#34273] An action that declares `refusals` refuses by code only, + // exactly as a hook does: the body's throw is answered with the + // declared entry in the caller's locale, or refused loudly when the + // catalogue cannot answer it. Everything else leaves as thrown. + const answered = resolveActionRefusal(action, err, actionCtx, { i18n: opts.i18n, logger: opts.logger }); + logBodyThrow(opts, { kind: 'action', name: action.name }, answered); + throw answered; } }; }; diff --git a/packages/runtime/src/sandbox/hook-refusal-catalogue.ts b/packages/runtime/src/sandbox/hook-refusal-catalogue.ts index 81dcd370f59..b4af045aa5f 100644 --- a/packages/runtime/src/sandbox/hook-refusal-catalogue.ts +++ b/packages/runtime/src/sandbox/hook-refusal-catalogue.ts @@ -68,9 +68,15 @@ */ import type { Hook } from '@objectstack/spec/data'; -import { undeclaredHookRefusalAtRun, undeclaredHookRefusalReasonAtRun } from '@objectstack/spec/data'; -import { hookRefusalMessageKey, resolveBundleLocale } from '@objectstack/spec/system'; +import { + undeclaredActionRefusalAtRun, + undeclaredActionRefusalReasonAtRun, + undeclaredHookRefusalAtRun, + undeclaredHookRefusalReasonAtRun, +} from '@objectstack/spec/data'; +import { actionRefusalMessageKey, hookRefusalMessageKey, resolveBundleLocale } from '@objectstack/spec/system'; import { templateEngine } from '@objectstack/formula'; +import { isObjectLessActionKey, standaloneActionOwnerKey } from '@objectstack/objectql'; import { sandboxBusinessMessage } from '@objectstack/types'; import { SandboxError, @@ -130,8 +136,56 @@ interface DeclaredRefusal { /** [#33214] What a hook's throw named beside its code: a declared reason and the params its holes name. */ export type HookRefusalAddress = SandboxRefusalAddress; +/** + * [#34273] The declaration a catalogue sits on — a hook, or an action — as + * the shared answer below needs it: its name for the log and fault text, the + * key its translations are read at, and the two run-time fault sentences. + * The answer itself is one code path for both, so a hook's refusal and an + * action's cannot be answered differently. + */ +interface RefusalOwner { + /** `hook 'NAME'` / `action 'NAME'`, for the log lines. */ + label: string; + messageKey(code: string, reason?: string): string; + undeclaredAtRun(code: string | undefined, declared: readonly string[]): string; + undeclaredReasonAtRun(code: string, reason: string, declared: readonly string[]): string; +} + +function hookOwner(hookName: string): RefusalOwner { + return { + label: `hook '${hookName}'`, + messageKey: (code, reason) => hookRefusalMessageKey(hookName, code, reason), + undeclaredAtRun: (code, declared) => undeclaredHookRefusalAtRun(hookName, code, declared), + undeclaredReasonAtRun: (code, reason, declared) => undeclaredHookRefusalReasonAtRun(hookName, code, reason, declared), + }; +} + +/** [#34273] An action as the catalogue reads it: its name, its OWN object (absent: object-less), its catalogue. */ +export interface ActionRefusalDeclaration { + name: string; + /** The object the action is declared on (`ActionSchema.objectName`). */ + objectName?: string; + /** The object that declares it inline, as the bundle collector stamps it. */ + object?: string; + refusals?: unknown; +} + +function actionOwner(action: ActionRefusalDeclaration): RefusalOwner { + const name = String(action.name); + // The action's OWN object, read by the one owner-key ladder + // (`objectName`, then `object`, else object-less) — never re-spelled here. + const ownerKey = standaloneActionOwnerKey(action); + const object = isObjectLessActionKey(ownerKey) ? undefined : ownerKey; + return { + label: `action '${name}'`, + messageKey: (code, reason) => actionRefusalMessageKey(object, name, code, reason), + undeclaredAtRun: (code, declared) => undeclaredActionRefusalAtRun(name, code, declared), + undeclaredReasonAtRun: (code, reason, declared) => undeclaredActionRefusalReasonAtRun(name, code, reason, declared), + }; +} + /** The hook's catalogue, or `undefined` when it declares none. */ -function catalogueOf(hook: Pick): Record | undefined { +function catalogueOf(hook: Pick | ActionRefusalDeclaration): Record | undefined { const refusals = (hook as { refusals?: unknown }).refusals; return refusals && typeof refusals === 'object' ? (refusals as Record) : undefined; } @@ -171,11 +225,22 @@ export function fillHookRefusalParams( declared: readonly string[], params: Record | undefined, logger?: { warn?: (...args: any[]) => void }, +): string { + return fillRefusalParams(hookOwner(hookName), template, declared, params, logger); +} + +/** {@link fillHookRefusalParams} for any declared refusal owner — a hook's or an action's (#34273). */ +function fillRefusalParams( + owner: RefusalOwner, + template: string, + declared: readonly string[], + params: Record | undefined, + logger?: { warn?: (...args: any[]) => void }, ): string { const result = renderHookTemplate(template, declared, params); if (result.ok) return result.value; logger?.warn?.( - `[BodyRunner] hook '${hookName}': its refusal sentence did not render (${result.error}), ` + `[BodyRunner] ${owner.label}: its refusal sentence did not render (${result.error}), ` + 'so it is served as written.', ); return template; @@ -233,12 +298,24 @@ export function declaredRefusalMessage( i18n: HookRefusalI18nSource | undefined, logger?: { warn?: (...args: any[]) => void }, address?: HookRefusalAddress, +): string { + return ownerRefusalMessage(hookOwner(hookName), code, entry, locale, i18n, logger, address); +} + +function ownerRefusalMessage( + owner: RefusalOwner, + code: string, + entry: DeclaredRefusal, + locale: string | undefined, + i18n: HookRefusalI18nSource | undefined, + logger?: { warn?: (...args: any[]) => void }, + address?: HookRefusalAddress, ): string { const reason = declaredReason(entry, address); const declaredSentence = reason !== undefined ? entry.reasons![reason]!.message : entry.message; - const picked = pickTranslatedSentence(hookName, code, reason, declaredSentence, locale, i18n, logger); + const picked = pickTranslatedSentence(owner, code, reason, declaredSentence, locale, i18n, logger); const params = Array.isArray(entry.params) ? entry.params : []; - return params.length > 0 ? fillHookRefusalParams(hookName, picked, params, address?.params, logger) : picked; + return params.length > 0 ? fillRefusalParams(owner, picked, params, address?.params, logger) : picked; } /** @@ -255,7 +332,7 @@ function declaredReason(entry: DeclaredRefusal, address: HookRefusalAddress | un /** The translation of a declared sentence in `locale`, or the declared sentence itself. */ function pickTranslatedSentence( - hookName: string, + owner: RefusalOwner, code: string, reason: string | undefined, declared: string, @@ -271,14 +348,14 @@ function pickTranslatedSentence( return declared; } if (!service || typeof service.t !== 'function') return declared; - const key = hookRefusalMessageKey(hookName, code, reason); + const key = owner.messageKey(code, reason); try { const translated = service.t(key, negotiatedLocale(service, locale)); // II18nService echoes the key back on a miss. if (typeof translated === 'string' && translated.trim().length > 0 && translated !== key) return translated; } catch (err: unknown) { logger?.warn?.( - `[BodyRunner] hook '${hookName}': the i18n service threw reading '${key}' ` + `[BodyRunner] ${owner.label}: the i18n service threw reading '${key}' ` + `(${err instanceof Error ? err.message : String(err)}), so the refusal shows its declared message.`, ); } @@ -292,11 +369,11 @@ function pickTranslatedSentence( * builds its `SandboxError` from it with the code it read. */ function declaredAnswer( - hook: Pick, + owner: RefusalOwner, thrownCode: string, entry: DeclaredRefusal, address: HookRefusalAddress | undefined, - engineCtx: { session?: { locale?: unknown } } | undefined, + locale: unknown, opts: { i18n?: HookRefusalI18nSource; logger?: { warn?: (...args: any[]) => void } }, ): { fault: SandboxError } | { message: string; status: number } { // A reason is judged only under a code that declares `reasons`; under any @@ -304,11 +381,10 @@ function declaredAnswer( const reason = address?.reason; const reasons = entry.reasons && typeof entry.reasons === 'object' ? entry.reasons : undefined; if (reason !== undefined && reasons && !Object.prototype.hasOwnProperty.call(reasons, reason)) { - return { fault: new SandboxError(undeclaredHookRefusalReasonAtRun(String(hook.name), thrownCode, reason, Object.keys(reasons))) }; + return { fault: new SandboxError(owner.undeclaredReasonAtRun(thrownCode, reason, Object.keys(reasons))) }; } - const locale = engineCtx?.session?.locale; - const message = declaredRefusalMessage( - String(hook.name), + const message = ownerRefusalMessage( + owner, thrownCode, entry, typeof locale === 'string' ? locale : undefined, @@ -332,6 +408,43 @@ export function resolveHookRefusal( ): unknown { const catalogue = catalogueOf(hook); if (!catalogue) return err; + return resolveSandboxedRefusal(hookOwner(String(hook.name)), catalogue, err, engineCtx?.session?.locale, opts); +} + +/** + * [#34273] Answer a sandboxed ACTION body's throw against the action's + * refusal catalogue (`ActionSchema.refusals`) — the action twin of + * {@link resolveHookRefusal}, called by the action body runner. One answer + * for both: a declared code (and declared reason) is answered with the + * entry's sentence in the caller's locale — picked at + * `objects.._actions..refusals.…` or + * `globalActions..refusals.…` (`actionRefusalMessageKey`) — its + * status, and the code on the wire; anything else the body threw is refused + * loudly; a host-relayed error, a nested refusal, the sandbox's own fault and + * a crash pass through unchanged. + * + * The caller's locale is the action context's `executionContext.locale` — + * the request's negotiated language, the one a flow action's run reads. + */ +export function resolveActionRefusal( + action: ActionRefusalDeclaration, + err: unknown, + actionCtx: { executionContext?: { locale?: unknown } } | undefined, + opts: { i18n?: HookRefusalI18nSource; logger?: { warn?: (...args: any[]) => void } } = {}, +): unknown { + const catalogue = catalogueOf(action); + if (!catalogue) return err; + return resolveSandboxedRefusal(actionOwner(action), catalogue, err, actionCtx?.executionContext?.locale, opts); +} + +/** The one answer {@link resolveHookRefusal} and {@link resolveActionRefusal} give a sandboxed body's throw. */ +function resolveSandboxedRefusal( + owner: RefusalOwner, + catalogue: Record, + err: unknown, + locale: unknown, + opts: { i18n?: HookRefusalI18nSource; logger?: { warn?: (...args: any[]) => void } }, +): unknown { // Not the body's own throw: the engine's error relayed as itself, the // sandbox's own fault, a host error re-thrown unchanged, a nested refusal. if (!(err instanceof SandboxError) || err.innerMessage === undefined) return err; @@ -342,9 +455,9 @@ export function resolveHookRefusal( const code = typeof err.code === 'string' && err.code.length > 0 ? err.code : undefined; const entry = code !== undefined && Object.prototype.hasOwnProperty.call(catalogue, code) ? catalogue[code] : undefined; if (code === undefined || !entry) { - return new SandboxError(undeclaredHookRefusalAtRun(String(hook.name), code, Object.keys(catalogue))); + return new SandboxError(owner.undeclaredAtRun(code, Object.keys(catalogue))); } - const answer = declaredAnswer(hook, code, entry, sandboxRefusalAddressOf(err), engineCtx, opts); + const answer = declaredAnswer(owner, code, entry, sandboxRefusalAddressOf(err), locale, opts); if ('fault' in answer) return answer.fault; return new SandboxError(err.message, answer.message, { code, status: answer.status, userMessage: answer.message }); } @@ -524,15 +637,16 @@ export function resolveInProcessHookRefusal( }; const code = typeof thrown.code === 'string' && thrown.code.length > 0 ? thrown.code : undefined; const entry = code !== undefined && Object.prototype.hasOwnProperty.call(catalogue, code) ? catalogue[code] : undefined; + const owner = hookOwner(String(hook.name)); if (code === undefined || !entry) { - return new SandboxError(undeclaredHookRefusalAtRun(String(hook.name), code, Object.keys(catalogue))); + return new SandboxError(owner.undeclaredAtRun(code, Object.keys(catalogue))); } const address: HookRefusalAddress = {}; if (typeof thrown.reason === 'string' && thrown.reason.length > 0) address.reason = thrown.reason; if (thrown.params !== null && typeof thrown.params === 'object' && !Array.isArray(thrown.params)) { address.params = thrown.params as Record; } - const answer = declaredAnswer(hook, code, entry, address, engineCtx, opts); + const answer = declaredAnswer(owner, code, entry, address, engineCtx?.session?.locale, opts); if ('fault' in answer) return answer.fault; return new SandboxError(`hook '${String(hook.name)}' threw: ${flattenThrown(err)}`, answer.message, { code, From 060c0583c2fed0be31b362a3a152c8f188b66982 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 07:05:26 +0000 Subject: [PATCH 03/13] fix(spec, lint, runtime): carry the action refusal work onto main beside the hook texts (#34545) The declared-entry factory now builds both kinds of declared sentence: a refusal entry (hook, action) and a text entry (hook), so HookTextSchema is made by it too and the action half of #34374 adds one row. Claude-Session: https://claude.ai/code/session_01ADHkmP879Ku8wbNev27oyN --- packages/lint/src/i18n-walk.ts | 3 - .../src/validate-hook-refusal-templates.ts | 101 ++++++++---------- packages/spec/authorable-surface/ui.json | 5 + .../spec/dropped-refinements.baseline.json | 21 +++- packages/spec/json-schema.manifest/ui.json | 1 + 5 files changed, 68 insertions(+), 63 deletions(-) diff --git a/packages/lint/src/i18n-walk.ts b/packages/lint/src/i18n-walk.ts index 1e36aa72fb6..672d869d393 100644 --- a/packages/lint/src/i18n-walk.ts +++ b/packages/lint/src/i18n-walk.ts @@ -140,12 +140,9 @@ * (see `authorWarnedTranslationGroups`) * hooks..refusals..message (#26170) * hooks..refusals..reasons..message (#33214) -<<<<<<< HEAD * hooks..texts..message (#34374) -======= * objects.._actions..refusals..message (#34273; and * globalActions..refusals..message, with `.reasons..message` under each) ->>>>>>> f0e42de65 (wip(runtime,lint): answer an action body's throw against its refusal catalogue) * positions..label / .description * permissions..label / .description * books..label / .description diff --git a/packages/lint/src/validate-hook-refusal-templates.ts b/packages/lint/src/validate-hook-refusal-templates.ts index 4a6ab2f3347..82403714343 100644 --- a/packages/lint/src/validate-hook-refusal-templates.ts +++ b/packages/lint/src/validate-hook-refusal-templates.ts @@ -54,48 +54,66 @@ function paramsOf(entry: AnyRec): string[] { return Array.isArray(entry.params) ? entry.params.filter((p): p is string => typeof p === 'string') : []; } +/** The subject a judged sentence belongs to, as a refusal names it. */ +type SentenceSubject = 'hook' | 'action'; + /** The refusal of an argument-less `currency` formatter in one hole, or `undefined`. */ -function currencyWithoutCode(holeText: string, inner: string, noun: 'hook' | 'action'): string | undefined { +function currencyWithoutCode(holeText: string, inner: string, noun: SentenceSubject): string | undefined { const bar = inner.indexOf('|'); if (bar === -1) return undefined; const formatter = inner.slice(bar + 1).trim(); if (formatter !== 'currency') return undefined; const path = inner.slice(0, bar).trim() || 'amount'; return ( -<<<<<<< HEAD - `\`${holeText}\` formats in the organization's default currency, which a hook sentence does not carry, so the ` -======= - `\`${holeText}\` formats in the organization's default currency, which a ${noun} refusal does not carry, so the ` ->>>>>>> f0e42de65 (wip(runtime,lint): answer an action body's throw against its refusal catalogue) + `\`${holeText}\` formats in the organization's default currency, which a ${noun} sentence does not carry, so the ` + 'sentence would be served with its braces. Name the code in the hole: ' + `\`{{ ${path} | currency:EUR }}\`.` ); } -/** Every finding one refusal catalogue draws, each located at `owner` + the sentence's path. */ -function judgeCatalogue(issues: ExprIssue[], refusals: AnyRec, owner: string, noun: 'hook' | 'action'): void { +/** One sentence to judge: its path under the declaration, and its text as written. */ +type Sentence = { path: string; text: unknown }; + +/** The sentences of a refusal catalogue whose entry declares `params` — `message` and each `reasons[*].message`. */ +function refusalSentences(refusals: unknown): Sentence[] { + const sentences: Sentence[] = []; + if (!isRec(refusals)) return sentences; for (const [code, entry] of Object.entries(refusals)) { - if (!isRec(entry)) continue; - const params = paramsOf(entry); - if (params.length === 0) continue; - const sentences: Array<{ path: string; text: unknown }> = [{ path: `refusals.${code}.message`, text: entry.message }]; + if (!isRec(entry) || paramsOf(entry).length === 0) continue; + sentences.push({ path: `refusals.${code}.message`, text: entry.message }); if (isRec(entry.reasons)) { for (const [reason, sentence] of Object.entries(entry.reasons)) { sentences.push({ path: `refusals.${code}.reasons.${reason}.message`, text: isRec(sentence) ? sentence.message : undefined }); } } - for (const { path, text } of sentences) { - if (typeof text !== 'string') continue; - const where = `${owner} ${path}`; - const refuse = (message: string, source: string): void => { - issues.push({ where, message, source, severity: 'error' }); - }; - for (const m of text.matchAll(HOLE)) { - const refusal = currencyWithoutCode(m[0], m[1]!, noun); - if (refusal !== undefined) refuse(refusal, m[0]); - } - for (const e of validateExpression('template', text).errors) refuse(e.message, e.source); + } + return sentences; +} + +/** The sentences of a declared-text catalogue (#34374) whose entry declares `params`. */ +function textSentences(texts: unknown): Sentence[] { + const sentences: Sentence[] = []; + if (!isRec(texts)) return sentences; + for (const [key, entry] of Object.entries(texts)) { + if (!isRec(entry) || paramsOf(entry).length === 0) continue; + sentences.push({ path: `texts.${key}.message`, text: entry.message }); + } + return sentences; +} + +/** Every finding `sentences` draw, each located at `owner` + the sentence's path. */ +function judgeSentences(issues: ExprIssue[], owner: string, sentences: readonly Sentence[], noun: SentenceSubject): void { + for (const { path, text } of sentences) { + if (typeof text !== 'string') continue; + const where = `${owner} ${path}`; + const refuse = (message: string, source: string): void => { + issues.push({ where, message, source, severity: 'error' }); + }; + for (const m of text.matchAll(HOLE)) { + const refusal = currencyWithoutCode(m[0], m[1]!, noun); + if (refusal !== undefined) refuse(refusal, m[0]); } + for (const e of validateExpression('template', text).errors) refuse(e.message, e.source); } } @@ -108,27 +126,7 @@ export function hookRefusalTemplateIssues(stack: AnyRec): ExprIssue[] { const issues: ExprIssue[] = []; for (const hook of recordsOf(stack.hooks)) { const hookName = typeof hook.name === 'string' ? hook.name : '?'; -<<<<<<< HEAD - const sentences: Array<{ path: string; text: unknown }> = []; - if (isRec(hook.refusals)) { - for (const [code, entry] of Object.entries(hook.refusals)) { - if (!isRec(entry) || paramsOf(entry).length === 0) continue; - sentences.push({ path: `refusals.${code}.message`, text: entry.message }); - if (isRec(entry.reasons)) { - for (const [reason, sentence] of Object.entries(entry.reasons)) { - sentences.push({ path: `refusals.${code}.reasons.${reason}.message`, text: isRec(sentence) ? sentence.message : undefined }); - } - } - } - } - if (isRec(hook.texts)) { - for (const [key, entry] of Object.entries(hook.texts)) { - if (!isRec(entry) || paramsOf(entry).length === 0) continue; - sentences.push({ path: `texts.${key}.message`, text: entry.message }); - } -======= - if (!isRec(hook.refusals)) continue; - judgeCatalogue(issues, hook.refusals, `hook '${hookName}'`, 'hook'); + judgeSentences(issues, `hook '${hookName}'`, [...refusalSentences(hook.refusals), ...textSentences(hook.texts)], 'hook'); } return issues; } @@ -157,7 +155,7 @@ export function actionRefusalTemplateIssues(stack: AnyRec, scope: ActionRefusalT const key = `${bound}:${name}`; if (seen.has(key)) return; seen.add(key); - if (isRec(action.refusals)) judgeCatalogue(issues, action.refusals, `${owner} · action '${name}'`, 'action'); + judgeSentences(issues, `${owner} · action '${name}'`, refusalSentences(action.refusals), 'action'); }; if (scope.actions) { for (const action of recordsOf(stack.actions)) judge('stack', action); @@ -166,19 +164,6 @@ export function actionRefusalTemplateIssues(stack: AnyRec, scope: ActionRefusalT for (const object of recordsOf(stack.objects)) { const objectName = typeof object.name === 'string' ? object.name : undefined; for (const action of recordsOf(object.actions)) judge(`object '${objectName ?? '?'}'`, action, objectName); ->>>>>>> f0e42de65 (wip(runtime,lint): answer an action body's throw against its refusal catalogue) - } - for (const { path, text } of sentences) { - if (typeof text !== 'string') continue; - const where = `hook '${hookName}' ${path}`; - const refuse = (message: string, source: string): void => { - issues.push({ where, message, source, severity: 'error' }); - }; - for (const m of text.matchAll(HOLE)) { - const refusal = currencyWithoutCode(m[0], m[1]!); - if (refusal !== undefined) refuse(refusal, m[0]); - } - for (const e of validateExpression('template', text).errors) refuse(e.message, e.source); } } return issues; diff --git a/packages/spec/authorable-surface/ui.json b/packages/spec/authorable-surface/ui.json index 4adf3548c7a..dc78ec34fd7 100644 --- a/packages/spec/authorable-surface/ui.json +++ b/packages/spec/authorable-surface/ui.json @@ -44,6 +44,7 @@ "ui/Action:recordIdField", "ui/Action:recordIdParam", "ui/Action:refreshAfter", + "ui/Action:refusals", "ui/Action:requiredPermissions", "ui/Action:requiresFeature", "ui/Action:requiresMembershipReach", @@ -160,6 +161,10 @@ "ui/ActionParam:type", "ui/ActionParam:visible", "ui/ActionParam:widget", + "ui/ActionRefusal:message", + "ui/ActionRefusal:params", + "ui/ActionRefusal:reasons", + "ui/ActionRefusal:status", "ui/ActionSession:organizationId", "ui/ActionSession:positions", "ui/ActionSession:roles", diff --git a/packages/spec/dropped-refinements.baseline.json b/packages/spec/dropped-refinements.baseline.json index c80b26cc463..828622a8aae 100644 --- a/packages/spec/dropped-refinements.baseline.json +++ b/packages/spec/dropped-refinements.baseline.json @@ -2,8 +2,8 @@ "description": "Shrink-only ledger of every PUBLISHED JSON Schema that is STILL WIDER than the Zod type it was generated from, because a rule written as `.refine()` reaches the runtime and not the file (#18670). `z.toJSONSchema()` has no arm for a `custom` check: a plain record, the same record with a `.refine()`, and the same record with an ABORTING `.refine()` all project byte-identically (measured on zod 4.4.3, the version packages/spec resolves). So a document one of these files ACCEPTS can still be refused at parse time, and an author -- or an AI -- validating against packages/spec/json-schema/** finds out a release later. Each `sites` path is a position under that schema at which a refinement is dropped; the same paths are written onto the artifact itself as `x-dropped-refinements`. Item 2 closed the first patterns: a refinement DECLARED through the closed list in src/shared/refinement-projection.ts is emitted into the published file, reads `projected` rather than `dropped`, and its row LEAVES this ledger in the same PR -- which is why the ledger shrinks and never grows on a repair. Every refinement outside that closed list stays here, and adding an arm to the list is a public-contract decision, not a refactor. Hand-edited on purpose and with no `gen:` script: a generator would let a new gap be admitted by running a command instead of by a decision, which is the silence this ledger exists to end. Adding, removing or moving a site fails packages/spec/scripts/build-schemas.ts until the line moves with it, and the failure prints the corrected entry in full. ⛔ Do not delete or weaken a refinement to shorten this file -- the runtime rule is correct; it is the projection that is silent, and the remedy is to teach the closed list a NAMED pattern, never to drop the rule.", "measured": { "zod": "4.4.3", - "publishedSchemasWithDroppedRefinements": 269, - "droppedRefinementSites": 1122, + "publishedSchemasWithDroppedRefinements": 270, + "droppedRefinementSites": 1135, "refinementSitesThatDidProject": 728, "refinementSitesWithNoJsonFormToCompare": 0 }, @@ -106,6 +106,7 @@ "manifest.actions.element.in.onSuccess", "manifest.actions.element.in.params.element.in", "manifest.actions.element.in.preflight.fields.element", + "manifest.actions.element.in.refusals.valueType", "manifest.actions.element.in.resultDialog.fields.element", "manifest.agents.element.memory", "manifest.agents.element.structuredOutput.schema", @@ -291,6 +292,7 @@ "data.options[1].manifest.actions.element.in.onSuccess", "data.options[1].manifest.actions.element.in.params.element.in", "data.options[1].manifest.actions.element.in.preflight.fields.element", + "data.options[1].manifest.actions.element.in.refusals.valueType", "data.options[1].manifest.actions.element.in.resultDialog.fields.element", "data.options[1].manifest.agents.element.memory", "data.options[1].manifest.agents.element.structuredOutput.schema", @@ -444,6 +446,7 @@ "options[1].manifest.actions.element.in.onSuccess", "options[1].manifest.actions.element.in.params.element.in", "options[1].manifest.actions.element.in.preflight.fields.element", + "options[1].manifest.actions.element.in.refusals.valueType", "options[1].manifest.actions.element.in.resultDialog.fields.element", "options[1].manifest.agents.element.memory", "options[1].manifest.agents.element.structuredOutput.schema", @@ -536,6 +539,7 @@ "data.packages.element.options[1].manifest.actions.element.in.onSuccess", "data.packages.element.options[1].manifest.actions.element.in.params.element.in", "data.packages.element.options[1].manifest.actions.element.in.preflight.fields.element", + "data.packages.element.options[1].manifest.actions.element.in.refusals.valueType", "data.packages.element.options[1].manifest.actions.element.in.resultDialog.fields.element", "data.packages.element.options[1].manifest.agents.element.memory", "data.packages.element.options[1].manifest.agents.element.structuredOutput.schema", @@ -626,6 +630,7 @@ "data.actions.element.in.onSuccess", "data.actions.element.in.params.element.in", "data.actions.element.in.preflight.fields.element", + "data.actions.element.in.refusals.valueType", "data.actions.element.in.resultDialog.fields.element" ] }, @@ -637,6 +642,7 @@ "data.actions.element.in.onSuccess", "data.actions.element.in.params.element.in", "data.actions.element.in.preflight.fields.element", + "data.actions.element.in.refusals.valueType", "data.actions.element.in.resultDialog.fields.element", "data.defaultRowScope", "data.fieldGroups", @@ -1148,6 +1154,7 @@ "actions.element.in.onSuccess", "actions.element.in.params.element.in", "actions.element.in.preflight.fields.element", + "actions.element.in.refusals.valueType", "actions.element.in.resultDialog.fields.element", "defaultRowScope", "fieldGroups", @@ -1390,6 +1397,7 @@ "actions.element.in.onSuccess", "actions.element.in.params.element.in", "actions.element.in.preflight.fields.element", + "actions.element.in.refusals.valueType", "actions.element.in.resultDialog.fields.element" ] }, @@ -1515,6 +1523,7 @@ "operations.element.options[3].object.actions.element.in.onSuccess", "operations.element.options[3].object.actions.element.in.params.element.in", "operations.element.options[3].object.actions.element.in.preflight.fields.element", + "operations.element.options[3].object.actions.element.in.refusals.valueType", "operations.element.options[3].object.actions.element.in.resultDialog.fields.element", "operations.element.options[3].object.defaultRowScope", "operations.element.options[3].object.fieldGroups", @@ -1541,6 +1550,7 @@ "object.actions.element.in.onSuccess", "object.actions.element.in.params.element.in", "object.actions.element.in.preflight.fields.element", + "object.actions.element.in.refusals.valueType", "object.actions.element.in.resultDialog.fields.element", "object.defaultRowScope", "object.fieldGroups", @@ -1599,6 +1609,7 @@ "options[3].object.actions.element.in.onSuccess", "options[3].object.actions.element.in.params.element.in", "options[3].object.actions.element.in.preflight.fields.element", + "options[3].object.actions.element.in.refusals.valueType", "options[3].object.actions.element.in.resultDialog.fields.element", "options[3].object.defaultRowScope", "options[3].object.fieldGroups", @@ -1737,6 +1748,7 @@ "in.onSuccess", "in.params.element.in", "in.preflight.fields.element", + "in.refusals.valueType", "in.resultDialog.fields.element" ] }, @@ -2205,6 +2217,11 @@ "filter.element", "filter.element.options[0]" ] + }, + "ui/ActionRefusal": { + "sites": [ + "" + ] } } } diff --git a/packages/spec/json-schema.manifest/ui.json b/packages/spec/json-schema.manifest/ui.json index a8f2ad41ff1..ef218d44c5a 100644 --- a/packages/spec/json-schema.manifest/ui.json +++ b/packages/spec/json-schema.manifest/ui.json @@ -11,6 +11,7 @@ "ui/ActionMenuProps", "ui/ActionNavItem", "ui/ActionParam", + "ui/ActionRefusal", "ui/ActionSession", "ui/ActionType", "ui/AddRecordConfig", From 7e9f80629e4b198fe92385803fe5459ab3469c2a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 07:15:17 +0000 Subject: [PATCH 04/13] =?UTF-8?q?feat(spec,=20runtime,=20lint):=20an=20act?= =?UTF-8?q?ion's=20refusal=20catalogue=20=E2=80=94=20validate,=20tests,=20?= =?UTF-8?q?liveness,=20docs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit objectstack validate refuses an action refusal translation over a code or reason the action does not declare; the shared declared-entry factory says "An action" where the subject is an action; tests on the real action body runner, the /actions door, the lint passes and the walk; the action.refusals liveness row; the actions and translations docs; the changeset. Claude-Session: https://claude.ai/code/session_01ADHkmP879Ku8wbNev27oyN Co-authored-by: Claude --- .changeset/34273-action-refusals.md | 21 ++ content/docs/ui/actions.mdx | 50 ++++ content/docs/ui/translations.mdx | 1 + packages/lint/src/i18n-walk.test.ts | 32 +++ .../validate-hook-refusal-templates.test.ts | 76 ++++- .../src/validate-hook-refusal-templates.ts | 2 +- .../validate-translation-references.test.ts | 106 ++++++- .../src/validate-translation-references.ts | 58 ++++ .../sandbox/action-refusal-catalogue.test.ts | 270 ++++++++++++++++++ packages/spec/liveness/action.json | 44 +++ packages/spec/src/data/declared-entry.zod.ts | 8 +- packages/spec/src/data/hook-refusal-codes.ts | 26 +- packages/spec/src/system/translation.zod.ts | 4 +- packages/spec/src/ui/action-refusals.test.ts | 268 +++++++++++++++++ packages/spec/src/ui/action.zod.ts | 24 +- 15 files changed, 955 insertions(+), 35 deletions(-) create mode 100644 .changeset/34273-action-refusals.md create mode 100644 packages/runtime/src/sandbox/action-refusal-catalogue.test.ts create mode 100644 packages/spec/src/ui/action-refusals.test.ts diff --git a/.changeset/34273-action-refusals.md b/.changeset/34273-action-refusals.md new file mode 100644 index 00000000000..0ae210cb843 --- /dev/null +++ b/.changeset/34273-action-refusals.md @@ -0,0 +1,21 @@ +--- +'@objectstack/spec': minor +'@objectstack/runtime': minor +'@objectstack/lint': minor +--- + +feat(actions): an action body refuses in the caller's language through a declared refusal catalogue + +Clause-②: yes (widening) — an action may now declare `refusals` (`ActionRefusalSchema`); translation bundles accept `objects.._actions..refusals..message` and `globalActions..refusals..message` (with `….reasons..message`); `@objectstack/spec` exports `ActionRefusalSchema` and `actionRefusalMessageKey`, `@objectstack/runtime` exports `resolveActionRefusal`. Nothing that was accepted before is refused +Metadata-protocol: added +Skills-docs: follow-up — `skills/objectstack-i18n/SKILL.md` lists the hook refusal key only, and no skill teaches an action's `refusals`; owed to a follow-up card. `content/docs/ui/actions.mdx` and `content/docs/ui/translations.mdx` gain the section and the key row here + +A `script` action's `js` body can now refuse the way a hook does: declare the refusals it may throw, keyed by code, and throw the code instead of the sentence — `refusals: { NOT_DRAFT: { message: 'Only a draft invoice can be signed off.', status: 409 } }`, then `throw { code: 'NOT_DRAFT' }`. The server answers with the entry's sentence in the caller's locale (the request's `executionContext.locale`), else the declared one, on the refusal's `userMessage`, with the entry's status (400 when it names none). The entry is the hook catalogue's, built by one shared factory: optional `reasons` (further sentences under one code) and `params` (the names a `{{ }}` hole may fill), under the same rules. + +- The translation sits beside the action's other copy: `objects.._actions..refusals..message` for an action bound to an object, `globalActions..refusals..message` for an object-less one. `os i18n extract` scaffolds the keys and the coverage check counts them; `objectstack validate` refuses a translation over a code or reason the action does not declare. +- A code the catalogue does not declare, a reason a code with `reasons` does not declare, or a throw with no code is refused: at save when the body names it literally, otherwise when it runs, as a fault naming the action and the code. An error a `ctx.api` call raised and the body let through unchanged passes through as before, and so does a crash. +- `refusals` is read only for a `type: 'script'` action with a `js` body (an inline `target` function is lowered to one by `os build`); on any other action, or with no body, it is refused at save. +- A sentence with `params` is compiled like a hook's: `objectstack validate`, `compile` and the publish gate refuse a hole holding logic, an unknown formatter, an empty hole and `{{ amount | currency }}` with no code. +- An action without `refusals` is answered exactly as before. + +The shared declared-entry factory (`packages/spec/src/data/declared-entry.zod.ts`) now builds `HookRefusalSchema`, `ActionRefusalSchema` and `HookTextSchema`; the published hook schemas are unchanged. diff --git a/content/docs/ui/actions.mdx b/content/docs/ui/actions.mdx index b87e78f74e5..499560bffd5 100644 --- a/content/docs/ui/actions.mdx +++ b/content/docs/ui/actions.mdx @@ -132,6 +132,56 @@ Body-carrying actions are **registered automatically** at boot. ``` +#### Refuse in the user's language — `refusals` + +A body that refuses with `throw new Error('…')` answers every caller in the +language the author wrote. To refuse in the caller's language, declare the +refusals the body may throw, keyed by code, and throw the code instead of the +sentence — the same catalogue a [hook declares](/docs/automation/hooks): + +```typescript +export const SubmitSignoff = defineAction({ + name: 'submit_signoff', + label: 'Submit for sign-off', + objectName: 'crm_invoice', + type: 'script', + refusals: { + NOT_DRAFT: { message: 'Only a draft invoice can be signed off.', status: 409 }, + STAGE_LOCKED: { + message: 'This stage change is not allowed.', + params: ['stage'], + reasons: { closed: { message: 'A {{ stage }} invoice can no longer change.' } }, + }, + }, + body: { + language: 'js', + source: + "if (ctx.record.status !== 'draft') throw { code: 'NOT_DRAFT' };" + + "if (ctx.record.closed) throw { code: 'STAGE_LOCKED', reason: 'closed', params: { stage: ctx.record.stage } };" + + "return { ok: true };", + capabilities: [], + }, +}); +``` + +The server answers a declared code with its entry: the `message` (or the +declared reason's), translated in the caller's locale with the declared +sentence as the fallback, its `{{ }}` holes filled from the throw's `params`, +and the entry's `status` (400 when it names none). The sentence rides on the +refusal's `userMessage`, which the console's failure toast shows. Translate it +beside the action's other copy — +`objects.._actions..refusals..message` (and +`….reasons..message`), or `globalActions..refusals.…` for an +action with no `objectName`; `os i18n extract` scaffolds the keys. + +A code the catalogue does not declare, a reason a code with `reasons` does not +declare, or a throw with no code is refused loudly: at save when the body +names it literally, otherwise when it runs, as a fault naming the action and +the code. An error a `ctx.api` call raised and the body let through unchanged +passes through as before, and so does a crash. `refusals` is read only for a +`type: 'script'` action with a `js` body (an inline `target` function is +lowered to one by `os build`); on any other action it is refused. + ### Path B: a registered handler (full TypeScript) For logic that belongs in real source files, point `target` at a handler name diff --git a/content/docs/ui/translations.mdx b/content/docs/ui/translations.mdx index 4d3fc2d0fd9..64e43d7ff96 100644 --- a/content/docs/ui/translations.mdx +++ b/content/docs/ui/translations.mdx @@ -93,6 +93,7 @@ export default defineStack({ | Text a flow writes into a record (a `create_record` / `update_record` field value marked `{ dialect: 'template', source }`) | `flows..records..fields.` — picked in the organization's language (the Localization setting when set, else the app's `i18n.defaultLocale`), never the run starter's; see [Flows](/docs/automation/flows#text-a-record-keeps--a-field-value-marked-as-text) | | Hook refusal messages | `hooks..refusals..message` — one per entry of the hook's `refusals` catalogue — and `hooks..refusals..reasons..message`, one per reason an entry declares. A hook (a `js` body or a TypeScript `handler`) refuses by code, optionally with a declared reason, and the server answers the refusal with this sentence in the caller's locale, else the declared one. A translation of an entry that declares `params` keeps its `{{ name }}` holes; the server fills them after picking the translation | | Hook texts | `hooks..texts..message` — one per entry of the hook's `texts`. A hook asks for the sentence with `ctx.text(key, params)` when it writes it into a record, and the server answers it in the **organization's** language (the Localization setting somebody set, else the app's `i18n.defaultLocale`), never the caller's, else the declared one. A translation of an entry that declares `params` keeps its `{{ name }}` holes; the server fills them after picking the translation | +| Action refusal messages | `objects.._actions..refusals..message` — one per entry of the action's `refusals` catalogue — and `….refusals..reasons..message`, one per reason an entry declares; `globalActions..refusals.…` for an action with no `objectName`. A `script` action's `js` body refuses by code, and the server answers the refusal with this sentence in the caller's locale, else the declared one, on the refusal's `userMessage`. A translation of an entry that declares `params` keeps its `{{ name }}` holes; the server fills them after picking the translation | | Position label / description | `positions..label` / `description` — keyed by the position's `name`; overlaid on every served position, which is the list the console's position picker draws | | Permission-set label / description | `permissions..label` / `description` — the group is spelled as the stack spells the collection (`permissions[]`), keyed by the set's `name` | | Doc book title, description and section titles | `books..label` / `description` / `groups..label` — keyed by the book's `name` and each group's `key`; overlaid on every served book and on the book tree, which is what the docs sidebar draws. A doc's own title and body localize through `doc.translations` instead | diff --git a/packages/lint/src/i18n-walk.test.ts b/packages/lint/src/i18n-walk.test.ts index 4e19a0b2bef..e9806dac2b5 100644 --- a/packages/lint/src/i18n-walk.test.ts +++ b/packages/lint/src/i18n-walk.test.ts @@ -153,3 +153,35 @@ describe('collectExpectedEntries — preflight field labels', () => { expect(preflightKeys(['objects', 'sys_package', '_actions', 'install_bare'])).toEqual([]); }); }); + +describe('collectExpectedEntries — an action\'s refusal catalogue (#34273)', () => { + const refusals = { + NOT_DRAFT: { message: 'Only a draft invoice can be signed off.' }, + STAGE_LOCKED: { message: 'Locked.', reasons: { closed: { message: 'A {{ stage }} deal is closed.' } }, params: ['stage'] }, + }; + const body = { language: 'js', source: "throw { code: 'NOT_DRAFT' };" }; + const entries = collectExpectedEntries({ + objects: [{ + name: 'crm_invoice', + fields: {}, + actions: [{ name: 'submit_signoff', label: 'Submit', type: 'script', body, refusals }], + }], + actions: [{ name: 'export_all', label: 'Export', type: 'script', body, refusals: { NOT_DRAFT: refusals.NOT_DRAFT } }], + }, { warnedGroups: new Set() }); + const at = (path: string) => entries.find((e) => e.path.join('.') === path); + + it('yields objects.._actions..refusals..message with the declared sentence', () => { + expect(at('objects.crm_invoice._actions.submit_signoff.refusals.NOT_DRAFT.message')?.sourceValue) + .toBe('Only a draft invoice can be signed off.'); + }); + + it('yields each declared reason under its code', () => { + expect(at('objects.crm_invoice._actions.submit_signoff.refusals.STAGE_LOCKED.reasons.closed.message')?.sourceValue) + .toBe('A {{ stage }} deal is closed.'); + }); + + it('yields an object-less action\'s refusals under globalActions', () => { + expect(at('globalActions.export_all.refusals.NOT_DRAFT.message')?.sourceValue) + .toBe('Only a draft invoice can be signed off.'); + }); +}); diff --git a/packages/lint/src/validate-hook-refusal-templates.test.ts b/packages/lint/src/validate-hook-refusal-templates.test.ts index 1873054e4ca..00d6d6c20bb 100644 --- a/packages/lint/src/validate-hook-refusal-templates.test.ts +++ b/packages/lint/src/validate-hook-refusal-templates.test.ts @@ -8,7 +8,7 @@ */ import { describe, it, expect } from 'vitest'; -import { hookRefusalTemplateIssues } from './validate-hook-refusal-templates.js'; +import { actionRefusalTemplateIssues, hookRefusalTemplateIssues } from './validate-hook-refusal-templates.js'; import { validateStackExpressions } from './validate-expressions.js'; import { runRuntimeAuthoringRules } from './runtime-gate.js'; @@ -157,3 +157,77 @@ describe('hook text templates over declared params (#34374)', () => { expect(control.errors.filter((e) => String(e.message).includes('currency'))).toEqual([]); }); }); + +describe('action refusal templates over declared params (#34273)', () => { + const action = (refusals: Record, extra: Record = {}) => ({ + name: 'submit_signoff', + label: 'Submit', + type: 'script', + body: { language: 'js', source: 'return 1;' }, + refusals, + ...extra, + }); + const stackWith = (message: string, extra: Record = {}) => ({ + objects: [{ name: 'crm_invoice', actions: [action(entry(message, extra))] }], + }); + const actionIssues = (message: string, extra?: Record) => + actionRefusalTemplateIssues(stackWith(message, extra), { actions: true, objects: true }); + + it.each([ + 'The invoice is {{ state }}.', + 'Over by {{ amount | number:2 }}.', + 'Paid {{ amount | currency:EUR }}.', + 'Plain text with no hole.', + ])('CONTROL: accepts %j', (message) => { + expect(actionIssues(message)).toEqual([]); + }); + + it.each([ + ['an unknown formatter', 'The invoice is {{ state | shout }}.'], + ['logic', 'The invoice is {{ state + 1 }}.'], + ['an empty hole', 'The invoice is {{ }}.'], + ])('refuses %s as an error, naming the object, the action and the sentence', (_label, message) => { + const issues = actionIssues(message); + expect(issues.length).toBeGreaterThan(0); + expect(issues.every((i) => i.severity === 'error')).toBe(true); + expect(issues[0]!.where).toBe("object 'crm_invoice' · action 'submit_signoff' refusals.VALIDATION_FAILED.message"); + }); + + it('refuses a currency formatter with no code, in the action\'s words', () => { + const issues = actionIssues('Paid {{ amount | currency }}.'); + expect(issues).toHaveLength(1); + expect(issues[0]!.message).toContain('which an action sentence does not carry'); + expect(issues[0]!.message).toContain('{{ amount | currency:EUR }}'); + }); + + it('judges each reason sentence at its own path', () => { + const issues = actionIssues('Fine {{ state }}.', { reasons: { closed: { message: 'Closed {{ state | shout }}.' } } }); + expect(issues.map((i) => i.where)) + .toEqual(["object 'crm_invoice' · action 'submit_signoff' refusals.VALIDATION_FAILED.reasons.closed.message"]); + }); + + it('judges a top-level action once, even when its object declares it too', () => { + const bound = { ...action(entry('{{ state | shout }}')), objectName: 'crm_invoice' }; + const issues = actionRefusalTemplateIssues( + { actions: [bound], objects: [{ name: 'crm_invoice', actions: [bound] }] }, + { actions: true, objects: true }, + ); + expect(issues).toHaveLength(1); + expect(issues[0]!.where).toBe("stack · action 'submit_signoff' refusals.VALIDATION_FAILED.message"); + }); + + it('is part of the stack expression pass `objectstack validate` and `compile` run', () => { + const issues = validateStackExpressions(stackWith('The invoice is {{ state | shout }}.') as never); + expect(issues.some((i) => i.where.endsWith("action 'submit_signoff' refusals.VALIDATION_FAILED.message") && i.severity === 'error')) + .toBe(true); + }); + + it('refuses an `action` write at the publish gate, and passes the CONTROL', () => { + const gate = (message: string) => + runRuntimeAuthoringRules({ type: 'action', item: action(entry(message)), context: { objects: [] } }) + .errors.filter((e) => String(e.where ?? '').includes('refusals.')); + const refused = gate('Paid {{ amount | currency }}.'); + expect(refused.some((e) => String(e.message).includes('{{ amount | currency:EUR }}')), JSON.stringify(refused)).toBe(true); + expect(gate('Paid {{ amount | currency:EUR }}.')).toEqual([]); + }); +}); diff --git a/packages/lint/src/validate-hook-refusal-templates.ts b/packages/lint/src/validate-hook-refusal-templates.ts index 82403714343..cbd5bb21828 100644 --- a/packages/lint/src/validate-hook-refusal-templates.ts +++ b/packages/lint/src/validate-hook-refusal-templates.ts @@ -65,7 +65,7 @@ function currencyWithoutCode(holeText: string, inner: string, noun: SentenceSubj if (formatter !== 'currency') return undefined; const path = inner.slice(0, bar).trim() || 'amount'; return ( - `\`${holeText}\` formats in the organization's default currency, which a ${noun} sentence does not carry, so the ` + `\`${holeText}\` formats in the organization's default currency, which ${noun === 'action' ? 'an action' : 'a hook'} sentence does not carry, so the ` + 'sentence would be served with its braces. Name the code in the hole: ' + `\`{{ ${path} | currency:EUR }}\`.` ); diff --git a/packages/lint/src/validate-translation-references.test.ts b/packages/lint/src/validate-translation-references.test.ts index 608dfae51fe..fb142def70e 100644 --- a/packages/lint/src/validate-translation-references.test.ts +++ b/packages/lint/src/validate-translation-references.test.ts @@ -4241,7 +4241,7 @@ describe('validateTranslationReferences — keyed children of an action entry (# }; type Address = 'bound' | 'global'; - type Host = 'outcome' | 'dialog' | 'noDialog' | 'noParams' | 'noPreRunDialog' | 'preflight'; + type Host = 'outcome' | 'dialog' | 'noDialog' | 'noParams' | 'noPreRunDialog' | 'preflight' | 'noRefusals'; /** * Which declared action a ghost is written under, per address. `noDialog` * names an action that declares no `resultDialog`: the dialog's leaves @@ -4260,6 +4260,9 @@ describe('validateTranslationReferences — keyed children of an action entry (# noPreRunDialog: { bound: 'plain_env', global: 'mint_token' }, // [#31885] An action whose `preflight` declares `fields`. preflight: { bound: 'upgrade_env', global: 'upgrade_pkg' }, + // [#34273] An action that declares no `refusals`, so a refusal key under + // it is read by nothing (`coverageStack` gives the outcome hosts one). + noRefusals: { bound: 'plain_env', global: 'mint_token' }, }; type Coverage = | { kind: 'reference-checked'; host: Host; ghost: Record; suffix: string; rule: string } @@ -4352,6 +4355,13 @@ describe('validateTranslationReferences — keyed children of an action entry (# suffix: '.preflight.fields.ghost_path', rule: TRANSLATION_TARGET_UNKNOWN, }, + refusals: { + kind: 'reference-checked', + host: 'noRefusals', + ghost: { refusals: { GHOST_CODE: { message: 'x' } } }, + suffix: '.refusals.GHOST_CODE', + rule: TRANSLATION_TARGET_UNKNOWN, + }, }; // The global action needs a param with inline options for the options ghost. @@ -4359,6 +4369,12 @@ describe('validateTranslationReferences — keyed children of an action entry (# const stack = actionStack(bundle); const check = stack.actions.find((a) => a.name === 'check_updates') as Record; check.params = [{ name: 'mode', label: 'Mode', type: 'select', options: [{ value: 'soft', label: 'Soft' }] }]; + // [#34273] The outcome hosts declare a refusal catalogue, for the real instance below. + for (const name of [HOST.outcome.bound, HOST.outcome.global]) { + (stack.actions.find((a) => a.name === name) as Record).refusals = { + NOT_READY: { message: 'Not ready.', reasons: { stale: { message: 'Stale.' } } }, + }; + } return stack; }; const bundleAt = (address: Address, actionName: string, node: Record) => @@ -4402,6 +4418,7 @@ describe('validateTranslationReferences — keyed children of an action entry (# cancelText: 'x', outcomeMessages: address === 'bound' ? { archived: 'x' } : { up_to_date: 'x' }, params: { mode: { label: 'x', helpText: 'x', placeholder: 'x', options: { soft: 'x' } } }, + refusals: { NOT_READY: { message: 'x', reasons: { stale: { message: 'x' } } } }, }, [dialog]: { resultDialog: { title: 'x', description: 'x', acknowledge: 'x', fields: { token: 'x' } } }, [HOST.preflight[address]]: { preflight: { fields: { findings: 'x' } } }, @@ -5120,3 +5137,90 @@ describe('validateTranslationReferences — text a flow writes into a record (ru expect(otherType[0].message).toContain('`save_notice` node'); }); }); + +describe('validateTranslationReferences — action refusals (#34273)', () => { + const refusals = { + NOT_DRAFT: { message: 'Only a draft invoice can be signed off.' }, + STAGE_LOCKED: { message: 'Locked.', reasons: { closed: { message: 'Closed.' } } }, + }; + const refusalStack = (bundle: Record) => ({ + objects: [{ name: 'crm_invoice', label: 'Invoice', fields: { name: { type: 'text', label: 'Name' } } }], + actions: [ + { + name: 'submit_signoff', + label: 'Submit', + objectName: 'crm_invoice', + type: 'script', + body: { language: 'js', source: "throw { code: 'NOT_DRAFT' };" }, + refusals, + }, + { + name: 'export_all', + label: 'Export', + type: 'script', + body: { language: 'js', source: "throw { code: 'NOT_DRAFT' };" }, + refusals, + }, + { name: 'plain_invoice', label: 'Plain', objectName: 'crm_invoice', type: 'script', target: 'plainInvoice' }, + ], + translations: [{ 'zh-CN': bundle }], + }); + const ON = 'translations[0]["zh-CN"].objects.crm_invoice._actions'; + const GLOBAL = 'translations[0]["zh-CN"].globalActions'; + + it('CONTROL: reports nothing for declared codes and reasons, bound and object-less', () => { + expect(validateTranslationReferences(refusalStack({ + objects: { + crm_invoice: { + _actions: { + submit_signoff: { + refusals: { + NOT_DRAFT: { message: '只有草稿发票可以签核。' }, + STAGE_LOCKED: { message: '已锁定。', reasons: { closed: { message: '已关闭。' } } }, + }, + }, + }, + }, + }, + globalActions: { export_all: { refusals: { NOT_DRAFT: { message: '只有草稿可以导出。' } } } }, + }))).toEqual([]); + }); + + it('refuses a code the action does not declare, with the nearest declared code offered', () => { + const findings = validateTranslationReferences(refusalStack({ + objects: { crm_invoice: { _actions: { submit_signoff: { refusals: { NOT_DRAFTT: { message: 'x' } } } } } }, + })); + expect(findings.map((f) => [f.rule, f.severity, f.path])).toEqual([ + [TRANSLATION_TARGET_UNKNOWN, 'error', `${ON}.submit_signoff.refusals.NOT_DRAFTT`], + ]); + expect(findings[0].message).toContain('a code action "submit_signoff" does not declare under `refusals`'); + expect(findings[0].message).toContain('Did you mean "NOT_DRAFT"?'); + }); + + it('refuses a refusal key on an action that declares no `refusals`', () => { + const findings = validateTranslationReferences(refusalStack({ + objects: { crm_invoice: { _actions: { plain_invoice: { refusals: { ANY: { message: 'x' } } } } } }, + })); + expect(findings.map((f) => f.path)).toEqual([`${ON}.plain_invoice.refusals.ANY`]); + expect(findings[0].message).toContain('action "plain_invoice" declares no `refusals`'); + }); + + it('refuses a reason the code does not declare, and a reason under a code that declares none', () => { + const findings = validateTranslationReferences(refusalStack({ + globalActions: { + export_all: { + refusals: { + STAGE_LOCKED: { reasons: { clsoed: { message: 'x' } } }, + NOT_DRAFT: { reasons: { any: { message: 'x' } } }, + }, + }, + }, + })); + expect(findings.map((f) => [f.rule, f.path])).toEqual([ + [TRANSLATION_TARGET_UNKNOWN, `${GLOBAL}.export_all.refusals.STAGE_LOCKED.reasons.clsoed`], + [TRANSLATION_TARGET_UNKNOWN, `${GLOBAL}.export_all.refusals.NOT_DRAFT.reasons.any`], + ]); + expect(findings[0].message).toContain('Did you mean "closed"?'); + expect(findings[1].message).toContain('declares no `reasons` under that code'); + }); +}); diff --git a/packages/lint/src/validate-translation-references.ts b/packages/lint/src/validate-translation-references.ts index b52150aa1d2..c35c41ed759 100644 --- a/packages/lint/src/validate-translation-references.ts +++ b/packages/lint/src/validate-translation-references.ts @@ -2738,6 +2738,7 @@ interface ActionEntryContext { * | `preflight.fields.` | `preflight.fields[].path` | `resolveActionPreflight` | * | `submitText` | a non-empty `params` (the param dialog) | `translateAction` | * | `cancelText` | `confirmText` or a non-empty `params` (either dialog) | `translateAction` | + * | `refusals.[.reasons.]` | the action's `refusals` codes (and each code's `reasons`) | `resolveActionRefusal` (#34273) | * * A dialog leaf under a DECLARED dialog is read whether or not the dialog * authors that leaf itself — the resolver overlays a translated `title` onto a @@ -2767,6 +2768,63 @@ function checkActionEntry(findings: TranslationRefFinding[], ctx: ActionEntryCon checkActionPreflightFields(findings, ctx); checkActionSubmitText(findings, ctx); checkActionCancelText(findings, ctx); + checkActionRefusals(findings, ctx); +} + +/** + * [#34273] `refusals.` and `refusals..reasons.` — the + * translations of the action's refusal catalogue (`ActionSchema.refusals`). + * The action body runner (`resolveActionRefusal`, `@objectstack/runtime`) + * reads them only for a code the catalogue declares, and a reason only under + * a code that declares it, so any other key is read by nothing: the bundle + * cannot add a refusal, only translate one — the hook catalogue's rule + * (`hooks..refusals.*`), in the action vocabulary. + */ +function checkActionRefusals(findings: TranslationRefFinding[], ctx: ActionEntryContext): void { + const rawRefusals = asRecord(isRec(ctx.rawAction) ? ctx.rawAction.refusals : undefined); + if (Object.keys(rawRefusals).length === 0) return; + const declared = asRecord(ctx.action.refusals); + const codes = new Set(Object.keys(declared)); + for (const [code, rawRefusal] of Object.entries(rawRefusals)) { + if (!codes.has(code)) { + findings.push({ + severity: TRANSLATION_TARGET_UNKNOWN_SEVERITY, + rule: TRANSLATION_TARGET_UNKNOWN, + where: `${ctx.where} · refusal "${code}"`, + path: `${ctx.path}.refusals.${code}`, + message: + codes.size > 0 + ? `Translations are keyed to refusal "${code}", a code ${ctx.subject} does not declare under ` + + `\`refusals\`, so nothing resolves this key.` + suggest(code, codes) + : `Translations are keyed to refusal "${code}", but ${ctx.subject} declares no \`refusals\`, ` + + `so nothing resolves this key.`, + hint: + `Refusal translations are keyed by a code the action's \`refusals\` declares; declare it there, ` + + `or drop the key.`, + }); + continue; + } + const entry = declared[code]; + const reasons = new Set(Object.keys(asRecord(isRec(entry) ? entry.reasons : undefined))); + for (const reason of Object.keys(asRecord(isRec(rawRefusal) ? rawRefusal.reasons : undefined))) { + if (reasons.has(reason)) continue; + findings.push({ + severity: TRANSLATION_TARGET_UNKNOWN_SEVERITY, + rule: TRANSLATION_TARGET_UNKNOWN, + where: `${ctx.where} · refusal "${code}" · reason "${reason}"`, + path: `${ctx.path}.refusals.${code}.reasons.${reason}`, + message: + reasons.size > 0 + ? `Translations are keyed to reason "${reason}", a reason refusal "${code}" of ${ctx.subject} does ` + + `not declare under \`reasons\`, so nothing resolves this key.` + suggest(reason, reasons) + : `Translations are keyed to reason "${reason}" of refusal "${code}", but ${ctx.subject} declares ` + + `no \`reasons\` under that code, so nothing resolves this key.`, + hint: + `Reason translations are keyed by a reason the code's \`reasons\` declares; declare it there, or ` + + `drop the key.`, + }); + } + } } /** diff --git a/packages/runtime/src/sandbox/action-refusal-catalogue.test.ts b/packages/runtime/src/sandbox/action-refusal-catalogue.test.ts new file mode 100644 index 00000000000..4c9514b07ff --- /dev/null +++ b/packages/runtime/src/sandbox/action-refusal-catalogue.test.ts @@ -0,0 +1,270 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34273] An action's declared refusal catalogue (`ActionSchema.refusals`), + * answered by the sandboxed ACTION body runner — the hook catalogue's twin + * (#26170, ruling 6431311681 letter A; #33214, ruling 6879477573). + * + * Driven through the real `actionBodyRunnerFactory` and the real QuickJS + * runner, and read off `mapDataError` (the ADR-0112 table) and the real + * `/actions` door (`HttpDispatcher.handleActions`), so what is asserted is the + * status, code and sentence the caller is answered with — never a hand-built + * `SandboxError`. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { mapDataError } from '@objectstack/types'; + +import { actionBodyRunnerFactory } from './body-runner.js'; +import { QuickJSScriptRunner, SandboxError } from './quickjs-runner.js'; +import { DEFAULT_HOOK_REFUSAL_STATUS, resolveActionRefusal, type HookRefusalI18nService } from './hook-refusal-catalogue.js'; +import { HttpDispatcher } from '../http-dispatcher.js'; + +const runner = new QuickJSScriptRunner({ hookTimeoutMs: 10_000, actionTimeoutMs: 10_000 }); + +const REFUSALS = { + SIGN_IN_REQUIRED: { message: 'Sign in to rate this article.', status: 401 }, + STAGE_LOCKED: { + message: 'This stage change is not allowed.', + params: ['stage'], + reasons: { closed: { message: 'A {{ stage }} opportunity can no longer change stage.' } }, + }, + NOT_DRAFT: { message: 'Only a draft invoice can be signed off.', status: 409 }, +}; + +/** An i18n service holding zh-CN translations; echoes the key on a miss, as `II18nService` does. */ +function i18nService(bundle: Record): HookRefusalI18nService { + const locales: Record> = { 'zh-CN': bundle }; + return { + t: (key, locale) => locales[locale]?.[key] ?? key, + getLocales: () => ['en', 'zh-CN'], + }; +} + +const BOUND_KEY = 'objects.crm_invoice._actions.submit_signoff.refusals.NOT_DRAFT.message'; +const GLOBAL_KEY = 'globalActions.submit_signoff.refusals.NOT_DRAFT.message'; +const ZH_BOUND = '只有草稿发票可以签核。'; +const ZH_GLOBAL = '(全局)只有草稿发票可以签核。'; + +/** A `script` action with a `js` body and the catalogue, bound through the real factory. */ +function boundAction( + source: string, + opts: { refusals?: object; objectName?: string | null; i18n?: () => HookRefusalI18nService | undefined } = {}, +) { + const objectName = opts.objectName === undefined ? 'crm_invoice' : opts.objectName ?? undefined; + const fn = actionBodyRunnerFactory(runner, { ql: {}, appId: 'crm', i18n: opts.i18n })({ + name: 'submit_signoff', + type: 'script', + ...(objectName !== undefined ? { objectName, object: objectName } : {}), + body: { language: 'js', source, capabilities: [] }, + refusals: 'refusals' in opts ? opts.refusals : REFUSALS, + } as any); + expect(fn, 'the action body must bind').toBeTypeOf('function'); + return fn!; +} + +/** The context the action dispatch hands a handler — the caller's negotiated locale on `executionContext`. */ +const actionCtx = (locale?: string) => ({ + input: {}, + executionContext: locale ? { userId: 'u1', locale } : { userId: 'u1' }, +}); + +async function rejectionOf(p: Promise): Promise { + const err = await p.then(() => null, (e) => e); + expect(err, 'expected the body to reject').not.toBeNull(); + return err; +} + +const throwing = (code: string) => `throw Object.assign(new Error('internal detail'), { code: '${code}' });`; + +describe('[#34273] a declared code is answered with the action\'s catalogue entry', () => { + it('the declared message, the entry\'s status and the declared code; the body\'s own text is not served', async () => { + const err = await rejectionOf(boundAction(throwing('NOT_DRAFT'))(actionCtx())); + expect(err).toBeInstanceOf(SandboxError); + const wire = mapDataError(err, 'crm_invoice'); + expect(wire.status).toBe(409); + expect(wire.body.declaredCode).toBe('NOT_DRAFT'); + expect(wire.body.userMessage).toBe(REFUSALS.NOT_DRAFT.message); + expect(JSON.stringify(wire.body)).not.toContain('internal detail'); + }); + + it('400 when the entry names no status, and a status the body sets is not read', async () => { + const err = await rejectionOf(boundAction( + "throw Object.assign(new Error('x'), { code: 'STAGE_LOCKED', status: 422 });", + )(actionCtx())); + const wire = mapDataError(err, 'crm_invoice'); + expect(wire.status).toBe(DEFAULT_HOOK_REFUSAL_STATUS); + expect(wire.body.declaredCode).toBe('STAGE_LOCKED'); + expect(wire.body.userMessage).toBe('This stage change is not allowed.'); + }); + + it('translated in the caller\'s locale (`executionContext.locale`) at `objects.._actions..refusals..message`', async () => { + const i18n = () => i18nService({ [BOUND_KEY]: ZH_BOUND, [GLOBAL_KEY]: ZH_GLOBAL }); + const err = await rejectionOf(boundAction(throwing('NOT_DRAFT'), { i18n })(actionCtx('zh-CN'))); + const wire = mapDataError(err, 'crm_invoice'); + expect(wire.status).toBe(409); + expect(wire.body.declaredCode).toBe('NOT_DRAFT'); + // The bound action reads its object's group, never `globalActions`. + expect(wire.body.userMessage).toBe(ZH_BOUND); + }); + + it('negotiated against the locales the service holds — `zh` picks `zh-CN`', async () => { + const i18n = () => i18nService({ [BOUND_KEY]: ZH_BOUND }); + const err = await rejectionOf(boundAction(throwing('NOT_DRAFT'), { i18n })(actionCtx('zh'))); + expect(mapDataError(err, 'crm_invoice').body.userMessage).toBe(ZH_BOUND); + }); + + it('an object-less action reads `globalActions..refusals..message`', async () => { + const i18n = () => i18nService({ [BOUND_KEY]: ZH_BOUND, [GLOBAL_KEY]: ZH_GLOBAL }); + const err = await rejectionOf(boundAction(throwing('NOT_DRAFT'), { i18n, objectName: null })(actionCtx('zh-CN'))); + expect(mapDataError(err, 'crm_invoice').body.userMessage).toBe(ZH_GLOBAL); + }); + + it('CONTROL: the declared message when the locale has no translation, no locale was asked, or no service is registered', async () => { + const withBundle = () => i18nService({ [BOUND_KEY]: ZH_BOUND }); + for (const [i18n, ctx] of [ + [withBundle, actionCtx('fr-FR')], + [withBundle, actionCtx()], + [() => undefined, actionCtx('zh-CN')], + ] as const) { + const err = await rejectionOf(boundAction(throwing('NOT_DRAFT'), { i18n })(ctx)); + expect(mapDataError(err, 'crm_invoice').body.userMessage).toBe(REFUSALS.NOT_DRAFT.message); + } + }); +}); + +describe('[#34273] a declared reason and declared params — the action body path', () => { + it('answers with the reason\'s sentence, its holes filled from the throw\'s params, under the code\'s status', async () => { + const err = await rejectionOf(boundAction( + "throw { code: 'STAGE_LOCKED', reason: 'closed', params: { stage: 'Closed Won' }, message: 'internal' };", + )(actionCtx())); + const wire = mapDataError(err, 'crm_invoice'); + expect(wire.status).toBe(400); + expect(wire.body.declaredCode).toBe('STAGE_LOCKED'); + expect(wire.body.userMessage).toBe('A Closed Won opportunity can no longer change stage.'); + expect(JSON.stringify(wire.body)).not.toContain('internal'); + }); + + it('the reason\'s translation is read at `….refusals..reasons..message`, filled after', async () => { + const i18n = () => i18nService({ + 'objects.crm_invoice._actions.submit_signoff.refusals.STAGE_LOCKED.reasons.closed.message': + '{{ stage }} 的商机不能再改阶段。', + }); + const err = await rejectionOf(boundAction( + "throw { code: 'STAGE_LOCKED', reason: 'closed', params: { stage: '赢单' } };", + { i18n }, + )(actionCtx('zh-CN'))); + expect(mapDataError(err, 'crm_invoice').body.userMessage).toBe('赢单 的商机不能再改阶段。'); + }); + + it('a reason the code does not declare is a 500 fault naming the action, the code and the reason', async () => { + const err = await rejectionOf(boundAction( + "const r = 'clos' + 'd'; throw { code: 'STAGE_LOCKED', reason: r };", + )(actionCtx())); + expect(err).toBeInstanceOf(SandboxError); + expect(err.innerMessage).toBeUndefined(); + expect(err.message).toContain("action 'submit_signoff' threw code 'STAGE_LOCKED' with reason 'closd'"); + expect(mapDataError(err, 'crm_invoice').status).toBe(500); + }); +}); + +describe('[#34273] what the catalogue cannot answer is refused loudly at run time', () => { + it('a code the catalogue does not declare is a 500 fault naming the action and the code', async () => { + const err = await rejectionOf(boundAction( + "const c = 'NOT_' + 'DRAFTT'; throw Object.assign(new Error('x'), { code: c });", + )(actionCtx())); + expect(err).toBeInstanceOf(SandboxError); + expect(err.innerMessage).toBeUndefined(); + expect(err.message).toContain("action 'submit_signoff' threw code 'NOT_DRAFTT'"); + expect(err.message).toContain('declares no such code'); + expect(mapDataError(err, 'crm_invoice').status).toBe(500); + }); + + it('a throw with no code is the same fault', async () => { + const err = await rejectionOf(boundAction("throw new Error('no code');")(actionCtx())); + expect(err.message).toContain("action 'submit_signoff'"); + expect(err.message).toContain('threw no `code`'); + expect(mapDataError(err, 'crm_invoice').status).toBe(500); + }); +}); + +describe('[#34273] what the catalogue does not own passes through untouched', () => { + it('CONTROL: an action without `refusals` is answered as before', async () => { + const err = await rejectionOf(boundAction( + "throw Object.assign(new Error('Refused.'), { code: 'ANY_CODE', status: 422 });", + { refusals: undefined }, + )(actionCtx('zh-CN'))); + const wire = mapDataError(err, 'crm_invoice'); + expect(wire.status).toBe(422); + expect(wire.body.declaredCode).toBe('ANY_CODE'); + expect(wire.body.userMessage).toBeUndefined(); + }); + + it('a crash stays a crash', async () => { + const err = await rejectionOf(boundAction('const v = null; return v.x;')(actionCtx())); + expect(err.message).not.toContain('declares no such code'); + expect(mapDataError(err, 'crm_invoice').status).toBe(500); + }); + + it('resolveActionRefusal leaves an error the body did not make as it is', () => { + const hostRefusal = Object.assign(new Error('Field `amount` is required.'), { code: 'VALIDATION_FAILED', status: 400 }); + const action = { name: 'submit_signoff', objectName: 'crm_invoice', refusals: REFUSALS }; + expect(resolveActionRefusal(action, hostRefusal, actionCtx('zh-CN'))).toBe(hostRefusal); + }); +}); + +/** The real `/actions` door, answering whatever the action dispatch threw. */ +async function throughActionsDoor(thrown: unknown) { + const action = { + name: 'submit_signoff', + objectName: 'crm_invoice', + type: 'script', + body: { language: 'js', source: throwing('NOT_DRAFT'), capabilities: [] }, + refusals: REFUSALS, + }; + const objectDef = { name: 'crm_invoice', actions: [action] }; + const ql: any = { + executeAction: vi.fn(async () => { throw thrown; }), + getSchema: (n: string) => (n === objectDef.name ? objectDef : undefined), + registry: { getObject: (n: string) => (n === objectDef.name ? objectDef : undefined), getItem: () => undefined }, + find: vi.fn(async () => [{ id: 'inv_1', status: 'sent' }]), + insert: vi.fn(), update: vi.fn(), delete: vi.fn(), + }; + const metadata: any = { + load: vi.fn(async () => null), + listObjects: vi.fn(async () => [objectDef]), + getObject: vi.fn(async () => objectDef), + }; + const kernel: any = { + context: { + getService: (n: string) => + n === 'objectql' || n === 'data' ? ql : n === 'metadata' ? metadata : null, + }, + }; + const res: any = await new HttpDispatcher(kernel).handleActions( + '/crm_invoice/submit_signoff/inv_1', + 'POST', + {}, + { request: {}, environmentId: 'platform', executionContext: { userId: 'u1', systemPermissions: [] } } as any, + ); + return res.response; +} + +describe('[#34273] the `/actions` door answers the declared refusal in the caller\'s language', () => { + it('the entry\'s status and code, and the translated sentence on `userMessage`', async () => { + const i18n = () => i18nService({ [BOUND_KEY]: ZH_BOUND }); + const err = await rejectionOf(boundAction(throwing('NOT_DRAFT'), { i18n })(actionCtx('zh-CN'))); + const response = await throughActionsDoor(err); + expect(response.status).toBe(409); + expect(response.body.error.userMessage).toBe(ZH_BOUND); + expect(JSON.stringify(response.body)).toContain('NOT_DRAFT'); + expect(JSON.stringify(response.body)).not.toContain('internal detail'); + }); + + it('CONTROL: an action without `refusals` keeps the body\'s own 400 and no `userMessage`', async () => { + const err = await rejectionOf(boundAction(throwing('NOT_DRAFT'), { refusals: undefined })(actionCtx('zh-CN'))); + const response = await throughActionsDoor(err); + expect(response.status).toBe(400); + expect(response.body.error.userMessage).toBeUndefined(); + }); +}); diff --git a/packages/spec/liveness/action.json b/packages/spec/liveness/action.json index 6e15ce14fdb..c60d9865f79 100644 --- a/packages/spec/liveness/action.json +++ b/packages/spec/liveness/action.json @@ -90,6 +90,50 @@ "evidence": "packages/runtime/src/sandbox/body-runner.ts#actionBodyRunnerFactory (`const raw = action.body`, in the factory whose own header calls it \"the ONE choke point where an `action.body` becomes an executable handler\" — both bind paths reach it: AppPlugin's collectBundleActions walk and engine.setDefaultActionRunner); packages/runtime/src/action-execution.ts#isHeadlessInvokableAction (gates headless dispatch on `action?.target || action?.body`)", "note": "server script (L1/L2) via engine.executeAction→body-runner. 2026-08-26: REPOINTED — the evidence cited packages/runtime/src/http-dispatcher.ts, which reads this key nowhere. Its 68 word-`body` occurrences are the inbound HTTP request body — the `body: any` parameter threaded through the handleX delegates (:890, :961, :1732, :1969 …) and the result envelope at :728 — plus the file's own \"Thin delegate — body extracted to ./domains/…\" extraction comments, where `body` means a function body. The consumer this note already NAMED in prose (body-runner) is where the read has always been; the surrounding action path was extracted into domains/actions.ts + action-execution.ts, and http-dispatcher.ts now only delegates (handleActions → handleActionsRequest at :1969-1970). WHY THE GATE COULD NOT SEE THE ROT: `body` is both a common English word and the name of the HTTP request member this dispatcher is built around, so the word-bounded key-mention check added in #11457 anchors on 68 unrelated hits and passes — the designed, honest limit of that signal, which is why this needed a hand call-graph read. Note the shape the repoint exposes: the NOTE's pointer (\"via engine.executeAction→body-runner\") stayed true the whole time while the EVIDENCE pointer rotted — the same split recorded on `requiredPermissions`, one layer over. 2026-08-28: RE-ANCHORED (commit 93ea19bca) — re-closed by hand against c459da6bc; both consumers stand where the 08-26 repoint put them, so the lines had not yet rotted and this is the grammar migration, not a second repair. The anchor is what makes that claim re-testable next time: `actionBodyRunnerFactory` is the symbol the header already calls the ONE choke point, so a consumer that moves inside this 798-line file keeps the pointer true and one that is deleted turns it red." }, + "refusals": { + "status": "live", + "verifiedAt": "2026-11-17", + "evidenceScope": "in-repo", + "evidence": "packages/runtime/src/sandbox/hook-refusal-catalogue.ts#resolveActionRefusal (the one reader: a sandboxed action body's throw of a declared code is answered with that entry, and any other deliberate throw of an action that declares `refusals` is refused as a fault naming the action and the code); packages/runtime/src/sandbox/body-runner.ts#actionBodyRunnerFactory (hands every body throw of the action to `resolveActionRefusal` before it leaves the handler)", + "producer": "packages/runtime/src/app-plugin.ts#collectBundleActions and packages/runtime/src/app-artifact-handlers.ts#bindAppArtifactHandlers (hand the AUTHORED action, `refusals` included, to the body runner factory); packages/spec/src/ui/action.zod.ts#refuseUndeclaredLiteralActionRefusalCode (refuses at save a catalogue on an action that runs no js body, and a code or reason the body throws literally that the catalogue does not declare)", + "note": "[#34273] The hook catalogue's twin (`HookSchema.refusals`, #26170 ruling 6431311681 letter A; #33214 ruling 6879477573), seeded `live` with its reader in one change (Prime Directive 10): the key, the action body runner that answers it, the translation address (`objects.._actions..refusals.…` / `globalActions..refusals.…`), `objectstack validate`'s key check and the i18n coverage walk. One entry shape for both catalogues (`data/declared-entry.zod.ts`) and one run-time answer (`resolveSandboxedRefusal`). An error a host call raised and the body let through unchanged, a crash and a sandbox fault pass through untouched. DRILLED to the entry's four keys: the entry face is closed (`.strict()`).", + "children": { + "message": { + "status": "live", + "verifiedAt": "2026-11-17", + "evidenceScope": "in-repo", + "evidence": "packages/runtime/src/sandbox/hook-refusal-catalogue.ts#ownerRefusalMessage (the sentence the refusal is answered with: `actionRefusalMessageKey` — `objects.._actions..refusals..message`, or `globalActions..refusals..message` for an object-less action — picked through the `i18n` service in the caller's `executionContext.locale`, negotiated by `resolveBundleLocale`, else the declared `message`); packages/runtime/src/sandbox/hook-refusal-catalogue.ts#resolveActionRefusal (serves it as the refusal's caller-facing sentence and its `userMessage`)" + }, + "status": { + "status": "live", + "verifiedAt": "2026-11-17", + "evidenceScope": "in-repo", + "evidence": "packages/runtime/src/sandbox/hook-refusal-catalogue.ts#resolveActionRefusal (the refusal carries the declared `status`, else 400; the status the body set on its own throw is not read)" + }, + "reasons": { + "status": "live", + "verifiedAt": "2026-11-17", + "evidenceScope": "in-repo", + "evidence": "packages/runtime/src/sandbox/hook-refusal-catalogue.ts#declaredAnswer (a throw naming a `reason` the code declares is answered with that reason's sentence, the code's status and the code on the wire; an undeclared reason is refused as a fault naming the action, the code and the reason); packages/runtime/src/sandbox/hook-refusal-catalogue.ts#ownerRefusalMessage (picks the reason's sentence and its key, `….refusals..reasons..message`)", + "producer": "packages/spec/src/ui/action.zod.ts#refuseUndeclaredLiteralActionRefusalCode (refuses at save a reason the body throws literally and the code does not declare)", + "children": { + "message": { + "status": "live", + "verifiedAt": "2026-11-17", + "evidenceScope": "in-repo", + "evidence": "packages/runtime/src/sandbox/hook-refusal-catalogue.ts#ownerRefusalMessage (the reason's sentence the refusal is answered with, translated through `….refusals..reasons..message`, else as declared)" + } + } + }, + "params": { + "status": "live", + "verifiedAt": "2026-11-17", + "evidenceScope": "in-repo", + "evidence": "packages/runtime/src/sandbox/hook-refusal-catalogue.ts#renderHookTemplate (fills the picked sentence's `{{ NAME }}` holes from the throw's `params` through the formula template engine, the declared names alone in scope); packages/runtime/src/sandbox/hook-refusal-catalogue.ts#ownerRefusalMessage (renders an entry that declares `params`; one that declares none stays plain text)", + "producer": "packages/spec/src/data/declared-entry.zod.ts#declaredRefusalEntrySchema (judges each sentence's holes against the declared names at save)" + } + } + }, "params": { "status": "live", "verifiedAt": "2026-09-15", diff --git a/packages/spec/src/data/declared-entry.zod.ts b/packages/spec/src/data/declared-entry.zod.ts index 956ef8d3b68..67f4dfc14f7 100644 --- a/packages/spec/src/data/declared-entry.zod.ts +++ b/packages/spec/src/data/declared-entry.zod.ts @@ -116,6 +116,8 @@ export type DeclaredRefusalSubject = 'hook' | 'action'; interface RefusalWords { /** `hook` / `action`. */ noun: DeclaredRefusalSubject; + /** The noun with its sentence-initial article: `A hook` / `An action`. */ + aNoun: string; /** The translation key of a code's message, as the describe text spells it. */ messageKey: string; /** The translation key of a reason's message, as the describe text spells it. */ @@ -129,6 +131,7 @@ interface RefusalWords { const REFUSAL_WORDS: Record = { hook: { noun: 'hook', + aNoun: 'A hook', messageKey: 'hooks..refusals..message', reasonKey: 'hooks..refusals..reasons..message', thrower: 'the body', @@ -136,6 +139,7 @@ const REFUSAL_WORDS: Record = { }, action: { noun: 'action', + aNoun: 'An action', messageKey: 'objects.._actions..refusals..message (globalActions..… for an object-less action)', reasonKey: @@ -205,7 +209,7 @@ function refusalReasonSchema(w: RefusalWords) { */ export function declaredRefusalEntrySchema(subject: DeclaredRefusalSubject) { const w = REFUSAL_WORDS[subject]; - const rule: SentenceRule = { slot: `A ${w.noun} refusal \`message\``, holeRefused: w.holeRefused }; + const rule: SentenceRule = { slot: `${w.aNoun} refusal \`message\``, holeRefused: w.holeRefused }; return lazySchema(() => strictObject( { surface: `this ${w.noun} refusal`, @@ -219,7 +223,7 @@ export function declaredRefusalEntrySchema(subject: DeclaredRefusalSubject) { '`code` is not a refusal key — the code is the entry\'s KEY in `refusals` ' + `(\`refusals: { CLEAN_VERSION_REQUIRED: { message } }\`), and ${w.thrower} throws it.`, title: - `A ${w.noun} refusal has no heading — the caller reads the \`message\` alone. Write the sentence in \`message\`.`, + `${w.aNoun} refusal has no heading — the caller reads the \`message\` alone. Write the sentence in \`message\`.`, }, }, { diff --git a/packages/spec/src/data/hook-refusal-codes.ts b/packages/spec/src/data/hook-refusal-codes.ts index 843c8eeced5..886fe0dde89 100644 --- a/packages/spec/src/data/hook-refusal-codes.ts +++ b/packages/spec/src/data/hook-refusal-codes.ts @@ -261,6 +261,9 @@ export function undeclaredHookRefusalCodeAtSave( /** [#34273] Which declaration a refusal catalogue sits on, as the sentences name it. */ type RefusalSubject = 'hook' | 'action'; +/** The subject with its sentence-initial article: `A hook` / `An action`. */ +const capArticle = (subject: RefusalSubject): string => (subject === 'action' ? 'An action' : 'A hook'); + function undeclaredRefusalCodeAtSave( subject: RefusalSubject, code: string, @@ -269,7 +272,7 @@ function undeclaredRefusalCodeAtSave( ): string { return ( `\`${at}\` throws code '${code}', and this ${subject}'s \`refusals\` declares no such code ` - + `(declared: ${declaredList(declared)}). A ${subject} that declares \`refusals\` refuses by code only, so the ` + + `(declared: ${declaredList(declared)}). ${capArticle(subject)} that declares \`refusals\` refuses by code only, so the ` + `throw is refused when the ${subject} runs. Declare it under \`refusals.${code}\` with the message the user ` + 'reads, or throw one of the declared codes.' ); @@ -292,7 +295,7 @@ export const ACTION_REFUSAL_MESSAGE_HOLE_REFUSED = refusalMessageHoleRefused('ac function refusalMessageHoleRefused(subject: RefusalSubject): string { return ( - `A ${subject} refusal \`message\` whose entry declares no \`params\` is plain text, and nothing fills a \`{{ }}\` hole: the ` + `${capArticle(subject)} refusal \`message\` whose entry declares no \`params\` is plain text, and nothing fills a \`{{ }}\` hole: the ` + 'caller would read the braces as written. Declare the name under the entry\'s `params` (`params: [\'state\']`) ' + 'and throw it in the error\'s `params` (`{ code, params: { state } }`), or write the sentence without the hole.' ); @@ -338,7 +341,7 @@ function undeclaredRefusalAtRun( const thrown = code === undefined ? 'threw no `code`' : `threw code '${code}'`; return ( `${subject} '${name}' ${thrown}, and its \`refusals\` declares no such code (declared: ${declaredList(declared)}). ` - + `A ${subject} that declares \`refusals\` refuses by code only: throw an error whose \`code\` is one of the declared ` + + `${capArticle(subject)} that declares \`refusals\` refuses by code only: throw an error whose \`code\` is one of the declared ` + 'codes, or declare this one with the message the user reads.' ); } @@ -508,22 +511,13 @@ export function undeclaredHookTextAtRun(hookName: string, key: string, declared: */ /** The save-time refusal for a code an action's source throws literally that its `refusals` does not declare. */ -export function undeclaredActionRefusalCodeAtSave( - code: string, - declared: readonly string[], - at: 'body.source' | 'target' = 'body.source', -): string { - return undeclaredRefusalCodeAtSave('action', code, declared, at); +export function undeclaredActionRefusalCodeAtSave(code: string, declared: readonly string[]): string { + return undeclaredRefusalCodeAtSave('action', code, declared, 'body.source'); } /** The save-time refusal for a reason an action's source throws literally under a code that does not declare it. */ -export function undeclaredActionRefusalReasonAtSave( - code: string, - reason: string, - declared: readonly string[], - at: 'body.source' | 'target' = 'body.source', -): string { - return undeclaredRefusalReasonAtSave('action', code, reason, declared, at); +export function undeclaredActionRefusalReasonAtSave(code: string, reason: string, declared: readonly string[]): string { + return undeclaredRefusalReasonAtSave('action', code, reason, declared, 'body.source'); } /** The run-time fault for an action's throw its catalogue cannot answer: an undeclared code, or none. */ diff --git a/packages/spec/src/system/translation.zod.ts b/packages/spec/src/system/translation.zod.ts index abf7bad6f91..209f863812d 100644 --- a/packages/spec/src/system/translation.zod.ts +++ b/packages/spec/src/system/translation.zod.ts @@ -345,7 +345,7 @@ const refusalTranslationsSchema = (noun: 'hook' | 'action') => z.record(z.string // entry's declared `params`; an empty string is the untranslated // skeleton slot `os i18n extract` writes (the declared message is served). message: z.string().optional().describe( - `Translated refusal message of a ${noun}'s declared refusal code — served whole in the caller's locale in ` + `Translated refusal message of ${noun === 'action' ? 'an action' : 'a hook'}'s declared refusal code — served whole in the caller's locale in ` + 'place of the declared message, its {{ }} holes (over the entry\'s declared params) filled after', ), // [#33214] A declared reason's sentence under the same code. @@ -355,7 +355,7 @@ const refusalTranslationsSchema = (noun: 'hook' | 'action') => z.record(z.string aliases: { text: 'message', description: 'message' }, }, { message: z.string().optional().describe( - `Translated sentence of a declared reason under a ${noun}'s refusal code — served in place of the declared ` + `Translated sentence of a declared reason under ${noun === 'action' ? 'an action' : 'a hook'}'s refusal code — served in place of the declared ` + 'reason message, its {{ }} holes filled after', ), })).optional().describe("Reason translations keyed by the reason the code's `reasons` declares"), diff --git a/packages/spec/src/ui/action-refusals.test.ts b/packages/spec/src/ui/action-refusals.test.ts new file mode 100644 index 00000000000..c184b0d1a59 --- /dev/null +++ b/packages/spec/src/ui/action-refusals.test.ts @@ -0,0 +1,268 @@ +import { describe, it, expect } from 'vitest'; +import { ActionSchema, ActionRefusalSchema } from './action.zod'; +import { HookRefusalSchema, HookTextSchema } from '../data/hook.zod'; +import { + ACTION_REFUSAL_MESSAGE_HOLE_REFUSED, + HOOK_REFUSAL_MESSAGE_HOLE_REFUSED, + HOOK_TEXT_MESSAGE_HOLE_REFUSED, + actionRefusalsWithoutSandboxedBody, + undeclaredActionRefusalAtRun, + undeclaredActionRefusalCodeAtSave, + undeclaredActionRefusalReasonAtRun, + undeclaredActionRefusalReasonAtSave, + undeclaredHookRefusalAtRun, + undeclaredHookRefusalCodeAtSave, +} from '../data/hook-refusal-codes'; +import { actionRefusalMessageKey } from '../system/i18n-resolver'; +import { TranslationDataSchema } from '../system/translation.zod'; + +// #34273: an action declares its refusal catalogue the way a hook does +// (`HookSchema.refusals`, #26170 ruling 6431311681 letter A; #33214 ruling +// 6879477573) — `refusals: { : { message, status?, reasons?, params? } }` +// — and its sandboxed body refuses by code only. + +const base = { name: 'submit_signoff', label: 'Submit', objectName: 'crm_invoice', type: 'script' as const }; +const body = (source: string) => ({ language: 'js' as const, source }); + +const issuesOf = (r: { success: boolean; error?: { issues: Array<{ path: PropertyKey[]; message: string }> } }) => + r.success ? [] : r.error!.issues; + +describe('Action.refusals — the declared catalogue', () => { + it('accepts a catalogue of SCREAMING_SNAKE codes with a message and an optional 4xx status', () => { + const parsed = ActionSchema.parse({ + ...base, + body: body("throw Object.assign(new Error('x'), { code: 'NOT_DRAFT' });"), + refusals: { + NOT_DRAFT: { message: 'Only a draft invoice can be signed off.', status: 409 }, + SIGN_IN_REQUIRED: { message: 'Sign in first.', status: 401 }, + }, + }); + expect(parsed.refusals?.NOT_DRAFT).toEqual({ message: 'Only a draft invoice can be signed off.', status: 409 }); + expect(parsed.refusals?.SIGN_IN_REQUIRED.status).toBe(401); + }); + + it('CONTROL: is optional — an action with no catalogue parses as before', () => { + const parsed = ActionSchema.parse({ ...base, body: body("throw new Error('no');") }); + expect(parsed.refusals).toBeUndefined(); + }); + + it('refuses a code that is not SCREAMING_SNAKE, at `refusals`', () => { + const r = ActionSchema.safeParse({ ...base, body: body('return;'), refusals: { notDraft: { message: 'x' } } }); + expect(r.success).toBe(false); + expect(issuesOf(r).some((i) => i.path[0] === 'refusals')).toBe(true); + }); + + it('refuses an empty message and a 5xx status', () => { + expect(ActionSchema.safeParse({ ...base, body: body('return;'), refusals: { NO: { message: ' ' } } }).success).toBe(false); + expect( + ActionSchema.safeParse({ ...base, body: body('return;'), refusals: { NO: { message: 'x', status: 500 } } }).success, + ).toBe(false); + }); + + it.each([ + ['no body', { type: 'script' }, "no `body` and no inline `target` function"], + ['an expression body', { type: 'script', body: { language: 'expression', source: 'record.amount > 0' } }, 'a `expression` body'], + ['a url action', { type: 'url', target: 'https://example.com' }, "`type: 'url'`"], + ['a flow action', { type: 'flow', target: 'approve_invoice' }, "`type: 'flow'`"], + ])('refuses a catalogue on an action that runs no js body of its own — %s', (_label, shape, says) => { + const r = ActionSchema.safeParse({ ...base, ...shape, refusals: { NOT_DRAFT: { message: 'x' } } }); + expect(r.success).toBe(false); + const issue = issuesOf(r).find((i) => i.path.join('.') === 'refusals'); + expect(issue?.message).toContain(says); + expect(issue?.message).toContain('drop `refusals`'); + }); + + it('accepts a catalogue on an action whose `type` is omitted (the schema default is `script`)', () => { + const { type: _omit, ...untyped } = base; + expect(ActionSchema.safeParse({ ...untyped, body: body('return;'), refusals: { NOT_DRAFT: { message: 'x' } } }).success) + .toBe(true); + }); + + it('names `httpStatus` as the rename onto `status` it is', () => { + const r = ActionSchema.safeParse({ ...base, body: body('return;'), refusals: { NO: { message: 'x', httpStatus: 409 } } }); + expect(r.success).toBe(false); + expect(issuesOf(r).find((i) => i.path.join('.').startsWith('refusals.NO'))?.message).toContain('`httpStatus` → `status`'); + }); +}); + +describe('Action.refusals — an undeclared code or reason is refused at save where the body names it literally', () => { + const refusals = { + NOT_DRAFT: { message: 'Only a draft invoice can be signed off.' }, + STAGE_LOCKED: { message: 'Locked.', reasons: { closed: { message: 'Closed.' } } }, + }; + + it('refuses a literal `code:` the catalogue does not declare, at `body.source`, naming the declared codes', () => { + const r = ActionSchema.safeParse({ + ...base, + body: body("throw Object.assign(new Error('x'), { code: 'NOT_DRAFTT' });"), + refusals, + }); + expect(r.success).toBe(false); + const issue = issuesOf(r).find((i) => i.path.join('.') === 'body.source'); + expect(issue?.message).toBe(undeclaredActionRefusalCodeAtSave('NOT_DRAFTT', ['NOT_DRAFT', 'STAGE_LOCKED'])); + expect(issue?.message).toContain("this action's `refusals` declares no such code"); + }); + + it('refuses a literal reason a code with `reasons` does not declare, at `body.source`', () => { + const r = ActionSchema.safeParse({ + ...base, + body: body("throw { code: 'STAGE_LOCKED', reason: 'clsoed' };"), + refusals, + }); + expect(r.success).toBe(false); + const issue = issuesOf(r).find((i) => i.path.join('.') === 'body.source'); + expect(issue?.message).toBe(undeclaredActionRefusalReasonAtSave('STAGE_LOCKED', 'clsoed', ['closed'])); + }); + + it('CONTROL: accepts a body whose literal codes and reasons are all declared', () => { + expect(ActionSchema.safeParse({ + ...base, + body: body("if (ctx.input.a) throw { code: 'STAGE_LOCKED', reason: 'closed' }; throw { code: 'NOT_DRAFT' };"), + refusals, + }).success).toBe(true); + }); + + it('CONTROL: leaves a computed code to the run-time refusal', () => { + expect(ActionSchema.safeParse({ + ...base, + body: body("const c = 'NOT_' + 'X'; throw Object.assign(new Error('x'), { code: c });"), + refusals, + }).success).toBe(true); + }); + + it('CONTROL: reads nothing when the action declares no catalogue — its throws save as before', () => { + expect(ActionSchema.safeParse({ + ...base, + body: body("throw Object.assign(new Error('x'), { code: 'ANY_CODE' });"), + }).success).toBe(true); + }); +}); + +describe('ActionRefusal.reasons and .params — the hook entry\'s rules', () => { + it('accepts a hole over a declared param in the message and in a reason', () => { + expect(ActionRefusalSchema.safeParse({ + message: 'Stage {{ stage }} is locked.', + params: ['stage'], + reasons: { closed: { message: 'A {{ stage | upper }} deal is closed.' } }, + }).success).toBe(true); + }); + + it('refuses a hole over a name the entry does not declare, naming the action slot', () => { + const r = ActionRefusalSchema.safeParse({ message: 'Stage {{ phase }} is locked.', params: ['stage'] }); + expect(r.success).toBe(false); + const issue = issuesOf(r).find((i) => i.path.join('.') === 'message'); + expect(issue?.message).toContain('An action refusal `message`'); + }); + + it('refuses every hole when the entry declares no params, with the action sentence', () => { + const r = ActionRefusalSchema.safeParse({ message: 'Stage {{ stage }} is locked.' }); + expect(issuesOf(r).find((i) => i.path.join('.') === 'message')?.message).toBe(ACTION_REFUSAL_MESSAGE_HOLE_REFUSED); + const reason = ActionRefusalSchema.safeParse({ message: 'x', reasons: { closed: { message: '{{ stage }}' } } }); + expect(issuesOf(reason).find((i) => i.path.join('.') === 'reasons.closed.message')?.message) + .toBe(ACTION_REFUSAL_MESSAGE_HOLE_REFUSED); + }); + + it('refuses a reason that is not snake_case, and a param declared twice', () => { + expect(ActionRefusalSchema.safeParse({ message: 'x', reasons: { Closed: { message: 'y' } } }).success).toBe(false); + const r = ActionRefusalSchema.safeParse({ message: '{{ stage }}', params: ['stage', 'stage'] }); + expect(issuesOf(r).find((i) => i.path.join('.') === 'params.1')?.message).toContain("names 'stage' twice"); + }); +}); + +describe('the shared declared-entry factory — one shape, the words per subject', () => { + it('the hook and action refusal entries accept and refuse the same documents', () => { + const docs: unknown[] = [ + { message: 'x' }, + { message: 'x', status: 409 }, + { message: '{{ a }}', params: ['a'] }, + { message: 'x', reasons: { r: { message: 'y' } } }, + { message: '' }, + { message: 'x', status: 500 }, + { message: '{{ b }}', params: ['a'] }, + { message: 'x', code: 'X' }, + { message: 'x', extra: 1 }, + ]; + for (const doc of docs) { + expect(ActionRefusalSchema.safeParse(doc).success, JSON.stringify(doc)) + .toBe(HookRefusalSchema.safeParse(doc).success); + } + }); + + it('each subject keeps its own words — the hook sentences are unchanged', () => { + expect(issuesOf(HookRefusalSchema.safeParse({ message: '{{ a }}' }))[0]?.message).toBe(HOOK_REFUSAL_MESSAGE_HOLE_REFUSED); + expect(issuesOf(HookTextSchema.safeParse({ message: '{{ a }}' }))[0]?.message).toBe(HOOK_TEXT_MESSAGE_HOLE_REFUSED); + expect(issuesOf(ActionRefusalSchema.safeParse({ message: '{{ a }}' }))[0]?.message).toBe(ACTION_REFUSAL_MESSAGE_HOLE_REFUSED); + }); + + it('a text entry is the core with no `status` or `reasons`', () => { + expect(HookTextSchema.safeParse({ message: 'Follow up {{ lead }}', params: ['lead'] }).success).toBe(true); + expect(HookTextSchema.safeParse({ message: 'x', status: 400 }).success).toBe(false); + expect(HookTextSchema.safeParse({ message: 'x', reasons: {} }).success).toBe(false); + }); +}); + +describe('the run-time sentences name the action', () => { + it('an undeclared code is a fault naming the action, the code and the declared codes', () => { + const m = undeclaredActionRefusalAtRun('submit_signoff', 'NOT_DRAFTT', ['NOT_DRAFT']); + expect(m).toContain("action 'submit_signoff' threw code 'NOT_DRAFTT'"); + expect(m).toContain('NOT_DRAFT'); + // The hook twin is unchanged by the shared core. + expect(undeclaredHookRefusalAtRun('credit_guard', 'X', ['Y'])).toContain("hook 'credit_guard' threw code 'X'"); + expect(undeclaredHookRefusalCodeAtSave('X', ['Y'])).toContain("this hook's `refusals` declares no such code"); + }); + + it('an undeclared reason names the action, the code and the reason', () => { + expect(undeclaredActionRefusalReasonAtRun('submit_signoff', 'STAGE_LOCKED', 'clsoed', ['closed'])) + .toContain("action 'submit_signoff' threw code 'STAGE_LOCKED' with reason 'clsoed'"); + }); + + it('the catalogue-without-body refusal names the type', () => { + expect(actionRefusalsWithoutSandboxedBody('url', undefined)).toContain("`type: 'url'`"); + }); +}); + +describe('the translation address — beside the action\'s other copy', () => { + it('a bound action: `objects.._actions..refusals..message`', () => { + expect(actionRefusalMessageKey('crm_invoice', 'submit_signoff', 'NOT_DRAFT')) + .toBe('objects.crm_invoice._actions.submit_signoff.refusals.NOT_DRAFT.message'); + expect(actionRefusalMessageKey('crm_invoice', 'submit_signoff', 'STAGE_LOCKED', 'closed')) + .toBe('objects.crm_invoice._actions.submit_signoff.refusals.STAGE_LOCKED.reasons.closed.message'); + }); + + it('an object-less action: `globalActions..refusals..message`', () => { + expect(actionRefusalMessageKey(undefined, 'export_all', 'NOT_ALLOWED')) + .toBe('globalActions.export_all.refusals.NOT_ALLOWED.message'); + expect(actionRefusalMessageKey('', 'export_all', 'NOT_ALLOWED', 'quota')) + .toBe('globalActions.export_all.refusals.NOT_ALLOWED.reasons.quota.message'); + }); + + it('is a path a translation bundle can write, at both addresses, reasons included', () => { + const r = TranslationDataSchema.safeParse({ + objects: { + crm_invoice: { + _actions: { + submit_signoff: { + refusals: { + NOT_DRAFT: { message: '只有草稿发票可以签核。' }, + STAGE_LOCKED: { message: '已锁定。', reasons: { closed: { message: '{{ stage }} 已关闭。' } } }, + }, + }, + }, + }, + }, + globalActions: { export_all: { refusals: { NOT_ALLOWED: { message: '' } } } }, + }) as { success: true; data: any }; + expect(r.success).toBe(true); + expect(r.data.objects.crm_invoice._actions.submit_signoff.refusals.NOT_DRAFT.message).toBe('只有草稿发票可以签核。'); + expect(r.data.globalActions.export_all.refusals.NOT_ALLOWED.message).toBe(''); + }); + + it('refuses a key an action refusal translation does not hold, and names `refusal` as the rename it is', () => { + expect(TranslationDataSchema.safeParse({ + globalActions: { export_all: { refusals: { NOT_ALLOWED: { label: 'x' } } } }, + }).success).toBe(false); + const r = TranslationDataSchema.safeParse({ globalActions: { export_all: { refusal: {} } } }); + expect(r.success).toBe(false); + expect(issuesOf(r).find((i) => /unrecognized|rename|→/.test(i.message))?.message).toContain('`refusal` → `refusals`'); + }); +}); diff --git a/packages/spec/src/ui/action.zod.ts b/packages/spec/src/ui/action.zod.ts index e9c74b24f9e..7347661c76c 100644 --- a/packages/spec/src/ui/action.zod.ts +++ b/packages/spec/src/ui/action.zod.ts @@ -2551,18 +2551,6 @@ function refuseUnopenableOnSuccessNavigate( if (refusal !== undefined) ctx.addIssue({ code: 'custom', path: ['navigate'], message: refusal }); } -/** - * [#25653, ruling record 6384657105 letter A] App-authored automation does not - * use elevation to write the four identity-assignment objects, and an action - * body always runs as system (`buildActionExecutionContext`, runtime). The data - * middleware refuses the write at run time (`flow-system-identity-write-refusal.ts`, - * plugin-security); this refuses the `script` action whose sandboxed JS (L2) - * `body` names one — a write method on `ctx.api.object('')`, called on - * the handle or on a name the body bound it to — at every door that parses an - * action, one issue per object at `body.source`. An expression (L1) body - * performs no IO, and reads of the four objects stay legal, as at run time. - * `HookSchema` carries the same check for a `runAs: 'system'` hook. - */ /** * [#34273] One entry of an action's refusal catalogue (`ActionSchema.refusals`): * the sentence the user reads when the action's body throws the entry's code, @@ -2620,6 +2608,18 @@ function refuseUndeclaredLiteralActionRefusalCode( } } +/** + * [#25653, ruling record 6384657105 letter A] App-authored automation does not + * use elevation to write the four identity-assignment objects, and an action + * body always runs as system (`buildActionExecutionContext`, runtime). The data + * middleware refuses the write at run time (`flow-system-identity-write-refusal.ts`, + * plugin-security); this refuses the `script` action whose sandboxed JS (L2) + * `body` names one — a write method on `ctx.api.object('')`, called on + * the handle or on a name the body bound it to — at every door that parses an + * action, one issue per object at `body.source`. An expression (L1) body + * performs no IO, and reads of the four objects stay legal, as at run time. + * `HookSchema` carries the same check for a `runAs: 'system'` hook. + */ function refuseIdentityAssignmentBodyWrite( data: { type?: string; body?: { language?: string; source?: unknown } }, ctx: z.core.$RefinementCtx, From aa821064390c6aa82909807e3a86dad4cd062407 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 07:32:14 +0000 Subject: [PATCH 05/13] chore(spec, lint, metadata-protocol): regenerate artifacts and record the forced pins for action.refusals check:generated --fix outputs (api-surface, export-origins, declaration-map, reference docs, liveness counts, strictness-ledger counts and the generator-owned skills reference index lines); a strictness-ledger row for declared-entry.zod.ts; the hook.refusals.params producer re-anchored at the shared factory; ActionRefusalSchema pinned as an isomorphic alias (858); the form-reconciliation omit row for action.refusals; the action top-level property count 53 -> 54. Claude-Session: https://claude.ai/code/session_01ADHkmP879Ku8wbNev27oyN Co-authored-by: Claude --- content/docs/references/data/object.mdx | 1 + content/docs/references/index.mdx | 10 +++--- .../references/kernel/metadata-plugin.mdx | 1 + .../docs/references/system/translation.mdx | 5 +++ content/docs/references/ui/action.mdx | 36 +++++++++++++++++-- .../data.md | 5 +-- .../2026-07-unknown-key-strictness-ledger.md | 1 + ...l.meta-types-degenerate-derivation.test.ts | 6 ++-- packages/spec/api-surface/data.json | 6 ++++ packages/spec/api-surface/system.json | 1 + packages/spec/api-surface/ui.json | 2 ++ packages/spec/declaration-map/ui.json | 2 ++ packages/spec/export-origins/data.json | 6 ++++ packages/spec/export-origins/system.json | 1 + packages/spec/export-origins/ui.json | 2 ++ packages/spec/liveness/hook.json | 2 +- packages/spec/liveness/state-counts/action.md | 2 +- .../metadata-form-zod-reconciliation.test.ts | 11 ++++++ .../src/type-alias-convention.pin.test.ts | 12 +++++-- skills/objectstack-data/references/_index.md | 3 +- skills/objectstack-ui/references/_index.md | 3 +- 21 files changed, 99 insertions(+), 19 deletions(-) diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index d5640b9fcf6..76738d2ed7a 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -500,6 +500,7 @@ const result = ApiMethod.parse(data); | **target** | `string` | optional | URL, Script Name, Flow ID, or API Endpoint. Supports $`{param.X}` and $`{ctx.X}` interpolation. For type:'url': an http:// or https:// URL, a mailto: address, or an in-app path starting with / or ./ (a console route; a record is /apps/APP/OBJECT/record/ID, APP being the app's route segment — see onSuccess.navigate) — every other scheme and a protocol-relative //host are refused. | | **openIn** | `Enum<'self' \| 'new-tab'>` | optional | For type:'url' — where to open `target`. 'new-tab' opens a new browser tab; 'self' navigates in place. When omitted, external/absolute URLs open in a new tab and relative URLs navigate in place. Static execution option — keep it OUT of `params` (which is user-input-collection only). | | **body** | `{ language: 'expression'; source: string } \| { language: 'js'; source: string; capabilities?: Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log' \| …>[]; timeoutMs?: integer; … }` | optional | Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`. An action body runs as system, and its update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' is refused with PERMISSION_DENIED; an insert is not judged by this rule. | +| **refusals** | `Record; params?: string[] }>` | optional | Refusal catalogue keyed by the SCREAMING_SNAKE code the action's js body throws: `{ message, status?, reasons?, params? }`. The body refuses by code only, optionally with a declared reason and params; the runtime answers with the declared message (translated through objects.``._actions.``.refusals.``.message, or globalActions.``.refusals.``.message for an object-less action, ….reasons.``.message for a reason, in the caller's locale, holes filled from params) and status. A code not declared here, or a reason a code with reasons does not declare, is refused loudly — at save when the body throws it literally, otherwise at run time. Only a type: 'script' action with a js body declares one | | **operation** | `Enum<'update'>` | optional | The declarative single-record field write, mirroring a list view's `bulkActionDefs`: `'update'` applies `patch` (merged under the collected `params`) to the current record on the data plane AS THE CALLER — never system-elevated — so the caller's permissions, the object's hooks and its validations fire as for a user edit. `type` stays at its default `'script'` (the platform action route the write is performed on); `target`/`body`/`method`/`bodyExtra` are refused beside it. `'delete'` and `'custom'` have no row-level form. | | **patch** | `Record` | optional | For `operation: 'update'` — static field values written to the current record, merged UNDER the user-supplied `params` so a fixed value can be declared without exposing it in the dialog. Written on the data plane as the caller: object permissions, hooks and validations fire as for a user edit. Refused on an action without `operation: 'update'` (it would be silently dropped). | | **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | The bulk dispatch contract this action's BODY is written for, in `bulkActionDefs`' own vocabulary: 'perRecord' = one dispatch per selected row carrying that row's `recordId` (the view's `bulkActions: ['']` bare-string form); 'aggregate' = ONE dispatch for the whole selection carrying every id in `params._selectedIds` (a `bulkActionDefs` entry with `execution: 'aggregate'`). Optional with NO default — omit it only when the body genuinely serves both. A list view wiring a declared action under the other contract is refused by `@objectstack/lint` (`action-dispatch-contract-mismatch`). | diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index d6c69c93bff..b1e49a0ec2d 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1669 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1670 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -33,8 +33,8 @@ counts are sums of the rows they head. Regenerate with | [Shared Protocol](/docs/references/shared) | 10 | 31 | Primitives used across every protocol — identifiers, HTTP, expressions, error maps, enums. | | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 297 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | -| [UI Protocol](/docs/references/ui) | 16 | 177 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **218** | **1669** | 14 protocol modules | +| [UI Protocol](/docs/references/ui) | 16 | 178 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | +| **Total** | **218** | **1670** | 14 protocol modules | --- @@ -385,13 +385,13 @@ The runtime environment — logging, jobs, cache, metrics, notifications, i18n a ## UI Protocol -**Source:** `packages/spec/src/ui/` · **Import:** `@objectstack/spec/ui` · **16 pages, 177 schemas** +**Source:** `packages/spec/src/ui/` · **Import:** `@objectstack/spec/ui` · **16 pages, 178 schemas** Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | File | Schemas | | :--- | :--- | -| [`action.zod.ts`](/docs/references/ui/action) | `Action`, `ActionAi`, `ActionLocation`, `ActionParam`, `ActionType`, `InlineAction` | +| [`action.zod.ts`](/docs/references/ui/action) | `Action`, `ActionAi`, `ActionLocation`, `ActionParam`, `ActionRefusal`, `ActionType`, `InlineAction` | | [`action-params.zod.ts`](/docs/references/ui/action-params) | `ActionSession` | | [`app.zod.ts`](/docs/references/ui/app) | `ActionNavItem`, `App`, `AppBranding`, `AppContextSelector`, `AppLandingEntry`, `ComponentNavItem`, `DashboardNavItem`, `DocNavItem`, `GroupNavItem`, `NavigationArea`, `NavigationContribution`, `NavigationItem`, `ObjectNavItem`, `PageNavItem`, `ReportNavItem`, `UrlNavItem` | | [`bulk-action.zod.ts`](/docs/references/ui/bulk-action) | `BulkActionDef`, `BulkActionExecution`, `BulkActionOperation`, `BulkActionParam`, `BulkActionResult` | diff --git a/content/docs/references/kernel/metadata-plugin.mdx b/content/docs/references/kernel/metadata-plugin.mdx index 142a458c8f7..f17a715bf92 100644 --- a/content/docs/references/kernel/metadata-plugin.mdx +++ b/content/docs/references/kernel/metadata-plugin.mdx @@ -331,6 +331,7 @@ const result = MetadataBulkResultSchema.parse(data); | **target** | `string` | optional | URL, Script Name, Flow ID, or API Endpoint. Supports $`{param.X}` and $`{ctx.X}` interpolation. For type:'url': an http:// or https:// URL, a mailto: address, or an in-app path starting with / or ./ (a console route; a record is /apps/APP/OBJECT/record/ID, APP being the app's route segment — see onSuccess.navigate) — every other scheme and a protocol-relative //host are refused. | | **openIn** | `Enum<'self' \| 'new-tab'>` | optional | For type:'url' — where to open `target`. 'new-tab' opens a new browser tab; 'self' navigates in place. When omitted, external/absolute URLs open in a new tab and relative URLs navigate in place. Static execution option — keep it OUT of `params` (which is user-input-collection only). | | **body** | `{ language: 'expression'; source: string } \| { language: 'js'; source: string; capabilities?: Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log' \| …>[]; timeoutMs?: integer; … }` | optional | Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`. An action body runs as system, and its update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' is refused with PERMISSION_DENIED; an insert is not judged by this rule. | +| **refusals** | `Record; params?: string[] }>` | optional | Refusal catalogue keyed by the SCREAMING_SNAKE code the action's js body throws: `{ message, status?, reasons?, params? }`. The body refuses by code only, optionally with a declared reason and params; the runtime answers with the declared message (translated through objects.``._actions.``.refusals.``.message, or globalActions.``.refusals.``.message for an object-less action, ….reasons.``.message for a reason, in the caller's locale, holes filled from params) and status. A code not declared here, or a reason a code with reasons does not declare, is refused loudly — at save when the body throws it literally, otherwise at run time. Only a type: 'script' action with a js body declares one | | **operation** | `Enum<'update'>` | optional | The declarative single-record field write, mirroring a list view's `bulkActionDefs`: `'update'` applies `patch` (merged under the collected `params`) to the current record on the data plane AS THE CALLER — never system-elevated — so the caller's permissions, the object's hooks and its validations fire as for a user edit. `type` stays at its default `'script'` (the platform action route the write is performed on); `target`/`body`/`method`/`bodyExtra` are refused beside it. `'delete'` and `'custom'` have no row-level form. | | **patch** | `Record` | optional | For `operation: 'update'` — static field values written to the current record, merged UNDER the user-supplied `params` so a fixed value can be declared without exposing it in the dialog. Written on the data plane as the caller: object permissions, hooks and validations fire as for a user edit. Refused on an action without `operation: 'update'` (it would be silently dropped). | | **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | The bulk dispatch contract this action's BODY is written for, in `bulkActionDefs`' own vocabulary: 'perRecord' = one dispatch per selected row carrying that row's `recordId` (the view's `bulkActions: ['']` bare-string form); 'aggregate' = ONE dispatch for the whole selection carrying every id in `params._selectedIds` (a `bulkActionDefs` entry with `execution: 'aggregate'`). Optional with NO default — omit it only when the body genuinely serves both. A list view wiring a declared action under the other contract is refused by `@objectstack/lint` (`action-dispatch-contract-mismatch`). | diff --git a/content/docs/references/system/translation.mdx b/content/docs/references/system/translation.mdx index 8fa67c8231d..06ce3e12abe 100644 --- a/content/docs/references/system/translation.mdx +++ b/content/docs/references/system/translation.mdx @@ -138,6 +138,7 @@ Translation data for a single field | **params** | `Record }>` | optional | Action parameter translations keyed by parameter name | | **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record }` | optional | Translations for the action result dialog | | **preflight** | `{ fields?: Record }` | optional | Translations for the action preflight panel | +| **refusals** | `Record }>` | optional | Refusal translations keyed by the code the action's `refusals` declares | ### Nested Shape: `ObjectTranslationData._sections[string]` @@ -243,6 +244,7 @@ Translation data for a single object | **params** | `Record }>` | optional | Action parameter translations keyed by parameter name | | **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record }` | optional | Translations for the action result dialog | | **preflight** | `{ fields?: Record }` | optional | Translations for the action preflight panel | +| **refusals** | `Record }>` | optional | Refusal translations keyed by the code the action's `refusals` declares | ### Nested Shape: `PlatformTranslationData.dashboards[string]` @@ -423,6 +425,7 @@ Translation data for a single object | **params** | `Record }>` | optional | Action parameter translations keyed by parameter name | | **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record }` | optional | Translations for the action result dialog | | **preflight** | `{ fields?: Record }` | optional | Translations for the action preflight panel | +| **refusals** | `Record }>` | optional | Refusal translations keyed by the code the action's `refusals` declares | ### Nested Shape: `ServedTranslationData.dashboards[string]` @@ -666,6 +669,7 @@ Translation data for a single object | **params** | `Record }>` | optional | Action parameter translations keyed by parameter name | | **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record }` | optional | Translations for the action result dialog | | **preflight** | `{ fields?: Record }` | optional | Translations for the action preflight panel | +| **refusals** | `Record }>` | optional | Refusal translations keyed by the code the action's `refusals` declares | ### Nested Shape: `TranslationData.dashboards[string]` @@ -878,6 +882,7 @@ Translation data for a single object | **params** | `Record }>` | optional | Action parameter translations keyed by parameter name | | **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record }` | optional | Translations for the action result dialog | | **preflight** | `{ fields?: Record }` | optional | Translations for the action preflight panel | +| **refusals** | `Record }>` | optional | Refusal translations keyed by the code the action's `refusals` declares | ### Nested Shape: `TranslationItem.dashboards[string]` diff --git a/content/docs/references/ui/action.mdx b/content/docs/references/ui/action.mdx index 9aa080fcd97..dec614aeb08 100644 --- a/content/docs/references/ui/action.mdx +++ b/content/docs/references/ui/action.mdx @@ -1,7 +1,7 @@ --- title: Action schema — UI Protocol property reference navTitle: Action -description: "Action schemas of the ObjectStack UI Protocol: Action, ActionAi, ActionLocation and 3 more — each property with its type, default and a TypeScript example." +description: "Action schemas of the ObjectStack UI Protocol: Action, ActionAi, ActionLocation and 4 more — each property with its type, default and a TypeScript example." --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -13,8 +13,8 @@ description: "Action schemas of the ObjectStack UI Protocol: Action, ActionAi, A ## TypeScript Usage ```typescript -import { ActionSchema, ActionAiSchema, ActionLocationSchema, ActionParamSchema, ActionType, InlineActionSchema } from '@objectstack/spec/ui'; -import type { Action, ActionAi, ActionLocation, ActionParam, ActionType, InlineAction } from '@objectstack/spec/ui'; +import { ActionSchema, ActionAiSchema, ActionLocationSchema, ActionParamSchema, ActionRefusalSchema, ActionType, InlineActionSchema } from '@objectstack/spec/ui'; +import type { Action, ActionAi, ActionLocation, ActionParam, ActionRefusal, ActionType, InlineAction } from '@objectstack/spec/ui'; // Validate data const result = ActionSchema.parse(data); @@ -39,6 +39,7 @@ const result = ActionSchema.parse(data); | **target** | `string` | optional | URL, Script Name, Flow ID, or API Endpoint. Supports $`{param.X}` and $`{ctx.X}` interpolation. For type:'url': an http:// or https:// URL, a mailto: address, or an in-app path starting with / or ./ (a console route; a record is /apps/APP/OBJECT/record/ID, APP being the app's route segment — see onSuccess.navigate) — every other scheme and a protocol-relative //host are refused. | | **openIn** | `Enum<'self' \| 'new-tab'>` | optional | For type:'url' — where to open `target`. 'new-tab' opens a new browser tab; 'self' navigates in place. When omitted, external/absolute URLs open in a new tab and relative URLs navigate in place. Static execution option — keep it OUT of `params` (which is user-input-collection only). | | **body** | `{ language: 'expression'; source: string } \| { language: 'js'; source: string; capabilities?: Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log' \| …>[]; timeoutMs?: integer; … }` | optional | Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`. An action body runs as system, and its update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' is refused with PERMISSION_DENIED; an insert is not judged by this rule. | +| **refusals** | `Record; params?: string[] }>` | optional | Refusal catalogue keyed by the SCREAMING_SNAKE code the action's js body throws: `{ message, status?, reasons?, params? }`. The body refuses by code only, optionally with a declared reason and params; the runtime answers with the declared message (translated through objects.``._actions.``.refusals.``.message, or globalActions.``.refusals.``.message for an object-less action, ….reasons.``.message for a reason, in the caller's locale, holes filled from params) and status. A code not declared here, or a reason a code with reasons does not declare, is refused loudly — at save when the body throws it literally, otherwise at run time. Only a type: 'script' action with a js body declares one | | **operation** | `Enum<'update'>` | optional | The declarative single-record field write, mirroring a list view's `bulkActionDefs`: `'update'` applies `patch` (merged under the collected `params`) to the current record on the data plane AS THE CALLER — never system-elevated — so the caller's permissions, the object's hooks and its validations fire as for a user edit. `type` stays at its default `'script'` (the platform action route the write is performed on); `target`/`body`/`method`/`bodyExtra` are refused beside it. `'delete'` and `'custom'` have no row-level form. | | **patch** | `Record` | optional | For `operation: 'update'` — static field values written to the current record, merged UNDER the user-supplied `params` so a fixed value can be declared without exposing it in the dialog. Written on the data plane as the caller: object permissions, hooks and validations fire as for a user edit. Refused on an action without `operation: 'update'` (it would be silently dropped). | | **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | The bulk dispatch contract this action's BODY is written for, in `bulkActionDefs`' own vocabulary: 'perRecord' = one dispatch per selected row carrying that row's `recordId` (the view's `bulkActions: ['']` bare-string form); 'aggregate' = ONE dispatch for the whole selection carrying every id in `params._selectedIds` (a `bulkActionDefs` entry with `execution: 'aggregate'`). Optional with NO default — omit it only when the body genuinely serves both. A list view wiring a declared action under the other contract is refused by `@objectstack/lint` (`action-dispatch-contract-mismatch`). | @@ -136,6 +137,15 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | **timeoutMs** | `integer` | optional | Per-invocation timeout (ms) | | **memoryMb** | `integer` | optional | Per-invocation memory cap (MB) | +### Nested Shape: `Action.refusals[string]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **message** | `string` | ✅ | The sentence the user reads when the action throws this code — in the source locale, translated whole through objects.``._actions.``.refusals.``.message (globalActions.``.… for an object-less action) in the caller's locale. With no params every `{{ }}` hole is refused; with params a hole is a path over one of them with an optional known formatter, and a hole over another name, a hole holding logic, an unknown formatter, an empty hole and a currency formatter with no code are refused | +| **status** | `integer` | optional | HTTP status the refusal is answered with (4xx; a refusal is never a fault). Absent: 400. A status the body itself sets on the throw is not read — the catalogue decides | +| **reasons** | `Record` | optional | Further sentences under this same code, keyed by the snake_case reason the action throws beside the code (`{ code, reason }`): `{ message }`. The wire code and status stay this entry's. A reason not declared here is refused loudly. Absent: the code has the one sentence, and a thrown reason is not read | +| **params** | `string[]` | optional | The names this entry's sentences may fill: a `{{ NAME }}` or `{{ NAME \| formatter }}` hole renders the value the action throws in `params` (`{ code, params: { NAME: value } }`). A hole over any other name, logic, an unknown formatter, an empty hole and a currency formatter with no code are refused. Absent: the sentences are plain text and a `{{ }}` hole is refused | + ### Nested Shape: `Action.params[number]` | Property | Type | Required | Description | @@ -342,6 +352,26 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Per-option visibility predicate (CEL) — option is offered only when TRUE (else omitted). Same env as the field-level per-option visibleWhen (record + current_user). e.g. P`record.tier == 'gold'` | +--- + +## ActionRefusal + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **message** | `string` | ✅ | The sentence the user reads when the action throws this code — in the source locale, translated whole through objects.``._actions.``.refusals.``.message (globalActions.``.… for an object-less action) in the caller's locale. With no params every `{{ }}` hole is refused; with params a hole is a path over one of them with an optional known formatter, and a hole over another name, a hole holding logic, an unknown formatter, an empty hole and a currency formatter with no code are refused | +| **status** | `integer` | optional | HTTP status the refusal is answered with (4xx; a refusal is never a fault). Absent: 400. A status the body itself sets on the throw is not read — the catalogue decides | +| **reasons** | `Record` | optional | Further sentences under this same code, keyed by the snake_case reason the action throws beside the code (`{ code, reason }`): `{ message }`. The wire code and status stay this entry's. A reason not declared here is refused loudly. Absent: the code has the one sentence, and a thrown reason is not read | +| **params** | `string[]` | optional | The names this entry's sentences may fill: a `{{ NAME }}` or `{{ NAME \| formatter }}` hole renders the value the action throws in `params` (`{ code, params: { NAME: value } }`). A hole over any other name, logic, an unknown formatter, an empty hole and a currency formatter with no code are refused. Absent: the sentences are plain text and a `{{ }}` hole is refused | + +### Nested Shape: `ActionRefusal.reasons[string]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **message** | `string` | ✅ | The sentence the user reads when the action throws this reason under its code — in the source locale, translated through objects.``._actions.``.refusals.``.reasons.``.message (globalActions.``.… for an object-less action) in the caller's locale; its `{{ }}` holes follow the entry's message rule | + + --- ## ActionType diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md index 4485bdc5f92..46d5d09fdc5 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md @@ -34,6 +34,7 @@ classify and is not listed (it becomes reportable the day it grows its first sit | `analytics.zod.ts` | 6 | | `data-engine.zod.ts` | 6 | | `datasource.zod.ts` | 6 | +| `declared-entry.zod.ts` | 3 | | `driver-nosql.zod.ts` | 10 | | `driver-sql.zod.ts` | 2 | | `driver.zod.ts` | 9 | @@ -51,7 +52,7 @@ classify and is not listed (it becomes reportable the day it grows its first sit | `filter.zod.ts` | 13 | | `hook-body-doors.zod.ts` | 4 | | `hook-body.zod.ts` | 2 | -| `hook.zod.ts` | 10 | +| `hook.zod.ts` | 7 | | `mapping.zod.ts` | 8 | | `object.zod.ts` | 26 | | `picklist.zod.ts` | 3 | @@ -80,7 +81,7 @@ over it is here. | `external-catalog.zod.ts` | 4 | 4 | | `field.zod.ts` | 1 | 16 | | `filter.zod.ts` | 11 | 13 | -| `hook.zod.ts` | 5 | 10 | +| `hook.zod.ts` | 5 | 7 | | `query.zod.ts` | 3 | 5 | | `recycle-bin.zod.ts` | 4 | 4 | | `seed-loader.zod.ts` | 12 | 12 | diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.md b/docs/audits/2026-07-unknown-key-strictness-ledger.md index 41118af139a..ca3888d0c89 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.md @@ -729,6 +729,7 @@ column does not move and the `strip` column falls by the count of what left. | `driver/oracle.zod.ts` | authorable | The Oracle `config` contract, added by **#31328** with the `oracle` driver row (a federation-only dialect, ADR-0015 §4.6). Strict from its first commit, same error factory as the rest of the campaign: the keys are what the factory hands node-oracledb Thin (`connectString`, or `host`/`port`/`serviceName`, and `username`), and the plausible wrong spellings are refused by name with the working one — `password` (the credential is the bound secret), `url` (an Oracle connect string is not a URL), and `ssl`/`ca`/`cert`/`key`/`rejectUnauthorized` (Thin chooses TLS by a `tcps://` connect string and has no slot for them, so each would parse and do nothing) | | `analytics.zod.ts` | authorable | **strict as of #4001 batch D — all 8 sites; the `mixed (p)` resolved to authorable on both halves.** **Two of the eight sites later left with their keys (ADR-0049 enforce-or-remove): the metric `filters[]` item (#10414) and the cube's `refreshKey` block (#20637, retired whole — nothing read `every` or `sql`, and no analytics result is cached). The batch-D verdicts for those two are superseded, not reopened; their pins in `analytics-strictness-batchd.test.ts` now assert the retirement prescriptions.** The cube family (Metric + its `filters[]` item, Dimension, CubeJoin, Cube + `refreshKey`) has two live authoring doors, measured: `defineCube()` `.parse()`s an author literal (the showcase example authors through it) and `defineStack({ analyticsCubes })` carries every cube through `StackSchema.parse` — the whole family resolves REACHABLE in the batch-D BFS (positive/negative controls green in the same run). Pre-close probes: a cube's `publik`, a metric's `title`, a join's `relationshipp` (falling back to the `many_to_one` default — a different join shape under a successful parse), a `refreshKey.sqll` all parsed clean and vanished. The query half was subtler and is the batch's live behaviour change: `AnalyticsQuerySchema`'s TOP level was already gated at its one production door (`api/analytics.zod.ts`'s `AnalyticsQueryRequestSchema` is `.extend(…).strict()` since #3878), but **top-level strictness does not recurse** — measured on `main`, `timeDimensions: [{ dimension, granuarity: 'day' }]` rode through the strict wrapper with the typo silently stripped, bucketing the whole range as one group under an ordinary 200. Closing the base makes the posture hold at every door instead of only at the wrapper that re-applied it. ADR-0010 envelope deliberately NOT declared: no protected item re-parses here (`CubeRegistry.register` takes typed objects without a parse; `analytics_cube` resolves no `getMetadataTypeSchema` entry so `saveMetaItem` never parses it; artifact ingest parses the compiled definition BEFORE `applyProtection` stamps). Producer sweep over objectui/cloud: zero cube/analytics-vocabulary producers (objectui's `data-objectstack` sends only declared keys — `cube`/`measures`/`dimensions`/`where`) | | `hook.zod.ts` / `hook-body.zod.ts` | mixed | **strict as of #4001 data step** for the AUTHORING shapes: `HookSchema` (+ `retryPolicy`) and both body branches (`ExpressionBodySchema` / `ScriptBodySchema`). `HookContextSchema` and its `session` / `provenance` / `user` blocks are the RUNTIME shape the engine hands a handler — they stay tolerant, and must: strictness there would make an engine-internal enrichment (as `provenance` was in #3712) a breaking change for anyone parsing a context they were given. The file's old blanket `authorable (p)` was too wide — verification split it | +| `declared-entry.zod.ts` | authorable | **strict from birth** (#34273). The shared declared-entry factory: a refusal entry (`HookRefusalSchema`, `ActionRefusalSchema`) with its reason sentence, and a text entry (`HookTextSchema`, #34374), each a `strictObject`. The sites were `hook.zod.ts`'s until the factory took them, and `ActionSchema.refusals` adds the action's; every one is written by an author under a hook's `refusals` / `texts` or an action's `refusals`, and parses at every door the declaration that carries it parses at | | `hook-body-doors.zod.ts` | authorable | **strict from birth.** Four sites: `BodyDoorRecordRefSchema`, the recipient object of `BodyMailSendInputSchema`, `BodyMailSendInputSchema` and `BodyActivityAppendInputSchema`. The input is what a script body's author writes as the argument of `ctx.email.send(…)` / `ctx.activity.append(…)`, and the door parses it on every call. A key outside the shape is refused rather than dropped, because the values the platform stamps (the sender, the sending user, the organization, the actor, the origin) are not inputs and a body that names one is told at the call | | `mapping.zod.ts` | authorable (p) | | | `picklist.zod.ts` | mixed | `PicklistSchema` and `PicklistExtensionSchema` are authoring shapes, strict from birth (`strictObject`). `PicklistServedFieldSchema` is a SERVED shape — the slice a resolved picklist reference adds to a served field — and is a `looseObject` by design: every other key of that field is `FieldSchema`'s | diff --git a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts index c8f606b6802..ec3076a9be4 100644 --- a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts +++ b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts @@ -272,10 +272,12 @@ describe('#17501 — /meta/types serves a real schema for `action`, and moves no // sample names it. // [#31840] 52 → 53: `preflight` (the same-origin read the param dialog // shows before submit) joined the accepted set, and the sample names it. - expect(Object.keys(properties).length + retiredTopLevelCount('action')).toBe(53); + // [#34273] 53 → 54: `refusals` (the action body's declared refusal + // catalogue) joined the accepted set, and the sample names it. + expect(Object.keys(properties).length + retiredTopLevelCount('action')).toBe(54); // A sample an author would actually address, and the one #17500's // repeater titles need a node to sit on. - for (const key of ['name', 'label', 'objectName', 'type', 'params', 'locations', 'outcomeMessages', 'requiresMembershipReach', 'disabledReason', 'pressed', 'submitText', 'cancelText', 'overrides', 'preflight']) { + for (const key of ['name', 'label', 'objectName', 'type', 'params', 'locations', 'outcomeMessages', 'requiresMembershipReach', 'disabledReason', 'pressed', 'submitText', 'cancelText', 'overrides', 'preflight', 'refusals']) { expect(Object.keys(properties)).toContain(key); } }); diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 3b54be1ad3f..0097b3131e6 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -4,6 +4,7 @@ "exports": [ "ACCEPTED_FILTER_COMPARAND_TYPES (const)", "ACCEPTED_FILTER_COMPARAND_TYPES_SENTENCE (const)", + "ACTION_REFUSAL_MESSAGE_HOLE_REFUSED (const)", "AGGREGATE_FIELD_TYPE_COMPATIBILITY (const)", "AGGREGATION_CASES (const)", "AGGREGATION_ROWS (const)", @@ -911,6 +912,7 @@ "ValueRoundTripColumn (type)", "ValueShapeFieldDef (interface)", "ZeroLimitConformanceCase (interface)", + "actionRefusalsWithoutSandboxedBody (function)", "aiReadExposureRefusal (function)", "analyticsDateRangeRefusalMessage (function)", "apiExposureDenialReason (function)", @@ -1120,6 +1122,10 @@ "summaryFunctionReadsField (function)", "textComparandRefusalReason (function)", "textOperatorDoorVerdict (function)", + "undeclaredActionRefusalAtRun (function)", + "undeclaredActionRefusalCodeAtSave (function)", + "undeclaredActionRefusalReasonAtRun (function)", + "undeclaredActionRefusalReasonAtSave (function)", "undeclaredHookRefusalAtRun (function)", "undeclaredHookRefusalCodeAtSave (function)", "undeclaredHookRefusalReasonAtRun (function)", diff --git a/packages/spec/api-surface/system.json b/packages/spec/api-surface/system.json index 1ad698476d2..ba4b300ff03 100644 --- a/packages/spec/api-surface/system.json +++ b/packages/spec/api-surface/system.json @@ -850,6 +850,7 @@ "WorkerConfigSchema (const)", "WorkerStats (type)", "WorkerStatsSchema (const)", + "actionRefusalMessageKey (function)", "audienceAllows (function)", "audiencePermitsSelfRegistration (function)", "authorisesIrreversibleAction (function)", diff --git a/packages/spec/api-surface/ui.json b/packages/spec/api-surface/ui.json index 929a8063a33..010748d682d 100644 --- a/packages/spec/api-surface/ui.json +++ b/packages/spec/api-surface/ui.json @@ -40,6 +40,8 @@ "ActionParamParsed (type)", "ActionParamSchema (const)", "ActionParsed (type)", + "ActionRefusal (type)", + "ActionRefusalSchema (const)", "ActionSchema (const)", "ActionSession (type)", "ActionSessionSchema (const)", diff --git a/packages/spec/declaration-map/ui.json b/packages/spec/declaration-map/ui.json index 2a31b911e0a..c353246a979 100644 --- a/packages/spec/declaration-map/ui.json +++ b/packages/spec/declaration-map/ui.json @@ -19,6 +19,8 @@ "ActionNavItemSchema": "ui/ActionNavItem", "ActionParam": "ui/ActionParam", "ActionParamSchema": "ui/ActionParam", + "ActionRefusal": "ui/ActionRefusal", + "ActionRefusalSchema": "ui/ActionRefusal", "ActionSchema": "ui/Action", "ActionSession": "ui/ActionSession", "ActionSessionSchema": "ui/ActionSession", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 62b3c71f639..b57563a62af 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -4,6 +4,7 @@ "exports": { "ACCEPTED_FILTER_COMPARAND_TYPES": "src/data/filter-comparand-type.ts#ACCEPTED_FILTER_COMPARAND_TYPES (const)", "ACCEPTED_FILTER_COMPARAND_TYPES_SENTENCE": "src/data/filter-comparand-type.ts#ACCEPTED_FILTER_COMPARAND_TYPES_SENTENCE (const)", + "ACTION_REFUSAL_MESSAGE_HOLE_REFUSED": "src/data/hook-refusal-codes.ts#ACTION_REFUSAL_MESSAGE_HOLE_REFUSED (const)", "AGGREGATE_FIELD_TYPE_COMPATIBILITY": "src/data/aggregate-field-type-compatibility.ts#AGGREGATE_FIELD_TYPE_COMPATIBILITY (const)", "AGGREGATION_CASES": "src/data/aggregation-conformance.ts#AGGREGATION_CASES (const)", "AGGREGATION_ROWS": "src/data/aggregation-conformance.ts#AGGREGATION_ROWS (const)", @@ -897,6 +898,7 @@ "ValueRoundTripColumn": "src/data/value-roundtrip-conformance.ts#ValueRoundTripColumn (type)", "ValueShapeFieldDef": "src/data/field-value.zod.ts#ValueShapeFieldDef (interface)", "ZeroLimitConformanceCase": "src/data/pagination-conformance.ts#ZeroLimitConformanceCase (interface)", + "actionRefusalsWithoutSandboxedBody": "src/data/hook-refusal-codes.ts#actionRefusalsWithoutSandboxedBody (function)", "aiReadExposureRefusal": "src/data/ai-read-exposure.ts#aiReadExposureRefusal (function)", "analyticsDateRangeRefusalMessage": "src/data/analytics.zod.ts#analyticsDateRangeRefusalMessage (function)", "apiExposureDenialReason": "src/data/api-derivation.ts#apiExposureDenialReason (function)", @@ -1106,6 +1108,10 @@ "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)", + "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)", + "undeclaredActionRefusalReasonAtSave": "src/data/hook-refusal-codes.ts#undeclaredActionRefusalReasonAtSave (function)", "undeclaredHookRefusalAtRun": "src/data/hook-refusal-codes.ts#undeclaredHookRefusalAtRun (function)", "undeclaredHookRefusalCodeAtSave": "src/data/hook-refusal-codes.ts#undeclaredHookRefusalCodeAtSave (function)", "undeclaredHookRefusalReasonAtRun": "src/data/hook-refusal-codes.ts#undeclaredHookRefusalReasonAtRun (function)", diff --git a/packages/spec/export-origins/system.json b/packages/spec/export-origins/system.json index 3e6d27b4a2d..3563b693b49 100644 --- a/packages/spec/export-origins/system.json +++ b/packages/spec/export-origins/system.json @@ -810,6 +810,7 @@ "WorkerConfigSchema": "src/system/worker.zod.ts#WorkerConfigSchema (const)", "WorkerStats": "src/system/worker.zod.ts#WorkerStats (type)", "WorkerStatsSchema": "src/system/worker.zod.ts#WorkerStatsSchema (const)", + "actionRefusalMessageKey": "src/system/i18n-resolver.ts#actionRefusalMessageKey (function)", "audienceAllows": "src/system/book.zod.ts#audienceAllows (function)", "audiencePermitsSelfRegistration": "src/system/auth-config.zod.ts#audiencePermitsSelfRegistration (function)", "authorisesIrreversibleAction": "src/system/migration.zod.ts#authorisesIrreversibleAction (function)", diff --git a/packages/spec/export-origins/ui.json b/packages/spec/export-origins/ui.json index f7675b375c4..9fe58477009 100644 --- a/packages/spec/export-origins/ui.json +++ b/packages/spec/export-origins/ui.json @@ -39,6 +39,8 @@ "ActionParamParsed": "src/ui/action.zod.ts#ActionParamParsed (type)", "ActionParamSchema": "src/ui/action.zod.ts#ActionParamSchema (const)", "ActionParsed": "src/ui/action.zod.ts#ActionParsed (type)", + "ActionRefusal": "src/ui/action.zod.ts#ActionRefusal (type)", + "ActionRefusalSchema": "src/ui/action.zod.ts#ActionRefusalSchema (const)", "ActionSchema": "src/ui/action.zod.ts#ActionSchema (const)", "ActionSession": "src/ui/action-params.zod.ts#ActionSession (type)", "ActionSessionSchema": "src/ui/action-params.zod.ts#ActionSessionSchema (const)", diff --git a/packages/spec/liveness/hook.json b/packages/spec/liveness/hook.json index 30dc46e1c70..58a13dd5f66 100644 --- a/packages/spec/liveness/hook.json +++ b/packages/spec/liveness/hook.json @@ -124,7 +124,7 @@ "verifiedAt": "2026-11-14", "evidenceScope": "in-repo", "evidence": "packages/runtime/src/sandbox/hook-refusal-catalogue.ts#fillHookRefusalParams (fills the picked sentence's `{{ NAME }}` holes from the throw's `params` through the formula template engine, the declared names alone in scope); packages/runtime/src/sandbox/hook-refusal-catalogue.ts#declaredRefusalMessage (renders an entry that declares `params`; one that declares none stays plain text)", - "producer": "packages/spec/src/data/hook.zod.ts#hookRefusalMessageRefusal (judges each sentence's holes against the declared names at save)", + "producer": "packages/spec/src/data/declared-entry.zod.ts#declaredRefusalEntrySchema (judges each sentence's holes against the declared names at save; #34273 moved the judge into the shared declared-entry factory)", "note": "[#33214, ruling 6879477573 问三] Seeded `live` with its reader in one change. The template engine is the one the flow `end` refusal renders through (`renderTextSlot`)." } }, diff --git a/packages/spec/liveness/state-counts/action.md b/packages/spec/liveness/state-counts/action.md index 5ab922ebcfd..e5c7313d174 100644 --- a/packages/spec/liveness/state-counts/action.md +++ b/packages/spec/liveness/state-counts/action.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `action` | 79 | 0 | 0 | 1 | 5 | 85 | +| `action` | 83 | 0 | 0 | 1 | 5 | 89 | diff --git a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts index a8c74bb6597..033e346b01f 100644 --- a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts +++ b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts @@ -475,6 +475,17 @@ const LEDGER: ReadonlyArray = [ key: 'texts', why: "live, not yet offered in the Studio — the sentences a hook writes into records (`ctx.text`, answered in the organization's language) are validated at parse (snake_case keys, closed-scope holes over declared `params`, a literal `ctx.text` key the hook does not declare refused at save) and read at run time, and they are declared in the hook's package source beside the code that asks for them. The Studio row, a key-only record beside `refusals`, needs its labels and help text translated in the eleven metadata-forms bundles and is owed to a follow-up card; until then a hook authored in the Studio declares `texts` through the metadata API or its package source", }, + // #34273 — an action's refusal catalogue lands in the action's source + // first, as a hook's declared texts did (#34374). The Studio row (a + // key-only record, with its help text in the eleven metadata-forms + // bundles) is a follow-up, so this row records why the key is not offered. + { + kind: 'omit', + type: 'action', + path: ROOT_PATH, + key: 'refusals', + why: "live, not yet offered in the Studio — the refusals a `script` action's `js` body throws by code (answered with the declared sentence in the caller's locale) are validated at parse (SCREAMING_SNAKE codes, the hook entry's closed-scope holes over declared `params`, a literal code or reason the catalogue does not declare refused at save) and read at run time, and they are declared in the action's package source beside the body that throws them. The Studio row, a key-only record, needs its labels and help text translated in the eleven metadata-forms bundles and is owed to a follow-up card; until then an action authored in the Studio declares `refusals` through the metadata API or its package source", + }, // #27946 — an action's pressed-state predicate lands spec-first the same // way: `planned` in the liveness ledger, drawn by no action surface until // the console card that draws `aria-pressed` on the header buttons. diff --git a/packages/spec/src/type-alias-convention.pin.test.ts b/packages/spec/src/type-alias-convention.pin.test.ts index 98d5e5a39d8..02b3e68fd04 100644 --- a/packages/spec/src/type-alias-convention.pin.test.ts +++ b/packages/spec/src/type-alias-convention.pin.test.ts @@ -304,7 +304,7 @@ import type * as M204 from './ai/dataset-tools.zod.js'; import type * as M205 from './ai/object-query-source.zod.js'; // --------------------------------------------------------------------------- -// 857 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. +// 858 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. // // That number is machine-checked, not hand-kept. The runtime companion at the // bottom of this file recomputes the pin count from the source and asserts that @@ -1574,6 +1574,7 @@ export type Iso_ui_actionParams__ActionSessionSchema = Assert, z.infer< typeof M155.ActionLocationSchema > >>; +export type Iso_ui_action__ActionRefusalSchema = Assert, z.infer< typeof M155.ActionRefusalSchema > >>; export type Iso_ui_action__ActionType = Assert, z.infer< typeof M155.ActionType > >>; // ui/app.zod.ts @@ -1832,7 +1833,7 @@ describe('ADR-0122 type-alias convention', () => { // this title and the section header above the pin list — are now asserted // against the recomputed count below, so neither can go stale without a red // test naming it. - it('still declares all 857 isomorphic pins', () => { + it('still declares all 858 isomorphic pins', () => { // The truth of each pin is proved by tsc, not here — an `Assert>` // that stops holding is a compile error with the alias named. What tsc // cannot notice is a pin that was DELETED: removing the assertion removes @@ -2909,7 +2910,12 @@ describe('ADR-0122 type-alias convention', () => { // (`data/hook.zod.ts`), closed at `message` / `params` with no default or // transform, pinned here (Iso_data_hook__HookTextSchema) beside its // refusal sibling rather than given a `…Parsed` synonym. +1 added. - expect(pins).toHaveLength(857); + // 857 -> 858 is #34273: an action's declared refusal entry, + // `ActionRefusalSchema` (`ui/action.zod.ts`), built by the same + // declared-entry factory as `HookRefusalSchema` and closed at the same + // four keys with no default or transform, pinned here + // (Iso_ui_action__ActionRefusalSchema). +1 added. + expect(pins).toHaveLength(858); // The count is stated in PROSE twice as well — this case's title and the // section header above the pin list — and until commit c6b05c76a nothing read either diff --git a/skills/objectstack-data/references/_index.md b/skills/objectstack-data/references/_index.md index 55f2b91ea75..70456ad9993 100644 --- a/skills/objectstack-data/references/_index.md +++ b/skills/objectstack-data/references/_index.md @@ -24,6 +24,7 @@ from `node_modules` — there is no local copy in the skill bundle. - `node_modules/@objectstack/spec/src/data/column-apply-on.zod.ts` — Exports: ColumnApplyOnSchema - `node_modules/@objectstack/spec/src/data/data-engine.zod.ts` — Data Engine Protocol - `node_modules/@objectstack/spec/src/data/date-macros.zod.ts` — Date Macro Tokens — the declarative placeholders the UI substitutes +- `node_modules/@objectstack/spec/src/data/declared-entry.zod.ts` — The declared-entry factory: one sentence a declaration hands over in the - `node_modules/@objectstack/spec/src/data/driver-sql.zod.ts` — Exports: SQLDialectSchema, DataTypeMappingSchema, SSLConfigSchema, SQLDriverConfigSchema, SQLiteDataTypeMappingDefaults - `node_modules/@objectstack/spec/src/data/driver.zod.ts` — Exports: DriverOptionsSchema, DriverCapabilitiesSchema, DriverInterfaceSchema, PoolConfigSchema, DriverConfigSchema - `node_modules/@objectstack/spec/src/data/driver/common.zod.ts` — Shared building blocks for the per-driver `datasource.config` shapes. @@ -58,7 +59,7 @@ from `node_modules` — there is no local copy in the skill bundle. - `node_modules/@objectstack/spec/src/system/deploy-bundle.zod.ts` — Deploy Bundle Protocol - `node_modules/@objectstack/spec/src/system/translation.zod.ts` — Exports: LocaleSchema, FieldTranslationSchema, ActionResultDialogTranslationSchema, ObjectTranslationDataSchema, TranslationDataSchema - `node_modules/@objectstack/spec/src/ui/action-params.zod.ts` — The action DISPATCH contract: what the platform validates on the way in, and -- `node_modules/@objectstack/spec/src/ui/action.zod.ts` — Exports: ActionParamSchema, ActionType, ActionLocationSchema, ActionAiSchema, ActionSchema +- `node_modules/@objectstack/spec/src/ui/action.zod.ts` — Exports: ActionParamSchema, ActionType, ActionLocationSchema, ActionAiSchema, ActionRefusalSchema - `node_modules/@objectstack/spec/src/ui/bulk-action.zod.ts` — Bulk Action Schemas - `node_modules/@objectstack/spec/src/ui/chart.zod.ts` — Unified Chart Type Taxonomy - `node_modules/@objectstack/spec/src/ui/i18n.zod.ts` — Display-label and ARIA-label primitives shared by every `ui/` shape. diff --git a/skills/objectstack-ui/references/_index.md b/skills/objectstack-ui/references/_index.md index b3621fd3e1f..4b1612be625 100644 --- a/skills/objectstack-ui/references/_index.md +++ b/skills/objectstack-ui/references/_index.md @@ -9,7 +9,7 @@ from `node_modules` — there is no local copy in the skill bundle. ## Core schemas -- `node_modules/@objectstack/spec/src/ui/action.zod.ts` — Exports: ActionParamSchema, ActionType, ActionLocationSchema, ActionAiSchema, ActionSchema +- `node_modules/@objectstack/spec/src/ui/action.zod.ts` — Exports: ActionParamSchema, ActionType, ActionLocationSchema, ActionAiSchema, ActionRefusalSchema - `node_modules/@objectstack/spec/src/ui/app.zod.ts` — Exports: ObjectNavItemSchema, DashboardNavItemSchema, PageNavItemSchema, UrlNavItemSchema, ReportNavItemSchema - `node_modules/@objectstack/spec/src/ui/chart.zod.ts` — Unified Chart Type Taxonomy - `node_modules/@objectstack/spec/src/ui/component.zod.ts` — Exports: PageContainerProps, PageHeaderProps, PageTabsProps, PageCardProps, RecordDetailsProps @@ -25,6 +25,7 @@ from `node_modules` — there is no local copy in the skill bundle. - `node_modules/@objectstack/spec/src/api/errors.zod.ts` — Standardized Error Codes Protocol - `node_modules/@objectstack/spec/src/data/data-engine.zod.ts` — Data Engine Protocol - `node_modules/@objectstack/spec/src/data/date-macros.zod.ts` — Date Macro Tokens — the declarative placeholders the UI substitutes +- `node_modules/@objectstack/spec/src/data/declared-entry.zod.ts` — The declared-entry factory: one sentence a declaration hands over in the - `node_modules/@objectstack/spec/src/data/feed.zod.ts` — Activity-timeline UI config enums, and the `sys_activity.type` built-in set. - `node_modules/@objectstack/spec/src/data/field-value.zod.ts` — Field runtime VALUE-shape contract (ADR-0104 D1). - `node_modules/@objectstack/spec/src/data/field.zod.ts` — Exports: FieldType, SelectOptionSchema, LocationCoordinatesSchema, CurrencyConfigSchema, UniqueScopeSchema From a9acead1684a8371fda2fc984e3351d9024e2312 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 07:36:04 +0000 Subject: [PATCH 06/13] test(lint): classify the action refusal template pass in the authored-site walk Claude-Session: https://claude.ai/code/session_01ADHkmP879Ku8wbNev27oyN Co-authored-by: Claude --- packages/lint/src/authored-site-expression.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/lint/src/authored-site-expression.test.ts b/packages/lint/src/authored-site-expression.test.ts index bb05f23e1e4..e242f840afa 100644 --- a/packages/lint/src/authored-site-expression.test.ts +++ b/packages/lint/src/authored-site-expression.test.ts @@ -121,6 +121,8 @@ const WALK_PUSHES: Record = { bulkConfirmTextIssues: "a list view's bulk `confirmText` template slots: no rule or field expression", actionCopyTemplateIssues: "an action's copy template slots: no rule or field expression", hookRefusalTemplateIssues: "a hook refusal's template sentences over its declared params: no rule or field expression", + // [#34273] The same judge over an action's refusal catalogue. + actionRefusalTemplateIssues: "an action refusal's template sentences over its declared params: no rule or field expression", }; /** The passes the walk pushes whole from INSIDE a site's regions: classified with that site's calls, in `SITE_CALLS`. */ From 04a9166882083f75963d952c612c3460cad18b12 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 08:09:17 +0000 Subject: [PATCH 07/13] fix(spec, runtime): llms.txt counts the declared-entry module; the action refusal test pays the metadata load at collection Claude-Session: https://claude.ai/code/session_01ADHkmP879Ku8wbNev27oyN Co-authored-by: Claude --- packages/runtime/src/sandbox/action-refusal-catalogue.test.ts | 3 +++ packages/spec/llms.txt | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/runtime/src/sandbox/action-refusal-catalogue.test.ts b/packages/runtime/src/sandbox/action-refusal-catalogue.test.ts index 4c9514b07ff..fd80dff5c60 100644 --- a/packages/runtime/src/sandbox/action-refusal-catalogue.test.ts +++ b/packages/runtime/src/sandbox/action-refusal-catalogue.test.ts @@ -13,6 +13,9 @@ */ import { describe, it, expect, vi } from 'vitest'; +// Paid at collection, not inside a case's clocked window: the dispatcher's +// reach loads `@objectstack/metadata` lazily (`check:test-source-alias`). +import '@objectstack/metadata'; import { mapDataError } from '@objectstack/types'; import { actionBodyRunnerFactory } from './body-runner.js'; diff --git a/packages/spec/llms.txt b/packages/spec/llms.txt index 99bcf5c5f68..9822e9d4a29 100644 --- a/packages/spec/llms.txt +++ b/packages/spec/llms.txt @@ -77,7 +77,7 @@ const query = { --- -## 3. Schema Inventory by Domain (226 schemas) +## 3. Schema Inventory by Domain (227 schemas) Counted as `*.zod.ts` modules under `packages/spec/src//` — the sources that ship in this tarball (`files` includes `src/**/*.zod.ts`), so every number @@ -87,7 +87,7 @@ here is verifiable from the installed package. |--------|-------|-------------| | system | 40 | Auth, Cache, Demo Staff, Dev Login, Email / SMS / Push Config, Push Device, Encryption, Fate Supplement (organization ownership), HTTP Server, License, Logging, Metrics, Restriction Profile | | kernel | 31 | Plugin, Manifest, Events (6 sub-modules), Feature, Context, Package Registry, Override Declaration | -| data | 36 | Object, Field, Picklist, Query, Filter, Driver (SQL/NoSQL/Memory/Mongo/Postgres/Oracle/SQL Server), Cube, Seed, Recycle Bin | +| data | 37 | Object, Field, Picklist, Query, Filter, Driver (SQL/NoSQL/Memory/Mongo/Postgres/Oracle/SQL Server), Cube, Seed, Recycle Bin, Declared Entry (refusal / text) | | api | 35 | Endpoint, REST Server, Discovery, OData, Batch, WebSocket, Response Envelope, Package Lifecycle, Package API (assembled stage), Record Page, App Metadata Bundle, Push Delivery, Push Relay | | ui | 18 | View, App, Action, Dashboard, Page, Chart, Component, Animation | | automation | 16 | Flow, Approval, Assignment Rule, BPMN Interop, Control Flow, Webhook, Schedule Organization | From 2b11c5b95a355751a62f4033ca16dbffcde14d29 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 08:51:40 +0000 Subject: [PATCH 08/13] fix(ui-core): list refusals among the spec's declared action keys Claude-Session: https://claude.ai/code/session_01ADHkmP879Ku8wbNev27oyN Co-authored-by: Claude --- .changeset/34273-action-refusals.md | 3 +++ ui/packages/core/src/actions/actionKeys.ts | 8 ++++++++ 2 files changed, 11 insertions(+) diff --git a/.changeset/34273-action-refusals.md b/.changeset/34273-action-refusals.md index 0ae210cb843..16a41b9f38f 100644 --- a/.changeset/34273-action-refusals.md +++ b/.changeset/34273-action-refusals.md @@ -2,6 +2,7 @@ '@objectstack/spec': minor '@objectstack/runtime': minor '@objectstack/lint': minor +'@object-ui/core': patch --- feat(actions): an action body refuses in the caller's language through a declared refusal catalogue @@ -19,3 +20,5 @@ A `script` action's `js` body can now refuse the way a hook does: declare the re - An action without `refusals` is answered exactly as before. The shared declared-entry factory (`packages/spec/src/data/declared-entry.zod.ts`) now builds `HookRefusalSchema`, `ActionRefusalSchema` and `HookTextSchema`; the published hook schemas are unchanged. + +`@object-ui/core` lists `refusals` among the spec's declared action keys, so an action carrying a catalogue is not reported as having an unknown key; the console reads nothing new, because the refusal arrives already rendered on `userMessage`. diff --git a/ui/packages/core/src/actions/actionKeys.ts b/ui/packages/core/src/actions/actionKeys.ts index b04d6c77c2e..784f82f21e2 100644 --- a/ui/packages/core/src/actions/actionKeys.ts +++ b/ui/packages/core/src/actions/actionKeys.ts @@ -338,6 +338,14 @@ export const SPEC_ACTION_KEYS = [ 'recordIdField', 'recordIdParam', 'refreshAfter', + // Added to `ActionSchema` by objectstack#34273: the refusal catalogue a + // `script` action's `js` body throws codes against. The SERVER answers it — + // the refusal reaches the console already rendered, its sentence on + // `userMessage`, which the failure toast already shows — so it is listed for + // the reason `overrides` is: this array restates the spec's declared keys, so + // an action carrying it is not reported as having an unknown key. `ActionDef` + // does NOT declare it and the runner does not read it. + 'refusals', 'requiredPermissions', 'requiresFeature', // Added to `ActionSchema` in @objectstack/spec 17.7.0 (objectui#11717): the From 2a25dade9108013cd07d1c2a6428e1acae5762ef Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 08:52:49 +0000 Subject: [PATCH 09/13] docs(protocol): the action shape lists refusals Claude-Session: https://claude.ai/code/session_01ADHkmP879Ku8wbNev27oyN Co-authored-by: Claude --- content/docs/protocol/objectui/actions.mdx | 1 + 1 file changed, 1 insertion(+) diff --git a/content/docs/protocol/objectui/actions.mdx b/content/docs/protocol/objectui/actions.mdx index 0810fef374e..7ea5dc58bfe 100644 --- a/content/docs/protocol/objectui/actions.mdx +++ b/content/docs/protocol/objectui/actions.mdx @@ -229,6 +229,7 @@ interface Action { operation?: 'update'; // Declarative single-record field write (rides the default script route) patch?: Record; // Static field values for operation: 'update', merged under params body?: HookBody; // Inline logic for type: 'script' + refusals?: Record; // Codes the js body may throw, answered with a declared sentence in the caller's locale params?: ActionParam[]; // Inputs collected before execution submitText?: I18nLabel; // The param dialog's submit button verb (default "Confirm") cancelText?: I18nLabel; // The confirm or param dialog's dismiss button label (default "Cancel") From ff1ba6635716487e6d8b5a54f4834c9dce7bbc4a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 10:20:15 +0000 Subject: [PATCH 10/13] chore(spec): regenerate the action liveness counts over the merge with main Claude-Session: https://claude.ai/code/session_01ADHkmP879Ku8wbNev27oyN Co-authored-by: Claude --- packages/spec/liveness/state-counts/action.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/spec/liveness/state-counts/action.md b/packages/spec/liveness/state-counts/action.md index e5c7313d174..be97fdd5c8b 100644 --- a/packages/spec/liveness/state-counts/action.md +++ b/packages/spec/liveness/state-counts/action.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `action` | 83 | 0 | 0 | 1 | 5 | 89 | +| `action` | 86 | 0 | 0 | 1 | 2 | 89 | From 0169fc10be77711968755536013f9d09d48868a4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 11:53:47 +0000 Subject: [PATCH 11/13] fix(spec): the action refusal sentences and changeset say what the diff publishes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The changeset's Clause-② line named a runtime export the package does not make (the action body runner answers through resolveActionRefusal internally) and listed two of the nine new spec exports; it now lists them all. The save-time sentence for a script action with no body no longer claims no inline target either, and the action key builder's doc calls itself the action twin. Claude-Session: https://claude.ai/code/session_01ADHkmP879Ku8wbNev27oyN Co-authored-by: Claude --- .changeset/34273-action-refusals.md | 4 ++-- packages/spec/src/data/hook-refusal-codes.ts | 2 +- packages/spec/src/system/i18n-resolver.ts | 2 +- packages/spec/src/ui/action-refusals.test.ts | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.changeset/34273-action-refusals.md b/.changeset/34273-action-refusals.md index 16a41b9f38f..cf300e81641 100644 --- a/.changeset/34273-action-refusals.md +++ b/.changeset/34273-action-refusals.md @@ -7,9 +7,9 @@ feat(actions): an action body refuses in the caller's language through a declared refusal catalogue -Clause-②: yes (widening) — an action may now declare `refusals` (`ActionRefusalSchema`); translation bundles accept `objects.._actions..refusals..message` and `globalActions..refusals..message` (with `….reasons..message`); `@objectstack/spec` exports `ActionRefusalSchema` and `actionRefusalMessageKey`, `@objectstack/runtime` exports `resolveActionRefusal`. Nothing that was accepted before is refused +Clause-②: yes (widening) — an action may now declare `refusals` (`ActionRefusalSchema`); translation bundles accept `objects.._actions..refusals..message` and `globalActions..refusals..message` (with `….reasons..message`); `@objectstack/spec` exports `ActionRefusalSchema` and the `ActionRefusal` type (`ui`), `actionRefusalMessageKey` (`system`), and `ACTION_REFUSAL_MESSAGE_HOLE_REFUSED`, `actionRefusalsWithoutSandboxedBody`, `undeclaredActionRefusalCodeAtSave`, `undeclaredActionRefusalReasonAtSave`, `undeclaredActionRefusalAtRun` and `undeclaredActionRefusalReasonAtRun` (`data`); `@objectstack/runtime` adds no export: the action body runner answers through `resolveActionRefusal` internally. Nothing that was accepted before is refused Metadata-protocol: added -Skills-docs: follow-up — `skills/objectstack-i18n/SKILL.md` lists the hook refusal key only, and no skill teaches an action's `refusals`; owed to a follow-up card. `content/docs/ui/actions.mdx` and `content/docs/ui/translations.mdx` gain the section and the key row here +Skills-docs: follow-up #34824 — `skills/objectstack-i18n/SKILL.md` lists the hook refusal key only and `skills/objectstack-ui/rules/actions.md` teaches no action `refusals`; `content/docs/ui/actions.mdx` and `content/docs/ui/translations.mdx` gain the section and the key row here A `script` action's `js` body can now refuse the way a hook does: declare the refusals it may throw, keyed by code, and throw the code instead of the sentence — `refusals: { NOT_DRAFT: { message: 'Only a draft invoice can be signed off.', status: 409 } }`, then `throw { code: 'NOT_DRAFT' }`. The server answers with the entry's sentence in the caller's locale (the request's `executionContext.locale`), else the declared one, on the refusal's `userMessage`, with the entry's status (400 when it names none). The entry is the hook catalogue's, built by one shared factory: optional `reasons` (further sentences under one code) and `params` (the names a `{{ }}` hole may fill), under the same rules. diff --git a/packages/spec/src/data/hook-refusal-codes.ts b/packages/spec/src/data/hook-refusal-codes.ts index 886fe0dde89..2159752116c 100644 --- a/packages/spec/src/data/hook-refusal-codes.ts +++ b/packages/spec/src/data/hook-refusal-codes.ts @@ -552,7 +552,7 @@ export function actionRefusalsWithoutSandboxedBody(type: string, language: strin ? `\`type: '${type}'\`, which runs no code of the action's own` : language !== undefined ? `a \`${language}\` body` - : 'no `body` and no inline `target` function'; + : 'no `body` (an inline `target` function `os build` could not lower leaves none)'; return ( "`refusals` is answered for a `type: 'script'` action's sandboxed `body` (`language: 'js'`) and for its inline " + `\`target\` function (which \`os build\` lowers to a \`js\` body), and this action has ${has}: nothing it runs ` diff --git a/packages/spec/src/system/i18n-resolver.ts b/packages/spec/src/system/i18n-resolver.ts index 76f38f13adf..f005ba36027 100644 --- a/packages/spec/src/system/i18n-resolver.ts +++ b/packages/spec/src/system/i18n-resolver.ts @@ -4462,7 +4462,7 @@ export function hookTextMessageKey(hookName: string, key: string): string { /** * Dot-notation i18n key for an action's declared refusal message (#34273, - * `ActionSchema.refusals`) — the hook twin of {@link hookRefusalMessageKey}, + * `ActionSchema.refusals`) — the action twin of {@link hookRefusalMessageKey}, * at the address every action translation is read at * ({@link actionTranslationNode}): * diff --git a/packages/spec/src/ui/action-refusals.test.ts b/packages/spec/src/ui/action-refusals.test.ts index c184b0d1a59..27354c86476 100644 --- a/packages/spec/src/ui/action-refusals.test.ts +++ b/packages/spec/src/ui/action-refusals.test.ts @@ -60,7 +60,7 @@ describe('Action.refusals — the declared catalogue', () => { }); it.each([ - ['no body', { type: 'script' }, "no `body` and no inline `target` function"], + ['no body', { type: 'script' }, "no `body` (an inline `target` function `os build` could not lower leaves none)"], ['an expression body', { type: 'script', body: { language: 'expression', source: 'record.amount > 0' } }, 'a `expression` body'], ['a url action', { type: 'url', target: 'https://example.com' }, "`type: 'url'`"], ['a flow action', { type: 'flow', target: 'approve_invoice' }, "`type: 'flow'`"], From b7d720db01d5c4450afd1f6977e42294bc578a02 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 16:31:13 +0000 Subject: [PATCH 12/13] docs(references): regenerate index after main merge Regenerated content/docs/references/index.mdx from the merged tree (gen:migration-registry, gen:schema, gen:docs). Main's +1 AI schema and this branch's +1 UI schema now both count: 1671 total. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfr1xZSFZzCR8HnqXX --- content/docs/references/index.mdx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index b1e49a0ec2d..1db6f92c073 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1670 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1671 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -20,7 +20,7 @@ counts are sums of the rows they head. Regenerate with | Module | Pages | Schemas | Description | | :--- | ---: | ---: | :--- | -| [AI Protocol](/docs/references/ai) | 14 | 81 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | +| [AI Protocol](/docs/references/ai) | 14 | 82 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | | [API Protocol](/docs/references/api) | 36 | 496 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | | [Data Protocol](/docs/references/data) | 35 | 188 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | @@ -34,13 +34,13 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 297 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 16 | 178 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **218** | **1670** | 14 protocol modules | +| **Total** | **218** | **1671** | 14 protocol modules | --- ## AI Protocol -**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **14 pages, 81 schemas** +**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **14 pages, 82 schemas** Agents, tools, skills, RAG and knowledge sources, model registry, conversations. @@ -49,7 +49,7 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | [`agent.zod.ts`](/docs/references/ai/agent) | `AIModelConfig`, `Agent`, `StructuredOutputConfig`, `StructuredOutputFormat`, `TransformPipelineStep` | | [`build-progress.zod.ts`](/docs/references/ai/build-progress) | `BuildProgressFrame`, `BuildProgressPhase` | | [`conversation.zod.ts`](/docs/references/ai/conversation) | `CodeContent`, `ConversationAnalytics`, `ConversationContext`, `ConversationMessage`, `ConversationSession`, `ConversationSummary`, `FileContent`, `FunctionCall`, `ImageContent`, `MessageContent`, `MessageContentType`, `MessagePruningEvent`, `MessageRole`, `TextContent`, `TokenBudgetConfig`, `TokenBudgetStrategy`, `TokenUsageStats`, `ToolCall` | -| [`dataset-tools.zod.ts`](/docs/references/ai/dataset-tools) | `DatasetProvenance`, `DatasetTermMatch`, `DatasetTermMatchedOn`, `DatasetToolCatalogDimension`, `DatasetToolCatalogEntry`, `DatasetToolCatalogMeasure`, `ListDatasetsInput`, `ListDatasetsOutput`, `QueryDatasetInput`, `QueryDatasetOutput` | +| [`dataset-tools.zod.ts`](/docs/references/ai/dataset-tools) | `DatasetProvenance`, `DatasetTermCandidate`, `DatasetTermMatch`, `DatasetTermMatchedOn`, `DatasetToolCatalogDimension`, `DatasetToolCatalogEntry`, `DatasetToolCatalogMeasure`, `ListDatasetsInput`, `ListDatasetsOutput`, `QueryDatasetInput`, `QueryDatasetOutput` | | [`embedding.zod.ts`](/docs/references/ai/embedding) | `EmbeddingModel`, `VectorStore`, `VectorStoreProvider` | | [`knowledge-document.zod.ts`](/docs/references/ai/knowledge-document) | `KnowledgeChunk`, `KnowledgeDocument`, `KnowledgeHit` | | [`knowledge-source.zod.ts`](/docs/references/ai/knowledge-source) | `FileKnowledgeSource`, `HttpKnowledgeSource`, `KnowledgeRefreshPolicy`, `KnowledgeSource`, `KnowledgeSourceKind`, `ObjectKnowledgeSource` | From 5a05e4f2f4d6f82ef610591d393c3ca509d1935c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 18:23:51 +0000 Subject: [PATCH 13/13] docs(references): regenerate translation reference after main merge Regenerated content/docs/references/system/translation.mdx from the merged tree (gen:migration-registry, gen:schema, gen:docs) after #34915 landed. The references differ from main by this branch's own five pages, as before. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfr1xZSFZzCR8HnqXX --- .../docs/references/system/translation.mdx | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/content/docs/references/system/translation.mdx b/content/docs/references/system/translation.mdx index 06ce3e12abe..825b2261401 100644 --- a/content/docs/references/system/translation.mdx +++ b/content/docs/references/system/translation.mdx @@ -34,6 +34,7 @@ Translations for an action result dialog | **description** | `string` | optional | Translated result dialog description | | **acknowledge** | `string` | optional | Translated acknowledge button label | | **fields** | `Record` | optional | Result field labels keyed by the literal field path declared in the action metadata (keys may contain dots) | +| **columns** | `Record>` | optional | Table column header labels: keyed by the literal path of a `format: 'table'` field, then by the literal path of one of its `columns[]` (keys may contain dots) | --- @@ -136,8 +137,8 @@ Translation data for a single field | **cancelText** | `string` | optional | Translated label of the dismiss button on the action's confirm or param dialog (the action must declare `confirmText` or `params`) | | **outcomeMessages** | `Record` | optional | Translated success copy per handler outcome, keyed by the snake_case outcome name the action's `outcomeMessages` declares | | **params** | `Record }>` | optional | Action parameter translations keyed by parameter name | -| **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record }` | optional | Translations for the action result dialog | -| **preflight** | `{ fields?: Record }` | optional | Translations for the action preflight panel | +| **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record; … }` | optional | Translations for the action result dialog | +| **preflight** | `{ fields?: Record; columns?: Record> }` | optional | Translations for the action preflight panel | | **refusals** | `Record }>` | optional | Refusal translations keyed by the code the action's `refusals` declares | ### Nested Shape: `ObjectTranslationData._sections[string]` @@ -242,8 +243,8 @@ Translation data for a single object | **cancelText** | `string` | optional | Translated label of the dismiss button on the action's confirm or param dialog (the action must declare `confirmText` or `params`) | | **outcomeMessages** | `Record` | optional | Translated success copy per handler outcome, keyed by the snake_case outcome name the action's `outcomeMessages` declares | | **params** | `Record }>` | optional | Action parameter translations keyed by parameter name | -| **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record }` | optional | Translations for the action result dialog | -| **preflight** | `{ fields?: Record }` | optional | Translations for the action preflight panel | +| **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record; … }` | optional | Translations for the action result dialog | +| **preflight** | `{ fields?: Record; columns?: Record> }` | optional | Translations for the action preflight panel | | **refusals** | `Record }>` | optional | Refusal translations keyed by the code the action's `refusals` declares | ### Nested Shape: `PlatformTranslationData.dashboards[string]` @@ -423,8 +424,8 @@ Translation data for a single object | **cancelText** | `string` | optional | Translated label of the dismiss button on the action's confirm or param dialog (the action must declare `confirmText` or `params`) | | **outcomeMessages** | `Record` | optional | Translated success copy per handler outcome, keyed by the snake_case outcome name the action's `outcomeMessages` declares | | **params** | `Record }>` | optional | Action parameter translations keyed by parameter name | -| **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record }` | optional | Translations for the action result dialog | -| **preflight** | `{ fields?: Record }` | optional | Translations for the action preflight panel | +| **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record; … }` | optional | Translations for the action result dialog | +| **preflight** | `{ fields?: Record; columns?: Record> }` | optional | Translations for the action preflight panel | | **refusals** | `Record }>` | optional | Refusal translations keyed by the code the action's `refusals` declares | ### Nested Shape: `ServedTranslationData.dashboards[string]` @@ -667,8 +668,8 @@ Translation data for a single object | **cancelText** | `string` | optional | Translated label of the dismiss button on the action's confirm or param dialog (the action must declare `confirmText` or `params`) | | **outcomeMessages** | `Record` | optional | Translated success copy per handler outcome, keyed by the snake_case outcome name the action's `outcomeMessages` declares | | **params** | `Record }>` | optional | Action parameter translations keyed by parameter name | -| **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record }` | optional | Translations for the action result dialog | -| **preflight** | `{ fields?: Record }` | optional | Translations for the action preflight panel | +| **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record; … }` | optional | Translations for the action result dialog | +| **preflight** | `{ fields?: Record; columns?: Record> }` | optional | Translations for the action preflight panel | | **refusals** | `Record }>` | optional | Refusal translations keyed by the code the action's `refusals` declares | ### Nested Shape: `TranslationData.dashboards[string]` @@ -880,8 +881,8 @@ Translation data for a single object | **cancelText** | `string` | optional | Translated label of the dismiss button on the action's confirm or param dialog (the action must declare `confirmText` or `params`) | | **outcomeMessages** | `Record` | optional | Translated success copy per handler outcome, keyed by the snake_case outcome name the action's `outcomeMessages` declares | | **params** | `Record }>` | optional | Action parameter translations keyed by parameter name | -| **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record }` | optional | Translations for the action result dialog | -| **preflight** | `{ fields?: Record }` | optional | Translations for the action preflight panel | +| **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record; … }` | optional | Translations for the action result dialog | +| **preflight** | `{ fields?: Record; columns?: Record> }` | optional | Translations for the action preflight panel | | **refusals** | `Record }>` | optional | Refusal translations keyed by the code the action's `refusals` declares | ### Nested Shape: `TranslationItem.dashboards[string]`