From 3a0bc79591f00cb7488a62c507bc0474a8078f92 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 12:42:21 +0000 Subject: [PATCH 1/7] test(approvals): pin the hook refusal on resumeFailure for recall and the subflow-parent strand Claude-Session: https://claude.ai/code/session_012MmDsNmJFXm6DALa3xPdkp Co-authored-by: Claude --- .../src/resume-failure-refusal.test.ts | 290 ++++++++++++++++++ .../src/resume-failure-refusal.test.ts | 127 ++++++++ 2 files changed, 417 insertions(+) create mode 100644 packages/plugins/plugin-approvals/src/resume-failure-refusal.test.ts create mode 100644 packages/services/service-automation/src/resume-failure-refusal.test.ts diff --git a/packages/plugins/plugin-approvals/src/resume-failure-refusal.test.ts b/packages/plugins/plugin-approvals/src/resume-failure-refusal.test.ts new file mode 100644 index 00000000000..cf753f72e16 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/resume-failure-refusal.test.ts @@ -0,0 +1,290 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #34638 — the success-answer channel (`resumeFailure`) tells the hook refusal + * that stranded the run, the same pair the thrown `RESUME_FAILED` envelope + * carries since #34579. + * + * ## The gap + * + * #34579 put `innerRefusal` / `userMessage` on the ERROR envelope of the + * decision doors (`StrandedDecisionDetails`). Two doors tell a stranded run on + * a SUCCESS answer instead, through `resumeFailure` (`ResumeFailureReport`): + * + * - the recall door, whose own resume strands (recall never throws — #4420, + * upheld by the #16472 ruling); + * - the subflow-parent strand: the run this door resumed advanced, and the + * subflow PARENT it bubbled into then stranded (#15556) — reached through + * `decide` and through `recall` alike. + * + * Both told the strand with `code` / `runId` / `status` / `repairable` and no + * refusal, so an approver whose recall or subflow ran into a refusing record + * hook still read a stranded run with no reason. + * + * ## What is pinned + * + * 1. Recall into a refusing hook → `resumeFailure` carries `innerRefusal` + * (the engine's own `{ code, message }`) and the hook's marked + * `userMessage`, verbatim, in two locales. + * 2. A subflow parent that resumes into a refusing hook → the same, through + * the decision door and through the recall door. + * 3. CONTROL: a strand that met no refusal (a fault — a throw that declares + * no HTTP answer) carries NEITHER member: absent, not empty, never + * synthesised from the prose. + * + * The locale half: which sentence a declared refusal catalogue answers is the + * runtime's choice (`resolveHookRefusal`, held by its own tests). This file + * pins the carrier — whatever sentence the hook marked reaches the caller + * byte for byte, in either locale, and nothing on the way rewrites it. + */ + +import { describe, it, expect } from 'vitest'; +import { AutomationEngine, InMemorySuspendedRunStore, installBuiltinNodes } from '@objectstack/service-automation'; +import { assertEngineDeleteDispatch, assertEngineUpdateDispatch } from '@objectstack/objectql'; +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, as the runtime answers it per caller locale. */ +const LOCALES = [ + { locale: 'zh-CN', userText: '产能已被其他订单占用,该方案无法按当前产能通过。' }, + { locale: 'en', userText: 'Capacity is already taken by other orders; this plan cannot be adopted at current capacity.' }, +] as const; + +const HOOK_DIAGNOSTIC = "hook 'alloc_plan_capacity_recheck' threw: Error: over_capacity"; + +/** A declared hook refusal as the runtime answers one: code + status ride the error, the sentence is marked. */ +const hookRefusal = (userText: string) => () => Object.assign( + new Error(HOOK_DIAGNOSTIC), + { name: 'SandboxError', innerMessage: userText, code: 'VALIDATION_FAILED', status: 400, userMessage: userText }, +); + +/** A fault: a throw that declares no HTTP answer, so no refusal is met. */ +const fault = () => new Error('ECONNREFUSED: could not reach the store'); + +/** In-memory ObjectQL stand-in: approvals tables plus the plan the flows write; `alloc_plan` updates are refused. */ +function makeFakeEngine(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 === 'alloc_plan') 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 }; + }, + }; +} + +const writePlan = (id: string, status: string) => ({ + id, type: 'update_record', label: id, + config: { objectName: 'alloc_plan', filter: { id: 'p1' }, fields: { status } }, +}); + +/** start → approval → (approve) end; (reject = recall) release the plan → end. */ +const DIRECT = { + name: 'plan_direct', + label: 'Plan Direct', + type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'director', type: 'approval', label: 'Director', config: { approvers: [{ type: 'user', value: 'director' }] } }, + writePlan('release_plan', 'draft'), + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'director' }, + { id: 'e2', source: 'director', target: 'end', label: 'approve' }, + { id: 'e3', source: 'director', target: 'release_plan', label: 'reject' }, + { id: 'e4', source: 'release_plan', target: 'end' }, + ], +}; + +/** The CHILD hosts the approval and writes nothing — it always completes. */ +const CHILD = { + name: 'plan_child', + label: 'Plan Child', + type: 'autolaunched', + nodes: [ + { id: 'cstart', type: 'start', label: 'Start' }, + { id: 'director', type: 'approval', label: 'Director', config: { approvers: [{ type: 'user', value: 'director' }] } }, + { id: 'cend', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'c1', source: 'cstart', target: 'director' }, + { id: 'c2', source: 'director', target: 'cend', label: 'approve' }, + { id: 'c3', source: 'director', target: 'cend', label: 'reject' }, + ], +}; + +/** The PARENT parks at its subflow node, then writes the plan — the write the hook refuses. */ +const PARENT = { + name: 'plan_parent', + label: 'Plan Parent', + type: 'autolaunched', + nodes: [ + { id: 'pstart', type: 'start', label: 'Start' }, + { id: 'sub', type: 'subflow', label: 'Approval subflow', config: { flowName: 'plan_child' } }, + writePlan('adopt_plan', 'settled'), + { id: 'pend', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'p1', source: 'pstart', target: 'sub' }, + { id: 'p2', source: 'sub', target: 'adopt_plan' }, + { id: 'p3', source: 'adopt_plan', target: 'pend' }, + ], +}; + +/** One live process: real engine, real builtin + approval nodes, real approvals service. */ +function boot(refusal: () => unknown) { + const data = makeFakeEngine(refusal); + 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()); + installBuiltinNodes(automation, { logger: noopLogger, getService: (n: string) => (n === 'data' ? data : undefined) } as any); + registerApprovalNode(automation, service, noopLogger); + for (const flow of [DIRECT, CHILD, PARENT]) automation.registerFlow(flow.name, flow as never); + service.attachAutomation(automation); + return { data, service, automation }; +} + +/** Start `flow`, and hand back the pending request plus the started run's id. */ +async function park(env: ReturnType, flow: string) { + const started = await env.automation.execute(flow, { + object: 'alloc_plan', record: { id: 'p1', status: 'submitted' }, userId: 'rep', + } as never); + expect((started as any).status, 'the run parks').toBe('paused'); + const req = (await env.data.find('sys_approval_request', { where: { status: 'pending' } }))[0]; + expect(req?.flow_run_id, 'the request names the run it gates').toBeTruthy(); + return { req, startedRunId: (started as any).runId as string }; +} + +describe('#34638 — resumeFailure tells the hook refusal that stranded the run', () => { + describe.each(LOCALES)('recall into a refusing hook ($locale)', ({ userText }) => { + it('the recall answer\'s resumeFailure carries innerRefusal and the marked userMessage', async () => { + const env = boot(hookRefusal(userText)); + const { req } = await park(env, 'plan_direct'); + const runId = req.flow_run_id as string; + + // Recall never throws (#4420): the withdrawal stands and the strand is told. + const answer = await env.service.recall(req.id, { actorId: 'rep' }, SYSTEM_CTX); + expect(answer.request.status).toBe('recalled'); + expect(answer.resumed, "this door's own resume stranded").toBe(false); + expect((await env.data.find('alloc_plan', { where: { id: 'p1' } }))[0].status).toBe('submitted'); + + expect(answer.resumeFailure).toEqual({ + code: 'RESUME_FAILED', + runId, + status: 'stranded', + repairable: true, + innerRefusal: { code: 'VALIDATION_FAILED', message: HOOK_DIAGNOSTIC }, + userMessage: userText, + }); + }); + }); + + describe.each(LOCALES)('subflow parent resumes into a refusing hook ($locale)', ({ userText }) => { + it('through the decision door: resumeFailure names the PARENT and carries the refusal', async () => { + const env = boot(hookRefusal(userText)); + const { req, startedRunId: parentRunId } = await park(env, 'plan_parent'); + expect(req.flow_run_id, 'the request names the CHILD').not.toBe(parentRunId); + + const answer = await env.service.decide(req.id, { decision: 'approve', actorId: 'director' }, SYSTEM_CTX); + expect(answer.resumed, 'the child really did resume').toBe(true); + expect((await env.automation.getRun(parentRunId))?.status).toBe('failed'); + + expect(answer.resumeFailure).toEqual({ + code: 'RESUME_FAILED', + runId: parentRunId, + status: 'stranded', + repairable: true, + innerRefusal: { code: 'VALIDATION_FAILED', message: HOOK_DIAGNOSTIC }, + userMessage: userText, + }); + }); + + it('through the recall door: the same report, the PARENT\'s id on it', async () => { + const env = boot(hookRefusal(userText)); + const { req, startedRunId: parentRunId } = await park(env, 'plan_parent'); + + const answer = await env.service.recall(req.id, { actorId: 'rep' }, SYSTEM_CTX); + expect(answer.resumed, 'the child really did resume').toBe(true); + expect(answer.request.status).toBe('recalled'); + + expect(answer.resumeFailure).toEqual({ + code: 'RESUME_FAILED', + runId: parentRunId, + status: 'stranded', + repairable: true, + innerRefusal: { code: 'VALIDATION_FAILED', message: HOOK_DIAGNOSTIC }, + userMessage: userText, + }); + }); + }); + + describe('CONTROL — a strand that met no refusal carries neither member', () => { + const neitherMember = (report: unknown) => { + expect(report, 'the strand is still told').toBeDefined(); + expect(Object.keys(report as object).sort(), 'absent, not empty').toEqual(['code', 'repairable', 'runId', 'status']); + }; + + it('recall whose own run strands on a fault', async () => { + const env = boot(fault); + const { req } = await park(env, 'plan_direct'); + const answer = await env.service.recall(req.id, { actorId: 'rep' }, SYSTEM_CTX); + expect(answer.resumeFailure).toMatchObject({ code: 'RESUME_FAILED', runId: req.flow_run_id, status: 'stranded', repairable: true }); + neitherMember(answer.resumeFailure); + }); + + it('a subflow parent that strands on a fault, through the decision door', async () => { + const env = boot(fault); + const { req, startedRunId: parentRunId } = await park(env, 'plan_parent'); + const answer = await env.service.decide(req.id, { decision: 'approve', actorId: 'director' }, SYSTEM_CTX); + expect(answer.resumeFailure).toMatchObject({ code: 'RESUME_FAILED', runId: parentRunId, status: 'stranded', repairable: true }); + neitherMember(answer.resumeFailure); + }); + + it('a subflow parent that strands on a fault, through the recall door', async () => { + const env = boot(fault); + const { req, startedRunId: parentRunId } = await park(env, 'plan_parent'); + const answer = await env.service.recall(req.id, { actorId: 'rep' }, SYSTEM_CTX); + expect(answer.resumeFailure).toMatchObject({ code: 'RESUME_FAILED', runId: parentRunId, status: 'stranded', repairable: true }); + neitherMember(answer.resumeFailure); + }); + }); +}); diff --git a/packages/services/service-automation/src/resume-failure-refusal.test.ts b/packages/services/service-automation/src/resume-failure-refusal.test.ts new file mode 100644 index 00000000000..c12151d50ba --- /dev/null +++ b/packages/services/service-automation/src/resume-failure-refusal.test.ts @@ -0,0 +1,127 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #34638 — the engine half: a {@link SubflowParentStrand} carries the refusal + * the stranded PARENT met. + * + * `bubbleToParent` records the strand under the CHILD's run id when the parent + * it resumes lands on the `'stranded'` exit; `takeSubflowParentStrand` hands it + * to whichever caller resumed that child (the approvals decision and recall + * doors). The parent's own result already carries `innerRefusal` / + * `userMessage` (ruling B′ on #24914, `readCarriedRefusal` on the resume + * catch arm); the record kept only `runId`, `repairable` and `error`, so the + * caller that reads the strand could not tell WHY the parent stopped. The + * record now carries the pair as the parent's result reported it. + * + * CONTROL: a parent that strands on a fault met no refusal, so the record + * carries neither member — absent, never synthesised from `error`'s text. + */ + +import { describe, it, expect } from 'vitest'; +import { AutomationEngine } from './engine.js'; +import type { NodeExecutor } from './engine.js'; +import { InMemorySuspendedRunStore } from './suspended-run-store.js'; +import { registerSubflowNode } from './builtin/subflow-node.js'; +import { registerCrudNodes } from './builtin/crud-nodes.js'; +import { defineActionDescriptor } from '@objectstack/spec/automation'; +import type { AutomationContext } from '@objectstack/spec/contracts'; + +const noopLogger: any = { info() {}, warn() {}, error() {}, debug() {} }; +noopLogger.child = () => noopLogger; + +const HOOK_DIAGNOSTIC = "hook 'alloc_plan_capacity_recheck' threw: Error: over_capacity"; +const USER_TEXT = '产能已被其他订单占用,该方案无法按当前产能通过。'; + +/** A declared hook refusal as the runtime answers one. */ +const hookRefusal = () => Object.assign( + new Error(HOOK_DIAGNOSTIC), + { name: 'SandboxError', innerMessage: USER_TEXT, code: 'VALIDATION_FAILED', status: 400, userMessage: USER_TEXT }, +); +/** A fault: no declared HTTP answer, so no refusal is met. */ +const fault = () => new Error('ECONNREFUSED: could not reach the store'); + +const CHILD = { + name: 'child_flow', + label: 'Child', + type: 'autolaunched', + nodes: [ + { id: 'cstart', type: 'start', label: 'Start' }, + { id: 'park', type: 'pauser', label: 'Park' }, + { id: 'cend', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'c1', source: 'cstart', target: 'park' }, + { id: 'c2', source: 'park', target: 'cend' }, + ], +}; + +const PARENT = { + name: 'parent_flow', + label: 'Parent', + type: 'autolaunched', + nodes: [ + { id: 'pstart', type: 'start', label: 'Start' }, + { id: 'sub', type: 'subflow', label: 'Sub', config: { flowName: 'child_flow' } }, + { + id: 'adopt_plan', type: 'update_record', label: 'Adopt Plan', + config: { objectName: 'alloc_plan', filter: { id: 'p1' }, fields: { status: 'settled' } }, + }, + { id: 'pend', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'p1', source: 'pstart', target: 'sub' }, + { id: 'p2', source: 'sub', target: 'adopt_plan' }, + { id: 'p3', source: 'adopt_plan', target: 'pend' }, + ], +}; + +function boot(refusal: () => unknown) { + const data = { + async find() { return [{ id: 'p1', status: 'submitted' }]; }, + async update() { throw refusal(); }, + }; + const engine = new AutomationEngine(noopLogger, new InMemorySuspendedRunStore()); + const ctx = { logger: noopLogger, getService: (n: string) => (n === 'data' ? data : undefined) } as never; + registerSubflowNode(engine, ctx); + registerCrudNodes(engine, ctx); + engine.registerNodeExecutor({ + type: 'pauser', + descriptor: defineActionDescriptor({ + type: 'pauser', version: '1.0.0', name: 'pauser', + supportsPause: true, resumeAuthority: 'any', + }), + async execute() { return { success: true, suspend: true }; }, + } as NodeExecutor); + engine.registerFlow('child_flow', CHILD as never); + engine.registerFlow('parent_flow', PARENT as never); + return engine; +} + +async function strandThroughChild(engine: AutomationEngine) { + const started = await engine.execute('parent_flow', {} as AutomationContext); + expect(started.status).toBe('paused'); + const parentRunId = started.runId!; + const childRunId = engine.listSuspendedRuns().find(r => r.flowName === 'child_flow')!.runId; + expect((await engine.resume(childRunId)).success, "the child's own completion is genuine").toBe(true); + expect((await engine.getRun(parentRunId))?.status).toBe('failed'); + return { parentRunId, strand: engine.takeSubflowParentStrand(childRunId) }; +} + +describe('#34638 — a subflow parent strand carries the refusal the parent met', () => { + it('a parent refused by a record hook: the strand carries innerRefusal and the marked userMessage', async () => { + const { parentRunId, strand } = await strandThroughChild(boot(hookRefusal)); + expect(strand).toMatchObject({ + runId: parentRunId, + repairable: true, + innerRefusal: { code: 'VALIDATION_FAILED', message: HOOK_DIAGNOSTIC }, + userMessage: USER_TEXT, + }); + expect(typeof strand?.error).toBe('string'); + }); + + it('CONTROL — a parent that strands on a fault: neither member, absent rather than empty', async () => { + const { parentRunId, strand } = await strandThroughChild(boot(fault)); + expect(strand).toMatchObject({ runId: parentRunId, repairable: true }); + expect(Object.keys(strand ?? {}).sort()).toEqual(['error', 'repairable', 'runId']); + }); +}); From 279fa0b7b1e3988967e91dcb1df55859e677fd0a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 12:46:48 +0000 Subject: [PATCH 2/7] fix(approvals): resumeFailure tells the hook refusal behind a recall or subflow-parent strand ResumeFailureReport gains innerRefusal / userMessage (the names and shapes the thrown RESUME_FAILED carries); the engine's SubflowParentStrand carries the stranded parent's refusal; the recall door and every subflow-parent builder fill the pair when the strand met a refusal. Claude-Session: https://claude.ai/code/session_012MmDsNmJFXm6DALa3xPdkp Co-authored-by: Claude --- .../plugin-approvals/src/approval-service.ts | 66 ++++++++++++++----- .../services/service-automation/src/engine.ts | 15 +++++ .../service-automation/src/inner-refusal.ts | 5 +- .../spec/src/contracts/approval-service.ts | 65 ++++++++++++++---- .../resume-failure-report.pin.test.ts | 32 +++++++-- 5 files changed, 145 insertions(+), 38 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 03dc3fc143e..3bdcc4b9caa 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -441,10 +441,17 @@ export interface ApprovalResumeSurface { * run a caller of `decide`/`resumeRecordedOutcome` was resuming. Optional: * an engine that predates this member simply never reports a bubbled * strand, exactly as before this card. + * + * [#34638] `innerRefusal` / `userMessage` are the refusal the PARENT's + * downstream step met, when it met one — carried onto + * {@link ResumeFailureReport} so the strand is told with its reason. */ - takeSubflowParentStrand?(childRunId: string): { runId: string; repairable: boolean; error: string } | undefined; + takeSubflowParentStrand?(childRunId: string): SubflowParentStrandReport | undefined; } +/** The subflow-parent strand {@link ApprovalResumeSurface.takeSubflowParentStrand} hands back. */ +type SubflowParentStrandReport = { runId: string; repairable: boolean; error: string } & ResumeRefusal; + /** A run parked at a `map` node on one item, as {@link ApprovalResumeSurface.suspendedMapParentOf} answers it. */ type BatchParent = { runId: string; flowName: string; nodeId: string; correlation?: string }; @@ -5928,7 +5935,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega private async serviceResume( runId: string, signal: { output?: Record; branchLabel?: string; resumedBy?: string; impersonatedBy?: string }, - ): Promise<{ runId: string; repairable: boolean; error: string } | undefined> { + ): Promise { const result = await this.automation!.resume!(runId, { ...signal, [RESUME_AUTHORITY_SERVICE]: true }); const reported = result as | ({ success?: boolean; code?: string; error?: string; status?: string } & ResumeRefusal) @@ -5987,12 +5994,33 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * (#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. + * refused with. Read by the stranded-decision envelope and, on the success + * channel, by the recall door's own strand report (#34638). */ private static resumeRefusalOf(err: unknown): ResumeRefusal { return (err as { resumeRefusal?: ResumeRefusal } | undefined)?.resumeRefusal ?? {}; } + /** + * [#34638] The {@link ResumeFailureReport} for a subflow PARENT that + * stranded behind a resume this door issued — built in ONE place for the + * three doors that read such a strand (`resumeRecordedOutcome`, `recall`, + * `resumeBatchOfRecalledItem`), so they cannot drift on what the report + * carries: the parent's `runId` and `repairable`, and the refusal the + * parent's downstream step met when it met one (`{}` otherwise, so a + * fault-stranded parent reports neither member). + */ + private static parentStrandReport(strand: SubflowParentStrandReport): ResumeFailureReport { + return { + code: 'RESUME_FAILED', + runId: strand.runId, + status: 'stranded', + repairable: strand.repairable, + ...(strand.innerRefusal !== undefined ? { innerRefusal: strand.innerRefusal } : {}), + ...(strand.userMessage !== undefined ? { userMessage: strand.userMessage } : {}), + }; + } + /** * A decision or a comment attaches only files its caller uploaded. * @@ -6247,12 +6275,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega `RESUME_FAILED: ${what} was recorded on request ${requestId} and its own flow run '${runId}' ` + `resumed, but the subflow parent above it — run '${bubbleStrand.runId}' — consumed its ` + `suspension and is now stranded: ${bubbleStrand.error}`, - resumeFailure: { - code: 'RESUME_FAILED', - runId: bubbleStrand.runId, - status: 'stranded', - repairable: bubbleStrand.repairable, - }, + resumeFailure: ApprovalService.parentStrandReport(bubbleStrand), }; } return { resumed: true }; @@ -6673,12 +6696,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega `RESUME_FAILED: the recall was recorded on request ${requestId} and its own flow run ` + `'${runId}' resumed, but the subflow parent above it — run '${bubbleStrand.runId}' — ` + `consumed its suspension and is now stranded: ${bubbleStrand.error}`; - resumeFailure = { - code: 'RESUME_FAILED', - runId: bubbleStrand.runId, - status: 'stranded', - repairable: bubbleStrand.repairable, - }; + resumeFailure = ApprovalService.parentStrandReport(bubbleStrand); } } catch (err: any) { resumeError = err?.message ?? String(err); @@ -6706,7 +6724,14 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // legitimate by the member's own docblock ("An absent member means // no report was made, never that no run is stranded") and is what // `resumeRecordedOutcome` answers on those same exits. - resumeFailure = { code: 'RESUME_FAILED', runId, status: 'stranded', repairable: true }; + // + // [#34638] …and it tells the refusal the continuation met, when + // it met one — the pair the decision doors' thrown envelope + // carries since #34579, under the same names; `{}` for a fault. + resumeFailure = { + code: 'RESUME_FAILED', runId, status: 'stranded', repairable: true, + ...ApprovalService.resumeRefusalOf(err), + }; await this.journalStrandedContinuation(requestId, { branchLabel: APPROVAL_BRANCH_LABELS.reject, output: { decision: 'recall', requestId }, @@ -6800,7 +6825,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega `RESUME_FAILED: the recall was recorded on request ${requestId} and cancelled its run '${itemRunId}', ` + `and the batch run '${batchRunId}' above it resumed, but the subflow parent above that — run ` + `'${bubbleStrand.runId}' — consumed its suspension and is now stranded: ${bubbleStrand.error}`, - resumeFailure: { code: 'RESUME_FAILED', runId: bubbleStrand.runId, status: 'stranded', repairable: bubbleStrand.repairable }, + resumeFailure: ApprovalService.parentStrandReport(bubbleStrand), }; } catch (err: any) { const message = err?.message ?? String(err); @@ -6812,7 +6837,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega resumeError: `the recall was recorded on request ${requestId} and cancelled its run '${itemRunId}', but ${at} failed: ${message}`, // Only the engine's own stranded exit is told in fields, as in `recall`. ...(batchRunId && ApprovalService.resumeStatusOf(err) === 'stranded' - ? { resumeFailure: { code: 'RESUME_FAILED' as const, runId: batchRunId, status: 'stranded' as const, repairable: true } } + ? { + resumeFailure: { + code: 'RESUME_FAILED' as const, runId: batchRunId, status: 'stranded' as const, repairable: true, + ...ApprovalService.resumeRefusalOf(err), + }, + } : {}), }; } diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 505c49d9c29..d5c3c5a7b93 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -2161,6 +2161,17 @@ export interface SubflowParentStrand { repairable: true; /** The parent's own downstream failure text, verbatim — `resumeInternal`'s `error` for that run. */ error: string; + /** + * [#34638] The refusal the parent's downstream step met, as the parent's + * own result reported it (`AutomationResult.innerRefusal`, ruling B′ on + * #24914) — so the caller that reads this strand can tell WHY the parent + * stopped, as the thrown `RESUME_FAILED` tells it for a run's own strand + * (#34579). Absent when the parent stranded on a fault that met no + * refusal; ⛔ never synthesised from {@link error}'s text. + */ + innerRefusal?: FlowInnerRefusal; + /** [#34638] That refusal's producer-marked end-user text (`AutomationResult.userMessage`), verbatim; absent when none was marked. */ + userMessage?: string; } /** @@ -9511,6 +9522,10 @@ export class AutomationEngine implements IAutomationService { runId: parentRunId, repairable: true, error: parentRes.error ?? 'unknown error', + // [#34638] The refusal the parent met, off its own + // result (`{}` when it met none) — so the caller that + // takes this strand tells WHY, not only THAT. + ...carriedRefusalOfResult(parentRes), }); while (this.subflowParentStrands.size > MAX_CONSUMED_SUSPENSIONS) { const oldest = this.subflowParentStrands.keys().next().value; diff --git a/packages/services/service-automation/src/inner-refusal.ts b/packages/services/service-automation/src/inner-refusal.ts index 6f65f80145d..3baee406a13 100644 --- a/packages/services/service-automation/src/inner-refusal.ts +++ b/packages/services/service-automation/src/inner-refusal.ts @@ -144,7 +144,10 @@ export function refusalCarriedBy(err: unknown): CarriedRefusal { * - Resumed at the CHILD's run id instead (the up-bubble leg, and the only * leg a `map` item takes), the caller already holds the child's own * terminal result, which carries the members; the ancestors that leg fails - * record no member, and no caller reads their result. + * record no member, and no caller reads their result — except a PARENT + * that lands on the `'stranded'` exit, whose members ride the + * `SubflowParentStrand` the child's resumer takes (#34638, + * `carriedRefusalOfResult(parentRes)` in `bubbleToParent`). * * On every carrier, a failure that met no refusal carries no member, which the * spec's "present only when a refusal was met" allows and which never invents diff --git a/packages/spec/src/contracts/approval-service.ts b/packages/spec/src/contracts/approval-service.ts index 2d88493f3de..620c1f85e0b 100644 --- a/packages/spec/src/contracts/approval-service.ts +++ b/packages/spec/src/contracts/approval-service.ts @@ -26,7 +26,7 @@ // `./sharing-service.js` for the boundary and the measured consequence. import type { ExecutionContext } from '../kernel/execution-context.zod.js'; import type { ErrorCode } from '../api/error-code-ledger.zod.js'; -import type { ResumeFailureDetails } from '../api/automation-api.zod.js'; +import type { FlowInnerRefusal, ResumeFailureDetails } from '../api/automation-api.zod.js'; /** * Lifecycle states of an approval request, in the order the @@ -688,10 +688,17 @@ export interface ApprovalRecallInput { * (`api/automation-api.zod.ts`), the structure the automation resume door * already publishes inside its `400 FLOW_FAILED` `error.details` (#15221, the * ruling's third carrier). They are inherited here, never re-spelled, so the - * two cannot drift. What this adds is the one member a success envelope - * cannot leave to its envelope: on the resume door the registered code is - * the answer's own `code`; on a success answer nothing else names the - * failure class, so it rides here as {@link code}. + * two cannot drift. What this adds is what a success envelope + * cannot leave to its envelope: on the resume door the registered code is the + * answer's own `code`; on a success answer nothing else names the failure + * class, so it rides here as {@link code}. The same holds for the refusal that stranded + * the run (#34638): on the resume door `innerRefusal` rides beside these + * members in `error.details` (`FlowFailureDetailsSchema`) and `userMessage` + * at the envelope's top level, and on the decision doors' thrown + * `RESUME_FAILED` both ride the error body (#34579); a success answer has no + * envelope to carry either, so they ride here as {@link innerRefusal} and + * {@link userMessage} — the same names and shapes, so a caller reads one + * spelling on every channel. * * ⛔ Which is exactly why `ResumeFailureDetailsSchema` is NOT the reader for * this member. That schema declares the three shared members and not @@ -720,7 +727,8 @@ export interface ApprovalRecallInput { * stands), and it stays exactly as it is. This structure is what a success * answer carries, and `finalized` / `decision` are already top-level members * of the results that carry it. The two share the `runId` / `repairable` - * vocabulary through the spec declaration, on purpose. + * vocabulary through the spec declaration, on purpose — and the refusal pair + * ({@link innerRefusal}, {@link userMessage}) by the same names and shapes. * * Two halves of ONE telling. The prose `resumeError` beside this member is * the human-readable half; this is the machine-readable half. A producer @@ -745,6 +753,33 @@ export interface ResumeFailureReport extends ResumeFailureDetails { * purpose: a success answer has no envelope `code` to fall back on. */ code: ErrorCode; + /** + * [#34638] The refusal the stranded run's next step 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 value the decision + * doors' thrown `RESUME_FAILED` carries since #34579 (`innerRefusal` on + * `StrandedDecisionDetails`), told on the success channel for the strands + * that channel reports: a recall whose own resume stranded, and a subflow + * PARENT that stranded behind a resume that succeeded. + * + * Optional, and absent when the run stranded on a fault that met no refusal + * (a crash, an unreachable store) — ⛔ never synthesised from the prose, and + * never part of the failure class: {@link code} and {@link repairable} are + * read the same way with or without it. + */ + innerRefusal?: FlowInnerRefusal; + /** + * [#34638] 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. + * Same semantics as on every other channel that carries it (the record + * save's error body, every flow door's `FLOW_FAILED`, the decision doors' + * `RESUME_FAILED`): presence IS the marking. Absent when the run met no + * marked refusal. + */ + userMessage?: string; } /** Result of a recall. */ @@ -781,7 +816,9 @@ export interface ApprovalRecallResult { * The machine-readable half of a resume failure this recall tolerated * (#15970; the #16472 ruling): the registered code, the `runId` of the run * that is actually stranded — which need not be {@link runId}, the run this - * request gated — and whether the engine says it is repairable. + * request gated — and whether the engine says it is repairable; and, when + * the strand met a refusal, that refusal (`innerRefusal` / `userMessage`, + * #34638). * * Optional and ADDITIVE. ⚠️ An absent member means no report was made, * never that no run is stranded: a producer that predates this field @@ -891,11 +928,12 @@ export interface ApprovalDecisionResult { * 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 - * reports the other event of the #16472 ruling — a resume failure behind an - * answer that still succeeded. + * ⛔ They are not top-level 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. The other event of the #16472 + * ruling — a resume failure behind an answer that still succeeded — is told + * on {@link resumeFailure}, which carries the same pair under the same + * names when THAT strand met a refusal (#34638). */ resumed?: boolean; /** @@ -916,7 +954,8 @@ export interface ApprovalDecisionResult { * answer (#15556; the #16472 ruling): the registered code, the `runId` of * the run that is actually stranded — the PARENT's when the strand is a * subflow's bubble-up, never the healthy child's that {@link runId} names — - * and whether the engine says it is repairable. + * and whether the engine says it is repairable; and, when the strand met a + * refusal, that refusal (`innerRefusal` / `userMessage`, #34638). * * Optional and ADDITIVE. ⚠️ An absent member means no report was made, * never that no run is stranded: a producer that predates this field diff --git a/packages/spec/src/contracts/resume-failure-report.pin.test.ts b/packages/spec/src/contracts/resume-failure-report.pin.test.ts index 062150318e8..4d30137cc46 100644 --- a/packages/spec/src/contracts/resume-failure-report.pin.test.ts +++ b/packages/spec/src/contracts/resume-failure-report.pin.test.ts @@ -13,12 +13,13 @@ * it is NOT a second declaration: its shared members are inherited from * `ResumeFailureDetails` (`api/automation-api.zod.ts`, the automation resume * door's `400 FLOW_FAILED` details — the ruling's third carrier, #15221), and - * it adds exactly the one member a success envelope cannot leave to its - * envelope, the code. + * it adds exactly what a success envelope cannot leave to its envelope: the + * code, and (#34638) the refusal that stranded the run, `innerRefusal` / + * `userMessage`, which the resume door carries on its envelope instead. * * Four things are pinned, because each drifts on its own: * - * 1. **Declared once.** `ResumeFailureReport` minus `code` IS + * 1. **Declared once.** `ResumeFailureReport` minus what it adds IS * `ResumeFailureDetails` — a type-level identity (`Eq`, the * `automation-result-status.pin.test.ts` form), so a member added to or * dropped from either side reds this file by name under @@ -58,7 +59,7 @@ import { fileURLToPath } from 'node:url'; import { describe, it, expect } from 'vitest'; import { ResumeFailureDetailsSchema } from '../api/automation-api.zod'; -import type { ResumeFailureDetails } from '../api/automation-api.zod'; +import type { FlowInnerRefusal, ResumeFailureDetails } from '../api/automation-api.zod'; import { REGISTERED_ERROR_CODES } from '../api/error-code-ledger.zod'; import type { ErrorCode } from '../api/error-code-ledger.zod'; @@ -78,8 +79,15 @@ type Assert< T extends true > = T; * pin no program compiles is no pin at all (`check:test-typecheck` compiles * this file under `tsconfig.test.json`). */ -/** 1. Declared once: the report minus its code IS the wire schema's input type. */ -export type ReportSharesTheWireMembers = Assert< Eq< Omit, ResumeFailureDetails > >; +/** + * 1. Declared once: the report minus what it adds IS the wire schema's input + * type. It adds the code and (#34638) the refusal pair — the members the + * resume door leaves to its envelope and a success answer has no envelope for. + */ +export type ReportSharesTheWireMembers = Assert< Eq< Omit, ResumeFailureDetails > >; +/** [#34638] The refusal pair, at the shapes every other channel spells it: the engine's `FlowInnerRefusal` and a string, both optional. */ +export type RefusalIsTheEngineShape = Assert< Eq< ResumeFailureReport['innerRefusal'], FlowInnerRefusal | undefined > >; +export type UserMessageIsOptionalText = Assert< Eq< ResumeFailureReport['userMessage'], string | undefined > >; /** 3. The code member is the ledger vocabulary, exactly. */ export type CodeIsTheLedgerVocabulary = Assert< Eq< ResumeFailureReport['code'], ErrorCode > >; /** 3. …and it is required — `undefined` is not a member of its type. */ @@ -145,6 +153,18 @@ describe('ResumeFailureReport — the resume failure a success answer carries', expect(Object.keys(strandedParent).sort()).toEqual([...Object.keys(parsed), 'code'].sort()); }); + it('1. [#34638] a report that carries the refusal pair still hands back exactly the three shared members', () => { + // The pair is the report's own, like `code`: the resume door carries it on + // its envelope (`FlowFailureDetailsSchema.innerRefusal`, top-level + // `userMessage`), so the shared wire schema neither declares nor keeps it. + const refused: ResumeFailureReport = { + ...strandedParent, + innerRefusal: { code: 'VALIDATION_FAILED', message: 'over capacity' }, + userMessage: 'Capacity is taken.', + }; + expect(ResumeFailureDetailsSchema.parse(refused)).toEqual({ runId: 'run_parent_001', status: 'stranded', repairable: true }); + }); + it('1. the wire schema strips that code SILENTLY, and the docblock no longer sends a caller down that path', () => { // [#17929] The type docblock used to invite a caller to parse this member // with the wire schema. The invitation deleted the one member the same From 6f933854480f65d22cc3dbb495decfea3b0fcdcc Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 12:49:33 +0000 Subject: [PATCH 3/7] test(automation): the strand pins name the failure they measure Claude-Session: https://claude.ai/code/session_012MmDsNmJFXm6DALa3xPdkp Co-authored-by: Claude --- .../src/resume-failure-refusal.test.ts | 10 ++++++---- .../src/resume-failure-refusal.test.ts | 5 +++-- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/resume-failure-refusal.test.ts b/packages/plugins/plugin-approvals/src/resume-failure-refusal.test.ts index cf753f72e16..f20ce6ad7c8 100644 --- a/packages/plugins/plugin-approvals/src/resume-failure-refusal.test.ts +++ b/packages/plugins/plugin-approvals/src/resume-failure-refusal.test.ts @@ -258,8 +258,10 @@ describe('#34638 — resumeFailure tells the hook refusal that stranded the run' }); describe('CONTROL — a strand that met no refusal carries neither member', () => { - const neitherMember = (report: unknown) => { + const neitherMember = (answer: { resumeFailure?: unknown; resumeError?: string }) => { + const report = answer.resumeFailure; expect(report, 'the strand is still told').toBeDefined(); + expect(answer.resumeError, 'and it is the fault, not some other failure').toContain('ECONNREFUSED'); expect(Object.keys(report as object).sort(), 'absent, not empty').toEqual(['code', 'repairable', 'runId', 'status']); }; @@ -268,7 +270,7 @@ describe('#34638 — resumeFailure tells the hook refusal that stranded the run' const { req } = await park(env, 'plan_direct'); const answer = await env.service.recall(req.id, { actorId: 'rep' }, SYSTEM_CTX); expect(answer.resumeFailure).toMatchObject({ code: 'RESUME_FAILED', runId: req.flow_run_id, status: 'stranded', repairable: true }); - neitherMember(answer.resumeFailure); + neitherMember(answer); }); it('a subflow parent that strands on a fault, through the decision door', async () => { @@ -276,7 +278,7 @@ describe('#34638 — resumeFailure tells the hook refusal that stranded the run' const { req, startedRunId: parentRunId } = await park(env, 'plan_parent'); const answer = await env.service.decide(req.id, { decision: 'approve', actorId: 'director' }, SYSTEM_CTX); expect(answer.resumeFailure).toMatchObject({ code: 'RESUME_FAILED', runId: parentRunId, status: 'stranded', repairable: true }); - neitherMember(answer.resumeFailure); + neitherMember(answer); }); it('a subflow parent that strands on a fault, through the recall door', async () => { @@ -284,7 +286,7 @@ describe('#34638 — resumeFailure tells the hook refusal that stranded the run' const { req, startedRunId: parentRunId } = await park(env, 'plan_parent'); const answer = await env.service.recall(req.id, { actorId: 'rep' }, SYSTEM_CTX); expect(answer.resumeFailure).toMatchObject({ code: 'RESUME_FAILED', runId: parentRunId, status: 'stranded', repairable: true }); - neitherMember(answer.resumeFailure); + neitherMember(answer); }); }); }); diff --git a/packages/services/service-automation/src/resume-failure-refusal.test.ts b/packages/services/service-automation/src/resume-failure-refusal.test.ts index c12151d50ba..ba77d2aaa49 100644 --- a/packages/services/service-automation/src/resume-failure-refusal.test.ts +++ b/packages/services/service-automation/src/resume-failure-refusal.test.ts @@ -98,7 +98,7 @@ function boot(refusal: () => unknown) { } async function strandThroughChild(engine: AutomationEngine) { - const started = await engine.execute('parent_flow', {} as AutomationContext); + const started = await engine.execute('parent_flow', { userId: 'rep' } as AutomationContext); expect(started.status).toBe('paused'); const parentRunId = started.runId!; const childRunId = engine.listSuspendedRuns().find(r => r.flowName === 'child_flow')!.runId; @@ -116,12 +116,13 @@ describe('#34638 — a subflow parent strand carries the refusal the parent met' innerRefusal: { code: 'VALIDATION_FAILED', message: HOOK_DIAGNOSTIC }, userMessage: USER_TEXT, }); - expect(typeof strand?.error).toBe('string'); + expect(strand?.error, 'the strand is the hook refusal, not another failure').toContain(HOOK_DIAGNOSTIC); }); it('CONTROL — a parent that strands on a fault: neither member, absent rather than empty', async () => { const { parentRunId, strand } = await strandThroughChild(boot(fault)); expect(strand).toMatchObject({ runId: parentRunId, repairable: true }); + expect(strand?.error, 'the strand is the fault, not another failure').toContain('ECONNREFUSED'); expect(Object.keys(strand ?? {}).sort()).toEqual(['error', 'repairable', 'runId']); }); }); From 2c8a3e95dad4bc4c4c647c71036add4365a29726 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 12:59:28 +0000 Subject: [PATCH 4/7] chore(changeset): resumeFailure carries the hook refusal Claude-Session: https://claude.ai/code/session_012MmDsNmJFXm6DALa3xPdkp Co-authored-by: Claude --- .changeset/34638-resume-failure-refusal.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 .changeset/34638-resume-failure-refusal.md diff --git a/.changeset/34638-resume-failure-refusal.md b/.changeset/34638-resume-failure-refusal.md new file mode 100644 index 00000000000..a187babb1a6 --- /dev/null +++ b/.changeset/34638-resume-failure-refusal.md @@ -0,0 +1,18 @@ +--- +'@objectstack/spec': patch +'@objectstack/service-automation': patch +'@objectstack/plugin-approvals': patch +--- + +fix(approvals): a recall or subflow-parent strand reports the hook refusal that stranded the run + +Clause-②: yes +Metadata-protocol: none + +When an approval decision strands its flow run because the next step was refused (a record hook's declared refusal, a validation rule, a permission), the thrown `RESUME_FAILED` already carries `innerRefusal` and the refusal's marked `userMessage`. Two doors report a stranded run on a success answer instead, through `resumeFailure`: the recall door, whose own resume stranded, and a subflow parent that stranded after the run this door resumed advanced (through `decide` and through `recall`). Those reports carried `code`, `runId`, `status` and `repairable` only, so the approver saw a stranded run with no reason. + +- `ResumeFailureReport` (`@objectstack/spec/contracts`) gains two optional members, `innerRefusal` (`{ code, message }`, the engine's `AutomationResult.innerRefusal`) and `userMessage` (the declared sentence in the caller's locale). The names and shapes are the ones the thrown `RESUME_FAILED` uses. Both are absent when the strand met no refusal (a fault), and neither changes how `code` and `repairable` are read. `ResumeFailureDetailsSchema` is unchanged. On the resume door these members already ride the error envelope. +- `AutomationEngine.takeSubflowParentStrand` now returns the stranded parent's `innerRefusal` / `userMessage` beside `runId`, `repairable` and `error`, read from the parent's own result. +- The approvals recall door and the subflow-parent strand fill both members whenever the strand met a refusal. + +No migration: the change only adds optional members, and a caller that ignores them reads exactly what it read before. From 3e227fa3f313c665d4b0595bec1db2b07694cbea Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 13:31:29 +0000 Subject: [PATCH 5/7] chore(gates): the engine-double ledger records the new resumeFailure refusal pin Claude-Session: https://claude.ai/code/session_012MmDsNmJFXm6DALa3xPdkp Co-authored-by: Claude --- scripts/engine-double-contract.pinned.json | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index cd593c9c3ea..24a816191b5 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -3636,6 +3636,16 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/plugins/plugin-approvals/src/resume-failure-refusal.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/plugins/plugin-approvals/src/resume-failure-refusal.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/plugins/plugin-approvals/src/run-status-liveness.test.ts", "verb": "delete", From 34fd229f09136ea0e985c94d75969cc6771cfeba Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 02:35:15 +0000 Subject: [PATCH 6/7] docs(spec): ResumeFailureReport.userMessage names the run's locale; the strip paragraph counts the refusal pair Claude-Session: https://claude.ai/code/session_012MmDsS4GoHCgYwA2uv3n3C Co-authored-by: Claude --- .changeset/34638-resume-failure-refusal.md | 4 +- .../spec/src/contracts/approval-service.ts | 50 ++++++++++++------- 2 files changed, 35 insertions(+), 19 deletions(-) diff --git a/.changeset/34638-resume-failure-refusal.md b/.changeset/34638-resume-failure-refusal.md index a187babb1a6..840704c20d9 100644 --- a/.changeset/34638-resume-failure-refusal.md +++ b/.changeset/34638-resume-failure-refusal.md @@ -11,8 +11,8 @@ Metadata-protocol: none When an approval decision strands its flow run because the next step was refused (a record hook's declared refusal, a validation rule, a permission), the thrown `RESUME_FAILED` already carries `innerRefusal` and the refusal's marked `userMessage`. Two doors report a stranded run on a success answer instead, through `resumeFailure`: the recall door, whose own resume stranded, and a subflow parent that stranded after the run this door resumed advanced (through `decide` and through `recall`). Those reports carried `code`, `runId`, `status` and `repairable` only, so the approver saw a stranded run with no reason. -- `ResumeFailureReport` (`@objectstack/spec/contracts`) gains two optional members, `innerRefusal` (`{ code, message }`, the engine's `AutomationResult.innerRefusal`) and `userMessage` (the declared sentence in the caller's locale). The names and shapes are the ones the thrown `RESUME_FAILED` uses. Both are absent when the strand met no refusal (a fault), and neither changes how `code` and `repairable` are read. `ResumeFailureDetailsSchema` is unchanged. On the resume door these members already ride the error envelope. +- `ResumeFailureReport` (`@objectstack/spec/contracts`) gains two optional members, `innerRefusal` (`{ code, message }`, the engine's `AutomationResult.innerRefusal`) and `userMessage` (the declared sentence in the language of whoever started the run, since a resumed leg keeps the starter's locale; the authored message when no person started the run). The names and shapes are the ones the thrown `RESUME_FAILED` uses. `innerRefusal` is absent when the strand met no refusal (a fault), and `userMessage` is absent unless the failure carried a marked end-user text, so it can ride alone; neither changes how `code` and `repairable` are read. `ResumeFailureDetailsSchema` is unchanged. On the resume door these members already ride the error envelope. - `AutomationEngine.takeSubflowParentStrand` now returns the stranded parent's `innerRefusal` / `userMessage` beside `runId`, `repairable` and `error`, read from the parent's own result. -- The approvals recall door and the subflow-parent strand fill both members whenever the strand met a refusal. +- The approvals recall door and the subflow-parent strand fill both members whenever the strand met a refusal, read the way the thrown `RESUME_FAILED` reads them: an `innerRefusal` whose `code` is outside the registered error codes or whose `message` is not a string, and a blank or non-string `userMessage`, are dropped, so a node that returns a malformed pair answers the same on the success channel as on the thrown one. No migration: the change only adds optional members, and a caller that ignores them reads exactly what it read before. diff --git a/packages/spec/src/contracts/approval-service.ts b/packages/spec/src/contracts/approval-service.ts index 620c1f85e0b..c638779108f 100644 --- a/packages/spec/src/contracts/approval-service.ts +++ b/packages/spec/src/contracts/approval-service.ts @@ -701,18 +701,20 @@ export interface ApprovalRecallInput { * spelling on every channel. * * ⛔ Which is exactly why `ResumeFailureDetailsSchema` is NOT the reader for - * this member. That schema declares the three shared members and not - * {@link code}, and it is a plain non-strict `z.object`: parsing a report - * with it SILENTLY STRIPS the code — the parse SUCCEEDS, raises no - * `unrecognized_keys` issue, logs nothing, and hands back an object whose - * failure class is simply gone. The one member the paragraph above calls - * indispensable is the one the act of validating removes, and nothing in the - * result says so. On the resume door that schema is the right reader, - * because there the registered code rides on the `error` envelope it parses - * beside; here there is no envelope, so read {@link code} off the report - * itself — it is typed `ErrorCode`, required, and needs no parse at all. Use - * that schema on this member to read the three shared facts if you like, - * ⛔ never as a way to obtain the report. Both halves are measured in + * this member. That schema declares the three shared members and none of + * {@link code}, {@link innerRefusal} or {@link userMessage}, and it is a plain + * non-strict `z.object`: parsing a report with it SILENTLY STRIPS all three — + * the parse SUCCEEDS, raises no `unrecognized_keys` issue, logs nothing, and + * hands back an object whose failure class and refusal are simply gone. The + * one member the paragraph above calls indispensable, the code, is among + * those the act of validating removes, and nothing in the result says so. On + * the resume door that schema is the right reader, because there the + * registered code rides on the `error` envelope it parses beside, and the + * refusal pair on that envelope too; here there is no envelope, so read + * {@link code}, {@link innerRefusal} and {@link userMessage} off the report + * itself — the code is typed `ErrorCode`, required, and needs no parse at + * all. Use that schema on this member to read the three shared facts if you + * like, ⛔ never as a way to obtain the report. Both halves are measured in * `contracts/resume-failure-report.pin.test.ts`. * * ⛔ No new error code is minted under the ruling. `code` is typed as @@ -761,7 +763,10 @@ export interface ResumeFailureReport extends ResumeFailureDetails { * doors' thrown `RESUME_FAILED` carries since #34579 (`innerRefusal` on * `StrandedDecisionDetails`), told on the success channel for the strands * that channel reports: a recall whose own resume stranded, and a subflow - * PARENT that stranded behind a resume that succeeded. + * PARENT that stranded behind a resume that succeeded. Read the way the + * thrown envelope reads it: a value outside the declared shape (a `code` + * outside the closed ADR-0112 set, a `message` that is not a string) is + * dropped, never relayed. * * Optional, and absent when the run stranded on a fault that met no refusal * (a crash, an unreachable store) — ⛔ never synthesised from the prose, and @@ -772,12 +777,23 @@ export interface ResumeFailureReport extends ResumeFailureDetails { /** * [#34638] 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. + * a `refusals` catalogue this is the declared sentence in the RUN's locale + * (`AutomationContext.locale`, `contracts/automation-service.ts`), while + * {@link innerRefusal}'s `message` keeps the diagnostic text. Every strand + * this report tells is a resumed leg, and a resumed leg renders in the + * language of whoever STARTED the run — usually the submitter, not this + * report's caller: a resume carries no locale of its own, and the decider's + * segment takes the decider's identity and grants and keeps the starter's + * locale. A run no person started (a record-change, schedule or webhook + * trigger) carries no locale, so there the sentence is the catalogue's + * authored message. + * * Same semantics as on every other channel that carries it (the record * save's error body, every flow door's `FLOW_FAILED`, the decision doors' - * `RESUME_FAILED`): presence IS the marking. Absent when the run met no - * marked refusal. + * `RESUME_FAILED`): presence IS the marking, and a blank or non-string + * value is no marking, so it is dropped. Absent when the run met no marked + * refusal; it can ride without {@link innerRefusal} (a marked failure that + * was no refusal). */ userMessage?: string; } From c5762e51cebe16ea10b9faad362203a43a2f2ffc Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 02:36:38 +0000 Subject: [PATCH 7/7] fix(approvals): the success channel reads the refusal pair the way the thrown RESUME_FAILED does Claude-Session: https://claude.ai/code/session_012MmDsS4GoHCgYwA2uv3n3C Co-authored-by: Claude --- .../plugin-approvals/src/approval-service.ts | 52 ++++++++--- .../batch-item-recall-resumes-batch.test.ts | 29 ++++++- .../src/resume-failure-refusal.test.ts | 86 ++++++++++++++++++- 3 files changed, 150 insertions(+), 17 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 3bdcc4b9caa..a26a26d029c 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, type StrandedDecisionDetails } from '@objectstack/types'; +import { declaredUserMessage, 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 @@ -61,6 +61,7 @@ import type { // what forced this file to cast its way out of its own contract to read // fields the caller had already supplied. import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { FlowInnerRefusalSchema } from '@objectstack/spec/api'; import { RESUME_AUTHORITY_SERVICE } from '@objectstack/spec/contracts'; import type { IOwnershipQueueService } from '@objectstack/spec/contracts'; import { @@ -5953,14 +5954,13 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // (`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 } : {}), - }; - } + // found `status` too. [#34638] Read here, once, through + // {@link recognisedRefusal}: two channels read this value — the thrown + // envelope (whose recogniser in `@objectstack/types` reads it again) + // and the success channel's own strand reports (`recall`, + // `resumeBatchOfRecalledItem`), which have no recogniser after this line. + const refusal = ApprovalService.recognisedRefusal(reported); + if (refusal.innerRefusal !== undefined || refusal.userMessage !== undefined) err.resumeRefusal = refusal; throw err; } return this.automation?.takeSubflowParentStrand?.(runId); @@ -6001,6 +6001,34 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega return (err as { resumeRefusal?: ResumeRefusal } | undefined)?.resumeRefusal ?? {}; } + /** + * [#34638] The refusal pair an engine result or a subflow-parent strand + * carries, read the way the thrown `RESUME_FAILED` reads it + * (`strandedDecisionDetails`, `@objectstack/types`), so the two approvals + * channels answer one engine result the same way. The engine relays what + * a node executor returned unchecked, and node types are open to plugins: + * + * - `innerRefusal` is kept only in its declared shape, read by the spec's + * own `FlowInnerRefusalSchema` — a `code` in the closed ADR-0112 set and + * a string `message`; anything else is dropped, never relayed; + * - `userMessage` is kept only as `declaredUserMessage` reads a marking — + * a blank or non-string value is no marking. + * + * A member that fails its read is dropped and the strand is still told. + * Applied where the pair is built for the success channel: + * {@link serviceResume} (a rejected resume) and {@link parentStrandReport}. + */ + private static recognisedRefusal(source: { innerRefusal?: unknown; userMessage?: unknown }): ResumeRefusal { + const innerRefusal = source.innerRefusal === undefined + ? undefined + : FlowInnerRefusalSchema.safeParse(source.innerRefusal); + const userMessage = declaredUserMessage(source); + return { + ...(innerRefusal?.success ? { innerRefusal: innerRefusal.data } : {}), + ...(userMessage !== undefined ? { userMessage } : {}), + }; + } + /** * [#34638] The {@link ResumeFailureReport} for a subflow PARENT that * stranded behind a resume this door issued — built in ONE place for the @@ -6008,7 +6036,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * `resumeBatchOfRecalledItem`), so they cannot drift on what the report * carries: the parent's `runId` and `repairable`, and the refusal the * parent's downstream step met when it met one (`{}` otherwise, so a - * fault-stranded parent reports neither member). + * fault-stranded parent reports neither member), read through + * {@link recognisedRefusal}. */ private static parentStrandReport(strand: SubflowParentStrandReport): ResumeFailureReport { return { @@ -6016,8 +6045,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega runId: strand.runId, status: 'stranded', repairable: strand.repairable, - ...(strand.innerRefusal !== undefined ? { innerRefusal: strand.innerRefusal } : {}), - ...(strand.userMessage !== undefined ? { userMessage: strand.userMessage } : {}), + ...ApprovalService.recognisedRefusal(strand), }; } diff --git a/packages/plugins/plugin-approvals/src/batch-item-recall-resumes-batch.test.ts b/packages/plugins/plugin-approvals/src/batch-item-recall-resumes-batch.test.ts index 0cd079bc808..b28b12eacfb 100644 --- a/packages/plugins/plugin-approvals/src/batch-item-recall-resumes-batch.test.ts +++ b/packages/plugins/plugin-approvals/src/batch-item-recall-resumes-batch.test.ts @@ -173,7 +173,7 @@ function wireReplica( fake: ReturnType, store: InMemorySuspendedRunStore | ObjectStoreSuspendedRunStore, clock: { now: () => Date }, - onPeek: (seen: { results: unknown; count: unknown }) => void, + onPeek: (seen: { results: unknown; count: unknown }) => void | Record, ) { const service = new ApprovalService({ engine: fake as any, logger: silentLogger(), clock }); const automation = new AutomationEngine(silentLogger(), store); @@ -189,8 +189,8 @@ function wireReplica( automation.registerNodeExecutor({ type: 'peek', async execute(_node: any, variables: Map) { - onPeek({ results: variables.get('signoffResults'), count: variables.get('signoffs.count') }); - return { success: true }; + // A peek may answer a failure of its own (#34638's refused batch resume). + return onPeek({ results: variables.get('signoffResults'), count: variables.get('signoffs.count') }) ?? { success: true }; }, } as never); automation.registerFlow('task_signoff', TASK_SIGNOFF as never); @@ -505,3 +505,26 @@ describe('a revise-window recall finds its batch past the first page of parked r expect(await storedRun(fan.runId!)).toMatchObject({ node_id: 'fan', correlation: `map:${req.flow_run_id}`, status: 'paused' }); }); }); + +describe('#34638 — a refused batch resume after a revise-window recall tells the refusal on resumeFailure', () => { + it('the batch strands on its next step\'s refusal: resumeFailure names the batch run and carries the pair', async () => { + const fake = makeFakeEngine(); + const refusal = { innerRefusal: { code: 'VALIDATION_FAILED', message: 'over capacity' }, userMessage: 'Capacity is already taken.' }; + const { automation, service } = wireReplica(fake, new InMemorySuspendedRunStore(), tickingClock(), + () => ({ success: false, error: 'peek refused', ...refusal })); + const paused = await automation.execute('release_signoff', { + userId: 'submitter', params: { items: [{ id: 't1', title: 'Task t1' }] }, + } as never); + const batchRunId = paused.runId!; + const item = (await fake.find('sys_approval_request', { where: { record_id: 't1', status: 'pending' } }))[0]; + await service.sendBack(item.id, { actorId: 'u1' }, asUser('u1')); + + const out = await service.recall(item.id, { actorId: 'submitter' }, asUser('submitter')); + + expect(out.request.status).toBe('recalled'); + expect(out.resumeError, 'the batch resume is the failure told').toContain(`resuming the batch run '${batchRunId}'`); + expect(out.resumeFailure).toEqual({ + code: 'RESUME_FAILED', runId: batchRunId, status: 'stranded', repairable: true, ...refusal, + }); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/resume-failure-refusal.test.ts b/packages/plugins/plugin-approvals/src/resume-failure-refusal.test.ts index f20ce6ad7c8..b3809a0c19e 100644 --- a/packages/plugins/plugin-approvals/src/resume-failure-refusal.test.ts +++ b/packages/plugins/plugin-approvals/src/resume-failure-refusal.test.ts @@ -31,6 +31,13 @@ * 3. CONTROL: a strand that met no refusal (a fault — a throw that declares * no HTTP answer) carries NEITHER member: absent, not empty, never * synthesised from the prose. + * 4. The pair is READ the way the thrown `RESUME_FAILED` reads it + * (`strandedDecisionDetails`): the engine relays whatever a node executor + * returns, and node types are open to plugins, so a plugin node's blank + * `userMessage`, or an `innerRefusal` whose `code` is unregistered or + * whose `message` is no string, reaches the recall answer WITHOUT that + * member — on the recall's own strand and on a subflow parent's — while a + * well-formed pair still rides (CONTROL). * * The locale half: which sentence a declared refusal catalogue answers is the * runtime's choice (`resolveHookRefusal`, held by its own tests). This file @@ -170,15 +177,40 @@ const PARENT = { ], }; +/** + * A plugin's node type: it fails with whatever pair it is configured to return + * — the shape a node executor hands the engine, which relays it unchecked. + */ +const PLUGIN_STEP = 'plugin_step'; +const pluginStep = (id: string) => ({ id, type: PLUGIN_STEP, label: id }); + +/** As {@link DIRECT}, with the plugin step on the reject (recall) branch. */ +const DIRECT_PLUGIN = { + ...DIRECT, + name: 'plan_direct_plugin', + nodes: DIRECT.nodes.map(n => (n.id === 'release_plan' ? pluginStep('release_plan') : n)), +}; + +/** As {@link PARENT}, with the plugin step after the subflow. */ +const PARENT_PLUGIN = { + ...PARENT, + name: 'plan_parent_plugin', + nodes: PARENT.nodes.map(n => (n.id === 'adopt_plan' ? pluginStep('adopt_plan') : n)), +}; + /** One live process: real engine, real builtin + approval nodes, real approvals service. */ -function boot(refusal: () => unknown) { +function boot(refusal: () => unknown, pluginCarried: Record = {}) { const data = makeFakeEngine(refusal); 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()); installBuiltinNodes(automation, { logger: noopLogger, getService: (n: string) => (n === 'data' ? data : undefined) } as any); registerApprovalNode(automation, service, noopLogger); - for (const flow of [DIRECT, CHILD, PARENT]) automation.registerFlow(flow.name, flow as never); + automation.registerNodeExecutor({ + type: PLUGIN_STEP, + async execute() { return { success: false, error: 'plugin step refused', ...pluginCarried }; }, + } as never); + for (const flow of [DIRECT, CHILD, PARENT, DIRECT_PLUGIN, PARENT_PLUGIN]) automation.registerFlow(flow.name, flow as never); service.attachAutomation(automation); return { data, service, automation }; } @@ -289,4 +321,54 @@ describe('#34638 — resumeFailure tells the hook refusal that stranded the run' neitherMember(answer); }); }); + describe('the pair is read the way the thrown RESUME_FAILED reads it — a plugin node\'s malformed member is dropped', () => { + const WELL_FORMED = { code: 'VALIDATION_FAILED', message: 'over capacity' }; + const MARKED = 'Capacity is already taken.'; + const CASES = [ + { + name: 'a blank userMessage is no marking: dropped, the well-formed innerRefusal rides', + carried: { innerRefusal: WELL_FORMED, userMessage: ' ' }, + told: { innerRefusal: WELL_FORMED }, + }, + { + name: 'an innerRefusal whose code is unregistered is dropped, the marked userMessage rides', + carried: { innerRefusal: { code: 'PLUGIN_OVER_CAPACITY', message: 'over capacity' }, userMessage: MARKED }, + told: { userMessage: MARKED }, + }, + { + name: 'an innerRefusal whose message is no string, and a non-string userMessage, are both dropped', + carried: { innerRefusal: { code: 'VALIDATION_FAILED', message: 42 }, userMessage: 7 }, + told: {}, + }, + { + name: 'CONTROL: a well-formed pair rides whole', + carried: { innerRefusal: WELL_FORMED, userMessage: MARKED }, + told: { innerRefusal: WELL_FORMED, userMessage: MARKED }, + }, + ]; + + describe.each(CASES)('$name', ({ carried, told }) => { + it('on the recall\'s own strand', async () => { + const env = boot(fault, carried); + const { req } = await park(env, 'plan_direct_plugin'); + const answer = await env.service.recall(req.id, { actorId: 'rep' }, SYSTEM_CTX); + expect(answer.resumed, "this door's own resume stranded").toBe(false); + expect(answer.resumeError, 'the strand is the plugin step').toContain('plugin step refused'); + expect(answer.resumeFailure).toEqual({ + code: 'RESUME_FAILED', runId: req.flow_run_id, status: 'stranded', repairable: true, ...told, + }); + }); + + it('on a subflow parent\'s strand, through the recall door', async () => { + const env = boot(fault, carried); + const { req, startedRunId: parentRunId } = await park(env, 'plan_parent_plugin'); + const answer = await env.service.recall(req.id, { actorId: 'rep' }, SYSTEM_CTX); + expect(answer.resumed, 'the child really did resume').toBe(true); + expect(answer.resumeError, 'the strand is the plugin step').toContain('plugin step refused'); + expect(answer.resumeFailure).toEqual({ + code: 'RESUME_FAILED', runId: parentRunId, status: 'stranded', repairable: true, ...told, + }); + }); + }); + }); });