Skip to content

Commit c77f8ca

Browse files
feat(runtime): dispatchActionResume resumes a handed-off resume_run as the person who approved it (#34492)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9T7a9Cf6D9HQLyMfF1wqqNX)_ Fixes #34386 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 改了什么:`@objectstack/runtime` 新导出 `dispatchActionResume`,宿主(cloud)在用户批准一条被交给人确认的 `resume_run` 后,用它以批准人的身份续跑那条暂停的流程。 - 为什么改:确认契约承诺"批准即续跑那条暂停的运行",但框架没有这个入口,cloud PR #4735 只能一直拒绝;cloud 自己重写一遍续跑门禁就成了第二份平台规则。 - 风险与回滚:只新增导出,MCP `resume_run` 和 `dispatchAction` 行为不变;回滚即撤掉这个 PR。 - 先看:`packages/runtime/src/domains/mcp.ts`(`resumeActionRunRequest` 与第 3 步确认门禁的宿主分支)、`packages/runtime/src/action-dispatch.ts`(导出入口)、`packages/runtime/src/action-confirmation-handoff-33690.test.ts`(新 describe)。 - 两分钟验证:`pnpm --filter @objectstack/runtime exec vitest run src/action-confirmation-handoff-33690.test.ts`,预期 7 条 `[#34386]` 用例全绿。 - 需要你做的:无,席位落地(新公开导出,先过契约复审)。 ## What changes The confirmation contract (`AI_ACTION_CONFIRMATION_CAPABILITY`, rule 4) says that approving a handed-off `resume_run` resumes THAT parked run, with the values the call carried, as the approver, who must be the run's owner, every gate re-checked. The framework exported no seam for it: `dispatchAction` only starts an action, and the MCP door's `resumeActionRun` always hands a gated action off again. - **`dispatchActionResume(kernel, { executionContext, environmentId?, runId, values?, confirm? })`** (new export of `@objectstack/runtime`, with its request type `ActionResumeRequest`). It runs the MCP `resume_run` door's own steps 1 to 6 again as `executionContext`, through `HttpDispatcher.resumeHostActionRun` → `resumeActionRunRequest` (`domains/mcp.ts`) → `resumeActionRun`. The host keeps no copy of the gates. - Step 2: a run that is no longer paused, or that another person started, gets the door's one not-found answer (`404 RESOURCE_NOT_FOUND`). - Step 3: every `run_action` gate of the flow action that admits the run. Its confirmation gate reads `confirm` as a host action door reads it (`actionConfirmationRefusal`, the member gate `dispatchAction` asks): a declared-gated action resumes on the person's `confirm: true`, and is refused `428 ACTION_CONFIRMATION_REQUIRED` without it. Nothing is handed off or elicited again. An AI service account is refused whatever it carries (ADR-0151 D3 rule 3, `reason: 'service_account'`). - Steps 4 and 5: the subject record is read again as the person; the run must be paused on a screen (`409`). Step 6 resumes it. - Step 2 refuses only a run that is no longer paused. A wizard the first approval moved on to its next screen is still paused under the same run id, so a second call with the same hand-off passes steps 2 to 5 and resumes that next screen with the values given. Deciding a pending item once, and voiding an item whose run has moved on, are the host's approve door's job; binding an approval to one screen is not in this PR (contract review S1, record 6932783796). - Placement is the host action door's (`placeHostActionRequest`). The answer is the REST envelope, as `dispatchAction`'s: `200` with `resume_run`'s `{ ok, action, objectName, recordId?, result }` as `data`, or the refusal's ADR-0112 envelope with its `details`. One invocation row is written for a call that cleared steps 1 to 3, with no surface (as the host action door's row). - **`resumeActionRun` (internal)** gains a `wiring.hostDoor` member: present only on the host path, it switches step 3's confirmation gate to the member gate and drops the MCP surface from the invocation row. The MCP tool path is unchanged. - **`actionDeclarationReads`** (internal): the per-request metadata, merged-listing, served-objects and served-actions reads moved out of `buildMcpBridge` verbatim, so the bridge and the host resume door read the same declarations. No line of the moved code changed. - **Door refusals keep their envelope at the host door**: `resumeDoorError` now records the envelope `deps.error` built for each refusal, and the host door answers that envelope. The dispatcher's generic thrown-value reader keeps `code` and `status` but drops `details` (a confirmation refusal's `reason`). Anything else thrown is answered by that reader as before. - **Contract docblock** (`IActionConfirmationService`, `@objectstack/spec/contracts`): names the two host doors of the approval leg, `dispatchAction` for a handed-off `run_action` and `dispatchActionResume` for a handed-off `resume_run`, and says the seam refuses only a run that is no longer paused, so deciding a pending item once is the host's. - **Docs**: `content/docs/ui/actions.mdx` gains "Resume a handed-off run as the person who approved it" under the host-code section. - Changeset: `.changeset/34386-dispatch-action-resume.md`, `@objectstack/runtime` patch. - **Naming**: `dispatchActionResume` and its request type `ActionResumeRequest` follow the precedent in the same file, `dispatchAction` and `ActionDispatchRequest` (`packages/runtime/src/action-dispatch.ts`), the host door that starts an action. - **System-context register** (`content/docs/permissions/system-context.mdx`): the host resume door opens with the anonymous-deny read `dispatchActionRequest` opens with, so row 52 names `resumeActionRunRequest` beside it and the generated site register is rewritten (`node scripts/check-system-context-census.mjs --write`). `check:system-context-census` refused the read without a row. ## Tests New top-level `describe` in the shared harness file `packages/runtime/src/action-confirmation-handoff-33690.test.ts` (seven cases). Each starts from a real hand-off made through the MCP bridge's `resumeRun`, and calls `dispatchActionResume` with the run and values the hand-off carried: - the approving person resumes THAT run with the hand-off's values (`automation.resume` called once with `[runId, { variables }]`), no new run, no second hand-off, and one invocation row with no `surface`; - another person is refused `404 RESOURCE_NOT_FOUND`, the run stays paused; - a run that is no longer parked is refused: a run the first approval completed is not resumed again; - without `confirm` (absent, or `false`) the gated resume is refused `428 ACTION_CONFIRMATION_REQUIRED` with the member gate's details (no `reason`), never handed off again; - an AI service account is refused `428`, `reason: service_account`, with `confirm: true`; - the subject record is re-read as the approver: one they can no longer read is refused `404 RECORD_NOT_FOUND`; - an anonymous caller is refused `401 UNAUTHENTICATED` (`ANONYMOUS_DENY_CODE`) before the run is read. No existing test was changed. ## Acceptance notes - The route path the placement step hands the resolver is `/mcp/resume_run/RUN_ID`: informational, as the host action door's is, and no environment hint is derived from it. It names the door whose steps run. - What stays the host's before it calls, as for `dispatchAction`: resolving the approver's envelope against the placed kernel, the ADR-0069 authentication-policy gate, environment membership, and the approve door's rule that only a person's signed-in session decides. - The cloud follow-up (holding resume hand-offs and dispatching through this seam) is the cloud seat's, after a pin move. - Review S1, the structural half (binding an approval to the screen it was given for, so a second resume of the same hand-off cannot reach a later screen): filed #34515. This PR only states the seam's check truthfully. - Review N2 (the enforced-set docblock of `actionConfirmationRefusal` in `action-execution.ts` does not name the host resume door): filed #34515. ## Verification <details><summary>Local runs (runtime closure built first)</summary> - `pnpm --filter @objectstack/runtime typecheck`: exit 0 (`tsc --noEmit`, then `check:test-typecheck` OK, ledger held). - `pnpm --filter @objectstack/runtime test`: Test Files 609 passed (609), Tests 11278 passed, 19 skipped. - Targeted: `vitest run src/action-confirmation-handoff-33690.test.ts src/mcp-resume-run.test.ts src/action-dispatch.test.ts`: 131 passed. - Ablation (`scripts/ablation-replace.mjs`, runtime tests import `src`, no dist leg): step 3's host branch disabled (`if (hostConfirmation !== undefined && false)`), the host call is handed off again. 3 of the 7 new cases go red (resumes THAT run; resumes once, never twice; the member gate's 428). The service-account case stays green, as expected: the MCP path refuses an account too. Restored: blob equals HEAD, `git diff HEAD` empty. </details> <details><summary>Derived gate round on 9c404cd</summary> - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`: 115 families; each run with stdin closed, exit captured before any pipe. 115 of 115 `exit 0`. - `dispatch-gates.mjs --ran`: 115 derived, 115 run, 0 NOT-MEASURED, 0 UNRUN. - Local-only families (spec source touched): `check-dev-prereqs` exit 0, `check:skill-frame-freshness` exit 0. - The first CI head (94c8ee5) went red on `check:system-context-census` (inside "Docs anchors resolve to real headings"): the new door's anonymous-deny read had no row. Fixed in 9c404cd. </details> <details><summary>Rework round (L1 REWORK 6932718088, contract review S1 6932783796)</summary> - 1313af8 (tests only): the anonymous case asserts the envelope code `UNAUTHENTICATED`; the approver case asserts the one invocation row and that its context carries no `surface`. Ablation: the host door's row given the MCP surface (`context: withActionSurface(ec, 'mcp'),`), the approver case goes red (1 of 39), restored blob equals HEAD. Runtime typecheck exit 0; derived round 115 of 115 `exit 0`. - f364cc0 (prose only, S1): the contract docblock, the `dispatchActionResume` and `resumeActionRunRequest` docblocks, the docs section and the changeset no longer say the run resumes once; they say the seam refuses only a run that is no longer paused and that deciding a pending item once is the host's. One test renamed to match. - Final head f364cc0: spec and runtime rebuilt; `action-confirmation-handoff-33690.test.ts` 39 of 39 passed; derived round 115 of 115 `exit 0`, `--ran` 115 derived, 115 run, 0 NOT-MEASURED, 0 UNRUN. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmQC5YhoBASNPYbDXuQ)_ <!-- signed: repo:objectstack#2 · os-steve · session_01ADHkmRXuRn93HphKp7kXEz --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 1ccb445 commit c77f8ca

9 files changed

Lines changed: 493 additions & 46 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/runtime': patch
3+
---
4+
5+
feat(runtime): `dispatchActionResume` resumes a handed-off `resume_run` as the person who approved it
6+
7+
Clause-②: yes (widening)
8+
Metadata-protocol: none
9+
10+
The confirmation contract says that approving a handed-off `resume_run` resumes that parked run, with the values the call carried, as the approver. Until now the framework exported no way to do that: `dispatchAction` only starts an action, and the MCP `resume_run` door hands a gated action off again. A host that implements the pending-confirmation service (`ai.actionConfirmation`) could hold a handed-off `resume_run` but had to keep refusing it.
11+
12+
`dispatchActionResume(kernel, { executionContext, runId, values, confirm })` is the approval leg. It asks every `resume_run` gate again as the approving person: the run must still be paused and started by that person, the flow action that admits it must pass every `run_action` gate, the subject record is read again as the person, and the run must be paused on a screen. Then it resumes that run. Only a run that is no longer paused is refused: a wizard the approval moved on to its next screen is still paused under the same run id, so the host's approve door decides each pending item once and voids an item whose run has moved on. The confirmation gate reads `confirm` as `dispatchAction`'s does, so a declared-gated action resumes on the person's `confirm: true` and nothing is handed off again. An AI service account is refused whatever it carries. The answer is the REST envelope, as `dispatchAction`'s is.
13+
14+
Nothing changes for an existing caller.

‎content/docs/permissions/system-context.mdx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ One of the largest consumers of the flag;
205205
| 50 | `manage_metadata` bypassed on metadata writes | runtime, rest | Get: schema writes without the capability (the permission-set clone door's save included) — and, because REST's save door and the stored-version read doors ask one save verdict, an app's full stored version on `/layers`, `?layers=true` and `/diff`, whatever its entry gates withhold | `handleMetadataRequest`, `registerMetaCollectionRoutes`, `registerMetaItemWriteRoutes`, `registerMetaItemHistoryRoutes`, `metaSaveVerdict`, `handlePermissionSetCloneWrite` |
206206
| 50b | `setup.write` bypassed on the record-currency code backfill door | rest | Get: `POST /meta/_migrate-record-currency-codes` without the capability. The door still fills only the caller's current organization's rows: a system context with no organization is refused like any other caller | `registerMetaRecordCurrencyBackfillRoute` |
207207
| 51 | The shared metadata-write verdict itself returns `allowed` | metadata-core | Get: the one function all of row 50's doors consult answers yes before any capability is examined | `metaWriteCapabilityVerdict` |
208-
| 52 | Anonymous-deny seam satisfied on the domain dispatchers and the package/federation routes | runtime, rest | Get: passes with no `userId` | `handleActionsRequest`, `dispatchActionRequest`, `handleAIRequest`, `handleAutomationRequest`, `handleMetadataRequest`, `handleSecurityRequest`, `handlePackagesRequest`, `handleAnalyticsRequest`, `handleI18nRequest`, `registerExternalDatasourceRoutes`, `refusePackageRequest` |
208+
| 52 | Anonymous-deny seam satisfied on the domain dispatchers and the package/federation routes | runtime, rest | Get: passes with no `userId` | `handleActionsRequest`, `dispatchActionRequest`, `resumeActionRunRequest`, `handleAIRequest`, `handleAutomationRequest`, `handleMetadataRequest`, `handleSecurityRequest`, `handlePackagesRequest`, `handleAnalyticsRequest`, `handleI18nRequest`, `registerExternalDatasourceRoutes`, `refusePackageRequest` |
209209
| 53 | MCP principal check satisfied | runtime | Get: MCP surface reachable with no user | `handleMcpRequest` |
210210
| 54 | Package REST route capability gate bypassed | rest | Get: a marketplace publish over REST (`POST /packages/publish`, the one route the REST registrar mounts since #14503) without `manage_metadata`; the package read cohort (`studio.access` / `setup.access`) is enforced by the dispatcher `/packages` domain's own read gate, where the reads are served | `refusePackageRequest` |
211211
| 55 | Package domain capability gates bypassed | runtime | Get: package management and package-inventory reads without the capability | `requireManageMetadata`, `requireReadCapability` |
@@ -676,6 +676,7 @@ and CI refuses one that differs from what the tree produces.
676676
| `packages/runtime/src/domains/mcp.ts#federationService` | 1 | 55b |
677677
| `packages/runtime/src/domains/mcp.ts#handleMcpRequest` | 1 | 53 |
678678
| `packages/runtime/src/domains/mcp.ts#membershipReachRefusal` | 1 | 62b |
679+
| `packages/runtime/src/domains/mcp.ts#resumeActionRunRequest` | 1 | 52 |
679680
| `packages/runtime/src/domains/meta.ts#handleMetadataRequest` | 5 | 50, 52 |
680681
| `packages/runtime/src/domains/packages.ts#handlePackagesRequest` | 1 | 52 |
681682
| `packages/runtime/src/domains/packages.ts#refuseWalledCatalogPackageWrite` | 1 | 55b |

‎content/docs/ui/actions.mdx‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -764,6 +764,43 @@ refusals carry the REST door's status and code: a name nothing declares is
764764
**503**, a caller without the action's capability is **403**, and an object
765765
whose package is disabled is **404** `OBJECT_PACKAGE_DISABLED`.
766766

767+
### Resume a handed-off run as the person who approved it
768+
769+
When the MCP `resume_run` tool hands a resume to the person (an action that
770+
declares `ai.requiresConfirmation: true`, on a host with a pending-confirmation
771+
service), the hand-off carries the paused run: `run: { runId, values }`.
772+
Your approve door resumes that run with `dispatchActionResume`, as the person
773+
who approved it, instead of re-implementing the `resume_run` checks:
774+
775+
```typescript
776+
import { dispatchActionResume } from '@objectstack/runtime';
777+
778+
const answer = await dispatchActionResume(kernel, {
779+
executionContext: approver, // the person who approved, signed in to the app
780+
environmentId, // optional, placed as for dispatchAction
781+
runId: handOff.run.runId,
782+
values: handOff.run.values,
783+
confirm: true, // the person's confirmation
784+
});
785+
if (answer.status !== 200) throw answer.body.error;
786+
```
787+
788+
It asks every `resume_run` check again, as that person: the run must still be
789+
paused and must have been started by them (otherwise **404**
790+
`RESOURCE_NOT_FOUND`, the same answer for an unknown run), the flow action
791+
that admits the run must pass every `run_action` check, the record is read
792+
again as them, and the run must be paused on a screen (otherwise **409**). The
793+
run then resumes; it never starts a new run and is never handed off again.
794+
Only a run that is no longer paused is refused: a wizard your approval moved
795+
on to its next screen is still paused under the same run id, so calling again
796+
with the same hand-off resumes that next screen with the same values. Decide
797+
each pending item once in your approve door, and void an item whose run has
798+
moved on. Without `confirm: true`, an action that declares
799+
`ai.requiresConfirmation: true` is refused **428** `ACTION_CONFIRMATION_REQUIRED`,
800+
and an AI service account is refused whatever it sends. The answer is the REST
801+
envelope, with `resume_run`'s `{ ok, action, objectName, recordId, result }` as
802+
`data`. Placement, and the three steps your door keeps, are `dispatchAction`'s.
803+
767804
## Troubleshooting
768805

769806
| Symptom | Cause → fix |

‎packages/runtime/src/action-confirmation-handoff-33690.test.ts‎

Lines changed: 138 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,11 @@ import '@objectstack/metadata';
3636
import { describe, it, expect, vi } from 'vitest';
3737

3838
import { ACTION_CONFIRMATION_SERVICE, AI_ACTION_CONFIRMATION_MEMBER } from '@objectstack/spec/contracts';
39+
import { ANONYMOUS_DENY_CODE } from '@objectstack/core';
3940

4041
import { HttpDispatcher } from './http-dispatcher.js';
4142
import { actionConfirmationElicitSubject, actionConfirmationRefusal } from './action-execution.js';
42-
import { dispatchAction } from './action-dispatch.js';
43+
import { dispatchAction, dispatchActionResume } from './action-dispatch.js';
4344

4445
const OBJECT = 'crm_lead';
4546

@@ -77,7 +78,7 @@ function makeConfirmationService() {
7778
return { submit: vi.fn(async (_handOff: unknown, _ec: unknown) => ({ pendingId: `pa_${++n}` })) };
7879
}
7980

80-
function makeHarness(opts: { service?: unknown } = {}) {
81+
function makeHarness(opts: { service?: unknown; audit?: unknown } = {}) {
8182
const leads = [
8283
{ id: 'lead_1', owner: 'u1', name: 'Ada', status: 'open' },
8384
{ id: 'lead_2', owner: 'u2', name: 'Grace', status: 'open' },
@@ -135,6 +136,8 @@ function makeHarness(opts: { service?: unknown } = {}) {
135136
const services: Record<string, unknown> = {
136137
objectql: ql, data: ql, metadata, automation,
137138
...(opts.service ? { [ACTION_CONFIRMATION_SERVICE]: opts.service } : {}),
139+
// [#34386] The audit slot's invocation writer, when a pin reads the row.
140+
...(opts.audit ? { audit: opts.audit } : {}),
138141
};
139142
const resolve = (name: string) => services[name] ?? null;
140143
const kernel: any = { getService: resolve, getServiceAsync: async (name: string) => resolve(name), context: { getService: resolve } };
@@ -149,7 +152,10 @@ function makeHarness(opts: { service?: unknown } = {}) {
149152
};
150153
const viaHost = (ec: unknown, action: string, extra: Record<string, unknown> = {}) =>
151154
dispatchAction(kernel, { executionContext: ec as any, environmentId: 'platform', objectName: OBJECT, actionName: action, ...extra } as any);
152-
return { ql, automation, runs, leads, bridgeAs, viaRest, viaHost };
155+
// [#34386] The host's resume door: the approval leg of a handed-off resume_run.
156+
const resumeAsHost = (ec: unknown, extra: Record<string, unknown>) =>
157+
dispatchActionResume(kernel, { executionContext: ec as any, environmentId: 'platform', ...extra } as any);
158+
return { ql, automation, runs, leads, bridgeAs, viaRest, viaHost, resumeAsHost };
153159
}
154160

155161
async function refusalOf(p: Promise<unknown>): Promise<{ code: unknown; status: unknown; message: string; details?: any }> {
@@ -581,3 +587,132 @@ describe('[#33712] the question names the record by the title its read served',
581587
expect(subject.recordId).toBe('lead_1');
582588
});
583589
});
590+
591+
/**
592+
* [#34386] The approval leg of a handed-off `resume_run`: the host's approve
593+
* door calls `dispatchActionResume` with the run and values the hand-off
594+
* carried, as the approving person, and their confirmation. It asks
595+
* `resume_run`'s gates again as that person and resumes THAT parked run once;
596+
* it never starts a new run and never hands off again.
597+
*/
598+
describe('[#34386] dispatchActionResume: approving a handed-off resume_run resumes that run as the approver', () => {
599+
/** A run owned by u1, paused on its screen, handed off by its resume_run call. */
600+
async function handedOffResume(h: ReturnType<typeof makeHarness>, service: ReturnType<typeof makeConfirmationService>) {
601+
const started: any = await h.automation.execute(GATED_FLOW.target, { userId: 'u1', object: OBJECT, record: { id: 'lead_1' } });
602+
h.automation.execute.mockClear();
603+
const pending = await h.bridgeAs(PERSON).resumeRun(started.runId, { values: { reason: 'approved later' } });
604+
expect(pending).toMatchObject({ status: 'pending_confirmation' });
605+
const handOff = (service.submit.mock.calls[0] as any[])[0];
606+
service.submit.mockClear();
607+
return handOff.run as { runId: string; values: Record<string, unknown> };
608+
}
609+
610+
it('the approving person resumes THAT parked run once, with the values the hand-off carried', async () => {
611+
const service = makeConfirmationService();
612+
const audit = { recordActionInvocation: vi.fn(async (_event: unknown) => undefined) };
613+
const h = makeHarness({ service, audit });
614+
const run = await handedOffResume(h, service);
615+
616+
const answer: any = await h.resumeAsHost(PERSON, { runId: run.runId, values: run.values, confirm: true });
617+
618+
expect(answer.status).toBe(200);
619+
expect(answer.body).toMatchObject({
620+
success: true,
621+
data: { ok: true, action: GATED_FLOW.name, objectName: OBJECT, recordId: 'lead_1', result: { status: 'completed' } },
622+
});
623+
expect(h.automation.resume).toHaveBeenCalledTimes(1);
624+
expect(h.automation.resume.mock.calls[0]).toEqual([run.runId, { variables: { reason: 'approved later' } }]);
625+
expect(h.runs.get(run.runId)?.status).toBe('completed');
626+
// Never a new run, and never handed off again.
627+
expect(h.automation.execute).not.toHaveBeenCalled();
628+
expect(service.submit).not.toHaveBeenCalled();
629+
// One invocation row, as the host action door writes it: no surface,
630+
// because the call came through neither REST nor MCP.
631+
expect(audit.recordActionInvocation).toHaveBeenCalledTimes(1);
632+
const event = audit.recordActionInvocation.mock.calls[0][0] as any;
633+
expect(event).toMatchObject({
634+
actionName: GATED_FLOW.name, objectName: OBJECT, recordId: 'lead_1', branch: 'flow', runId: run.runId, outcome: 'succeeded',
635+
});
636+
expect(event.context.userId).toBe('u1');
637+
expect(event.context).not.toHaveProperty('surface');
638+
});
639+
640+
it('another person is refused with the one not-found answer, and the run stays parked', async () => {
641+
const service = makeConfirmationService();
642+
const h = makeHarness({ service });
643+
const run = await handedOffResume(h, service);
644+
645+
const refused: any = await h.resumeAsHost({ userId: 'u2', systemPermissions: [] }, { runId: run.runId, values: run.values, confirm: true });
646+
647+
expect({ status: refused.status, code: refused.body?.error?.code }).toEqual({ status: 404, code: 'RESOURCE_NOT_FOUND' });
648+
expect(refused.body.error.message).toContain('Only the user whose call started a run can resume it');
649+
expect(h.automation.resume).not.toHaveBeenCalled();
650+
expect(h.runs.get(run.runId)?.status).toBe('paused');
651+
});
652+
653+
it('a run that is no longer parked is refused: a run the first approval completed is not resumed again', async () => {
654+
const service = makeConfirmationService();
655+
const h = makeHarness({ service });
656+
const run = await handedOffResume(h, service);
657+
658+
const first: any = await h.resumeAsHost(PERSON, { runId: run.runId, values: run.values, confirm: true });
659+
const second: any = await h.resumeAsHost(PERSON, { runId: run.runId, values: run.values, confirm: true });
660+
661+
expect(first.status).toBe(200);
662+
expect({ status: second.status, code: second.body?.error?.code }).toEqual({ status: 404, code: 'RESOURCE_NOT_FOUND' });
663+
expect(h.automation.resume).toHaveBeenCalledTimes(1);
664+
});
665+
666+
it('without the person\'s confirmation a gated resume is refused 428 (the member gate), never handed off again', async () => {
667+
const service = makeConfirmationService();
668+
const h = makeHarness({ service });
669+
const run = await handedOffResume(h, service);
670+
671+
for (const extra of [{}, { [AI_ACTION_CONFIRMATION_MEMBER]: false }]) {
672+
const refused: any = await h.resumeAsHost(PERSON, { runId: run.runId, values: run.values, ...extra });
673+
expect({ status: refused.status, code: refused.body?.error?.code }, JSON.stringify(extra)).toEqual({
674+
status: 428, code: 'ACTION_CONFIRMATION_REQUIRED',
675+
});
676+
// The member gate's refusal: no contract reason.
677+
expect(refused.body.error.details).toEqual({
678+
actionName: GATED_FLOW.name, objectName: OBJECT, confirmationMember: AI_ACTION_CONFIRMATION_MEMBER,
679+
});
680+
}
681+
expect(service.submit).not.toHaveBeenCalled();
682+
expect(h.automation.resume).not.toHaveBeenCalled();
683+
expect(h.runs.get(run.runId)?.status).toBe('paused');
684+
});
685+
686+
it('[ADR-0151 D3 rule 3] an AI service account is refused whatever it carries, reason service_account', async () => {
687+
const service = makeConfirmationService();
688+
const h = makeHarness({ service });
689+
const started: any = await h.automation.execute(GATED_FLOW.target, { userId: 'bot_1', object: OBJECT, record: { id: 'lead_1' } });
690+
691+
const refused: any = await h.resumeAsHost(ACCOUNT, { runId: started.runId, values: { reason: 'x' }, confirm: true });
692+
693+
expect({ status: refused.status, code: refused.body?.error?.code }).toEqual({ status: 428, code: 'ACTION_CONFIRMATION_REQUIRED' });
694+
expect(refused.body.error.details).toMatchObject({ reason: 'service_account' });
695+
expect(h.automation.resume).not.toHaveBeenCalled();
696+
expect(service.submit).not.toHaveBeenCalled();
697+
});
698+
699+
it('the subject record is read again as the approver: one they can no longer read is refused 404, nothing resumes', async () => {
700+
const service = makeConfirmationService();
701+
const h = makeHarness({ service });
702+
const run = await handedOffResume(h, service);
703+
h.leads[0] = { ...h.leads[0], owner: 'u2' };
704+
705+
const refused: any = await h.resumeAsHost(PERSON, { runId: run.runId, values: run.values, confirm: true });
706+
707+
expect({ status: refused.status, code: refused.body?.error?.code }).toEqual({ status: 404, code: 'RECORD_NOT_FOUND' });
708+
expect(h.automation.resume).not.toHaveBeenCalled();
709+
expect(h.runs.get(run.runId)?.status).toBe('paused');
710+
});
711+
712+
it('an anonymous caller is refused 401 before anything is read', async () => {
713+
const h = makeHarness({ service: makeConfirmationService() });
714+
const refused: any = await h.resumeAsHost({}, { runId: 'run_1', confirm: true });
715+
expect({ status: refused.status, code: refused.body?.error?.code }).toEqual({ status: 401, code: ANONYMOUS_DENY_CODE });
716+
expect(h.automation.getRun).not.toHaveBeenCalled();
717+
});
718+
});

0 commit comments

Comments
 (0)