Files
PaperClipAI/server/src/services/task-interruption-presentation.test.ts
T
DottaandClaude Opus 5.5 3ad8f00192 feat(antigravity): trusted /swarm from the task composer, behind an experimental flag (#22733)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Google Antigravity agents can run Google's native `/swarm` (a
coordinator, helpers and a verifier) only on the Antigravity CLI
> - #22731 adds a verified CLI route to the Runner, but nothing selects
it yet
> - A swarm must start only when the signed-in user asks for it, only
when an admin turned the experimental feature on, and never silently run
as an ordinary request when it cannot run
> - This pull request adds the trusted `/swarm` request in the task
composer, the server checks and run selection behind an experimental
flag, removes Paperclip delegation tools from a swarm turn, and adds the
attended catalog cells, docs and ledger
> - The benefit is that a user can start a native swarm from a task, and
gets one plain message when it is not available

## Linked Issues or Issue Description

Refs #22731, #22727, #22728, #22701

**Subsystem affected**
Task composer (UI), issue comments API, run selection (server),
Paperclip Runner tool bridge, runner-e2e catalog, docs.

**Problem or motivation**
A user who writes `/swarm <request>` to a Google Antigravity agent
should get a real native swarm in the task folder. Today `/swarm` is
neutralised text, and the task runs as an ordinary request.

**Proposed solution**
Read a leading `/swarm` with the shared rule from #22727 in the
composer, send it as a structured request, check it on the server, and
select the CLI route from #22731 for that run only.

## What Changed

- **Trusted start (UI).** `parseSwarmCommand` in `composer-commands.ts`
uses `parseLeadingUserCommand` (the one rule from #22727). A leading
`/swarm` in the task composer sends the request text with
`nativeCommand: "swarm"`; a bare `/swarm` asks for a request; `/swarm`
with an assignee change is refused; `/swarm` anywhere else stays text. A
resent draft keeps the structured request.
- **Contract.** `addIssueCommentSchema` gains `nativeCommand: "swarm"`.
`instance.experimental.enableAntigravitySwarm` (feature catalog,
settings page, server defaults), off by default. No Cloud policy in
Core.
- **Server (`services/antigravity-swarm.ts`, comments route, runtime
selection).**
- The comments route accepts `nativeCommand` only from a signed-in board
user. When a swarm cannot run it answers 422 with one plain message and
posts nothing: flag off, not a Google Antigravity assignee, a chat, Plan
mode.
- An accepted request is recorded in the activity log
(`issue.antigravity_swarm_requested`, server-written) and the assignee's
wake carries the comment id. Comment text is never read as a command.
- Run selection makes the run a swarm only when that activity record
exists. It refuses a remote or cloud environment and Plan mode with a
plain run failure, so a swarm is never run as an ordinary request. It
logs `issue.antigravity_swarm_started` in plain language: helper actions
are auto-approved, Paperclip does not sandbox the helpers and cannot see
their shell commands, and usage is one total.
- The native execution input sets the Antigravity provider mode `swarm`
for that run only, and carries the verified request in its own field,
`provider.swarmRequest` (the Runner contract accepts it only with that
mode and requires it there, 1 to 16,000 characters). The Runner copies
it into the model envelope as `swarmRequest`; the swarm route sends
exactly `/swarm <swarmRequest>` and never reads `task.prompt`, which
holds rendered wake comments, task context and text the Runner adds
(handoff, attachments, queued messages).
- The swarm turn contract (mode `swarm`, envelope
`paperclip.native-model-envelope.v3`, `swarmRequest` of 1 to 16,000
characters) is declared as `antigravitySwarmTurn` in
`protocol/provider-schemas/acpx-sidecar.schema.json` and generated into
TypeScript, so the pack `contractDigest` covers it (it changes; older
image packs are rebuilt rather than reused). Provider profile
`commandDigest`s and versions are unchanged, so no saved session is
reset.
- What the swarm sees of the task: only the request. The title, the
description (which other people or agents may have written) and other
comments are not part of the prompt; the coordinator can read them
through Paperclip's task tools as data if it needs context.
- An empty `/swarm` or one over 16,000 characters is refused in the
composer, by the comments route (422, nothing posted) and at run
selection (plain run failure), so it never runs as ordinary work.
- A swarm run never takes queued messages, and Interrupt treats it as
already started: it stops the swarm and delivers the queued message as
the next ordinary request, before or after the provider accepted the
turn.
- Retry after Stop, and past the three automatic attempts, counts only
when the signed-in user asked for it (their own Retry request on the
task after the last attempt). Wake reasons and copied run context are
not proof: a recovery that copies the request marker, an automatic retry
on the user's behalf, or an agent wake that names `task_retry` stay
bounded.
- **Runner.** For a swarm turn the Paperclip bridge drops delegation
tools (`paperclip_create_task`, `paperclip_create_issue`, hire/assign
tools); the instructions also tell the coordinator not to delegate.
- **runner-e2e.** `antigravity-swarm` suite, 5 local cells
(`two-helpers-and-verifier`, `stop-mid-swarm`, `process-loss-retry`,
`follow-up-after-swarm`, `flag-off-refusal`), explicit-only, never in
`--all` or CI matrix jobs. There is no automated executor yet: the
launcher refuses the cells and points at the live recipe. Catalog counts
updated (1392 cells).
- **Docs.** `tests/runner-e2e/SUITES.md`, `doc/evals.md`, and the
`/swarm` section, ledger row and live recipe in
`doc/plans/2026-11-22-antigravity-qualification.md`.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/services/antigravity-swarm.test.ts`: 2 passed (red first: module
missing; Plan mode red then green).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-comment-reopen-routes.test.ts -t swarm`: 3 passed; 2
red against the route without this change.
- `pnpm --filter @paperclipai/ui exec vitest run
src/components/task-chat/TaskChatComposer.test.tsx`: 164 passed,
including 4 new `/swarm` tests (red first).
- Runner: `vitest run src/drivers/acpx/antigravity-swarm-*.test.ts`: 69
passed (route tool filter red first).
- runner-e2e: `antigravity-swarm.test.ts` (red first) plus the catalog,
selector and Antigravity tests: 28 files passed.
- Typecheck: server, UI (except generated Storybook files absent from a
worktree) and runner: no errors.
- Live, real CLI 1.5.15 with the owner's sign-in, through the driver:
the receipt verified (pinned identity, task folder, `auto` read back,
`gemini-3.8-flash` + `low`). Google then refused the prompt with its 429
quota text; the driver reported it as a typed "out of quota" failure,
retired the CLI and nothing was written.
- **Not run live yet:** the full Paperclip proof (swarm to Done, Stop,
kill and Retry, follow-up, flag off). This PR is merged only after it
passes. Recipe:
`doc/plans/2026-11-22-antigravity-qualification.md#swarm-live-proof`.

## Risks

### Security notes: the trust boundary

Helpers are auto-approved and Paperclip does not sandbox the CLI on a
local computer, so the boundary is who asked and what text is sent.
Every input that can influence it:

**(a) Whether a run is a swarm**
- `nativeCommand: "swarm"` on the comment request: accepted only from a
signed-in board user; the request record
(`issue.antigravity_swarm_requested`, actor = that user, `commentId`)
commits in the same transaction as the comment. Paperclip-written.
- `antigravitySwarmCommentId` on the wake/run context: set only by the
comments route and by run selection. It is a pointer, never trusted
alone: selection re-verifies comment id + task + company + human author
(no agent author) + a matching record by the same user.
- The pending request for marker-less wakes: the task's latest human
comment, verified the same way.
- Retry inheritance: the run's `retryOfRunId` chain (server-written),
bounded to 8 hops on the same task.
- Manual vs automatic: a request's first run, or a user's own Retry
request (`task_retry` / `retry_failed_run`, requested by a user, not
`initiatedBy` automation) after the last attempt. Not the wake reason
string.
- Instance flag `enableAntigravitySwarm` (admin), the assignee's adapter
config (Google Antigravity), execution target (local only), work mode
(Standard only: Plan, Ask and any other mode are refused, at comment
time and at run time), chat vs task: all Paperclip-owned settings.
- Prior attempts on the same request (run status rows):
Paperclip-written.

**(b) What text and tools the swarm gets**
- The prompt: `/swarm ` + `provider.swarmRequest`, which is the recorded
comment body minus a leading `/swarm`, trimmed, byte for byte (tested
through the production input builder and envelope with a merged wake
that contains an agent comment). The verified request.
- The system prompt append: only Paperclip-authored text: Paperclip's
fixed execution prompt, the run's hand-in values (the server-written
completion revision and criterion IDs that
`paperclip_finish`/`paperclip_block` require; never a criterion's
requirement text), and the fixed swarm rules. **The swarm runs without
the agent's own instructions**: the instruction bundle and connection
instructions are left out, because an agent with an editable
instructions folder can rewrite its instructions in an earlier ordinary
run, the helpers act under auto mode, and Paperclip keeps no
user-approved copy of those instructions to trust instead.
- Tools: only Paperclip's own MCP bridge (any other assigned tool server
refuses the swarm), with delegation, hiring, routing and generic API
operations removed. Paperclip's permission handler approves a CLI
permission request only when its tool name is `mcp_paperclip_<tool>` and
`<tool>` is one the run's bridge admits; everything else is refused, and
the CLI then ends the turn. Tool descriptions are Paperclip-authored;
tool results (for example other comments) are data the coordinator
reads, not the request.
- Model and mode: the agent's configured model, Antigravity's `auto`
mode, both read back and pinned by the receipt.
- Not sent: task title, description, wake comments, continuation events,
attachments, queued messages, handoff text.

Known residual: a Retry or recovery run that has not yet been selected
(still preparing) does not carry the request marker, so an Interrupt in
that short window keeps the message for the turn boundary instead of
stopping the run; the message is delivered after the run ends.

- Off by default and local only. With the flag on, helpers act under
Antigravity's `auto` mode. **Paperclip does not sandbox them on a local
computer**, and their tool calls never reach Paperclip, so helper shell
commands can write outside the task folder where the CLI's own sandbox
allows (workspace plus temp directories). The settings text, the
activity log and the plan doc say so.
- On macOS the CLI uses its own Google sign-in from the login keychain,
not Paperclip's stored connection.
- Google's consumer terms have a clause about third-party tools that
access the service. A legal read is pending; this PR does not claim
compliance.
- `/swarm` as the first word of a composer message is now a swarm
request for every agent; for agents other than Google Antigravity the
server refuses it with a plain message. To send the literal text, put
other text first.
- The new runner-e2e cells are attended only and have no automated
executor.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

Review round 2 (head a2decc65f3): Greptile's "swarms must guess
completion fields" fixed as above (runner `nativeSystemInstructions`,
red first 1 in the fake-CLI swarm runtime test; request text to the CLI
still exactly `/swarm <request>`); CI typecheck failure was a TS18046 in
`acpx-runtime-sidecar.test.ts` (test-program typecheck), fixed; master
merged, its pruned `heartbeat-provider-limit-wait` and
`provider-failure-classification` suites dropped, with this branch's
swarm cases kept in `antigravity-swarm-provider-limit.test.ts` and
`antigravity-swarm.test.ts`. No protocol schema change. Round 3 (head
1444503e84, from live run6): CLI 1.5.15 names a client MCP call
`mcp_<server>_<tool>` with no `_meta` (payload recorded from the pinned
CLI, now the fake CLI's fixture), so Paperclip's permission handler
refused the coordinator's own `get_task_context` and the CLI ended the
turn on the denial. The handler now approves only tools the run's
Paperclip bridge admits, by that name, and fails closed otherwise; a
refused Paperclip tool is reported as such, not as a helper blocked
outside the task folder. A swarm turn without a hand-in fails plainly
(`ANTIGRAVITY_SWARM_NO_RESULT`: "The swarm ended without doing any
work"), every swarm-route failure code settles as
`antigravity_swarm_unavailable` (no automatic retry; Retry offered), and
selection never starts another swarm automatically after one; a lost CLI
process still recovers on its own. The run history always records
whether the CLI's sign-in matches the connection account (with the
reason when unknown). Usage-limit evidence is scoped by the executed
provider mode, so limits from pre-scope swarms hold only swarms. Red
first: runtime 5, server 3.

Then (head 74454a17f3): an empty `/swarm` body now gets the documented
422 `antigravity_swarm_unavailable` instead of a generic 400
(`addIssueSwarmCommentSchema`, route red first 1); an empty ordinary
comment keeps its 400.

Review round (earlier head):
- `pnpm --filter @paperclipai/server exec vitest run` on the swarm,
request-path, native-execution-input, first-turn, queued-comments and
comment-route tests: 475 passed. Red first: request path 1, execution
input 3, empty/over-long DB 3 and route 2, Interrupt during a swarm 2,
Retry proof 2.
- Runner `src/drivers/acpx src/contracts`: passed; swarm runtime red
first 6 (request field, verbatim text, empty, over-long, no field,
request only in the rendered prompt).
- UI `TaskChatComposer.test.tsx`: over-long `/swarm` refused (red first
1).
- Typecheck: server (layers), UI and runner: no errors.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell,
file edit) in Claude Code.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:54:23 -06:00

685 lines
46 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { describe, expect, it } from "vitest";
import { projectTaskInterruption } from "./task-interruption-presentation.js";
const issue = { id: "task", companyId: "11111111-1111-4111-8111-111111111111", status: "blocked", assigneeAgentId: "agent", projectId: "22222222-2222-4222-8222-222222222222" };
const run = { id: "run", agentId: "agent", status: "failed", scheduledRetryAt: null,
errorCode: "project_access_denied", error: null, livenessState: null,
resultJson: { projectAccessDenied: { projectId: "22222222-2222-4222-8222-222222222222" } } };
const agent = { status: "idle", pauseReason: null };
describe("pending question presentation", () => {
const failed = { ...run, errorCode: "native_session_interrupted", resultJson: null };
const input = { run: failed, agent, paused: false, approval: false, question: true };
it("names the unanswered question instead of a historical failure, preserving an available manual Retry", () => {
for (const previousRun of [failed, { ...failed, status: "succeeded" }, undefined]) {
const presentation = projectTaskInterruption(issue, { ...input, run: previousRun });
expect(presentation).toMatchObject({ responsibility: "user", state: "waiting_for_user", userAction: "question",
canRetry: previousRun?.status === "failed" });
expect(presentation?.providerFailure).toBeUndefined();
}
});
it("does not offer another Retry while saved input or a Retry is pending", () => {
const wait = { id: "saved-input", requestedAt: new Date(), sourceRunId: failed.id };
for (const pending of [{ wait }, { retryWait: wait }])
expect(projectTaskInterruption(issue, { ...input, ...pending })).toMatchObject({ canRetry: false });
});
it("shows the question while automatic continuation waits, without offering to move it forward", () => {
for (const pendingSince of [undefined, Date.now() - 16 * 60_000])
expect(projectTaskInterruption(issue, { ...input, freshContinuation: { state: "continuing", pendingSince } }))
.toMatchObject({ state: "waiting_for_user", userAction: "question", canRetry: false });
});
it("preserves other current user gates", () => {
for (const [gate, userAction] of [[{ approval: true }, "approval"], [{ paused: true }, "resume"],
[{ ownerStopRequired: true }, "confirm_owner_stop"]] as const)
expect(projectTaskInterruption(issue, { ...input, ...gate })).toMatchObject({ state: "waiting_for_user", userAction, canRetry: false });
});
it("preserves live work and terminal task states", () => {
expect(projectTaskInterruption(issue, { ...input, run: { ...run, status: "running", errorCode: null } }))
.toMatchObject({ state: "working" });
expect(projectTaskInterruption({ ...issue, status: "done" }, input)).toMatchObject({ state: "resolved" });
});
});
describe("saved governed wait shutdown", () => {
const now = Date.parse("2026-11-09T12:00:00Z");
const pending = { ...run, runtimeMode: "native", errorCode: "native_governed_wait_settlement_pending", resultJson: null };
it("names automatic shutdown settlement without offering a duplicate Retry", () => {
expect(projectTaskInterruption(issue, { run: { ...pending, nativeResumeAt: new Date(now + 30_000) }, agent,
paused: false, approval: false }, now)).toMatchObject({ state: "working", canRetry: false,
retryWait: { reason: "governed_wait_settlement", message: "Your work is saved. Paperclip is finishing shutdown." } });
});
it("explains exhausted shutdown recovery while preserving the saved work", () => {
expect(projectTaskInterruption(issue, { run: pending, agent, paused: false, approval: false }, now))
.toMatchObject({ state: "failed", canRetry: false, retryWait: { reason: "governed_wait_settlement",
message: "Paperclip couldn’t confirm shutdown. Your work is saved; continuation is paused." } });
});
it("keeps genuine approvals authoritative", () => {
expect(projectTaskInterruption(issue, { run: pending, agent, paused: false, approval: true }, now))
.toMatchObject({ state: "waiting_for_user", userAction: "approval" });
});
});
describe("queued dependency wait presentation", () => {
const waitingRun = { ...run, status: "cancelled", runtimeMode: "legacy" as const, startedAt: null,
errorCode: "issue_dependencies_blocked", resultJson: {
stopReason: "issue_dependencies_blocked", timeoutSource: "dependency_gate",
cancellation: { source: "unknown", expected: false },
} };
it("keeps a dependency-gated wake out of the failed-attempt UI, including retained input", () => {
for (const wait of [undefined, { id: "saved-input", requestedAt: new Date(0) }]) {
expect(projectTaskInterruption(issue, { run: waitingRun, agent, wait, paused: false, approval: false }))
.toMatchObject({ state: "resolved", canRetry: false });
}
});
it.each(["legacy", "native"])("keeps an unstarted %s dispatcher dependency wait neutral", runtimeMode => {
const dispatchedWait = { ...waitingRun, runtimeMode,
resultJson: { ...waitingRun.resultJson, timeoutSource: "stale_queued_run_gate" } };
expect(projectTaskInterruption(issue, { run: dispatchedWait, agent, paused: false, approval: false }))
.toMatchObject({ state: "resolved", canRetry: false });
expect(projectTaskInterruption(issue, { run: { ...dispatchedWait, startedAt: new Date() }, agent, paused: false, approval: false }))
.toMatchObject({ state: "failed", canRetry: true });
});
it("keeps genuine failures and current user gates visible", () => {
for (const changed of [{ status: "failed" }, { runtimeMode: "native" }, { startedAt: new Date() },
{ errorCode: "setup_failed" }, { resultJson: {} }, { resultJson: { ...waitingRun.resultJson, timeoutFired: true } }]) {
expect(projectTaskInterruption(issue, { run: { ...waitingRun, ...changed }, agent, paused: false, approval: false }))
.toMatchObject({ state: "failed", canRetry: true });
}
expect(projectTaskInterruption(issue, { run: waitingRun, agent, paused: true, approval: false }))
.toMatchObject({ state: "waiting_for_user", userAction: "resume" });
expect(projectTaskInterruption(issue, { run: waitingRun, agent, paused: false, approval: true }))
.toMatchObject({ state: "waiting_for_user", userAction: "approval" });
expect(projectTaskInterruption(issue, { run: waitingRun, agent, paused: false, approval: false,
action: { evidence: {}, status: "active" } as never })).toMatchObject({ state: "failed", canRetry: true });
expect(projectTaskInterruption(issue, { run: waitingRun, agent, paused: false, approval: false,
retryWait: { id: "retry", sourceRunId: waitingRun.id, requestedAt: new Date(), preparationStatus: "failed" } }))
.toMatchObject({ state: "failed", canRetry: true });
});
});
describe("never-started task refused by admission", () => {
const todo = { ...issue, status: "todo" };
const admissionWait = { id: "wake", status: "skipped", reason: "budget.blocked", agentId: "agent" };
it("names an accounting hold as an automatic wait without a Retry", () => {
expect(projectTaskInterruption(todo, { agent, admissionWait, paused: false, approval: false })).toMatchObject({
responsibility: "system", state: "working", canRetry: false,
retryWait: { reason: "budget.blocked", message: expect.stringContaining("starts automatically") } });
});
it("keeps pauses and budget stops as user actions instead of promising an automatic start", () => {
for (const [state, action] of [
[{ project: { pausedAt: new Date(), pauseReason: null } }, "resume"],
[{ company: { status: "paused", pauseReason: "manual" } }, "resume"],
[{ paused: true }, "resume"],
[{ agent: { status: "paused", pauseReason: "manual" } }, "resume"],
[{ company: { status: "paused", pauseReason: "budget" } }, "budget"],
[{ approval: true }, "approval"],
] as const) {
expect(projectTaskInterruption(todo, { agent, admissionWait, paused: false, approval: false, ...state }))
.toMatchObject({ responsibility: "user", state: "waiting_for_user", userAction: action });
}
});
it("shows nothing for other refusals, started tasks or another assignee", () => {
for (const changed of [{ reason: "agent.not_invokable" }, { status: "queued" }, { agentId: "other" }]) {
expect(projectTaskInterruption(todo, { agent, admissionWait: { ...admissionWait, ...changed }, paused: false, approval: false }))
.toBeNull();
}
expect(projectTaskInterruption({ ...todo, status: "cancelled" }, { agent, admissionWait, paused: false, approval: false })).toBeNull();
});
});
describe("unadmitted chat Retry presentation", () => {
const now = Date.parse("2026-01-01T12:00:00Z");
const failed = { ...run, errorCode: "native_provider_terminal_failed", resultJson: null };
const wait = { id: "retry", requestedAt: new Date(now), sourceRunId: run.id,
preparationStatus: "issued", preparationRetryAt: now + 250 };
const input = { run: failed, agent, wait, paused: false, approval: false };
it.each(["issued", "processing"])("uses the persisted %s outbox deadline without implying provider work", status => {
for (const offset of [0, 20_000]) expect(projectTaskInterruption(issue, {
...input, wait: { ...wait, preparationStatus: status },
}, now + offset)).toMatchObject({ state: "retry_scheduled", canRetry: false,
nextRetryAt: new Date(wait.preparationRetryAt).toISOString() });
});
it.each(["failed", "cancelled"])("keeps terminal %s preparation out of the working state", status => {
expect(projectTaskInterruption(issue, { ...input, wait: { ...wait, preparationStatus: status,
preparationRetryAt: null } }, now)).toMatchObject({ state: "failed", nextRetryAt: null });
});
it("keeps current gates and admitted execution authoritative", () => {
expect(projectTaskInterruption(issue, { ...input, paused: true }, now))
.toMatchObject({ state: "waiting_for_user", userAction: "resume" });
expect(projectTaskInterruption(issue, { ...input, approval: true }, now))
.toMatchObject({ state: "waiting_for_user", userAction: "approval" });
for (const status of ["queued", "running"]) expect(projectTaskInterruption(issue, {
...input, run: { ...failed, id: "successor", status },
}, now)).toMatchObject({ state: "working", nextRetryAt: null });
expect(projectTaskInterruption(issue, { ...input, wait: { ...wait, sourceRunId: "old-run" } }, now))
.toMatchObject({ state: "working", nextRetryAt: null });
});
});
// The native coordinator resumes the same run itself after an attach failure.
// A manual Retry offered meanwhile would race that automatic resume.
it("shows a pending native same-run resume instead of a competing Retry", () => {
const now = Date.parse("2026-11-06T15:25:50.000Z");
const failed = { ...run, runtimeMode: "native" as const, errorCode: "native_session_interrupted", resultJson: null };
const resumeAt = new Date("2026-11-06T15:26:18.687Z");
expect(projectTaskInterruption(issue, { run: { ...failed, nativeResumeAt: resumeAt }, agent, paused: false, approval: false }, now))
.toMatchObject({ state: "retry_scheduled", canRetry: false, nextRetryAt: resumeAt.toISOString() });
// A due resume is being dispatched; it is still not the user's turn.
expect(projectTaskInterruption(issue, { run: { ...failed, nativeResumeAt: new Date(now - 30_000) }, agent, paused: false, approval: false }, now))
.toMatchObject({ state: "working", canRetry: false });
// A resume that never ran, or no resume at all, leaves exactly one Retry.
expect(projectTaskInterruption(issue, { run: { ...failed, nativeResumeAt: new Date(now - 10 * 60_000) }, agent, paused: false, approval: false }, now))
.toMatchObject({ state: "failed", canRetry: true });
expect(projectTaskInterruption(issue, { run: failed, agent, paused: false, approval: false }, now))
.toMatchObject({ state: "failed", canRetry: true });
});
it("explains a persisted Retry wait without exposing the saved payload", () => {
const failed = { ...run, errorCode: "native_provider_terminal_failed", resultJson: null };
const wait = { id: "retry", requestedAt: new Date(), sourceRunId: failed.id,
executionWaitReason: "workspace_repair_required" };
const presentation = projectTaskInterruption(issue, { run: failed, agent, wait, paused: false, approval: false });
expect(presentation).toMatchObject({ state: "failed", canRetry: true,
retryWait: { reason: "workspace_repair_required", message: "Retry is waiting for Paperclip to recover the saved files. Your message is saved." } });
expect(projectTaskInterruption(issue, { run: failed, agent, wait: { ...wait, sourceRunId: "another-run" }, paused: false, approval: false }))
.not.toHaveProperty("retryWait");
expect(projectTaskInterruption(issue, { run: failed, agent, wait: { ...wait, executionWaitReason: "secret-payload" }, paused: false, approval: false }))
.toMatchObject({ retryWait: { reason: "execution_recovery", message: "Retry is waiting for execution checks. Your message is saved." } });
expect(projectTaskInterruption(issue, { run: failed, agent, wait, paused: true, approval: false }))
.toMatchObject({ state: "waiting_for_user", userAction: "resume" });
});
it("names a budget gate instead of generic execution checks for a refused Retry", () => {
const failed = { ...run, errorCode: "native_provider_terminal_failed", resultJson: null };
expect(projectTaskInterruption(issue, { run: failed, agent, paused: false, approval: false,
wait: { id: "retry", requestedAt: new Date(), sourceRunId: failed.id, executionWaitReason: "budget.blocked" } }))
.toMatchObject({ state: "failed", canRetry: true, retryWait: { reason: "budget.blocked",
message: "Retry is waiting for the budget to allow new work. Check Costs for unrecorded or unpriced usage." } });
});
it.each(["cancelled_by_operator", "retry_source_changed"])("does not offer Retry for terminal Retry waits: %s", reason => {
const failed = { ...run, errorCode: "native_provider_terminal_failed", resultJson: null };
expect(projectTaskInterruption(issue, { run: failed, agent, paused: false, approval: false,
wait: { id: "retry", requestedAt: new Date(), sourceRunId: failed.id, executionWaitReason: reason } }))
.toMatchObject({ state: "failed", canRetry: false, retryWait: { reason } });
});
it("holds a Retry on a cleanup gate only while an owner settles it", () => {
const failed = { ...run, errorCode: "native_provider_terminal_failed", resultJson: null };
const wait = { id: "retry", requestedAt: new Date(), sourceRunId: failed.id, executionWaitReason: "cleanup_quarantined" };
expect(projectTaskInterruption(issue, { run: failed, agent, paused: false, approval: false, wait, cleanupSettling: true }))
.toMatchObject({ state: "failed", canRetry: false, retryWait: { reason: "cleanup_quarantined" } });
expect(projectTaskInterruption(issue, { run: failed, agent, paused: false, approval: false, wait }))
.toMatchObject({ state: "failed", canRetry: true, retryWait: { reason: "cleanup_quarantined" } });
});
it("keeps Retry for a Retry declined for its requester's access, since a new click replaces it", () => {
const failed = { ...run, errorCode: "native_provider_terminal_failed", resultJson: null };
expect(projectTaskInterruption(issue, { run: failed, agent, paused: false, approval: false,
wait: { id: "retry", requestedAt: new Date(), sourceRunId: failed.id, executionWaitReason: "retry_authority_denied" } }))
.toMatchObject({ state: "failed", canRetry: true, retryWait: { reason: "retry_authority_denied" } });
});
it("preserves the actual workspace preparation error without changing retry authority", () => {
const failedRun = { ...run, errorCode: "workspace_validation_failed",
error: "The selected project has no repository source for a remote workspace.", resultJson: null };
expect(projectTaskInterruption(issue, { run: failedRun, agent, paused: false, approval: false }))
.toMatchObject({ state: "failed", canRetry: true, workspaceFailure: { message: failedRun.error } });
for (const status of ["done", "cancelled"]) expect(projectTaskInterruption({ ...issue, status },
{ run: failedRun, agent, paused: false, approval: false })).not.toHaveProperty("workspaceFailure");
expect(projectTaskInterruption(issue, { run: { ...failedRun, errorCode: "unrelated_failure" }, agent, paused: false, approval: false }))
.not.toHaveProperty("workspaceFailure");
});
describe("setup command failure presentation (CF1)", () => {
const setupError = "Execution workspace provision command \"bash ./scripts/provision-worktree.sh\" failed: bash: ./scripts/provision-worktree.sh: No such file or directory";
const setupRun = { ...run, errorCode: "setup_failed", error: setupError, resultJson: { setupCommandFailure: {
step: "workspace_provision", command: "bash ./scripts/provision-worktree.sh", exitCode: 127,
output: "bash: ./scripts/provision-worktree.sh: No such file or directory" } } };
it("names the broken setup command on the task without changing retry authority", () => {
const withCause = projectTaskInterruption(issue, { run: setupRun, agent, paused: false, approval: false });
const withoutCause = projectTaskInterruption(issue, { run: { ...setupRun, error: "x", resultJson: null }, agent, paused: false, approval: false });
expect(withCause).toMatchObject({ state: "failed", canRetry: true, userAction: null, setupFailure: {
step: "workspace_provision", command: "bash ./scripts/provision-worktree.sh", exitCode: 127,
message: "The project's workspace provision command \"bash ./scripts/provision-worktree.sh\" failed with exit code 127: bash: ./scripts/provision-worktree.sh: No such file or directory" } });
const { setupFailure: _named, ...rest } = withCause!;
expect(rest).toEqual(withoutCause);
expect(withCause).not.toHaveProperty("workspaceFailure");
});
it("recognizes a setup failure recorded before the structured cause existed", () => {
expect(projectTaskInterruption(issue, { run: { ...setupRun, resultJson: null }, agent, paused: false, approval: false }))
.toMatchObject({ state: "failed", setupFailure: { step: "workspace_provision", command: "bash ./scripts/provision-worktree.sh",
exitCode: null, output: "bash: ./scripts/provision-worktree.sh: No such file or directory" } });
});
it("keeps a transient setup retry scheduled and only adds the name", () => {
const retrying = { ...setupRun, status: "scheduled_retry", scheduledRetryAt: new Date(Date.now() + 60_000), scheduledRetryReason: "transient_failure" };
const named = projectTaskInterruption(issue, { run: retrying, agent, paused: false, approval: false });
const unnamed = projectTaskInterruption(issue, { run: { ...retrying, error: "x", resultJson: null }, agent, paused: false, approval: false });
expect(named?.setupFailure?.command).toBe("bash ./scripts/provision-worktree.sh");
const { setupFailure: _named, ...rest } = named!;
expect(rest).toEqual(unnamed);
});
it("bounds the output tail and strips credentials from the command", () => {
const noisy = { ...setupRun, resultJson: { setupCommandFailure: { step: "workspace_provision",
command: "GITHUB_TOKEN=ghp_abcdefghijklmnopqrstuvwxyz0123456789 ./setup.sh --password hunter22", exitCode: 1,
output: `${"x".repeat(5_000)}\nfinal line` } } };
const failure = projectTaskInterruption(issue, { run: noisy, agent, paused: false, approval: false })?.setupFailure;
expect(failure?.command).not.toContain("ghp_abcdefghijklmnopqrstuvwxyz0123456789");
expect(failure?.command).not.toContain("hunter22");
expect(failure?.output?.length).toBeLessThanOrEqual(300);
expect(failure?.output).toMatch(/final line$/);
});
it("recognizes older quoted and multiline commands", () => {
for (const command of ['bash "./scripts/provision-worktree.sh"', "set -e\n./setup.sh"]) {
expect(projectTaskInterruption(issue, { run: { ...setupRun, resultJson: null,
error: `Execution workspace provision command "${command}" failed with exit code 2` }, agent, paused: false, approval: false })?.setupFailure)
.toMatchObject({ command, exitCode: 2 });
}
});
it("does not name setup for other failures or settled tasks", () => {
expect(projectTaskInterruption(issue, { run: { ...setupRun, errorCode: "adapter_failed" }, agent, paused: false, approval: false }))
.not.toHaveProperty("setupFailure");
expect(projectTaskInterruption({ ...issue, status: "done" }, { run: setupRun, agent, paused: false, approval: false }))
.not.toHaveProperty("setupFailure");
});
});
function operatorStoppedRun() {
return { ...run, status: "cancelled", runtimeMode: "native" as const, companyId: issue.companyId,
nativeIssueId: issue.id, errorCode: "cancelled", resultJson: {
cancelledByActorType: "user", cancelledByUserId: "board",
executionCancellation: { state: "requested" },
nativeCancellation: { schema: "paperclip.native-cancellation.v1", runId: run.id,
companyId: issue.companyId, issueId: issue.id, scope: "run",
reasonCode: "cancellation_run_only", dispatched: true, dispatchState: "acknowledged",
intentAuditId: "intent", acknowledgementAuditId: "ack" },
} };
}
describe("intentional native Stop presentation", () => {
const workingIssue = { ...issue, status: "in_progress" };
it("does not offer a failed-attempt Retry for an audited operator Stop that keeps its task in progress", () => {
expect(projectTaskInterruption(workingIssue, { run: operatorStoppedRun(), agent, paused: false, approval: false }))
.toMatchObject({ state: "resolved", canRetry: false, userAction: null });
expect(workingIssue.status).toBe("in_progress");
});
it.each([{ runId: "foreign" }, { companyId: "foreign" }, { issueId: "foreign" },
{ dispatchState: "pending" }, { dispatched: false }, { acknowledgementAuditId: undefined },
{ intentAuditId: 123 }, { acknowledgementAuditId: {} },
{ scope: "subtree" }])("retains failure presentation without the matching operator receipt %j", change => {
const stopped = operatorStoppedRun();
expect(projectTaskInterruption(workingIssue, { run: { ...stopped, resultJson: { ...stopped.resultJson,
nativeCancellation: { ...stopped.resultJson.nativeCancellation, ...change } } }, agent, paused: false, approval: false }))
.toMatchObject({ state: "failed", canRetry: true });
});
it("keeps pause, approval, non-user cancellation and new input authoritative", () => {
const stopped = operatorStoppedRun();
expect(projectTaskInterruption(workingIssue, { run: stopped, agent, paused: true, approval: false }))
.toMatchObject({ state: "waiting_for_user", userAction: "resume" });
expect(projectTaskInterruption(workingIssue, { run: stopped, agent, paused: false, approval: true }))
.toMatchObject({ state: "waiting_for_user", userAction: "approval" });
expect(projectTaskInterruption(workingIssue, { run: { ...stopped, resultJson: {
...stopped.resultJson, cancelledByActorType: "system" } }, agent, paused: false, approval: false }))
.toMatchObject({ state: "failed", canRetry: true });
expect(projectTaskInterruption(workingIssue, { run: stopped, agent, paused: false, approval: false,
wait: { id: "new-input", requestedAt: new Date() } }))
.toMatchObject({ state: "working", canRetry: false });
});
});
describe("intentional legacy Stop presentation", () => {
it("clears the failed-attempt notice only after the requested Stop is acknowledged", () => {
const stopped = { ...run, runtimeMode: "legacy" as const, status: "cancelled", finishedAt: new Date(), resultJson: {
cancellation: { source: "operator", expected: true, initiator: { type: "user" }, reason: "Stop", recordedAt: new Date().toISOString() },
executionCancellation: { state: "acknowledged", proof: "preparation_settled" },
} };
const input = { run: stopped, agent, paused: false, approval: false };
expect(projectTaskInterruption(issue, input)).toMatchObject({ state: "resolved", canRetry: false });
expect(projectTaskInterruption(issue, { ...input, run: { ...stopped, resultJson: { ...stopped.resultJson,
executionCancellation: { state: "requested" } } } })).toMatchObject({ state: "failed", canRetry: true });
expect(projectTaskInterruption(issue, { ...input, paused: true })).toMatchObject({ userAction: "resume" });
expect(projectTaskInterruption(issue, { ...input, approval: true })).toMatchObject({ userAction: "approval" });
});
});
it("preserves a provider explanation on a failed task without changing retry authority", () => {
const providerFailure = { schema: "paperclip.provider-failure.v1", provider: "anthropic", phase: "startup",
category: "rate_limit", message: "API error: 429 This request would exceed your account's rate limit.",
httpStatus: 429, retryability: "unknown" };
const failedRun = { ...run, errorCode: "native_session_interrupted", resultJson: { providerFailure } };
const presentation = projectTaskInterruption(issue, { run: failedRun, agent, paused: false, approval: false });
expect(presentation).toMatchObject({ state: "failed", canRetry: true, providerFailure });
expect(projectTaskInterruption({ ...issue, status: "done" }, { run: failedRun, agent, paused: false, approval: false }))
.not.toHaveProperty("providerFailure");
});
it("shows a refused /swarm's plain reason without a Retry that would meet the same refusal", () => {
const providerFailure = { schema: "paperclip.provider-failure.v1", provider: "antigravity", phase: "startup",
category: "model_unavailable", retryability: "requires_action",
message: "Swarm is not available with Gemini 4 Neon (Low) yet, so nothing was changed: choose another model for this agent, such as Gemini 4 Argon, and send /swarm again." };
const refused = { ...run, errorCode: "antigravity_swarm_unavailable", error: providerFailure.message, resultJson: { providerFailure } };
expect(projectTaskInterruption(issue, { run: refused, agent, paused: false, approval: false }))
.toMatchObject({ state: "failed", canRetry: false, providerFailure });
// A swarm verification failure that may not repeat keeps its Retry.
const mismatch = { ...providerFailure, category: "unknown", retryability: "unknown", message: "Swarm stopped before it started: the provider did not confirm auto mode. Nothing was changed." };
expect(projectTaskInterruption(issue, { run: { ...refused, resultJson: { providerFailure: mismatch } }, agent, paused: false, approval: false }))
.toMatchObject({ state: "failed", canRetry: true });
});
it("asks for billing action for an exhausted provider quota without inventing a retry time", () => {
const failed = { ...run, errorCode: "native_provider_usage_limit", resultJson: { providerFailure: {
schema: "paperclip.provider-failure.v1", provider: "openai", phase: "turn",
category: "quota_exhausted", providerCode: "insufficient_quota", message: "Check your plan and billing details.",
retryability: "requires_action",
} } };
const input = { run: failed, agent, paused: false, approval: false };
expect(projectTaskInterruption(issue, input)).toMatchObject({ state: "waiting_for_user", responsibility: "user",
userAction: "provider_billing", nextRetryAt: null });
expect(projectTaskInterruption(issue, { ...input, paused: true })).toMatchObject({ userAction: "resume" });
expect(projectTaskInterruption(issue, { ...input, approval: true })).toMatchObject({ userAction: "approval" });
expect(projectTaskInterruption(issue, { ...input, run: { ...failed, resultJson: { providerFailure: {
...failed.resultJson.providerFailure, retryAt: new Date(Date.now() + 60_000).toISOString(),
} } } })).not.toMatchObject({ userAction: "provider_billing" });
});
describe("task project-access interruption", () => {
it("explains a project denial without offering a futile retry", () => {
expect(projectTaskInterruption(issue, { run, agent, paused: false, approval: false })).toMatchObject({
state: "waiting_for_user", responsibility: "user", userAction: "project_access", canRetry: false,
projectAccess: { agentId: "agent", projectId: "22222222-2222-4222-8222-222222222222", ready: false },
});
});
it("projects the historical setup denial without requiring another failed run", () => {
expect(projectTaskInterruption(issue, { run: { ...run, errorCode: "setup_failed",
error: "Project is outside this low-trust boundary.", resultJson: null }, agent, paused: false, approval: false }))
.toMatchObject({ userAction: "project_access", canRetry: false });
});
it("offers an explicit retry after the project is added, without changing the failed run", () => {
expect(projectTaskInterruption(issue, { run, agent, projectAccessAllowed: true, paused: false, approval: false }))
.toMatchObject({ state: "failed", canRetry: true, projectAccess: { ready: true } });
expect(run.status).toBe("failed");
});
it("shows an accepted retry as working after access is repaired", () => {
const input = { run, agent, paused: false, approval: false, wait: { id: "request", requestedAt: new Date() } };
expect(projectTaskInterruption(issue, { ...input, projectAccessAllowed: true }))
.toMatchObject({ state: "working", canRetry: false });
expect(projectTaskInterruption(issue, { ...input, projectAccessAllowed: true })).not.toHaveProperty("projectAccess");
expect(projectTaskInterruption(issue, { ...input, projectAccessAllowed: false }))
.toMatchObject({ state: "waiting_for_user", userAction: "project_access", canRetry: false });
});
it("does not reinterpret unrelated failures or an old assignee's denial", () => {
for (const otherRun of [{ ...run, errorCode: "setup_failed", error: "Disk full", resultJson: null },
{ ...run, agentId: "previous-agent" }]) {
expect(projectTaskInterruption(issue, { run: otherRun, agent, paused: false, approval: false }))
.not.toHaveProperty("projectAccess");
}
});
it("keeps approval, pause, running and completed states authoritative", () => {
expect(projectTaskInterruption(issue, { run, agent, paused: false, approval: true })).toMatchObject({ userAction: "approval" });
expect(projectTaskInterruption(issue, { run, agent, paused: true, approval: false })).toMatchObject({ userAction: "resume" });
expect(projectTaskInterruption(issue, { run: { ...run, status: "running" }, agent, paused: false, approval: false }))
.toMatchObject({ state: "working" });
expect(projectTaskInterruption({ ...issue, status: "done" }, { run, agent, paused: false, approval: false }))
.toMatchObject({ state: "resolved" });
});
});
describe("saved-work recovery step", () => {
const now = Date.parse("2026-01-01T12:00:00Z");
const failed = { ...run, errorCode: "setup_failed", resultJson: null };
const system = (phase: string, state: string, nextAttemptAt: number | null) => ({
schema: "paperclip.system-recovery.v1", policyVersion: 1, sourceRunId: "33333333-3333-4333-8333-333333333333", revision: 3,
generationId: "44444444-4444-4444-8444-444444444444", intentId: null, phase, state, attemptId: null, attempts: 2,
retriesUsed: 1, firstFailureAt: now - 60_000, nextAttemptAt, deadlineAt: now + 600_000, providerCooldownAt: null,
failure: null, preservationOperationIds: [], freshAttemptRunId: null });
const action = (evidence: Record<string, unknown>) => ({ evidence }) as never;
it("names the step a scheduled recovery will retry", () => {
expect(projectTaskInterruption(issue, { run: failed, agent, paused: false, approval: false,
action: action({ systemRecovery: system("verify_execution", "scheduled", now + 30_000) }) }, now))
.toMatchObject({ state: "retry_scheduled", recoveryStep: "checking_previous_run" });
});
it("names the step a running recovery is on", () => {
expect(projectTaskInterruption(issue, { run: failed, agent, paused: false, approval: false,
action: action({ systemRecovery: system("preserve_files", "running", null), systemRecoveryActiveAt: now - 1_000 }) }, now))
.toMatchObject({ state: "working", recoveryStep: "saving_previous_files" });
});
it("names recovery over a pending chat preparation and keeps failed preparation authoritative", () => {
const wait = { id: "retry", requestedAt: new Date(now), sourceRunId: failed.id, preparationStatus: "issued", preparationRetryAt: now + 250 };
const running = action({ systemRecovery: system("preserve_files", "running", null), systemRecoveryActiveAt: now - 1_000 });
expect(projectTaskInterruption(issue, { run: failed, agent, wait, paused: false, approval: false, action: running }, now))
.toMatchObject({ state: "working", recoveryStep: "saving_previous_files" });
const scheduled = action({ systemRecovery: system("verify_execution", "scheduled", now + 30_000) });
expect(projectTaskInterruption(issue, { run: failed, agent, wait, paused: false, approval: false, action: scheduled }, now))
.toMatchObject({ state: "retry_scheduled", recoveryStep: "checking_previous_run", canRetry: false });
expect(projectTaskInterruption(issue, { run: failed, agent, paused: false, approval: false, action: scheduled }, now))
.toMatchObject({ state: "retry_scheduled", canRetry: true });
expect(projectTaskInterruption(issue, { run: failed, agent, wait: { ...wait, preparationStatus: "failed" },
paused: false, approval: false, action: running }, now)).toMatchObject({ state: "failed" });
expect(projectTaskInterruption(issue, { run: failed, agent, wait, paused: false, approval: false }, now))
.toMatchObject({ state: "retry_scheduled", nextRetryAt: new Date(now + 250).toISOString() });
});
it("does not name a step for an ordinary scheduled retry", () => {
expect(projectTaskInterruption(issue, { run: { ...failed, scheduledRetryAt: new Date(now + 30_000) }, agent,
paused: false, approval: false }, now)).not.toHaveProperty("recoveryStep");
});
});
describe("scheduled resource wait presentation", () => {
const now = Date.parse("2026-01-01T12:00:00Z");
const waiting = { ...run, status: "scheduled_retry", errorCode: null, resultJson: null,
scheduledRetryReason: "workspace_busy", scheduledRetryAt: new Date(now - 60_000) };
it("keeps an overdue workspace wait out of the failed-attempt UI", () => {
expect(projectTaskInterruption(issue, { run: waiting, agent, paused: false, approval: false }, now))
.toMatchObject({ state: "working", canRetry: false });
});
it("keeps failure retries, user gates and failed Retry preparation authoritative", () => {
expect(projectTaskInterruption(issue, { run: { ...waiting, scheduledRetryReason: "transient_failure",
scheduledRetryAt: new Date(now - 10 * 60_000) }, agent, paused: false, approval: false }, now))
.toMatchObject({ state: "failed", canRetry: true });
expect(projectTaskInterruption(issue, { run: waiting, agent, paused: true, approval: false }, now))
.toMatchObject({ state: "waiting_for_user", userAction: "resume" });
expect(projectTaskInterruption(issue, { run: waiting, agent, paused: false, approval: false,
retryWait: { id: "retry", sourceRunId: run.id, requestedAt: new Date(now), preparationStatus: "failed" } }, now))
.toMatchObject({ state: "failed", canRetry: true });
});
});
describe("saved Retry held by dependencies", () => {
const failedRun = { ...run, status: "failed", errorCode: "native_session_interrupted", resultJson: {} };
const retryWait = { id: "retry", requestedAt: new Date(0), sourceRunId: "run" };
const project = (retryDependencies: { count: number; blocked: boolean; cancelled: boolean; savingFilesOnly: boolean }) =>
projectTaskInterruption(issue, { run: failedRun, agent, retryWait, paused: false, approval: false, retryDependencies });
it.each([
[{ count: 1, blocked: true, cancelled: false, savingFilesOnly: false }, "Retry or unblock it"],
[{ count: 1, blocked: false, cancelled: true, savingFilesOnly: false }, "Remove or replace that dependency"],
[{ count: 1, blocked: false, cancelled: false, savingFilesOnly: true }, "to save its files"],
[{ count: 2, blocked: false, cancelled: false, savingFilesOnly: false }, "to finish"],
])("names what the saved Retry waits on (%o)", (dependencies, text) => {
const presentation = project(dependencies);
expect(presentation).toMatchObject({ state: "working", canRetry: false, intentId: "retry",
retryWait: { reason: "dependency_blocked" } });
expect(presentation?.retryWait?.message).toContain(text);
});
});
describe("setup command failure evidence", () => {
it("removes a registered secret that crosses the output cut before shortening", async () => {
const { setupCommandFailureResultJson } = await import("./workspace-setup-command-failure.js");
const secret = "registered-private-value-0123456789";
const failure = Object.assign(new Error("setup failed"), { step: "workspace_provision", command: "./setup.sh", exitCode: 1,
// The cut keeps the last 299 characters; it lands inside the secret.
output: `${secret}${"y".repeat(299 - 10)}` });
const recorded = setupCommandFailureResultJson(failure, [secret]);
expect(recorded).toMatchObject({ setupCommandFailure: { step: "workspace_provision", exitCode: 1 } });
const text = JSON.stringify(recorded);
for (let index = 0; index + 8 <= secret.length; index += 1) expect(text).not.toContain(secret.slice(index, index + 8));
});
});
describe("saved result that ran out of finalization retries", () => {
const review = { ...issue, status: "in_review" };
const succeeded = { ...run, status: "succeeded", runtimeMode: "native" as const, errorCode: null, resultJson: null };
it("offers Retry for a succeeded run whose accepted result could not be finalized", () => {
expect(projectTaskInterruption(review, { run: { ...succeeded, nativeFinalizationRetry: true }, agent,
paused: false, approval: false })).toMatchObject({ state: "failed", canRetry: true, observedRunId: "run" });
});
it("shows the saved result being applied after Retry", () => {
expect(projectTaskInterruption(review, { run: { ...succeeded, nativeFinalizationRetryPending: true }, agent,
paused: false, approval: false })).toMatchObject({ state: "working", canRetry: false, recoveryStep: "finishing_recovery" });
});
it("keeps ordinary succeeded and failed runs unchanged", () => {
expect(projectTaskInterruption(review, { run: succeeded, agent, paused: false, approval: false }))
.toMatchObject({ state: "resolved", canRetry: false });
expect(projectTaskInterruption(review, { run: { ...succeeded, status: "failed", errorCode: "adapter_failed" }, agent,
paused: false, approval: false })).toMatchObject({ state: "failed", canRetry: true });
expect(projectTaskInterruption({ ...review, status: "done" }, { run: { ...succeeded, nativeFinalizationRetry: true },
agent, paused: false, approval: false })).toMatchObject({ state: "resolved", canRetry: false });
});
});
// Remote native run shape: the provider turn completed and its work was
// saved, then a same-run recovery was refused by the cleanup gate. The task
// showed "Couldn't finish this attempt" with a Retry the server refuses (409).
describe("native cleanup quarantine presentation", () => {
const quarantined = { ...run, runtimeMode: "native" as const, errorCode: "native_session_cleanup_quarantined",
error: "native_session_cleanup_quarantined: prior session cleanup requires operator recovery; verify its retained process ownership and checkpoint before a controlled restart. Clearing a task session does not resolve this quarantine.",
resultJson: null, finishedAt: new Date("2026-11-10T14:39:31.873Z") };
it("shows the task's blocker wait, not a failed attempt, after a completed turn", () => {
expect(projectTaskInterruption(issue, { run: { ...quarantined, completedTurnCleanup: true }, agent,
waitingOnBlockers: true, paused: false, approval: false })).toMatchObject({ state: "resolved", canRetry: false });
});
it("waits without Retry while an owner settles the gate", () => {
for (const completedTurnCleanup of [true, false]) {
const presentation = projectTaskInterruption(issue, { run: { ...quarantined, completedTurnCleanup }, agent,
cleanupSettling: true, paused: false, approval: false });
expect(presentation).toMatchObject({ state: "failed", canRetry: false, retryWait: { reason: "cleanup_quarantined" } });
expect(presentation?.retryWait?.message).not.toMatch(/operator|admin/i);
}
const preparation = { id: "retry", requestedAt: new Date(0), sourceRunId: quarantined.id, preparationStatus: "failed" };
expect(projectTaskInterruption(issue, { run: quarantined, agent, retryWait: preparation, cleanupSettling: true,
paused: false, approval: false })).toMatchObject({ canRetry: false });
});
it("offers Retry when nothing settles the gate by itself (s9107 t04/t05)", () => {
// An operator-required gate, or one lost with a restarted process, has no
// owner. Waiting would never end, so Retry is the way forward.
for (const completedTurnCleanup of [true, false]) {
const presentation = projectTaskInterruption(issue, { run: { ...quarantined, completedTurnCleanup }, agent,
paused: false, approval: false });
expect(presentation).toMatchObject({ state: "failed", canRetry: true });
expect(presentation).not.toHaveProperty("retryWait");
}
});
it("never leaves a failed task without Retry, a scheduled retry or a settling owner", () => {
// Invariant: a failed presentation without Retry must name a wait that an
// owner is settling. Enumerate the quarantine-related inputs.
const waits = [undefined, ...["cleanup_quarantined", "local_cleanup", "execution_settling"].map(reason =>
({ id: "retry", requestedAt: new Date(0), sourceRunId: quarantined.id, executionWaitReason: reason }))];
for (const completedTurnCleanup of [true, false]) for (const wait of waits) for (const settling of [true, false]) {
const presentation = projectTaskInterruption(issue, { run: { ...quarantined, completedTurnCleanup }, agent,
retryWait: wait, cleanupSettling: settling, paused: false, approval: false });
if (presentation?.state !== "failed" || presentation.canRetry) continue;
expect(presentation.retryWait, JSON.stringify({ completedTurnCleanup, wait: wait?.executionWaitReason, settling }))
.toBeDefined();
if (presentation.retryWait?.reason === "cleanup_quarantined") expect(settling).toBe(true);
}
});
it("keeps Retry for ordinary failed native attempts", () => {
expect(projectTaskInterruption(issue, { run: { ...quarantined, errorCode: "native_session_interrupted" }, agent,
paused: false, approval: false })).toMatchObject({ state: "failed", canRetry: true });
});
});
describe("automatic scheduled retry", () => {
const now = Date.parse("2026-11-12T23:00:00Z");
const scheduled = { ...run, status: "scheduled_retry", runtimeMode: "legacy", errorCode: null, resultJson: null,
scheduledRetryReason: "transient_failure", scheduledRetryAt: new Date(now + 60_000) };
it("shows a pending transient-failure retry as scheduled without a competing Retry", () => {
expect(projectTaskInterruption(issue, { run: scheduled, agent, paused: false, approval: false }, now))
.toMatchObject({ state: "retry_scheduled", canRetry: false, nextRetryAt: new Date(now + 60_000).toISOString() });
});
it.each(["transient_failure", "native_environment_blocker"])(
"keeps a just-due %s retry working while the dispatcher promotes it", scheduledRetryReason => {
for (const overdueMs of [0, 1_000, 30_000, 119_000]) {
expect(projectTaskInterruption({ ...issue, status: "in_progress" }, { run: { ...scheduled, runtimeMode: "native",
scheduledRetryReason, scheduledRetryAt: new Date(now - overdueMs) }, agent, paused: false, approval: false }, now))
.toMatchObject({ state: "working", canRetry: false });
}
});
it("offers Retry once the scheduled retry is past due with nothing else pending", () => {
expect(projectTaskInterruption(issue, { run: { ...scheduled, scheduledRetryAt: new Date(now - 10 * 60_000) }, agent,
paused: false, approval: false }, now)).toMatchObject({ state: "failed", canRetry: true });
});
it("offers Retry once the scheduled retries are exhausted", () => {
expect(projectTaskInterruption(issue, { run: { ...scheduled, status: "failed", errorCode: "transient_failure_retry_exhausted",
scheduledRetryAt: new Date(now - 60_000) }, agent, paused: false, approval: false }, now))
.toMatchObject({ state: "failed", canRetry: true });
});
});
describe("hand-off of a run that failed before any provider work", () => {
const now = Date.parse("2026-11-13T15:08:12Z");
const failed = { ...run, runtimeMode: "native" as const, errorCode: "adapter_failed", finishedAt: new Date(now - 3_000),
resultJson: { failureCause: "native_predecessor_retirement_unproven", executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } };
const inProgress = { ...issue, status: "in_progress" };
it("shows the task as working while its fresh-sandbox continuation is being queued", () => {
for (const failureCause of ["native_predecessor_retirement_unproven", "native_failed_before_provider_turn"]) {
expect(projectTaskInterruption(inProgress, { run: { ...failed, resultJson: { ...failed.resultJson, failureCause } },
agent, paused: false, approval: false }, now)).toMatchObject({ state: "working", canRetry: false });
}
});
it("keeps the task working after the fallback is recorded while its continuation is still being scheduled", () => {
const recorded = { ...failed, resultJson: { ...failed.resultJson, predecessorRetirementFallback: { version: 1, providerWorkStarted: false } } };
expect(projectTaskInterruption(inProgress, { run: recorded, agent, paused: false, approval: false }, now))
.toMatchObject({ state: "working", canRetry: false });
});
it("offers Retry when the continuation was refused or never queued", () => {
const refused = { ...failed, resultJson: { ...failed.resultJson, predecessorRetirementFallback: { version: 1, providerWorkStarted: false },
continuationScheduling: "refused" } };
expect(projectTaskInterruption(inProgress, { run: refused, agent, paused: false, approval: false }, now))
.toMatchObject({ state: "failed", canRetry: true });
expect(projectTaskInterruption(inProgress, { run: { ...failed, finishedAt: new Date(now - 31_000) }, agent, paused: false, approval: false }, now))
.toMatchObject({ state: "failed", canRetry: true });
});
});