From eca1eed454d952367621d18b4c3443f5bfbb917c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 15:19:45 +0000 Subject: [PATCH 01/22] wip(spec): hook refusals on handler hooks, reasons and params (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- packages/spec/src/data/hook-refusal-codes.ts | 189 +++++++++++--- packages/spec/src/data/hook.zod.ts | 260 +++++++++++++++---- packages/spec/src/system/i18n-resolver.ts | 16 +- packages/spec/src/system/translation.zod.ts | 51 ++-- 4 files changed, 414 insertions(+), 102 deletions(-) diff --git a/packages/spec/src/data/hook-refusal-codes.ts b/packages/spec/src/data/hook-refusal-codes.ts index c2bbbe725be..ed176cf0106 100644 --- a/packages/spec/src/data/hook-refusal-codes.ts +++ b/packages/spec/src/data/hook-refusal-codes.ts @@ -5,17 +5,22 @@ * letter A): the vocabulary, the save-time reading of a body's literal throws, * and the sentences both halves speak. * - * A hook that declares `refusals: { : { message, status? } }` refuses by - * code only. Its body throws an error carrying a declared `code`; the runtime + * A hook that declares `refusals: { : { message, status?, reasons?, + * params? } }` refuses by code only. Its code — a sandboxed `js` body, or an + * in-process `handler` the build lowers to one (#33214, ruling 6879477573 + * letter A) — throws an error carrying a declared `code`, and optionally a + * declared `reason` and the `params` the sentence's holes name; the runtime * answers with the declared message, translated through - * `hooks..refusals..message` in the caller's locale, and the - * declared status. A code the catalogue does not declare is refused loudly: + * `hooks..refusals..message` (or + * `hooks..refusals..reasons..message`) in the caller's + * locale, and the declared status. A code, or a reason, the catalogue does not + * declare is refused loudly: * - * - at save time, where the body names the code literally in a `throw` - * ({@link hookRefusalCodesThrownIn}) — `HookSchema` refuses the hook at - * every door that parses one; - * - otherwise at run time, where the sandboxed body runner answers the throw - * as a fault naming the hook and the code + * - at save time, where the hook's source names it literally in a `throw` + * ({@link hookRefusalCodesThrownIn}, {@link hookRefusalReasonsThrownIn}) — + * `HookSchema` refuses the hook at every door that parses one; + * - otherwise at run time, where the runtime answers the throw as a fault + * naming the hook and the code * (`packages/runtime/src/sandbox/hook-refusal-catalogue.ts`). * * It imports nothing, on purpose: `data/hook.zod.ts` reads it and so does the @@ -34,6 +39,32 @@ export const HOOK_REFUSAL_CODE_PATTERN = /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*$/; /** A string literal in any of the three quote forms, holding a refusal code. */ const CODE_LITERAL = String.raw`(?['"\x60])(?[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*)\k`; +/** + * The spelling of a declared refusal reason (#33214): snake_case, a machine + * name like every other key an author declares under a code. A reason never + * reaches the wire — the code does — so it is spelled as a data value, not as + * an error code, and the literal reading can tell the two apart. + */ +export const HOOK_REFUSAL_REASON_PATTERN = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/; + +/** + * The spelling of a declared refusal param (#33214): an identifier, the root a + * `{{ name }}` hole in the entry's sentences names. + */ +export const HOOK_REFUSAL_PARAM_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/; + +/** A string literal in any of the three quote forms, holding a refusal reason. */ +const REASON_LITERAL = String.raw`(?['"\x60])(?[a-z][a-z0-9]*(?:_[a-z0-9]+)*)\k`; + +/** `reason: 'x'` — the property in an object literal a `throw` builds. */ +const REASON_PROPERTY = new RegExp(String.raw`(?[A-Za-z_$][\w$]*)\s*\.\s*reason\s*=(?!=)\s*` + REASON_LITERAL, + 'g', +); + /** `code: 'X'` — the property in an object literal a `throw` builds. */ const CODE_PROPERTY = new RegExp(String.raw`(? { + const pairs: Array<{ code: string; reason: string }> = []; + const seen = new Set(); + const add = (code: string, reason: string) => { + const key = `${code}.${reason}`; + if (seen.has(key)) return; + seen.add(key); + pairs.push({ code, reason }); + }; + const thrownNames = new Set(); + const masked = maskedSource(source); + for (const statement of throwStatements(masked)) { + const codes = new Set([...statement.matchAll(CODE_PROPERTY)].map((m) => m.groups!.code)); + if (codes.size === 1) { + const [code] = codes; + for (const m of statement.matchAll(REASON_PROPERTY)) add(code!, m.groups!.reason); + } + const binding = thrownBinding(statement); + if (binding) thrownNames.add(binding); + } + const codeOf = new Map(); + for (const m of masked.matchAll(CODE_ASSIGNMENT)) { + if (thrownNames.has(m.groups!.binding)) codeOf.set(m.groups!.binding, m.groups!.code); + } + for (const m of masked.matchAll(REASON_ASSIGNMENT)) { + const code = codeOf.get(m.groups!.binding); + if (code !== undefined) add(code, m.groups!.reason); + } + return pairs; +} + /** The declared codes, as the sentence lists them. */ function declaredList(declared: readonly string[]): string { return declared.length > 0 ? declared.map((c) => `'${c}'`).join(', ') : 'none'; @@ -171,44 +249,54 @@ function declaredList(declared: readonly string[]): string { * The save-time refusal for a code a body throws literally and the hook's * catalogue does not declare. */ -export function undeclaredHookRefusalCodeAtSave(code: string, declared: readonly string[]): string { +export function undeclaredHookRefusalCodeAtSave( + code: string, + declared: readonly string[], + at: 'body.source' | 'handler' = 'body.source', +): string { return ( - `\`body.source\` throws code '${code}', and this hook's \`refusals\` declares no such code ` + `\`${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 body runs. Declare it under \`refusals.${code}\` with the message the user ` + + `throw is refused when the hook runs. Declare it under \`refusals.${code}\` with the message the user ` + 'reads, or throw one of the declared codes.' ); } /** - * A refusal message with no `{{ … }}` hole. Nothing fills one today (a declared - * message is plain text, translated whole), so a hole is refused at save: a - * later params slot then stays a widening instead of re-reading text authors - * already saved with braces in it. A pattern, not a refinement, so the - * published JSON Schema refuses the same text. + * A refusal message with no `{{ … }}` hole — the rule for an entry that + * declares no `params`: nothing fills a hole there (the message is plain text, + * translated whole), so a hole is refused at save. An entry that declares + * `params` (#33214) is judged by the closed-scope template rule instead + * (`HookSchema`), which allows a hole over a declared param only. */ export const HOOK_REFUSAL_MESSAGE_WITHOUT_HOLE = /^(?![\s\S]*\{\{[^{}]*\}\})[\s\S]*$/; -/** The save-time refusal for a `{{ … }}` hole in a refusal message. */ +/** 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` is plain text and nothing fills a `{{ }}` hole: the caller would read the braces as ' - + 'written. Write the sentence without the hole (a refusal carries no parameters yet).'; + '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.'; + +/** How a hook carrying `refusals` names the code that would answer it, for the sentence below. */ +function refusalCarrier(language: string | undefined): string { + return language !== undefined ? `a \`${language}\` body` : 'no `body` and no `handler`'; +} /** - * The save-time refusal for a catalogue on a hook with no sandboxed `js` body: - * the catalogue is answered only on that path. + * The save-time refusal for a catalogue on a hook whose code cannot throw a + * code: an `expression` body, or no body and no handler at all. */ export function hookRefusalsWithoutSandboxedBody(language: string | undefined): string { - const has = language === undefined ? 'no `body`' : `a \`${language}\` body`; return ( - `\`refusals\` is answered only for a sandboxed \`body\` (\`language: 'js'\`), and this hook has ${has}: ` - + 'an in-process `handler` or an expression body would never serve the catalogue, while `os i18n` still ' - + 'demanded its translations. Give the hook a `js` body that throws the declared codes, or drop `refusals`.' + '`refusals` is answered for a sandboxed `body` (`language: \'js\'`) and for an in-process `handler` (which ' + + `\`os build\` lowers to a \`js\` body), and this hook has ${refusalCarrier(language)}: nothing it runs ` + + 'can throw a declared code, while `os i18n` still demanded its translations. Give the hook a `js` body or a ' + + '`handler` that throws the declared codes, or drop `refusals`.' ); } /** - * The run-time refusal for a body throw the catalogue cannot answer: a code it + * The run-time refusal for a throw the catalogue cannot answer: a code it * does not declare, or no code at all. Fault text, for the server log and the * author: it names the hook and the code and says how to fix it. */ @@ -224,3 +312,44 @@ export function undeclaredHookRefusalAtRun( + 'codes, or declare this one with the message the user reads.' ); } + +/** The declared reasons of one code, as the sentence lists them. */ +function reasonList(declared: readonly string[]): string { + return declared.length > 0 ? declared.map((r) => `'${r}'`).join(', ') : 'none'; +} + +/** + * The save-time refusal for a reason a hook's source throws literally under a + * declared code whose `reasons` does not declare it (#33214). + */ +export function undeclaredHookRefusalReasonAtSave( + code: string, + reason: string, + declared: readonly string[], + at: 'body.source' | 'handler', +): 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 ` + + 'message the user reads, or throw one of the declared reasons.' + ); +} + +/** + * The run-time refusal for a declared code thrown with a reason the code's + * `reasons` does not declare (#33214). Fault text, like + * {@link undeclaredHookRefusalAtRun}. + */ +export function undeclaredHookRefusalReasonAtRun( + hookName: string, + code: string, + reason: string, + declared: readonly string[], +): string { + return ( + `hook '${hookName}' 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.' + ); +} diff --git a/packages/spec/src/data/hook.zod.ts b/packages/spec/src/data/hook.zod.ts index 2911ddc36d8..44ff52316fe 100644 --- a/packages/spec/src/data/hook.zod.ts +++ b/packages/spec/src/data/hook.zod.ts @@ -33,10 +33,19 @@ import { HOOK_REFUSAL_CODE_PATTERN, HOOK_REFUSAL_MESSAGE_HOLE_REFUSED, HOOK_REFUSAL_MESSAGE_WITHOUT_HOLE, + HOOK_REFUSAL_PARAM_PATTERN, + HOOK_REFUSAL_REASON_PATTERN, hookRefusalCodesThrownIn, + hookRefusalReasonsThrownIn, hookRefusalsWithoutSandboxedBody, undeclaredHookRefusalCodeAtSave, + undeclaredHookRefusalReasonAtSave, } 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'; /* * ── Unknown-key strictness (#4001 data step) ──────────────────────────────── @@ -237,65 +246,169 @@ function refuseHookBodyMailGrant( * ── A hook that declares `refusals` refuses by code only ──────────────────── * * [#26170, maintainer ruling 6431311681 letter A] A hook's refusal catalogue - * names every refusal its body may throw. The runtime answers a declared code + * names every refusal its code may throw. The runtime answers a declared code * with the declared message in the caller's locale; it refuses a code the - * catalogue does not declare, loudly. Where the body names the code literally - * in a `throw` (`hookRefusalCodesThrownIn`), the save decides it first: the - * parse refuses the hook at every door that parses one — the metadata save - * door, `defineStack` / `os validate`, compile, an artifact's parse — so the - * author meets the refusal before any write does. One issue per code, at - * `body.source`. A code that arrives any other way is the run-time refusal's. + * catalogue does not declare, loudly. Where the hook's source names the code + * literally in a `throw` (`hookRefusalCodesThrownIn`), the save decides it + * first: the parse refuses the hook at every door that parses one — the + * metadata save door, `defineStack` / `os validate`, compile, an artifact's + * parse — so the author meets the refusal before any write does. One issue per + * code. A code that arrives any other way is the run-time refusal's. The same + * holds for a reason under a code (#33214, `hookRefusalReasonsThrownIn`). * - * A catalogue is answered only on the sandboxed `body` path, so `refusals` on - * a hook with no `js` body — an in-process `handler`, or an `expression` body - * that cannot throw a code — is refused at `refusals`: the catalogue would be - * demanded by `os i18n` and served by nobody. + * [#33214, ruling 6879477573 letter A] The catalogue is answered on every path + * a hook runs on: a sandboxed `js` body, and an in-process `handler` — an + * inline function (`os build` lowers it to a `js` body; a source boot runs it + * in-process) or the string reference the build leaves when it cannot lower + * one. The source a save reads is the code that runs: a `js` body's `source` + * (a body wins over a handler at bind), else an inline handler's own source, + * which is the text the build's lowering peels. A string reference names code + * the save cannot read, so its codes are the run-time refusal's alone. Only a + * hook whose code cannot throw a code — an `expression` body, or neither a body + * nor a handler — is refused at `refusals`: the catalogue would be demanded by + * `os i18n` and served by nobody. * - * A hook that declares no `refusals` is untouched: its body's throws are - * answered as they always were. + * A hook that declares no `refusals` is untouched: its throws are answered as + * they always were. */ +/** The source a save reads a hook's literal throws from, and where an issue about it points. */ +function refusalSourceOf( + hook: { body?: { language?: string; source?: unknown }; handler?: unknown }, +): { source: string; at: 'body.source' | 'handler' } | undefined { + if (hook.body?.language === 'js') { + return typeof hook.body.source === 'string' ? { source: hook.body.source, at: 'body.source' } : undefined; + } + if (typeof hook.handler === 'function') { + let source: string; + try { + source = Function.prototype.toString.call(hook.handler); + } catch { + return undefined; + } + return { source, at: 'handler' }; + } + return undefined; +} + /** * The object-level check that refuses a catalogue nothing would answer, and a - * code a hook's sandboxed body throws literally that its `refusals` does not - * declare. See the block above. + * code (or a reason under a code) a hook's source throws literally that its + * `refusals` does not declare. See the block above. */ function refuseUndeclaredLiteralRefusalCode( - hook: { refusals?: Record; body?: { language?: string; source?: unknown } }, + hook: { + refusals?: Record } | undefined>; + body?: { language?: string; source?: unknown }; + handler?: unknown; + }, ctx: z.RefinementCtx, ): void { if (!hook.refusals) return; - if (hook.body?.language !== 'js') { + const hasHandler = typeof hook.handler === 'function' || (typeof hook.handler === 'string' && hook.handler.length > 0); + const answered = hook.body === undefined ? hasHandler : hook.body.language === 'js'; + if (!answered) { ctx.addIssue({ code: 'custom', path: ['refusals'], message: hookRefusalsWithoutSandboxedBody(hook.body?.language) }); return; } - if (typeof hook.body.source !== 'string') return; + const read = refusalSourceOf(hook); + if (!read) return; + const path = read.at === 'body.source' ? ['body', 'source'] : ['handler']; const declared = Object.keys(hook.refusals); - for (const code of hookRefusalCodesThrownIn(hook.body.source)) { + for (const code of hookRefusalCodesThrownIn(read.source)) { if (Object.prototype.hasOwnProperty.call(hook.refusals, code)) continue; + ctx.addIssue({ code: 'custom', path, message: undeclaredHookRefusalCodeAtSave(code, declared, read.at) }); + } + for (const { code, reason } of hookRefusalReasonsThrownIn(read.source)) { + if (!Object.prototype.hasOwnProperty.call(hook.refusals, code)) continue; + const reasons = hook.refusals[code]?.reasons ?? {}; + if (Object.prototype.hasOwnProperty.call(reasons, reason)) continue; ctx.addIssue({ code: 'custom', - path: ['body', 'source'], - message: undeclaredHookRefusalCodeAtSave(code, declared), + path, + message: undeclaredHookRefusalReasonAtSave(code, reason, Object.keys(reasons), read.at), }); } } +/** + * 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. + */ +export 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; a {{ }} ' + + 'hole names one of the entry\'s params', + ), + }, +)); + +export type HookRefusalReason = z.input; + +/** 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's body throws this entry's code, and the status the - * refusal is answered with. + * 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: * - * The message is plain text, handed over verbatim in the source locale and - * replaced whole by its translation, `hooks..refusals..message` — - * the validation-rule message's posture (`objects.._validations..message`): - * an authored refusal has no parameter contract, so a `{{ }}` hole is refused at save. + * - `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. + * - `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 save; an entry that + * declares no `params` is plain text and every `{{ }}` hole in it is + * refused, as before. */ 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' }, + 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` ' @@ -305,16 +418,53 @@ export const HookRefusalSchema = lazySchema(() => strictObject( }, }, { - message: z.string().trim().min(1).regex(HOOK_REFUSAL_MESSAGE_WITHOUT_HOLE, HOOK_REFUSAL_MESSAGE_HOLE_REFUSED).describe( - 'The sentence the user reads when the body throws this code — plain text in the source locale, translated ' - + 'whole through hooks..refusals..message in the caller\'s locale; a {{ }} hole is refused', + 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; a {{ }} hole is refused unless it names one ' + + 'of the entry\'s params', ), 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', + ), + 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 }} hole renders the value the hook throws in ' + + '`params` ({ code, params: { NAME: value } }). A hole over any other name is 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 type HookRefusal = z.input; @@ -640,26 +790,37 @@ export const HookSchema = lazySchema(() => strictObject( /** * The hook's refusal catalogue (#26170, maintainer ruling 6431311681 - * letter A): every refusal its body may throw, keyed by the code it throws. + * letter A): every refusal its code may throw, keyed by the code it throws. * * refusals: { * CLEAN_VERSION_REQUIRED: { message: 'A current clean version is required before signing.', status: 422 }, + * VALIDATION_FAILED: { + * message: 'This plan cannot be submitted.', + * params: ['state'], + * reasons: { plan_locked: { message: 'The plan is {{ state }} and can no longer change.' } }, + * }, * } * - * The body refuses by code only — it throws an error carrying a declared - * `code`, and the runtime answers with that entry: its `message`, translated - * through `hooks..refusals..message` in the caller's locale with - * the declared message as the fallback, marked as the end user's sentence, - * and its `status`. A code the catalogue does not declare, or a throw with no - * code, is refused loudly: at save where the body names it literally, - * otherwise when it runs, as a fault naming the hook and the code. An error - * a host call raised and the body let through unchanged (a `ctx.api` write - * refused by the engine, a nested hook's refusal) passes through as before, - * and so does a crash. + * The hook refuses by code only — it throws an error carrying a declared + * `code` (and, #33214, optionally a declared `reason` and the `params` its + * sentence names), and the runtime answers with that entry: its `message` + * (or the reason's), translated through `hooks..refusals..message` + * (`…..reasons..message`) in the caller's locale with the + * declared sentence as the fallback, its holes filled from `params`, marked + * as the end user's sentence, and its `status`. A code or reason the + * catalogue does not declare, or a throw with no code, is refused loudly: at + * save where the hook's source names it literally, otherwise when it runs, + * as a fault naming the hook and the code. An error a host call raised and + * the hook let through unchanged (a `ctx.api` write refused by the engine, a + * nested hook's refusal) passes through as before, and so does a crash. * * Keyed by hook name, not by object: one hook bound to several objects, or - * to `'*'`, owns one catalogue and one translation per code. Read by the - * sandboxed `body` runner only, so it is refused on a hook with no `js` body. + * to `'*'`, owns one catalogue and one translation per code. Answered on + * every path the hook runs on (#33214, ruling 6879477573): a sandboxed `js` + * body, and an in-process `handler` — inline, or the string reference a + * build leaves when it cannot lower one — through one in-process seam with + * the same wire. Refused on a hook whose code cannot throw a code: an + * `expression` body, or neither a body nor a handler. * Absent: the hook's throws are answered as they always were. */ refusals: z.record( @@ -668,10 +829,11 @@ export const HookSchema = lazySchema(() => strictObject( }), HookRefusalSchema, ).optional().describe( - 'Refusal catalogue keyed by the SCREAMING_SNAKE code the body throws: { message, status? }. The body refuses ' - + 'by code only; the runtime answers with the declared message (translated through ' - + 'hooks..refusals..message in the caller\'s locale) and status. A code not declared here is refused ' - + 'loudly — at save when the body throws it literally, otherwise at run time', + 'Refusal catalogue keyed by the SCREAMING_SNAKE code the hook throws: { message, status?, reasons?, params? }. ' + + 'The hook (a js body or a handler) refuses by code only, optionally with a declared reason and params; the ' + + 'runtime answers with the declared message (translated through hooks..refusals..message, or ' + + '…..reasons..message, in the caller\'s locale, holes filled from params) and status. A code or ' + + 'reason not declared here is refused loudly — at save when the hook throws it literally, otherwise at run time', ), /** diff --git a/packages/spec/src/system/i18n-resolver.ts b/packages/spec/src/system/i18n-resolver.ts index d1eb39029d2..22ab117fc82 100644 --- a/packages/spec/src/system/i18n-resolver.ts +++ b/packages/spec/src/system/i18n-resolver.ts @@ -4392,21 +4392,25 @@ export function flowNoticeMessageKey(flowName: string, nodeId: string): string { /** * Dot-notation i18n key for a hook's declared refusal message — * `hooks..refusals..message` (#26170, maintainer ruling 6431311681 - * letter A). + * letter A), or, given a declared reason under the code (#33214, ruling + * 6879477573 S1), `hooks..refusals..reasons..message`. * * A sibling of {@link objectValidationMessageKey} and * {@link flowRefusalMessageKey}, spelled here for the same reason: its consumer * holds an `II18nService` (which takes a key), not a `TranslationBundle`. Used - * by the sandboxed body runner, which answers a body's throw of a declared code - * (`HookSchema.refusals`) with this translation in the caller's locale - * (`HookContext.session.locale`), the declared message on a miss. + * by the hook runtime (the sandboxed body runner and the in-process handler + * seam), which answers a throw of a declared code (`HookSchema.refusals`) with + * this translation in the caller's locale (`HookContext.session.locale`), the + * declared sentence on a miss. * * `hookName` is `Hook.name` and `code` the catalogue's key — by hook, never by * object, so a hook bound to several objects or to `'*'` owns one translation * per code. */ -export function hookRefusalMessageKey(hookName: string, code: string): string { - return `hooks.${hookName}.refusals.${code}.message`; +export function hookRefusalMessageKey(hookName: string, code: string, reason?: string): string { + return reason === undefined + ? `hooks.${hookName}.refusals.${code}.message` + : `hooks.${hookName}.refusals.${code}.reasons.${reason}.message`; } /** diff --git a/packages/spec/src/system/translation.zod.ts b/packages/spec/src/system/translation.zod.ts index d6657994a77..0d34a304b28 100644 --- a/packages/spec/src/system/translation.zod.ts +++ b/packages/spec/src/system/translation.zod.ts @@ -2047,7 +2047,8 @@ const appTranslationDataShape = () => ({ * Hook translations keyed by hook name (`Hook.name`) — #26170, maintainer * ruling 6431311681 letter A. * - * hooks..refusals..message (a declared refusal, `HookSchema.refusals`) + * hooks..refusals..message (a declared refusal, `HookSchema.refusals`) + * hooks..refusals..reasons..message (a declared reason under it, #33214) * * A hook's business refusal ("A current clean version is required before * signing.") is the sentence a user reads most often when an app says "not @@ -2063,16 +2064,21 @@ const appTranslationDataShape = () => ({ * `'*'` (`HookSchema.object`); one catalogue per hook means one translation * per code, whatever the hook is bound to. * - * **Picked before it is served, by the body runner.** The sandboxed body - * runner answers a throw of a declared code with `hookRefusalMessageKey(hook, - * code)` (`system/i18n-resolver.ts`), read through the `i18n` service in the - * caller's `HookContext.session.locale` negotiated by `resolveBundleLocale`; - * with no locale, or no entry, the declared message is served. The message - * is plain text like the validation-rule message it sits beside: no `{{ }}` - * hole is filled, the translation replaces it whole. - * - * `objectstack validate` refuses a key over an unknown hook, or a code the - * hook's `refusals` does not declare. + * **Picked before it is served, by the runtime.** The hook runtime — the + * sandboxed body runner, and the in-process seam a `handler` runs through + * (#33214) — answers a throw of a declared code with + * `hookRefusalMessageKey(hook, code, reason?)` (`system/i18n-resolver.ts`), + * read through the `i18n` service in the caller's `HookContext.session.locale` + * negotiated by `resolveBundleLocale`; with no locale, or no entry, the + * declared sentence is served. The translation replaces the declared sentence + * whole. A sentence whose entry declares `params` is a template: the + * translation keeps the declared `{{ NAME }}` holes, and the runtime fills + * them from the throw's `params` after picking it — the flow `end` refusal's + * posture (translated before it is rendered). A sentence whose entry declares + * no `params` is plain text and nothing in it is filled. + * + * `objectstack validate` refuses a key over an unknown hook, a code the hook's + * `refusals` does not declare, or a reason that code does not declare. */ hooks: z.record(z.string(), strictObject({ surface: 'this hook translation', @@ -2087,16 +2093,27 @@ const appTranslationDataShape = () => ({ refusals: z.record(z.string(), strictObject({ surface: 'this hook refusal translation', history: TRANSLATION_HISTORY, - // The spellings `HookRefusalSchema` renames onto its own `message`. - aliases: { text: 'message', reason: 'message', description: 'message' }, + // The spellings `HookRefusalSchema` renames onto its own `message` and `reasons`. + aliases: { text: 'message', reason: 'message', description: 'message', variants: 'reasons', messages: 'reasons' }, }, { - // Plain text, like the declared message it translates; an empty string - // is the untranslated skeleton slot `os i18n extract` writes (the - // declared message is served). + // 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', + + '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"), })).optional().describe('Hook translations keyed by hook name'), From 96c899d0211feeb0700d54288fbda7c949e6c0f5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 15:24:50 +0000 Subject: [PATCH 02/22] wip(spec): tests and dropped-refinement ledger (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- packages/spec/authorable-surface/data.json | 3 + .../spec/dropped-refinements.baseline.json | 12 +- packages/spec/json-schema.manifest/data.json | 1 + packages/spec/src/data/hook-refusals.test.ts | 226 +++++++++++++++++- 4 files changed, 238 insertions(+), 4 deletions(-) diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index 60273ebb7ab..d83fb0408b2 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -488,7 +488,10 @@ "data/HookContext:transaction", "data/HookContext:user", "data/HookRefusal:message", + "data/HookRefusal:params", + "data/HookRefusal:reasons", "data/HookRefusal:status", + "data/HookRefusalReason:message", "data/ImportFieldMapping:params", "data/ImportFieldMapping:source", "data/ImportFieldMapping:target", diff --git a/packages/spec/dropped-refinements.baseline.json b/packages/spec/dropped-refinements.baseline.json index 9787bbef748..c32ec7acdcc 100644 --- a/packages/spec/dropped-refinements.baseline.json +++ b/packages/spec/dropped-refinements.baseline.json @@ -133,6 +133,7 @@ "manifest.flows.element.variables.element", "manifest.hooks.element", "manifest.hooks.element.object", + "manifest.hooks.element.refusals.valueType", "manifest.jobs.element", "manifest.jobs.element.schedule.options[0].timezone", "manifest.mappings.element", @@ -311,6 +312,7 @@ "data.options[1].manifest.flows.element.variables.element", "data.options[1].manifest.hooks.element", "data.options[1].manifest.hooks.element.object", + "data.options[1].manifest.hooks.element.refusals.valueType", "data.options[1].manifest.jobs.element", "data.options[1].manifest.jobs.element.schedule.options[0].timezone", "data.options[1].manifest.mappings.element", @@ -458,6 +460,7 @@ "options[1].manifest.flows.element.variables.element", "options[1].manifest.hooks.element", "options[1].manifest.hooks.element.object", + "options[1].manifest.hooks.element.refusals.valueType", "options[1].manifest.jobs.element", "options[1].manifest.jobs.element.schedule.options[0].timezone", "options[1].manifest.mappings.element", @@ -545,6 +548,7 @@ "data.packages.element.options[1].manifest.flows.element.variables.element", "data.packages.element.options[1].manifest.hooks.element", "data.packages.element.options[1].manifest.hooks.element.object", + "data.packages.element.options[1].manifest.hooks.element.refusals.valueType", "data.packages.element.options[1].manifest.jobs.element", "data.packages.element.options[1].manifest.jobs.element.schedule.options[0].timezone", "data.packages.element.options[1].manifest.mappings.element", @@ -1023,7 +1027,13 @@ "data/Hook": { "sites": [ "", - "object" + "object", + "refusals.valueType" + ] + }, + "data/HookRefusal": { + "sites": [ + "" ] }, "data/InlineGridColumn": { diff --git a/packages/spec/json-schema.manifest/data.json b/packages/spec/json-schema.manifest/data.json index 32d125d021d..f67a85c53bd 100644 --- a/packages/spec/json-schema.manifest/data.json +++ b/packages/spec/json-schema.manifest/data.json @@ -90,6 +90,7 @@ "data/HookContext", "data/HookEvent", "data/HookRefusal", + "data/HookRefusalReason", "data/ImportFieldMapping", "data/Index", "data/InlineGridColumn", diff --git a/packages/spec/src/data/hook-refusals.test.ts b/packages/spec/src/data/hook-refusals.test.ts index 406ac3ea338..cdc77f4d605 100644 --- a/packages/spec/src/data/hook-refusals.test.ts +++ b/packages/spec/src/data/hook-refusals.test.ts @@ -5,8 +5,12 @@ import { HOOK_REFUSAL_MESSAGE_HOLE_REFUSED, hookRefusalCodesThrownIn, hookRefusalsWithoutSandboxedBody, + HOOK_REFUSAL_REASON_PATTERN, + hookRefusalReasonsThrownIn, undeclaredHookRefusalAtRun, undeclaredHookRefusalCodeAtSave, + undeclaredHookRefusalReasonAtRun, + undeclaredHookRefusalReasonAtSave, } from './hook-refusal-codes'; import { hookRefusalMessageKey } from '../system/i18n-resolver'; import { TranslationDataSchema } from '../system/translation.zod'; @@ -48,18 +52,23 @@ describe('Hook.refusals — the declared catalogue', () => { }); it.each([ - ['an in-process `handler`', { handler: 'creditGuard' }, 'no `body`'], + ['neither a body nor a handler', {}, 'no `body` and no `handler`'], ['an expression body', { body: { language: 'expression', source: 'record.amount > 0' } }, 'a `expression` body'], + [ + 'an expression body beside a handler (the body wins at bind)', + { body: { language: 'expression', source: 'record.amount > 0' }, handler: 'creditGuard' }, + 'a `expression` body', + ], ])('refuses a catalogue on a hook with %s — nothing would answer it', (_label, rest, has) => { const r = HookSchema.safeParse({ ...base, ...rest, refusals: { CREDIT_LIMIT: { message: 'x' } } }); expect(r.success).toBe(false); const issue = r.error!.issues.find((i) => i.path.join('.') === 'refusals')!; - expect(issue.message).toBe(hookRefusalsWithoutSandboxedBody(has === 'no `body`' ? undefined : 'expression')); + expect(issue.message).toBe(hookRefusalsWithoutSandboxedBody(has.startsWith('no') ? undefined : 'expression')); expect(issue.message).toContain(has); }); it.each(['Over the limit of {{limit}}.', 'Hi {{ user.name }}, no.', 'Line one.\nOver {{limit}}.'])( - 'refuses a `{{ }}` hole in %j — nothing fills it, and a params slot stays additive', + 'refuses a `{{ }}` hole in %j when the entry declares no `params` — nothing fills it', (message) => { const r = HookSchema.safeParse({ ...base, body: body('return;'), refusals: { CREDIT_LIMIT: { message } } }); expect(r.success).toBe(false); @@ -225,3 +234,214 @@ describe('HookContext.session.locale — the locale a refusal is picked in', () expect(HookContextSchema.safeParse({ ...ctx, session: { userId: 'u1' } }).success).toBe(true); }); }); + +// #33214 (ruling 6879477573: 问一 A, 问二 S1, 问三 是) — the catalogue is answered +// on a handler-authored hook too, a code holds further sentences under declared +// reasons, and a sentence may name declared params. + +describe('Hook.refusals on a handler-authored hook (#33214)', () => { + const refusals = { CREDIT_LIMIT: { message: 'Over the credit limit.' } }; + + it('accepts a catalogue on a hook whose `handler` is an inline function', () => { + const handler = async (ctx: any) => { + if (ctx.input.amount > 10) throw Object.assign(new Error('x'), { code: 'CREDIT_LIMIT' }); + }; + const r = HookSchema.safeParse({ ...base, handler, refusals }); + expect(r.success).toBe(true); + expect(r.success && r.data.refusals?.CREDIT_LIMIT.message).toBe('Over the credit limit.'); + }); + + it('accepts a catalogue on a hook whose `handler` is a string reference — its codes are judged when it runs', () => { + expect(HookSchema.safeParse({ ...base, handler: 'creditGuard', refusals }).success).toBe(true); + }); + + it('refuses a literal code the catalogue does not declare, read off the inline handler, at `handler`', () => { + const handler = async () => { + throw Object.assign(new Error('x'), { code: 'CREDIT_LIMT' }); + }; + const r = HookSchema.safeParse({ ...base, handler, refusals }); + expect(r.success).toBe(false); + const issue = r.error!.issues.find((i) => i.path.join('.') === 'handler')!; + expect(issue.message).toBe(undeclaredHookRefusalCodeAtSave('CREDIT_LIMT', ['CREDIT_LIMIT'], 'handler')); + expect(issue.message.startsWith('`handler` throws code')).toBe(true); + }); + + it('reads the body, not the handler, when both are present — the body wins at bind', () => { + const handler = async () => { + throw Object.assign(new Error('x'), { code: 'NOT_RUN' }); + }; + const r = HookSchema.safeParse({ + ...base, + handler, + body: body("throw Object.assign(new Error('x'), { code: 'CREDIT_LIMIT' });"), + refusals, + }); + expect(r.success).toBe(true); + }); +}); + +describe('HookRefusal.reasons — further sentences under one code (#33214, S1)', () => { + const refusals = { + VALIDATION_FAILED: { + message: 'This plan cannot be submitted.', + reasons: { plan_locked: { message: 'The plan is locked.' }, second_primary: { message: 'A primary plant exists.' } }, + }, + }; + + it('accepts declared snake_case reasons with a message each', () => { + const r = HookSchema.safeParse({ + ...base, + body: body("throw { code: 'VALIDATION_FAILED', reason: 'plan_locked', message: 'x' };"), + refusals, + }); + expect(r.success).toBe(true); + }); + + it.each(['PlanLocked', 'PLAN_LOCKED', 'plan-locked', '1st'])('refuses the reason key %j — a reason is snake_case', (key) => { + const r = HookRefusalSchema.safeParse({ message: 'x', reasons: { [key]: { message: 'y' } } }); + expect(r.success).toBe(false); + expect(r.error!.issues.some((i) => i.path[0] === 'reasons')).toBe(true); + }); + + it('refuses an empty reason message and a reason carrying its own status', () => { + expect(HookRefusalSchema.safeParse({ message: 'x', reasons: { a: { message: ' ' } } }).success).toBe(false); + const r = HookRefusalSchema.safeParse({ message: 'x', reasons: { a: { message: 'y', status: 409 } } }); + expect(r.success).toBe(false); + expect(r.error!.issues.find((i) => i.code === 'unrecognized_keys')?.message).toContain('`status`'); + }); + + it('refuses at `body.source` a literal reason the code does not declare', () => { + const r = HookSchema.safeParse({ + ...base, + body: body("throw { code: 'VALIDATION_FAILED', reason: 'plan_lockd', message: 'x' };"), + refusals, + }); + expect(r.success).toBe(false); + const issue = r.error!.issues.find((i) => i.path.join('.') === 'body.source')!; + expect(issue.message).toBe( + undeclaredHookRefusalReasonAtSave('VALIDATION_FAILED', 'plan_lockd', ['plan_locked', 'second_primary'], 'body.source'), + ); + }); + + it('refuses at `handler` a literal reason under a code with no `reasons`', () => { + const handler = async () => { + const e: any = new Error('x'); + e.code = 'CREDIT_LIMIT'; + e.reason = 'over_by_far'; + throw e; + }; + const r = HookSchema.safeParse({ ...base, handler, refusals: { CREDIT_LIMIT: { message: 'Over.' } } }); + expect(r.success).toBe(false); + const issue = r.error!.issues.find((i) => i.path.join('.') === 'handler')!; + expect(issue.message).toContain("reason 'over_by_far'"); + expect(issue.message).toContain('declared: none'); + }); +}); + +describe('hookRefusalReasonsThrownIn — the save-time reading of reasons', () => { + it.each([ + ["throw { code: 'A_B', reason: 'x_y' };", [{ code: 'A_B', reason: 'x_y' }]], + ["throw Object.assign(new Error('m'), { reason: \"r\", code: \"C\" });", [{ code: 'C', reason: 'r' }]], + ["const e = new Error('m'); e.code = 'C'; e.reason = 'r'; throw e;", [{ code: 'C', reason: 'r' }]], + ])('reads %j', (source, pairs) => { + expect(hookRefusalReasonsThrownIn(source)).toEqual(pairs); + }); + + it.each([ + // no literal code beside it + "throw { code: c, reason: 'r' };", + // a reason outside any throw + "const row = { reason: 'r' }; throw { code: 'C' };", + // inside a string or a comment + "// throw { code: 'C', reason: 'r' }\nreturn;", + "throw new Error(\"reason: 'r'\");", + ])('reads nothing in %j', (source) => { + expect(hookRefusalReasonsThrownIn(source)).toEqual([]); + }); + + it('does not read a kept reason literal spelling `throw` as a throw statement', () => { + expect(hookRefusalCodesThrownIn("const k = 'throw'; const r = { code: 'NOPE' };")).toEqual([]); + }); + + it.each(['a', 'plan_locked', 'x1_y2'])('the reason pattern accepts %s', (r) => expect(HOOK_REFUSAL_REASON_PATTERN.test(r)).toBe(true)); + it.each(['A', 'Plan', '_a', 'a_', 'a__b', 'a-b'])('the reason pattern refuses %s', (r) => expect(HOOK_REFUSAL_REASON_PATTERN.test(r)).toBe(false)); + + it('the run-time fault names the hook, the code, the reason and the declared reasons', () => { + const text = undeclaredHookRefusalReasonAtRun('plan_gate', 'VALIDATION_FAILED', 'nope', ['plan_locked']); + expect(text).toContain("hook 'plan_gate' threw code 'VALIDATION_FAILED' with reason 'nope'"); + expect(text).toContain("declared: 'plan_locked'"); + }); +}); + +describe('HookRefusal.params — declared names a sentence may fill (#33214)', () => { + it('accepts a hole over a declared param, in the message and in a reason', () => { + const r = HookRefusalSchema.safeParse({ + message: 'The plan is {{ state }}.', + params: ['state', 'owner'], + reasons: { locked: { message: 'Locked by {{ owner }} while {{ state }}.' } }, + }); + expect(r.success).toBe(true); + }); + + it('accepts a hole with a formatter over a declared param', () => { + expect(HookRefusalSchema.safeParse({ message: 'Over by {{ amount | number }}.', params: ['amount'] }).success).toBe(true); + }); + + it('refuses a hole over a name the entry does not declare, naming the declared roots', () => { + const r = HookRefusalSchema.safeParse({ message: 'The plan is {{ stat }}.', params: ['state'] }); + expect(r.success).toBe(false); + const issue = r.error!.issues.find((i) => i.path.join('.') === 'message')!; + expect(issue.message).toContain('`{{ stat }}`'); + expect(issue.message).toContain('`state`'); + }); + + it('refuses an undeclared hole in a reason at `reasons.REASON.message`', () => { + const r = HookRefusalSchema.safeParse({ message: 'x', params: ['a'], reasons: { r: { message: 'Hi {{ b }}.' } } }); + expect(r.success).toBe(false); + expect(r.error!.issues.some((i) => i.path.join('.') === 'reasons.r.message')).toBe(true); + }); + + it('refuses every hole in a reason when the entry declares no params', () => { + const r = HookRefusalSchema.safeParse({ message: 'x', reasons: { r: { message: 'Hi {{ b }}.' } } }); + expect(r.success).toBe(false); + expect(r.error!.issues.find((i) => i.path.join('.') === 'reasons.r.message')!.message).toBe(HOOK_REFUSAL_MESSAGE_HOLE_REFUSED); + }); + + it('prescribes the hole for a single-brace token over a declared param', () => { + const r = HookRefusalSchema.safeParse({ message: 'The plan is {state}.', params: ['state'] }); + expect(r.success).toBe(false); + expect(r.error!.issues[0]!.message).toContain('{{ state }}'); + }); + + it.each([['1a'], ['a-b'], ['$x']])('refuses the param name %j', (name) => { + expect(HookRefusalSchema.safeParse({ message: 'x', params: [name] }).success).toBe(false); + }); + + it('refuses a param declared twice', () => { + const r = HookRefusalSchema.safeParse({ message: 'x', params: ['a', 'a'] }); + expect(r.success).toBe(false); + expect(r.error!.issues[0]!.path.join('.')).toBe('params.1'); + }); +}); + +describe('the translation address of a reason — `hooks..refusals..reasons..message`', () => { + it('is the key the runtime asks the i18n service for', () => { + expect(hookRefusalMessageKey('plan_gate', 'VALIDATION_FAILED', 'plan_locked')).toBe( + 'hooks.plan_gate.refusals.VALIDATION_FAILED.reasons.plan_locked.message', + ); + expect(hookRefusalMessageKey('plan_gate', 'VALIDATION_FAILED')).toBe('hooks.plan_gate.refusals.VALIDATION_FAILED.message'); + }); + + it('is a path a translation bundle can write, holes kept', () => { + const r = TranslationDataSchema.safeParse({ + hooks: { plan_gate: { refusals: { VALIDATION_FAILED: { reasons: { plan_locked: { message: '计划已{{ state }}。' } } } } } }, + }) as { success: true; data: any }; + expect(r.success).toBe(true); + expect(r.data.hooks.plan_gate.refusals.VALIDATION_FAILED.reasons.plan_locked.message).toBe('计划已{{ state }}。'); + }); + + it('refuses a key a reason translation does not hold', () => { + const r = TranslationDataSchema.safeParse({ hooks: { h: { refusals: { C: { reasons: { r: { title: 'x' } } } } } } }); + expect(r.success).toBe(false); + }); +}); From 8e0dccd99921cf166ef55f537b3811ecd4e1cb7a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 15:31:34 +0000 Subject: [PATCH 03/22] wip(runtime): answer hook refusal reasons, params and in-process handlers (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- content/docs/references/data/hook.mdx | 33 +- content/docs/references/index.mdx | 10 +- .../docs/references/system/translation.mdx | 8 +- .../data.md | 12 +- .../system.md | 2 +- packages/runtime/src/app-artifact-handlers.ts | 7 +- packages/runtime/src/sandbox/body-runner.ts | 39 +- .../src/sandbox/hook-refusal-catalogue.ts | 358 ++++++++++++++++-- .../runtime/src/sandbox/quickjs-runner.ts | 54 ++- packages/spec/api-surface/data.json | 7 + packages/spec/declaration-map/data.json | 2 + packages/spec/export-origins/data.json | 7 + packages/spec/src/data/hook.zod.ts | 6 +- 13 files changed, 489 insertions(+), 56 deletions(-) diff --git a/content/docs/references/data/hook.mdx b/content/docs/references/data/hook.mdx index a218a160b3f..0b9aeac3a8e 100644 --- a/content/docs/references/data/hook.mdx +++ b/content/docs/references/data/hook.mdx @@ -1,7 +1,7 @@ --- title: Hook schema — Data Protocol property reference navTitle: Hook -description: "Hook schemas of the ObjectStack Data Protocol: Hook, HookContext, HookEvent, HookRefusal — each property with its type, default and a TypeScript example." +description: "Hook schemas of the ObjectStack Data Protocol: Hook, HookContext, HookEvent and 2 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: "Hook schemas of the ObjectStack Data Protocol: Hook, HookContext, ## TypeScript Usage ```typescript -import { HookSchema, HookContextSchema, HookEvent, HookRefusalSchema } from '@objectstack/spec/data'; -import type { Hook, HookContext, HookRefusal } from '@objectstack/spec/data'; +import { HookSchema, HookContextSchema, HookEvent, HookRefusalSchema, HookRefusalReasonSchema } from '@objectstack/spec/data'; +import type { Hook, HookContext, HookRefusal, HookRefusalReason } from '@objectstack/spec/data'; // Validate data const result = HookSchema.parse(data); @@ -42,7 +42,7 @@ const result = HookSchema.parse(data); | **timeoutMs** | `number` | optional | Maximum execution time in milliseconds before the hook is aborted | | **timeout** | `never` | optional | [REMOVED] `hook.timeout` was removed in @objectstack/spec 17 — its unit (milliseconds) lived only in the description, beside a body-level `timeoutMs` and a `retryPolicy.backoffMs` that spell theirs, so the same number read as two conventions on one surface. Rename the key to `timeoutMs`; the value (milliseconds) is unchanged. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **onError** | `Enum<'abort' \| 'log'>` | optional (default: `"abort"`) | Error handling strategy. abort: refuse the operation; a blocking hook's abort rolls the write back inside a unit of work, which the write door opens for an after* hook on an object on the default datasource whose driver declares transactions (elsewhere the caller is refused and the row stays stored). log: log the error and continue | -| **refusals** | `Record` | optional | Refusal catalogue keyed by the SCREAMING_SNAKE code the body throws: `{ message, status? }`. The body refuses by code only; the runtime answers with the declared message (translated through hooks.``.refusals.``.message in the caller's locale) and status. A code not declared here is refused loudly — at save when the body throws it literally, otherwise at run time | +| **refusals** | `Record; params?: string[] }>` | optional | Refusal catalogue keyed by the SCREAMING_SNAKE code the hook throws: `{ message, status?, reasons?, params? }`. The hook (a js body or a handler) refuses by code only, optionally with a declared reason and params; the runtime answers with the declared message (translated through hooks.``.refusals.``.message, or ….``.reasons.``.message, in the caller's locale, holes filled from params) and status. A code or reason not declared here is refused loudly — at save when the hook throws it literally, otherwise at run time | | **runAs** | `Enum<'system' \| 'user' \| 'inherit'>` | optional (default: `"inherit"`) | Execution identity for the hook's ctx.api data operations: system = elevated (bypasses RLS), user = the triggering user (RLS-respecting), inherit = the context of the write that fired the hook (the pre-runAs behaviour; the default). A hook with no trigger user has no identity to scope to, so under user its ctx.api data operations are REFUSED — declare system to make the elevation explicit. This covers any hook fired by a write that carried no user (an isSystem plugin/service write; a system-elevated flow node). Elevation does not reach identity assignment: a system hook's governed writes (insert, update, delete, transfer, restore, purge) to sys_user_position, sys_user_permission_set, sys_invitation and sys_member are refused with PERMISSION_DENIED, and a system hook whose body names such a write is refused at save; declare user for position holdings and permission-set grants (the ADR-0090 D12 delegated-administration gate then judges the user the hook acts for), and change invitations and memberships through the organization endpoints. Nor does it reach a ledger: a system hook body's 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. Scope: ctx.api only — condition evaluation, the readonly strip on ctx.input, ctx.session and async are unchanged. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | @@ -84,8 +84,10 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **message** | `string` | ✅ | The sentence the user reads when the body throws this code — plain text in the source locale, translated whole through hooks.``.refusals.``.message in the caller's locale; a `{{ }}` hole is refused | +| **message** | `string` | ✅ | 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; a `{{ }}` hole is refused unless it names one of the entry's params | | **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 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 | +| **params** | `string[]` | optional | The names this entry's sentences may fill: a `{{ NAME }}` hole renders the value the hook throws in `params` (`{ code, params: { NAME: value } }`). A hole over any other name is refused. Absent: the sentences are plain text and a `{{ }}` hole is refused | --- @@ -182,8 +184,27 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **message** | `string` | ✅ | The sentence the user reads when the body throws this code — plain text in the source locale, translated whole through hooks.``.refusals.``.message in the caller's locale; a `{{ }}` hole is refused | +| **message** | `string` | ✅ | 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; a `{{ }}` hole is refused unless it names one of the entry's params | | **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 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 | +| **params** | `string[]` | optional | The names this entry's sentences may fill: a `{{ NAME }}` hole renders the value the hook throws in `params` (`{ code, params: { NAME: value } }`). A hole over any other name is refused. Absent: the sentences are plain text and a `{{ }}` hole is refused | + +### Nested Shape: `HookRefusal.reasons[string]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **message** | `string` | ✅ | 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; a `{{ }}` hole names one of the entry's params | + + +--- + +## HookRefusalReason + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **message** | `string` | ✅ | 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; a `{{ }}` hole names one of the entry's params | --- diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 7161e90a222..4ad300e5580 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 — 1661 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1662 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/. */} @@ -23,7 +23,7 @@ counts are sums of the rows they head. Regenerate with | [AI Protocol](/docs/references/ai) | 14 | 81 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | | [API Protocol](/docs/references/api) | 36 | 492 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 81 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | -| [Data Protocol](/docs/references/data) | 35 | 186 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | +| [Data Protocol](/docs/references/data) | 35 | 187 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | | [Identity Protocol](/docs/references/identity) | 5 | 27 | Users and accounts, organizations, positions, SCIM provisioning. | | [Integration Protocol](/docs/references/integration) | 1 | 23 | The single connector protocol (ADR-0097) — catalog descriptors and provider-bound instances. | | [Kernel Protocol](/docs/references/kernel) | 30 | 153 | Plugin lifecycle and manifests, capabilities and security, metadata loading, service registry. | @@ -34,7 +34,7 @@ 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 | 176 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **218** | **1661** | 14 protocol modules | +| **Total** | **218** | **1662** | 14 protocol modules | --- @@ -139,7 +139,7 @@ Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execu ## Data Protocol -**Source:** `packages/spec/src/data/` · **Import:** `@objectstack/spec/data` · **35 pages, 186 schemas** +**Source:** `packages/spec/src/data/` · **Import:** `@objectstack/spec/data` · **35 pages, 187 schemas** Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. @@ -168,7 +168,7 @@ Objects, fields, queries, filters, datasources and drivers — the ObjectQL laye | [`field.zod.ts`](/docs/references/data/field) | `CurrencyConfig`, `Field`, `FieldMaskingKeep`, `FieldMaskingRule`, `FieldType`, `InlineGridColumn`, `LocationCoordinates`, `SelectOption`, `UniqueScope` | | [`field-value.zod.ts`](/docs/references/data/field-value) | `Address`, `AddressValue`, `CalendarDateValue`, `ClockTimeValue`, `FileLikeValue`, `FileReferenceIdValue`, `FileRefusedValue`, `FileValue`, `InstantValue`, `LocationValue`, `ReferenceIdValue`, `ReferenceNameOnlyValue` | | [`filter.zod.ts`](/docs/references/data/filter) | `ComparisonOperator`, `EqualityOperator`, `FieldOperators`, `FieldReference`, `FilterArray`, `FilterCondition`, `NormalizedFilter`, `NowAnchor`, `QueryFilter`, `RangeOperator`, `SetOperator`, `SpecialOperator`, `StringOperator` | -| [`hook.zod.ts`](/docs/references/data/hook) | `Hook`, `HookContext`, `HookEvent`, `HookRefusal` | +| [`hook.zod.ts`](/docs/references/data/hook) | `Hook`, `HookContext`, `HookEvent`, `HookRefusal`, `HookRefusalReason` | | [`hook-body.zod.ts`](/docs/references/data/hook-body) | `ExpressionBody`, `HookBody`, `HookBodyCapability`, `ScriptBody` | | [`hook-body-doors.zod.ts`](/docs/references/data/hook-body-doors) | `BodyActivityAppendInput`, `BodyDoorRecordRef`, `BodyMailSendInput` | | [`mapping.zod.ts`](/docs/references/data/mapping) | `ImportFieldMapping`, `Mapping`, `TransformType` | diff --git a/content/docs/references/system/translation.mdx b/content/docs/references/system/translation.mdx index 51970ef6b6e..f04ba20ebf0 100644 --- a/content/docs/references/system/translation.mdx +++ b/content/docs/references/system/translation.mdx @@ -297,7 +297,7 @@ Translation data for a single object | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **refusals** | `Record` | optional | Refusal translations keyed by the code the hook's `refusals` declares | +| **refusals** | `Record }>` | optional | Refusal translations keyed by the code the hook's `refusals` declares | ### Nested Shape: `PlatformTranslationData.positions[string]` @@ -475,7 +475,7 @@ Translation data for a single object | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **refusals** | `Record` | optional | Refusal translations keyed by the code the hook's `refusals` declares | +| **refusals** | `Record }>` | optional | Refusal translations keyed by the code the hook's `refusals` declares | ### Nested Shape: `ServedTranslationData.positions[string]` @@ -715,7 +715,7 @@ Translation data for a single object | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **refusals** | `Record` | optional | Refusal translations keyed by the code the hook's `refusals` declares | +| **refusals** | `Record }>` | optional | Refusal translations keyed by the code the hook's `refusals` declares | ### Nested Shape: `TranslationData.positions[string]` @@ -925,7 +925,7 @@ Translation data for a single object | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **refusals** | `Record` | optional | Refusal translations keyed by the code the hook's `refusals` declares | +| **refusals** | `Record }>` | optional | Refusal translations keyed by the code the hook's `refusals` declares | ### Nested Shape: `TranslationItem.positions[string]` 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 f99230906ff..68b2fe02d41 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 @@ -21,7 +21,7 @@ The `strict` column is the one the campaign schedules against; it counts both th | Dir | Sites | strict | passthrough | catchall | strip | |---|---|---|---|---|---| -| `data/` | 173 | 104 | 2 | 0 | 67 | +| `data/` | 174 | 105 | 2 | 0 | 67 | ## `data/` — sites @@ -51,7 +51,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` | 8 | +| `hook.zod.ts` | 9 | | `mapping.zod.ts` | 8 | | `object.zod.ts` | 26 | | `picklist.zod.ts` | 3 | @@ -61,7 +61,7 @@ classify and is not listed (it becomes reportable the day it grows its first sit | `seed-loader.zod.ts` | 12 | | `seed.zod.ts` | 2 | | `validation.zod.ts` | 6 | -| **total** | **173** | +| **total** | **174** | ## `data/` — open @@ -69,7 +69,7 @@ Per file, how many of its sites still silently discard unknown keys. The `Class` column that decides the bucket split is hand-written in the ledger; the arithmetic over it is here. -**67 strip of 173**, in 11 file(s). +**67 strip of 174**, in 11 file(s). | File | Strip | Sites | |---|---|---| @@ -80,11 +80,11 @@ over it is here. | `external-catalog.zod.ts` | 4 | 4 | | `field.zod.ts` | 1 | 15 | | `filter.zod.ts` | 11 | 13 | -| `hook.zod.ts` | 5 | 8 | +| `hook.zod.ts` | 5 | 9 | | `query.zod.ts` | 3 | 5 | | `recycle-bin.zod.ts` | 4 | 4 | | `seed-loader.zod.ts` | 12 | 12 | -| **total** | **67** | **173** | +| **total** | **67** | **174** | | Bucket | Sites | |---|---| diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/system.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/system.md index 4aa342e606b..25a387f907f 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/system.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/system.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `system/` | 402 | +| `system/` | 403 | diff --git a/packages/runtime/src/app-artifact-handlers.ts b/packages/runtime/src/app-artifact-handlers.ts index 60c48287482..83fe05c7b37 100644 --- a/packages/runtime/src/app-artifact-handlers.ts +++ b/packages/runtime/src/app-artifact-handlers.ts @@ -434,7 +434,12 @@ export function bindAppArtifactHandlers( // the function a string `handler` names, is handed the // `ctx.title(field?)` a `body` gets in the sandbox. The binder // applies it after resolving the name, so both take this one wrap. - wrapHandler: (handler, hook) => withInProcessHookTitle(handler, ql, String(hook.name)), + // [#33214] …and its throws are answered against the hook's refusal + // catalogue, in the caller's language, with the body path's wire. + wrapHandler: (handler, hook) => withInProcessHookTitle(handler, ql, hook, { + i18n: options.i18n, + logger, + }), }); out.hooks += group.hooks.length; out.functions += Object.keys(group.functions).length; diff --git a/packages/runtime/src/sandbox/body-runner.ts b/packages/runtime/src/sandbox/body-runner.ts index cb46a4ea8f1..5788d0d2698 100644 --- a/packages/runtime/src/sandbox/body-runner.ts +++ b/packages/runtime/src/sandbox/body-runner.ts @@ -75,7 +75,12 @@ import { storedMetadataFamilyTableList, } from '../stored-metadata-body-boundary.js'; import { mapDataError } from '@objectstack/types'; -import { resolveHookRefusal, type HookRefusalI18nSource } from './hook-refusal-catalogue.js'; +import { + inProcessHostSurface, + resolveHookRefusal, + resolveInProcessHookRefusal, + type HookRefusalI18nSource, +} from './hook-refusal-catalogue.js'; import { isRelayedSandboxRefusal } from './quickjs-runner.js'; import { buildBodyDoors, callerScopeOf, type BodyDoorCaller } from './body-doors.js'; import { deriveHookApi, openTransactionKind, seedHookUnreadMembership, seedHookUserGrants } from '@objectstack/objectql'; @@ -364,21 +369,45 @@ function buildTitleSurface( export function withInProcessHookTitle( handler: (ctx: any) => unknown, ql: unknown, - hookName: string, + hook: string | Pick, + opts: InProcessHookOptions = {}, ): (ctx: any) => Promise { + const hookName = typeof hook === 'string' ? hook : String(hook.name); + // [#33214] Only a hook that declares a refusal catalogue is answered here; + // every other handler runs exactly as before. + const catalogued = typeof hook !== 'string' && hook.refusals !== undefined && hook.refusals !== null; return async function inProcessHookHandler(engineCtx: any): Promise { if (engineCtx === null || typeof engineCtx !== 'object') return handler(engineCtx); const surface = buildTitleSurface(engineCtx, ql, { kind: 'hook', name: hookName }); - const title = async (field?: unknown): Promise => + const readTitle = async (field?: unknown): Promise => (await surface(field === undefined || field === null ? undefined : String(field), undefined)) ?? null; + const title = catalogued ? inProcessHostSurface(readTitle) : readTitle; const view = new Proxy(engineCtx, { - get: (target, prop) => (prop === 'title' ? title : Reflect.get(target, prop)), + get: (target, prop) => { + if (prop === 'title') return title; + const value = Reflect.get(target, prop); + // [#33214] The host surfaces a handler calls: what they raise is the + // platform's, never the handler's refusal. + return catalogued && (prop === 'api' || prop === 'ql') ? inProcessHostSurface(value) : value; + }, has: (target, prop) => prop === 'title' || Reflect.has(target, prop), }); - return handler(view); + if (!catalogued) return handler(view); + try { + return await handler(view); + } catch (err: unknown) { + throw resolveInProcessHookRefusal(hook as Pick, err, engineCtx, opts); + } }; } +/** [#33214] What the in-process seam answers a hook's refusal catalogue with. */ +export interface InProcessHookOptions { + /** The `i18n` service a declared refusal is translated through, read at refusal time. */ + i18n?: HookRefusalI18nSource; + logger?: { warn?: (...args: any[]) => void }; +} + /** * The evaluation scope a formula title is computed in, derived from what the * hook context actually carries. diff --git a/packages/runtime/src/sandbox/hook-refusal-catalogue.ts b/packages/runtime/src/sandbox/hook-refusal-catalogue.ts index 636db3ffdd7..d1aaa08cfc8 100644 --- a/packages/runtime/src/sandbox/hook-refusal-catalogue.ts +++ b/packages/runtime/src/sandbox/hook-refusal-catalogue.ts @@ -38,14 +38,45 @@ * sandbox's own faults (budget, capability) all pass through as before: they * are the platform speaking, or a bug, never a refusal the body chose. * + * **Reasons and params (#33214, ruling 6879477573: S1 and params).** A code + * may hold further declared sentences under `reasons`; a throw that names a + * `reason` is answered with that sentence + * (`hooks..refusals..reasons..message`), the code's + * status and the code on the wire, unchanged. A reason the code does not + * declare is refused loudly, like an undeclared code. An entry that declares + * `params` is a template: its picked sentence (translated or declared) has its + * `{{ NAME }}` holes filled from the throw's `params` through the formula + * template engine — the engine the flow `end` refusal renders through + * (`renderTextSlot`, service-automation) — with only the declared names in + * scope. An entry with no `params` is plain text and nothing is filled. + * + * **Every path a hook runs on (#33214, ruling 6879477573 letter A).** A hook's + * code runs as a sandboxed `body` ({@link resolveHookRefusal}, called by the + * body runner) or as an in-process `handler` — an inline function on a source + * boot, or the function a string `handler` names when the build could not + * lower it ({@link resolveInProcessHookRefusal}, called by the in-process seam + * `withInProcessHookTitle`). Both answer one way and throw one error shape, so + * the wire is identical. In-process there is no VM bridge to mark what a host + * call raised, so the seam hands the handler host surfaces ({@link + * inProcessHostSurface}) that mark every error a host call raises; a marked + * error passes through unchanged, as a host-relayed error does on the body + * path. + * * A hook that declares no `refusals` is answered exactly as before. */ import type { Hook } from '@objectstack/spec/data'; -import { undeclaredHookRefusalAtRun } from '@objectstack/spec/data'; +import { undeclaredHookRefusalAtRun, undeclaredHookRefusalReasonAtRun } from '@objectstack/spec/data'; import { hookRefusalMessageKey, resolveBundleLocale } from '@objectstack/spec/system'; +import { templateEngine } from '@objectstack/formula'; import { sandboxBusinessMessage } from '@objectstack/types'; -import { SandboxError, isHostRelayedSandboxError, isRelayedSandboxRefusal } from './quickjs-runner.js'; +import { + SandboxError, + isHostRelayedSandboxError, + isRelayedSandboxRefusal, + sandboxRefusalAddressOf, + type SandboxRefusalAddress, +} from './quickjs-runner.js'; /** The status a declared refusal is answered with when its entry names none. */ export const DEFAULT_HOOK_REFUSAL_STATUS = 400; @@ -88,8 +119,15 @@ export function hookRefusalI18nReader(ctx: { getService(name: string): T }): interface DeclaredRefusal { message: string; status?: number; + /** [#33214] Further declared sentences under this code, by reason. */ + reasons?: Record; + /** [#33214] The names the entry's sentences may fill. */ + params?: string[]; } +/** [#33214] What a hook's throw named beside its code: a declared reason and the params its holes name. */ +export type HookRefusalAddress = SandboxRefusalAddress; + /** The hook's catalogue, or `undefined` when it declares none. */ function catalogueOf(hook: Pick): Record | undefined { const refusals = (hook as { refusals?: unknown }).refusals; @@ -113,14 +151,52 @@ function negotiatedLocale(service: HookRefusalI18nService, requested: string): s return resolveBundleLocale(offered, requested) ?? requested; } +/** + * [#33214] `template` with each `{{ NAME }}` hole filled from `params`, through + * the formula template engine the flow `end` refusal renders with + * (`renderTextSlot`, service-automation) — ⛔ never a second template engine. + * Only the entry's declared names are in scope: a value the throw passed under + * any other name is not read, and a declared name the throw did not pass + * renders nothing. A template the engine cannot render is served as written + * and the failure is logged: a refusal stays a refusal. + */ +export function fillHookRefusalParams( + hookName: string, + template: string, + declared: readonly string[], + params: Record | undefined, + logger?: { warn?: (...args: any[]) => void }, +): string { + const scope: Record = {}; + for (const name of declared) { + scope[name] = params && Object.prototype.hasOwnProperty.call(params, name) ? params[name] : undefined; + } + let result: { ok: boolean; value?: unknown; error?: { message?: string } }; + try { + result = templateEngine.evaluate({ dialect: 'template', source: template }, { extra: scope }) as typeof result; + } catch (err: unknown) { + result = { ok: false, error: { message: err instanceof Error ? err.message : String(err) } }; + } + if (result.ok) return String(result.value ?? ''); + logger?.warn?.( + `[BodyRunner] hook '${hookName}': its refusal sentence did not render (${result.error?.message ?? 'unknown'}), ` + + 'so it is served as written.', + ); + return template; +} + /** * The sentence a declared refusal is answered with: its translation in - * `locale` when the `i18n` service holds one, else the declared `message`. + * `locale` when the `i18n` service holds one, else the declared sentence — + * the entry's `message`, or, when the throw named a declared reason + * (#33214), that reason's `message` and key. An entry that declares `params` + * then has its holes filled from the throw's `params` + * ({@link fillHookRefusalParams}); one that declares none is plain text both + * ways, replaced whole. A service that throws, or a key it echoes back, picks + * nothing; a refusal stays a refusal whatever the service does. * - * Plain text both ways — an authored refusal has no parameter contract, so the - * translation replaces the message whole. A service that throws, or a key it - * echoes back, picks nothing; a refusal stays a refusal whatever the service - * does. + * The caller has already checked that `address.reason`, when present, is one + * the entry declares. */ export function declaredRefusalMessage( hookName: string, @@ -129,16 +205,34 @@ export function declaredRefusalMessage( locale: string | undefined, i18n: HookRefusalI18nSource | undefined, logger?: { warn?: (...args: any[]) => void }, + address?: HookRefusalAddress, ): string { - if (typeof locale !== 'string' || locale.length === 0 || !i18n) return entry.message; + const reason = address?.reason; + const declaredSentence = reason !== undefined && entry.reasons?.[reason] ? entry.reasons[reason]!.message : entry.message; + const picked = pickTranslatedSentence(hookName, 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; +} + +/** The translation of a declared sentence in `locale`, or the declared sentence itself. */ +function pickTranslatedSentence( + hookName: string, + code: string, + reason: string | undefined, + declared: string, + locale: string | undefined, + i18n: HookRefusalI18nSource | undefined, + logger?: { warn?: (...args: any[]) => void }, +): string { + if (typeof locale !== 'string' || locale.length === 0 || !i18n) return declared; let service: HookRefusalI18nService | undefined; try { service = i18n(); } catch { - return entry.message; + return declared; } - if (!service || typeof service.t !== 'function') return entry.message; - const key = hookRefusalMessageKey(hookName, code); + if (!service || typeof service.t !== 'function') return declared; + const key = hookRefusalMessageKey(hookName, code, reason); try { const translated = service.t(key, negotiatedLocale(service, locale)); // II18nService echoes the key back on a miss. @@ -149,7 +243,45 @@ export function declaredRefusalMessage( + `(${err instanceof Error ? err.message : String(err)}), so the refusal shows its declared message.`, ); } - return entry.message; + return declared; +} + +/** + * The error a declared code answers with, or the loud fault for a reason the + * code does not declare — shared by the body path and the in-process path so + * the two cannot answer differently. + */ +function answerDeclaredCode( + hook: Pick, + code: string, + entry: DeclaredRefusal, + address: HookRefusalAddress | undefined, + logMessage: string, + engineCtx: { session?: { locale?: unknown } } | undefined, + opts: { i18n?: HookRefusalI18nSource; logger?: { warn?: (...args: any[]) => void } }, +): SandboxError { + const reason = address?.reason; + if (reason !== undefined) { + const reasons = entry.reasons && typeof entry.reasons === 'object' ? entry.reasons : {}; + if (!Object.prototype.hasOwnProperty.call(reasons, reason)) { + return new SandboxError(undeclaredHookRefusalReasonAtRun(String(hook.name), code, reason, Object.keys(reasons))); + } + } + const locale = engineCtx?.session?.locale; + const message = declaredRefusalMessage( + String(hook.name), + code, + entry, + typeof locale === 'string' ? locale : undefined, + opts.i18n, + opts.logger, + address, + ); + return new SandboxError(logMessage, message, { + code, + status: typeof entry.status === 'number' ? entry.status : DEFAULT_HOOK_REFUSAL_STATUS, + userMessage: message, + }); } /** @@ -177,19 +309,199 @@ export function resolveHookRefusal( if (code === undefined || !entry) { return new SandboxError(undeclaredHookRefusalAtRun(String(hook.name), code, Object.keys(catalogue))); } + return answerDeclaredCode(hook, code, entry, sandboxRefusalAddressOf(err), err.message, engineCtx, opts); +} - const locale = engineCtx?.session?.locale; - const message = declaredRefusalMessage( - String(hook.name), +// ── The in-process half (#33214, ruling 6879477573 letter A) ───────────────── + +/** Errors a host call raised in-process: an engine refusal, a nested hook's refusal. */ +const inProcessHostRaised = new WeakSet(); + +/** Errors a handler's own callback threw INTO a host call (a `transaction` body), so its rejection is the handler's. */ +const inProcessHandlerRaised = new WeakSet(); + +/** A host surface's proxy → the object it fronts, so a host call never receives a proxy. */ +const surfaceTargets = new WeakMap(); + +/** An object or function → its host-surface proxy, so one host object has one proxy. */ +const surfaceProxies = new WeakMap(); + +/** Was this error raised by a host call an in-process handler made (marked by {@link inProcessHostSurface})? */ +export function isInProcessHostRaised(err: unknown): boolean { + return typeof err === 'object' && err !== null && inProcessHostRaised.has(err); +} + +function markHostRaised(err: unknown): void { + if (typeof err === 'object' && err !== null && !inProcessHandlerRaised.has(err)) inProcessHostRaised.add(err); +} + +function markHandlerRaised(err: unknown): void { + if (typeof err === 'object' && err !== null && !inProcessHostRaised.has(err)) inProcessHandlerRaised.add(err); +} + +/** The object a host-surface proxy fronts, or the value itself. */ +function unwrapSurface(value: unknown): unknown { + return (typeof value === 'object' || typeof value === 'function') && value !== null + ? (surfaceTargets.get(value) ?? value) + : value; +} + +/** A callback the handler hands a host call: what it throws is the handler's own, and what it is handed is a host surface. */ +function handlerCallback(fn: (...args: any[]) => unknown): (...args: any[]) => unknown { + return function handlerOwnedCallback(this: unknown, ...args: unknown[]): unknown { + let out: unknown; + try { + out = Reflect.apply(fn, this, args.map((a) => inProcessHostSurface(a))); + } catch (err) { + markHandlerRaised(err); + throw err; + } + if (out instanceof Promise) { + return out.then(undefined, (err: unknown) => { + markHandlerRaised(err); + throw err; + }); + } + return out; + }; +} + +/** Call a host function: every error it raises is marked, a callback argument is the handler's, a result a surface. */ +function callHost(fn: (...args: any[]) => unknown, thisArg: unknown, args: unknown[]): unknown { + const hostArgs = args.map((a) => (typeof a === 'function' && !surfaceTargets.has(a) ? handlerCallback(a as any) : unwrapSurface(a))); + let out: unknown; + try { + out = Reflect.apply(fn, thisArg, hostArgs); + } catch (err) { + markHostRaised(err); + throw err; + } + if (out instanceof Promise) { + return out.then(undefined, (err: unknown) => { + markHostRaised(err); + throw err; + }); + } + return inProcessHostSurface(out); +} + +/** + * `value` as a HOST SURFACE an in-process handler may call: every error a call + * through it raises — synchronously, or as the rejection of the promise it + * returns — is marked as host-raised ({@link isInProcessHostRaised}), so the + * refusal catalogue passes it through unchanged, as the body path passes a + * host-relayed error. An object a call returns is itself a surface (a + * repository from `ctx.api.object(…)`); a promise is left a native promise and + * only its rejection is marked; a plain value passes as is. + * + * What the handler hands back is the host's own again: a surface passed as an + * argument is unwrapped, so a host call never receives a proxy; and a function + * argument (a `transaction` callback) is the handler's — what it throws is + * the handler's own throw, never marked host-raised by the call it rejects. + * + * Methods are called on the object the surface fronts, never on the proxy, so + * a class's private state is read where it lives. + */ +export function inProcessHostSurface(value: T): T { + if ((typeof value !== 'object' && typeof value !== 'function') || value === null) return value; + if (value instanceof Promise || surfaceTargets.has(value as object)) return value; + const cached = surfaceProxies.get(value as object); + if (cached) return cached as T; + const target = value as object; + const proxy = new Proxy(target as any, { + get(t, prop) { + const v = Reflect.get(t, prop, t); + if (typeof v !== 'function' || prop === 'constructor') return v; + // A proxy must answer a frozen own property with its own value. + const own = Reflect.getOwnPropertyDescriptor(t, prop); + if (own && own.configurable === false && own.writable === false) return v; + if (prop === 'then') { + // A thenable host value: await reads its rejection through here. + return (onFulfilled?: (v: unknown) => unknown, onRejected?: (e: unknown) => unknown) => + Reflect.apply(v, t, [ + onFulfilled, + (err: unknown) => { + markHostRaised(err); + if (onRejected) return onRejected(err); + throw err; + }, + ]); + } + return (...args: unknown[]) => callHost(v as (...a: any[]) => unknown, t, args); + }, + apply(t, thisArg, args) { + return callHost(t as (...a: any[]) => unknown, unwrapSurface(thisArg), args); + }, + }); + surfaceProxies.set(target, proxy); + surfaceTargets.set(proxy, target); + return proxy as T; +} + +/** A native crash class: a bug, never a refusal the handler chose. */ +function isCrash(err: unknown): boolean { + return err instanceof TypeError || err instanceof ReferenceError || err instanceof RangeError + || err instanceof SyntaxError || err instanceof EvalError || err instanceof URIError; +} + +/** `err` flattened the way the VM flattens a body's throw, for the log-facing message. */ +function flattenThrown(err: unknown): string { + if (err instanceof Error) return `${err.name}: ${err.message}`; + if (typeof err === 'object' && err !== null && typeof (err as { message?: unknown }).message === 'string') { + return `Error: ${(err as { message: string }).message}`; + } + return String(err); +} + +/** + * [#33214] Answer an IN-PROCESS hook handler's throw against the hook's refusal + * catalogue — the in-process twin of {@link resolveHookRefusal}, called by the + * seam every in-process handler runs through (`withInProcessHookTitle`). + * Returns the error to throw in its place: `err` itself whenever the catalogue + * has nothing to say about it. + * + * - A declared code (and declared reason) is answered exactly as on the body + * path: the same `SandboxError` carrying the declared code, the declared + * status, and the picked sentence as its caller-facing message and + * `userMessage` — so every door builds the same envelope from it. + * - Any other throw the handler made — an undeclared code, an undeclared + * reason, no code at all — is refused loudly, as the same fault the body + * path raises. + * - Untouched: an error a host call raised ({@link isInProcessHostRaised}), a + * `SandboxError` (a nested body's, or the platform's), and a crash + * (`TypeError` and the other native classes). + */ +export function resolveInProcessHookRefusal( + hook: Pick, + err: unknown, + engineCtx: { session?: { locale?: unknown } } | undefined, + opts: { i18n?: HookRefusalI18nSource; logger?: { warn?: (...args: any[]) => void } } = {}, +): unknown { + const catalogue = catalogueOf(hook); + if (!catalogue) return err; + if (isInProcessHostRaised(err) || err instanceof SandboxError || isCrash(err)) return err; + const thrown = (typeof err === 'object' && err !== null ? err : {}) as { + code?: unknown; + reason?: unknown; + params?: unknown; + }; + 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; + if (code === undefined || !entry) { + return new SandboxError(undeclaredHookRefusalAtRun(String(hook.name), 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; + } + return answerDeclaredCode( + hook, code, entry, - typeof locale === 'string' ? locale : undefined, - opts.i18n, - opts.logger, + address, + `hook '${String(hook.name)}' threw: ${flattenThrown(err)}`, + engineCtx, + opts, ); - return new SandboxError(err.message, message, { - code, - status: typeof entry.status === 'number' ? entry.status : DEFAULT_HOOK_REFUSAL_STATUS, - userMessage: message, - }); } diff --git a/packages/runtime/src/sandbox/quickjs-runner.ts b/packages/runtime/src/sandbox/quickjs-runner.ts index 5354a1aa892..b85f2c860c6 100644 --- a/packages/runtime/src/sandbox/quickjs-runner.ts +++ b/packages/runtime/src/sandbox/quickjs-runner.ts @@ -366,8 +366,10 @@ export class QuickJSScriptRunner implements ScriptRunner { } catch (_) { flat = undefined; } globalThis.__error = (typeof flat === 'string' && flat !== '') ? flat : ${JSON.stringify(`Error: ${UNREADABLE_REJECTION_SENTENCE}`)}; try { + var __refusalParams; + try { __refusalParams = (e && e.params !== undefined) ? JSON.parse(JSON.stringify(e.params)) : undefined; } catch (_) { __refusalParams = undefined; } globalThis.__errorInfo = (e && (e.code || e.fields || e.status || e.userMessage || e['${SANDBOX_FAULT_PROP}'])) - ? JSON.stringify({ code: e.code, fields: e.fields, status: e.status, userMessage: e.userMessage, sandboxFault: e['${SANDBOX_FAULT_PROP}'] === true }) + ? JSON.stringify({ code: e.code, fields: e.fields, status: e.status, userMessage: e.userMessage, sandboxFault: e['${SANDBOX_FAULT_PROP}'] === true, reason: typeof e.reason === 'string' ? e.reason : undefined, params: __refusalParams }) : undefined; } catch (_) { globalThis.__errorInfo = undefined; } try { @@ -539,6 +541,10 @@ export class QuickJSScriptRunner implements ScriptRunner { // unchanged is remembered as such, so a hook's refusal catalogue // answers only the body's own throws (`isHostRelayedSandboxError`). if (readErrorFromHost(vm)) hostRelayedErrors.add(thrown); + // [#33214] …and the refusal address the body's throw named beside its + // code (`reason`, `params`), for a hook's refusal catalogue. + const address = readRefusalAddress(vm); + if (address !== undefined) refusalAddresses.set(thrown, address); throw thrown; } @@ -2294,6 +2300,52 @@ export function isHostRelayedSandboxError(err: unknown): boolean { return typeof err === 'object' && err !== null && hostRelayedErrors.has(err); } +/** + * [#33214] What a body's throw named beside its `code` for a hook's refusal + * catalogue: a `reason` (one of the code's declared sentences) and the + * `params` its holes name. Carried across the VM on the `__errorInfo` channel, + * and kept off {@link SandboxErrorInfo} and the error's own fields for the + * reason {@link relayedRefusals} gives: it is a fact about the hop, read only + * by `resolveHookRefusal`, and it never reaches the wire. + */ +export interface SandboxRefusalAddress { + reason?: string; + params?: Record; +} + +/** [#33214] The errors this runner built from a body throw that named a refusal address. */ +const refusalAddresses = new WeakMap(); + +/** [#33214] The refusal address a body's throw named ({@link SandboxRefusalAddress}), or `undefined`. */ +export function sandboxRefusalAddressOf(err: unknown): SandboxRefusalAddress | undefined { + return typeof err === 'object' && err !== null ? refusalAddresses.get(err) : undefined; +} + +/** [#33214] Read the `reason` / `params` the wrapper's reject handler wrote onto `__errorInfo`. */ +function readRefusalAddress(vm: QuickJSContext): SandboxRefusalAddress | undefined { + let raw: unknown; + try { + const h = vm.getProp(vm.global, '__errorInfo'); + raw = vm.dump(h); + h.dispose(); + } catch { + return undefined; + } + if (typeof raw !== 'string' || !raw) return undefined; + let parsed: { reason?: unknown; params?: unknown }; + try { + parsed = JSON.parse(raw); + } catch { + return undefined; + } + const address: SandboxRefusalAddress = {}; + if (typeof parsed?.reason === 'string' && parsed.reason.length > 0) address.reason = parsed.reason; + if (parsed?.params !== null && typeof parsed?.params === 'object' && !Array.isArray(parsed.params)) { + address.params = parsed.params as Record; + } + return address.reason !== undefined || address.params !== undefined ? address : undefined; +} + /** [#26170] Read the `__errorFromHost` channel the wrapper's reject handler writes. */ function readErrorFromHost(vm: QuickJSContext): boolean { try { diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 51365a7af95..4839bee4e5d 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -382,6 +382,8 @@ "HOOK_REFUSAL_CODE_PATTERN (const)", "HOOK_REFUSAL_MESSAGE_HOLE_REFUSED (const)", "HOOK_REFUSAL_MESSAGE_WITHOUT_HOLE (const)", + "HOOK_REFUSAL_PARAM_PATTERN (const)", + "HOOK_REFUSAL_REASON_PATTERN (const)", "Hook (type)", "HookApi (interface)", "HookBody (type)", @@ -403,6 +405,8 @@ "HookParsed (type)", "HookQuery (type)", "HookRefusal (type)", + "HookRefusalReason (type)", + "HookRefusalReasonSchema (const)", "HookRefusalSchema (const)", "HookSchema (const)", "HookUpdateDoc (type)", @@ -965,6 +969,7 @@ "hasNulInLikePattern (function)", "hookForm (const)", "hookRefusalCodesThrownIn (function)", + "hookRefusalReasonsThrownIn (function)", "hookRefusalsWithoutSandboxedBody (function)", "importMappingEntryTargets (function)", "indexImportMappingTargets (function)", @@ -1093,6 +1098,8 @@ "textOperatorDoorVerdict (function)", "undeclaredHookRefusalAtRun (function)", "undeclaredHookRefusalCodeAtSave (function)", + "undeclaredHookRefusalReasonAtRun (function)", + "undeclaredHookRefusalReasonAtSave (function)", "uniqueNullDistinctDivergence (function)", "unknownImportMappingTargets (function)", "unprovisionedInjectedColumns (function)", diff --git a/packages/spec/declaration-map/data.json b/packages/spec/declaration-map/data.json index ce5810ff0e2..6c2c691df9e 100644 --- a/packages/spec/declaration-map/data.json +++ b/packages/spec/declaration-map/data.json @@ -164,6 +164,8 @@ "HookContextSchema": "data/HookContext", "HookEvent": "data/HookEvent", "HookRefusal": "data/HookRefusal", + "HookRefusalReason": "data/HookRefusalReason", + "HookRefusalReasonSchema": "data/HookRefusalReason", "HookRefusalSchema": "data/HookRefusal", "HookSchema": "data/Hook", "ImportFieldMapping": "data/ImportFieldMapping", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 85a19d2ebc7..564dbc62fff 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -373,6 +373,8 @@ "HOOK_REFUSAL_CODE_PATTERN": "src/data/hook-refusal-codes.ts#HOOK_REFUSAL_CODE_PATTERN (const)", "HOOK_REFUSAL_MESSAGE_HOLE_REFUSED": "src/data/hook-refusal-codes.ts#HOOK_REFUSAL_MESSAGE_HOLE_REFUSED (const)", "HOOK_REFUSAL_MESSAGE_WITHOUT_HOLE": "src/data/hook-refusal-codes.ts#HOOK_REFUSAL_MESSAGE_WITHOUT_HOLE (const)", + "HOOK_REFUSAL_PARAM_PATTERN": "src/data/hook-refusal-codes.ts#HOOK_REFUSAL_PARAM_PATTERN (const)", + "HOOK_REFUSAL_REASON_PATTERN": "src/data/hook-refusal-codes.ts#HOOK_REFUSAL_REASON_PATTERN (const)", "Hook": "src/data/hook.zod.ts#Hook (type)", "HookApi": "src/data/hook-api.ts#HookApi (interface)", "HookBody": "src/data/hook-body.zod.ts#HookBody (type)", @@ -393,6 +395,8 @@ "HookParsed": "src/data/hook.zod.ts#HookParsed (type)", "HookQuery": "src/data/hook-api.ts#HookQuery (type)", "HookRefusal": "src/data/hook.zod.ts#HookRefusal (type)", + "HookRefusalReason": "src/data/hook.zod.ts#HookRefusalReason (type)", + "HookRefusalReasonSchema": "src/data/hook.zod.ts#HookRefusalReasonSchema (const)", "HookRefusalSchema": "src/data/hook.zod.ts#HookRefusalSchema (const)", "HookSchema": "src/data/hook.zod.ts#HookSchema (const)", "HookUpdateDoc": "src/data/hook-api.ts#HookUpdateDoc (type)", @@ -951,6 +955,7 @@ "hasNulInLikePattern": "src/data/filter.zod.ts#hasNulInLikePattern (function)", "hookForm": "src/data/hook.form.ts#hookForm (const)", "hookRefusalCodesThrownIn": "src/data/hook-refusal-codes.ts#hookRefusalCodesThrownIn (function)", + "hookRefusalReasonsThrownIn": "src/data/hook-refusal-codes.ts#hookRefusalReasonsThrownIn (function)", "hookRefusalsWithoutSandboxedBody": "src/data/hook-refusal-codes.ts#hookRefusalsWithoutSandboxedBody (function)", "importMappingEntryTargets": "src/data/import-mapping-target.ts#importMappingEntryTargets (function)", "indexImportMappingTargets": "src/data/import-mapping-target.ts#indexImportMappingTargets (function)", @@ -1079,6 +1084,8 @@ "textOperatorDoorVerdict": "src/data/filter-text-operator-declared-type.ts#textOperatorDoorVerdict (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)", + "undeclaredHookRefusalReasonAtSave": "src/data/hook-refusal-codes.ts#undeclaredHookRefusalReasonAtSave (function)", "uniqueNullDistinctDivergence": "src/data/unique-null-distinct-conformance.ts#uniqueNullDistinctDivergence (function)", "unknownImportMappingTargets": "src/data/import-mapping-target.ts#unknownImportMappingTargets (function)", "unprovisionedInjectedColumns": "src/data/injected-system-column-provenance.ts#unprovisionedInjectedColumns (function)", diff --git a/packages/spec/src/data/hook.zod.ts b/packages/spec/src/data/hook.zod.ts index 44ff52316fe..fe6e662aa99 100644 --- a/packages/spec/src/data/hook.zod.ts +++ b/packages/spec/src/data/hook.zod.ts @@ -336,9 +336,9 @@ function refuseUndeclaredLiteralRefusalCode( * 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. + * own message. Not exported: it is published as part of {@link HookRefusalSchema}. */ -export const HookRefusalReasonSchema = lazySchema(() => strictObject( +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.', @@ -361,8 +361,6 @@ export const HookRefusalReasonSchema = lazySchema(() => strictObject( }, )); -export type HookRefusalReason = z.input; - /** The slot a refusal message's `{{ }}` holes are judged in, as a sentence names it. */ const HOOK_REFUSAL_MESSAGE_SLOT = 'A hook refusal `message`'; From 5462b6034609e94d8790fe08456da3f704769353 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 15:40:58 +0000 Subject: [PATCH 04/22] wip(runtime): tests for reasons, params and the in-process seam (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- .../sandbox/hook-refusal-catalogue.test.ts | 234 +++++++++++++++++- packages/spec/authorable-surface/data.json | 1 - packages/spec/json-schema.manifest/data.json | 1 - 3 files changed, 233 insertions(+), 3 deletions(-) diff --git a/packages/runtime/src/sandbox/hook-refusal-catalogue.test.ts b/packages/runtime/src/sandbox/hook-refusal-catalogue.test.ts index d136707e5f1..19aadc3583e 100644 --- a/packages/runtime/src/sandbox/hook-refusal-catalogue.test.ts +++ b/packages/runtime/src/sandbox/hook-refusal-catalogue.test.ts @@ -12,13 +12,16 @@ import { describe, it, expect } from 'vitest'; import { mapDataError } from '@objectstack/types'; -import { hookBodyRunnerFactory } from './body-runner.js'; +import { hookBodyRunnerFactory, withInProcessHookTitle } from './body-runner.js'; import { QuickJSScriptRunner, SandboxError } from './quickjs-runner.js'; import { DEFAULT_HOOK_REFUSAL_STATUS, declaredRefusalMessage, hookRefusalI18nReader, + inProcessHostSurface, + isInProcessHostRaised, resolveHookRefusal, + resolveInProcessHookRefusal, type HookRefusalI18nService, } from './hook-refusal-catalogue.js'; @@ -231,3 +234,232 @@ describe('declaredRefusalMessage / hookRefusalI18nReader', () => { expect(resolveHookRefusal({ name: 'h', refusals: REFUSALS } as any, err, ctx())).toBe(err); }); }); + +// ── #33214 (ruling 6879477573: 问一 A, 问二 S1, 问三 是) ────────────────────── + +/** A catalogue with a code holding reasons and params. */ +const PLAN_REFUSALS = { + VALIDATION_FAILED: { + message: 'This plan cannot be submitted.', + params: ['state'], + reasons: { + plan_locked: { message: 'The plan is {{ state }} and can no longer change.' }, + second_primary: { message: 'This plant already has a primary.' }, + }, + }, + CREDIT_LIMIT: { message: 'Over the credit limit.' }, +}; + +const PLAN_ZH = { + 'hooks.plan_gate.refusals.VALIDATION_FAILED.reasons.plan_locked.message': '计划已{{ state }},不能再修改。', + 'hooks.plan_gate.refusals.CREDIT_LIMIT.message': '超出信用额度。', +}; + +function planI18n(): HookRefusalI18nService { + return { t: (key, locale) => (locale === 'zh-CN' ? (PLAN_ZH as Record)[key] ?? key : key), getLocales: () => ['en', 'zh-CN'] }; +} + +/** The plan hook, bound as a sandboxed body. */ +function planBody(source: string) { + return hookBodyRunnerFactory(runner, { ql: {}, appId: 'crm', i18n: () => planI18n() })({ + name: 'plan_gate', + object: 'plan', + events: ['beforeUpdate'], + body: { language: 'js', source, capabilities: [] }, + refusals: PLAN_REFUSALS, + } as any)!; +} + +/** The plan hook, bound as an in-process handler through the seam every in-process handler runs through. */ +function planHandler(handler: (ctx: any) => unknown, refusals: object | null = PLAN_REFUSALS) { + return withInProcessHookTitle(handler, {}, { name: 'plan_gate', refusals } as any, { i18n: () => planI18n() }); +} + +const planCtx = (locale?: string, api?: unknown) => ({ + object: 'plan', event: 'beforeUpdate', input: {}, session: locale ? { userId: 'u1', locale } : { userId: 'u1' }, + ...(api !== undefined ? { api } : {}), +}); + +describe('[#33214] a declared reason under a code — the body path', () => { + it('answers with the reason\'s sentence, the code\'s status and the code on the wire, unchanged', async () => { + const err = await rejectionOf(planBody( + "throw { code: 'VALIDATION_FAILED', reason: 'second_primary', message: 'internal' };", + )(planCtx())); + const wire = mapDataError(err, 'plan'); + expect(wire.status).toBe(400); + expect(wire.body.code).toBe('VALIDATION_FAILED'); + expect(wire.body.userMessage).toBe('This plant already has a primary.'); + expect(JSON.stringify(wire.body)).not.toContain('internal'); + expect(JSON.stringify(wire.body)).not.toContain('second_primary'); + }); + + it('a code thrown with no reason keeps the entry\'s own sentence', async () => { + const err = await rejectionOf(planBody("throw { code: 'VALIDATION_FAILED', message: 'x' };")(planCtx())); + expect(mapDataError(err, 'plan').body.userMessage).toBe('This plan cannot be submitted.'); + }); + + it('a reason the code does not declare is a 500 fault naming the hook, the code and the reason', async () => { + const err = await rejectionOf(planBody( + "const r = 'plan_' + 'lockd'; throw { code: 'VALIDATION_FAILED', reason: r, message: 'x' };", + )(planCtx())); + expect(err).toBeInstanceOf(SandboxError); + expect(err.innerMessage).toBeUndefined(); + expect(err.message).toContain("hook 'plan_gate' threw code 'VALIDATION_FAILED' with reason 'plan_lockd'"); + expect(mapDataError(err, 'plan').status).toBe(500); + }); + + it('a reason under a code that declares no reasons is the same fault', async () => { + const err = await rejectionOf(planBody( + "const r = 'x' + 'y'; throw { code: 'CREDIT_LIMIT', reason: r, message: 'x' };", + )(planCtx())); + expect(err.message).toContain("reason 'xy'"); + expect(mapDataError(err, 'plan').status).toBe(500); + }); +}); + +describe('[#33214] declared params fill the sentence\'s holes — the body path', () => { + it('fills a declared hole from the throw\'s params', async () => { + const err = await rejectionOf(planBody( + "throw { code: 'VALIDATION_FAILED', reason: 'plan_locked', params: { state: 'approved' }, message: 'x' };", + )(planCtx())); + const wire = mapDataError(err, 'plan'); + expect(wire.status).toBe(400); + expect(wire.body.code).toBe('VALIDATION_FAILED'); + expect(wire.body.userMessage).toBe('The plan is approved and can no longer change.'); + }); + + it('fills the translated template in the caller\'s locale', async () => { + const err = await rejectionOf(planBody( + "throw Object.assign(new Error('x'), { code: 'VALIDATION_FAILED', reason: 'plan_locked', params: { state: '已批准' } });", + )(planCtx('zh-CN'))); + expect(mapDataError(err, 'plan').body.userMessage).toBe('计划已已批准,不能再修改。'); + }); + + it('a declared param the throw did not pass renders nothing; an undeclared one is not read', async () => { + const err = await rejectionOf(planBody( + "throw { code: 'VALIDATION_FAILED', reason: 'plan_locked', params: { other: 'leak' }, message: 'x' };", + )(planCtx())); + const sentence = mapDataError(err, 'plan').body.userMessage; + expect(sentence).toBe('The plan is and can no longer change.'); + expect(sentence).not.toContain('leak'); + }); +}); + +describe('[#33214] a hook that uses none of the new parts answers byte-for-byte as before', () => { + // Measured on the base commit (e540baf887) with the same fixture: the wire a + // declared code answers with when the hook declares no reasons and no params. + const BEFORE = '{"status":400,"body":{"error":"This order exceeds the customer credit limit.","code":"VALIDATION_ERROR","declaredCode":"CREDIT_LIMIT","object":"order","userMessage":"This order exceeds the customer credit limit."}}'; + + it('the body path', async () => { + const err = await rejectionOf(boundHook(throwing('CREDIT_LIMIT'))(ctx())); + expect(JSON.stringify(mapDataError(err, 'order'))).toBe(BEFORE); + }); +}); + +describe('[#33214] the in-process seam answers the catalogue with the body path\'s wire', () => { + it('a declared code: the same envelope the sandboxed body answers with', async () => { + const viaBody = await rejectionOf(planBody("throw Object.assign(new Error('x'), { code: 'CREDIT_LIMIT' });")(planCtx('zh-CN'))); + const viaHandler = await rejectionOf(planHandler(async () => { + throw Object.assign(new Error('x'), { code: 'CREDIT_LIMIT' }); + })(planCtx('zh-CN'))); + expect(viaHandler).toBeInstanceOf(SandboxError); + expect(mapDataError(viaHandler, 'plan')).toEqual(mapDataError(viaBody, 'plan')); + expect(mapDataError(viaHandler, 'plan').body.userMessage).toBe('超出信用额度。'); + }); + + it('a declared reason with params, translated', async () => { + const err = await rejectionOf(planHandler(async () => { + throw Object.assign(new Error('x'), { code: 'VALIDATION_FAILED', reason: 'plan_locked', params: { state: '已批准' } }); + })(planCtx('zh-CN'))); + const wire = mapDataError(err, 'plan'); + expect(wire.status).toBe(400); + expect(wire.body.code).toBe('VALIDATION_FAILED'); + expect(wire.body.userMessage).toBe('计划已已批准,不能再修改。'); + }); + + it('a plain thrown object is read like an error', async () => { + const err = await rejectionOf(planHandler(async () => { + throw { code: 'VALIDATION_FAILED', reason: 'second_primary' }; + })(planCtx())); + expect(mapDataError(err, 'plan').body.userMessage).toBe('This plant already has a primary.'); + }); + + it('an undeclared code, an undeclared reason and a throw with no code are 500 faults', async () => { + const cases: Array<[() => never, string]> = [ + [() => { throw Object.assign(new Error('x'), { code: 'NOPE' }); }, "threw code 'NOPE'"], + [() => { throw Object.assign(new Error('x'), { code: 'VALIDATION_FAILED', reason: 'nope' }); }, "reason 'nope'"], + [() => { throw new Error('no code'); }, 'threw no `code`'], + ]; + for (const [thrower, text] of cases) { + const err = await rejectionOf(planHandler(async () => thrower())(planCtx())); + expect(err).toBeInstanceOf(SandboxError); + expect(err.innerMessage).toBeUndefined(); + expect(err.message).toContain(text); + expect(mapDataError(err, 'plan').status).toBe(500); + } + }); + + it('a crash passes through untouched', async () => { + const crash = new TypeError('x is undefined'); + const err = await rejectionOf(planHandler(async () => { throw crash; })(planCtx())); + expect(err).toBe(crash); + }); + + it('an error a ctx.api call raised passes through unchanged, though its code is undeclared', async () => { + const hostRefusal = Object.assign(new Error('Field `amount` is required.'), { code: 'VALIDATION_ERROR_X', status: 400 }); + const api = { object: () => ({ insert: async () => { throw hostRefusal; } }) }; + const err = await rejectionOf(planHandler(async (c: any) => { + await c.api.object('audit').insert({}); + })(planCtx(undefined, api))); + expect(err).toBe(hostRefusal); + expect(isInProcessHostRaised(hostRefusal)).toBe(true); + }); + + it('…and so does one a ctx.ql call raised', async () => { + const hostRefusal = Object.assign(new Error('engine'), { code: 'RECORD_NOT_FOUND' }); + const engineCtx = { ...planCtx(), ql: { getObject: () => { throw hostRefusal; } } }; + const err = await rejectionOf(planHandler(async (c: any) => { c.ql.getObject('x'); })(engineCtx)); + expect(err).toBe(hostRefusal); + }); + + it('the handler\'s own throw inside a transaction callback is its refusal; a host error inside it is not', async () => { + const hostRefusal = Object.assign(new Error('dup'), { code: 'DUPLICATE_X' }); + const tx = { insert: async () => { throw hostRefusal; } }; + const api = { transaction: async (fn: (t: unknown) => Promise) => fn(tx) }; + const own = await rejectionOf(planHandler(async (c: any) => { + await c.api.transaction(async () => { throw Object.assign(new Error('x'), { code: 'CREDIT_LIMIT' }); }); + })(planCtx(undefined, api))); + expect(mapDataError(own, 'plan').body.userMessage).toBe('Over the credit limit.'); + const relayed = await rejectionOf(planHandler(async (c: any) => { + await c.api.transaction(async (t: any) => { await t.insert({}); }); + })(planCtx(undefined, api))); + expect(relayed).toBe(hostRefusal); + }); + + it('a host surface hands the host its own objects back, never a proxy', () => { + const repo = { name: 'repo' }; + let received: unknown; + const api = inProcessHostSurface({ object: () => repo, use: (r: unknown) => { received = r; } }); + const surfaced = api.object(); + expect(surfaced).not.toBe(repo); + api.use(surfaced); + expect(received).toBe(repo); + }); + + it('a hook that declares no catalogue is untouched: the same error, the context\'s own api', async () => { + const thrown = Object.assign(new Error('Refused.'), { code: 'ANY_CODE', status: 422 }); + const api = { object: () => ({}) }; + let seenApi: unknown; + const err = await rejectionOf(planHandler(async (c: any) => { seenApi = c.api; throw thrown; }, null)(planCtx(undefined, api))); + expect(err).toBe(thrown); + expect(seenApi).toBe(api); + // The pre-#33214 call shape (a hook name) is unchanged too. + const byName = await rejectionOf(withInProcessHookTitle(async () => { throw thrown; }, {}, 'plan_gate')(planCtx())); + expect(byName).toBe(thrown); + }); + + it('resolveInProcessHookRefusal returns a SandboxError unchanged — a nested body\'s, or the platform\'s', () => { + const nested = new SandboxError("hook 'inner' threw: x", 'x', { code: 'ANY' }); + expect(resolveInProcessHookRefusal({ name: 'plan_gate', refusals: PLAN_REFUSALS } as any, nested, planCtx())).toBe(nested); + }); +}); diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index d83fb0408b2..97ab2741f32 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -491,7 +491,6 @@ "data/HookRefusal:params", "data/HookRefusal:reasons", "data/HookRefusal:status", - "data/HookRefusalReason:message", "data/ImportFieldMapping:params", "data/ImportFieldMapping:source", "data/ImportFieldMapping:target", diff --git a/packages/spec/json-schema.manifest/data.json b/packages/spec/json-schema.manifest/data.json index f67a85c53bd..32d125d021d 100644 --- a/packages/spec/json-schema.manifest/data.json +++ b/packages/spec/json-schema.manifest/data.json @@ -90,7 +90,6 @@ "data/HookContext", "data/HookEvent", "data/HookRefusal", - "data/HookRefusalReason", "data/ImportFieldMapping", "data/Index", "data/InlineGridColumn", From 2a1d95106e4cfbfa11aa28a879bee22bcc63a878 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 15:42:24 +0000 Subject: [PATCH 05/22] wip(lint): count and check hook refusal reasons (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- packages/lint/src/i18n-walk.ts | 21 +++++++-- .../src/validate-translation-references.ts | 46 +++++++++++++++---- 2 files changed, 53 insertions(+), 14 deletions(-) diff --git a/packages/lint/src/i18n-walk.ts b/packages/lint/src/i18n-walk.ts index 6aa83825ec9..e49b28b027f 100644 --- a/packages/lint/src/i18n-walk.ts +++ b/packages/lint/src/i18n-walk.ts @@ -138,6 +138,7 @@ * author; a group the ledger does warn on is left out of the walk * (see `authorWarnedTranslationGroups`) * hooks..refusals..message (#26170) + * hooks..refusals..reasons..message (#33214) * positions..label / .description * permissions..label / .description * books..label / .description @@ -2385,10 +2386,11 @@ function walkScreenFlows(config: any, out: ExpectedEntry[]): void { * catalogue declares (#26170, maintainer ruling 6431311681 letter A), seeded * with the declared message. * - * The sandboxed body runner reads exactly that key (`hookRefusalMessageKey`) - * in the caller's locale when the body throws the entry's code, so each - * declared entry is one demand, counted by the coverage gate under its own - * `hook` bucket. Keyed by hook name, not by the objects the hook binds, so a + * The hook runtime reads exactly that key (`hookRefusalMessageKey`) in the + * caller's locale when the hook throws the entry's code, so each declared + * entry is one demand, counted by the coverage gate under its own `hook` + * bucket — and so is each reason the entry declares (#33214), + * `hooks..refusals..reasons..message`. Keyed by hook name, not by the objects the hook binds, so a * hook bound to several objects or to `'*'` is asked for one translation per * code. A hook that declares no `refusals` has no key here: its throws carry * no address a bundle could reach. @@ -2402,6 +2404,17 @@ function walkHookRefusals(config: any, out: ExpectedEntry[]): void { if (!refusals || typeof refusals !== 'object' || Array.isArray(refusals)) continue; for (const [code, entry] of Object.entries(refusals)) { pushOptional(out, ['hooks', hookName, 'refusals', code, 'message'], inlineText(entry?.message), 'hook'); + // [#33214] Each declared reason under the code is one more demand. + const reasons = entry?.reasons; + if (!reasons || typeof reasons !== 'object' || Array.isArray(reasons)) continue; + for (const [reason, sentence] of Object.entries(reasons)) { + pushOptional( + out, + ['hooks', hookName, 'refusals', code, 'reasons', reason, 'message'], + inlineText(sentence?.message), + 'hook', + ); + } } } } diff --git a/packages/lint/src/validate-translation-references.ts b/packages/lint/src/validate-translation-references.ts index ac49a416c26..c59090318ce 100644 --- a/packages/lint/src/validate-translation-references.ts +++ b/packages/lint/src/validate-translation-references.ts @@ -548,7 +548,8 @@ interface Universe { * (`HookSchema.refusals`) declares — what a `hooks..refusals.` * key may name. Empty for a hook that declares no catalogue. */ - hooks: Map>; + /** [#26170] Each hook's declared refusal codes, and (#33214) each code's declared reasons. */ + hooks: Map>>; /** Object-less actions — the ones `globalActions.*` may name. */ globalActions: Map; /** Action name → owning object, so a misfiled `globalActions` key can say where it belongs. */ @@ -1657,17 +1658,23 @@ function buildUniverse(stack: AnyRec): Universe { // ── Hooks: the refusal codes `hooks..refusals.` may name (#26170) ── // - // The body runner reads `hooks..refusals..message` for a code the - // hook's catalogue declares, so the universe is each hook's declared codes. - // `hooks` carries disposition `concat` in `COMPOSE_KEY_DISPOSITIONS`, so a - // sibling package's hooks are read through the artifact carrier; the - // declaration this leg is JUDGING keeps the slot, the flows' decision. - const hooks = new Map>(); + // The hook runtime reads `hooks..refusals..message` for a code the + // hook's catalogue declares, and (#33214) `…..reasons..message` + // for a reason that code declares, so the universe is each hook's declared + // codes and each code's declared reasons. `hooks` carries disposition `concat` + // in `COMPOSE_KEY_DISPOSITIONS`, so a sibling package's hooks are read through + // the artifact carrier; the declaration this leg is JUDGING keeps the slot, + // the flows' decision. + const hooks = new Map>>(); const collectHookRecord = (hook: AnyRec, { ownDeclaration }: { ownDeclaration: boolean }) => { const hookName = strName(hook.name); if (!hookName) return; if (!ownDeclaration && hooks.has(hookName)) return; - hooks.set(hookName, new Set(Object.keys(asRecord(hook.refusals)))); + const codes = new Map>(); + for (const [code, entry] of Object.entries(asRecord(hook.refusals))) { + codes.set(code, new Set(Object.keys(asRecord(isRec(entry) ? entry.reasons : undefined)))); + } + hooks.set(hookName, codes); }; for (const hook of recordsOf(stack.hooks)) collectHookRecord(hook, { ownDeclaration: true }); for (const hook of artifactProvidedRecords(stack, 'hooks')) { @@ -2496,8 +2503,27 @@ export function validateTranslationReferences(stack: AnyRec): TranslationRefFind continue; } if (!isRec(rawHook)) continue; - for (const code of Object.keys(asRecord(rawHook.refusals))) { - if (declared.has(code)) continue; + for (const [code, rawRefusal] of Object.entries(asRecord(rawHook.refusals))) { + const reasons = declared.get(code); + if (reasons) { + // ── hooks..refusals..reasons. (#33214) ────── + for (const reason of Object.keys(asRecord(isRec(rawRefusal) ? rawRefusal.reasons : undefined))) { + if (reasons.has(reason)) continue; + orphan( + `${inLocale} · hook "${hookName}" · refusal "${code}" · reason "${reason}"`, + `${hookPath}.refusals.${code}.reasons.${reason}`, + reasons.size === 0 + ? `Translations are keyed to reason "${reason}" of refusal "${code}", but hook "${hookName}" ` + + `declares no \`reasons\` under that code, so nothing resolves this key.` + : `Translations are keyed to reason "${reason}", a reason refusal "${code}" of hook ` + + `"${hookName}" does not declare under \`reasons\`, so nothing resolves this key.` + + suggest(reason, reasons), + `Reason translations are keyed by a reason the code's \`reasons\` declares; declare it there, ` + + `or drop the key.`, + ); + } + continue; + } orphan( `${inLocale} · hook "${hookName}" · refusal "${code}"`, `${hookPath}.refusals.${code}`, From 34d34eb06cfa973bc7a281f41df81285fcbcd7aa Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 15:53:01 +0000 Subject: [PATCH 06/22] wip(lint,cli): reason translation targets and coverage pins (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- .../test/i18n-hook-refusal-coverage.test.ts | 64 +++++++++++++++++++ .../validate-translation-references.test.ts | 47 ++++++++++++++ .../src/validate-translation-references.ts | 2 +- 3 files changed, 112 insertions(+), 1 deletion(-) diff --git a/packages/cli/test/i18n-hook-refusal-coverage.test.ts b/packages/cli/test/i18n-hook-refusal-coverage.test.ts index 8c7430e46e6..d284397b985 100644 --- a/packages/cli/test/i18n-hook-refusal-coverage.test.ts +++ b/packages/cli/test/i18n-hook-refusal-coverage.test.ts @@ -117,3 +117,67 @@ describe('the skeleton `os i18n extract` writes (#26170)', () => { } }); }); + +// objectstack#33214 (ruling 6879477573, S1) — a declared reason under a code is +// one more key, `hooks..refusals..reasons..message`, +// harvested, demanded and scaffolded like the code's own message. + +const PRIMARY = 'This plant already has a primary.'; +const LOCKED = 'The plan is {{ state }} and can no longer change.'; + +const planGate = { + name: 'plan_gate', + object: 'plan', + events: ['beforeUpdate'], + handler: 'planGate', + refusals: { + VALIDATION_FAILED: { + message: 'This plan cannot be submitted.', + params: ['state'], + reasons: { plan_locked: { message: LOCKED }, second_primary: { message: PRIMARY } }, + }, + }, +}; + +describe('a declared reason is one more demand (#33214)', () => { + it('the walker emits one key per reason, keyed as the runtime reads it, seeded with its sentence', () => { + const entries = hookEntries({ hooks: [planGate] }); + expect(entries.map((e) => e.path.join('.'))).toEqual([ + hookRefusalMessageKey('plan_gate', 'VALIDATION_FAILED'), + hookRefusalMessageKey('plan_gate', 'VALIDATION_FAILED', 'plan_locked'), + hookRefusalMessageKey('plan_gate', 'VALIDATION_FAILED', 'second_primary'), + ]); + expect(entries[2]).toMatchObject({ sourceValue: PRIMARY, source: 'hook' }); + }); + + it('the coverage gate reports an untranslated reason, and goes quiet once it is translated', () => { + const tree = (refusals?: Record) => ({ + i18n: { defaultLocale: 'en', supportedLocales: ['en', 'zh-CN'] }, + hooks: [planGate], + translations: [{ 'zh-CN': refusals ? { hooks: { plan_gate: { refusals } } } : {} }], + }); + const zh = (config: any) => + computeI18nCoverage(config).issues.filter((i) => i.locale === 'zh-CN' && i.key.startsWith('hooks.')).map((i) => i.key).sort(); + expect(zh(tree())).toEqual([ + 'hooks.plan_gate.refusals.VALIDATION_FAILED.message', + 'hooks.plan_gate.refusals.VALIDATION_FAILED.reasons.plan_locked.message', + 'hooks.plan_gate.refusals.VALIDATION_FAILED.reasons.second_primary.message', + ]); + expect(zh(tree({ + VALIDATION_FAILED: { + message: '该计划不能提交。', + reasons: { plan_locked: { message: '计划已{{ state }},不能再修改。' }, second_primary: { message: '该工厂已有主工厂。' } }, + }, + }))).toEqual([]); + }); + + it('the skeleton writes each reason, and parses through the translation schema', () => { + const result = extractTranslations({ hooks: [planGate] }, { locales: ['en', 'zh-CN'] }); + expect((result.bundles.en as any).hooks.plan_gate.refusals.VALIDATION_FAILED.reasons).toEqual({ + plan_locked: { message: LOCKED }, + second_primary: { message: PRIMARY }, + }); + expect((result.bundles['zh-CN'] as any).hooks.plan_gate.refusals.VALIDATION_FAILED.reasons.plan_locked).toEqual({ message: '' }); + for (const bundle of Object.values(result.bundles)) expect(TranslationDataSchema.safeParse(bundle).success).toBe(true); + }); +}); diff --git a/packages/lint/src/validate-translation-references.test.ts b/packages/lint/src/validate-translation-references.test.ts index 040423dd6ff..adedbf952ae 100644 --- a/packages/lint/src/validate-translation-references.test.ts +++ b/packages/lint/src/validate-translation-references.test.ts @@ -4922,6 +4922,53 @@ describe('validateTranslationReferences — hook refusals (#26170)', () => { }); }); +describe('validateTranslationReferences — hook refusal reasons (#33214)', () => { + const planStack = { + hooks: [ + { + name: 'plan_gate', + object: 'plan', + events: ['beforeUpdate'], + handler: 'planGate', + refusals: { + VALIDATION_FAILED: { message: 'Cannot submit.', reasons: { plan_locked: { message: 'Locked.' } } }, + CREDIT_LIMIT: { message: 'Over.' }, + }, + }, + ], + }; + const bundle = (refusals: unknown) => ({ ...planStack, translations: [{ 'zh-CN': { hooks: { plan_gate: { refusals } } } }] }); + + it('reports nothing for a translation of a declared reason', () => { + expect(validateTranslationReferences(bundle({ + VALIDATION_FAILED: { message: '不能提交。', reasons: { plan_locked: { message: '已锁定。' } } }, + }))).toEqual([]); + }); + + it('refuses a reason the code does not declare, with the nearest declared reason offered', () => { + const findings = validateTranslationReferences(bundle({ VALIDATION_FAILED: { reasons: { plan_lockd: { message: 'x' } } } })); + expect(findings).toHaveLength(1); + expect(findings[0].rule).toBe(TRANSLATION_TARGET_UNKNOWN); + expect(findings[0].severity).toBe('error'); + expect(findings[0].path).toBe('translations[0]["zh-CN"].hooks.plan_gate.refusals.VALIDATION_FAILED.reasons.plan_lockd'); + expect(findings[0].message).toContain('a reason refusal "VALIDATION_FAILED" of hook "plan_gate" does not declare'); + expect(findings[0].message).toContain('Did you mean "plan_locked"?'); + }); + + it('refuses a reason key under a code that declares no reasons', () => { + const findings = validateTranslationReferences(bundle({ CREDIT_LIMIT: { reasons: { any: { message: 'x' } } } })); + expect(findings).toHaveLength(1); + expect(findings[0].path).toBe('translations[0]["zh-CN"].hooks.plan_gate.refusals.CREDIT_LIMIT.reasons.any'); + expect(findings[0].message).toContain('declares no `reasons` under that code'); + }); + + it('a reason under an undeclared code is reported once, at the code', () => { + const findings = validateTranslationReferences(bundle({ NOPE: { reasons: { any: { message: 'x' } } } })); + expect(findings).toHaveLength(1); + expect(findings[0].path).toBe('translations[0]["zh-CN"].hooks.plan_gate.refusals.NOPE'); + }); +}); + describe('validateTranslationReferences — doc books (#26690)', () => { const stack = (data: Record, extra: Record = {}) => ({ books: [{ diff --git a/packages/lint/src/validate-translation-references.ts b/packages/lint/src/validate-translation-references.ts index c59090318ce..6be4fdf6182 100644 --- a/packages/lint/src/validate-translation-references.ts +++ b/packages/lint/src/validate-translation-references.ts @@ -2532,7 +2532,7 @@ export function validateTranslationReferences(stack: AnyRec): TranslationRefFind `\`refusals\`, so nothing resolves this key.` : `Translations are keyed to refusal "${code}", a code hook "${hookName}" does not declare ` + `under \`refusals\`, so nothing resolves this key.` + - suggest(code, declared), + suggest(code, declared.keys()), `Refusal translations are keyed by a code the hook's \`refusals\` declares; declare it there, ` + `or drop the key.`, ); From 92ab7f59ab2fed5717e9de870921ca2e60f20009 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 16:00:59 +0000 Subject: [PATCH 07/22] test(verify): hook refusal catalogue parity on both bootStack doors (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- .../src/harness.hook-refusal-door.test.ts | 173 ++++++++++++++++++ 1 file changed, 173 insertions(+) create mode 100644 packages/verify/src/harness.hook-refusal-door.test.ts diff --git a/packages/verify/src/harness.hook-refusal-door.test.ts b/packages/verify/src/harness.hook-refusal-door.test.ts new file mode 100644 index 00000000000..fab3cdecbbf --- /dev/null +++ b/packages/verify/src/harness.hook-refusal-door.test.ts @@ -0,0 +1,173 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #33214 (ruling 6879477573, 问一 A) — a hook's declared refusal catalogue + * answers the same on both doors of `bootStack`, under `Accept-Language: + * zh-CN`: the source boot, where the hook's inline `handler` runs in-process + * (an app's own test harness), and the artifact door, where the `body` the + * build lowered it to runs in the sandbox, as `objectstack dev` serves it. + * + * Measured before (`origin/main` e540baf887): the configuration did not load at + * all — `defineStack` refused `refusals` on a hook with no `js` body — and once + * accepted, the in-process handler's throw would have reached the caller as the + * handler's own English error, never the catalogue. + * + * Pinned on each door, for one `beforeInsert` that refuses three ways: + * + * - a declared code with a translation: the zh-CN sentence and the code; + * - a declared reason under a registered code, with a declared param: the + * zh-CN reason sentence, its hole filled, the wire code unchanged; + * - the two doors' envelopes are byte-identical. + */ + +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; +import { defineStack } from '@objectstack/spec'; +import { bootStack, type VerifyStack } from './harness.js'; + +const BOOT_TIMEOUT = 120_000; + +const manifest = { id: 'com.example.hook-refusal-door', name: 'Hook Refusal Door', namespace: 'hrd', version: '1.0.0', type: 'app' }; + +const plan = { + name: 'hrd_plan', label: 'Plan', pluralLabel: 'Plans', sharingModel: 'public_read_write', + fields: { + name: { name: 'name', type: 'text', label: 'Name', required: true }, + state: { name: 'state', type: 'text', label: 'State' }, + }, +}; + +const refusals = { + CREDIT_LIMIT: { message: 'This plan exceeds the credit limit.' }, + VALIDATION_FAILED: { + message: 'This plan cannot be saved.', + params: ['state'], + reasons: { plan_locked: { message: 'The plan is {{ state }} and can no longer change.' } }, + }, +}; + +const translations = [ + { + 'zh-CN': { + hooks: { + hrd_plan_gate: { + refusals: { + CREDIT_LIMIT: { message: '该计划超出信用额度。' }, + VALIDATION_FAILED: { reasons: { plan_locked: { message: '计划处于{{ state }}状态,不能再修改。' } } }, + }, + }, + }, + }, + }, +]; + +/** One statement set, run in-process by the handler and in the sandbox by the body. */ +const SOURCE = [ + "if (ctx.input.state === 'over') throw Object.assign(new Error('internal'), { code: 'CREDIT_LIMIT' });", + "if (ctx.input.state === '锁定') throw Object.assign(new Error('internal'), { code: 'VALIDATION_FAILED', reason: 'plan_locked', params: { state: ctx.input.state } });", +].join('\n'); + +type GateCtx = { input: Record }; + +/** The configuration: the hook is an inline TypeScript handler, which a source boot runs in-process. */ +const app = (): Record => + defineStack({ + manifest, + objects: [plan], + hooks: [ + { + name: 'hrd_plan_gate', + object: 'hrd_plan', + events: ['beforeInsert'], + handler: async (ctx: GateCtx) => { + if (ctx.input.state === 'over') throw Object.assign(new Error('internal'), { code: 'CREDIT_LIMIT' }); + if (ctx.input.state === '锁定') { + throw Object.assign(new Error('internal'), { + code: 'VALIDATION_FAILED', + reason: 'plan_locked', + params: { state: ctx.input.state }, + }); + } + }, + refusals, + }, + ], + translations, + } as never) as unknown as Record; + +/** The artifact: the same app, its hook carrying the same statements as a `body`. */ +const artifact = (): Record => + JSON.parse( + JSON.stringify( + defineStack({ + manifest, + objects: [plan], + hooks: [ + { + name: 'hrd_plan_gate', + object: 'hrd_plan', + events: ['beforeInsert'], + body: { language: 'js', source: SOURCE, capabilities: [] }, + refusals, + }, + ], + translations, + } as never), + ), + ) as Record; + +let hostRoot: string; +beforeAll(() => { + hostRoot = mkdtempSync(join(tmpdir(), 'verify-hook-refusal-door-')); + mkdirSync(join(hostRoot, 'dist')); + writeFileSync(join(hostRoot, 'dist', 'objectstack.json'), JSON.stringify(artifact())); +}); +afterAll(() => { + if (hostRoot) rmSync(hostRoot, { recursive: true, force: true }); +}); + +const live: VerifyStack[] = []; +afterEach(async () => { + for (const stack of live.splice(0)) await stack.stop(); +}); + +/** The two refusals as a zh-CN caller reads them, over REST. */ +const refusalsOn = async (stack: VerifyStack): Promise> => { + live.push(stack); + const token = await stack.signIn(); + const insert = async (state: string) => { + const res = await stack.api('/data/hrd_plan', { + method: 'POST', + headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, 'Accept-Language': 'zh-CN' }, + body: JSON.stringify({ name: 'P1', state }), + }); + return { status: res.status, body: await res.json() }; + }; + return [await insert('over'), await insert('锁定')]; +}; + +describe('#33214: a hook\'s refusal catalogue answers the same on both bootStack doors, in zh-CN', () => { + let viaArtifact: Array<{ status: number; body: any }>; + + it('the artifact door: the body, in the sandbox, as `objectstack dev` serves it', async () => { + viaArtifact = await refusalsOn(await bootStack(app(), { hostRoot, artifact: 'dist/objectstack.json' })); + const [over, locked] = viaArtifact; + expect(over.status).toBe(400); + expect(over.body.code).toBe('VALIDATION_ERROR'); + expect(over.body.declaredCode).toBe('CREDIT_LIMIT'); + expect(over.body.userMessage).toBe('该计划超出信用额度。'); + expect(locked.status).toBe(400); + expect(locked.body.code).toBe('VALIDATION_FAILED'); + expect(locked.body.userMessage).toBe('计划处于锁定状态,不能再修改。'); + expect(JSON.stringify(viaArtifact)).not.toContain('internal'); + }, BOOT_TIMEOUT); + + it('the source door: the inline handler, in-process, answers byte-for-byte the same', async () => { + const viaSource = await refusalsOn(await bootStack(app(), { hostRoot })); + expect(viaSource[0].body.userMessage).toBe('该计划超出信用额度。'); + expect(viaSource[1].body.code).toBe('VALIDATION_FAILED'); + expect(JSON.stringify(viaSource)).toBe(JSON.stringify(viaArtifact)); + }, BOOT_TIMEOUT); +}); From 21b1092a13909fd2fd578641f1d9e7d4f29d3068 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 16:08:06 +0000 Subject: [PATCH 08/22] chore(spec): liveness rows for hook refusal reasons and params (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- packages/spec/liveness/hook.json | 28 +++++++++++++++++-- packages/spec/liveness/state-counts/hook.md | 2 +- .../spec/liveness/state-counts/translation.md | 2 +- packages/spec/liveness/translation.json | 16 +++++++++++ 4 files changed, 44 insertions(+), 4 deletions(-) diff --git a/packages/spec/liveness/hook.json b/packages/spec/liveness/hook.json index 9a9e8609d9d..e8d071b1a14 100644 --- a/packages/spec/liveness/hook.json +++ b/packages/spec/liveness/hook.json @@ -88,7 +88,7 @@ "status": "live", "verifiedAt": "2026-10-27", "evidenceScope": "in-repo", - "evidence": "packages/runtime/src/sandbox/hook-refusal-catalogue.ts#resolveHookRefusal (the one reader: a sandboxed body's throw of a declared code is answered with that entry, and any other deliberate throw of a hook that declares `refusals` is refused as a fault naming the hook and the code); packages/runtime/src/sandbox/body-runner.ts#hookBodyRunnerFactory (hands every body throw of the hook to `resolveHookRefusal` before it leaves the handler)", + "evidence": "packages/runtime/src/sandbox/hook-refusal-catalogue.ts#resolveHookRefusal (the one reader: a sandboxed body's throw of a declared code is answered with that entry, and any other deliberate throw of a hook that declares `refusals` is refused as a fault naming the hook and the code); packages/runtime/src/sandbox/body-runner.ts#hookBodyRunnerFactory (hands every body throw of the hook to `resolveHookRefusal` before it leaves the handler); packages/runtime/src/sandbox/hook-refusal-catalogue.ts#resolveInProcessHookRefusal (#33214: the in-process twin, for an inline `handler` on a source boot and the function a string `handler` names); packages/runtime/src/sandbox/body-runner.ts#withInProcessHookTitle (the one in-process seam that hands every in-process handler's throw to it)", "producer": "packages/objectql/src/hook-binder.ts#bindHooksToEngine (hands the AUTHORED hook to the body runner factory, `refusals` included); packages/spec/src/data/hook.zod.ts#HookSchema (refuses at save a code the body throws literally and the catalogue does not declare)", "children": { "message": { @@ -102,9 +102,33 @@ "verifiedAt": "2026-10-27", "evidenceScope": "in-repo", "evidence": "packages/runtime/src/sandbox/hook-refusal-catalogue.ts#resolveHookRefusal (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-14", + "evidenceScope": "in-repo", + "evidence": "packages/runtime/src/sandbox/hook-refusal-catalogue.ts#answerDeclaredCode (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 hook, the code and the reason); packages/runtime/src/sandbox/hook-refusal-catalogue.ts#declaredRefusalMessage (picks the reason's sentence and its key, `hooks..refusals..reasons..message`); packages/runtime/src/sandbox/quickjs-runner.ts#readRefusalAddress (carries the body's `reason` across the VM)", + "producer": "packages/spec/src/data/hook.zod.ts#refuseUndeclaredLiteralRefusalCode (refuses at save a reason the hook's source throws literally and the code does not declare)", + "note": "[#33214, ruling 6879477573 S1] Seeded `live` with its reader in one change (Prime Directive 10): the key, the runtime that answers it on both paths, the translation group and the coverage count.", + "children": { + "message": { + "status": "live", + "verifiedAt": "2026-11-14", + "evidenceScope": "in-repo", + "evidence": "packages/runtime/src/sandbox/hook-refusal-catalogue.ts#declaredRefusalMessage (the reason's sentence the refusal is answered with, translated through `hooks..refusals..reasons..message`, else as declared)" + } + } + }, + "params": { + "status": "live", + "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)", + "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`)." } }, - "note": "[#26170, maintainer ruling 6431311681 letter A] Seeded `live` together with its reader: the key, the body runner that answers it, the translation group and the coverage count land in one change (Prime Directive 10). Read on the sandboxed `body` path only, so the schema refuses `refusals` on a hook with no `js` body (an in-process `handler`, an expression body): a catalogue nothing would answer is never saved. An error a host call raised and the body let through unchanged, a nested hook's refusal, a crash and a sandbox fault pass through untouched. DRILLED to the entry's two keys: the entry face is closed (`.strict()`)." + "note": "[#26170, maintainer ruling 6431311681 letter A] Seeded `live` together with its reader: the key, the body runner that answers it, the translation group and the coverage count land in one change (Prime Directive 10). [#33214, ruling 6879477573 letter A] Read on every path a hook runs on: the sandboxed `body` and the in-process `handler` seam, so the schema refuses `refusals` only on a hook whose code cannot throw a code (an expression body, or neither a body nor a handler). An error a host call raised and the body let through unchanged, a nested hook's refusal, a crash and a sandbox fault pass through untouched. DRILLED to the entry's four keys: the entry face is closed (`.strict()`)." }, "label": { "status": "live", diff --git a/packages/spec/liveness/state-counts/hook.md b/packages/spec/liveness/state-counts/hook.md index 63586507ed5..884217259e9 100644 --- a/packages/spec/liveness/state-counts/hook.md +++ b/packages/spec/liveness/state-counts/hook.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `hook` | 23 | 0 | 0 | 1 | 0 | 24 | +| `hook` | 25 | 0 | 0 | 1 | 0 | 26 | diff --git a/packages/spec/liveness/state-counts/translation.md b/packages/spec/liveness/state-counts/translation.md index 69c65159418..03c986d6b07 100644 --- a/packages/spec/liveness/state-counts/translation.md +++ b/packages/spec/liveness/state-counts/translation.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `translation` | 43 | 0 | 0 | 0 | 2 | 45 | +| `translation` | 44 | 0 | 0 | 0 | 2 | 46 | diff --git a/packages/spec/liveness/translation.json b/packages/spec/liveness/translation.json index 51070423a3e..be20ea086f1 100644 --- a/packages/spec/liveness/translation.json +++ b/packages/spec/liveness/translation.json @@ -260,6 +260,22 @@ "evidenceScope": "in-repo", "evidence": "packages/runtime/src/sandbox/hook-refusal-catalogue.ts#declaredRefusalMessage (reads `hooks..refusals..message` through the `i18n` service, spelled by `hookRefusalMessageKey`, in the caller's `HookContext.session.locale` negotiated by `resolveBundleLocale`; a miss echoes the key and the declared message is served); packages/runtime/src/sandbox/hook-refusal-catalogue.ts#resolveHookRefusal (serves the picked sentence as the refusal's caller-facing message and `userMessage`)", "producer": "packages/runtime/src/app-plugin.ts#loadTranslations (hands each bundle's locale data to the i18n service whole, `hooks` included); packages/objectql/src/engine-execution-plumbing.ts#buildSession (copies the write's `ExecutionContext.locale` onto the hook session the body runner reads)" + }, + "reasons": { + "status": "live", + "verifiedAt": "2026-11-14", + "evidenceScope": "in-repo", + "evidence": "packages/runtime/src/sandbox/hook-refusal-catalogue.ts#pickTranslatedSentence (reads `hooks..refusals..reasons..message` through the `i18n` service, spelled by `hookRefusalMessageKey`, in the caller's locale; a miss echoes the key and the declared reason sentence is served)", + "producer": "packages/runtime/src/app-plugin.ts#loadTranslations (hands each bundle's locale data to the i18n service whole, `hooks` included)", + "note": "[#33214, ruling 6879477573 S1] Seeded `live` with its reader. `objectstack validate` refuses a key over a reason the code does not declare; the i18n walk counts each declared reason.", + "children": { + "message": { + "status": "live", + "verifiedAt": "2026-11-14", + "evidenceScope": "in-repo", + "evidence": "packages/runtime/src/sandbox/hook-refusal-catalogue.ts#pickTranslatedSentence (reads `hooks..refusals..reasons..message` through the `i18n` service in the caller's locale)" + } + } } } } From 8f3978a133fb66a805d478f40508ac93531c7a63 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 16:11:43 +0000 Subject: [PATCH 09/22] chore(spec): regenerate api surface, export origins, declaration map and reference docs (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- content/docs/references/data/hook.mdx | 17 +++-------------- content/docs/references/index.mdx | 10 +++++----- packages/spec/api-surface/data.json | 2 -- packages/spec/declaration-map/data.json | 2 -- packages/spec/export-origins/data.json | 2 -- 5 files changed, 8 insertions(+), 25 deletions(-) diff --git a/content/docs/references/data/hook.mdx b/content/docs/references/data/hook.mdx index 0b9aeac3a8e..764f06db33a 100644 --- a/content/docs/references/data/hook.mdx +++ b/content/docs/references/data/hook.mdx @@ -1,7 +1,7 @@ --- title: Hook schema — Data Protocol property reference navTitle: Hook -description: "Hook schemas of the ObjectStack Data Protocol: Hook, HookContext, HookEvent and 2 more — each property with its type, default and a TypeScript example." +description: "Hook schemas of the ObjectStack Data Protocol: Hook, HookContext, HookEvent, HookRefusal — 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: "Hook schemas of the ObjectStack Data Protocol: Hook, HookContext, ## TypeScript Usage ```typescript -import { HookSchema, HookContextSchema, HookEvent, HookRefusalSchema, HookRefusalReasonSchema } from '@objectstack/spec/data'; -import type { Hook, HookContext, HookRefusal, HookRefusalReason } from '@objectstack/spec/data'; +import { HookSchema, HookContextSchema, HookEvent, HookRefusalSchema } from '@objectstack/spec/data'; +import type { Hook, HookContext, HookRefusal } from '@objectstack/spec/data'; // Validate data const result = HookSchema.parse(data); @@ -198,14 +198,3 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities --- -## HookRefusalReason - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **message** | `string` | ✅ | 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; a `{{ }}` hole names one of the entry's params | - - ---- - diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 4ad300e5580..7161e90a222 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 — 1662 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1661 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/. */} @@ -23,7 +23,7 @@ counts are sums of the rows they head. Regenerate with | [AI Protocol](/docs/references/ai) | 14 | 81 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | | [API Protocol](/docs/references/api) | 36 | 492 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 81 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | -| [Data Protocol](/docs/references/data) | 35 | 187 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | +| [Data Protocol](/docs/references/data) | 35 | 186 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | | [Identity Protocol](/docs/references/identity) | 5 | 27 | Users and accounts, organizations, positions, SCIM provisioning. | | [Integration Protocol](/docs/references/integration) | 1 | 23 | The single connector protocol (ADR-0097) — catalog descriptors and provider-bound instances. | | [Kernel Protocol](/docs/references/kernel) | 30 | 153 | Plugin lifecycle and manifests, capabilities and security, metadata loading, service registry. | @@ -34,7 +34,7 @@ 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 | 176 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **218** | **1662** | 14 protocol modules | +| **Total** | **218** | **1661** | 14 protocol modules | --- @@ -139,7 +139,7 @@ Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execu ## Data Protocol -**Source:** `packages/spec/src/data/` · **Import:** `@objectstack/spec/data` · **35 pages, 187 schemas** +**Source:** `packages/spec/src/data/` · **Import:** `@objectstack/spec/data` · **35 pages, 186 schemas** Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. @@ -168,7 +168,7 @@ Objects, fields, queries, filters, datasources and drivers — the ObjectQL laye | [`field.zod.ts`](/docs/references/data/field) | `CurrencyConfig`, `Field`, `FieldMaskingKeep`, `FieldMaskingRule`, `FieldType`, `InlineGridColumn`, `LocationCoordinates`, `SelectOption`, `UniqueScope` | | [`field-value.zod.ts`](/docs/references/data/field-value) | `Address`, `AddressValue`, `CalendarDateValue`, `ClockTimeValue`, `FileLikeValue`, `FileReferenceIdValue`, `FileRefusedValue`, `FileValue`, `InstantValue`, `LocationValue`, `ReferenceIdValue`, `ReferenceNameOnlyValue` | | [`filter.zod.ts`](/docs/references/data/filter) | `ComparisonOperator`, `EqualityOperator`, `FieldOperators`, `FieldReference`, `FilterArray`, `FilterCondition`, `NormalizedFilter`, `NowAnchor`, `QueryFilter`, `RangeOperator`, `SetOperator`, `SpecialOperator`, `StringOperator` | -| [`hook.zod.ts`](/docs/references/data/hook) | `Hook`, `HookContext`, `HookEvent`, `HookRefusal`, `HookRefusalReason` | +| [`hook.zod.ts`](/docs/references/data/hook) | `Hook`, `HookContext`, `HookEvent`, `HookRefusal` | | [`hook-body.zod.ts`](/docs/references/data/hook-body) | `ExpressionBody`, `HookBody`, `HookBodyCapability`, `ScriptBody` | | [`hook-body-doors.zod.ts`](/docs/references/data/hook-body-doors) | `BodyActivityAppendInput`, `BodyDoorRecordRef`, `BodyMailSendInput` | | [`mapping.zod.ts`](/docs/references/data/mapping) | `ImportFieldMapping`, `Mapping`, `TransformType` | diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 4839bee4e5d..d40252718fa 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -405,8 +405,6 @@ "HookParsed (type)", "HookQuery (type)", "HookRefusal (type)", - "HookRefusalReason (type)", - "HookRefusalReasonSchema (const)", "HookRefusalSchema (const)", "HookSchema (const)", "HookUpdateDoc (type)", diff --git a/packages/spec/declaration-map/data.json b/packages/spec/declaration-map/data.json index 6c2c691df9e..ce5810ff0e2 100644 --- a/packages/spec/declaration-map/data.json +++ b/packages/spec/declaration-map/data.json @@ -164,8 +164,6 @@ "HookContextSchema": "data/HookContext", "HookEvent": "data/HookEvent", "HookRefusal": "data/HookRefusal", - "HookRefusalReason": "data/HookRefusalReason", - "HookRefusalReasonSchema": "data/HookRefusalReason", "HookRefusalSchema": "data/HookRefusal", "HookSchema": "data/Hook", "ImportFieldMapping": "data/ImportFieldMapping", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 564dbc62fff..aedcc92d461 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -395,8 +395,6 @@ "HookParsed": "src/data/hook.zod.ts#HookParsed (type)", "HookQuery": "src/data/hook-api.ts#HookQuery (type)", "HookRefusal": "src/data/hook.zod.ts#HookRefusal (type)", - "HookRefusalReason": "src/data/hook.zod.ts#HookRefusalReason (type)", - "HookRefusalReasonSchema": "src/data/hook.zod.ts#HookRefusalReasonSchema (const)", "HookRefusalSchema": "src/data/hook.zod.ts#HookRefusalSchema (const)", "HookSchema": "src/data/hook.zod.ts#HookSchema (const)", "HookUpdateDoc": "src/data/hook-api.ts#HookUpdateDoc (type)", From ffdc490956b6c0122e90aa20ffe5102632d3432c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 16:12:21 +0000 Subject: [PATCH 10/22] test(cli): a lowered handler hook keeps its refusal catalogue (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- packages/cli/test/lower-callables.test.ts | 33 +++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/packages/cli/test/lower-callables.test.ts b/packages/cli/test/lower-callables.test.ts index c2b0065ff84..3650492ac6b 100644 --- a/packages/cli/test/lower-callables.test.ts +++ b/packages/cli/test/lower-callables.test.ts @@ -466,3 +466,36 @@ describe('[#22839] lowerCallables — bodylessCallables, one row per callable no function moduleHelper(s: string): string { return String(s).toLowerCase().replace(/\s+/g, '-'); } + +// objectstack#33214 (ruling 6879477573, 问一 A): a hook authored as an inline +// TypeScript handler may declare `refusals`; the build lowers it to a `js` body +// and the catalogue rides along, judged on the lowered body. +describe('[#33214] lowerCallables — a handler hook\'s refusal catalogue', () => { + const refusals = { + VALIDATION_FAILED: { message: 'Cannot submit.', params: ['state'], reasons: { plan_locked: { message: 'Locked: {{ state }}.' } } }, + }; + + it('keeps `refusals` beside the lowered body, and the lowered hook parses', async () => { + const { HookSchema } = await import('@objectstack/spec/data'); + const handler = async (ctx: any) => { + if (ctx.input.locked) throw { code: 'VALIDATION_FAILED', reason: 'plan_locked', params: { state: ctx.input.state } }; + }; + const out = lowerCallables({ hooks: [{ name: 'plan_gate', object: 'plan', events: ['beforeUpdate'], handler, refusals }] }); + const hook = (out.lowered.hooks as any[])[0]; + expect(hook.body?.language).toBe('js'); + expect(hook.body.source).toContain("reason: \"plan_locked\"".replace(/"/g, hook.body.source.includes("'plan_locked'") ? "'" : '"')); + expect(hook.refusals).toEqual(refusals); + expect(HookSchema.safeParse(hook).success).toBe(true); + }); + + it('a literal reason the code does not declare is refused on the lowered body, at `body.source`', async () => { + const { HookSchema } = await import('@objectstack/spec/data'); + const handler = async () => { + throw { code: 'VALIDATION_FAILED', reason: 'plan_lockd' }; + }; + const out = lowerCallables({ hooks: [{ name: 'plan_gate', object: 'plan', events: ['beforeUpdate'], handler, refusals }] }); + const r = HookSchema.safeParse((out.lowered.hooks as any[])[0]); + expect(r.success).toBe(false); + expect(r.error!.issues.find((i) => i.path.join('.') === 'body.source')?.message).toContain("reason 'plan_lockd'"); + }); +}); From ef84ba71d6889a83c554a4c0b129cd2c32f4cc1c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 16:12:39 +0000 Subject: [PATCH 11/22] test(cli): read the lowered reason literal with one pattern (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- packages/cli/test/lower-callables.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/cli/test/lower-callables.test.ts b/packages/cli/test/lower-callables.test.ts index 3650492ac6b..8970122d578 100644 --- a/packages/cli/test/lower-callables.test.ts +++ b/packages/cli/test/lower-callables.test.ts @@ -483,7 +483,7 @@ describe('[#33214] lowerCallables — a handler hook\'s refusal catalogue', () = const out = lowerCallables({ hooks: [{ name: 'plan_gate', object: 'plan', events: ['beforeUpdate'], handler, refusals }] }); const hook = (out.lowered.hooks as any[])[0]; expect(hook.body?.language).toBe('js'); - expect(hook.body.source).toContain("reason: \"plan_locked\"".replace(/"/g, hook.body.source.includes("'plan_locked'") ? "'" : '"')); + expect(hook.body.source).toMatch(/reason:\s*['"]plan_locked['"]/); expect(hook.refusals).toEqual(refusals); expect(HookSchema.safeParse(hook).success).toBe(true); }); From 51b46e82e007935973c2ff9699be239f28c1b5bf Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 16:13:45 +0000 Subject: [PATCH 12/22] docs(hooks,i18n): declared refusals on handler hooks, reasons and params; changeset (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- .changeset/33214-handler-hook-refusals.md | 21 ++++++ content/docs/automation/hooks.mdx | 67 +++++++++++++++++++ .../docs/protocol/kernel/i18n-standard.mdx | 1 + content/docs/ui/translations.mdx | 2 +- 4 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 .changeset/33214-handler-hook-refusals.md diff --git a/.changeset/33214-handler-hook-refusals.md b/.changeset/33214-handler-hook-refusals.md new file mode 100644 index 00000000000..04a3755e58c --- /dev/null +++ b/.changeset/33214-handler-hook-refusals.md @@ -0,0 +1,21 @@ +--- +'@objectstack/spec': minor +'@objectstack/runtime': minor +'@objectstack/lint': minor +--- + +feat(spec,runtime): a hook written as a TypeScript `handler` can declare `refusals`, and a refusal code can hold several declared sentences with parameters + +Clause-②: yes +Metadata-protocol: added +Skills-docs: follow-up owed — skills/objectstack-data/references/data-hooks.md (the "Declared refusals (`refusals`)" section teaches a sandboxed `body` only, one sentence per code, no params), skills/objectstack-i18n/SKILL.md (the `hooks..refusals..message` row has no `reasons` key) + +A hook's refusal catalogue (`HookSchema.refusals`) is answered on every path the hook runs on, and an entry can hold more than one sentence (maintainer ruling 6879477573: letter A, S1, params; inside ruling 6431311681 letter A). + +- **A `handler` hook may declare `refusals`.** `defineStack`, `os validate`, `os build` and the metadata save door used to refuse `refusals` on a hook with no `js` body. They now accept it on a hook whose `handler` is an inline function or a string reference. An undeclared code that the handler's source throws literally is refused at save, at `handler`. The catalogue is answered on every path: the body `os build` lowers the handler to (as before), and the in-process handler of a source boot (`bootStack(config)`, `os serve` over a host config), plus the function a string `handler` names when the build could not lower it. Both answer with the same envelope. An error a `ctx.api` or `ctx.ql` call raised, which the handler lets through unchanged, passes through as it does on the body path. Still refused: `refusals` on a hook whose code cannot throw a code (an `expression` body, or neither a body nor a handler). +- **`reasons`: several sentences under one wire code.** `refusals.CODE.reasons.REASON.message`, with a snake_case reason. The hook throws `{ code, reason }`. The caller reads the reason's sentence, with the code and the status of its entry, so the wire code and the envelope are unchanged. A reason the code does not declare is refused loudly: at save where the hook's source throws it literally, otherwise at run time as a `500` naming the hook, the code and the reason. Translated through `hooks.HOOK.refusals.CODE.reasons.REASON.message`. `os i18n extract` and `os i18n check` count each declared reason, and `os validate` refuses a translation key over a reason the code does not declare (`translation-target-unknown`). +- **`params`: names a sentence may fill.** An entry declares `params: ['state']`, and its sentences (its `message` and each reason) may write a double-brace hole over those names. The hook throws `params: { state }`. The runtime fills the holes after it picks the translation, through the formula template engine the flow `end` refusal renders with, and only declared names are in scope. A hole over an undeclared name is refused at save. An entry with no `params` stays plain text and every hole in it is refused, as before. The rule is now a refinement (`dropped-refinements.baseline.json` gains `data/HookRefusal`), so the published JSON Schema no longer carries the hole pattern on `message`. + +Unchanged: a hook that declares none of the new parts answers byte-for-byte as before (pinned against the base commit's output), and a hook that declares no `refusals` is untouched on both paths. + +New exports in `@objectstack/spec/data`: `HOOK_REFUSAL_REASON_PATTERN`, `HOOK_REFUSAL_PARAM_PATTERN`, `hookRefusalReasonsThrownIn`, `undeclaredHookRefusalReasonAtSave`, `undeclaredHookRefusalReasonAtRun`. `hookRefusalMessageKey(hook, code, reason?)` takes an optional reason. diff --git a/content/docs/automation/hooks.mdx b/content/docs/automation/hooks.mdx index 2498dcacd71..3fc6a6147dd 100644 --- a/content/docs/automation/hooks.mdx +++ b/content/docs/automation/hooks.mdx @@ -327,6 +327,73 @@ would move a handler's own `ctx.api` writes *outside* the transaction the write ran in, which is a worse guarantee than the one documented here. +## Refusing in the user's language — `refusals` + +A hook that says "no" to a write throws. A sentence written into the throw +reaches every caller in the language you wrote it in. To refuse in the +caller's language, **declare the refusals** on the hook and throw a declared +code. The runtime answers with the declared sentence, translated in the +caller's locale, and with the declared status: + +```typescript +export const planGate = { + name: 'plan_gate', + object: 'production_plan', + events: ['beforeUpdate'], + refusals: { + CREDIT_LIMIT: { message: 'This plan exceeds the credit limit.', status: 409 }, + VALIDATION_FAILED: { + message: 'This plan cannot be submitted.', + params: ['state'], + reasons: { + plan_locked: { message: 'The plan is {{ state }} and can no longer change.' }, + second_primary: { message: 'This plant already has a primary plan.' }, + }, + }, + }, + handler: async (ctx) => { + if (ctx.previous?.locked) { + throw Object.assign(new Error('locked'), { + code: 'VALIDATION_FAILED', + reason: 'plan_locked', + params: { state: ctx.previous.state }, + }); + } + }, +}; +``` + +- **The code is the key.** Each entry of `refusals` is keyed by the + SCREAMING_SNAKE code the hook throws, and the caller's envelope carries that + code. An entry has a `message` and, optionally, a 4xx `status` (400 when + absent). +- **`reasons` — several sentences under one code.** A gate with several + refusals of the same class keeps one wire code and declares one snake_case + reason per sentence. Throw `{ code, reason }`. The caller reads the reason's + sentence, with the code and the status of the entry it sits under. +- **`params` — names a sentence may fill.** An entry that declares `params` + may write `{{ name }}` holes over those names, in its own `message` and in + each reason. Throw the values as `params: { name: value }`. A hole over any + other name is refused when the hook is saved. An entry that declares no + `params` is plain text, and every `{{ }}` hole in it is refused. +- **It works whichever way the hook is written.** A TypeScript `handler` (run + in-process on a source boot such as `bootStack(config)`, and lowered to a + `js` body by `os build`) and a sandboxed `js` body answer the same envelope. +- **Loud on a mistake.** A code, or a reason, the catalogue does not declare is + refused when the hook is saved if the hook names it literally in a `throw`. + Otherwise it is refused when the hook runs, as a `500` that names the hook + and the code. A throw with no code is refused the same way. An error a + `ctx.api` call raised and the hook let through unchanged, and a crash, pass + through as they always did. +- **Translated by key.** Each sentence has a key the translation bundle + writes, `hooks..refusals..message` and + `hooks..refusals..reasons..message`; `os i18n extract` + scaffolds them and `os i18n check` counts them. A translation keeps the + entry's `{{ }}` holes. See [Translations](/docs/ui/translations). + +A hook that declares no `refusals` refuses exactly as before: the thrown +error's own `code`, `status` and message reach the caller. + ## Hook Context `handler` receives a `HookContext` with these fields: diff --git a/content/docs/protocol/kernel/i18n-standard.mdx b/content/docs/protocol/kernel/i18n-standard.mdx index 2cf41593f66..27b3bb77c93 100644 --- a/content/docs/protocol/kernel/i18n-standard.mdx +++ b/content/docs/protocol/kernel/i18n-standard.mdx @@ -1165,6 +1165,7 @@ beneath an action entry are judged the same way under either. | `reports.{name}` | a report's `name`, declared | | `hooks.{hook}` | a hook's `name`, declared | | `hooks.{hook}.refusals.{code}` | a code that hook's `refusals` declares | +| `hooks.{hook}.refusals.{code}.reasons.{reason}` | a reason that code declares under `reasons` | | `flows.{flow}.screens.{node}` | the `id` of a `type: 'screen'` node in that flow, nodes nested in loop, parallel and try/catch regions included | | `flows.{flow}.screens.{node}.fields.{field}` | a `config.fields[].name` on that screen — an object-form screen (`config.objectName`) declares none, and its input labels live under `objects.{objectName}.fields` | diff --git a/content/docs/ui/translations.mdx b/content/docs/ui/translations.mdx index 07b48a1d177..33656b4c512 100644 --- a/content/docs/ui/translations.mdx +++ b/content/docs/ui/translations.mdx @@ -90,7 +90,7 @@ export default defineStack({ | Page tab labels (`page:tabs` items) | `pages..components..items..label` — keyed by the tabs component's `id` and the item's `value`; an item without a `value` has no key (localize it with an inline locale map), and `page:accordion` panels have none | | A page `object-form`'s thank-you panel | `pages..components..submitBehavior.title` / `.message` — keyed by the `object-form` component's `id` (a form without an `id` has no key), by the same rules as a form view's panel | | Screen-flow wizards (flow label, screen headings and body text, screen field copy) | `flows..label` / `flows..screens..title` / `.description` / `.fields..label` / `.placeholder` / `.inlineHelpText` — a screen field's help text is `inlineHelpText`, the key the field itself declares, not `help`; see the boundary note below | -| Hook refusal messages | `hooks..refusals..message` — one per entry of the hook's `refusals` catalogue. A sandboxed hook body refuses by code, and the server answers the refusal with this message in the caller's locale, else the declared `message` | +| 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 | | 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 | From ec27b08b4b1d0095a5b1d87ee3de690cdfcb94b7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 16:44:39 +0000 Subject: [PATCH 13/22] refactor(spec,runtime): build the refusal answer's code from a local, not a helper parameter (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- .../src/sandbox/hook-refusal-catalogue.ts | 42 +++++++++---------- packages/spec/liveness/hook.json | 2 +- packages/spec/src/data/hook-refusal-codes.ts | 24 +++++------ 3 files changed, 32 insertions(+), 36 deletions(-) diff --git a/packages/runtime/src/sandbox/hook-refusal-catalogue.ts b/packages/runtime/src/sandbox/hook-refusal-catalogue.ts index d1aaa08cfc8..acc2c306ef0 100644 --- a/packages/runtime/src/sandbox/hook-refusal-catalogue.ts +++ b/packages/runtime/src/sandbox/hook-refusal-catalogue.ts @@ -247,41 +247,37 @@ function pickTranslatedSentence( } /** - * The error a declared code answers with, or the loud fault for a reason the - * code does not declare — shared by the body path and the in-process path so - * the two cannot answer differently. + * What a declared code answers with — the picked sentence and the status — or + * the loud fault for a reason the code does not declare. Shared by the body + * path and the in-process path so the two cannot answer differently; each + * builds its `SandboxError` from it with the code it read. */ -function answerDeclaredCode( +function declaredAnswer( hook: Pick, - code: string, + thrownCode: string, entry: DeclaredRefusal, address: HookRefusalAddress | undefined, - logMessage: string, engineCtx: { session?: { locale?: unknown } } | undefined, opts: { i18n?: HookRefusalI18nSource; logger?: { warn?: (...args: any[]) => void } }, -): SandboxError { +): { fault: SandboxError } | { message: string; status: number } { const reason = address?.reason; if (reason !== undefined) { const reasons = entry.reasons && typeof entry.reasons === 'object' ? entry.reasons : {}; if (!Object.prototype.hasOwnProperty.call(reasons, reason)) { - return new SandboxError(undeclaredHookRefusalReasonAtRun(String(hook.name), code, reason, Object.keys(reasons))); + return { fault: new SandboxError(undeclaredHookRefusalReasonAtRun(String(hook.name), thrownCode, reason, Object.keys(reasons))) }; } } const locale = engineCtx?.session?.locale; const message = declaredRefusalMessage( String(hook.name), - code, + thrownCode, entry, typeof locale === 'string' ? locale : undefined, opts.i18n, opts.logger, address, ); - return new SandboxError(logMessage, message, { - code, - status: typeof entry.status === 'number' ? entry.status : DEFAULT_HOOK_REFUSAL_STATUS, - userMessage: message, - }); + return { message, status: typeof entry.status === 'number' ? entry.status : DEFAULT_HOOK_REFUSAL_STATUS }; } /** @@ -309,7 +305,9 @@ export function resolveHookRefusal( if (code === undefined || !entry) { return new SandboxError(undeclaredHookRefusalAtRun(String(hook.name), code, Object.keys(catalogue))); } - return answerDeclaredCode(hook, code, entry, sandboxRefusalAddressOf(err), err.message, engineCtx, opts); + const answer = declaredAnswer(hook, code, entry, sandboxRefusalAddressOf(err), engineCtx, opts); + if ('fault' in answer) return answer.fault; + return new SandboxError(err.message, answer.message, { code, status: answer.status, userMessage: answer.message }); } // ── The in-process half (#33214, ruling 6879477573 letter A) ───────────────── @@ -495,13 +493,11 @@ export function resolveInProcessHookRefusal( if (thrown.params !== null && typeof thrown.params === 'object' && !Array.isArray(thrown.params)) { address.params = thrown.params as Record; } - return answerDeclaredCode( - hook, + const answer = declaredAnswer(hook, code, entry, address, engineCtx, opts); + if ('fault' in answer) return answer.fault; + return new SandboxError(`hook '${String(hook.name)}' threw: ${flattenThrown(err)}`, answer.message, { code, - entry, - address, - `hook '${String(hook.name)}' threw: ${flattenThrown(err)}`, - engineCtx, - opts, - ); + status: answer.status, + userMessage: answer.message, + }); } diff --git a/packages/spec/liveness/hook.json b/packages/spec/liveness/hook.json index e8d071b1a14..72b799dd1df 100644 --- a/packages/spec/liveness/hook.json +++ b/packages/spec/liveness/hook.json @@ -107,7 +107,7 @@ "status": "live", "verifiedAt": "2026-11-14", "evidenceScope": "in-repo", - "evidence": "packages/runtime/src/sandbox/hook-refusal-catalogue.ts#answerDeclaredCode (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 hook, the code and the reason); packages/runtime/src/sandbox/hook-refusal-catalogue.ts#declaredRefusalMessage (picks the reason's sentence and its key, `hooks..refusals..reasons..message`); packages/runtime/src/sandbox/quickjs-runner.ts#readRefusalAddress (carries the body's `reason` across the VM)", + "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 hook, the code and the reason); packages/runtime/src/sandbox/hook-refusal-catalogue.ts#declaredRefusalMessage (picks the reason's sentence and its key, `hooks..refusals..reasons..message`); packages/runtime/src/sandbox/quickjs-runner.ts#readRefusalAddress (carries the body's `reason` across the VM)", "producer": "packages/spec/src/data/hook.zod.ts#refuseUndeclaredLiteralRefusalCode (refuses at save a reason the hook's source throws literally and the code does not declare)", "note": "[#33214, ruling 6879477573 S1] Seeded `live` with its reader in one change (Prime Directive 10): the key, the runtime that answers it on both paths, the translation group and the coverage count.", "children": { diff --git a/packages/spec/src/data/hook-refusal-codes.ts b/packages/spec/src/data/hook-refusal-codes.ts index ed176cf0106..4e12876c3a5 100644 --- a/packages/spec/src/data/hook-refusal-codes.ts +++ b/packages/spec/src/data/hook-refusal-codes.ts @@ -210,21 +210,14 @@ export function hookRefusalCodesThrownIn(source: string): string[] { * is left to the run-time refusal. */ export function hookRefusalReasonsThrownIn(source: string): Array<{ code: string; reason: string }> { - const pairs: Array<{ code: string; reason: string }> = []; - const seen = new Set(); - const add = (code: string, reason: string) => { - const key = `${code}.${reason}`; - if (seen.has(key)) return; - seen.add(key); - pairs.push({ code, reason }); - }; + const found: Array<[string, string]> = []; const thrownNames = new Set(); const masked = maskedSource(source); for (const statement of throwStatements(masked)) { const codes = new Set([...statement.matchAll(CODE_PROPERTY)].map((m) => m.groups!.code)); if (codes.size === 1) { - const [code] = codes; - for (const m of statement.matchAll(REASON_PROPERTY)) add(code!, m.groups!.reason); + const [only] = codes; + for (const m of statement.matchAll(REASON_PROPERTY)) found.push([only!, m.groups!.reason]); } const binding = thrownBinding(statement); if (binding) thrownNames.add(binding); @@ -234,8 +227,15 @@ export function hookRefusalReasonsThrownIn(source: string): Array<{ code: string if (thrownNames.has(m.groups!.binding)) codeOf.set(m.groups!.binding, m.groups!.code); } for (const m of masked.matchAll(REASON_ASSIGNMENT)) { - const code = codeOf.get(m.groups!.binding); - if (code !== undefined) add(code, m.groups!.reason); + const bound = codeOf.get(m.groups!.binding); + if (bound !== undefined) found.push([bound, m.groups!.reason]); + } + const pairs: Array<{ code: string; reason: string }> = []; + const seen = new Set(); + for (const [code, reason] of found) { + if (seen.has(`${code}.${reason}`)) continue; + seen.add(`${code}.${reason}`); + pairs.push({ code, reason }); } return pairs; } From 990d46107b21b108634ede1a647f5950a9cba4d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 17:00:04 +0000 Subject: [PATCH 14/22] test(cli,verify): pay the module loads at collection (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- packages/cli/test/lower-callables.test.ts | 7 +++---- packages/verify/src/harness.hook-refusal-door.test.ts | 3 +++ 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/cli/test/lower-callables.test.ts b/packages/cli/test/lower-callables.test.ts index 8970122d578..58fdcbde352 100644 --- a/packages/cli/test/lower-callables.test.ts +++ b/packages/cli/test/lower-callables.test.ts @@ -1,6 +1,7 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. import { describe, it, expect } from 'vitest'; +import { HookSchema } from '@objectstack/spec/data'; import { AUTHORED_BODY_BESIDE_FUNCTION_REASON, FUNCTIONS_ENTRY_NO_BODY_REASON, @@ -475,8 +476,7 @@ describe('[#33214] lowerCallables — a handler hook\'s refusal catalogue', () = VALIDATION_FAILED: { message: 'Cannot submit.', params: ['state'], reasons: { plan_locked: { message: 'Locked: {{ state }}.' } } }, }; - it('keeps `refusals` beside the lowered body, and the lowered hook parses', async () => { - const { HookSchema } = await import('@objectstack/spec/data'); + it('keeps `refusals` beside the lowered body, and the lowered hook parses', () => { const handler = async (ctx: any) => { if (ctx.input.locked) throw { code: 'VALIDATION_FAILED', reason: 'plan_locked', params: { state: ctx.input.state } }; }; @@ -488,8 +488,7 @@ describe('[#33214] lowerCallables — a handler hook\'s refusal catalogue', () = expect(HookSchema.safeParse(hook).success).toBe(true); }); - it('a literal reason the code does not declare is refused on the lowered body, at `body.source`', async () => { - const { HookSchema } = await import('@objectstack/spec/data'); + it('a literal reason the code does not declare is refused on the lowered body, at `body.source`', () => { const handler = async () => { throw { code: 'VALIDATION_FAILED', reason: 'plan_lockd' }; }; diff --git a/packages/verify/src/harness.hook-refusal-door.test.ts b/packages/verify/src/harness.hook-refusal-door.test.ts index fab3cdecbbf..f24a1c40aaa 100644 --- a/packages/verify/src/harness.hook-refusal-door.test.ts +++ b/packages/verify/src/harness.hook-refusal-door.test.ts @@ -26,6 +26,9 @@ import { join } from 'node:path'; import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; import { defineStack } from '@objectstack/spec'; import { bootStack, type VerifyStack } from './harness.js'; +// The boot's dynamic loads, paid at collection rather than inside a clocked case. +import '@objectstack/service-datasource'; +import '@objectstack/service-automation'; const BOOT_TIMEOUT = 120_000; From 68aca57b50c7f86b229f4a3aff2588398b8dd678 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 17:21:29 +0000 Subject: [PATCH 15/22] test(spec): declare the hook form's refusal reasons/params gap; ledger header totals (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- packages/spec/dropped-refinements.baseline.json | 4 ++-- .../system/metadata-form-zod-reconciliation.test.ts | 13 +++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/packages/spec/dropped-refinements.baseline.json b/packages/spec/dropped-refinements.baseline.json index c32ec7acdcc..fd5aae4e073 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": 264, - "droppedRefinementSites": 1063, + "publishedSchemasWithDroppedRefinements": 265, + "droppedRefinementSites": 1069, "refinementSitesThatDidProject": 728, "refinementSitesWithNoJsonFormToCompare": 0 }, 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 5c1868dca5d..35f979507fa 100644 --- a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts +++ b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts @@ -191,6 +191,19 @@ type OmitEntry = { kind: 'omit'; type: string; path: string; key: string; why: s type SubsetEntry = { kind: 'subset'; type: string; path: string; why: string }; const LEDGER: ReadonlyArray = [ + // #33214 (ruling 6879477573, S1 and params) — a hook refusal's further + // sentences under one code and the names its holes fill. The hook form lays + // out a refusal as message + status, which is all a Studio-authored hook + // needs to refuse by code; `reasons` and `params` are authored in code + // beside the throw that names them. Offering them in the form is a Studio + // change of its own (a record nested in a key-only record, and a name list). + ...(['reasons', 'params'] as const).map((key): OmitEntry => ({ + kind: 'omit', + type: 'hook', + path: 'refusals', + key, + why: "authored in code beside the throw that names it — a `reason` or a `params` value is spelled in the hook's throw, which a Studio-authored body writes in the same code; the form lays out a refusal as message + status, and offering a nested reasons record and a params list is a Studio change of its own", + })), { kind: 'omit', type: 'page', From 7bb349830803b0d09613b47a9e4679fff9af50f9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 04:09:37 +0000 Subject: [PATCH 16/22] chore(spec): regenerate api-surface and export-origins after merging main (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- packages/spec/api-surface/data.json | 5 +++++ packages/spec/export-origins/data.json | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 3dd6a05f3f6..e37466bad16 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -382,6 +382,8 @@ "HOOK_REFUSAL_CODE_PATTERN (const)", "HOOK_REFUSAL_MESSAGE_HOLE_REFUSED (const)", "HOOK_REFUSAL_MESSAGE_WITHOUT_HOLE (const)", + "HOOK_REFUSAL_PARAM_PATTERN (const)", + "HOOK_REFUSAL_REASON_PATTERN (const)", "Hook (type)", "HookApi (interface)", "HookBody (type)", @@ -966,6 +968,7 @@ "hasNulInLikePattern (function)", "hookForm (const)", "hookRefusalCodesThrownIn (function)", + "hookRefusalReasonsThrownIn (function)", "hookRefusalsWithoutSandboxedBody (function)", "importMappingEntryTargets (function)", "indexImportMappingTargets (function)", @@ -1094,6 +1097,8 @@ "textOperatorDoorVerdict (function)", "undeclaredHookRefusalAtRun (function)", "undeclaredHookRefusalCodeAtSave (function)", + "undeclaredHookRefusalReasonAtRun (function)", + "undeclaredHookRefusalReasonAtSave (function)", "uniqueNullDistinctDivergence (function)", "unknownImportMappingTargets (function)", "unprovisionedInjectedColumns (function)", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 24f322456c9..0527624bbd1 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -373,6 +373,8 @@ "HOOK_REFUSAL_CODE_PATTERN": "src/data/hook-refusal-codes.ts#HOOK_REFUSAL_CODE_PATTERN (const)", "HOOK_REFUSAL_MESSAGE_HOLE_REFUSED": "src/data/hook-refusal-codes.ts#HOOK_REFUSAL_MESSAGE_HOLE_REFUSED (const)", "HOOK_REFUSAL_MESSAGE_WITHOUT_HOLE": "src/data/hook-refusal-codes.ts#HOOK_REFUSAL_MESSAGE_WITHOUT_HOLE (const)", + "HOOK_REFUSAL_PARAM_PATTERN": "src/data/hook-refusal-codes.ts#HOOK_REFUSAL_PARAM_PATTERN (const)", + "HOOK_REFUSAL_REASON_PATTERN": "src/data/hook-refusal-codes.ts#HOOK_REFUSAL_REASON_PATTERN (const)", "Hook": "src/data/hook.zod.ts#Hook (type)", "HookApi": "src/data/hook-api.ts#HookApi (interface)", "HookBody": "src/data/hook-body.zod.ts#HookBody (type)", @@ -952,6 +954,7 @@ "hasNulInLikePattern": "src/data/filter.zod.ts#hasNulInLikePattern (function)", "hookForm": "src/data/hook.form.ts#hookForm (const)", "hookRefusalCodesThrownIn": "src/data/hook-refusal-codes.ts#hookRefusalCodesThrownIn (function)", + "hookRefusalReasonsThrownIn": "src/data/hook-refusal-codes.ts#hookRefusalReasonsThrownIn (function)", "hookRefusalsWithoutSandboxedBody": "src/data/hook-refusal-codes.ts#hookRefusalsWithoutSandboxedBody (function)", "importMappingEntryTargets": "src/data/import-mapping-target.ts#importMappingEntryTargets (function)", "indexImportMappingTargets": "src/data/import-mapping-target.ts#indexImportMappingTargets (function)", @@ -1080,6 +1083,8 @@ "textOperatorDoorVerdict": "src/data/filter-text-operator-declared-type.ts#textOperatorDoorVerdict (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)", + "undeclaredHookRefusalReasonAtSave": "src/data/hook-refusal-codes.ts#undeclaredHookRefusalReasonAtSave (function)", "uniqueNullDistinctDivergence": "src/data/unique-null-distinct-conformance.ts#uniqueNullDistinctDivergence (function)", "unknownImportMappingTargets": "src/data/import-mapping-target.ts#unknownImportMappingTargets (function)", "unprovisionedInjectedColumns": "src/data/injected-system-column-provenance.ts#unprovisionedInjectedColumns (function)", From 90536ecd71287da37cadaf7a54494e0129adcaa8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 05:23:08 +0000 Subject: [PATCH 17/22] fix(spec,runtime,lint): read a refusal reason only under a code that declares reasons; compile hook refusal templates (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- content/docs/automation/hooks.mdx | 8 +- packages/lint/src/validate-expressions.ts | 7 ++ .../src/validate-hook-refusal-templates.ts | 104 ++++++++++++++++++ .../sandbox/hook-refusal-catalogue.test.ts | 35 +++++- .../src/sandbox/hook-refusal-catalogue.ts | 32 ++++-- packages/spec/src/data/hook-refusal-codes.ts | 5 +- packages/spec/src/data/hook-refusals.test.ts | 17 ++- packages/spec/src/data/hook.zod.ts | 52 +++++---- 8 files changed, 217 insertions(+), 43 deletions(-) create mode 100644 packages/lint/src/validate-hook-refusal-templates.ts diff --git a/content/docs/automation/hooks.mdx b/content/docs/automation/hooks.mdx index bdd34a8206e..c93cf1d14f2 100644 --- a/content/docs/automation/hooks.mdx +++ b/content/docs/automation/hooks.mdx @@ -379,12 +379,14 @@ export const planGate = { - **It works whichever way the hook is written.** A TypeScript `handler` (run in-process on a source boot such as `bootStack(config)`, and lowered to a `js` body by `os build`) and a sandboxed `js` body answer the same envelope. -- **Loud on a mistake.** A code, or a reason, the catalogue does not declare is - refused when the hook is saved if the hook names it literally in a `throw`. +- **Loud on a mistake.** A code the catalogue does not declare, or a reason a + code with `reasons` does not declare, is refused when the hook is saved if + the hook names it literally in a `throw`. Otherwise it is refused when the hook runs, as a `500` that names the hook and the code. A throw with no code is refused the same way. An error a `ctx.api` call raised and the hook let through unchanged, and a crash, pass - through as they always did. + through as they always did. Under a code that declares no `reasons`, a + `reason` on the throw is not read: the entry's own sentence answers. - **Translated by key.** Each sentence has a key the translation bundle writes, `hooks..refusals..message` and `hooks..refusals..reasons..message`; `os i18n extract` diff --git a/packages/lint/src/validate-expressions.ts b/packages/lint/src/validate-expressions.ts index 0f0665c533c..7d70e46fd9b 100644 --- a/packages/lint/src/validate-expressions.ts +++ b/packages/lint/src/validate-expressions.ts @@ -117,6 +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'; // [#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 @@ -4377,6 +4378,12 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression issues.push(...kept); } + // [#33214] A hook refusal sentence over declared `params` is a template: + // compiled here (logic, an unknown formatter, an empty hole and an + // argument-less `currency` are errors), off an object write, like the hook + // `condition` walk above. + if (!objectWrite) issues.push(...hookRefusalTemplateIssues(stack)); + // [#24798] The bulk `confirmText` template slots: an object's own // `listViews` on every run (an object write included — they are the // object's own body), a view's list containers off an object write. diff --git a/packages/lint/src/validate-hook-refusal-templates.ts b/packages/lint/src/validate-hook-refusal-templates.ts new file mode 100644 index 00000000000..aaa79300360 --- /dev/null +++ b/packages/lint/src/validate-hook-refusal-templates.ts @@ -0,0 +1,104 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#33214] Judge the template sentences of a hook's refusal catalogue — an + * entry's `message` and each of its `reasons[*].message` — for an entry that + * declares `params` (`HookRefusalSchema`, `@objectstack/spec/data`). + * + * The save-time parse judges only the ROOTS of such a sentence's holes + * (`closedScopeTemplateRefusal`: a hole over a name the entry does not declare, + * a single-brace token). That reading skips every hole that does not compile as + * a path, so a hole holding logic (`{{ state + 1 }}`), an unknown formatter + * (`{{ state | shout }}`) or nothing at all (`{{ }}`) parsed — and the runtime, + * which cannot render it, serves the declared sentence as written, braces and + * all, to the person the hook refused. This pass is the compile half the + * action copy slots already have (`validate-action-copy-templates.ts`): each + * sentence is compiled as the `template` it is (`validateExpression('template', + * …)`), and an empty hole is named. + * + * And one rule that is the hook refusal's own: a `{{ amount | currency }}` hole + * with no argument formats in the organization's default currency, which a + * flow run carries and a hook refusal does not, so the runtime cannot render + * it either. It is refused with the spelling that names the code. + * + * Every finding is an ERROR: `objectstack validate` and `compile` fail, and the + * publish gate refuses a `hook` write carrying one (the `hook` write type runs + * 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. + */ + +import { validateExpression } from '@objectstack/formula'; +import { recordsOf } from './object-graph.js'; +import type { ExprIssue } from './validate-expressions.js'; + +type AnyRec = Record; + +const isRec = (v: unknown): v is AnyRec => typeof v === 'object' && v !== null && !Array.isArray(v); + +/** Every `{{ … }}` hole of a sentence, its inner text as written. */ +const HOLE = /\{\{([^{}]*)\}\}/g; + +/** The declared params of an entry, or none. */ +function paramsOf(entry: AnyRec): string[] { + return Array.isArray(entry.params) ? entry.params.filter((p): p is string => typeof p === 'string') : []; +} + +/** The refusal of an argument-less `currency` formatter in one hole, or `undefined`. */ +function currencyWithoutCode(holeText: string, inner: string): 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 ( + `\`${holeText}\` formats in the organization's default currency, which a hook refusal does not carry, so the ` + + 'sentence would be served with its braces. Name the code in the hole: ' + + `\`{{ ${path} | currency:EUR }}\`.` + ); +} + +/** The refusal of an empty hole, or `undefined`. */ +function emptyHole(holeText: string, inner: string, params: readonly string[]): string | undefined { + if (inner.trim().length > 0) return undefined; + return ( + `\`${holeText}\` names nothing, so the sentence would be served with its braces. Name one of the entry's ` + + `params (${params.map((p) => `\`${p}\``).join(', ')}) in the hole, or remove it.` + ); +} + +/** + * The findings for every hook refusal sentence of `stack` whose entry declares + * `params` (see the module header). + */ +export function hookRefusalTemplateIssues(stack: AnyRec): ExprIssue[] { + const issues: ExprIssue[] = []; + for (const hook of recordsOf(stack.hooks)) { + const hookName = typeof hook.name === 'string' ? hook.name : '?'; + if (!isRec(hook.refusals)) continue; + for (const [code, entry] of Object.entries(hook.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 = `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 = emptyHole(m[0], m[1]!, params) ?? 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/runtime/src/sandbox/hook-refusal-catalogue.test.ts b/packages/runtime/src/sandbox/hook-refusal-catalogue.test.ts index 19aadc3583e..9c113ac1791 100644 --- a/packages/runtime/src/sandbox/hook-refusal-catalogue.test.ts +++ b/packages/runtime/src/sandbox/hook-refusal-catalogue.test.ts @@ -308,12 +308,15 @@ describe('[#33214] a declared reason under a code — the body path', () => { expect(mapDataError(err, 'plan').status).toBe(500); }); - it('a reason under a code that declares no reasons is the same fault', async () => { + it('a reason under a code that declares no reasons is not read: the entry answers as before', async () => { const err = await rejectionOf(planBody( "const r = 'x' + 'y'; throw { code: 'CREDIT_LIMIT', reason: r, message: 'x' };", - )(planCtx())); - expect(err.message).toContain("reason 'xy'"); - expect(mapDataError(err, 'plan').status).toBe(500); + )(planCtx('zh-CN'))); + const wire = mapDataError(err, 'plan'); + expect(wire.status).toBe(400); + expect(wire.body.declaredCode).toBe('CREDIT_LIMIT'); + // The code's own key is read, never a reason key under it. + expect(wire.body.userMessage).toBe('超出信用额度。'); }); }); @@ -345,6 +348,30 @@ describe('[#33214] declared params fill the sentence\'s holes — the body path' }); }); +describe('[#33214] a main-shaped hook that throws a `reason` answers exactly as on main', () => { + // A catalogue with no `reasons`, a body that throws a `reason` property: + // main never read `reason`, so the declared message answers, 4xx. + it('the body path', async () => { + const err = await rejectionOf(boundHook( + "throw Object.assign(new Error('internal detail'), { code: 'ACCOUNT_ON_HOLD', reason: 'plan_locked' });", + )(ctx())); + const wire = mapDataError(err, 'order'); + expect(wire.status).toBe(409); + expect(wire.body.declaredCode).toBe('ACCOUNT_ON_HOLD'); + expect(wire.body.userMessage).toBe('The account is on hold.'); + }); + + it('the in-process path', async () => { + const fn = withInProcessHookTitle(async () => { + throw Object.assign(new Error('internal detail'), { code: 'ACCOUNT_ON_HOLD', reason: 'plan_locked' }); + }, {}, { name: 'credit_guard', refusals: REFUSALS } as any); + const wire = mapDataError(await rejectionOf(fn(ctx())), 'order'); + expect(wire.status).toBe(409); + expect(wire.body.declaredCode).toBe('ACCOUNT_ON_HOLD'); + expect(wire.body.userMessage).toBe('The account is on hold.'); + }); +}); + describe('[#33214] a hook that uses none of the new parts answers byte-for-byte as before', () => { // Measured on the base commit (e540baf887) with the same fixture: the wire a // declared code answers with when the hook declares no reasons and no params. diff --git a/packages/runtime/src/sandbox/hook-refusal-catalogue.ts b/packages/runtime/src/sandbox/hook-refusal-catalogue.ts index acc2c306ef0..145db461235 100644 --- a/packages/runtime/src/sandbox/hook-refusal-catalogue.ts +++ b/packages/runtime/src/sandbox/hook-refusal-catalogue.ts @@ -42,8 +42,10 @@ * may hold further declared sentences under `reasons`; a throw that names a * `reason` is answered with that sentence * (`hooks..refusals..reasons..message`), the code's - * status and the code on the wire, unchanged. A reason the code does not - * declare is refused loudly, like an undeclared code. An entry that declares + * status and the code on the wire, unchanged. Under a code that declares + * `reasons`, a reason it does not declare is refused loudly, like an + * undeclared code; under a code that declares none, a thrown `reason` is not + * read, exactly as before. An entry that declares * `params` is a template: its picked sentence (translated or declared) has its * `{{ NAME }}` holes filled from the throw's `params` through the formula * template engine — the engine the flow `end` refusal renders through @@ -207,13 +209,25 @@ export function declaredRefusalMessage( logger?: { warn?: (...args: any[]) => void }, address?: HookRefusalAddress, ): string { - const reason = address?.reason; - const declaredSentence = reason !== undefined && entry.reasons?.[reason] ? entry.reasons[reason]!.message : entry.message; + 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 params = Array.isArray(entry.params) ? entry.params : []; return params.length > 0 ? fillHookRefusalParams(hookName, picked, params, address?.params, logger) : picked; } +/** + * The reason a throw names that the entry declares, or `undefined`. A reason + * under a code that declares no `reasons` is not part of the refusal — the + * catalogue reads it only where `reasons` exists — so such a throw is answered + * exactly as before `reasons` existed. + */ +function declaredReason(entry: DeclaredRefusal, address: HookRefusalAddress | undefined): string | undefined { + const reason = address?.reason; + if (reason === undefined || !entry.reasons || typeof entry.reasons !== 'object') return undefined; + return Object.prototype.hasOwnProperty.call(entry.reasons, reason) ? reason : undefined; +} + /** The translation of a declared sentence in `locale`, or the declared sentence itself. */ function pickTranslatedSentence( hookName: string, @@ -260,12 +274,12 @@ function declaredAnswer( engineCtx: { session?: { locale?: unknown } } | undefined, 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 + // other code it is ignored, as it was before `reasons` existed. const reason = address?.reason; - if (reason !== undefined) { - const reasons = entry.reasons && typeof entry.reasons === 'object' ? entry.reasons : {}; - if (!Object.prototype.hasOwnProperty.call(reasons, reason)) { - return { fault: new SandboxError(undeclaredHookRefusalReasonAtRun(String(hook.name), thrownCode, reason, Object.keys(reasons))) }; - } + 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))) }; } const locale = engineCtx?.session?.locale; const message = declaredRefusalMessage( diff --git a/packages/spec/src/data/hook-refusal-codes.ts b/packages/spec/src/data/hook-refusal-codes.ts index 4e12876c3a5..609f199fdec 100644 --- a/packages/spec/src/data/hook-refusal-codes.ts +++ b/packages/spec/src/data/hook-refusal-codes.ts @@ -13,8 +13,9 @@ * answers with the declared message, translated through * `hooks..refusals..message` (or * `hooks..refusals..reasons..message`) in the caller's - * locale, and the declared status. A code, or a reason, the catalogue does not - * declare is refused loudly: + * locale, and the declared status. A code the catalogue does not declare, or a + * reason a code that declares `reasons` does not declare, is refused loudly (a + * thrown `reason` under a code with no `reasons` is not read, as before): * * - at save time, where the hook's source names it literally in a `throw` * ({@link hookRefusalCodesThrownIn}, {@link hookRefusalReasonsThrownIn}) — diff --git a/packages/spec/src/data/hook-refusals.test.ts b/packages/spec/src/data/hook-refusals.test.ts index cdc77f4d605..6d5c29632bc 100644 --- a/packages/spec/src/data/hook-refusals.test.ts +++ b/packages/spec/src/data/hook-refusals.test.ts @@ -323,18 +323,23 @@ describe('HookRefusal.reasons — further sentences under one code (#33214, S1)' ); }); - it('refuses at `handler` a literal reason under a code with no `reasons`', () => { + it('reads no reason under a code with no `reasons` — a handler throwing one saves, as before', () => { const handler = async () => { const e: any = new Error('x'); e.code = 'CREDIT_LIMIT'; e.reason = 'over_by_far'; throw e; }; - const r = HookSchema.safeParse({ ...base, handler, refusals: { CREDIT_LIMIT: { message: 'Over.' } } }); - expect(r.success).toBe(false); - const issue = r.error!.issues.find((i) => i.path.join('.') === 'handler')!; - expect(issue.message).toContain("reason 'over_by_far'"); - expect(issue.message).toContain('declared: none'); + expect(HookSchema.safeParse({ ...base, handler, refusals: { CREDIT_LIMIT: { message: 'Over.' } } }).success).toBe(true); + }); + + it('a main-shaped body hook throwing a `reason` under a code with no `reasons` saves unchanged', () => { + const r = HookSchema.safeParse({ + ...base, + body: body("throw Object.assign(new Error('x'), { code: 'CREDIT_LIMIT', reason: 'plan_locked' });"), + refusals: { CREDIT_LIMIT: { message: 'Over the credit limit.' } }, + }); + expect(r.success).toBe(true); }); }); diff --git a/packages/spec/src/data/hook.zod.ts b/packages/spec/src/data/hook.zod.ts index fe6e662aa99..e4aa4890305 100644 --- a/packages/spec/src/data/hook.zod.ts +++ b/packages/spec/src/data/hook.zod.ts @@ -254,7 +254,9 @@ function refuseHookBodyMailGrant( * metadata save door, `defineStack` / `os validate`, compile, an artifact's * parse — so the author meets the refusal before any write does. One issue per * code. A code that arrives any other way is the run-time refusal's. The same - * holds for a reason under a code (#33214, `hookRefusalReasonsThrownIn`). + * holds for a reason under a code that declares `reasons` (#33214, + * `hookRefusalReasonsThrownIn`); under a code that declares none, a thrown + * `reason` is not read at all, as before. * * [#33214, ruling 6879477573 letter A] The catalogue is answered on every path * a hook runs on: a sandboxed `js` body, and an in-process `handler` — an @@ -321,8 +323,11 @@ function refuseUndeclaredLiteralRefusalCode( } for (const { code, reason } of hookRefusalReasonsThrownIn(read.source)) { if (!Object.prototype.hasOwnProperty.call(hook.refusals, code)) continue; - const reasons = hook.refusals[code]?.reasons ?? {}; - if (Object.prototype.hasOwnProperty.call(reasons, reason)) continue; + // A `reason` is read only under a code that declares `reasons`: under any + // other code it is not part of the refusal, exactly as before `reasons` + // existed, so a hook that already throws one is answered as it was. + const reasons = hook.refusals[code]?.reasons; + if (!reasons || Object.prototype.hasOwnProperty.call(reasons, reason)) continue; ctx.addIssue({ code: 'custom', path, @@ -355,8 +360,8 @@ const HookRefusalReasonSchema = lazySchema(() => strictObject( { 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; a {{ }} ' - + 'hole names one of the entry\'s params', + + 'translated through hooks..refusals..reasons..message in the caller\'s locale; its {{ }} ' + + 'holes follow the entry\'s message rule', ), }, )); @@ -391,13 +396,18 @@ function hookRefusalMessageRefusal(message: string, params: readonly string[] | * - `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. + * 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 save; an entry that - * declares no `params` is plain text and every `{{ }}` hole in it is - * refused, as before. + * 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. */ export const HookRefusalSchema = lazySchema(() => strictObject( { @@ -418,8 +428,9 @@ export const HookRefusalSchema = lazySchema(() => strictObject( { 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; a {{ }} hole is refused unless it names one ' - + 'of the entry\'s params', + + '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 ' @@ -433,16 +444,17 @@ export const HookRefusalSchema = lazySchema(() => strictObject( ).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', + + '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 }} hole renders the value the hook throws in ' - + '`params` ({ code, params: { NAME: value } }). A hole over any other name is refused. Absent: the ' - + 'sentences are plain text and a {{ }} hole is refused', + '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) => { @@ -805,8 +817,9 @@ export const HookSchema = lazySchema(() => strictObject( * (or the reason's), translated through `hooks..refusals..message` * (`…..reasons..message`) in the caller's locale with the * declared sentence as the fallback, its holes filled from `params`, marked - * as the end user's sentence, and its `status`. A code or reason the - * catalogue does not declare, or a throw with no code, is refused loudly: at + * as the end user's sentence, and its `status`. 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 hook's source names it literally, otherwise when it runs, * as a fault naming the hook and the code. An error a host call raised and * the hook let through unchanged (a `ctx.api` write refused by the engine, a @@ -830,8 +843,9 @@ export const HookSchema = lazySchema(() => strictObject( 'Refusal catalogue keyed by the SCREAMING_SNAKE code the hook throws: { message, status?, reasons?, params? }. ' + 'The hook (a js body or a handler) refuses by code only, optionally with a declared reason and params; the ' + 'runtime answers with the declared message (translated through hooks..refusals..message, or ' - + '…..reasons..message, in the caller\'s locale, holes filled from params) and status. A code or ' - + 'reason not declared here is refused loudly — at save when the hook throws it literally, otherwise at run time', + + '…..reasons..message, 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 hook throws ' + + 'it literally, otherwise at run time; under a code with no reasons a thrown reason is not read', ), /** From 9337b82aaff2db87263ffe43ceb19529eef3804b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 05:29:46 +0000 Subject: [PATCH 18/22] test(lint): hook refusal template compile pins; drop the duplicate empty-hole rule (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- .../validate-hook-refusal-templates.test.ts | 82 +++++++++++++++++++ .../src/validate-hook-refusal-templates.ts | 13 +-- 2 files changed, 84 insertions(+), 11 deletions(-) create mode 100644 packages/lint/src/validate-hook-refusal-templates.test.ts diff --git a/packages/lint/src/validate-hook-refusal-templates.test.ts b/packages/lint/src/validate-hook-refusal-templates.test.ts new file mode 100644 index 00000000000..87b1095a34b --- /dev/null +++ b/packages/lint/src/validate-hook-refusal-templates.test.ts @@ -0,0 +1,82 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#33214] A hook refusal sentence over declared `params` is compiled as the + * template it is: logic, an unknown formatter, an empty hole and a `currency` + * formatter with no code are errors — at `objectstack validate` / `compile` + * (the stack expression pass) and at the publish gate's `hook` write. + */ + +import { describe, it, expect } from 'vitest'; +import { hookRefusalTemplateIssues } from './validate-hook-refusal-templates.js'; +import { validateStackExpressions } from './validate-expressions.js'; +import { runRuntimeAuthoringRules } from './runtime-gate.js'; + +const hook = (refusals: Record) => ({ + name: 'plan_gate', + object: 'plan', + events: ['beforeUpdate'], + handler: 'planGate', + refusals, +}); + +const entry = (message: string, extra: Record = {}) => ({ + VALIDATION_FAILED: { message, params: ['state', 'amount'], ...extra }, +}); + +const issuesOf = (message: string, extra?: Record) => + hookRefusalTemplateIssues({ hooks: [hook(entry(message, extra))] }); + +describe('hook refusal templates over declared params (#33214)', () => { + it.each([ + 'The plan is {{ state }}.', + 'Over by {{ amount | number:2 }}.', + 'Paid {{ amount | currency:EUR }}.', + 'Plain text with no hole.', + ])('accepts %j', (message) => { + expect(issuesOf(message)).toEqual([]); + }); + + it.each([ + ['an unknown formatter', 'The plan is {{ state | shout }}.'], + ['logic', 'The plan is {{ state + 1 }}.'], + ['an empty hole', 'The plan is {{ }}.'], + ])('refuses %s as an error, naming the hook and the sentence', (_label, message) => { + const issues = issuesOf(message); + expect(issues.length).toBeGreaterThan(0); + expect(issues.every((i) => i.severity === 'error')).toBe(true); + expect(issues[0]!.where).toBe("hook 'plan_gate' refusals.VALIDATION_FAILED.message"); + }); + + it('refuses a currency formatter with no code, naming the spelling that names one', () => { + const issues = issuesOf('Paid {{ amount | currency }}.'); + expect(issues).toHaveLength(1); + expect(issues[0]).toMatchObject({ severity: 'error', source: '{{ amount | currency }}' }); + expect(issues[0]!.message).toContain('{{ amount | currency:EUR }}'); + }); + + it('judges each reason sentence at its own path', () => { + const issues = issuesOf('Fine {{ state }}.', { reasons: { plan_locked: { message: 'Locked {{ state | shout }}.' } } }); + expect(issues.map((i) => i.where)).toEqual(["hook 'plan_gate' refusals.VALIDATION_FAILED.reasons.plan_locked.message"]); + }); + + it('reads no entry that declares no params — the parse refuses every hole there', () => { + expect(hookRefusalTemplateIssues({ hooks: [hook({ X: { message: 'Paid {{ amount | currency }}.' } })] })).toEqual([]); + }); + + it('is part of the stack expression pass `objectstack validate` and `compile` run', () => { + const issues = validateStackExpressions({ hooks: [hook(entry('The plan is {{ state | shout }}.'))] } as never); + expect(issues.some((i) => i.where === "hook 'plan_gate' refusals.VALIDATION_FAILED.message" && i.severity === 'error')).toBe(true); + }); + + it('refuses a `hook` write at the publish gate', () => { + const result = runRuntimeAuthoringRules({ + type: 'hook', + item: hook(entry('Paid {{ amount | currency }}.')), + context: { objects: [] }, + }); + const finding = result.errors.find((e) => String(e.message).includes('{{ amount | currency:EUR }}')); + expect(finding, JSON.stringify(result.errors)).toBeDefined(); + expect(finding!.severity).toBe('error'); + }); +}); diff --git a/packages/lint/src/validate-hook-refusal-templates.ts b/packages/lint/src/validate-hook-refusal-templates.ts index aaa79300360..0db7d236ef3 100644 --- a/packages/lint/src/validate-hook-refusal-templates.ts +++ b/packages/lint/src/validate-hook-refusal-templates.ts @@ -14,7 +14,7 @@ * all, to the person the hook refused. This pass is the compile half the * action copy slots already have (`validate-action-copy-templates.ts`): each * sentence is compiled as the `template` it is (`validateExpression('template', - * …)`), and an empty hole is named. + * …)`), which names logic, an unknown formatter and an empty hole. * * And one rule that is the hook refusal's own: a `{{ amount | currency }}` hole * with no argument formats in the organization's default currency, which a @@ -58,15 +58,6 @@ function currencyWithoutCode(holeText: string, inner: string): string | undefine ); } -/** The refusal of an empty hole, or `undefined`. */ -function emptyHole(holeText: string, inner: string, params: readonly string[]): string | undefined { - if (inner.trim().length > 0) return undefined; - return ( - `\`${holeText}\` names nothing, so the sentence would be served with its braces. Name one of the entry's ` - + `params (${params.map((p) => `\`${p}\``).join(', ')}) in the hole, or remove it.` - ); -} - /** * The findings for every hook refusal sentence of `stack` whose entry declares * `params` (see the module header). @@ -93,7 +84,7 @@ export function hookRefusalTemplateIssues(stack: AnyRec): ExprIssue[] { issues.push({ where, message, source, severity: 'error' }); }; for (const m of text.matchAll(HOLE)) { - const refusal = emptyHole(m[0], m[1]!, params) ?? currencyWithoutCode(m[0], m[1]!); + 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); From 3a820ad122df9741d98a59a5188cf1935c57229e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 05:30:31 +0000 Subject: [PATCH 19/22] docs(changeset): reasons read only under a declared reasons map; params compile refusals; skills follow-up #33658 (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- .changeset/33214-handler-hook-refusals.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.changeset/33214-handler-hook-refusals.md b/.changeset/33214-handler-hook-refusals.md index 04a3755e58c..0a751ea3507 100644 --- a/.changeset/33214-handler-hook-refusals.md +++ b/.changeset/33214-handler-hook-refusals.md @@ -8,14 +8,14 @@ feat(spec,runtime): a hook written as a TypeScript `handler` can declare `refusa Clause-②: yes Metadata-protocol: added -Skills-docs: follow-up owed — skills/objectstack-data/references/data-hooks.md (the "Declared refusals (`refusals`)" section teaches a sandboxed `body` only, one sentence per code, no params), skills/objectstack-i18n/SKILL.md (the `hooks..refusals..message` row has no `reasons` key) +Skills-docs: follow-up #33658 — skills/objectstack-data/references/data-hooks.md (the "Declared refusals (`refusals`)" section teaches a sandboxed `body` only, one sentence per code, no params), skills/objectstack-i18n/SKILL.md (the `hooks..refusals..message` row has no `reasons` key) A hook's refusal catalogue (`HookSchema.refusals`) is answered on every path the hook runs on, and an entry can hold more than one sentence (maintainer ruling 6879477573: letter A, S1, params; inside ruling 6431311681 letter A). - **A `handler` hook may declare `refusals`.** `defineStack`, `os validate`, `os build` and the metadata save door used to refuse `refusals` on a hook with no `js` body. They now accept it on a hook whose `handler` is an inline function or a string reference. An undeclared code that the handler's source throws literally is refused at save, at `handler`. The catalogue is answered on every path: the body `os build` lowers the handler to (as before), and the in-process handler of a source boot (`bootStack(config)`, `os serve` over a host config), plus the function a string `handler` names when the build could not lower it. Both answer with the same envelope. An error a `ctx.api` or `ctx.ql` call raised, which the handler lets through unchanged, passes through as it does on the body path. Still refused: `refusals` on a hook whose code cannot throw a code (an `expression` body, or neither a body nor a handler). -- **`reasons`: several sentences under one wire code.** `refusals.CODE.reasons.REASON.message`, with a snake_case reason. The hook throws `{ code, reason }`. The caller reads the reason's sentence, with the code and the status of its entry, so the wire code and the envelope are unchanged. A reason the code does not declare is refused loudly: at save where the hook's source throws it literally, otherwise at run time as a `500` naming the hook, the code and the reason. Translated through `hooks.HOOK.refusals.CODE.reasons.REASON.message`. `os i18n extract` and `os i18n check` count each declared reason, and `os validate` refuses a translation key over a reason the code does not declare (`translation-target-unknown`). -- **`params`: names a sentence may fill.** An entry declares `params: ['state']`, and its sentences (its `message` and each reason) may write a double-brace hole over those names. The hook throws `params: { state }`. The runtime fills the holes after it picks the translation, through the formula template engine the flow `end` refusal renders with, and only declared names are in scope. A hole over an undeclared name is refused at save. An entry with no `params` stays plain text and every hole in it is refused, as before. The rule is now a refinement (`dropped-refinements.baseline.json` gains `data/HookRefusal`), so the published JSON Schema no longer carries the hole pattern on `message`. +- **`reasons`: several sentences under one wire code.** `refusals.CODE.reasons.REASON.message`, with a snake_case reason. The hook throws `{ code, reason }`. The caller reads the reason's sentence, with the code and the status of its entry, so the wire code and the envelope are unchanged. Under a code that declares `reasons`, a reason it does not declare is refused loudly: at save where the hook's source throws it literally, otherwise at run time as a `500` naming the hook, the code and the reason. Under a code that declares no `reasons`, a thrown `reason` is not read, as before: the entry's own sentence answers. Translated through `hooks.HOOK.refusals.CODE.reasons.REASON.message`. `os i18n extract` and `os i18n check` count each declared reason, and `os validate` refuses a translation key over a reason the code does not declare (`translation-target-unknown`). +- **`params`: names a sentence may fill.** An entry declares `params: ['state']`, and its sentences (its `message` and each reason) may write a double-brace hole over those names. The hook throws `params: { state }`. The runtime fills the holes after it picks the translation, through the formula template engine the flow `end` refusal renders with, and only declared names are in scope. A hole over an undeclared name is refused at save. 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 by `os validate`, `os compile` and the publish gate's `hook` write (`@objectstack/lint`). An entry with no `params` stays plain text and every hole in it is refused, as before. The rule is now a refinement (`dropped-refinements.baseline.json` gains `data/HookRefusal`), so the published JSON Schema no longer carries the hole pattern on `message`. -Unchanged: a hook that declares none of the new parts answers byte-for-byte as before (pinned against the base commit's output), and a hook that declares no `refusals` is untouched on both paths. +Unchanged: a hook that declares none of the new parts answers byte-for-byte as before (pinned against the base commit's output), including one that throws a `reason` property under a code with no `reasons` (saved and answered as on `main`, pinned on both paths), and a hook that declares no `refusals` is untouched on both paths. New exports in `@objectstack/spec/data`: `HOOK_REFUSAL_REASON_PATTERN`, `HOOK_REFUSAL_PARAM_PATTERN`, `hookRefusalReasonsThrownIn`, `undeclaredHookRefusalReasonAtSave`, `undeclaredHookRefusalReasonAtRun`. `hookRefusalMessageKey(hook, code, reason?)` takes an optional reason. From 7434178fb648ec3f933c9444df2e686a5c9f8d8a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 05:40:43 +0000 Subject: [PATCH 20/22] chore(spec): regenerate the hook reference page (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- content/docs/references/data/hook.mdx | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/content/docs/references/data/hook.mdx b/content/docs/references/data/hook.mdx index 764f06db33a..78c4dd2bea9 100644 --- a/content/docs/references/data/hook.mdx +++ b/content/docs/references/data/hook.mdx @@ -42,7 +42,7 @@ const result = HookSchema.parse(data); | **timeoutMs** | `number` | optional | Maximum execution time in milliseconds before the hook is aborted | | **timeout** | `never` | optional | [REMOVED] `hook.timeout` was removed in @objectstack/spec 17 — its unit (milliseconds) lived only in the description, beside a body-level `timeoutMs` and a `retryPolicy.backoffMs` that spell theirs, so the same number read as two conventions on one surface. Rename the key to `timeoutMs`; the value (milliseconds) is unchanged. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **onError** | `Enum<'abort' \| 'log'>` | optional (default: `"abort"`) | Error handling strategy. abort: refuse the operation; a blocking hook's abort rolls the write back inside a unit of work, which the write door opens for an after* hook on an object on the default datasource whose driver declares transactions (elsewhere the caller is refused and the row stays stored). log: log the error and continue | -| **refusals** | `Record; params?: string[] }>` | optional | Refusal catalogue keyed by the SCREAMING_SNAKE code the hook throws: `{ message, status?, reasons?, params? }`. The hook (a js body or a handler) refuses by code only, optionally with a declared reason and params; the runtime answers with the declared message (translated through hooks.``.refusals.``.message, or ….``.reasons.``.message, in the caller's locale, holes filled from params) and status. A code or reason not declared here is refused loudly — at save when the hook throws it literally, otherwise at run time | +| **refusals** | `Record; params?: string[] }>` | optional | Refusal catalogue keyed by the SCREAMING_SNAKE code the hook throws: `{ message, status?, reasons?, params? }`. The hook (a js body or a handler) refuses by code only, optionally with a declared reason and params; the runtime answers with the declared message (translated through hooks.``.refusals.``.message, or ….``.reasons.``.message, 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 hook throws it literally, otherwise at run time; under a code with no reasons a thrown reason is not read | | **runAs** | `Enum<'system' \| 'user' \| 'inherit'>` | optional (default: `"inherit"`) | Execution identity for the hook's ctx.api data operations: system = elevated (bypasses RLS), user = the triggering user (RLS-respecting), inherit = the context of the write that fired the hook (the pre-runAs behaviour; the default). A hook with no trigger user has no identity to scope to, so under user its ctx.api data operations are REFUSED — declare system to make the elevation explicit. This covers any hook fired by a write that carried no user (an isSystem plugin/service write; a system-elevated flow node). Elevation does not reach identity assignment: a system hook's governed writes (insert, update, delete, transfer, restore, purge) to sys_user_position, sys_user_permission_set, sys_invitation and sys_member are refused with PERMISSION_DENIED, and a system hook whose body names such a write is refused at save; declare user for position holdings and permission-set grants (the ADR-0090 D12 delegated-administration gate then judges the user the hook acts for), and change invitations and memberships through the organization endpoints. Nor does it reach a ledger: a system hook body's 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. Scope: ctx.api only — condition evaluation, the readonly strip on ctx.input, ctx.session and async are unchanged. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | @@ -84,10 +84,10 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **message** | `string` | ✅ | 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; a `{{ }}` hole is refused unless it names one of the entry's params | +| **message** | `string` | ✅ | 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** | `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 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 | -| **params** | `string[]` | optional | The names this entry's sentences may fill: a `{{ NAME }}` hole renders the value the hook throws in `params` (`{ code, params: { NAME: value } }`). A hole over any other name is refused. Absent: the sentences are plain text and a `{{ }}` hole is refused | +| **reasons** | `Record` | optional | 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** | `string[]` | optional | 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 | --- @@ -184,16 +184,16 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **message** | `string` | ✅ | 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; a `{{ }}` hole is refused unless it names one of the entry's params | +| **message** | `string` | ✅ | 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** | `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 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 | -| **params** | `string[]` | optional | The names this entry's sentences may fill: a `{{ NAME }}` hole renders the value the hook throws in `params` (`{ code, params: { NAME: value } }`). A hole over any other name is refused. Absent: the sentences are plain text and a `{{ }}` hole is refused | +| **reasons** | `Record` | optional | 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** | `string[]` | optional | 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 | ### Nested Shape: `HookRefusal.reasons[string]` | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **message** | `string` | ✅ | 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; a `{{ }}` hole names one of the entry's params | +| **message** | `string` | ✅ | 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 | --- From 1c9a1ecf2461a0de9e7095aae08318cc27f791fd Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 06:00:32 +0000 Subject: [PATCH 21/22] test(lint): classify the hook refusal template pass in the authored-site walk ledger (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- packages/lint/src/authored-site-expression.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/lint/src/authored-site-expression.test.ts b/packages/lint/src/authored-site-expression.test.ts index 4ab2e298e86..bb8a9b20395 100644 --- a/packages/lint/src/authored-site-expression.test.ts +++ b/packages/lint/src/authored-site-expression.test.ts @@ -120,6 +120,7 @@ const SITE_MEMBER_CALLS: Record> = { 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", }; /** The passes the walk pushes whole from INSIDE a site's regions: classified with that site's calls, in `SITE_CALLS`. */ From da6c538b7643003b2de36ac47aea018c6aa39c87 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 07:28:26 +0000 Subject: [PATCH 22/22] chore(spec): regenerate export-origins, api-surface and the translation reference after merging main (#33214) Claude-Session: https://claude.ai/code/session_017xRBcRivaGj55DhDi7sE8w Co-authored-by: Claude --- content/docs/references/system/translation.mdx | 1 + packages/spec/api-surface/data.json | 14 +++++++++++++- packages/spec/export-origins/data.json | 14 +++++++++++++- 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/content/docs/references/system/translation.mdx b/content/docs/references/system/translation.mdx index f04ba20ebf0..a839f281025 100644 --- a/content/docs/references/system/translation.mdx +++ b/content/docs/references/system/translation.mdx @@ -539,6 +539,7 @@ Internationalization configuration | **defaultLocale** | `string` | ✅ | Default locale (e.g., "en") | | **supportedLocales** | `string[]` | ✅ | Supported BCP-47 locale codes | | **fallbackLocale** | `string` | optional | Fallback locale code | +| **sourceLocale** | `string` | optional | Language the inline metadata text (a plain-string label) is written in, when it differs from defaultLocale (e.g. "en" for an English-authored app whose users default to "zh-CN"). Absent, it is defaultLocale. Read by os lint, os i18n check and os i18n extract as the source language; their --default-locale flag overrides it. Not yet read by the serving layer: the runtime label resolvers still treat defaultLocale as the authored label's language. | --- diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index e37466bad16..97b8901acb1 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -304,6 +304,9 @@ "FILTER_LOGIC_CASES (const)", "FILTER_LOGIC_ROWS (const)", "FILTER_OPERATORS (const)", + "FILTER_STRING_STORED_COMPARAND_CASES (const)", + "FILTER_STRING_STORED_COMPARAND_FIELDS (const)", + "FILTER_STRING_STORED_COMPARAND_ROWS (const)", "FILTER_SUBTREE_PROVENANCE (const)", "FILTER_TEXT_CASES (const)", "FILTER_TEXT_ROWS (const)", @@ -727,6 +730,7 @@ "SEARCHABLE_TEXTUAL_TYPES (const)", "SEARCH_AUTO_EXCLUDED_FIELDS (const)", "SEARCH_AUTO_EXCLUDED_TYPES (const)", + "SEARCH_COMPANION_FIELD (const)", "SEARCH_FLAG_EXCLUDED_TYPES (const)", "SEARCH_VIRTUAL_TYPES (const)", "SECRET_MASK (const)", @@ -744,6 +748,9 @@ "SSL_DETAIL_BELONGS_ON_DATASOURCE (const)", "STACK_KEY_GUIDANCE (const)", "STACK_RUNTIME_MEMBERS (const)", + "STRING_STORED_COMPARAND_DOOR_FAMILIES (const)", + "STRING_STORED_COMPARAND_DOOR_LIST_OPERATORS (const)", + "STRING_STORED_COMPARAND_DOOR_SCALAR_OPERATORS (const)", "STRING_VALUE_TYPES (const)", "STRUCTURED_JSON_TYPES (const)", "SYS_ACTIVITY_BUILTIN_TYPES (const)", @@ -818,6 +825,10 @@ "StateMachineValidationParsed (type)", "StateMachineValidationSchema (const)", "StringOperatorSchema (const)", + "StringStoredComparandCase (interface)", + "StringStoredComparandDoorFieldMeta (interface)", + "StringStoredComparandDoorVerdict (type)", + "StringStoredComparandRow (interface)", "SysActivityBuiltinType (type)", "TEMPORAL_CASES (const)", "TEMPORAL_NOW (const)", @@ -936,7 +947,6 @@ "deriveInlineRowFormFields (function)", "deriveRecordFlowSurface (function)", "deriveRecordSurface (function)", - "describeManagedApiMethodConflicts (function)", "discriminateDefaultValueShape (function)", "driverConfigJsonSchema (function)", "driverHasLocalDefault (function)", @@ -1089,6 +1099,8 @@ "resolveSearchFields (function)", "seedFile (function)", "sequenceWidth (function)", + "stringStoredComparandDoorVerdict (function)", + "stringStoredComparandFieldVerdict (function)", "stripLegacyApiMethods (function)", "suggestDefaultValueToken (function)", "suggestFieldTypeForSqlType (function)", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 0527624bbd1..d15ca9d0c1c 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -299,6 +299,9 @@ "FILTER_LOGIC_CASES": "src/data/filter-logic-conformance.ts#FILTER_LOGIC_CASES (const)", "FILTER_LOGIC_ROWS": "src/data/filter-logic-conformance.ts#FILTER_LOGIC_ROWS (const)", "FILTER_OPERATORS": "src/data/filter.zod.ts#FILTER_OPERATORS (const)", + "FILTER_STRING_STORED_COMPARAND_CASES": "src/data/filter-comparand-type-conformance.ts#FILTER_STRING_STORED_COMPARAND_CASES (const)", + "FILTER_STRING_STORED_COMPARAND_FIELDS": "src/data/filter-comparand-type-conformance.ts#FILTER_STRING_STORED_COMPARAND_FIELDS (const)", + "FILTER_STRING_STORED_COMPARAND_ROWS": "src/data/filter-comparand-type-conformance.ts#FILTER_STRING_STORED_COMPARAND_ROWS (const)", "FILTER_SUBTREE_PROVENANCE": "src/data/filter-subtree-provenance.ts#FILTER_SUBTREE_PROVENANCE (const)", "FILTER_TEXT_CASES": "src/data/filter-text-conformance.ts#FILTER_TEXT_CASES (const)", "FILTER_TEXT_ROWS": "src/data/filter-text-conformance.ts#FILTER_TEXT_ROWS (const)", @@ -715,6 +718,7 @@ "SEARCHABLE_TEXTUAL_TYPES": "src/data/search-fields.ts#SEARCHABLE_TEXTUAL_TYPES (const)", "SEARCH_AUTO_EXCLUDED_FIELDS": "src/data/search-fields.ts#SEARCH_AUTO_EXCLUDED_FIELDS (const)", "SEARCH_AUTO_EXCLUDED_TYPES": "src/data/search-fields.ts#SEARCH_AUTO_EXCLUDED_TYPES (const)", + "SEARCH_COMPANION_FIELD": "src/data/search-fields.ts#SEARCH_COMPANION_FIELD (const)", "SEARCH_FLAG_EXCLUDED_TYPES": "src/data/search-fields.ts#SEARCH_FLAG_EXCLUDED_TYPES (const)", "SEARCH_VIRTUAL_TYPES": "src/data/search-fields.ts#SEARCH_VIRTUAL_TYPES (const)", "SECRET_MASK": "src/data/secret-mask.ts#SECRET_MASK (const)", @@ -732,6 +736,9 @@ "SSL_DETAIL_BELONGS_ON_DATASOURCE": "src/data/driver/common.zod.ts#SSL_DETAIL_BELONGS_ON_DATASOURCE (const)", "STACK_KEY_GUIDANCE": "src/data/authoring-key-lint.ts#STACK_KEY_GUIDANCE (const)", "STACK_RUNTIME_MEMBERS": "src/data/authoring-key-lint.ts#STACK_RUNTIME_MEMBERS (const)", + "STRING_STORED_COMPARAND_DOOR_FAMILIES": "src/data/filter-string-stored-comparand-declared-type.ts#STRING_STORED_COMPARAND_DOOR_FAMILIES (const)", + "STRING_STORED_COMPARAND_DOOR_LIST_OPERATORS": "src/data/filter-string-stored-comparand-declared-type.ts#STRING_STORED_COMPARAND_DOOR_LIST_OPERATORS (const)", + "STRING_STORED_COMPARAND_DOOR_SCALAR_OPERATORS": "src/data/filter-string-stored-comparand-declared-type.ts#STRING_STORED_COMPARAND_DOOR_SCALAR_OPERATORS (const)", "STRING_VALUE_TYPES": "src/data/field-value.zod.ts#STRING_VALUE_TYPES (const)", "STRUCTURED_JSON_TYPES": "src/data/field-value.zod.ts#STRUCTURED_JSON_TYPES (const)", "SYS_ACTIVITY_BUILTIN_TYPES": "src/data/feed.zod.ts#SYS_ACTIVITY_BUILTIN_TYPES (const)", @@ -806,6 +813,10 @@ "StateMachineValidationParsed": "src/data/validation.zod.ts#StateMachineValidationParsed (type)", "StateMachineValidationSchema": "src/data/validation.zod.ts#StateMachineValidationSchema (const)", "StringOperatorSchema": "src/data/filter.zod.ts#StringOperatorSchema (const)", + "StringStoredComparandCase": "src/data/filter-comparand-type-conformance.ts#StringStoredComparandCase (interface)", + "StringStoredComparandDoorFieldMeta": "src/data/filter-string-stored-comparand-declared-type.ts#StringStoredComparandDoorFieldMeta (interface)", + "StringStoredComparandDoorVerdict": "src/data/filter-string-stored-comparand-declared-type.ts#StringStoredComparandDoorVerdict (type)", + "StringStoredComparandRow": "src/data/filter-comparand-type-conformance.ts#StringStoredComparandRow (interface)", "SysActivityBuiltinType": "src/data/feed.zod.ts#SysActivityBuiltinType (type)", "TEMPORAL_CASES": "src/data/temporal-conformance.ts#TEMPORAL_CASES (const)", "TEMPORAL_NOW": "src/data/temporal-conformance.ts#TEMPORAL_NOW (const)", @@ -922,7 +933,6 @@ "deriveInlineRowFormFields": "src/data/inline-grid-columns.ts#deriveInlineRowFormFields (function)", "deriveRecordFlowSurface": "src/data/record-surface.ts#deriveRecordFlowSurface (function)", "deriveRecordSurface": "src/data/record-surface.ts#deriveRecordSurface (function)", - "describeManagedApiMethodConflicts": "src/data/managed-api-affordance.ts#describeManagedApiMethodConflicts (function)", "discriminateDefaultValueShape": "src/data/default-value-shape.ts#discriminateDefaultValueShape (function)", "driverConfigJsonSchema": "src/data/driver/common.zod.ts#driverConfigJsonSchema (function)", "driverHasLocalDefault": "src/data/driver/config-registry.zod.ts#driverHasLocalDefault (function)", @@ -1075,6 +1085,8 @@ "resolveSearchFields": "src/data/search-fields.ts#resolveSearchFields (function)", "seedFile": "src/data/seed-file.zod.ts#seedFile (function)", "sequenceWidth": "src/data/autonumber-format.ts#sequenceWidth (function)", + "stringStoredComparandDoorVerdict": "src/data/filter-string-stored-comparand-declared-type.ts#stringStoredComparandDoorVerdict (function)", + "stringStoredComparandFieldVerdict": "src/data/filter-string-stored-comparand-declared-type.ts#stringStoredComparandFieldVerdict (function)", "stripLegacyApiMethods": "src/data/object.zod.ts#stripLegacyApiMethods (function)", "suggestDefaultValueToken": "src/data/default-value-shape.ts#suggestDefaultValueToken (function)", "suggestFieldTypeForSqlType": "src/data/type-compat.ts#suggestFieldTypeForSqlType (function)",