Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions .changeset/36877-refusal-reasons-list.md
Original file line number Diff line number Diff line change
@@ -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

<!-- adr-0087: registered refusal-reasons-list-literal-judged -->

**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.
54 changes: 54 additions & 0 deletions packages/runtime/src/sandbox/action-refusal-catalogue.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
157 changes: 156 additions & 1 deletion packages/runtime/src/sandbox/hook-refusal-catalogue.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<string, string>)[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();
}
});
});
Loading
Loading