Skip to content

Commit 62d9d0d

Browse files
fix(approvals): RESUME_FAILED carries the refusal that stranded the run (#34619)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9Pe4kChjRUAqJ91tVGSLW5b)_ Fixes #34579 Clause-②: yes (widening) Metadata-protocol: none Skills-docs: follow-up #34637 ## 维护者速读 - 现象:审批通过后,下一步「改记录」被记录钩子拒绝,接口回 500 RESUME_FAILED,审批人看不到被拒原因,流程卡住。 - 改了什么:状态码按 #13807 裁决仍是 500,决定照旧记下;错误体新增 `innerRefusal`(拒绝码和原文)和 `userMessage`(钩子声明的、按调用者语言的那句话),审批人能看到为什么。 - 流程作者在这一步画一条 fault 边,拒绝就走 fault 分支(比如退回给销售),审批正常返回,流程不卡;这条行为已钉测并写进审批文档。 - 没碰的:不先试跑、不回滚决定(#13807 B、#13937 形态 4 两条裁决不动);钩子没拒绝而是崩溃时,两个新字段都不出现。 - 契约面:`@objectstack/types` 的 `StrandedDecisionDetails` 加两个可选成员,属放宽,需契约复审。 - 需要你做的:无。 ## What changes The card's preferred route (dry-run the post-decision step and keep the request pending) conflicts with ruling #13807 B and the #13937 shape-4 ruling. Per the seat's premise correction (comment 6936860860), this PR ships the fallback inside those rulings. - **`@objectstack/types` — `StrandedDecisionDetails`** gains two optional members: - `innerRefusal?: FlowInnerRefusal` — the engine's `AutomationResult.innerRefusal` (ruling B′ on #24914), the same member every flow door serves in `FLOW_FAILED` details; - `userMessage?: string` — the refusal's producer-marked end-user text (the engine's `AutomationResult.userMessage`). `strandedDecisionDetails` validates both (`ErrorCode` for the code, `declaredUserMessage` for the text) and **drops** a malformed one while keeping the four #13807 facts. The four facts stay all-or-nothing; a refusal member never rescues a partial envelope. - **`@objectstack/plugin-approvals`** — `serviceResume` keeps the engine's `innerRefusal` / `userMessage` beside `resumeCode` / `resumeStatus` instead of dropping them, and `resumeRecordedOutcome` attaches them to the stranded-decision envelope. Every decision door that resumes through `resumeRecordedOutcome` (approve, reject, revise, resubmit, the restored-run continuation) carries them. - **`@objectstack/rest`** — no logic change: `handleApprovalError` already spreads the recognised envelope into the `RESUME_FAILED` body, so both members reach the wire at the top level. Comment updated. - **`@objectstack/spec`** — `ApprovalDecisionResult.resumed` docblock (`contracts/approval-service.ts`) names the two members and the `fault`-edge route. Comment only; no schema or generated artifact moves. - **Docs** — `content/docs/automation/approvals.mdx` gains a callout: what the 500 body carries when the step after the decision is refused, and how a `fault` edge on that step handles it instead. ### Why `userMessage` as well as `innerRefusal` Measured, not assumed: for a hook that declares a `refusals` catalogue, the runtime's `SandboxError` keeps the diagnostic `hook '<name>' threw: …` as `.message` and puts the declared, localized sentence on `.userMessage` (`resolveHookRefusal` / `resolveInProcessHookRefusal`, `runtime/src/sandbox/hook-refusal-catalogue.ts`). `refusalCarriedBy` builds `innerRefusal.message` from `.message`, so `innerRefusal` alone does not give the approver the hook's readable sentence. The flow doors serve the same pair (details `innerRefusal` + top-level `userMessage`, `flow-dispatch-status.ts`), so this reuses that vocabulary and adds none. ## Why The engine already reported the refusal on the stranded exit (`run-resume.ts`, `...readCarriedRefusal(err)`), and the approvals door dropped it one line before building the envelope, the same place #13807 found `status` being dropped. ## Verification - `packages/plugins/plugin-approvals/src/hook-refusal-after-decision.test.ts` (new): the card's flow end to end with a real `AutomationEngine`, the real `update_record` node and approval node, and a data double that throws a declared hook refusal in the runtime's shape. 1. No fault edge: still `RESUME_FAILED`, decision `approved`, plan still `submitted`, and `strandedDecisionDetails(err)` equals the four facts plus `innerRefusal: { code: 'VALIDATION_FAILED', message }` and the hook's `userMessage`. 2. A `fault` edge on the step: the refusal is routed to the handler, `decide` answers `finalized: true, resumed: true`, nothing left parked. (Pins existing engine behaviour; green before and after the fix.) 3. Reverse control: a step that faults (no declared status) carries neither member. - Ablation: with `approval-service.ts` reverted to `origin/main`, case 1 goes red (`expected { finalized: true, …(3) } to deeply equal { finalized: true, …(5) }`); cases 2 and 3 stay green. - `packages/rest/src/rest-approvals-wire-codes.test.ts`: new case — the 500 body carries `innerRefusal` and `userMessage` at the top level, exact key set pinned. The existing #13807 exact-key-set pins are unchanged and still green. - `packages/types/src/stranded-decision.test.ts`: round-trip, malformed members dropped with the four facts kept, and a refusal member never rescues a partial envelope. The existing "exactly the four declared keys" pin is unchanged and still green. - Derived gates at head `95eae72668321d7f8eb2233f80753911e1202288`: `dispatch-gates --commands` derived 125; all 125 exit 0; `--ran` reconcile: 125 run, 0 NOT-MEASURED, 0 UNRUN. - Package suites: `plugin-approvals` 122 files / 1723 tests, `types` 40 / 923, `rest` 419 / 8865 (373 skipped), all green; `typecheck` green for `types`, `plugin-approvals` and `rest`. The second commit only touches the two new/edited test files (an unused `findOne` dropped from the new double for `check:engine-double-contract`, and a module-top `import '@objectstack/objectql'` for `check:test-source-alias`) plus `scripts/engine-double-contract.pinned.json`; both test files re-ran green on the final head. - `git merge-tree` at the final head: clean against `origin/main` (97defd6), #34545 (df9ac15) and #34592 (a6661f5). No existing test was changed to accommodate the fix. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (Comment only; no artifact moves.) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmT4f9MMpnjemPU3Esb <!-- signed: repo:objectstack#2 · os-steve · session_01ADHkmT4f9MMpnjemPU3Esb --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent d635555 commit 62d9d0d

10 files changed

Lines changed: 458 additions & 6 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
'@objectstack/types': patch
3+
'@objectstack/plugin-approvals': patch
4+
'@objectstack/rest': patch
5+
---
6+
7+
fix(approvals): a decision stranded by a refused next step says which refusal stranded it
8+
9+
Clause-②: yes (widening)
10+
Metadata-protocol: none
11+
12+
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.
13+
14+
The `RESUME_FAILED` body now also carries that refusal when there was one:
15+
16+
- `innerRefusal`: `{ code, message }`, the same member the flow doors serve in their `FLOW_FAILED` details;
17+
- `userMessage`: the refusal's marked end-user text at the top level, for example a hook's declared sentence in the caller's locale.
18+
19+
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.
20+
21+
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.

‎content/docs/automation/approvals.mdx‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -833,6 +833,20 @@ for you.
833833
would open a second approval request.
834834
</Callout>
835835

836+
<Callout type="warn">
837+
**A refusal on the step after the decision.** Say the `approve` branch
838+
updates the record and that record's `beforeUpdate` hook refuses the write
839+
(a declared refusal, a validation rule, a permission). With no `fault` edge
840+
on that step, `POST …/approve` answers **500 `RESUME_FAILED`**. The decision
841+
still stands (`finalized: true`), the run is stranded (`runId`, and
842+
`repairable` says whether an operator can re-arm it), and the body also
843+
carries the refusal: `innerRefusal` (`{ code, message }`) and the hook's
844+
`userMessage`, the sentence to show the approver. Draw a `fault` edge from
845+
that step to a handler, for example one that sends the record back to its
846+
owner, and the engine routes the refusal there instead: the decision answers
847+
normally and the run finishes without an administrator.
848+
</Callout>
849+
836850
</Steps>
837851

838852
### Beyond approve/reject — the full decision surface

‎packages/plugins/plugin-approvals/src/approval-service.ts‎

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import {
2525
type ObjectSchemaReadDelegate,
2626
type RecordOrganizationResolver,
2727
} from '@objectstack/metadata-core';
28-
import { isObjectAbsentError, keysetWalk, strandedDecisionFailure } from '@objectstack/types';
28+
import { isObjectAbsentError, keysetWalk, strandedDecisionFailure, type StrandedDecisionDetails } from '@objectstack/types';
2929
// [#15981 / #16166] Every built-in identity NAME is deliberately absent here:
3030
// both arms of `isOverrideActor` read an ADR-0095 capability rung, never a name.
3131
// `BUILTIN_IDENTITY_PLATFORM_ADMIN` went with the platform arm's name read and
@@ -2064,6 +2064,12 @@ export function slotLabelSourceOf(service: ApprovalService): SlotLabelSource {
20642064
return source;
20652065
}
20662066

2067+
/**
2068+
* [#34579] The refusal half of a failed resume, as {@link ApprovalService}
2069+
* carries it from the engine's answer to the stranded-decision envelope.
2070+
*/
2071+
type ResumeRefusal = Pick<StrandedDecisionDetails, 'innerRefusal' | 'userMessage'>;
2072+
20672073
/**
20682074
* [#22559] The visibility source the read gate consumes for `service`: the
20692075
* approvals door's own `visibleRequestIds`, asked for a read that arrives
@@ -5925,16 +5931,29 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
59255931
): Promise<{ runId: string; repairable: boolean; error: string } | undefined> {
59265932
const result = await this.automation!.resume!(runId, { ...signal, [RESUME_AUTHORITY_SERVICE]: true });
59275933
const reported = result as
5928-
{ success?: boolean; code?: string; error?: string; status?: string } | undefined;
5934+
| ({ success?: boolean; code?: string; error?: string; status?: string } & ResumeRefusal)
5935+
| undefined;
59295936
// Only an explicit `success: false` is a failure. An engine (or a test
59305937
// double) that returns nothing is reporting nothing, and has always meant
59315938
// "it ran".
59325939
if (reported && typeof reported === 'object' && reported.success === false) {
59335940
const err = new Error(
59345941
`resume of run '${runId}' failed${reported.code ? ` [${reported.code}]` : ''}: ${reported.error ?? 'unknown error'}`,
5935-
) as Error & { resumeCode?: string; resumeStatus?: string };
5942+
) as Error & { resumeCode?: string; resumeStatus?: string; resumeRefusal?: ResumeRefusal };
59365943
err.resumeCode = reported.code;
59375944
err.resumeStatus = reported.status;
5945+
// [#34579] The refusal the continuation met, as the engine reported it
5946+
// (`AutomationResult.innerRefusal` / `.userMessage`, ruling B′ on
5947+
// #24914) — kept beside the code and status instead of being dropped
5948+
// here, one line before the envelope is built, which is where #13807
5949+
// found `status` too. Copied as reported; the recogniser in
5950+
// `@objectstack/types` validates it before anything reaches the wire.
5951+
if (reported.innerRefusal !== undefined || reported.userMessage !== undefined) {
5952+
err.resumeRefusal = {
5953+
...(reported.innerRefusal !== undefined ? { innerRefusal: reported.innerRefusal } : {}),
5954+
...(reported.userMessage !== undefined ? { userMessage: reported.userMessage } : {}),
5955+
};
5956+
}
59385957
throw err;
59395958
}
59405959
return this.automation?.takeSubflowParentStrand?.(runId);
@@ -5962,6 +5981,18 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
59625981
return (err as { resumeStatus?: string } | undefined)?.resumeStatus;
59635982
}
59645983

5984+
/**
5985+
* The refusal behind a {@link serviceResume} rejection — the engine's
5986+
* `innerRefusal` / `userMessage` — or `{}` when the engine reported none
5987+
* (#34579). A third sibling of {@link resumeCodeOf} and
5988+
* {@link resumeStatusOf}: `code` says why a resume was refused, `status`
5989+
* how the run ended, and this what the continuation's own data call was
5990+
* refused with. Only the stranded-decision envelope reads it.
5991+
*/
5992+
private static resumeRefusalOf(err: unknown): ResumeRefusal {
5993+
return (err as { resumeRefusal?: ResumeRefusal } | undefined)?.resumeRefusal ?? {};
5994+
}
5995+
59655996
/**
59665997
* A decision or a comment attaches only files its caller uploaded.
59675998
*
@@ -6257,10 +6288,14 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
62576288
...(signal.resumedBy && signal.impersonatedBy ? { impersonatedBy: signal.impersonatedBy } : {}),
62586289
});
62596290
}
6291+
// [#34579] The refusal the continuation met rides the same envelope —
6292+
// the status code still does not move (#13807 B), but an approver whose
6293+
// decision stranded on a record hook's refusal is told WHICH refusal.
6294+
// The recogniser drops anything not in the declared shape.
62606295
throw strandedDecisionFailure(
62616296
`RESUME_FAILED: ${what} was recorded on request ${requestId}, but its flow run '${runId}' ` +
62626297
`could not be resumed and is now stranded: ${reason}`,
6263-
{ finalized: true, decision, runId, repairable },
6298+
{ finalized: true, decision, runId, repairable, ...ApprovalService.resumeRefusalOf(err) },
62646299
);
62656300
}
62666301
}
Lines changed: 233 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,233 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* #34579 — a record hook refuses the step AFTER an approval decision.
5+
*
6+
* ## The reported case
7+
*
8+
* A special-approval flow parks at an `approval` node; on `approve` an
9+
* `update_record` moves the plan to `approved`. The plan's `beforeUpdate` hook
10+
* re-checks capacity and refuses with a declared refusal. The approver's
11+
* `POST …/approve` then answered `500 RESUME_FAILED`, the decision stood, the
12+
* run stranded, and the approver could not read WHY: the engine reported the
13+
* refusal (`AutomationResult.innerRefusal` / `.userMessage`, ruling B′ on
14+
* #24914), and the approvals door dropped it before building the envelope.
15+
*
16+
* ## What is pinned, within the rulings on file
17+
*
18+
* ⛔ The status code does not move and the decision is not rolled back or made
19+
* atomic: #13807 B keeps the 500 and the #13937 shape-4 ruling excludes undoing
20+
* a human decision. So the card is pinned on its fallback route:
21+
*
22+
* 1. NO fault edge: the `RESUME_FAILED` envelope carries the refusal the step
23+
* met — `innerRefusal` in the engine's own shape and the hook's marked
24+
* `userMessage` — beside the four #13807 facts, which are unchanged.
25+
* 2. A declared FAULT edge on that step: the hook refusal is routed down it,
26+
* like any run-time failure (`dag-traversal.ts`; only guard refusals are
27+
* not routed). The decision answers normally, `resumed: true`, and the run
28+
* completes through the author's handler. A flow author can bounce the
29+
* record back without an administrator.
30+
* 3. Reverse control: a step that FAULTS (a throw that declares no HTTP
31+
* answer) met no refusal, so the envelope carries neither member — nothing
32+
* is synthesised from the prose.
33+
*/
34+
35+
import { describe, it, expect, beforeEach } from 'vitest';
36+
import { AutomationEngine, InMemorySuspendedRunStore, registerCrudNodes } from '@objectstack/service-automation';
37+
import { assertEngineDeleteDispatch, assertEngineUpdateDispatch } from '@objectstack/objectql';
38+
import { strandedDecisionDetails } from '@objectstack/types';
39+
import { ApprovalService } from './approval-service.js';
40+
import { registerApprovalNode } from './approval-node.js';
41+
42+
const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] } as any;
43+
const noopLogger: any = { info() {}, warn() {}, error() {}, debug() {} };
44+
noopLogger.child = () => noopLogger;
45+
46+
/** The hook's declared sentence, in the caller's locale — what the approver should read. */
47+
const HOOK_USER_TEXT = '产能已被其他订单占用,该方案无法按当前产能通过。';
48+
49+
/**
50+
* A declared hook refusal as the runtime answers one
51+
* (`resolveHookRefusal`, `runtime/src/sandbox/hook-refusal-catalogue.ts`):
52+
* the diagnostic message names the hook, the declared code and status ride
53+
* the error, and the declared sentence is both the caller-facing message and
54+
* the marked `userMessage`.
55+
*/
56+
const hookRefusal = () => Object.assign(
57+
new Error("hook 'alloc_plan_capacity_recheck' threw: Error: over_capacity"),
58+
{ name: 'SandboxError', innerMessage: HOOK_USER_TEXT, code: 'VALIDATION_FAILED', status: 400, userMessage: HOOK_USER_TEXT },
59+
);
60+
61+
/** In-memory ObjectQL stand-in: approvals tables plus the plan the flow writes. */
62+
function makeFakeEngine(refuseUpdateOf: string, refusal: () => unknown) {
63+
const tables = new Map<string, any[]>();
64+
const rows = (o: string) => (tables.get(o) ?? (tables.set(o, []), tables.get(o)!));
65+
const matches = (row: any, where: any) => Object.entries(where ?? {}).every(([k, v]) => {
66+
if (k.startsWith('$')) throw new Error(`fake engine: unsupported filter operator ${k}`);
67+
if (v && typeof v === 'object' && '$in' in (v as any)) return (v as any).$in.includes(row[k]);
68+
if (v && typeof v === 'object' && '$ne' in (v as any)) return row[k] !== (v as any).$ne;
69+
return row[k] === v;
70+
});
71+
return {
72+
tables,
73+
async find(object: string, opts: any = {}) {
74+
const where = opts.where ?? opts.filter ?? {};
75+
const out = rows(object).filter(r => matches(r, where));
76+
const start = opts.offset ?? 0;
77+
const page = typeof opts.limit === 'number' ? out.slice(start, start + opts.limit) : out.slice(start);
78+
return page.map(r => ({ ...r }));
79+
},
80+
async insert(object: string, data: any) { rows(object).push({ ...data }); return { ...data }; },
81+
async update(object: string, data: any, options?: any) {
82+
const dispatch = assertEngineUpdateDispatch(data, options);
83+
// The record hook: accepts the call the way ObjectQL does, then refuses.
84+
if (object === refuseUpdateOf) throw refusal();
85+
const table = rows(object);
86+
if (dispatch.kind === 'multi') {
87+
let n = 0;
88+
for (let i = 0; i < table.length; i++) {
89+
if (matches(table[i], options?.where)) { table[i] = { ...table[i], ...data }; n++; }
90+
}
91+
return { updated: n };
92+
}
93+
const i = table.findIndex(r => r.id === dispatch.id);
94+
if (i >= 0) table[i] = { ...table[i], ...data };
95+
return i >= 0 ? { ...table[i] } : null;
96+
},
97+
async delete(object: string, options?: any) {
98+
const dispatch = assertEngineDeleteDispatch(options);
99+
const table = rows(object);
100+
const i = table.findIndex(r => r.id === (dispatch as any).id);
101+
if (i >= 0) table.splice(i, 1);
102+
return { id: (dispatch as any).id };
103+
},
104+
};
105+
}
106+
107+
/** start → approval → (approve) adopt the plan → end; (reject) → end. */
108+
function specialApprovalFlow(withFaultEdge: boolean) {
109+
return {
110+
name: 'plan_special_approval',
111+
label: 'Plan Special Approval',
112+
type: 'autolaunched',
113+
nodes: [
114+
{ id: 'start', type: 'start', label: 'Start' },
115+
{
116+
id: 'director', type: 'approval', label: 'Director Approval',
117+
config: { approvers: [{ type: 'user', value: 'director' }] },
118+
},
119+
{
120+
id: 'adopt_plan', type: 'update_record', label: 'Adopt Plan',
121+
config: { objectName: 'alloc_plan', filter: { id: 'p1' }, fields: { status: 'approved' } },
122+
},
123+
{ id: 'bounce_back', type: 'mark', label: 'Bounce back to the rep' },
124+
{ id: 'end', type: 'end', label: 'End' },
125+
],
126+
edges: [
127+
{ id: 'e1', source: 'start', target: 'director' },
128+
{ id: 'e2', source: 'director', target: 'adopt_plan', label: 'approve' },
129+
{ id: 'e3', source: 'director', target: 'end', label: 'reject' },
130+
{ id: 'e4', source: 'adopt_plan', target: 'end' },
131+
...(withFaultEdge
132+
? [
133+
{ id: 'ef', source: 'adopt_plan', target: 'bounce_back', type: 'fault' },
134+
{ id: 'e5', source: 'bounce_back', target: 'end' },
135+
]
136+
: []),
137+
],
138+
};
139+
}
140+
141+
describe('#34579 — a hook refusal on the step after an approval decision', () => {
142+
let marks: string[];
143+
144+
beforeEach(() => { marks = []; });
145+
146+
/** One live process: real engine, real CRUD + approval nodes, real approvals service. */
147+
function boot(opts: { withFaultEdge: boolean; refusal?: () => unknown }) {
148+
const data = makeFakeEngine('alloc_plan', opts.refusal ?? hookRefusal);
149+
data.tables.set('alloc_plan', [{ id: 'p1', status: 'submitted' }]);
150+
const service = new ApprovalService({ engine: data as any, logger: noopLogger });
151+
const automation = new AutomationEngine(noopLogger, new InMemorySuspendedRunStore());
152+
registerCrudNodes(automation, { logger: noopLogger, getService: (n: string) => (n === 'data' ? data : undefined) } as any);
153+
registerApprovalNode(automation, service, noopLogger);
154+
automation.registerNodeExecutor({
155+
type: 'mark',
156+
async execute(node: any) { marks.push(node.id); return { success: true }; },
157+
} as never);
158+
automation.registerFlow('plan_special_approval', specialApprovalFlow(opts.withFaultEdge) as never);
159+
service.attachAutomation(automation);
160+
return { data, service, automation };
161+
}
162+
163+
async function park(env: ReturnType<typeof boot>) {
164+
const started = await env.automation.execute('plan_special_approval', {
165+
object: 'alloc_plan', record: { id: 'p1', status: 'submitted' }, userId: 'rep',
166+
} as never);
167+
expect(started.status, 'the run must park at the approval node').toBe('paused');
168+
const req = (await env.data.find('sys_approval_request', { where: { status: 'pending' } }))[0];
169+
expect(req?.flow_run_id, 'the request must name the run it gates').toBeTruthy();
170+
return req;
171+
}
172+
173+
it('NO fault edge: still 500 RESUME_FAILED, and the envelope now carries the refusal the step met', async () => {
174+
const env = boot({ withFaultEdge: false });
175+
const req = await park(env);
176+
const runId = req.flow_run_id;
177+
178+
const err = await env.service
179+
.decide(req.id, { decision: 'approve', actorId: 'director' }, SYSTEM_CTX)
180+
.then(() => null, (e: Error) => e);
181+
182+
// #13807 B, unchanged: the door still throws, and the prose still names the run.
183+
expect(err, '⛔ not "return 200" — the status code does not move').toBeTruthy();
184+
expect(err?.message).toMatch(/^RESUME_FAILED: the approve decision was recorded on request /);
185+
expect(err?.message).toMatch(/could not be resumed and is now stranded/);
186+
187+
// The decision is durable and the plan did not move: the reported state.
188+
const row = (await env.data.find('sys_approval_request', { where: { id: req.id } }))[0];
189+
expect(row.status).toBe('approved');
190+
expect((await env.data.find('alloc_plan', { where: { id: 'p1' } }))[0].status).toBe('submitted');
191+
192+
// ⭐ The card's deliverable: the refusal, structured, beside the four facts.
193+
expect(strandedDecisionDetails(err)).toEqual({
194+
finalized: true,
195+
decision: 'approve',
196+
runId,
197+
repairable: true,
198+
innerRefusal: { code: 'VALIDATION_FAILED', message: hookRefusal().message },
199+
userMessage: HOOK_USER_TEXT,
200+
});
201+
});
202+
203+
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 () => {
204+
const env = boot({ withFaultEdge: true });
205+
const req = await park(env);
206+
const runId = req.flow_run_id;
207+
208+
const out = await env.service.decide(req.id, { decision: 'approve', actorId: 'director' }, SYSTEM_CTX);
209+
210+
expect(out.finalized).toBe(true);
211+
expect(out.decision).toBe('approve');
212+
expect(out.resumed, 'the run advanced through the fault edge').toBe(true);
213+
expect(out.resumeError).toBeUndefined();
214+
expect(marks, "the author's handler ran").toEqual(['bounce_back']);
215+
// Nothing left parked and nothing to repair: the run ended.
216+
expect(await env.automation.hasSuspendedRun(runId)).toBe(false);
217+
expect(strandedDecisionDetails(out as unknown)).toBeUndefined();
218+
});
219+
220+
it('reverse control: a step that FAULTS met no refusal — the envelope carries neither member', async () => {
221+
const env = boot({ withFaultEdge: false, refusal: () => new Error('ECONNREFUSED: could not reach the store') });
222+
const req = await park(env);
223+
224+
const err = await env.service
225+
.decide(req.id, { decision: 'approve', actorId: 'director' }, SYSTEM_CTX)
226+
.then(() => null, (e: Error) => e);
227+
228+
const details = strandedDecisionDetails(err);
229+
expect(details).toEqual({ finalized: true, decision: 'approve', runId: req.flow_run_id, repairable: true });
230+
expect(details && 'innerRefusal' in details).toBe(false);
231+
expect(details && 'userMessage' in details).toBe(false);
232+
});
233+
});

‎packages/rest/src/approvals-routes.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,14 @@ export function registerApprovalsEndpoints(this: ApprovalsRouteHost, basePath: s
254254
// same reason the strip above is: these four facts are
255255
// about a recorded-decision-with-stranded-run and
256256
// about nothing else.
257+
//
258+
// [#34579] …and, when the run stranded on a refusal,
259+
// that refusal: `innerRefusal` (ruling B′ on #24914,
260+
// the engine's own shape) and the marked `userMessage`
261+
// at the top level, the channel a record save's refusal
262+
// and every flow door's `FLOW_FAILED` already use. Both
263+
// are present only when the producer attached them and
264+
// the recogniser accepted them.
257265
...(code === 'RESUME_FAILED' && stranded ? stranded : {}),
258266
});
259267
return true;

0 commit comments

Comments
 (0)