diff --git a/.changeset/34579-resume-failed-carries-refusal.md b/.changeset/34579-resume-failed-carries-refusal.md new file mode 100644 index 00000000000..4aa1e013c89 --- /dev/null +++ b/.changeset/34579-resume-failed-carries-refusal.md @@ -0,0 +1,21 @@ +--- +'@objectstack/types': patch +'@objectstack/plugin-approvals': patch +'@objectstack/rest': patch +--- + +fix(approvals): a decision stranded by a refused next step says which refusal stranded it + +Clause-②: yes (widening) +Metadata-protocol: none + +Say an approval flow's next step after the decision is an `update_record`, and a record hook refuses that write (a declared refusal, a validation rule, a permission). `POST /api/v1/approvals/requests/{id}/approve` answers `500 RESUME_FAILED`. The status code and the four #13807 facts are unchanged: the decision stands (`finalized: true`), and `runId` and `repairable` name the stranded run. The body did not say why the run stopped. The engine reported the refusal (`AutomationResult.innerRefusal` and `.userMessage`), and the approvals service dropped it before it built the error. + +The `RESUME_FAILED` body now also carries that refusal when there was one: + +- `innerRefusal`: `{ code, message }`, the same member the flow doors serve in their `FLOW_FAILED` details; +- `userMessage`: the refusal's marked end-user text at the top level, for example a hook's declared sentence in the caller's locale. + +Both are absent when the run met a fault rather than a refusal. `StrandedDecisionDetails` (`@objectstack/types`) declares them as optional members, and `strandedDecisionDetails` drops a malformed one without dropping the four facts. + +A flow author who wants the refusal handled instead of stranded can draw a `fault` edge from that step. The engine routes the refusal down it, and the decision then answers normally. This is now pinned and documented in the approvals guide. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index c4391f2331c..2036b7ef64c 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -833,6 +833,20 @@ for you. would open a second approval request. + + **A refusal on the step after the decision.** Say the `approve` branch + updates the record and that record's `beforeUpdate` hook refuses the write + (a declared refusal, a validation rule, a permission). With no `fault` edge + on that step, `POST …/approve` answers **500 `RESUME_FAILED`**. The decision + still stands (`finalized: true`), the run is stranded (`runId`, and + `repairable` says whether an operator can re-arm it), and the body also + carries the refusal: `innerRefusal` (`{ code, message }`) and the hook's + `userMessage`, the sentence to show the approver. Draw a `fault` edge from + that step to a handler, for example one that sends the record back to its + owner, and the engine routes the refusal there instead: the decision answers + normally and the run finishes without an administrator. + + ### Beyond approve/reject — the full decision surface diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index c2ea21e7a9e..03dc3fc143e 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -25,7 +25,7 @@ import { type ObjectSchemaReadDelegate, type RecordOrganizationResolver, } from '@objectstack/metadata-core'; -import { isObjectAbsentError, keysetWalk, strandedDecisionFailure } from '@objectstack/types'; +import { isObjectAbsentError, keysetWalk, strandedDecisionFailure, type StrandedDecisionDetails } from '@objectstack/types'; // [#15981 / #16166] Every built-in identity NAME is deliberately absent here: // both arms of `isOverrideActor` read an ADR-0095 capability rung, never a name. // `BUILTIN_IDENTITY_PLATFORM_ADMIN` went with the platform arm's name read and @@ -2064,6 +2064,12 @@ export function slotLabelSourceOf(service: ApprovalService): SlotLabelSource { return source; } +/** + * [#34579] The refusal half of a failed resume, as {@link ApprovalService} + * carries it from the engine's answer to the stranded-decision envelope. + */ +type ResumeRefusal = Pick; + /** * [#22559] The visibility source the read gate consumes for `service`: the * approvals door's own `visibleRequestIds`, asked for a read that arrives @@ -5925,16 +5931,29 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega ): Promise<{ runId: string; repairable: boolean; error: string } | undefined> { const result = await this.automation!.resume!(runId, { ...signal, [RESUME_AUTHORITY_SERVICE]: true }); const reported = result as - { success?: boolean; code?: string; error?: string; status?: string } | undefined; + | ({ success?: boolean; code?: string; error?: string; status?: string } & ResumeRefusal) + | undefined; // Only an explicit `success: false` is a failure. An engine (or a test // double) that returns nothing is reporting nothing, and has always meant // "it ran". if (reported && typeof reported === 'object' && reported.success === false) { const err = new Error( `resume of run '${runId}' failed${reported.code ? ` [${reported.code}]` : ''}: ${reported.error ?? 'unknown error'}`, - ) as Error & { resumeCode?: string; resumeStatus?: string }; + ) as Error & { resumeCode?: string; resumeStatus?: string; resumeRefusal?: ResumeRefusal }; err.resumeCode = reported.code; err.resumeStatus = reported.status; + // [#34579] The refusal the continuation met, as the engine reported it + // (`AutomationResult.innerRefusal` / `.userMessage`, ruling B′ on + // #24914) — kept beside the code and status instead of being dropped + // here, one line before the envelope is built, which is where #13807 + // found `status` too. Copied as reported; the recogniser in + // `@objectstack/types` validates it before anything reaches the wire. + if (reported.innerRefusal !== undefined || reported.userMessage !== undefined) { + err.resumeRefusal = { + ...(reported.innerRefusal !== undefined ? { innerRefusal: reported.innerRefusal } : {}), + ...(reported.userMessage !== undefined ? { userMessage: reported.userMessage } : {}), + }; + } throw err; } return this.automation?.takeSubflowParentStrand?.(runId); @@ -5962,6 +5981,18 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega return (err as { resumeStatus?: string } | undefined)?.resumeStatus; } + /** + * The refusal behind a {@link serviceResume} rejection — the engine's + * `innerRefusal` / `userMessage` — or `{}` when the engine reported none + * (#34579). A third sibling of {@link resumeCodeOf} and + * {@link resumeStatusOf}: `code` says why a resume was refused, `status` + * how the run ended, and this what the continuation's own data call was + * refused with. Only the stranded-decision envelope reads it. + */ + private static resumeRefusalOf(err: unknown): ResumeRefusal { + return (err as { resumeRefusal?: ResumeRefusal } | undefined)?.resumeRefusal ?? {}; + } + /** * A decision or a comment attaches only files its caller uploaded. * @@ -6257,10 +6288,14 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega ...(signal.resumedBy && signal.impersonatedBy ? { impersonatedBy: signal.impersonatedBy } : {}), }); } + // [#34579] The refusal the continuation met rides the same envelope — + // the status code still does not move (#13807 B), but an approver whose + // decision stranded on a record hook's refusal is told WHICH refusal. + // The recogniser drops anything not in the declared shape. throw strandedDecisionFailure( `RESUME_FAILED: ${what} was recorded on request ${requestId}, but its flow run '${runId}' ` + `could not be resumed and is now stranded: ${reason}`, - { finalized: true, decision, runId, repairable }, + { finalized: true, decision, runId, repairable, ...ApprovalService.resumeRefusalOf(err) }, ); } } diff --git a/packages/plugins/plugin-approvals/src/hook-refusal-after-decision.test.ts b/packages/plugins/plugin-approvals/src/hook-refusal-after-decision.test.ts new file mode 100644 index 00000000000..7bd25d18ace --- /dev/null +++ b/packages/plugins/plugin-approvals/src/hook-refusal-after-decision.test.ts @@ -0,0 +1,233 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #34579 — a record hook refuses the step AFTER an approval decision. + * + * ## The reported case + * + * A special-approval flow parks at an `approval` node; on `approve` an + * `update_record` moves the plan to `approved`. The plan's `beforeUpdate` hook + * re-checks capacity and refuses with a declared refusal. The approver's + * `POST …/approve` then answered `500 RESUME_FAILED`, the decision stood, the + * run stranded, and the approver could not read WHY: the engine reported the + * refusal (`AutomationResult.innerRefusal` / `.userMessage`, ruling B′ on + * #24914), and the approvals door dropped it before building the envelope. + * + * ## What is pinned, within the rulings on file + * + * ⛔ The status code does not move and the decision is not rolled back or made + * atomic: #13807 B keeps the 500 and the #13937 shape-4 ruling excludes undoing + * a human decision. So the card is pinned on its fallback route: + * + * 1. NO fault edge: the `RESUME_FAILED` envelope carries the refusal the step + * met — `innerRefusal` in the engine's own shape and the hook's marked + * `userMessage` — beside the four #13807 facts, which are unchanged. + * 2. A declared FAULT edge on that step: the hook refusal is routed down it, + * like any run-time failure (`dag-traversal.ts`; only guard refusals are + * not routed). The decision answers normally, `resumed: true`, and the run + * completes through the author's handler. A flow author can bounce the + * record back without an administrator. + * 3. Reverse control: a step that FAULTS (a throw that declares no HTTP + * answer) met no refusal, so the envelope carries neither member — nothing + * is synthesised from the prose. + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { AutomationEngine, InMemorySuspendedRunStore, registerCrudNodes } from '@objectstack/service-automation'; +import { assertEngineDeleteDispatch, assertEngineUpdateDispatch } from '@objectstack/objectql'; +import { strandedDecisionDetails } from '@objectstack/types'; +import { ApprovalService } from './approval-service.js'; +import { registerApprovalNode } from './approval-node.js'; + +const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] } as any; +const noopLogger: any = { info() {}, warn() {}, error() {}, debug() {} }; +noopLogger.child = () => noopLogger; + +/** The hook's declared sentence, in the caller's locale — what the approver should read. */ +const HOOK_USER_TEXT = '产能已被其他订单占用,该方案无法按当前产能通过。'; + +/** + * A declared hook refusal as the runtime answers one + * (`resolveHookRefusal`, `runtime/src/sandbox/hook-refusal-catalogue.ts`): + * the diagnostic message names the hook, the declared code and status ride + * the error, and the declared sentence is both the caller-facing message and + * the marked `userMessage`. + */ +const hookRefusal = () => Object.assign( + new Error("hook 'alloc_plan_capacity_recheck' threw: Error: over_capacity"), + { name: 'SandboxError', innerMessage: HOOK_USER_TEXT, code: 'VALIDATION_FAILED', status: 400, userMessage: HOOK_USER_TEXT }, +); + +/** In-memory ObjectQL stand-in: approvals tables plus the plan the flow writes. */ +function makeFakeEngine(refuseUpdateOf: string, refusal: () => unknown) { + const tables = new Map(); + const rows = (o: string) => (tables.get(o) ?? (tables.set(o, []), tables.get(o)!)); + const matches = (row: any, where: any) => Object.entries(where ?? {}).every(([k, v]) => { + if (k.startsWith('$')) throw new Error(`fake engine: unsupported filter operator ${k}`); + if (v && typeof v === 'object' && '$in' in (v as any)) return (v as any).$in.includes(row[k]); + if (v && typeof v === 'object' && '$ne' in (v as any)) return row[k] !== (v as any).$ne; + return row[k] === v; + }); + return { + tables, + async find(object: string, opts: any = {}) { + const where = opts.where ?? opts.filter ?? {}; + const out = rows(object).filter(r => matches(r, where)); + const start = opts.offset ?? 0; + const page = typeof opts.limit === 'number' ? out.slice(start, start + opts.limit) : out.slice(start); + return page.map(r => ({ ...r })); + }, + async insert(object: string, data: any) { rows(object).push({ ...data }); return { ...data }; }, + async update(object: string, data: any, options?: any) { + const dispatch = assertEngineUpdateDispatch(data, options); + // The record hook: accepts the call the way ObjectQL does, then refuses. + if (object === refuseUpdateOf) throw refusal(); + const table = rows(object); + if (dispatch.kind === 'multi') { + let n = 0; + for (let i = 0; i < table.length; i++) { + if (matches(table[i], options?.where)) { table[i] = { ...table[i], ...data }; n++; } + } + return { updated: n }; + } + const i = table.findIndex(r => r.id === dispatch.id); + if (i >= 0) table[i] = { ...table[i], ...data }; + return i >= 0 ? { ...table[i] } : null; + }, + async delete(object: string, options?: any) { + const dispatch = assertEngineDeleteDispatch(options); + const table = rows(object); + const i = table.findIndex(r => r.id === (dispatch as any).id); + if (i >= 0) table.splice(i, 1); + return { id: (dispatch as any).id }; + }, + }; +} + +/** start → approval → (approve) adopt the plan → end; (reject) → end. */ +function specialApprovalFlow(withFaultEdge: boolean) { + return { + name: 'plan_special_approval', + label: 'Plan Special Approval', + type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { + id: 'director', type: 'approval', label: 'Director Approval', + config: { approvers: [{ type: 'user', value: 'director' }] }, + }, + { + id: 'adopt_plan', type: 'update_record', label: 'Adopt Plan', + config: { objectName: 'alloc_plan', filter: { id: 'p1' }, fields: { status: 'approved' } }, + }, + { id: 'bounce_back', type: 'mark', label: 'Bounce back to the rep' }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'director' }, + { id: 'e2', source: 'director', target: 'adopt_plan', label: 'approve' }, + { id: 'e3', source: 'director', target: 'end', label: 'reject' }, + { id: 'e4', source: 'adopt_plan', target: 'end' }, + ...(withFaultEdge + ? [ + { id: 'ef', source: 'adopt_plan', target: 'bounce_back', type: 'fault' }, + { id: 'e5', source: 'bounce_back', target: 'end' }, + ] + : []), + ], + }; +} + +describe('#34579 — a hook refusal on the step after an approval decision', () => { + let marks: string[]; + + beforeEach(() => { marks = []; }); + + /** One live process: real engine, real CRUD + approval nodes, real approvals service. */ + function boot(opts: { withFaultEdge: boolean; refusal?: () => unknown }) { + const data = makeFakeEngine('alloc_plan', opts.refusal ?? hookRefusal); + data.tables.set('alloc_plan', [{ id: 'p1', status: 'submitted' }]); + const service = new ApprovalService({ engine: data as any, logger: noopLogger }); + const automation = new AutomationEngine(noopLogger, new InMemorySuspendedRunStore()); + registerCrudNodes(automation, { logger: noopLogger, getService: (n: string) => (n === 'data' ? data : undefined) } as any); + registerApprovalNode(automation, service, noopLogger); + automation.registerNodeExecutor({ + type: 'mark', + async execute(node: any) { marks.push(node.id); return { success: true }; }, + } as never); + automation.registerFlow('plan_special_approval', specialApprovalFlow(opts.withFaultEdge) as never); + service.attachAutomation(automation); + return { data, service, automation }; + } + + async function park(env: ReturnType) { + const started = await env.automation.execute('plan_special_approval', { + object: 'alloc_plan', record: { id: 'p1', status: 'submitted' }, userId: 'rep', + } as never); + expect(started.status, 'the run must park at the approval node').toBe('paused'); + const req = (await env.data.find('sys_approval_request', { where: { status: 'pending' } }))[0]; + expect(req?.flow_run_id, 'the request must name the run it gates').toBeTruthy(); + return req; + } + + it('NO fault edge: still 500 RESUME_FAILED, and the envelope now carries the refusal the step met', async () => { + const env = boot({ withFaultEdge: false }); + const req = await park(env); + const runId = req.flow_run_id; + + const err = await env.service + .decide(req.id, { decision: 'approve', actorId: 'director' }, SYSTEM_CTX) + .then(() => null, (e: Error) => e); + + // #13807 B, unchanged: the door still throws, and the prose still names the run. + expect(err, '⛔ not "return 200" — the status code does not move').toBeTruthy(); + expect(err?.message).toMatch(/^RESUME_FAILED: the approve decision was recorded on request /); + expect(err?.message).toMatch(/could not be resumed and is now stranded/); + + // The decision is durable and the plan did not move: the reported state. + const row = (await env.data.find('sys_approval_request', { where: { id: req.id } }))[0]; + expect(row.status).toBe('approved'); + expect((await env.data.find('alloc_plan', { where: { id: 'p1' } }))[0].status).toBe('submitted'); + + // ⭐ The card's deliverable: the refusal, structured, beside the four facts. + expect(strandedDecisionDetails(err)).toEqual({ + finalized: true, + decision: 'approve', + runId, + repairable: true, + innerRefusal: { code: 'VALIDATION_FAILED', message: hookRefusal().message }, + userMessage: HOOK_USER_TEXT, + }); + }); + + it('a declared FAULT edge on that step routes the hook refusal to the handler — the decision answers normally and the run does not strand', async () => { + const env = boot({ withFaultEdge: true }); + const req = await park(env); + const runId = req.flow_run_id; + + const out = await env.service.decide(req.id, { decision: 'approve', actorId: 'director' }, SYSTEM_CTX); + + expect(out.finalized).toBe(true); + expect(out.decision).toBe('approve'); + expect(out.resumed, 'the run advanced through the fault edge').toBe(true); + expect(out.resumeError).toBeUndefined(); + expect(marks, "the author's handler ran").toEqual(['bounce_back']); + // Nothing left parked and nothing to repair: the run ended. + expect(await env.automation.hasSuspendedRun(runId)).toBe(false); + expect(strandedDecisionDetails(out as unknown)).toBeUndefined(); + }); + + it('reverse control: a step that FAULTS met no refusal — the envelope carries neither member', async () => { + const env = boot({ withFaultEdge: false, refusal: () => new Error('ECONNREFUSED: could not reach the store') }); + const req = await park(env); + + const err = await env.service + .decide(req.id, { decision: 'approve', actorId: 'director' }, SYSTEM_CTX) + .then(() => null, (e: Error) => e); + + const details = strandedDecisionDetails(err); + expect(details).toEqual({ finalized: true, decision: 'approve', runId: req.flow_run_id, repairable: true }); + expect(details && 'innerRefusal' in details).toBe(false); + expect(details && 'userMessage' in details).toBe(false); + }); +}); diff --git a/packages/rest/src/approvals-routes.ts b/packages/rest/src/approvals-routes.ts index 8fecd091873..17fec4754be 100644 --- a/packages/rest/src/approvals-routes.ts +++ b/packages/rest/src/approvals-routes.ts @@ -254,6 +254,14 @@ export function registerApprovalsEndpoints(this: ApprovalsRouteHost, basePath: s // same reason the strip above is: these four facts are // about a recorded-decision-with-stranded-run and // about nothing else. + // + // [#34579] …and, when the run stranded on a refusal, + // that refusal: `innerRefusal` (ruling B′ on #24914, + // the engine's own shape) and the marked `userMessage` + // at the top level, the channel a record save's refusal + // and every flow door's `FLOW_FAILED` already use. Both + // are present only when the producer attached them and + // the recogniser accepted them. ...(code === 'RESUME_FAILED' && stranded ? stranded : {}), }); return true; diff --git a/packages/rest/src/rest-approvals-wire-codes.test.ts b/packages/rest/src/rest-approvals-wire-codes.test.ts index 784551b1371..9ec8ee68d27 100644 --- a/packages/rest/src/rest-approvals-wire-codes.test.ts +++ b/packages/rest/src/rest-approvals-wire-codes.test.ts @@ -56,6 +56,10 @@ import { strandedDecisionFailure } from '@objectstack/types'; import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; // `.js` on purpose — NodeNext resolution requires the extension (#7248). import { RestServer } from './rest-server.js'; +// The rest server's routes load `@objectstack/objectql` lazily, inside a +// handler; paying that load here, at collection, keeps it out of the first +// case's `testTimeout` window (check:test-source-alias). +import '@objectstack/objectql'; const REQ = '/api/v1/approvals/requests/:id'; @@ -409,6 +413,37 @@ describe('approvals wire codes are registered vocabulary (#8885)', () => { .toEqual(['code', 'decision', 'error', 'finalized', 'repairable', 'runId']); }); + it('a decision stranded by a record hook\'s refusal carries that refusal on the same 500 (#34579)', async () => { + // The step after the decision was refused by a record hook. The status + // code still does not move (#13807 B), and the four facts are as + // above; what is added is WHICH refusal stranded the run: the engine's + // `innerRefusal` (ruling B′ on #24914) and the hook's marked + // `userMessage`, at the top level where a record save's refusal and + // every flow door's `FLOW_FAILED` already put it. + const userMessage = '产能已被其他订单占用,该方案无法按当前产能通过。'; + const innerRefusal = { + code: 'VALIDATION_FAILED' as const, + message: "hook 'alloc_plan_capacity_recheck' threw: Error: over_capacity", + }; + const rest = boot({ + decide: vi.fn().mockRejectedValue(strandedDecisionFailure( + "RESUME_FAILED: the approve decision was recorded on request req_1, but its flow run " + + "'run_1' could not be resumed and is now stranded: Node 'adopt_plan' failed", + { finalized: true, decision: 'approve', runId: 'run_1', repairable: true, innerRefusal, userMessage }, + )), + }); + const answer = await drive(rest, 'POST', `${REQ}/approve`); + + expect(answer.status).toBe(500); + expect(answer.body?.code).toBe('RESUME_FAILED'); + expect(answer.body?.finalized).toBe(true); + expect(answer.body?.innerRefusal).toEqual(innerRefusal); + expect(answer.body?.userMessage).toBe(userMessage); + expect(Object.keys(answer.body ?? {}).sort()).toEqual( + ['code', 'decision', 'error', 'finalized', 'innerRefusal', 'repairable', 'runId', 'userMessage'], + ); + }); + it('REVERSE CONTROL — a RESUME_FAILED with no carrier answers exactly the body it always did', async () => { // ⛔ The door never synthesises the envelope. A `RESUME_FAILED` raised // by something that had no decision to report must not be dressed up diff --git a/packages/spec/src/contracts/approval-service.ts b/packages/spec/src/contracts/approval-service.ts index ee6c2039ed9..2d88493f3de 100644 --- a/packages/spec/src/contracts/approval-service.ts +++ b/packages/spec/src/contracts/approval-service.ts @@ -880,6 +880,17 @@ export interface ApprovalDecisionResult { * declares — a caller holding only the status code reads a bare 500 as "the * decision did not happen", and the row IS terminal. * + * When the run stranded because the step after the decision was REFUSED — + * a record hook's declared refusal, a validation rule, a permission — the + * same body also carries that refusal (#34579): `innerRefusal` + * (`{ code, message }`, the engine's `AutomationResult.innerRefusal`, + * ruling B′ on #24914) and the refusal's marked `userMessage`, the text an + * approver can read. Both are absent when the run met no refusal (a fault), + * and neither moves the status code or the four facts. A flow author who + * wants such a refusal handled rather than stranded draws a `fault` edge + * from that step: the engine routes the refusal down it like any run-time + * failure, and the decision then answers normally. + * * ⛔ They are not members of this result and must never be added to it: * they ride the ERROR, so declaring them here would declare a success shape * that never carries them. ⛔ Nor are they {@link resumeFailure}, which diff --git a/packages/types/src/stranded-decision.test.ts b/packages/types/src/stranded-decision.test.ts index e327d937cc7..d9b51bbb479 100644 --- a/packages/types/src/stranded-decision.test.ts +++ b/packages/types/src/stranded-decision.test.ts @@ -74,3 +74,34 @@ describe('strandedDecisionFailure / strandedDecisionDetails (#13807)', () => { .toEqual(['decision', 'finalized', 'repairable', 'runId']); }); }); + +describe('the refusal that stranded the run rides the same envelope (#34579)', () => { + const facts = { finalized: true, decision: 'approve', runId: 'run_1', repairable: true } as const; + const innerRefusal = { code: 'VALIDATION_FAILED', message: "hook 'h' threw: Error: over_capacity" } as const; + const userMessage = '产能已被其他订单占用。'; + + it('round-trips innerRefusal and userMessage beside the four facts', () => { + const err = strandedDecisionFailure('RESUME_FAILED: …', { ...facts, innerRefusal, userMessage }); + expect(strandedDecisionDetails(err)).toEqual({ ...facts, innerRefusal, userMessage }); + }); + + it('⛔ a malformed refusal member is DROPPED, and the four facts still stand', () => { + // The four facts are all-or-nothing; the refusal is not one of them. A + // WHY that is not in the declared shape must not reach the wire, and + // must not take the truthful WHAT down with it. + const carrying = (extra: Record) => + strandedDecisionDetails({ strandedDecision: { ...facts, ...extra } }); + expect(carrying({ innerRefusal: { code: 'NOT_A_LEDGER_CODE', message: 'x' } })).toEqual(facts); + expect(carrying({ innerRefusal: { code: 'VALIDATION_FAILED' } })).toEqual(facts); + expect(carrying({ innerRefusal: 'VALIDATION_FAILED: x' })).toEqual(facts); + expect(carrying({ userMessage: ' ' })).toEqual(facts); + expect(carrying({ userMessage: 42 })).toEqual(facts); + // REVERSE CONTROL: the well-formed members on the same path resolve. + expect(carrying({ innerRefusal, userMessage })).toEqual({ ...facts, innerRefusal, userMessage }); + }); + + it('⛔ a refusal member never rescues a partial envelope', () => { + expect(strandedDecisionDetails({ strandedDecision: { ...facts, runId: '', innerRefusal, userMessage } })) + .toBeUndefined(); + }); +}); diff --git a/packages/types/src/stranded-decision.ts b/packages/types/src/stranded-decision.ts index 81f38850ddb..8a484483b78 100644 --- a/packages/types/src/stranded-decision.ts +++ b/packages/types/src/stranded-decision.ts @@ -1,5 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +import { ErrorCode, type FlowInnerRefusal } from '@objectstack/spec/api'; +import { declaredUserMessage } from './thrown-http-error.js'; + /** * The machine-readable half of a `RESUME_FAILED` — a decision that is durably * recorded whose flow run could not be resumed (#13807). @@ -59,7 +62,8 @@ /** * The four facts a stranded decision publishes alongside its `code` and - * `error`. Every field is present or the whole envelope is absent — a partial + * `error`, plus — since #34579 — the refusal that stranded the run, when it + * met one. Each of the four facts is present or the whole envelope is absent — a partial * one would let a consumer branch on `finalized === undefined` and read it as * "the decision did not stand", which is the exact misreading this exists to * end. @@ -91,6 +95,32 @@ export interface StrandedDecisionDetails { * repair verb that will refuse is worse than promising nothing. */ repairable: boolean; + /** + * [#34579] The refusal the node after the decision met, when it met one — + * the engine's own `AutomationResult.innerRefusal` (ruling B′ on #24914), + * copied verbatim: `code` in its wire spelling, `message` the refusal's own + * text without the node and operation prefixes. The flow doors already serve + * this member in their `FLOW_FAILED` details; this is the same value at the + * approvals door, so an approver whose decision stranded on a record hook's + * refusal can be told which refusal it was. + * + * Optional, and never part of the all-or-nothing rule above: the four facts + * describe the decision and the run, this describes WHY the run stopped, + * and a run can strand on a fault that met no refusal at all (a crash, an + * unreachable store). ⛔ Absent there, never synthesised from `error`. + */ + innerRefusal?: FlowInnerRefusal; + /** + * [#34579] The producer-marked end-user text of that refusal — the engine's + * `AutomationResult.userMessage`, verbatim. For a record hook that declares + * a `refusals` catalogue this is the declared sentence in the caller's + * locale, while {@link innerRefusal}'s `message` keeps the diagnostic text. + * It reaches the wire at the top level of the error body, the channel a + * record save's refusal and every flow door's `FLOW_FAILED` already use, and + * with the same semantics: presence IS the marking. Absent when the run met + * no marked refusal. + */ + userMessage?: string; } /** Property under which {@link StrandedDecisionDetails} rides a thrown error. */ @@ -114,7 +144,31 @@ export function strandedDecisionDetails(err: unknown): StrandedDecisionDetails | if (typeof d.decision !== 'string' || d.decision === '') return undefined; if (typeof d.runId !== 'string' || d.runId === '') return undefined; if (typeof d.repairable !== 'boolean') return undefined; - return { finalized: true, decision: d.decision, runId: d.runId, repairable: d.repairable }; + const innerRefusal = carriedInnerRefusal(d.innerRefusal); + const userMessage = declaredUserMessage(d); + return { + finalized: true, + decision: d.decision, + runId: d.runId, + repairable: d.repairable, + ...(innerRefusal !== undefined ? { innerRefusal } : {}), + ...(userMessage !== undefined ? { userMessage } : {}), + }; +} + +/** + * [#34579] The optional refusal member, or `undefined` when the carrier holds + * none or holds one that is not a refusal in the declared shape — a `code` + * outside the closed ADR-0112 set, or a `message` that is not a string. The + * member is dropped, the four facts stand: a malformed WHY must not take the + * truthful WHAT down with it, and it must not reach the wire either. + */ +function carriedInnerRefusal(value: unknown): FlowInnerRefusal | undefined { + if (!value || typeof value !== 'object') return undefined; + const { code, message } = value as { code?: unknown; message?: unknown }; + if (typeof message !== 'string') return undefined; + const parsed = ErrorCode.safeParse(code); + return parsed.success ? { code: parsed.data, message } : undefined; } /** diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index a978196a866..fb40193688f 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -3561,6 +3561,16 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/plugins/plugin-approvals/src/hook-refusal-after-decision.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/plugins/plugin-approvals/src/hook-refusal-after-decision.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/plugins/plugin-approvals/src/manager-approver-org-screen.test.ts", "verb": "delete",