Files
PaperClipAI/server/src/services/recovery/stranded-notice.test.ts
DottaandClaude Opus 5.5 6b9e45787f fix(recovery): continue a task whose system retry was refused at claim behind a saved-work hold (#21505)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - When a run stops before it finishes, automatic recovery continues
the task, through the fresh-continuation fallback, in a new run that
starts from the saved work
> - A follow-up run (for example one started by a new comment or by
finished subtasks) can fail before any provider work and leave a
saved-work hold. The system then queues its own retry, and the dispatch
gate cancels that retry at claim with
`execution_reconciliation_required` because the hold is still in place
> - The fallback takes over the hold when that happens, but it continued
only "recent interruptions". That test required the failed run to be a
recovery run itself or to fail with a restart code. A first follow-up
run that failed with `adapter_failed` passed neither test, even though
the system had already decided to retry it. So the fallback answered "a
person must press Retry". The backlog pass used the same test, and the
assigned-work sweep never listed the task. The task stayed blocked with
no run, no pending path and no Retry button
> - This pull request treats a system retry refused at dispatch as proof
that the system continues the task. It also stops cancelled-at-dispatch
attempts from counting against the hourly budget, lets the sweep
continue a blocked task whose latest run was refused at dispatch, and
keeps recovery notices from asking for a Retry that the task does not
offer
> - The benefit is that such a task continues by itself in exactly one
fresh run from the saved work, whether the saved work was recovered
before or after the refusal, and a person's own failed Retry keeps
today's behaviour

## Linked Issues or Issue Description

Refs #21394, #21348, #21363, #21478

**What happened?**
A task's follow-up run, a legacy run that was not a recovery run, failed
before any provider work with `adapter_failed`. Its files could not be
restored, so it left a saved-work hold
(`legacy_execution_requires_reconciliation`, `workspaceRestoreFailure:
restore_failed`). The system queued a retry of that run. The dispatch
gate cancelled the retry at claim with
`execution_reconciliation_required`, and the "older run hold" path
handed the hold to the fresh-continuation fallback
(`run-dispatch/adapters/postgres.ts` `settleOlderRunHold`). The fallback
found the refused run and asked `interruptionEligibility` whether the
interruption was recent. That predicate required
`continuesAutomaticallySql(source)` (a recovery run, or a restart,
deploy or bootstrap code), so it returned `person_owned` /
`retry_needed`. The stranded reconciler then blocked the task with
"Press Retry", but the saved-work hold reports that Retry is not
available. This happened twice in a local restart-chaos wave. In one
case the saved work was recovered two minutes before the claim. In the
other it was recovered thirty seconds after the claim.

**Expected behavior**
A task never rests blocked with no live run, no pending path and no
Retry. While the saved-work recovery runs, that recovery is the pending
path. When it finishes, one continuation starts from the saved work
through the fallback (isolation, the shared hourly cap). A run that was
cancelled at dispatch before it started does not use up the automatic
budget. A person's own failed Retry is still left for that person.

**Steps to reproduce**
1. Fail a follow-up run (wake reason `issue_children_completed`) before
provider work with `adapter_failed` and `workspaceRestoreFailure:
restore_failed`.
2. Queue the system's retry of that run (`retryOfRunId`, wake reason
`issue_continuation_needed`) and claim it. The dispatch gate cancels it
with `execution_reconciliation_required`.
3. Before this change, no continuation is recorded, the stranded
reconciler blocks the task, and nothing ever continues it.

**Paperclip version or commit**
master at 2756be2f32

## What Changed

- `fresh-continuation-fallback.ts`, `interruptionEligibility`: the
interruption counts as one the system continues when the failed run's
cause is system-owned and a later run that the dispatch gate refused
before it started is a system recovery run (`recoveryRunSql`, which
excludes a person's Retry). A failed run that was itself a person's
Retry (`task_retry` or `explicitUserContinuation`) never qualifies this
way. The 24-hour recency bound is unchanged. The claim-gate hand-off,
the backlog pass and its deadline query all use this one predicate.
- `recovery/continuation-ledger.ts`,
`recovery/task-automatic-attempts.ts`: one shared rule,
`startedOrPendingAutomaticRetry`. An automatic retry that the dispatch
gate cancelled before it started (`cancelled`, no `startedAt`,
`execution_reconciliation_required`) does not count toward the hourly
cap in either ledger.
- `recovery/assigned-work-sweep.ts`:
- When the latest run was refused at dispatch, the sweep continues from
the run it was refused for through the fallback. Before, it gave up.
- A blocked task with an active hold and a recent refused-at-dispatch
latest run is now listed as a suspect. The check hands it to the
fallback before it answers `left_to_hold_owner`. A pending recovery
becomes `waiting_on_recovery` with its recheck time.
- Holds that wait for a person's configuration or confirmation are still
excluded.
- Review follow-up (`recovery/task-automatic-attempts.ts`,
`recovery/assigned-work-sweep.ts`):
- The task ledger counts a sweep's fresh-continuation record (`trigger:
assigned_work`) itself. It no longer depends on a companion activity
entry, and an activity entry marked `continuedFromSavedWork` is not
counted a second time. Every sweep continuation counts once, whatever
path recorded it.
- When the sweep claims a continuation, it marks its claim entry
`continuedFromSavedWork` inside the transaction that records the fresh
continuation. A restart between the two writes can no longer leave one
attempt counted twice.
- The sweep's continuation behind a refused run spends the per-minute
repair budget (`ASSIGNED_WORK_REPAIRS_PER_MINUTE`). The excess is
deferred with a `retryAt`.
- `recovery/stranded-notice.ts`, `recovery/service.ts`: when the task's
execution blocker offers no Retry, the escalation notice and the
recovery action's next action leave out every Retry instruction. They
say that Paperclip is holding the task until its saved work is settled.
- No change to the dispatch gate (`heartbeat/queue.ts`, the restore-hold
predicate in `run-dispatch/adapters/postgres.ts`, or
`execution-blocker.ts`). The recorded continuation settles the hold, so
the delivered run is not refused again.

## Verification

Red before the change, green after (embedded Postgres, real services:
`terminalizeLegacyExecution`, the dispatch adapter's
`cancelStaleQueuedRun`, `reconcileStrandedAssignedIssues`,
`deliverReconciledExecutions`, `continueHeldExecutions`,
`recoveryService().assignedWork`):
- `server/src/services/fresh-continuation-fallback.test.ts`
- "continues a follow-up … when the saved work was recovered before the
system retry was refused at claim": red (`continuationDelivery:
"invalidated"`, no continuation). Green: the continuation is recorded at
the claim, and the stranded reconciler does not block the task. The
delivered run is queued and passes the claim gate (`not_stale`).
- "… recovered after the system retry was refused at claim": red (no
pending check). Green: the claim records `exact_recovery_pending` /
`saved_work_recovery_running`. When the recovery completes, the backlog
pass continues the task, and the delivered run passes the claim gate.
- "continues a follow-up … with its files in place, after its system
retry was refused at claim": red, then green. This is the control
without a restore failure.
- "still leaves a person's failed Retry of a follow-up for that person
…": stays `person_owned` / `retry_needed`, before and after.
- "counts only automatic retries that started, or still may, against the
task's hourly budget": new.
- `server/src/__tests__/failed-continuation-continues-again.test.ts`,
"the sweep continues a blocked task whose system retry was refused at
claim behind a recovered saved-work hold": red (the task was not a
suspect). Green: `repaired`, a pending continuation in the hold, the
task back in `todo`, and no wake enqueued. The next check reports a
pending intent.
- Same file, "a continuation the sweep records behind a refused run
counts once toward the task's hourly cap": red (5 counted after 5
attempts plus the new continuation), green (6, and the transient-retry
cap check refuses the next attempt).
- Same file, "continuations behind refused runs spend the sweep's
per-minute repair budget": 20 tasks. Red (20 continued in one pass),
green (10 continue, 10 are deferred with a `retryAt`, and the 10
continue in the next pass).
- Same file, "a sweep continuation interrupted right after it was
recorded still counts once": the continuation commits, then the
post-commit activity write fails (a simulated server stop). Red: 6
counted for 5 real attempts. Green: 5 counted, and the next automatic
retry is still allowed.
- `server/src/services/recovery/stranded-notice.test.ts`, "never tells a
person to press Retry when the task offers no Retry": new.

Local runs on this branch, one file at a time:
- `fresh-continuation-fallback.test.ts`: 77 passed. The suite's
`afterAll` teardown hit the 30 s hook timeout on a heavily loaded
machine.
- `failed-continuation-continues-again.test.ts`: 32 passed
- `assigned-work-invariant.test.ts`: 31 passed
- `stranded-notice.test.ts`: 33 passed
- CI on the first head (ce4431410b): every required check passed
- `server` `tsc --noEmit`: clean
- `pnpm verify --explain` selects most of the repository (2666 files),
so required CI supplies the broad coverage.

## Risks

- More tasks continue automatically. Each continuation goes through the
existing fallback. The 24-hour recency bound, the per-task hourly cap
(6), isolation of the next run, and every person-owned gate
(person-owned failure codes, a person's Stop, review, a person-owned
hold, a person's failed Retry) are unchanged.
- The hourly cap now ignores automatic retries that never started. A
task whose retries are refused at dispatch again and again is still
bounded: the refusal hands the hold to the fallback, and the fallback
records one continuation per source run.
- Known separate gap, not changed here: after an interrupted
preparation's holds are resolved (`settleInterruptedNativeBootstrap`),
`scheduleBoundedRetry` can report `exhausted` or `blocked`, and nothing
follows that up. The assigned-work sweep may now pick such a task up
through the refused-at-dispatch path, but this pull request does not
prove that.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with
tool use (shell, file edits, local 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
- [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-13 22:01:39 -06:00

417 lines
19 KiB
TypeScript
Raw Permalink 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 { noticeMetadataReferencesRecoveryAction } from "./successful-run-handoff.js";
import { ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE } from "../environment-provider-unavailable-error.js";
import {
DEFAULT_STRANDED_RECOVERY_NOTICE_BODY,
buildConfigurationIncompleteRecoveryNoticeSeed,
buildExecutionReviewParticipantRecoveryNoticeSeed,
buildExecutionReviewParticipantUnavailableNoticeSeed,
buildImmediateExecutionPathRecoveryNoticeSeed,
buildNoRunningExecutionNoticeSeed,
buildStrandedRecoveryEscalationNotice,
buildWorkspaceValidationRecoveryNoticeSeed,
} from "./stranded-notice.js";
function allRows(metadata: { sections: Array<{ rows: unknown[] }> }) {
return metadata.sections.flatMap((section) => section.rows) as Array<Record<string, unknown>>;
}
describe("stranded recovery notice seeds", () => {
it("says what happened and the one thing to do, with no internal words (the UI recognizes this wording)", () => {
for (const seed of [buildImmediateExecutionPathRecoveryNoticeSeed({ status: "todo" }),
buildNoRunningExecutionNoticeSeed({ status: "in_progress", attempts: 3 })]) {
expect(seed.body).toMatch(/^Paperclip tried to (start|continue) this task again, but it still could not (start|continue)\b/);
expect(seed.body).toContain("Press Retry");
expect(seed.body).not.toMatch(/execution path|intervention|`blocked`|`todo`|`in_progress`|issue|board operator|inspect|repair/i);
}
expect(buildNoRunningExecutionNoticeSeed({ status: "in_progress", attempts: 3 }).body).toContain("after 3 tries");
});
it.each([
["todo dispatch", buildImmediateExecutionPathRecoveryNoticeSeed({ status: "todo" }), "Task could not continue"],
["in_progress continuation", buildImmediateExecutionPathRecoveryNoticeSeed({ status: "in_progress" }), "Task could not continue"],
["workspace validation", buildWorkspaceValidationRecoveryNoticeSeed(), "Workspace validation failed"],
["configuration incomplete", buildConfigurationIncompleteRecoveryNoticeSeed(), "Configuration incomplete"],
["review participant recovery", buildExecutionReviewParticipantRecoveryNoticeSeed(), "Review recovery stalled"],
["review participant unavailable", buildExecutionReviewParticipantUnavailableNoticeSeed(), "Review recovery stalled"],
])("%s seed has a short body plus title and tone", (_label, seed, expectedTitle) => {
expect(seed.title).toBe(expectedTitle);
expect(seed.tone).toBe("danger");
expect(seed.body.length).toBeGreaterThan(0);
// Failure details now live in metadata rows, never inline in the body.
expect(seed.body).not.toContain("Latest retry failure");
expect(seed.body).not.toContain("Recovery action:");
});
it("names the sandbox provider plugin and its status when that is the configuration gap", () => {
const seed = buildConfigurationIncompleteRecoveryNoticeSeed({
reason: "sandbox_provider_plugin_not_ready",
pluginKey: "paperclip.kubernetes-sandbox-provider",
pluginStatus: "error",
});
expect(seed.title).toBe("Configuration incomplete");
expect(seed.tone).toBe("danger");
expect(seed.body).toContain("`paperclip.kubernetes-sandbox-provider`");
expect(seed.body).toContain("`error`");
expect(seed.body).toContain("enable the plugin");
expect(seed.body).not.toContain("secret/env bindings");
});
it("asks for a capability review before enabling an upgrade_pending plugin, and names an operator disable", () => {
const upgrade = buildConfigurationIncompleteRecoveryNoticeSeed({
reason: "sandbox_provider_plugin_not_ready",
pluginKey: "paperclip.daytona-sandbox-provider",
pluginStatus: "upgrade_pending",
});
expect(upgrade.body).toContain("review and approve the upgraded plugin's capabilities");
const disabled = buildConfigurationIncompleteRecoveryNoticeSeed({
reason: "sandbox_provider_plugin_not_ready",
pluginKey: "paperclip.daytona-sandbox-provider",
pluginStatus: "disabled",
});
expect(disabled.body).toContain("an operator disabled it");
});
it("explains unsupported concurrent shared workspace placement instead of missing secrets", () => {
const seed = buildConfigurationIncompleteRecoveryNoticeSeed({ reason: "shared_realization_unsupported" });
expect(seed.title).toBe("Shared workspace unavailable");
expect(seed.body).toContain("cannot place concurrent agents in one physical shared folder");
expect(seed.body).not.toContain("secret/env bindings");
expect(seed.nextAction).toContain("isolated task workspace");
});
it("explains a quiet holder that still owns the shared workspace", () => {
const seed = buildConfigurationIncompleteRecoveryNoticeSeed({ reason: "shared_realization_unsupported", holderStale: true });
expect(seed.title).toBe("Shared workspace still held");
expect(seed.body).toContain("no output for more than an hour");
expect(seed.body).not.toContain("secret/env bindings");
expect(seed.nextAction).toContain("Stop the other run on this task");
});
it("offers retry without a workspace repair checklist", () => {
const seed = buildConfigurationIncompleteRecoveryNoticeSeed({ reason: "workspace_source_restricted" });
expect(seed.title).toBe("Task couldn’t start");
expect(seed.body).toBe("The task couldn’t start.");
expect(seed.nextAction).toBe("Retry the task.");
});
it("keeps the secret-binding copy for other configuration gaps", () => {
expect(buildConfigurationIncompleteRecoveryNoticeSeed({ reason: "secret_binding_missing" }).body).toContain(
"a secret it needs is not set",
);
expect(buildConfigurationIncompleteRecoveryNoticeSeed(null).body).toContain("a secret it needs is not set");
});
it("explains an unresolved workspace base ref and carries its remedy into the recovery card", () => {
const seed = buildConfigurationIncompleteRecoveryNoticeSeed({
reason: "workspace_base_ref_unresolved",
requestedRef: "main",
attemptedRefs: ["origin/main"],
fetchError: "fatal: couldn't find remote ref refs/heads/main",
missingBindings: [],
});
const notice = buildStrandedRecoveryEscalationNotice({
seed,
recoveryActionId: "base-ref-recovery",
recoveryOwner: null,
sourceRun: { id: "failed-run", status: "failed", errorCode: "configuration_incomplete" },
});
expect(notice.presentation.title).toBe("Workspace base ref unavailable");
expect(notice.body).toContain("did not start");
expect(notice.body).toContain("starting branch");
expect(notice.body).not.toContain("secret");
expect(allRows(notice.metadata)).toContainEqual({
type: "key_value",
label: "Next action",
value: "Set a starting branch that exists in the repository, then press Retry.",
});
});
it("distinguishes todo dispatch from in_progress continuation copy", () => {
expect(buildImmediateExecutionPathRecoveryNoticeSeed({ status: "todo" }).body).toContain("tried to start this task again");
expect(buildImmediateExecutionPathRecoveryNoticeSeed({ status: "in_progress" }).body).toContain(
"tried to continue this task again",
);
});
});
describe("buildStrandedRecoveryEscalationNotice", () => {
it("names a workspace timeout and its repair instead of claiming generic continuation", () => {
const notice = buildStrandedRecoveryEscalationNotice({
seed: buildImmediateExecutionPathRecoveryNoticeSeed({ status: "in_progress" }),
recoveryActionId: "scan-recovery",
recoveryOwner: null,
sourceRun: { id: "failed-run", status: "failed", errorCode: "workspace_git_scan_timeout" },
});
expect(notice.presentation.title).toBe("Workspace scan timed out");
expect(notice.body).toContain("before the agent started");
expect(notice.body).not.toContain("retried continuation");
expect(JSON.stringify(notice.metadata)).toContain("took too long, so no agent work started");
});
it("promises an automatic retry for a timed-out sandbox setup only when the sweep will continue it", () => {
for (const errorCode of ["reusable_sandbox_resume_failed", "remote_workspace_prepare_timeout"]) {
for (const continuesAutomatically of [true, false]) {
const notice = buildStrandedRecoveryEscalationNotice({
seed: buildImmediateExecutionPathRecoveryNoticeSeed({ status: "in_progress" }),
recoveryActionId: "sandbox-recovery", recoveryOwner: null, continuesAutomatically,
sourceRun: { id: "failed-run", status: "failed", errorCode },
});
const text = `${notice.body} ${JSON.stringify(notice.metadata)}`;
expect(text).not.toMatch(/inspect|repair|check /i);
if (continuesAutomatically) expect(text).toContain("tries again automatically");
else {
expect(text).not.toContain("tries again automatically");
expect(notice.body).toContain("Press Retry to start it again.");
}
}
}
});
it("names an environment plugin that was not running after its bounded retries", () => {
const notice = buildStrandedRecoveryEscalationNotice({
seed: buildImmediateExecutionPathRecoveryNoticeSeed({ status: "in_progress" }),
recoveryActionId: "worker-recovery",
recoveryOwner: null,
sourceRun: { id: "failed-run", status: "failed", errorCode: "plugin_worker_unavailable" },
});
expect(notice.presentation.title).toBe("Environment plugin was not running");
expect(notice.body).toContain("before the agent started");
expect(JSON.stringify(notice.metadata)).toContain("Press Retry once it is running again");
});
it("asks for Retry, not a board decision, when the environment provider stayed unavailable", () => {
const notice = buildStrandedRecoveryEscalationNotice({
seed: buildImmediateExecutionPathRecoveryNoticeSeed({ status: "in_progress" }),
recoveryCause: ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE,
recoveryActionId: "provider-recovery",
recoveryOwner: null,
sourceRun: { id: "failed-run", status: "failed", errorCode: ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE },
});
const metadata = JSON.stringify(notice.metadata);
expect(notice.presentation.title).toBe("Environment provider was temporarily unavailable");
expect(metadata).toContain("Retry when ready");
expect(metadata).not.toContain("Waiting for you");
});
const actionId = "6a2f8e64-6f5e-4b58-b7fd-111111111111";
const owner = { id: "9b1c2d3e-4f50-4a61-8b72-222222222222", name: "CTO" };
const sourceRun = {
id: "0c1d2e3f-4a5b-4c6d-8e7f-333333333333",
agentId: "4d5e6f70-8a9b-4c1d-8e2f-444444444444",
status: "failed",
errorCode: "workspace_validation_failed",
errorSummary: "Expected project worktree but resolved the agent fallback directory.",
};
it("emits system_notice presentation and the required metadata rows", () => {
const seed = buildWorkspaceValidationRecoveryNoticeSeed();
const notice = buildStrandedRecoveryEscalationNotice({
seed,
recoveryActionId: actionId,
recoveryOwner: owner,
sourceRun,
});
expect(notice.body).toBe(seed.body);
expect(notice.presentation).toMatchObject({
kind: "system_notice",
tone: "danger",
title: "Workspace validation failed",
});
expect(notice.metadata.version).toBe(1);
expect(notice.metadata.sourceRunId).toBe(sourceRun.id);
const rows = allRows(notice.metadata);
expect(rows).toContainEqual({ type: "key_value", label: "Recovery action", value: actionId });
expect(rows).toContainEqual({ type: "agent_link", label: "Recovery owner", agentId: owner.id, name: owner.name });
expect(rows).toContainEqual({
type: "run_link",
label: "Source run",
runId: sourceRun.id,
agentId: sourceRun.agentId,
title: "failed",
});
expect(rows).toContainEqual({
type: "key_value",
label: "Failure code",
value: "workspace_validation_failed",
});
expect(rows).toContainEqual({
type: "key_value",
label: "Failure summary",
value: sourceRun.errorSummary,
});
expect(rows.some((row) => row.label === "Next action")).toBe(true);
});
it("records board escalation when there is no invokable recovery owner", () => {
const notice = buildStrandedRecoveryEscalationNotice({
seed: buildConfigurationIncompleteRecoveryNoticeSeed(),
recoveryActionId: actionId,
recoveryOwner: null,
sourceRun,
});
const ownerRow = allRows(notice.metadata).find((row) => row.label === "Recovery owner");
expect(ownerRow?.type).toBe("key_value");
expect(ownerRow?.value).toBe("Waiting for you");
});
it("derives title from the recovery cause and body from the plain-comment fallback", () => {
const notice = buildStrandedRecoveryEscalationNotice({
fallbackBody: "Legacy plain comment body.",
recoveryCause: "configuration_incomplete",
recoveryActionId: actionId,
recoveryOwner: owner,
sourceRun: null,
});
expect(notice.body).toBe("Legacy plain comment body.");
expect(notice.presentation.title).toBe("Configuration incomplete");
expect(notice.metadata.sourceRunId).toBeNull();
expect(notice.metadata.sections).toHaveLength(1);
});
it("falls back to the default body and title when no seed or comment is given", () => {
const notice = buildStrandedRecoveryEscalationNotice({
recoveryActionId: actionId,
recoveryOwner: null,
sourceRun: null,
});
expect(notice.body).toBe(DEFAULT_STRANDED_RECOVERY_NOTICE_BODY);
expect(notice.presentation.title).toBe("Automatic recovery blocked");
});
it("omits the failure code row when the source run has no error code", () => {
const notice = buildStrandedRecoveryEscalationNotice({
seed: buildImmediateExecutionPathRecoveryNoticeSeed({ status: "in_progress" }),
recoveryActionId: actionId,
recoveryOwner: owner,
sourceRun: {
id: sourceRun.id,
agentId: sourceRun.agentId,
status: "cancelled",
errorCode: null,
errorSummary: null,
},
});
const rows = allRows(notice.metadata);
expect(rows).toContainEqual({
type: "run_link",
label: "Source run",
runId: sourceRun.id,
agentId: sourceRun.agentId,
title: "cancelled",
});
expect(rows.some((row) => row.label === "Failure code")).toBe(false);
expect(rows.some((row) => row.label === "Failure summary")).toBe(false);
});
it("leads with the classified run failure code over the generic seed title", () => {
const notice = buildStrandedRecoveryEscalationNotice({
seed: buildImmediateExecutionPathRecoveryNoticeSeed({ status: "in_progress" }),
recoveryActionId: actionId,
recoveryOwner: owner,
sourceRun: {
...sourceRun,
errorCode: "provider_quota",
errorSummary: "You've hit your limit · resets 2:30am (UTC)",
},
});
expect(notice.presentation.title).toBe("Error: usage limit reached");
expect(allRows(notice.metadata)).toContainEqual({
type: "key_value",
label: "Failure code",
value: "provider_quota",
});
});
it("titles auth-required run failures as a login error", () => {
expect(
buildStrandedRecoveryEscalationNotice({
seed: buildImmediateExecutionPathRecoveryNoticeSeed({ status: "todo" }),
recoveryActionId: actionId,
recoveryOwner: null,
sourceRun: { ...sourceRun, errorCode: "claude_auth_required" },
}).presentation.title,
).toBe("Error: not logged in to Claude");
});
it("is matched by the metadata-based escalation dedupe matcher", () => {
const notice = buildStrandedRecoveryEscalationNotice({
seed: buildImmediateExecutionPathRecoveryNoticeSeed({ status: "todo" }),
recoveryActionId: actionId,
recoveryOwner: owner,
sourceRun,
});
// The escalation dedupe in recovery/service.ts no longer relies on the
// `Recovery action: \`id\`` body marker for new comments; the metadata
// matcher must recognize every notice this builder produces.
expect(notice.body).not.toContain(actionId);
expect(noticeMetadataReferencesRecoveryAction(notice.metadata, actionId)).toBe(true);
expect(
noticeMetadataReferencesRecoveryAction(notice.metadata, "1f2e3d4c-5b6a-4798-8899-444444444444"),
).toBe(false);
});
});
it("names the unavailable AI account instead of suggesting secret bindings", () => {
const notice = buildConfigurationIncompleteRecoveryNoticeSeed({ reason: "ai_connection_unavailable", provider: "openai" });
expect(notice.nextAction).toContain("Reconnect the selected AI account");
expect(notice.title).toBe("AI connection needs attention");
expect(notice.body).toContain("Reconnect the account");
expect(notice.body).not.toContain("secret/env");
});
it("names a found project authentication conflict instead of suggesting secret bindings", () => {
const notice = buildConfigurationIncompleteRecoveryNoticeSeed({ reason: "ai_connection_incompatible", actionUrl: "/agents/agent-1/runtime" });
expect(notice.title).toBe("AI connection conflicts with project settings");
expect(notice.body).toContain("apiKeyHelper");
expect(notice.nextAction).toContain("choose a different AI connection");
expect(notice.body).not.toContain("secret/env");
});
it("names a remote Runner that was still not updated after its retries", () => {
const notice = buildStrandedRecoveryEscalationNotice({
seed: buildImmediateExecutionPathRecoveryNoticeSeed({ status: "in_progress" }),
recoveryActionId: "runner-recovery",
recoveryOwner: null,
sourceRun: { id: "failed-run", status: "failed", errorCode: "runner_revision_mismatch" },
});
expect(notice.presentation.title).toBe("Remote Runner is out of date");
expect(notice.body).toContain("Runner was still not updated");
expect(notice.body).not.toContain("workspace");
expect(notice.body).not.toContain("authentication");
expect(JSON.stringify(notice.metadata)).toContain("remote Runner received the update");
});
it("names the managed AI connection a plugin Runner-task environment requires", () => {
const notice = buildConfigurationIncompleteRecoveryNoticeSeed({ reason: "ai_connection_required" });
expect(notice.title).toBe("AI connection required");
expect(notice.body).toContain("requires a managed AI connection");
expect(notice.nextAction).toContain("Choose an AI connection");
expect(notice.body).not.toContain("secret/env");
});
it("tells the operator to switch a preconfigured Runner home to an isolated one", () => {
const notice = buildConfigurationIncompleteRecoveryNoticeSeed({ reason: "ai_connection_required", homeMode: "preconfigured" });
expect(notice.title).toBe("Isolated Runner home required");
expect(notice.nextAction).toContain("isolated Runner home");
expect(notice.nextAction).not.toContain("Choose an AI connection");
});
it("never tells a person to press Retry when the task offers no Retry", () => {
const sourceRun = { id: "run-1", status: "cancelled", errorCode: "execution_reconciliation_required" };
for (const seed of [buildNoRunningExecutionNoticeSeed({ status: "in_progress" }), null]) {
const offered = buildStrandedRecoveryEscalationNotice({ seed, recoveryActionId: "action-1", recoveryOwner: null, sourceRun });
expect(`${offered.body} ${JSON.stringify(allRows(offered.metadata))}`).toMatch(/Press Retry/);
const withheld = buildStrandedRecoveryEscalationNotice({ seed, recoveryActionId: "action-1", recoveryOwner: null, sourceRun,
retryOffered: false });
expect(withheld.body).not.toMatch(/retry/i);
expect(JSON.stringify(allRows(withheld.metadata))).not.toMatch(/retry/i);
expect(withheld.body).toContain("Paperclip is holding this task until its saved work is settled.");
}
});