mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 11:59:26 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - When a run is interrupted, a saved-work hold protects the files it
left. The fresh-continuation fallback then continues the task in a new
run, or asks a person to press Retry.
> - Staging found that an older run's saved-work hold made the dispatch
gate cancel every new run of the task. The hold was never settled, so
the task could not run again, and no person could act on the reason.
> - Recovery notices also showed internal codes and words such as
"board", "inspect", "repair" and "no live execution path". People cannot
act on these.
> - A person's Retry pressed while an isolated continuation was waiting
for delivery was saved, and then ran a second time after the
continuation.
> - This pull request settles an older run's hold through the fallback's
existing machinery, uses plain wording in every remaining recovery
notice (server and UI together), and folds a waiting Retry into the
isolated continuation that answers it.
> - The benefit is that a task held by an older run continues by itself,
or on one Retry, in a fresh isolated workspace. People read only what
happened and the one thing they can do, and a Retry never starts a
redundant second run.
## Linked Issues or Issue Description
**What happened?**
1. An earlier run's saved-work hold (for example "Automatic recovery of
saved work failed … Retry to try again") made the dispatch gate cancel
every new run of the task with `execution_reconciliation_required`. The
fresh-continuation fallback only took holds of the task's latest run.
Each refused run looked like a newer run, so the hold was never settled.
2. Recovery notices and recovery-task comments showed internal codes,
raw IDs, "board", "inspect", "repair" and "no live execution path". The
hold for remote files that could not be restored asked a person to
"verify its exact stop receipt" and to "record workspaceRepairEvidence".
3. On a projectless task whose old legacy writer might still be alive, a
person's Retry pressed after the isolated continuation was recorded, but
before it was delivered, stayed deferred. When the continuation run
ended, task release promoted that Retry into a second, sequential run.
Concurrent writers were already impossible on this path, because the
Retry waited behind the continuation. The second run was redundant: the
continuation was the answer to the person's Retry.
**Expected behavior**
An older run's hold does not block new runs indefinitely. The task
continues in an isolated workspace, by itself while the interruption is
recent, or on a person's Retry. Notices say what happened and the one
thing to do. A person's Retry answered by the continuation never starts
another run.
**Steps to reproduce**
1. Leave a hold from an older run whose saved-work recovery gave up,
then start a new run of the task. Before this change, the run is
cancelled at dispatch every time and the hold stays.
2. Open a task whose run was cut off and its retries exhausted. Before
this change, the notice reads "No live execution path … visible for
intervention".
3. On a projectless task with an isolated continuation recorded, press
Retry before delivery, then let the continuation end. Before this
change, a second run follows it.
## What Changed
- Older-run holds (`fresh-continuation-fallback.ts`,
`modules/run-dispatch/adapters/postgres.ts`):
- A run that was cancelled at dispatch (status `cancelled`, never
started, `execution_reconciliation_required`) never ran and follows no
run. The held-run listing and the fallback's successor check now ignore
it.
- The older run's hold goes through the fallback's existing machinery. A
saved-work recovery that is still in progress keeps its bounded wait.
Holds that a person owns stay. Past the bound, the hold is settled and
the task continues in a new isolated workspace. Held files are kept,
recorded as `kept_not_applied`, and never applied.
- One recency rule, `interruptionEligibility` (the #21222 rule), judges
recency by the newest run that the hold refused at dispatch. It no
longer uses the end time of the hold's own run. If the last attempt is
older than 24 hours, no automatic continuation starts. A person's Retry
always continues the task.
- After the dispatch gate refuses a run for another run's hold, it hands
that hold to the fallback in the same transaction. The normal dispatch
path is not changed.
- A person's Retry and the isolated continuation (`heartbeat/queue.ts`,
`execution-recovery-resolution.ts`, new
`fresh-continuation-retry-fold.ts`):
- The wake-admission transaction that inserts an isolated continuation
run (context `freshContinuationIsolation`) also coalesces the person's
waiting `task_retry` wake for that task, under the task row lock. This
applies only to a Retry with no message attached. The wake gets `status:
coalesced` and `runId` set to the continuation. A server stop after the
commit cannot leave the Retry unfolded.
- The delivery pass is idempotent about this. An action whose own
continuation is already queued is no longer hidden from the pass. When
the pass finds that continuation, it marks the action delivered and
folds any Retry that is still waiting.
- Before this change, the fold covered only a Retry that was already
waiting when the continuation was recorded. A Retry that carries a
person's message is not folded. Only a Retry whose source run is the
continuation's own source run is folded, and only while the continuation
is queued or running. A Retry for the continuation's own failure gets
its own run.
- Plain wording (server and UI together):
- "No live execution path" is now "Task could not continue". One seed
(`buildNoRunningExecutionNoticeSeed`) builds it for every producer.
- Exhausted saved-work recovery: "Paperclip could not recover the
agent's saved files … Press Retry to try again".
- The non-retryable continuation notice no longer shows the error code.
Recovery-task comments no longer show `stranded_issue_recovery`, raw IDs
or retry reason codes.
- `legacy-execution-recovery.ts` uses plain text for remote files that
could not be restored.
- `IssueRecoveryActionCard`: "Board decision required" is now "Waiting
for you".
- The UI still recognizes notices saved with the old text
(`adjacent-errors.ts`, `system-notice-humanizer.ts`).
- The precise codes stay in the evidence and in the notice details.
- Merge with current master: `recovery/service.ts` keeps master's
three-way choice (retry exhausted / continuation refused /
non-retryable). The non-retryable branch now uses the plain notice
without the code.
- Code comments that the original commits added are removed
(CONTRIBUTING).
## Verification
Red-to-green tests:
- `server/src/services/fresh-continuation-fallback.test.ts`:
- "continues a task held by an older run's saved-work hold in a new
isolated workspace…"
- "keeps the wait of a saved-work recovery that is still advancing…"
- "keeps a hold a person owns blocking…"
- "leaves an old hold for a person's Retry, and that Retry runs
isolated" (refused run and waiting Retry)
- "continues a recent restart-stopped run whose prepared remote
workspace could not be restored…" (red on the wording)
- "leaves an older restart-stopped remote restore failure for a person's
Retry, which then runs isolated"
- Same file, "consumes a person's Retry exactly once when the server
stops right after admitting the isolated continuation": the test runs
the admission and nothing after it. The Retry is already coalesced. The
test then resets it to unfolded, as an older release would leave it, and
runs the next delivery pass. The result is exactly one run and the Retry
consumed. Red without the in-transaction fold, and red without the
delivery-pass fold.
- Same file, "never folds a Retry for the admitted continuation's own
failure into that ended continuation": the continuation ends (real
`cancelRun`), then the person presses Retry on it. The Retry gets its
own run. Red without the source-run and liveness guard.
- Same file, "runs a person's Retry pressed before delivery as the
recorded isolated continuation, never in the shared directory": a
projectless task, an old legacy writer that may still be alive, and an
isolated continuation pending. Delivery starts exactly one run, which
carries `freshContinuationIsolation` in a `fresh_isolated_workspace`.
Extended here: after the continuation run ends (real `cancelRun` release
path, then `resumeQueuedRuns` and delivery), no run comes from the
person's Retry. The Retry wake stays `coalesced` into the continuation.
Red without the delivery fold (the Retry became a second run), green
with it.
Local runs on this branch (based on master 566843820c, independent of
#21347), one file at a time:
- `fresh-continuation-fallback.test.ts`: 72 passed
- `__tests__/recovery-wake-herd.test.ts` 18,
`__tests__/issue-recovery-actions.test.ts` 112,
`workspace-recovery-fallback.test.ts` 19,
`__tests__/execution-control-work.test.ts` 27, `heartbeat/queue.test.ts`
101: all passed
- `recovery/stranded-notice.test.ts`: 32 passed
- `system-recovery-state.test.ts`: 11 passed
- `workspace-recovery-warm-handoff.test.ts`: 44 passed
- `modules/run-dispatch/adapters/postgres.test.ts`: 88 passed
- `__tests__/legacy-workspace-restore-recovery.test.ts`: 73 passed
- `__tests__/heartbeat-process-recovery.test.ts`: 457 passed
- UI: `IssueRecoveryActionCard.test.tsx` 70,
`task-chat/adjacent-errors.test.ts` 26,
`lib/system-notice-humanizer.test.ts` 10,
`task-chat/TaskChatSystemNotice.test.tsx` 14, all passed
- `server` `pnpm run typecheck` (CI's layered typecheck, including
tests) and `ui` `tsc --noEmit`: clean
Test expectations changed on purpose, because they asserted the old
wording or behavior:
- `stranded-notice.test.ts`: seed title "No live execution path" is now
"Task could not continue". "retried dispatch/continuation" is now "tried
to start/continue this task again". A new test covers the plain wording.
- `system-recovery-state.test.ts`: the exact exhausted text is now
"Paperclip could not recover the agent's saved files. Press Retry to try
again; …". "stopped after 6 attempts" is now "after 6 tries". The
refusal text no longer contains "(allocation_ownership_ambiguous)".
"names the last failure and its cause" is replaced by "keeps the failure
code and cause in the evidence".
- `workspace-recovery-warm-handoff.test.ts`: `/stopped after 6
attempts/` is now `/after 6 tries/`.
- `heartbeat-process-recovery.test.ts`: new wording replaces "bounded
retry budget" / "no live execution path" (x2), "retried continuation"
(x2), "retried dispatch" and "3x attempts". "non-retryable failure" +
"`budget_blocked`" is now "retrying alone would not fix", with no code
in the body. The recovery-task comment lines are now plain.
- UI: humanizer "Task paused - waiting on a recovery owner" is now "Task
could not continue". `IssueRecoveryActionCard` "Board decision required"
is now "Waiting for you".
- `fresh-continuation-fallback.test.ts` "runs a person's Retry pressed
before delivery…": it asserted that the Retry's wake stays
`deferred_issue_execution` after delivery. It now asserts that the wake
is `coalesced` into the continuation run.
## Risks
- An older run's hold is now settled automatically while the
interruption is recent. The continuation always runs in a new isolated
workspace, and the held files are never applied, so the old run's files
cannot be overwritten or reused.
- A person's Retry without a message, pressed while an isolated
continuation waits for delivery, does not start a run of its own. The
continuation is the answer to that Retry. A Retry that carries a message
still runs. Concurrent writers were already impossible on this path (the
Retry waited behind the continuation); this change removes the redundant
second run.
- Wording only changes what a person reads. The UI still recognizes
notices that older releases saved.
- No migration. No schema change.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Claude Code agent with tool use
(shell, file edit, test runs).
## 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
- [ ] I have updated relevant documentation to reflect my changes (no
documented behavior or command 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
- [x] 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>
1267 lines
53 KiB
TypeScript
1267 lines
53 KiB
TypeScript
// @vitest-environment jsdom
|
|
|
|
import { canBoardConfirmOwnerStop } from "../lib/recovery-reconcile";
|
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
|
import { createRoot } from "react-dom/client";
|
|
import { flushSync } from "react-dom";
|
|
import type { AnchorHTMLAttributes, ReactElement } from "react";
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import type { Agent, IssueRecoveryAction } from "@paperclipai/shared";
|
|
import { IssueRecoveryActionCard, NativeControllerContainmentRecovery, deriveRecoveryCardState } from "./IssueRecoveryActionCard";
|
|
|
|
const containmentApi = vi.hoisted(() => ({ resolveRecoveryAction: vi.fn() }));
|
|
vi.mock("../api/issues", () => ({ issuesApi: containmentApi }));
|
|
|
|
vi.mock("@/lib/router", () => ({
|
|
Link: ({ children, to, ...props }: AnchorHTMLAttributes<HTMLAnchorElement> & { to: string }) => (
|
|
<a href={to} {...props}>{children}</a>
|
|
),
|
|
}));
|
|
|
|
const visibility = vi.hoisted(() => ({ visible: true, loaded: true }));
|
|
vi.mock("@/hooks/useWorkspaceIsolationControls", () => ({ useWorkspaceIsolationControls: () => visibility }));
|
|
beforeEach(() => { visibility.visible = true; visibility.loaded = true; });
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
|
|
|
function act<T>(callback: () => T): T {
|
|
let result: T | undefined;
|
|
flushSync(() => {
|
|
result = callback();
|
|
});
|
|
const maybePromise = result as unknown as PromiseLike<unknown>;
|
|
if (result && typeof maybePromise.then === "function") {
|
|
throw new TypeError("This test act shim only supports synchronous callbacks.");
|
|
}
|
|
return result as T;
|
|
}
|
|
|
|
let root: ReturnType<typeof createRoot> | null = null;
|
|
let container: HTMLDivElement | null = null;
|
|
|
|
afterEach(() => {
|
|
if (root) {
|
|
act(() => root?.unmount());
|
|
}
|
|
root = null;
|
|
container?.remove();
|
|
container = null;
|
|
});
|
|
|
|
function render(element: ReactElement) {
|
|
container = document.createElement("div");
|
|
document.body.appendChild(container);
|
|
root = createRoot(container);
|
|
act(() => root?.render(element));
|
|
return container;
|
|
}
|
|
|
|
function click(element: Element | null) {
|
|
if (!element) throw new Error("Expected element to exist");
|
|
act(() => {
|
|
element.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
|
});
|
|
}
|
|
|
|
const ownerAgent: Agent = {
|
|
id: "11111111-1111-1111-1111-111111111111",
|
|
companyId: "company-1",
|
|
name: "ClaudeCoder",
|
|
role: "engineer",
|
|
status: "idle",
|
|
adapterType: "claude_local",
|
|
adapterConfig: {},
|
|
runtimeConfig: {},
|
|
permissions: {},
|
|
urlKey: "claudecoder",
|
|
} as unknown as Agent;
|
|
|
|
const returnAgent: Agent = {
|
|
...ownerAgent,
|
|
id: "22222222-2222-2222-2222-222222222222",
|
|
name: "CodexCoder",
|
|
urlKey: "codexcoder",
|
|
} as Agent;
|
|
|
|
function buildAction(overrides: Partial<IssueRecoveryAction> = {}): IssueRecoveryAction {
|
|
return {
|
|
id: "00000000-0000-0000-0000-0000000000aa",
|
|
companyId: "company-1",
|
|
sourceIssueId: "00000000-0000-0000-0000-0000000000ff",
|
|
recoveryIssueId: null,
|
|
kind: "missing_disposition",
|
|
status: "active",
|
|
ownerType: "agent",
|
|
ownerAgentId: ownerAgent.id,
|
|
ownerUserId: null,
|
|
previousOwnerAgentId: returnAgent.id,
|
|
returnOwnerAgentId: returnAgent.id,
|
|
cause: "missing_disposition",
|
|
fingerprint: "fp",
|
|
evidence: {
|
|
summary: "Run finished but no disposition was chosen.",
|
|
sourceRunId: "7accd7a4-c9ca-4db2-9233-3228a037cc09",
|
|
},
|
|
nextAction: "Choose and record a valid issue disposition.",
|
|
wakePolicy: { type: "wake_owner" },
|
|
monitorPolicy: null,
|
|
attemptCount: 1,
|
|
maxAttempts: 3,
|
|
timeoutAt: null,
|
|
lastAttemptAt: "2026-05-09T19:30:00.000Z",
|
|
outcome: null,
|
|
resolutionNote: null,
|
|
resolvedAt: null,
|
|
createdAt: "2026-05-09T19:30:00.000Z",
|
|
updatedAt: "2026-05-09T19:30:00.000Z",
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
describe("deriveRecoveryCardState", () => {
|
|
it("maps active missing_disposition to needed", () => {
|
|
expect(deriveRecoveryCardState(buildAction())).toBe("needed");
|
|
});
|
|
|
|
it("maps active_run_watchdog to observe_only", () => {
|
|
expect(deriveRecoveryCardState(buildAction({ kind: "active_run_watchdog" }))).toBe("observe_only");
|
|
});
|
|
|
|
it("maps escalated status to escalated", () => {
|
|
expect(deriveRecoveryCardState(buildAction({ status: "escalated" }))).toBe("escalated");
|
|
});
|
|
|
|
it("maps resolved/cancelled to resolved", () => {
|
|
expect(deriveRecoveryCardState(buildAction({ status: "resolved" }))).toBe("resolved");
|
|
expect(deriveRecoveryCardState(buildAction({ status: "cancelled" }))).toBe("resolved");
|
|
});
|
|
});
|
|
|
|
describe("IssueRecoveryActionCard", () => {
|
|
it.each(["running", "scheduled", "missed"] as const)("describes native %s finalization without claiming another agent turn", (state) => {
|
|
const node = render(<IssueRecoveryActionCard action={buildAction({
|
|
kind: "active_run_watchdog", cause: "native_finalization_invalid",
|
|
nextAction: "Finish the existing run.",
|
|
wakePolicy: { kind: "resume_native_run", runId: "native-run", notBefore: state === "scheduled" ? "2099-01-01T00:00:00Z" : "2020-01-01T00:00:00Z" },
|
|
nativeRunActivity: state === "running" ? { runId: "native-run", status: "running", workspaceOperationId: "export-operation" } : null,
|
|
})} />);
|
|
expect(node.querySelector("section")?.getAttribute("data-recovery-state")).toBe(state === "missed" ? "needed" : "in_progress");
|
|
expect(node.textContent).toContain("existing run");
|
|
expect(node.textContent).not.toContain("retrying the original owner");
|
|
expect(node.textContent).not.toContain("retrying itself");
|
|
expect(node.textContent).not.toContain("repairs the next step only");
|
|
expect(node.textContent).not.toContain("stopped to wait");
|
|
expect(node.querySelector('[data-testid="recovery-retry-progress"]')?.getAttribute("data-recovery-lane")).toBe("native_run");
|
|
});
|
|
|
|
it("describes actual export progress after the board retries an exhausted repair", () => {
|
|
const node = render(<IssueRecoveryActionCard action={buildAction({
|
|
kind: "active_run_watchdog", cause: "native_finalization_invalid", ownerType: "board", status: "escalated", attemptCount: 3,
|
|
wakePolicy: { kind: "resume_native_run", runId: "native-run" },
|
|
nativeRunActivity: { runId: "native-run", status: "running", workspaceOperationId: "export-operation" },
|
|
})} />);
|
|
expect(node.querySelector("section")?.getAttribute("data-recovery-state")).toBe("in_progress");
|
|
expect(node.textContent).toContain("Paperclip is recovering the existing run");
|
|
expect(node.querySelector('[data-testid="recovery-recovery-owner"]')?.textContent).toContain("Paperclip");
|
|
expect(node.textContent).not.toContain("Automatic retries are finished");
|
|
});
|
|
|
|
it("renders state and kind attributes with owner names and the recorded next action", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildAction()}
|
|
agentMap={new Map([
|
|
[ownerAgent.id, ownerAgent],
|
|
[returnAgent.id, returnAgent],
|
|
])}
|
|
onResolve={() => {}}
|
|
/>,
|
|
);
|
|
const section = node.querySelector("section[aria-label]");
|
|
expect(section).not.toBeNull();
|
|
expect(section?.getAttribute("data-recovery-state")).toBe("needed");
|
|
expect(section?.getAttribute("data-recovery-kind")).toBe("missing_disposition");
|
|
expect(node.textContent).toContain("RECOVERY NEEDED");
|
|
expect(node.textContent).toContain("Missing Disposition");
|
|
expect(node.textContent).toContain(
|
|
"This task's run finished, but no next step was chosen. Choose what happens next — try the task again, mark it done, or send it for review.",
|
|
);
|
|
expect(node.textContent).toContain("An agent will be asked to choose the next step");
|
|
expect(node.textContent).toContain("ClaudeCoder");
|
|
expect(node.textContent).toContain("CodexCoder");
|
|
expect(node.textContent).toContain("Choose and record a valid issue disposition.");
|
|
});
|
|
|
|
it("renders observe_only tone for active_run_watchdog", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard action={buildAction({ kind: "active_run_watchdog" })} />,
|
|
);
|
|
const section = node.querySelector("section[aria-label]");
|
|
expect(section?.getAttribute("data-recovery-state")).toBe("observe_only");
|
|
expect(node.textContent).toContain("OBSERVING ACTIVE RUN");
|
|
expect(node.textContent).toContain(
|
|
"The active run has been silent. Recovery is observing without interrupting it.",
|
|
);
|
|
});
|
|
|
|
it.each(["active", "escalated", "resolved"] as const)("keeps %s runner recovery in the run log without a card", status => {
|
|
const node = render(<IssueRecoveryActionCard action={buildAction({
|
|
kind: "active_run_watchdog", cause: "uncertain_external_action", status, ownerType: "board",
|
|
})} />);
|
|
expect(node.textContent).toBe("");
|
|
expect(node.querySelector("section")).toBeNull();
|
|
});
|
|
|
|
it.each(["active", "escalated"] as const)(
|
|
"describes a %s board-owned watchdog as a human decision, not a live run",
|
|
(status) => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildAction({
|
|
kind: "active_run_watchdog",
|
|
status,
|
|
ownerType: "board",
|
|
ownerAgentId: null,
|
|
wakePolicy: null,
|
|
})}
|
|
/>,
|
|
);
|
|
expect(node.textContent).toContain(
|
|
"This recovery needs a human decision. Review the recorded failure and choose the next step.",
|
|
);
|
|
expect(node.textContent).not.toContain("The active run has been silent");
|
|
expect(node.textContent).not.toContain("observing without interrupting");
|
|
expect(
|
|
node.querySelector("[data-testid='recovery-action-resolve-trigger']"),
|
|
).toBeNull();
|
|
},
|
|
);
|
|
|
|
it("retains the existing authorized controls for a board-owned watchdog", () => {
|
|
const onResolve = vi.fn();
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildAction({
|
|
kind: "active_run_watchdog",
|
|
ownerType: "board",
|
|
ownerAgentId: null,
|
|
wakePolicy: null,
|
|
})}
|
|
onResolve={onResolve}
|
|
/>,
|
|
);
|
|
click(
|
|
node.querySelector("[data-testid='recovery-action-resolve-trigger']"),
|
|
);
|
|
expect(document.body.textContent).not.toContain("False positive");
|
|
click(
|
|
[...document.body.querySelectorAll("button")].find((button) =>
|
|
button.textContent?.includes("Try again"),
|
|
) ?? null,
|
|
);
|
|
expect(onResolve).toHaveBeenCalledExactlyOnceWith("todo");
|
|
});
|
|
|
|
it("explains issue_graph_liveness in plain language", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildAction({ kind: "issue_graph_liveness", cause: "issue_graph_liveness" })}
|
|
/>,
|
|
);
|
|
expect(node.textContent).toContain("Task Needs Next Step");
|
|
expect(node.textContent).toContain(
|
|
"Paperclip could not find a clear next step for this open task. Choose whether to continue work, send it for review, mark it done, or record what is blocking it.",
|
|
);
|
|
});
|
|
|
|
it("falls back to an em dash when no evidence summary is available", () => {
|
|
const node = render(<IssueRecoveryActionCard action={buildAction({ evidence: {} })} />);
|
|
expect(node.textContent).toContain("—");
|
|
});
|
|
|
|
it("renders workspace_validation with its kind attribute and the recorded next action", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildAction({
|
|
kind: "workspace_validation",
|
|
cause: "workspace_validation_failed",
|
|
nextAction:
|
|
"Repair the source issue workspace link, project workspace cwd, or git checkout before resuming adapter execution.",
|
|
wakePolicy: { type: "manual_repair_required" },
|
|
evidence: {
|
|
recoveryCause: "workspace_validation_failed",
|
|
latestRunErrorCode: "workspace_validation_failed",
|
|
},
|
|
})}
|
|
/>,
|
|
);
|
|
const section = node.querySelector("section[aria-label]");
|
|
expect(section?.getAttribute("data-recovery-kind")).toBe("workspace_validation");
|
|
expect(node.textContent).toContain("Workspace Validation");
|
|
expect(node.textContent).toContain(
|
|
"Paperclip stopped this run because the task's git workspace could not be validated.",
|
|
);
|
|
expect(node.textContent).toContain("Repair the source issue workspace link");
|
|
});
|
|
|
|
it("renders a human evidence summary as prose, not a mono log line", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildAction({
|
|
kind: "stranded_assigned_issue",
|
|
cause: "stranded_assigned_issue",
|
|
evidence: {
|
|
summary: "Unmanaged background task stopped; no durable live path.",
|
|
latestRunStatus: "failed",
|
|
latestRunErrorCode: "unmanaged_background_task_stopped",
|
|
sourceRunId: "7accd7a4-c9ca-4db2-9233-3228a037cc09",
|
|
},
|
|
})}
|
|
/>,
|
|
);
|
|
const summary = Array.from(node.querySelectorAll("span")).find((el) =>
|
|
el.textContent === "Unmanaged background task stopped; no durable live path.",
|
|
);
|
|
expect(summary).toBeTruthy();
|
|
expect(summary?.className).toContain("text-xs");
|
|
expect(summary?.className).not.toContain("font-mono");
|
|
expect(node.textContent).toContain(
|
|
"To get it moving, choose what happens next — try the task again, mark it done, or send it for review.",
|
|
);
|
|
});
|
|
|
|
it("keeps code-shaped evidence (error code, no summary) in the mono treatment", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildAction({
|
|
kind: "workspace_validation",
|
|
cause: "workspace_validation_failed",
|
|
evidence: {
|
|
latestRunErrorCode: "workspace_validation_failed",
|
|
},
|
|
})}
|
|
/>,
|
|
);
|
|
const code = Array.from(node.querySelectorAll("span")).find((el) =>
|
|
el.textContent === "workspace_validation_failed",
|
|
);
|
|
expect(code).toBeTruthy();
|
|
expect(code?.className).toContain("font-mono");
|
|
});
|
|
|
|
it("renders the resolved state and outcome when resolved", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard action={buildAction({ status: "resolved", outcome: "restored", resolvedAt: "2026-05-09T19:35:00.000Z" })} />,
|
|
);
|
|
const section = node.querySelector("section[aria-label]");
|
|
expect(section?.getAttribute("data-recovery-state")).toBe("resolved");
|
|
expect(node.textContent).toContain("RECOVERY RESOLVED");
|
|
expect(node.textContent).toContain("Recovery resolved as restored.");
|
|
expect(node.textContent).toContain("Resolved as restored");
|
|
});
|
|
|
|
it("calls resolve with todo and does not offer delegated recovery", () => {
|
|
const onResolve = vi.fn();
|
|
const node = render(
|
|
<IssueRecoveryActionCard action={buildAction()} onResolve={onResolve} />,
|
|
);
|
|
click(node.querySelector("[data-testid='recovery-action-resolve-trigger']"));
|
|
|
|
expect(document.body.textContent).toContain("Try again");
|
|
expect(document.body.textContent).toContain("Mark task done");
|
|
expect(document.body.textContent).not.toContain("Mark blocked");
|
|
expect(document.body.textContent).not.toContain("Delegate follow-up issue");
|
|
click([...document.body.querySelectorAll("button")].find((button) => button.textContent?.includes("Try again")) ?? null);
|
|
|
|
expect(onResolve).toHaveBeenCalledWith("todo");
|
|
});
|
|
|
|
it("does not offer blocked recovery resolution without a blocker selection flow", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard action={buildAction()} onResolve={() => {}} canFalsePositive />,
|
|
);
|
|
click(node.querySelector("[data-testid='recovery-action-resolve-trigger']"));
|
|
|
|
expect(document.body.textContent).toContain("Try again");
|
|
expect(document.body.textContent).toContain("Mark task done");
|
|
expect(document.body.textContent).toContain("Send for review");
|
|
expect(document.body.textContent).toContain("False positive, done");
|
|
expect(document.body.textContent).toContain("False positive, review");
|
|
expect(document.body.textContent).not.toContain("Mark blocked");
|
|
});
|
|
|
|
it("hides false-positive options unless canFalsePositive is set", () => {
|
|
const first = render(
|
|
<IssueRecoveryActionCard action={buildAction()} onResolve={() => {}} />,
|
|
);
|
|
click(first.querySelector("[data-testid='recovery-action-resolve-trigger']"));
|
|
expect(document.body.textContent).not.toContain("False positive");
|
|
|
|
act(() => root?.unmount());
|
|
root = null;
|
|
container?.remove();
|
|
container = null;
|
|
|
|
const onResolve = vi.fn();
|
|
const second = render(
|
|
<IssueRecoveryActionCard action={buildAction()} onResolve={onResolve} canFalsePositive />,
|
|
);
|
|
click(second.querySelector("[data-testid='recovery-action-resolve-trigger']"));
|
|
expect(document.body.textContent).toContain("False positive, done");
|
|
expect(document.body.textContent).toContain("False positive, review");
|
|
click([...document.body.querySelectorAll("button")].find((button) => button.textContent?.includes("False positive, done")) ?? null);
|
|
expect(onResolve).toHaveBeenCalledWith("false_positive_done");
|
|
});
|
|
});
|
|
|
|
function buildWorkspaceValidationAction(
|
|
overrides: {
|
|
action?: Partial<IssueRecoveryAction>;
|
|
provenance?: Record<string, unknown>;
|
|
workspaceValidation?: Record<string, unknown>;
|
|
} = {},
|
|
): IssueRecoveryAction {
|
|
const provenance = {
|
|
expectedHeadSha: "aaaaaaaaaaaa11112222",
|
|
actualHeadSha: "bbbbbbbbbbbb33334444",
|
|
ancestryVerdict: "diverged",
|
|
plainLanguageReason:
|
|
'The recorded branch "PAP-522-recorded" is not an ancestor of the checked-out branch "nleach/PAP-1405-live", so Paperclip cannot prove a forward-only reconciliation.',
|
|
...overrides.provenance,
|
|
};
|
|
return buildAction({
|
|
kind: "workspace_validation",
|
|
cause: "workspace_validation_failed",
|
|
evidence: {
|
|
workspaceValidation: {
|
|
reason: "git_worktree_branch_incoherence",
|
|
expectedBranch: "PAP-522-recorded",
|
|
actualBranch: "nleach/PAP-1405-live",
|
|
cleanliness: "clean",
|
|
provenance,
|
|
...overrides.workspaceValidation,
|
|
},
|
|
},
|
|
...overrides.action,
|
|
});
|
|
}
|
|
|
|
describe("IssueRecoveryActionCard workspace_validation divergence", () => {
|
|
it("renders the divergence diagnosis with branches, shas, verdict and plain-language reason", () => {
|
|
const node = render(<IssueRecoveryActionCard action={buildWorkspaceValidationAction()} />);
|
|
const diagnosis = node.querySelector("[data-testid='recovery-divergence-diagnosis']");
|
|
expect(diagnosis).not.toBeNull();
|
|
const text = diagnosis?.textContent ?? "";
|
|
expect(text).toContain("Divergence diagnosis");
|
|
expect(text).toContain("Expected · recorded");
|
|
expect(text).toContain("Live · checked out");
|
|
expect(text).toContain("PAP-522-recorded");
|
|
expect(text).toContain("nleach/PAP-1405-live");
|
|
// shortened shas (10 chars)
|
|
expect(text).toContain("aaaaaaaaaa");
|
|
expect(text).toContain("bbbbbbbbbb");
|
|
expect(text).toContain("cannot prove a forward-only reconciliation");
|
|
expect(node.querySelector("[data-testid='recovery-ancestry-verdict']")).not.toBeNull();
|
|
});
|
|
|
|
it("labels each ancestry verdict", () => {
|
|
const diverged = render(<IssueRecoveryActionCard action={buildWorkspaceValidationAction()} />);
|
|
expect(diverged.querySelector("[data-testid='recovery-ancestry-verdict']")?.textContent).toBe("Diverged");
|
|
|
|
const ancestor = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildWorkspaceValidationAction({ provenance: { ancestryVerdict: "ancestor" } })}
|
|
/>,
|
|
);
|
|
expect(ancestor.querySelector("[data-testid='recovery-ancestry-verdict']")?.textContent).toBe("Forward-only");
|
|
|
|
const unknown = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildWorkspaceValidationAction({ provenance: { ancestryVerdict: "unknown" } })}
|
|
/>,
|
|
);
|
|
expect(unknown.querySelector("[data-testid='recovery-ancestry-verdict']")?.textContent).toBe("Ancestry unknown");
|
|
});
|
|
|
|
it("does not render a divergence diagnosis for non-incoherence workspace failures", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildWorkspaceValidationAction({
|
|
workspaceValidation: { reason: "workspace_link_missing", provenance: undefined },
|
|
})}
|
|
/>,
|
|
);
|
|
expect(node.querySelector("[data-testid='recovery-divergence-diagnosis']")).toBeNull();
|
|
});
|
|
|
|
it("hides the isolated re-issue action under operator visibility policy", () => {
|
|
visibility.visible = false;
|
|
const onReissueIsolated = vi.fn();
|
|
const node = render(<IssueRecoveryActionCard action={buildWorkspaceValidationAction()} onReissueIsolated={onReissueIsolated} />);
|
|
expect(node.querySelector("[data-testid='recovery-action-reissue-trigger']")).toBeNull();
|
|
expect(node.querySelector("[data-testid='recovery-divergence-diagnosis']")).not.toBeNull();
|
|
expect(onReissueIsolated).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("offers the re-issue action and passes the live branch as the base ref", () => {
|
|
const onReissueIsolated = vi.fn();
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildWorkspaceValidationAction()}
|
|
onReissueIsolated={onReissueIsolated}
|
|
/>,
|
|
);
|
|
click(node.querySelector("[data-testid='recovery-action-reissue-trigger']"));
|
|
click(document.body.querySelector("[data-testid='recovery-action-reissue-confirm']"));
|
|
expect(onReissueIsolated).toHaveBeenCalledWith({
|
|
baseRef: "nleach/PAP-1405-live",
|
|
liveBranch: "nleach/PAP-1405-live",
|
|
liveHeadSha: "bbbbbbbbbbbb33334444",
|
|
expectedBranch: "PAP-522-recorded",
|
|
});
|
|
});
|
|
|
|
it("falls back to the live HEAD sha as base ref when the branch is detached", () => {
|
|
const onReissueIsolated = vi.fn();
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildWorkspaceValidationAction({ workspaceValidation: { actualBranch: null } })}
|
|
onReissueIsolated={onReissueIsolated}
|
|
/>,
|
|
);
|
|
click(node.querySelector("[data-testid='recovery-action-reissue-trigger']"));
|
|
click(document.body.querySelector("[data-testid='recovery-action-reissue-confirm']"));
|
|
expect(onReissueIsolated).toHaveBeenCalledWith(
|
|
expect.objectContaining({ baseRef: "bbbbbbbbbbbb33334444", liveBranch: null }),
|
|
);
|
|
});
|
|
|
|
it("does not offer the re-issue action for non-workspace kinds", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard action={buildAction()} onReissueIsolated={() => {}} />,
|
|
);
|
|
expect(node.querySelector("[data-testid='recovery-action-reissue-trigger']")).toBeNull();
|
|
});
|
|
|
|
it("disables the re-issue action while a re-issue is pending", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildWorkspaceValidationAction()}
|
|
onReissueIsolated={() => {}}
|
|
reissuePending
|
|
/>,
|
|
);
|
|
const trigger = node.querySelector<HTMLButtonElement>("[data-testid='recovery-action-reissue-trigger']");
|
|
expect(trigger?.disabled).toBe(true);
|
|
});
|
|
});
|
|
|
|
function setTextareaValue(element: HTMLTextAreaElement | null, value: string) {
|
|
if (!element) throw new Error("Expected a textarea to exist");
|
|
const setter = Object.getOwnPropertyDescriptor(
|
|
window.HTMLTextAreaElement.prototype,
|
|
"value",
|
|
)?.set;
|
|
act(() => {
|
|
setter?.call(element, value);
|
|
element.dispatchEvent(new Event("input", { bubbles: true }));
|
|
});
|
|
}
|
|
|
|
describe("IssueRecoveryActionCard W7 reconcile actions", () => {
|
|
it("offers 'Reconcile forward & continue' only for an ancestor verdict and calls the handler", () => {
|
|
const onReconcileForward = vi.fn();
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildWorkspaceValidationAction({ provenance: { ancestryVerdict: "ancestor" } })}
|
|
onReconcileForward={onReconcileForward}
|
|
/>,
|
|
);
|
|
const button = node.querySelector("[data-testid='recovery-action-reconcile-forward']");
|
|
expect(button).not.toBeNull();
|
|
click(button);
|
|
expect(onReconcileForward).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("hides 'Reconcile forward & continue' when the verdict is not an ancestor", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildWorkspaceValidationAction({ provenance: { ancestryVerdict: "diverged" } })}
|
|
onReconcileForward={() => {}}
|
|
/>,
|
|
);
|
|
expect(node.querySelector("[data-testid='recovery-action-reconcile-forward']")).toBeNull();
|
|
});
|
|
|
|
it("disables reconcile-forward while a reconcile is pending", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildWorkspaceValidationAction({ provenance: { ancestryVerdict: "ancestor" } })}
|
|
onReconcileForward={() => {}}
|
|
reconcilePending
|
|
/>,
|
|
);
|
|
const button = node.querySelector<HTMLButtonElement>("[data-testid='recovery-action-reconcile-forward']");
|
|
expect(button?.disabled).toBe(true);
|
|
});
|
|
|
|
it("never renders the break-glass action for a non-permitted operator", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildWorkspaceValidationAction()}
|
|
onBreakGlassOverride={() => {}}
|
|
canBreakGlass={false}
|
|
/>,
|
|
);
|
|
expect(node.querySelector("[data-testid='recovery-action-breakglass-trigger']")).toBeNull();
|
|
});
|
|
|
|
it("break-glass restates the divergence and gates the override behind a required reason", () => {
|
|
const onBreakGlassOverride = vi.fn();
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildWorkspaceValidationAction()}
|
|
onBreakGlassOverride={onBreakGlassOverride}
|
|
canBreakGlass
|
|
/>,
|
|
);
|
|
click(node.querySelector("[data-testid='recovery-action-breakglass-trigger']"));
|
|
|
|
// The confirm step restates the divergence: both branches and both short SHAs.
|
|
const restated = document.body.querySelector("[data-testid='recovery-breakglass-restated-divergence']");
|
|
const restatedText = restated?.textContent ?? "";
|
|
expect(restatedText).toContain("PAP-522-recorded");
|
|
expect(restatedText).toContain("nleach/PAP-1405-live");
|
|
expect(restatedText).toContain("aaaaaaaaaa");
|
|
expect(restatedText).toContain("bbbbbbbbbb");
|
|
|
|
// The override is disabled until a non-empty reason is recorded.
|
|
const confirm = document.body.querySelector<HTMLButtonElement>(
|
|
"[data-testid='recovery-action-breakglass-confirm']",
|
|
);
|
|
expect(confirm?.disabled).toBe(true);
|
|
click(confirm);
|
|
expect(onBreakGlassOverride).not.toHaveBeenCalled();
|
|
|
|
// Whitespace-only reason does not enable it.
|
|
setTextareaValue(
|
|
document.body.querySelector<HTMLTextAreaElement>("[data-testid='recovery-breakglass-reason']"),
|
|
" ",
|
|
);
|
|
expect(
|
|
document.body.querySelector<HTMLButtonElement>("[data-testid='recovery-action-breakglass-confirm']")?.disabled,
|
|
).toBe(true);
|
|
|
|
// A real reason enables the override and is passed (trimmed) to the handler.
|
|
setTextareaValue(
|
|
document.body.querySelector<HTMLTextAreaElement>("[data-testid='recovery-breakglass-reason']"),
|
|
" Verified live branch is safe to adopt. ",
|
|
);
|
|
const enabledConfirm = document.body.querySelector<HTMLButtonElement>(
|
|
"[data-testid='recovery-action-breakglass-confirm']",
|
|
);
|
|
expect(enabledConfirm?.disabled).toBe(false);
|
|
click(enabledConfirm);
|
|
expect(onBreakGlassOverride).toHaveBeenCalledWith("Verified live branch is safe to adopt.");
|
|
});
|
|
|
|
it("does not offer reconcile actions for non-workspace recovery kinds", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildAction()}
|
|
onReconcileForward={() => {}}
|
|
onBreakGlassOverride={() => {}}
|
|
canBreakGlass
|
|
/>,
|
|
);
|
|
expect(node.querySelector("[data-testid='recovery-action-reconcile-forward']")).toBeNull();
|
|
expect(node.querySelector("[data-testid='recovery-action-breakglass-trigger']")).toBeNull();
|
|
});
|
|
});
|
|
|
|
function buildDirtyDivergenceAction(
|
|
overrides: {
|
|
action?: Partial<IssueRecoveryAction>;
|
|
provenance?: Record<string, unknown>;
|
|
workspaceValidation?: Record<string, unknown>;
|
|
} = {},
|
|
): IssueRecoveryAction {
|
|
return buildWorkspaceValidationAction({
|
|
...overrides,
|
|
workspaceValidation: {
|
|
cleanliness: "dirty",
|
|
statusEntryCount: 3,
|
|
dirtyPathSample: ["src/app.ts", "README.md"],
|
|
sourceIdentifier: "PAP-1405",
|
|
...overrides.workspaceValidation,
|
|
},
|
|
});
|
|
}
|
|
|
|
describe("IssueRecoveryActionCard repair workspace (quarantine_restore)", () => {
|
|
it("offers the repair action only for a dirty divergence", () => {
|
|
const cleanNode = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildWorkspaceValidationAction({ workspaceValidation: { cleanliness: "clean" } })}
|
|
onQuarantineRestore={() => {}}
|
|
/>,
|
|
);
|
|
expect(cleanNode.querySelector("[data-testid='recovery-action-repair-trigger']")).toBeNull();
|
|
|
|
const dirtyNode = render(
|
|
<IssueRecoveryActionCard action={buildDirtyDivergenceAction()} onQuarantineRestore={() => {}} />,
|
|
);
|
|
expect(dirtyNode.querySelector("[data-testid='recovery-action-repair-trigger']")).not.toBeNull();
|
|
});
|
|
|
|
it("does not offer the repair action without a handler or for non-workspace kinds", () => {
|
|
const noHandler = render(<IssueRecoveryActionCard action={buildDirtyDivergenceAction()} />);
|
|
expect(noHandler.querySelector("[data-testid='recovery-action-repair-trigger']")).toBeNull();
|
|
|
|
const nonWorkspace = render(
|
|
<IssueRecoveryActionCard action={buildAction()} onQuarantineRestore={() => {}} />,
|
|
);
|
|
expect(nonWorkspace.querySelector("[data-testid='recovery-action-repair-trigger']")).toBeNull();
|
|
});
|
|
|
|
it("confirm popover restates the dirty count, live branch, rescue branch and recorded branch, then fires the handler", () => {
|
|
const onQuarantineRestore = vi.fn();
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildDirtyDivergenceAction()}
|
|
onQuarantineRestore={onQuarantineRestore}
|
|
/>,
|
|
);
|
|
click(node.querySelector("[data-testid='recovery-action-repair-trigger']"));
|
|
const restated = document.body.querySelector("[data-testid='recovery-repair-restated']");
|
|
const text = restated?.textContent ?? "";
|
|
expect(
|
|
document.body.querySelector("[data-testid='recovery-repair-dirty-count']")?.textContent,
|
|
).toBe("3 uncommitted changes");
|
|
// live branch is named in the restated summary, left untouched
|
|
expect(text).toContain("nleach/PAP-1405-live");
|
|
expect(text).toContain("(left untouched)");
|
|
// rescue branch preview mirrors the server naming (prefix + timestamp marker)
|
|
expect(
|
|
document.body.querySelector("[data-testid='recovery-repair-rescue-branch']")?.textContent,
|
|
).toContain("paperclip/rescue/PAP-1405/");
|
|
// recorded branch to be restored
|
|
expect(text).toContain("PAP-522-recorded");
|
|
|
|
// No reason field is present — the operation is lossless.
|
|
expect(document.body.querySelector("textarea")).toBeNull();
|
|
|
|
click(document.body.querySelector("[data-testid='recovery-action-repair-confirm']"));
|
|
expect(onQuarantineRestore).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("singularizes a one-file dirty count", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildDirtyDivergenceAction({ workspaceValidation: { statusEntryCount: 1 } })}
|
|
onQuarantineRestore={() => {}}
|
|
/>,
|
|
);
|
|
click(node.querySelector("[data-testid='recovery-action-repair-trigger']"));
|
|
expect(
|
|
document.body.querySelector("[data-testid='recovery-repair-dirty-count']")?.textContent,
|
|
).toBe("1 uncommitted change");
|
|
});
|
|
|
|
it("disables the repair trigger while a quarantine-restore is pending", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildDirtyDivergenceAction()}
|
|
onQuarantineRestore={() => {}}
|
|
quarantineRestorePending
|
|
/>,
|
|
);
|
|
expect(
|
|
node.querySelector<HTMLButtonElement>("[data-testid='recovery-action-repair-trigger']")?.disabled,
|
|
).toBe(true);
|
|
});
|
|
|
|
it("in the contended case disables repair, explains the claimant, and recommends re-issue", () => {
|
|
const onQuarantineRestore = vi.fn();
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildDirtyDivergenceAction({
|
|
workspaceValidation: {
|
|
contention: {
|
|
claimedByWorkspaceId: "ws-99",
|
|
claimedByIssueId: "issue-99",
|
|
claimedByIssueIdentifier: "PAP-9001",
|
|
activeRun: { id: "run-9001", status: "running", issueId: "issue-99", issueIdentifier: "PAP-9001" },
|
|
},
|
|
},
|
|
})}
|
|
onQuarantineRestore={onQuarantineRestore}
|
|
onReissueIsolated={() => {}}
|
|
/>,
|
|
);
|
|
// Diagnosis gains a claimant line naming the claiming issue.
|
|
const notice = node.querySelector("[data-testid='recovery-contention-notice']");
|
|
expect(notice?.textContent).toContain("Worktree claimed by");
|
|
expect(notice?.textContent).toContain("PAP-9001");
|
|
expect(notice?.textContent).toContain("(active run)");
|
|
|
|
// The repair control is present but disabled, with the claimant as the explanation.
|
|
const disabled = node.querySelector("[data-testid='recovery-action-repair-disabled']");
|
|
expect(disabled).not.toBeNull();
|
|
const trigger = disabled?.querySelector<HTMLButtonElement>(
|
|
"[data-testid='recovery-action-repair-trigger']",
|
|
);
|
|
expect(trigger?.disabled).toBe(true);
|
|
expect(disabled?.textContent).toContain(
|
|
"Held by PAP-9001 — re-issue on an isolated workspace instead.",
|
|
);
|
|
// Clicking the disabled control never fires the repair.
|
|
click(trigger ?? null);
|
|
expect(onQuarantineRestore).not.toHaveBeenCalled();
|
|
|
|
// Re-issue is surfaced as the recommended action.
|
|
expect(node.querySelector("[data-testid='recovery-reissue-recommended']")).not.toBeNull();
|
|
expect(
|
|
node
|
|
.querySelector("[data-testid='recovery-action-reissue-trigger']")
|
|
?.getAttribute("data-recommended"),
|
|
).toBe("true");
|
|
});
|
|
|
|
it("compact variant drops the metadata table but keeps the diagnosis and repair action", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildDirtyDivergenceAction()}
|
|
onQuarantineRestore={() => {}}
|
|
variant="compact"
|
|
/>,
|
|
);
|
|
// Metadata rows (e.g. the Owner/Next action table) are dropped in compact mode.
|
|
expect(node.textContent).not.toContain("Choose and record a valid issue disposition.");
|
|
// The divergence diagnosis and repair action still render.
|
|
expect(node.querySelector("[data-testid='recovery-divergence-diagnosis']")).not.toBeNull();
|
|
expect(node.querySelector("[data-testid='recovery-action-repair-trigger']")).not.toBeNull();
|
|
});
|
|
});
|
|
|
|
describe("IssueRecoveryActionCard owner-sticky retry lineage", () => {
|
|
const NOW = new Date("2026-08-18T12:00:00.000Z");
|
|
|
|
beforeEach(() => {
|
|
vi.useFakeTimers();
|
|
vi.setSystemTime(NOW);
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
function at(offsetMs: number) {
|
|
return new Date(NOW.getTime() + offsetMs).toISOString();
|
|
}
|
|
|
|
const bothAgents = new Map([
|
|
[ownerAgent.id, ownerAgent],
|
|
[returnAgent.id, returnAgent],
|
|
]);
|
|
|
|
/** Phase 1 — the original owner (CodexCoder) is retrying itself. */
|
|
function buildSourceLaneAction(overrides: Partial<IssueRecoveryAction> = {}) {
|
|
return buildAction({
|
|
kind: "deliberate_wait_without_target",
|
|
cause: "deliberate_wait_without_target",
|
|
ownerAgentId: returnAgent.id,
|
|
previousOwnerAgentId: returnAgent.id,
|
|
returnOwnerAgentId: returnAgent.id,
|
|
nextAction:
|
|
"The original owner must replace the parked summary with a terminal, live, blocked, monitored, or typed waiting disposition.",
|
|
wakePolicy: {
|
|
type: "bounded_owner_disposition_repair",
|
|
retryAgentId: returnAgent.id,
|
|
attempt: 2,
|
|
maxAttempts: 5,
|
|
baseBackoffMs: 60_000,
|
|
jitterMs: 3_000,
|
|
retryAt: at(3 * 60_000),
|
|
scheduledRunId: "00000000-0000-0000-0000-0000000000b1",
|
|
},
|
|
attemptCount: 2,
|
|
maxAttempts: 5,
|
|
timeoutAt: at(3 * 60_000),
|
|
...overrides,
|
|
});
|
|
}
|
|
|
|
/** Phase 2 — a manager (ClaudeCoder) repairs the path; CodexCoder keeps the task. */
|
|
function buildRecoveryLaneAction(overrides: Partial<IssueRecoveryAction> = {}) {
|
|
return buildSourceLaneAction({
|
|
ownerAgentId: ownerAgent.id,
|
|
nextAction:
|
|
"Repair the source issue disposition or request an explicit reassignment decision without taking source ownership.",
|
|
evidence: {
|
|
summary: "Run finished but no disposition was chosen.",
|
|
sourceAttemptCount: 5,
|
|
sourceMaxAttempts: 5,
|
|
},
|
|
wakePolicy: {
|
|
type: "bounded_recovery_owner",
|
|
ownerAgentId: ownerAgent.id,
|
|
attempt: 1,
|
|
maxAttempts: 3,
|
|
retryAt: at(60_000),
|
|
scheduledRunId: "00000000-0000-0000-0000-0000000000b2",
|
|
preservesSourceAssignee: true,
|
|
},
|
|
attemptCount: 1,
|
|
maxAttempts: 3,
|
|
timeoutAt: at(60_000),
|
|
...overrides,
|
|
});
|
|
}
|
|
|
|
it("stays quiet and names the retry lane while the original owner is being retried", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard action={buildSourceLaneAction()} agentMap={bothAgents} />,
|
|
);
|
|
const section = node.querySelector("section[aria-label]");
|
|
expect(section?.getAttribute("data-recovery-state")).toBe("in_progress");
|
|
expect(section?.getAttribute("data-recovery-kind")).toBe("deliberate_wait_without_target");
|
|
expect(section?.getAttribute("data-recovery-lane")).toBe("source_owner");
|
|
expect(node.textContent).toContain("RECOVERY IN PROGRESS");
|
|
expect(node.textContent).not.toContain("RECOVERY NEEDED");
|
|
expect(node.textContent).toContain("Wait Without A Target");
|
|
expect(node.textContent).toContain("The task stays with its owner, and no action is needed yet.");
|
|
expect(node.textContent).toContain("Paperclip is retrying the original owner");
|
|
});
|
|
|
|
it("shows the five-attempt budget and the next due time", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard action={buildSourceLaneAction()} agentMap={bothAgents} />,
|
|
);
|
|
const progress = node.querySelector("[data-testid='recovery-retry-progress']");
|
|
expect(progress).not.toBeNull();
|
|
expect(progress?.getAttribute("data-recovery-lane")).toBe("source_owner");
|
|
expect(progress?.getAttribute("data-recovery-attempt")).toBe("2");
|
|
expect(progress?.getAttribute("data-recovery-max-attempts")).toBe("5");
|
|
expect(progress?.textContent).toContain("Attempt 2 of 5");
|
|
expect(node.querySelector("[data-testid='recovery-next-retry']")?.textContent).toBe(
|
|
"Next try in 3m",
|
|
);
|
|
});
|
|
|
|
it("keeps the source owner and the recovery owner as separate roles", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard action={buildRecoveryLaneAction()} agentMap={bothAgents} />,
|
|
);
|
|
const sourceOwner = node.querySelector("[data-testid='recovery-source-owner']");
|
|
const recoveryOwner = node.querySelector("[data-testid='recovery-recovery-owner']");
|
|
// CodexCoder is the original owner and keeps the deliverable.
|
|
expect(sourceOwner?.textContent).toContain("CodexCoder");
|
|
expect(sourceOwner?.textContent).toContain("keeps this task");
|
|
// ClaudeCoder only repairs the path.
|
|
expect(recoveryOwner?.textContent).toContain("ClaudeCoder");
|
|
expect(recoveryOwner?.textContent).toContain("repairs the next step only");
|
|
expect(recoveryOwner?.textContent).not.toContain("CodexCoder");
|
|
expect(node.textContent).toContain(
|
|
"the task itself still belongs to its original owner",
|
|
);
|
|
});
|
|
|
|
it("labels the source lane as the owner retrying itself", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard action={buildSourceLaneAction()} agentMap={bothAgents} />,
|
|
);
|
|
expect(
|
|
node.querySelector("[data-testid='recovery-recovery-owner']")?.textContent,
|
|
).toContain("Original owner — retrying itself");
|
|
});
|
|
|
|
it("reports the spent source attempts once the manager lane opens", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard action={buildRecoveryLaneAction()} agentMap={bothAgents} />,
|
|
);
|
|
const section = node.querySelector("section[aria-label]");
|
|
expect(section?.getAttribute("data-recovery-lane")).toBe("recovery_owner");
|
|
expect(section?.getAttribute("data-recovery-state")).toBe("in_progress");
|
|
expect(
|
|
node.querySelector("[data-testid='recovery-source-attempts']")?.textContent,
|
|
).toContain("The original owner used 5 of 5 automatic attempts.");
|
|
expect(
|
|
node.querySelector("[data-testid='recovery-retry-progress']")?.textContent,
|
|
).toContain("Attempt 1 of 3");
|
|
});
|
|
|
|
it("warns strongly only once the automatic path is exhausted", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildSourceLaneAction({
|
|
wakePolicy: {
|
|
type: "bounded_owner_disposition_repair",
|
|
retryAgentId: returnAgent.id,
|
|
attempt: 5,
|
|
maxAttempts: 5,
|
|
retryAt: at(-60_000),
|
|
},
|
|
attemptCount: 5,
|
|
})}
|
|
agentMap={bothAgents}
|
|
/>,
|
|
);
|
|
const section = node.querySelector("section[aria-label]");
|
|
expect(section?.getAttribute("data-recovery-state")).toBe("needed");
|
|
expect(node.textContent).toContain("RECOVERY NEEDED");
|
|
expect(node.textContent).toContain("has used every automatic repair attempt");
|
|
expect(node.querySelector("[data-testid='recovery-next-retry']")?.textContent).toBe(
|
|
"Automatic retries used up",
|
|
);
|
|
// The follow-up line must not keep promising a retry that will never run, and the
|
|
// generic timeout chip must not reintroduce a stale due time next to it.
|
|
expect(node.textContent).toContain("Automatic retries are finished — a decision is needed");
|
|
expect(node.textContent).not.toContain("Paperclip is retrying the original owner");
|
|
expect(node.textContent).not.toContain("Times out");
|
|
});
|
|
|
|
it("warns strongly when the stored retry came due and never ran", () => {
|
|
// PAP-17561: this exact shape rendered "Recovery in progress · Attempt 1 of 5 · Next try
|
|
// 5m ago" — a calm card over a lane nothing was working on.
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildSourceLaneAction({
|
|
wakePolicy: {
|
|
type: "bounded_owner_disposition_repair",
|
|
retryAgentId: returnAgent.id,
|
|
attempt: 1,
|
|
maxAttempts: 5,
|
|
retryAt: at(-5 * 60_000),
|
|
scheduledRunId: "00000000-0000-0000-0000-0000000000b2",
|
|
},
|
|
attemptCount: 1,
|
|
timeoutAt: at(-5 * 60_000),
|
|
})}
|
|
agentMap={bothAgents}
|
|
/>,
|
|
);
|
|
const section = node.querySelector("section[aria-label]");
|
|
expect(section?.getAttribute("data-recovery-state")).toBe("needed");
|
|
expect(node.textContent).toContain("RECOVERY NEEDED");
|
|
expect(node.textContent).not.toContain("RECOVERY IN PROGRESS");
|
|
const retry = node.querySelector("[data-testid='recovery-next-retry']");
|
|
expect(retry?.textContent).toBe("Retry missed 5m ago");
|
|
expect(retry?.getAttribute("data-recovery-retry-expired")).toBe("true");
|
|
// Nothing may still read as an upcoming attempt or as needing no action.
|
|
expect(node.textContent).not.toContain("Next try");
|
|
expect(node.textContent).not.toContain("no action is needed yet");
|
|
expect(node.textContent).toContain("came due and did not run");
|
|
expect(node.textContent).toContain("The scheduled retry did not run");
|
|
// The repair lane still must not move the deliverable off its original owner.
|
|
expect(node.querySelector("[data-testid='recovery-source-owner']")?.textContent).toContain(
|
|
"keeps this task",
|
|
);
|
|
});
|
|
|
|
it("stays quiet when the overdue attempt is a verified live run", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildSourceLaneAction({
|
|
wakePolicy: {
|
|
type: "bounded_owner_disposition_repair",
|
|
retryAgentId: returnAgent.id,
|
|
attempt: 2,
|
|
maxAttempts: 5,
|
|
retryAt: at(-5 * 60_000),
|
|
scheduledRunId: "00000000-0000-0000-0000-0000000000b2",
|
|
},
|
|
timeoutAt: at(-5 * 60_000),
|
|
})}
|
|
agentMap={bothAgents}
|
|
scheduledRetry={{
|
|
runId: "00000000-0000-0000-0000-0000000000b2",
|
|
status: "running",
|
|
agentId: returnAgent.id,
|
|
agentName: returnAgent.name,
|
|
retryOfRunId: null,
|
|
scheduledRetryAt: at(-5 * 60_000),
|
|
scheduledRetryAttempt: 2,
|
|
scheduledRetryReason: null,
|
|
}}
|
|
/>,
|
|
);
|
|
const section = node.querySelector("section[aria-label]");
|
|
expect(section?.getAttribute("data-recovery-state")).toBe("in_progress");
|
|
expect(node.querySelector("[data-testid='recovery-next-retry']")?.textContent).toBe(
|
|
"Attempt running now",
|
|
);
|
|
expect(node.textContent).not.toContain("Retry missed");
|
|
});
|
|
|
|
it("keeps timing in the retry-progress row only while a lane is live", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard action={buildSourceLaneAction()} agentMap={bothAgents} />,
|
|
);
|
|
expect(node.textContent).toContain("Paperclip is retrying the original owner");
|
|
expect(node.textContent).not.toContain("Times out");
|
|
});
|
|
|
|
it("shows a current-policy board recovery action without implying the board owns the task", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard
|
|
action={buildSourceLaneAction({
|
|
status: "active",
|
|
ownerType: "board",
|
|
ownerAgentId: null,
|
|
evidence: {
|
|
sourceAttemptCount: 5,
|
|
sourceMaxAttempts: 5,
|
|
routingPolicy: "board_escalation_no_takeover_v1",
|
|
},
|
|
wakePolicy: {
|
|
type: "board_escalation",
|
|
reason: "unchanged_source_state_exhausted",
|
|
preservesSourceAssignee: true,
|
|
},
|
|
attemptCount: 5,
|
|
maxAttempts: null,
|
|
timeoutAt: null,
|
|
})}
|
|
agentMap={bothAgents}
|
|
/>,
|
|
);
|
|
const section = node.querySelector("section[aria-label]");
|
|
expect(section?.getAttribute("data-recovery-state")).toBe("needed");
|
|
expect(section?.getAttribute("data-recovery-lane")).toBe("board");
|
|
expect(node.textContent).toContain("Automatic recovery is exhausted");
|
|
expect(node.textContent).toContain("Waiting for you");
|
|
expect(node.textContent).not.toContain("Board decision required");
|
|
const recoveryOwner = node.querySelector("[data-testid='recovery-recovery-owner']");
|
|
expect(recoveryOwner?.textContent).toContain("Board");
|
|
expect(recoveryOwner?.textContent).toContain("decides the next step only");
|
|
expect(
|
|
node.querySelector("[data-testid='recovery-source-owner']")?.textContent,
|
|
).toContain("CodexCoder");
|
|
});
|
|
|
|
it("leaves kinds without a bounded lineage on the original single owner row", () => {
|
|
const node = render(
|
|
<IssueRecoveryActionCard action={buildAction()} agentMap={bothAgents} />,
|
|
);
|
|
expect(node.querySelector("section[aria-label]")?.getAttribute("data-recovery-lane")).toBeNull();
|
|
expect(node.querySelector("[data-testid='recovery-retry-progress']")).toBeNull();
|
|
expect(node.querySelector("[data-testid='recovery-source-owner']")).toBeNull();
|
|
expect(node.textContent).toContain("→ Returns to:");
|
|
});
|
|
});
|
|
|
|
it.each(["active", "escalated", "resolved"] as const)("does not show a historical unsafe-export repair card: %s", status => {
|
|
const node = render(<IssueRecoveryActionCard action={buildAction({ status, kind: "active_run_watchdog",
|
|
cause: "native_workspace_sync_out_unsafe_archive", ownerType: "board", nextAction: "Repair the unsafe link manually" })} onResolve={() => {}} />);
|
|
expect(node.textContent).toBe("");
|
|
});
|
|
|
|
it("requires export retry for ordinary restoration while keeping explicit board overrides", () => {
|
|
const node = render(<IssueRecoveryActionCard action={buildAction({ kind: "active_run_watchdog", ownerType: "board",
|
|
cause: "native_workspace_sync_out_retry_exhausted" })} onResolve={() => {}} canFalsePositive />);
|
|
click(node.querySelector("[data-testid='recovery-action-resolve-trigger']"));
|
|
expect(document.body.textContent).not.toContain("Try again");
|
|
expect(document.body.textContent).not.toContain("Mark task done");
|
|
expect(document.body.textContent).not.toContain("Send for review");
|
|
expect(document.body.textContent).toContain("False positive, done");
|
|
});
|
|
|
|
it("requires owner-stop recovery even for board false-positive dispositions", () => {
|
|
const node = render(<IssueRecoveryActionCard action={buildAction({ kind: "active_run_watchdog", ownerType: "board",
|
|
cause: "native_workspace_finalization_owner_unverified" })} onResolve={() => {}} canFalsePositive />);
|
|
expect(node.querySelector("[data-testid='recovery-action-resolve-trigger']")).toBeNull();
|
|
expect(node.textContent).not.toContain("False positive");
|
|
});
|
|
|
|
|
|
describe("original-host controller containment in task recovery", () => {
|
|
let client: QueryClient;
|
|
const digest = "a".repeat(64);
|
|
const runId = "00000000-0000-4000-8000-000000000041";
|
|
const onRecorded = vi.fn();
|
|
beforeEach(() => {
|
|
client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
|
|
containmentApi.resolveRecoveryAction.mockReset().mockResolvedValue({});
|
|
onRecorded.mockReset();
|
|
});
|
|
afterEach(() => client.clear());
|
|
function mount(canManage = true, reason = "controller_process_space_unverified", authority = digest) {
|
|
const action = buildAction({ kind: "active_run_watchdog", ownerType: "board", cause: "native_restart_recovery_blocked",
|
|
evidence: { runId, reason, controllerAuthority: { schema: "paperclip.native-controller-authority.v1", digest: authority } } });
|
|
const issue = { id: "ordinary-task", status: "in_progress" as const, activeRecoveryAction: action };
|
|
const element = <QueryClientProvider client={client}><NativeControllerContainmentRecovery key={authority} issue={issue}
|
|
canManage={canManage} onRecorded={onRecorded} /></QueryClientProvider>;
|
|
if (!root) return render(element);
|
|
act(() => root?.render(element));
|
|
return container!;
|
|
}
|
|
function fillFields(node: HTMLDivElement) {
|
|
act(() => {
|
|
const area = node.querySelector("textarea")!;
|
|
Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(area,
|
|
"Verified the original deployment controller and provider stopped; completed actions were reviewed.");
|
|
area.dispatchEvent(new Event("input", { bubbles: true }));
|
|
const select = node.querySelector("select")!;
|
|
select.value = "mixed";
|
|
select.dispatchEvent(new Event("change", { bubbles: true }));
|
|
});
|
|
}
|
|
function recordButton(node: HTMLDivElement) {
|
|
return Array.from(node.querySelectorAll("button")).find(button => button.textContent === "Record containment")!;
|
|
}
|
|
it("requires separate controller and provider confirmations on an ordinary task", async () => {
|
|
const node = mount();
|
|
expect(node.textContent).toContain("original host");
|
|
expect(node.textContent).toContain("does not retry");
|
|
expect(node.textContent).not.toContain(digest);
|
|
fillFields(node);
|
|
const boxes = node.querySelectorAll('[role="checkbox"]');
|
|
expect(recordButton(node).disabled).toBe(true);
|
|
click(boxes[0]);
|
|
expect(recordButton(node).disabled).toBe(true);
|
|
click(boxes[1]);
|
|
expect(recordButton(node).disabled).toBe(false);
|
|
click(recordButton(node));
|
|
await new Promise(resolve => setTimeout(resolve, 0));
|
|
expect(containmentApi.resolveRecoveryAction).toHaveBeenCalledOnce();
|
|
expect(containmentApi.resolveRecoveryAction).toHaveBeenCalledWith("ordinary-task", expect.objectContaining({
|
|
outcome: "restored", sourceIssueStatus: "in_progress", executionReconciliation: {
|
|
runId, controllerStopped: true, providerStopped: true, controllerAuthorityDigest: digest,
|
|
actionOutcome: "mixed", outcomeEvidence: "Verified the original deployment controller and provider stopped; completed actions were reviewed.",
|
|
},
|
|
}));
|
|
});
|
|
it("does not expose a confirmation form to non-board runtime managers", () => {
|
|
const node = mount(false);
|
|
expect(node.querySelector("button")).toBeNull();
|
|
expect(node.textContent).toContain("company owner");
|
|
expect(containmentApi.resolveRecoveryAction).not.toHaveBeenCalled();
|
|
});
|
|
it.each(["owner", "admin", "operator", "viewer"] as const)("shows the containment form only for a board %s with owner-stop authority", role => {
|
|
const allowed = canBoardConfirmOwnerStop("company", { source: "session", user: null, userId: "board-user", keyId: null, companyIds: ["company"], isInstanceAdmin: false,
|
|
memberships: [{ companyId: "company", status: "active", membershipRole: role }] });
|
|
const node = mount(allowed);
|
|
expect(node.querySelectorAll('[role="checkbox"]').length).toBe(role === "owner" || role === "admin" ? 2 : 0);
|
|
expect(Boolean(node.querySelector("button"))).toBe(role === "owner" || role === "admin");
|
|
expect(containmentApi.resolveRecoveryAction).not.toHaveBeenCalled();
|
|
});
|
|
it("does not offer local containment for remote or unrelated recovery", () => {
|
|
const node = mount(true, "remote_controller_process_space_unverified");
|
|
expect(node.querySelector("section")).toBeNull();
|
|
mount(true, "some_other_hold");
|
|
expect(node.querySelector("section")).toBeNull();
|
|
});
|
|
it("clears old confirmations when the server supplies a different authority snapshot", () => {
|
|
const node = mount();
|
|
fillFields(node);
|
|
for (const box of node.querySelectorAll('[role="checkbox"]')) click(box);
|
|
expect(recordButton(node).disabled).toBe(false);
|
|
mount(true, "controller_process_space_unverified", "b".repeat(64));
|
|
expect(recordButton(node).disabled).toBe(true);
|
|
expect(node.querySelector("textarea")?.value).toBe("");
|
|
expect(containmentApi.resolveRecoveryAction).not.toHaveBeenCalled();
|
|
});
|
|
});
|