diff --git a/.changeset/36877-refusal-reasons-list.md b/.changeset/36877-refusal-reasons-list.md new file mode 100644 index 00000000000..ec3ec290066 --- /dev/null +++ b/.changeset/36877-refusal-reasons-list.md @@ -0,0 +1,43 @@ +--- +'@objectstack/spec': minor +'@objectstack/runtime': minor +'@objectstack/types': minor +--- + +feat(refusals)!: one refusal names several declared reasons, each in the person's language + +Clause-②: yes (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** accept-set narrowing beside a widening, shipped as `minor`. The widening is the new `reasons` list below. The narrowing is what that list makes of a `reasons` key that was ignored before: three sources that save and run on the previous release are refused now (see the migration at the end). + +A hook or a `script` action that declares `refusals` can now refuse with several declared sentences at once, for example when it checks a whole selection and refuses all of it. Under one declared code it throws an ordered list of the code's declared reasons, each with its own `params`, instead of one `reason`: + +```js +throw { code: 'SUBMIT_REFUSED', params: { count }, reasons: [ + { reason: 'on_report', params: { name: 'Taxi 12' } }, + { reason: 'approved', params: { name: 'Hotel 7' } }, +] }; +``` + +- Each listed reason's sentence is picked in the caller's locale and its holes are filled from that reason's own `params`, as a single reason's sentence is. The answer's `userMessage` is those sentences joined by a line break, in the order thrown, then the code's own `message` as the last line (its holes are filled from the throw's top-level `params`). The code's status and the code on the wire are unchanged. +- Every door that answers the refusal also carries each listed reason's sentence structured, as `details.refusals: [{ reason, message }, …]`. The `/data` door bounds `userMessage` at 500 characters as before, and `details.refusals` is not bounded, so each listed line stays whole there. The closing line (the code's own `message`) is not on `details.refusals`: on a list long enough that `/data` cuts `userMessage`, the closing line is lost on that door. A client that renders the list reads the lines from `details.refusals`. +- Every listed reason must be one the code declares under `reasons`. One that is not makes the whole throw the loud `500` fault naming the hook or action, the code and the reason. Under a code that declares no `reasons`, every listed reason is undeclared. A literal list in the source (`throw { code, reasons: [{ reason: 'x' }] }`, or `e.reasons = [{ reason: 'x' }]` on an error the body throws) is refused when the hook or action is saved. Only a `reasons` key that is a direct member of the thrown object is a list; one nested deeper (`params: { reasons: [ … ] }`) is the body's own data, as before. +- A throw that carries both a `reason` and a `reasons` list, an empty list, or a `reasons` value that is not a list of `{ reason, params? }` is the same loud fault. +- The sandboxed body and the in-process hook handler read the list the same way and answer byte-identically. + +The catalogue entry (`message`, `status`, `reasons`, `params`) and the translation keys do not change, so no `os i18n` key is added. A throw with one `reason`, or none, is answered exactly as before. + +New exports: `@objectstack/spec` adds `isUndeclaredThrownReason`, `unreadableHookRefusalListAtRun`, `unreadableActionRefusalListAtRun` and the `HookRefusalThrownReason` and `RefusalListProblem` types (`data`); `hookRefusalReasonsThrownIn` now answers `HookRefusalThrownReason[]` (a listed pair carries `listed: true`). `@objectstack/types` adds `declaredRefusalLines` and the `DeclaredRefusalLine` type. `@objectstack/runtime` adds no export; its `SandboxError` gains an optional `refusals`, the list the doors read. + +**Migration (FROM → TO).** Each row was accepted and answered as if the `reasons` key were absent; it is refused now. + +| FROM (accepted before, refused now) | Where it is refused | TO | +|:---|:---|:---| +| A literal `throw { code: 'X', reasons: [{ reason: 'y' }] }` where `X` declares no `reasons` (a literal `y` under a code that declares `reasons` without it was already refused) | At save: `HookSchema` / `ActionSchema` at `body.source` (the metadata save door, `defineStack`, `os validate`, compile, an artifact's parse) | Declare `reasons` on `X` with `y` and its `message`, or remove the `reasons` key | +| `e.code = 'X'; e.reasons = [{ reason: 'y' }]; throw e` with `y` undeclared under `X` | At save, as above | Declare `y` under `refusals.X.reasons`, or remove the `e.reasons` assignment | +| A body that throws a declared code with a `reasons` property of its own: an empty list, a value that is not a list of `{ reason, params? }`, a list beside a `reason`, or a list naming an undeclared reason | At run: the loud `500` fault naming the hook or action and the code, where the declared sentence and status answered before | Rename the body's own property (for example to `items`, or put it under `params`), or throw it as the declared list | + +One-line fix: a `reasons` key on a thrown refusal is now the declared list, so name only reasons the code declares there, or rename the key. diff --git a/packages/runtime/src/sandbox/action-refusal-catalogue.test.ts b/packages/runtime/src/sandbox/action-refusal-catalogue.test.ts index 332a4e4b330..9b38c9069d3 100644 --- a/packages/runtime/src/sandbox/action-refusal-catalogue.test.ts +++ b/packages/runtime/src/sandbox/action-refusal-catalogue.test.ts @@ -370,3 +370,57 @@ describe('the runner\'s own faults pass an action\'s refusal catalogue untouched } }); }); + +/** + * [#36877, ruling 7178348458 letter A] An action that refuses a whole selection + * names several declared reasons in one throw; the `/actions` door answers each + * sentence in the caller's language, in the order thrown, with the entry's own + * sentence last, and the lines structured on `details.refusals`. + */ +describe('[#36877] an action\'s reasons list on the `/actions` door', () => { + const LIST = { + ...REFUSALS, + NOT_SUBMITTED: { + message: 'Nothing was submitted.', + status: 409, + params: ['name'], + reasons: { + on_report: { message: 'Expense {{ name }} is already on an expense report.' }, + approved: { message: 'Expense {{ name }} is already approved.' }, + }, + }, + }; + const KEY = 'objects.crm_invoice._actions.submit_signoff.refusals.NOT_SUBMITTED'; + const i18n = () => i18nService({ + [`${KEY}.message`]: '未提交任何费用。', + [`${KEY}.reasons.on_report.message`]: '费用 {{ name }} 已在报销单上。', + [`${KEY}.reasons.approved.message`]: '费用 {{ name }} 已审批。', + }); + const source = "throw Object.assign(new Error('internal detail'), { code: 'NOT_SUBMITTED', reasons: [" + + "{ reason: 'on_report', params: { name: 'Taxi 12' } }, { reason: 'approved', params: { name: 'Hotel 7' } }] });"; + + it('every line translated, the closing sentence last, the list on details.refusals', async () => { + const err = await rejectionOf(boundAction(source, { refusals: LIST, i18n })(actionCtx('zh-CN'))); + const response = await throughActionsDoor(err); + expect(response.status).toBe(409); + expect(response.body.error.userMessage).toBe('费用 Taxi 12 已在报销单上。\n费用 Hotel 7 已审批。\n未提交任何费用。'); + expect(response.body.error.details.refusals).toEqual([ + { reason: 'on_report', message: '费用 Taxi 12 已在报销单上。' }, + { reason: 'approved', message: '费用 Hotel 7 已审批。' }, + ]); + expect(JSON.stringify(response.body)).not.toContain('internal detail'); + // The reader the MCP `run_action` tool answers a throw with agrees. + expect(actionsDoorAnswerOf(err, 'crm_invoice').details).toEqual({ refusals: response.body.error.details.refusals }); + }); + + it('an undeclared listed reason is the 500 fault naming the action, the code and the reason', async () => { + const err = await rejectionOf(boundAction( + "const r = 'gone'; throw { code: 'NOT_SUBMITTED', reasons: [{ reason: 'approved' }, { reason: r }] };", + { refusals: LIST }, + )(actionCtx())); + expect(err).toBeInstanceOf(SandboxError); + expect(err.innerMessage).toBeUndefined(); + expect(err.message).toContain("action 'submit_signoff' threw code 'NOT_SUBMITTED' with reason 'gone'"); + expect(mapDataError(err, 'crm_invoice').status).toBe(500); + }); +}); diff --git a/packages/runtime/src/sandbox/hook-refusal-catalogue.test.ts b/packages/runtime/src/sandbox/hook-refusal-catalogue.test.ts index 9c113ac1791..3515733701f 100644 --- a/packages/runtime/src/sandbox/hook-refusal-catalogue.test.ts +++ b/packages/runtime/src/sandbox/hook-refusal-catalogue.test.ts @@ -10,7 +10,7 @@ */ import { describe, it, expect } from 'vitest'; -import { mapDataError } from '@objectstack/types'; +import { mapDataError, thrownAnswerOf } from '@objectstack/types'; import { hookBodyRunnerFactory, withInProcessHookTitle } from './body-runner.js'; import { QuickJSScriptRunner, SandboxError } from './quickjs-runner.js'; @@ -490,3 +490,158 @@ describe('[#33214] the in-process seam answers the catalogue with the body path\ expect(resolveInProcessHookRefusal({ name: 'plan_gate', refusals: PLAN_REFUSALS } as any, nested, planCtx())).toBe(nested); }); }); + +// ── #36877 (ruling 7178348458 letter A): one throw, several declared reasons ── + +/** A catalogue whose code holds two reasons with params and a closing entry sentence. */ +const LIST_REFUSALS = { + SUBMIT_REFUSED: { + message: 'Nothing was submitted ({{ count }} selected).', + status: 409, + params: ['name', 'count'], + reasons: { + on_report: { message: 'Expense {{ name }} is already on an expense report.' }, + approved: { message: 'Expense {{ name }} is already approved.' }, + }, + }, + PLAIN: { message: 'Refused.' }, +}; + +const LIST_ZH = { + 'hooks.expense_gate.refusals.SUBMIT_REFUSED.message': '未提交任何费用(已选 {{ count }} 条)。', + 'hooks.expense_gate.refusals.SUBMIT_REFUSED.reasons.on_report.message': '费用 {{ name }} 已在报销单上。', + 'hooks.expense_gate.refusals.SUBMIT_REFUSED.reasons.approved.message': '费用 {{ name }} 已审批。', +}; + +function listI18n(): HookRefusalI18nService { + return { t: (key, locale) => (locale === 'zh-CN' ? (LIST_ZH as Record)[key] ?? key : key), getLocales: () => ['en', 'zh-CN'] }; +} + +const LIST_HOOK = { name: 'expense_gate', object: 'expense', events: ['beforeUpdate'], refusals: LIST_REFUSALS }; + +function listBody(source: string) { + return hookBodyRunnerFactory(runner, { ql: {}, appId: 'crm', i18n: () => listI18n() })({ + ...LIST_HOOK, + body: { language: 'js', source, capabilities: [] }, + } as any)!; +} + +function listHandler(handler: (ctx: any) => unknown) { + return withInProcessHookTitle(handler, {}, LIST_HOOK as any, { i18n: () => listI18n() }); +} + +const LIST_THROW = "throw Object.assign(new Error('internal detail'), { code: 'SUBMIT_REFUSED', params: { count: 3 }, " + + "reasons: [{ reason: 'on_report', params: { name: 'Taxi 12' } }, { reason: 'approved', params: { name: 'Hotel 7' } }] });"; +const listCtx = (locale?: string) => ({ + object: 'expense', event: 'beforeUpdate', input: {}, session: locale ? { userId: 'u1', locale } : { userId: 'u1' }, +}); + +describe('[#36877] a reasons list is answered line by line — the body path', () => { + it('each listed sentence in the order thrown, the entry\'s own sentence last, and the list on details.refusals', async () => { + const err = await rejectionOf(listBody(LIST_THROW)(listCtx())); + expect(err).toBeInstanceOf(SandboxError); + const wire = mapDataError(err, 'expense'); + expect(wire.status).toBe(409); + expect(wire.body.declaredCode).toBe('SUBMIT_REFUSED'); + expect(wire.body.userMessage).toBe( + 'Expense Taxi 12 is already on an expense report.\nExpense Hotel 7 is already approved.\nNothing was submitted (3 selected).', + ); + expect(wire.body.details).toEqual({ + refusals: [ + { reason: 'on_report', message: 'Expense Taxi 12 is already on an expense report.' }, + { reason: 'approved', message: 'Expense Hotel 7 is already approved.' }, + ], + }); + expect(JSON.stringify(wire.body)).not.toContain('internal detail'); + }); + + it('every line translated in the caller\'s locale and filled from its own params', async () => { + const err = await rejectionOf(listBody(LIST_THROW)(listCtx('zh-CN'))); + const wire = mapDataError(err, 'expense'); + expect(wire.body.userMessage).toBe('费用 Taxi 12 已在报销单上。\n费用 Hotel 7 已审批。\n未提交任何费用(已选 3 条)。'); + expect((wire.body.details as any).refusals.map((l: any) => l.message)).toEqual(['费用 Taxi 12 已在报销单上。', '费用 Hotel 7 已审批。']); + }); + + it('a list assigned onto the thrown error (`e.reasons = […]`) is read the same way', async () => { + const err = await rejectionOf(listBody( + "const e = new Error('x'); e.code = 'SUBMIT_REFUSED'; e.reasons = [{ reason: 'approved', params: { name: 'A' } }]; throw e;", + )(listCtx())); + expect(mapDataError(err, 'expense').body.userMessage).toBe('Expense A is already approved.\nNothing was submitted ( selected).'); + }); + + it('the /actions and dispatcher composition carries the same list', async () => { + const err = await rejectionOf(listBody(LIST_THROW)(listCtx())); + const answer = thrownAnswerOf(err, 500); + expect(answer.status).toBe(409); + expect(answer.declaredCode).toBe('SUBMIT_REFUSED'); + expect(answer.details).toEqual({ refusals: (mapDataError(err, 'expense').body.details as any).refusals }); + }); +}); + +describe('[#36877] a list the catalogue cannot answer makes the whole throw the loud fault', () => { + const cases: Array<[string, string, string]> = [ + ['an undeclared listed reason (computed)', "const r = 'no' + 'pe'; throw { code: 'SUBMIT_REFUSED', reasons: [{ reason: 'approved' }, { reason: r }] };", "with reason 'nope'"], + ['a listed reason under a code that declares no reasons', "const r = 'appr' + 'oved'; throw { code: 'PLAIN', reasons: [{ reason: r }] };", "code 'PLAIN' with reason 'approved'"], + ['a single reason beside a list', "throw { code: 'SUBMIT_REFUSED', reason: 'approved', reasons: [{ reason: 'approved' }] };", 'both a `reason` and a `reasons` list'], + ['an empty list', "throw { code: 'SUBMIT_REFUSED', reasons: [] };", 'names no reason'], + ['an element with no reason', "throw { code: 'SUBMIT_REFUSED', reasons: [{ reason: 'approved' }, { params: {} }] };", 'not a list of'], + ['a reasons value that is not a list', "throw { code: 'SUBMIT_REFUSED', reasons: 'approved' };", 'not a list of'], + ['an element whose params is a list', "throw { code: 'SUBMIT_REFUSED', reasons: [{ reason: 'approved', params: ['A'] }] };", 'not a list of'], + ]; + it.each(cases)('%s', async (_name, source, text) => { + const err = await rejectionOf(listBody(source)(listCtx())); + expect(err).toBeInstanceOf(SandboxError); + expect(err.innerMessage).toBeUndefined(); + expect(err.message).toContain("hook 'expense_gate' threw code"); + expect(err.message).toContain(text); + const wire = mapDataError(err, 'expense'); + expect(wire.status).toBe(500); + expect(wire.body.userMessage).toBeUndefined(); + expect(wire.body.details).toBeUndefined(); + }); +}); + +describe('[#36877] the in-process handler answers a list byte-identically to the sandboxed body (parity pin)', () => { + const thrownList = () => Object.assign(new Error('internal detail'), { + code: 'SUBMIT_REFUSED', + params: { count: 3 }, + reasons: [{ reason: 'on_report', params: { name: 'Taxi 12' } }, { reason: 'approved', params: { name: 'Hotel 7' } }], + }); + + it.each([undefined, 'zh-CN'])('locale %s: /data envelope and dispatcher answer identical', async (locale) => { + const viaBody = await rejectionOf(listBody(LIST_THROW)(listCtx(locale))); + const viaHandler = await rejectionOf(listHandler(async () => { throw thrownList(); })(listCtx(locale))); + expect(viaHandler).toBeInstanceOf(SandboxError); + expect(JSON.stringify(mapDataError(viaHandler, 'expense'))).toBe(JSON.stringify(mapDataError(viaBody, 'expense'))); + expect(JSON.stringify(thrownAnswerOf(viaHandler, 500))).toBe(JSON.stringify(thrownAnswerOf(viaBody, 500))); + expect((mapDataError(viaHandler, 'expense').body.details as any).refusals).toHaveLength(2); + }); + + it('the same faults: an undeclared listed reason, both forms, an empty list', async () => { + const cases: Array<[() => never, string]> = [ + [() => { throw { code: 'SUBMIT_REFUSED', reasons: [{ reason: 'nope' }] }; }, "with reason 'nope'"], + [() => { throw { code: 'SUBMIT_REFUSED', reason: 'approved', reasons: [{ reason: 'approved' }] }; }, 'both a `reason`'], + [() => { throw { code: 'SUBMIT_REFUSED', reasons: [] }; }, 'names no reason'], + ]; + for (const [thrower, text] of cases) { + const err = await rejectionOf(listHandler(async () => thrower())(listCtx())); + expect(err).toBeInstanceOf(SandboxError); + expect(err.innerMessage).toBeUndefined(); + expect(err.message).toContain(text); + expect(mapDataError(err, 'expense').status).toBe(500); + } + }); + + it('CONTROL: a single declared reason carries no details.refusals on either path', async () => { + const viaBody = await rejectionOf(listBody("throw { code: 'SUBMIT_REFUSED', reason: 'approved', params: { name: 'A' } };")(listCtx())); + const viaHandler = await rejectionOf(listHandler(async () => { + throw { code: 'SUBMIT_REFUSED', reason: 'approved', params: { name: 'A' } }; + })(listCtx())); + for (const err of [viaBody, viaHandler]) { + const wire = mapDataError(err, 'expense'); + expect(wire.body.userMessage).toBe('Expense A is already approved.'); + expect(wire.body.details).toBeUndefined(); + expect(err.refusals).toBeUndefined(); + } + }); +}); diff --git a/packages/runtime/src/sandbox/hook-refusal-catalogue.ts b/packages/runtime/src/sandbox/hook-refusal-catalogue.ts index 1d140e65a29..5f2aba5d103 100644 --- a/packages/runtime/src/sandbox/hook-refusal-catalogue.ts +++ b/packages/runtime/src/sandbox/hook-refusal-catalogue.ts @@ -67,6 +67,15 @@ * error passes through unchanged, as a host-relayed error does on the body * path. * + * **Several reasons in one refusal (#36877, ruling 7178348458 letter A).** A + * throw may name an ordered list of declared reasons instead of one — + * `{ code, reasons: [{ reason, params? }, …] }` — and the answer carries each + * one's sentence in the caller's locale, in the order thrown, the entry's own + * `message` closing it ({@link declaredAnswer}); the lines also ride the error + * as `refusals`, which the doors answer as `details.refusals`. Both paths + * read the address through one function (`refusalAddressFrom`), so a list is + * answered byte-identically on each. + * * A hook that declares no `refusals` is answered exactly as before. */ @@ -76,6 +85,9 @@ import { undeclaredActionRefusalReasonAtRun, undeclaredHookRefusalAtRun, undeclaredHookRefusalReasonAtRun, + unreadableActionRefusalListAtRun, + unreadableHookRefusalListAtRun, + type RefusalListProblem, } from '@objectstack/spec/data'; import { actionRefusalMessageKey, hookRefusalMessageKey, resolveBundleLocale } from '@objectstack/spec/system'; import { templateEngine } from '@objectstack/formula'; @@ -86,6 +98,7 @@ import { isHostRelayedSandboxError, isRelayedSandboxRefusal, isRunnerOwnFault, + refusalAddressFrom, sandboxRefusalAddressOf, type SandboxRefusalAddress, } from './quickjs-runner.js'; @@ -153,6 +166,8 @@ interface RefusalOwner { messageKey(code: string, reason?: string): string; undeclaredAtRun(code: string | undefined, declared: readonly string[]): string; undeclaredReasonAtRun(code: string, reason: string, declared: readonly string[]): string; + /** [#36877] The fault for a `reasons` list the catalogue cannot answer. */ + unreadableListAtRun(code: string, problem: RefusalListProblem): string; } function hookOwner(hookName: string): RefusalOwner { @@ -161,6 +176,7 @@ function hookOwner(hookName: string): RefusalOwner { messageKey: (code, reason) => hookRefusalMessageKey(hookName, code, reason), undeclaredAtRun: (code, declared) => undeclaredHookRefusalAtRun(hookName, code, declared), undeclaredReasonAtRun: (code, reason, declared) => undeclaredHookRefusalReasonAtRun(hookName, code, reason, declared), + unreadableListAtRun: (code, problem) => unreadableHookRefusalListAtRun(hookName, code, problem), }; } @@ -193,6 +209,7 @@ function actionOwner(action: ActionRefusalDeclaration): RefusalOwner { messageKey: (code, reason) => actionRefusalMessageKey(object, name, code, reason), undeclaredAtRun: (code, declared) => undeclaredActionRefusalAtRun(name, code, declared), undeclaredReasonAtRun: (code, reason, declared) => undeclaredActionRefusalReasonAtRun(name, code, reason, declared), + unreadableListAtRun: (code, problem) => unreadableActionRefusalListAtRun(name, code, problem), }; } @@ -374,11 +391,36 @@ function pickTranslatedSentence( return declared; } +/** [#36877] One rendered sentence of a refusal thrown as a `reasons` list — an element of the wire's `details.refusals`. */ +export interface DeclaredRefusalLine { + reason: string; + message: string; +} + +/** What {@link declaredAnswer} answers a declared code with. */ +type DeclaredAnswer = + | { fault: SandboxError } + | { message: string; status: number; refusals?: DeclaredRefusalLine[] }; + /** * 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. + * builds its `SandboxError` from it with the code it read, in one shape. + * + * [#36877, ruling 7178348458 terms 1–3] A throw that names an ordered + * `reasons` list instead of one `reason` is answered line by line: + * + * - every listed reason is checked against the entry's `reasons` — under a + * code that declares none, every one is undeclared — and ONE undeclared + * reason makes the whole throw the loud fault naming it; a list the address + * could not read (beside a `reason`, empty, malformed) is the fault too; + * - each line is that reason's sentence, translated and filled from its own + * `params` exactly as a single reason is; + * - the message (served as the caller sentence and as `userMessage`) is the + * lines joined by `\n`, then the entry's own `message` — translated, its + * holes filled from the throw's top-level `params` — as the last line; + * - `refusals` carries the lines structured (`details.refusals` on the wire). */ function declaredAnswer( owner: RefusalOwner, @@ -387,24 +429,44 @@ function declaredAnswer( address: HookRefusalAddress | undefined, locale: unknown, opts: { i18n?: HookRefusalI18nSource; logger?: { warn?: (...args: any[]) => void } }, -): { fault: SandboxError } | { message: string; status: number } { +): DeclaredAnswer { + const reasons = entry.reasons && typeof entry.reasons === 'object' ? entry.reasons : undefined; + const status = typeof entry.status === 'number' ? entry.status : DEFAULT_HOOK_REFUSAL_STATUS; + const pickedLocale = typeof locale === 'string' ? locale : undefined; + if (address?.listProblem !== undefined) { + return { fault: new SandboxError(owner.unreadableListAtRun(thrownCode, address.listProblem)) }; + } + if (address?.reasons !== undefined) { + for (const line of address.reasons) { + if (!reasons || !Object.prototype.hasOwnProperty.call(reasons, line.reason)) { + return { + fault: new SandboxError(owner.undeclaredReasonAtRun(thrownCode, line.reason, reasons ? Object.keys(reasons) : [])), + }; + } + } + const refusals: DeclaredRefusalLine[] = address.reasons.map((line) => ({ + reason: line.reason, + message: ownerRefusalMessage(owner, thrownCode, entry, pickedLocale, opts.i18n, opts.logger, line), + })); + const closing = ownerRefusalMessage( + owner, + thrownCode, + entry, + pickedLocale, + opts.i18n, + opts.logger, + address.params !== undefined ? { params: address.params } : undefined, + ); + return { message: [...refusals.map((line) => line.message), closing].join('\n'), status, refusals }; + } // 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; - 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(owner.undeclaredReasonAtRun(thrownCode, reason, Object.keys(reasons))) }; } - const message = ownerRefusalMessage( - owner, - thrownCode, - entry, - typeof locale === 'string' ? locale : undefined, - opts.i18n, - opts.logger, - address, - ); - return { message, status: typeof entry.status === 'number' ? entry.status : DEFAULT_HOOK_REFUSAL_STATUS }; + const message = ownerRefusalMessage(owner, thrownCode, entry, pickedLocale, opts.i18n, opts.logger, address); + return { message, status }; } /** @@ -475,7 +537,12 @@ function resolveSandboxedRefusal( } const answer = declaredAnswer(owner, code, entry, sandboxRefusalAddressOf(err), locale, opts); if ('fault' in answer) return answer.fault; - return new SandboxError(err.message, answer.message, { code, status: answer.status, userMessage: answer.message }); + return new SandboxError(err.message, answer.message, { + code, + status: answer.status, + userMessage: answer.message, + ...(answer.refusals !== undefined ? { refusals: answer.refusals } : {}), + }); } // ── The in-process half (#33214, ruling 6879477573 letter A) ───────────────── @@ -650,6 +717,7 @@ export function resolveInProcessHookRefusal( code?: unknown; reason?: unknown; params?: unknown; + reasons?: 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; @@ -657,16 +725,19 @@ export function resolveInProcessHookRefusal( if (code === undefined || !entry) { return new SandboxError(owner.undeclaredAtRun(code, Object.keys(catalogue))); } - const address: HookRefusalAddress = {}; - if (typeof thrown.reason === 'string' && thrown.reason.length > 0) address.reason = thrown.reason; - if (thrown.params !== null && typeof thrown.params === 'object' && !Array.isArray(thrown.params)) { - address.params = thrown.params as Record; - } + // [#36877] The one address reading the body path makes too (`refusalAddressFrom`). + const address = refusalAddressFrom({ + reason: thrown.reason, + params: thrown.params, + reasons: thrown.reasons, + hasReasons: thrown.reasons !== undefined, + }); const answer = declaredAnswer(owner, code, entry, address, engineCtx?.session?.locale, opts); if ('fault' in answer) return answer.fault; return new SandboxError(`hook '${String(hook.name)}' threw: ${flattenThrown(err)}`, answer.message, { code, status: answer.status, userMessage: answer.message, + ...(answer.refusals !== undefined ? { refusals: answer.refusals } : {}), }); } diff --git a/packages/runtime/src/sandbox/quickjs-runner.ts b/packages/runtime/src/sandbox/quickjs-runner.ts index 61b0aae79ad..30e757424e8 100644 --- a/packages/runtime/src/sandbox/quickjs-runner.ts +++ b/packages/runtime/src/sandbox/quickjs-runner.ts @@ -395,8 +395,10 @@ export class QuickJSScriptRunner implements ScriptRunner { try { var __refusalParams; try { __refusalParams = (e && e.params !== undefined) ? JSON.parse(JSON.stringify(e.params)) : undefined; } catch (_) { __refusalParams = undefined; } + var __refusalReasons, __hasReasons = false; + try { __hasReasons = !!e && e.reasons !== undefined; __refusalReasons = __hasReasons ? JSON.parse(JSON.stringify(e.reasons)) : undefined; } catch (_) { __refusalReasons = null; } 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, reason: typeof e.reason === 'string' ? e.reason : undefined, params: __refusalParams }) + ? 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, hasReasons: __hasReasons || undefined, reasons: __hasReasons ? (__refusalReasons === undefined ? null : __refusalReasons) : undefined }) : undefined; } catch (_) { globalThis.__errorInfo = undefined; } try { @@ -2540,6 +2542,15 @@ export class SandboxError extends Error { * body's own throw declared it — the sandbox never invents one. */ readonly userMessage?: string; + /** + * [#36877, ruling 7178348458 term 3] The sentences of a declared refusal + * thrown as a `reasons` list, each rendered in the caller's locale, in the + * order thrown — the wire's `details.refusals` (`declaredRefusalLines` in + * `@objectstack/types` reads it). Set only by the refusal catalogue + * (`hook-refusal-catalogue.ts`), never read off the VM: a body cannot hand + * the wire a list the catalogue did not render. + */ + readonly refusals?: ReadonlyArray<{ reason: string; message: string }>; constructor(message: string, innerMessage?: string, info?: SandboxErrorInfo) { super(message); this.name = 'SandboxError'; @@ -2548,6 +2559,7 @@ export class SandboxError extends Error { if (info?.fields) this.fields = info.fields; if (typeof info?.status === 'number') this.status = info.status; if (info?.userMessage) this.userMessage = info.userMessage; + if (Array.isArray(info?.refusals)) this.refusals = info.refusals; } } @@ -2559,6 +2571,8 @@ export interface SandboxErrorInfo { status?: number; /** [commit 79c46da90] See {@link SandboxError.userMessage}. */ userMessage?: string; + /** [#36877] See {@link SandboxError.refusals}. Never read off the VM's `__errorInfo` channel. */ + refusals?: ReadonlyArray<{ reason: string; message: string }>; /** * [#4431] The error that crossed `__error` was the SANDBOX's own fault — an * unavailable `ctx.api`, a marshalling failure — not @@ -2656,6 +2670,77 @@ export function isRunnerOwnFault(err: unknown): boolean { export interface SandboxRefusalAddress { reason?: string; params?: Record; + /** + * [#36877, ruling 7178348458 term 1] The ordered list of declared sentences + * the throw named instead of one `reason`: `{ code, reasons: [{ reason, + * params? }, …] }`. Present only when the list is readable; `listProblem` + * says why it is not. + */ + reasons?: SandboxRefusalLine[]; + /** [#36877] Why the throw's `reasons` cannot be answered — the run-time fault's subject. */ + listProblem?: 'both' | 'empty' | 'malformed'; +} + +/** [#36877] One sentence of a thrown `reasons` list: a reason and the params its holes name. */ +export interface SandboxRefusalLine { + reason: string; + params?: Record; +} + +/** + * [#36877] The refusal address read off a throw's `reason`, `params` and + * `reasons` — the ONE reading both run paths make (the body path from the + * VM's `__errorInfo` channel, the in-process path off the thrown value), so + * the two cannot read a throw differently (ruling 7178348458 term 4). + * + * - `reason` only as a non-empty string, `params` only as a non-array object + * (unchanged since #33214); + * - `reasons`, when the throw carries the key at all: a non-empty list whose + * every element is `{ reason: non-empty string, params?: non-array object }`; + * anything else is a `listProblem` (`malformed`, `empty`), and a list + * beside a single `reason` is `both` — each the loud fault, never a list + * quietly shortened. + * + * `hasReasons` says the key was present (a value JSON could not carry arrives + * as `null`, which is `malformed`). + */ +export function refusalAddressFrom(raw: { + reason?: unknown; + params?: unknown; + reasons?: unknown; + hasReasons?: boolean; +}): SandboxRefusalAddress | undefined { + const address: SandboxRefusalAddress = {}; + if (typeof raw.reason === 'string' && raw.reason.length > 0) address.reason = raw.reason; + if (isPlainParams(raw.params)) address.params = raw.params; + if (raw.hasReasons) { + const list = raw.reasons; + if (address.reason !== undefined) address.listProblem = 'both'; + else if (!Array.isArray(list)) address.listProblem = 'malformed'; + else if (list.length === 0) address.listProblem = 'empty'; + else { + const lines: SandboxRefusalLine[] = []; + for (const item of list as unknown[]) { + const line = item as { reason?: unknown; params?: unknown } | null; + if (line === null || typeof line !== 'object' || Array.isArray(line) + || typeof line.reason !== 'string' || line.reason.length === 0 + || (line.params !== undefined && !isPlainParams(line.params))) { + address.listProblem = 'malformed'; + break; + } + lines.push(line.params !== undefined ? { reason: line.reason, params: line.params as Record } : { reason: line.reason }); + } + if (address.listProblem === undefined) address.reasons = lines; + } + } + return address.reason !== undefined || address.params !== undefined || address.reasons !== undefined + || address.listProblem !== undefined + ? address + : undefined; +} + +function isPlainParams(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); } /** [#33214] The errors this runner built from a body throw that named a refusal address. */ @@ -2677,18 +2762,19 @@ function readRefusalAddress(vm: QuickJSContext): SandboxRefusalAddress | undefin return undefined; } if (typeof raw !== 'string' || !raw) return undefined; - let parsed: { reason?: unknown; params?: unknown }; + let parsed: { reason?: unknown; params?: unknown; reasons?: unknown; hasReasons?: 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; + if (parsed === null || typeof parsed !== 'object') return undefined; + return refusalAddressFrom({ + reason: parsed.reason, + params: parsed.params, + reasons: parsed.reasons, + hasReasons: parsed.hasReasons === true, + }); } /** [#26170] Read the `__errorFromHost` channel the wrapper's reject handler writes. */ diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 0c9a47c042e..fa1400089ec 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -438,6 +438,7 @@ "HookQuery (type)", "HookRefusal (type)", "HookRefusalSchema (const)", + "HookRefusalThrownReason (interface)", "HookSchema (const)", "HookText (type)", "HookTextReader (type)", @@ -778,6 +779,7 @@ "ReferenceResolutionErrorSchema (const)", "ReferenceResolutionParsed (type)", "ReferenceResolutionSchema (const)", + "RefusalListProblem (type)", "RelatedListEntry (type)", "RelatedListEntryInput (type)", "RelatedListEntryObject (interface)", @@ -1154,6 +1156,7 @@ "isTitleEligible (function)", "isTransferEligible (function)", "isUnboundedAbove (function)", + "isUndeclaredThrownReason (function)", "isUniqueDeclared (function)", "isVirtualSearchField (function)", "judgeImportMappingTarget (function)", @@ -1260,6 +1263,8 @@ "uniqueNullDistinctDivergence (function)", "unknownImportMappingTargets (function)", "unprovisionedInjectedColumns (function)", + "unreadableActionRefusalListAtRun (function)", + "unreadableHookRefusalListAtRun (function)", "urlCredentialQueryParams (function)", "urlUserinfoPassword (function)", "urlUserinfoUsername (function)", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index a5867cd7a04..057c96e7857 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -428,6 +428,7 @@ "HookQuery": "src/data/hook-api.ts#HookQuery (type)", "HookRefusal": "src/data/hook.zod.ts#HookRefusal (type)", "HookRefusalSchema": "src/data/hook.zod.ts#HookRefusalSchema (const)", + "HookRefusalThrownReason": "src/data/hook-refusal-codes.ts#HookRefusalThrownReason (interface)", "HookSchema": "src/data/hook.zod.ts#HookSchema (const)", "HookText": "src/data/hook.zod.ts#HookText (type)", "HookTextReader": "src/data/hook.zod.ts#HookTextReader (type)", @@ -766,6 +767,7 @@ "ReferenceResolutionErrorSchema": "src/data/seed-loader.zod.ts#ReferenceResolutionErrorSchema (const)", "ReferenceResolutionParsed": "src/data/seed-loader.zod.ts#ReferenceResolutionParsed (type)", "ReferenceResolutionSchema": "src/data/seed-loader.zod.ts#ReferenceResolutionSchema (const)", + "RefusalListProblem": "src/data/hook-refusal-codes.ts#RefusalListProblem (type)", "RelatedListEntry": "src/data/object.zod.ts#RelatedListEntry (type)", "RelatedListEntryInput": "src/data/related-list-entry.ts#RelatedListEntryInput (type)", "RelatedListEntryObject": "src/data/related-list-entry.ts#RelatedListEntryObject (interface)", @@ -1139,6 +1141,7 @@ "isTitleEligible": "src/data/display-name.ts#isTitleEligible (function)", "isTransferEligible": "src/data/user-action-transfer.ts#isTransferEligible (function)", "isUnboundedAbove": "src/data/calendar-day.ts#isUnboundedAbove (function)", + "isUndeclaredThrownReason": "src/data/hook-refusal-codes.ts#isUndeclaredThrownReason (function)", "isUniqueDeclared": "src/data/field.zod.ts#isUniqueDeclared (function)", "isVirtualSearchField": "src/data/search-fields.ts#isVirtualSearchField (function)", "judgeImportMappingTarget": "src/data/import-mapping-target.ts#judgeImportMappingTarget (function)", @@ -1245,6 +1248,8 @@ "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)", + "unreadableActionRefusalListAtRun": "src/data/hook-refusal-codes.ts#unreadableActionRefusalListAtRun (function)", + "unreadableHookRefusalListAtRun": "src/data/hook-refusal-codes.ts#unreadableHookRefusalListAtRun (function)", "urlCredentialQueryParams": "src/data/driver/common.zod.ts#urlCredentialQueryParams (function)", "urlUserinfoPassword": "src/data/driver/common.zod.ts#urlUserinfoPassword (function)", "urlUserinfoUsername": "src/data/driver/common.zod.ts#urlUserinfoUsername (function)", diff --git a/packages/spec/src/data/hook-refusal-codes.ts b/packages/spec/src/data/hook-refusal-codes.ts index c25b9072dcc..c72c4aee1a3 100644 --- a/packages/spec/src/data/hook-refusal-codes.ts +++ b/packages/spec/src/data/hook-refusal-codes.ts @@ -42,9 +42,11 @@ const CODE_LITERAL = String.raw`(?['"\x60])(?[A-Z][A-Z0-9]*(?:_[A-Z /** * 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. + * name like every other key an author declares under a code. A client + * branches on the code, not on a reason: a reason reaches the wire only as the + * label of a rendered line (`details.refusals[].reason`, #36877), beside the + * sentence it picked. 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]+)*$/; @@ -66,6 +68,17 @@ const REASON_ASSIGNMENT = new RegExp( 'g', ); +/** + * [#36877] `reasons: [` — the opening of the list a `throw`'s object literal + * carries (`{ code, reasons: [{ reason, params? }, …] }`); the reasons inside + * the bracket are the listed ones. Read only as a direct member of the thrown + * object literal ({@link listedSpans}). + */ +const REASONS_LIST_PROPERTY = /(?[A-Za-z_$][\w$]*)\s*\.\s*reasons\s*=(?!=)\s*\[/g; + /** `code: 'X'` — the property in an object literal a `throw` builds. */ const CODE_PROPERTY = new RegExp(String.raw`(? { + const spans: Array<[number, number]> = []; + for (const m of statement.matchAll(REASONS_LIST_PROPERTY)) { + const at = m.index ?? 0; + const enclosing = openBracketsAt(statement, at); + const direct = + enclosing[enclosing.length - 1] === '{' && + enclosing.filter((ch) => ch === '{').length === 1 && + !enclosing.includes('['); + if (!direct) continue; + const open = at + m[0].length - 1; + spans.push([open, closeOfBracket(statement, open)]); + } + return spans; +} + /** The identifier a `throw` statement throws, when it throws a bare name. */ function thrownBinding(statement: string): string | undefined { const m = /^\s*([A-Za-z_$][\w$]*)\s*$/.exec(statement); @@ -197,28 +274,49 @@ export function hookRefusalCodesThrownIn(source: string): string[] { return [...codes]; } +/** + * One `(code, reason)` pair a source throws literally. `listed` marks a reason + * read from a `reasons` list (#36877): a listed reason is judged under every + * declared code, also one that declares no `reasons` (where it is undeclared), + * because the list is new and nothing that saves today throws one. + */ +export interface HookRefusalThrownReason { + code: string; + reason: string; + listed?: true; +} + /** * The `(code, reason)` pairs a hook's source throws LITERALLY (#33214), in * first-seen order — the reason half of {@link hookRefusalCodesThrownIn}, read * the same two ways: * * - a `reason: 'x'` property inside a `throw` statement that also names - * exactly one code literally: `throw { code: 'X', reason: 'x' }`; + * exactly one code literally: `throw { code: 'X', reason: 'x' }` — and, + * marked `listed` (#36877, ruling 7178348458 term 2), each one inside its + * `reasons` list: `throw { code: 'X', reasons: [{ reason: 'x' }, …] }`; * - `e.reason = 'x'` on a name some `throw` statement throws bare, paired - * with that name's literal `e.code = 'X'`. + * with that name's literal `e.code = 'X'` — and, marked `listed`, each + * `reason: 'x'` inside `e.reasons = [ … ]` on such a name. * - * A reason with no literal code beside it, or one that arrives any other way, - * is left to the run-time refusal. + * A reason with no literal code beside it, or one that arrives any other way + * (a list built in a variable, a computed reason), is left to the run-time + * refusal. */ -export function hookRefusalReasonsThrownIn(source: string): Array<{ code: string; reason: string }> { - const found: Array<[string, string]> = []; +export function hookRefusalReasonsThrownIn(source: string): HookRefusalThrownReason[] { + const found: HookRefusalThrownReason[] = []; 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 [only] = codes; - for (const m of statement.matchAll(REASON_PROPERTY)) found.push([only!, m.groups!.reason]); + const spans = listedSpans(statement); + for (const m of statement.matchAll(REASON_PROPERTY)) { + const at = m.index ?? 0; + const listed = spans.some(([from, to]) => at > from && at < to); + found.push(listed ? { code: only!, reason: m.groups!.reason, listed: true } : { code: only!, reason: m.groups!.reason }); + } } const binding = thrownBinding(statement); if (binding) thrownNames.add(binding); @@ -229,18 +327,40 @@ export function hookRefusalReasonsThrownIn(source: string): Array<{ code: string } for (const m of masked.matchAll(REASON_ASSIGNMENT)) { const bound = codeOf.get(m.groups!.binding); - if (bound !== undefined) found.push([bound, m.groups!.reason]); + if (bound !== undefined) found.push({ code: bound, reason: m.groups!.reason }); } - const pairs: Array<{ code: string; reason: string }> = []; + for (const m of masked.matchAll(REASONS_LIST_ASSIGNMENT)) { + const bound = codeOf.get(m.groups!.binding); + if (bound === undefined) continue; + const open = (m.index ?? 0) + m[0].length - 1; + const list = masked.slice(open, closeOfBracket(masked, open)); + for (const r of list.matchAll(REASON_PROPERTY)) found.push({ code: bound, reason: r.groups!.reason, listed: true }); + } + const pairs: HookRefusalThrownReason[] = []; const seen = new Set(); - for (const [code, reason] of found) { - if (seen.has(`${code}.${reason}`)) continue; - seen.add(`${code}.${reason}`); - pairs.push({ code, reason }); + for (const pair of found) { + const key = `${pair.code}.${pair.reason}.${pair.listed === true}`; + if (seen.has(key)) continue; + seen.add(key); + pairs.push(pair); } return pairs; } +/** + * [#36877] Whether a literal pair names a reason the code's catalogue entry + * does not declare, as both save checks (a hook's, an action's) judge it: a + * single `reason` is read only under a code that declares `reasons` (as before + * the list existed); a listed one under every code. + */ +export function isUndeclaredThrownReason( + pair: HookRefusalThrownReason, + reasons: Record | undefined, +): boolean { + if (!reasons) return pair.listed === true; + return !Object.prototype.hasOwnProperty.call(reasons, pair.reason); +} + /** The declared codes, as the sentence lists them. */ function declaredList(declared: readonly string[]): string { return declared.length > 0 ? declared.map((c) => `'${c}'`).join(', ') : 'none'; @@ -407,6 +527,49 @@ function undeclaredRefusalReasonAtRun( ); } +/** + * [#36877, ruling 7178348458 terms 1 and 2] What is wrong with a `reasons` + * list a body threw beside a declared code, so the throw cannot be answered: + * + * - `both`: the throw carries a single `reason` AND a `reasons` list; + * - `empty`: the list names no reason; + * - `malformed`: `reasons` is not a list, or an element is not + * `{ reason: 'snake_case', params?: { … } }`. + */ +export type RefusalListProblem = 'both' | 'empty' | 'malformed'; + +/** + * The run-time fault for a declared code a hook threw with a `reasons` list + * the catalogue cannot answer ({@link RefusalListProblem}). Fault text, like + * {@link undeclaredHookRefusalAtRun}. + */ +export function unreadableHookRefusalListAtRun(hookName: string, code: string, problem: RefusalListProblem): string { + return unreadableRefusalListAtRun('hook', hookName, code, problem); +} + +/** [#36877] The action twin of {@link unreadableHookRefusalListAtRun}. */ +export function unreadableActionRefusalListAtRun(actionName: string, code: string, problem: RefusalListProblem): string { + return unreadableRefusalListAtRun('action', actionName, code, problem); +} + +function unreadableRefusalListAtRun( + subject: RefusalSubject, + name: string, + code: string, + problem: RefusalListProblem, +): string { + const what = problem === 'both' + ? 'with both a `reason` and a `reasons` list' + : problem === 'empty' + ? 'with a `reasons` list that names no reason' + : 'with a `reasons` value that is not a list of `{ reason, params? }`'; + return ( + `${subject} '${name}' threw code '${code}' ${what}, so the refusal cannot be answered. A throw names one ` + + `declared sentence (\`{ code, reason, params }\`) or an ordered list of them (\`{ code, reasons: [{ reason, ` + + 'params }, …] }`), each reason one the code declares under `reasons`, never both.' + ); +} + /* * ── A hook's declared texts (#34374, ruling 6913660232 parameter 7) ───────── * diff --git a/packages/spec/src/data/hook-refusals.test.ts b/packages/spec/src/data/hook-refusals.test.ts index 16f1b2f3c0d..044204031cb 100644 --- a/packages/spec/src/data/hook-refusals.test.ts +++ b/packages/spec/src/data/hook-refusals.test.ts @@ -7,7 +7,9 @@ import { hookRefusalsWithoutSandboxedBody, HOOK_REFUSAL_REASON_PATTERN, hookRefusalReasonsThrownIn, + isUndeclaredThrownReason, undeclaredHookRefusalAtRun, + unreadableHookRefusalListAtRun, undeclaredHookRefusalCodeAtSave, undeclaredHookRefusalReasonAtRun, undeclaredHookRefusalReasonAtSave, @@ -474,3 +476,119 @@ describe('hookForm refusals row — help names every hook kind that may declare expect(help('handler')).not.toBe(''); }); }); + +// #36877 (ruling 7178348458 letter A): one throw names an ordered list of +// declared reasons, `{ code, reasons: [{ reason, params? }, …] }`. +describe('hookRefusalReasonsThrownIn — the reasons of a thrown list (#36877)', () => { + it.each([ + [ + "throw { code: 'SUBMIT_REFUSED', reasons: [{ reason: 'on_report', params: { name } }, { reason: 'approved' }] };", + [{ code: 'SUBMIT_REFUSED', reason: 'on_report', listed: true }, { code: 'SUBMIT_REFUSED', reason: 'approved', listed: true }], + ], + [ + "const e = new Error('x'); e.code = 'SUBMIT_REFUSED'; e.reasons = [{ reason: 'approved' }]; throw e;", + [{ code: 'SUBMIT_REFUSED', reason: 'approved', listed: true }], + ], + [ + // a single reason beside a list: each read as what it is + "throw { code: 'C', reason: 'r', reasons: [{ reason: 'l' }] };", + [{ code: 'C', reason: 'r' }, { code: 'C', reason: 'l', listed: true }], + ], + [ + // the list as a direct member of the object Object.assign stamps + "throw Object.assign(new Error('x'), { code: 'C', reasons: [{ reason: 'l' }] });", + [{ code: 'C', reason: 'l', listed: true }], + ], + [ + // CONTROL: a `reasons` key nested under `params` is not the thrown list + // (the run reads `e.reasons` only), so its reason is read as main reads + // any `reason: 'x'` in the statement: a single, unlisted pair + "throw { code: 'C', params: { reasons: [{ reason: 'late' }] } };", + [{ code: 'C', reason: 'late' }], + ], + ])('reads %j', (source, pairs) => { + expect(hookRefusalReasonsThrownIn(source)).toEqual(pairs); + }); + + it.each([ + // a list built in a variable is the run-time refusal's + "const lines = [{ reason: 'r' }]; throw { code: 'C', reasons: lines };", + // a list on a name nobody throws + "const e = {}; e.code = 'C'; e.reasons = [{ reason: 'r' }]; return e;", + // inside a string or a comment + "// throw { code: 'C', reasons: [{ reason: 'r' }] }\nreturn;", + ])('reads nothing in %j', (source) => { + expect(hookRefusalReasonsThrownIn(source)).toEqual([]); + }); + + it('isUndeclaredThrownReason: a listed reason is judged under every code, a single one only under a code with reasons', () => { + expect(isUndeclaredThrownReason({ code: 'C', reason: 'r', listed: true }, undefined)).toBe(true); + expect(isUndeclaredThrownReason({ code: 'C', reason: 'r' }, undefined)).toBe(false); + expect(isUndeclaredThrownReason({ code: 'C', reason: 'r', listed: true }, { r: {} })).toBe(false); + expect(isUndeclaredThrownReason({ code: 'C', reason: 'x', listed: true }, { r: {} })).toBe(true); + }); + + it('the run-time list fault names the hook, the code and what is wrong', () => { + expect(unreadableHookRefusalListAtRun('expense_gate', 'SUBMIT_REFUSED', 'both')).toContain( + "hook 'expense_gate' threw code 'SUBMIT_REFUSED' with both a `reason` and a `reasons` list", + ); + expect(unreadableHookRefusalListAtRun('expense_gate', 'SUBMIT_REFUSED', 'empty')).toContain('names no reason'); + expect(unreadableHookRefusalListAtRun('expense_gate', 'SUBMIT_REFUSED', 'malformed')).toContain('not a list of'); + }); +}); + +describe('Hook.refusals — a listed reason is refused at save where the body names it literally (#36877)', () => { + const refusals = { + SUBMIT_REFUSED: { + message: 'Nothing was submitted.', + reasons: { on_report: { message: 'Already on a report.' }, approved: { message: 'Already approved.' } }, + }, + PLAIN: { message: 'Refused.' }, + }; + + it('accepts a list of declared reasons', () => { + const r = HookSchema.safeParse({ + ...base, + body: body("throw { code: 'SUBMIT_REFUSED', reasons: [{ reason: 'on_report' }, { reason: 'approved' }] };"), + refusals, + }); + expect(r.success).toBe(true); + }); + + it('refuses an undeclared listed reason at body.source, one issue, naming the declared reasons', () => { + const r = HookSchema.safeParse({ + ...base, + body: body("throw { code: 'SUBMIT_REFUSED', reasons: [{ reason: 'approved' }, { reason: 'missing' }] };"), + refusals, + }); + expect(r.success).toBe(false); + const issues = r.error!.issues; + expect(issues).toHaveLength(1); + expect(issues[0]!.path).toEqual(['body', 'source']); + expect(issues[0]!.message).toBe(undeclaredHookRefusalReasonAtSave('SUBMIT_REFUSED', 'missing', ['on_report', 'approved'], 'body.source')); + }); + + it('refuses a listed reason under a code that declares no reasons (declared: none)', () => { + const r = HookSchema.safeParse({ + ...base, + body: body("const e = new Error('x'); e.code = 'PLAIN'; e.reasons = [{ reason: 'approved' }]; throw e;"), + refusals, + }); + expect(r.success).toBe(false); + expect(r.error!.issues[0]!.message).toContain('(declared: none)'); + }); + + it('CONTROL: a `reasons` list nested under `params` is not a thrown list, so it saves under a code with no reasons', () => { + const r = HookSchema.safeParse({ + ...base, + body: body("throw { code: 'PLAIN', params: { reasons: [{ reason: 'late' }] } };"), + refusals, + }); + expect(r.success).toBe(true); + }); + + it('CONTROL: a single reason under a code that declares no reasons still saves, as before', () => { + const r = HookSchema.safeParse({ ...base, body: body("throw { code: 'PLAIN', reason: 'anything' };"), refusals }); + expect(r.success).toBe(true); + }); +}); diff --git a/packages/spec/src/data/hook.zod.ts b/packages/spec/src/data/hook.zod.ts index 66a7c022b6f..e412970962f 100644 --- a/packages/spec/src/data/hook.zod.ts +++ b/packages/spec/src/data/hook.zod.ts @@ -34,6 +34,7 @@ import { HOOK_TEXT_KEY_PATTERN, hookRefusalCodesThrownIn, hookRefusalReasonsThrownIn, + isUndeclaredThrownReason, hookRefusalsWithoutSandboxedBody, hookTextKeysAskedIn, hookTextsWithoutRunnableCode, @@ -253,8 +254,11 @@ function refuseHookBodyMailGrant( * 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 that declares `reasons` (#33214, - * `hookRefusalReasonsThrownIn`); under a code that declares none, a thrown - * `reason` is not read at all, as before. + * `hookRefusalReasonsThrownIn`); under a code that declares none, a single + * thrown `reason` is not read at all, as before. A reason inside a `reasons` + * list (#36877, ruling 7178348458) is read under every code: under one that + * declares no `reasons`, every listed reason is undeclared and the save + * refuses it (`isUndeclaredThrownReason`). * * [#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 @@ -319,17 +323,19 @@ function refuseUndeclaredLiteralRefusalCode( 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)) { + for (const pair of hookRefusalReasonsThrownIn(read.source)) { + const { code, reason } = pair; if (!Object.prototype.hasOwnProperty.call(hook.refusals, code)) 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. + // A single `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. A reason in a `reasons` list (#36877) is judged under every code. const reasons = hook.refusals[code]?.reasons; - if (!reasons || Object.prototype.hasOwnProperty.call(reasons, reason)) continue; + if (!isUndeclaredThrownReason(pair, reasons)) continue; ctx.addIssue({ code: 'custom', path, - message: undeclaredHookRefusalReasonAtSave(code, reason, Object.keys(reasons), read.at), + message: undeclaredHookRefusalReasonAtSave(code, reason, Object.keys(reasons ?? {}), read.at), }); } } diff --git a/packages/spec/src/migrations/entries/semantic/18.refusal-reasons-list-literal-judged.ts b/packages/spec/src/migrations/entries/semantic/18.refusal-reasons-list-literal-judged.ts new file mode 100644 index 00000000000..0a90b8bda7d --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.refusal-reasons-list-literal-judged.ts @@ -0,0 +1,29 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +export const entry: SemanticMigration = { + id: 'refusal-reasons-list-literal-judged', + surface: 'a hook `body.source` or a `script` action `body.source` whose `throw` carries a `reasons` key beside a ' + + 'code its `refusals` catalogue declares: `throw { code, reasons: [ … ] }`, or `e.reasons = [ … ]` on an error ' + + 'the body throws', + replacement: 'name in `reasons` only reasons the code declares under `refusals..reasons`, each as ' + + '`{ reason, params? }` (declare `reasons` on the code, with each sentence, where it has none); or rename a ' + + "`reasons` property the body uses for its own data (for example to `items`, or put it under `params`).", + reason: + 'A refusal may now name an ordered list of declared reasons in one throw, `{ code, reasons: [{ reason, params? }, ' + + "… ] }`, each rendered in the caller's locale as one line of `userMessage` and of `details.refusals`. Before, a " + + '`reasons` key on a thrown refusal was ignored and the code\'s own sentence answered. Now it is read: at save, a ' + + 'literal list naming a reason under a code that declares no `reasons` is refused at `body.source` (a literal ' + + 'reason the code does not declare under its `reasons` was already refused), and so is a literal ' + + '`e.reasons = [ … ]` list on a thrown error naming an undeclared reason. At run, a `reasons` value that is empty, ' + + 'not a list of `{ reason, params? }`, thrown beside a `reason`, or naming an undeclared reason is the loud 500 ' + + 'fault naming the hook or action and the code, where the declared sentence and status answered before. Only a ' + + '`reasons` key that is a direct member of the thrown object is read; a nested one (`params: { reasons }`) is ' + + 'the body\'s own data. There is no mechanical rewrite: whether the key was meant as the list or as the body\'s ' + + 'own property is the author\'s call.', + acceptanceCriteria: + 'Every hook and `script` action that declares `refusals` saves (`os validate` reports no undeclared-reason issue ' + + 'at `body.source`), and no run of it answers the 500 refusal-list fault: every thrown `reasons` key is a ' + + 'non-empty list of reasons its code declares, with no `reason` beside it.', +}; diff --git a/packages/spec/src/ui/action-refusals.test.ts b/packages/spec/src/ui/action-refusals.test.ts index 27354c86476..8f5a9e86f11 100644 --- a/packages/spec/src/ui/action-refusals.test.ts +++ b/packages/spec/src/ui/action-refusals.test.ts @@ -10,6 +10,7 @@ import { undeclaredActionRefusalCodeAtSave, undeclaredActionRefusalReasonAtRun, undeclaredActionRefusalReasonAtSave, + unreadableActionRefusalListAtRun, undeclaredHookRefusalAtRun, undeclaredHookRefusalCodeAtSave, } from '../data/hook-refusal-codes'; @@ -266,3 +267,56 @@ describe('the translation address — beside the action\'s other copy', () => { expect(issuesOf(r).find((i) => /unrecognized|rename|→/.test(i.message))?.message).toContain('`refusal` → `refusals`'); }); }); + +// #36877 (ruling 7178348458 letter A): an action refusing a whole selection +// names an ordered list of declared reasons in one throw. +describe('Action.refusals — a listed reason is refused at save where the body names it literally (#36877)', () => { + const refusals = { + NOT_DRAFT: { message: 'Only a draft invoice can be signed off.' }, + STAGE_LOCKED: { message: 'Nothing changed.', reasons: { closed: { message: 'Closed.' }, won: { message: 'Won.' } } }, + }; + + it('CONTROL: accepts a list of declared reasons', () => { + expect(ActionSchema.safeParse({ + ...base, + body: body("throw { code: 'STAGE_LOCKED', reasons: [{ reason: 'closed' }, { reason: 'won' }] };"), + refusals, + }).success).toBe(true); + }); + + it('refuses an undeclared listed reason at `body.source`', () => { + const r = ActionSchema.safeParse({ + ...base, + body: body("throw { code: 'STAGE_LOCKED', reasons: [{ reason: 'closed' }, { reason: 'lost' }] };"), + refusals, + }); + expect(r.success).toBe(false); + const issue = issuesOf(r).find((i) => i.path.join('.') === 'body.source'); + expect(issue?.message).toBe(undeclaredActionRefusalReasonAtSave('STAGE_LOCKED', 'lost', ['closed', 'won'])); + }); + + it('refuses a listed reason under a code that declares no reasons', () => { + const r = ActionSchema.safeParse({ + ...base, + body: body("throw { code: 'NOT_DRAFT', reasons: [{ reason: 'closed' }] };"), + refusals, + }); + expect(r.success).toBe(false); + const issue = issuesOf(r).find((i) => i.path.join('.') === 'body.source'); + expect(issue?.message).toBe(undeclaredActionRefusalReasonAtSave('NOT_DRAFT', 'closed', [])); + }); + + it('CONTROL: a `reasons` list nested under `params` is not a thrown list, so it saves under a code with no reasons', () => { + expect(ActionSchema.safeParse({ + ...base, + body: body("throw { code: 'NOT_DRAFT', params: { reasons: [{ reason: 'closed' }] } };"), + refusals, + }).success).toBe(true); + }); + + it('the run-time list fault names the action', () => { + expect(unreadableActionRefusalListAtRun('submit_signoff', 'STAGE_LOCKED', 'empty')).toContain( + "action 'submit_signoff' threw code 'STAGE_LOCKED' with a `reasons` list that names no reason", + ); + }); +}); diff --git a/packages/spec/src/ui/action.zod.ts b/packages/spec/src/ui/action.zod.ts index 5e1bbde631a..91fe35a5061 100644 --- a/packages/spec/src/ui/action.zod.ts +++ b/packages/spec/src/ui/action.zod.ts @@ -65,6 +65,7 @@ import { actionTextsWithoutRunnableCode, hookRefusalCodesThrownIn, hookRefusalReasonsThrownIn, + isUndeclaredThrownReason, hookTextKeysAskedIn, undeclaredActionRefusalCodeAtSave, undeclaredActionRefusalReasonAtSave, @@ -2779,15 +2780,17 @@ function refuseUndeclaredLiteralActionRefusalCode( if (Object.prototype.hasOwnProperty.call(data.refusals, code)) continue; ctx.addIssue({ code: 'custom', path: ['body', 'source'], message: undeclaredActionRefusalCodeAtSave(code, declared) }); } - for (const { code, reason } of hookRefusalReasonsThrownIn(source)) { + for (const pair of hookRefusalReasonsThrownIn(source)) { + const { code, reason } = pair; if (!Object.prototype.hasOwnProperty.call(data.refusals, code)) continue; - // Read only under a code that declares `reasons`, as on a hook. + // A single reason is read only under a code that declares `reasons`, a + // listed one (#36877) under every code, as on a hook. const reasons = data.refusals[code]?.reasons; - if (!reasons || Object.prototype.hasOwnProperty.call(reasons, reason)) continue; + if (!isUndeclaredThrownReason(pair, reasons)) continue; ctx.addIssue({ code: 'custom', path: ['body', 'source'], - message: undeclaredActionRefusalReasonAtSave(code, reason, Object.keys(reasons)), + message: undeclaredActionRefusalReasonAtSave(code, reason, Object.keys(reasons ?? {})), }); } } diff --git a/packages/types/src/data-error-classification.ts b/packages/types/src/data-error-classification.ts index 7b7c8d7799f..c86fa23930f 100644 --- a/packages/types/src/data-error-classification.ts +++ b/packages/types/src/data-error-classification.ts @@ -33,6 +33,7 @@ import { demotedDeclaredCode, declaredUserMessage, declaredRefusalMessage, + declaredRefusalLines, packageScopedRefusalCandidates, UNDECLARED_HOOK_REFUSAL_CODE, } from './thrown-http-error.js'; @@ -603,7 +604,29 @@ function withDeclaredUserMessage( const headed = withRefusalHeadAnswer(error, mapped); const userMessage = boundedDeclaredUserMessage(error); if (userMessage === undefined) return headed; - return { status: headed.status, body: { ...headed.body, userMessage } }; + return { status: headed.status, body: { ...withDeclaredRefusalLines(error, headed.body), userMessage } }; +} + +/** + * [#36877, ruling 7178348458 term 3] A declared refusal thrown as a `reasons` + * list carries its sentences as `details.refusals` on this door too, riding + * with the `userMessage` that joins them ({@link declaredRefusalLines}, the + * one recogniser the dispatcher's composition reads). `userMessage` is bounded + * at {@link CLIENT_MESSAGE_MAX} (#5423) and the list is not: each listed + * reason's line stays whole on `details.refusals`. The closing line — the + * code's own `message`, the last line of `userMessage` — is not on the list, + * so on a list long enough to cut it, this door carries it nowhere. `details` + * is merged, so a member another arm set is kept; a body with no list is + * returned as it was. + */ +function withDeclaredRefusalLines(error: unknown, body: Record): Record { + const refusals = declaredRefusalLines(error); + if (refusals === undefined) return body; + const details = body.details; + const kept = details !== null && typeof details === 'object' && !Array.isArray(details) + ? details as Record + : {}; + return { ...body, details: { ...kept, refusals } }; } /** diff --git a/packages/types/src/thrown-http-error.test.ts b/packages/types/src/thrown-http-error.test.ts index 3fcb5b0c368..706bc56765e 100644 --- a/packages/types/src/thrown-http-error.test.ts +++ b/packages/types/src/thrown-http-error.test.ts @@ -13,7 +13,7 @@ // side-channel, because all three call this function. import { describe, it, expect } from 'vitest'; -import { declaredUserMessage, packageScopedRefusalCandidates, resolveThrownHttpError } from './thrown-http-error.js'; +import { declaredRefusalLines, declaredUserMessage, packageScopedRefusalCandidates, resolveThrownHttpError } from './thrown-http-error.js'; import { thrownAnswerOf } from './actions-door-answer.js'; import { mapDataError } from './data-error-classification.js'; @@ -204,3 +204,49 @@ describe('[#32250] resolveThrownHttpError carries a package-scoped refusal\'s ca expect(resolveThrownHttpError(thrown).details).toEqual({ issues: [{ path: ['x'], message: 'y' }], candidates: CANDIDATES }); }); }); + +describe('[#36877] declaredRefusalLines — a declared refusal thrown as a reasons list', () => { + const LINES = [ + { reason: 'on_report', message: '费用 Taxi 12 已在报销单上。' }, + { reason: 'approved', message: '费用 Hotel 7 已审批。' }, + ]; + const refusal = (extra: Record = {}) => Object.assign(new Error('x'), { + code: 'SUBMIT_REFUSED', + status: 409, + userMessage: `${LINES[0]!.message}\n${LINES[1]!.message}\n未提交任何费用。`, + refusals: LINES, + ...extra, + }); + + it('reads the lines off a refusal that carries them beside its userMessage', () => { + expect(declaredRefusalLines(refusal())).toEqual(LINES); + }); + + it.each([ + ['no userMessage', { userMessage: undefined }], + ['an empty list', { refusals: [] }], + ['not a list', { refusals: { reason: 'a', message: 'b' } }], + ['an element missing its message', { refusals: [{ reason: 'a' }] }], + ['an element whose reason is not a string', { refusals: [{ reason: 1, message: 'b' }] }], + ])('answers no list for %s', (_name, extra) => { + expect(declaredRefusalLines(refusal(extra))).toBeUndefined(); + }); + + it('copies only reason and message', () => { + const [first] = declaredRefusalLines(refusal({ refusals: [{ reason: 'a', message: 'b', secret: 'host' }] }))!; + expect(first).toEqual({ reason: 'a', message: 'b' }); + }); + + it('every door carries it as details.refusals: the dispatcher composition and the /data classification', () => { + expect(resolveThrownHttpError(refusal(), 500).details).toEqual({ refusals: LINES }); + expect(thrownAnswerOf(refusal(), 500).details).toEqual({ refusals: LINES }); + const data = mapDataError(refusal(), 'expense'); + expect(data.status).toBe(409); + expect(data.body.details).toEqual({ refusals: LINES }); + }); + + it('CONTROL: a refusal with no list carries no details on either door', () => { + expect(resolveThrownHttpError(refusal({ refusals: undefined }), 500).details).toBeUndefined(); + expect(mapDataError(refusal({ refusals: undefined }), 'expense').body.details).toBeUndefined(); + }); +}); diff --git a/packages/types/src/thrown-http-error.ts b/packages/types/src/thrown-http-error.ts index cdde14b75cf..fe6ac1912ea 100644 --- a/packages/types/src/thrown-http-error.ts +++ b/packages/types/src/thrown-http-error.ts @@ -196,7 +196,8 @@ export interface ThrownHttpError { /** * Structured context: spec-validation `issues[]`, record-validation * `fields[]`, a package-scoped refusal's `candidates[]` (#32250, - * {@link packageScopedRefusalCandidates}). Absent rather than `{}` when the + * {@link packageScopedRefusalCandidates}), a declared refusal list's + * `refusals[]` (#36877, {@link declaredRefusalLines}). Absent rather than `{}` when the * throw carried none, so an empty object never reads as "there is context * here". */ @@ -275,6 +276,46 @@ function isPackageScopedRefusalHolder(candidate: unknown): candidate is PackageS } } +/** [#36877] One sentence of a declared refusal thrown as a list: the reason and its rendered sentence. */ +export interface DeclaredRefusalLine { + readonly reason: string; + readonly message: string; +} + +/** + * [#36877, ruling 7178348458 term 3] The sentences of a declared refusal + * thrown as a `reasons` list, as every door answers them in + * `details.refusals` — or `undefined` for any other thrown value. + * + * The runtime's refusal catalogue (`hook-refusal-catalogue.ts` in + * `@objectstack/runtime`) renders each listed reason in the caller's locale + * and sets them on the refusal it throws as `refusals`, beside the + * `userMessage` that joins them. Recognised by SHAPE — a non-empty list whose + * every element is `{ reason: string, message: string }`, on an error that + * also carries a declared `userMessage` ({@link declaredUserMessage}) — + * because this package depends on nothing but `@objectstack/spec` and cannot + * name the runtime's class (the {@link packageScopedRefusalCandidates} + * precedent). A list with any element of another shape is answered as no + * list. Read here, by {@link resolveThrownHttpError} and by the `/data` + * classification's `userMessage` rider, so no door carries a second + * recogniser. Each element is copied to exactly those two members. + */ +export function declaredRefusalLines(error: unknown): readonly DeclaredRefusalLine[] | undefined { + if (typeof error !== 'object' || error === null) return undefined; + if (declaredUserMessage(error) === undefined) return undefined; + const list: unknown = (error as { refusals?: unknown }).refusals; + if (!Array.isArray(list) || list.length === 0) return undefined; + const lines: DeclaredRefusalLine[] = []; + for (const item of list as unknown[]) { + const line = item as { reason?: unknown; message?: unknown } | null; + if (line === null || typeof line !== 'object' || typeof line.reason !== 'string' || typeof line.message !== 'string') { + return undefined; + } + lines.push({ reason: line.reason, message: line.message }); + } + return lines; +} + /** * Resolve a thrown error into the status, code, message and structured context * an HTTP boundary should answer with. @@ -289,7 +330,7 @@ function isPackageScopedRefusalHolder(candidate: unknown): candidate is PackageS * | declaredCode | `VALIDATION_FAILED` if it is one → any non-empty string `.code` → the derived code if it is an unevaluable hook condition → absent | * | message | `.message` when it is a string → `String(error)` | * | userMessage | a non-empty string `.userMessage` → absent (see {@link declaredUserMessage}) | - * | details | a non-string `.code`, `.issues`, a validation failure's `fields`, a package-scoped refusal's `candidates` → absent | + * | details | a non-string `.code`, `.issues`, a validation failure's `fields`, a package-scoped refusal's `candidates`, a declared refusal list's `refusals` ({@link declaredRefusalLines}) → absent | * * Both status spellings are read because both are produced in this repo: * `plugin-approvals`' lifecycle hooks and `metadata-protocol` throw @@ -351,6 +392,8 @@ export function resolveThrownHttpError(error: unknown, fallbackStatus = 500): Th // [#32250] A package-scoped refusal's holders, so every door that answers // from this resolver names them (ADR-0150 D5). const candidates = packageScopedRefusalCandidates(e); + // [#36877] A declared refusal thrown as a list carries its sentences. + const refusals = declaredRefusalLines(e); const details: Record = { // A truthy NON-string `code` (a driver errno, say) is context and stays // context — promoting it would put a number in the field callers branch on, @@ -359,6 +402,7 @@ export function resolveThrownHttpError(error: unknown, fallbackStatus = 500): Th ...(issues ? { issues } : {}), ...(validation ? { fields: validation.fields } : {}), ...(candidates ? { candidates } : {}), + ...(refusals ? { refusals } : {}), }; const userMessage = declaredUserMessage(error);