fix(runtime): prevent pre-start plugin workspace, checkpoint, and taskless wake failures (#22973)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Paperclip Runner agents run tasks inside local, sandbox, and plugin
task environments.
> - Four pre-start failure modes still prevent valid runs from starting
or create doomed failing runs before the agent launches.
> - A Core-storage project running on a workspace-storage plugin
environment can reserve an empty `adapter_managed` workspace on fresh
retries or `project_primary` runs and retry in an hourly loop.
> - A task reassigned to or reviewed by another agent on the same plugin
environment fails with `plugin_workspace_owner_mismatch` because the
retained `adapter_managed` workspace still names the previous agent.
> - A follow-up wake whose prior plugin task stopped without retained
session state fails with `checkpoint_status_unconfirmed`, and sanitized
plugin task worker errors drop safe closed-enum operation and RPC codes.
> - Non-timer taskless wakes (such as manual Run Heartbeat) still
enqueue doomed Runner runs that immediately fail with an
ineligible-work-mode message.
> - This pull request fixes all four pre-start paths while preserving
cross-environment, local-workspace, credential-redaction, and stop-proof
invariants.

## Linked Issues or Issue Description

Refs #19921, #22849, #19878.

**What happened?**

Four pre-start failure modes affected Paperclip Runner tasks before the
agent started:

1. When a task in a Core-storage project (no `storageProviderPluginId`)
ran on a workspace-storage plugin environment with `project_primary` or
a fresh continuation retry, `prepareHeartbeatWorkspace` called
`reserveFreshPluginTaskWorkspace` before checking project storage
compatibility, creating an empty `adapter_managed` workspace and looping
on retries.
2. When a task with a retained `adapter_managed` plugin workspace was
reassigned to another agent or reviewed by another agent on the same
plugin environment, `prepareHeartbeatWorkspace` threw
`WorkspaceValidationFailure` (`plugin_workspace_owner_mismatch`).
3. When `executeEnvironmentTask` sanitized worker failures, it discarded
safe closed-enum operation and RPC error codes, and when a follow-up run
inspected a committed, provably stopped prior plugin task whose provider
session state was gone (`executionStopped: true, sessionStateAvailable:
false`), `recoverPluginRunnerCheckpoint` failed the run with
`checkpoint_status_unconfirmed` instead of retiring the settled root
into a fresh session.
4. When a user or caller triggered a non-timer taskless wake (for
example `POST /api/agents/:id/heartbeat/invoke` or `/wakeup` without a
task) on a `paperclip_runner` agent, `heartbeat.wakeup` still created a
run that immediately failed with `"Paperclip Runner requires a standard,
planning, ask, or skill test task."`

**Expected behavior**

1. Core-storage project sources running on a workspace-storage plugin
environment fail early with `configuration_incomplete`
(`project_storage_environment_incompatible`) across all workspace
strategies and fresh retries without reserving an empty workspace.
2. Reassigned assignees and reviewers on the same plugin environment
provision their own agent-owned `adapter_managed` workspace (rebinding
`issues.executionWorkspaceId` only for the assignee, leaving the
assignee's workspace intact during reviews, and keeping
cross-environment and local-workspace ownership guards fail-closed).
3. Sanitized plugin task errors carry closed-enum `pluginTaskError`
(`operation`, `errorCode`, `rpcErrorCode`) into `resultJson` without
leaking worker text or credentials, and a committed, provably stopped
prior plugin task with `executionStopped: true` and
`sessionStateAvailable: false` retires cleanly into `continuity-breaks`
so the new run starts fresh.
4. Non-timer taskless wakes for `paperclip_runner` agents are skipped
cleanly with a `heartbeat.task_required` receipt and `reason:
"task_required"` wakeup response instead of creating a failing run, and
`resolveNativeRuntimeMode` distinguishes missing-task
(`paperclip_runner_task_required`) from wrong work mode
(`paperclip_runner_issue_ineligible`).

**Steps to reproduce**

1. Run `prepareHeartbeatWorkspace` with a Core-storage project workspace
on an active workspace-storage plugin environment during a fresh retry
or `project_primary` run.
2. Run `prepareHeartbeatWorkspace` as Agent A on a plugin environment,
then reassign or review the task as Agent B on the same plugin
environment.
3. Trigger a follow-up replacement run when the prior committed plugin
task is stopped (`executionStopped: true`) with `sessionStateAvailable:
false`, or throw a `JsonRpcCallError` timeout from a plugin task worker.
4. Call `heartbeat.wakeup` with `source: "on_demand"` and no task scope
on a `paperclip_runner` agent.

**Paperclip version or commit**

Reproduced on `origin/master` at
`2d065677959b585065ff3fec8718156a4cf6f41d`.

**Deployment mode**

Self-hosted / Cloud server. Verified locally on macOS arm64 with
embedded PostgreSQL.

## What Changed

- `server/src/services/heartbeat/workspace-preparation.ts`:
- Check `projectStorageForEnvironment` for Core-storage project sources
on workspace-storage plugin environments immediately after
`preparePluginWorkspace` and before `reserveFreshPluginTaskWorkspace`,
covering `fresh` retries and `project_primary` as well as
`git_worktree`.
- Detach a foreign agent's `adapter_managed` plugin workspace when a
different `paperclip_runner` agent runs on the same plugin environment
(not during native restart recovery) so the new agent provisions its own
agent-owned workspace cleanly; rebind `issues.executionWorkspaceId` and
idle the previous workspace only when `wasIssueAssignee` is true, and
leave the assignee's workspace untouched during reviews.
- `server/src/services/environment-task-runtime.ts` and
`server/src/services/heartbeat/run-completion.ts`:
- Attach closed-enum `pluginTaskError` (`operation`, optional
`errorCode`, optional `rpcErrorCode`) on sanitized worker errors without
forwarding raw worker text or `cause`, and persist it to
`resultJson.pluginTaskError` on failed runs.
- Attach closed-enum `pluginTaskCheckpointStatus` (`executionStopped`,
`sessionStateAvailable`) to `checkpoint_status_unconfirmed` refusals
while preserving the exact error message.
- `server/src/services/native-runtime/native-session-executor.ts`:
- When a replacement/created run hits `checkpoint_status_unconfirmed`
with explicit `executionStopped: true` and `sessionStateAvailable:
false` on a non-quarantined settled journal, pass
`pluginCheckpointUnavailableConfirmed` into
`retireFinishedPerTurnRunnerdOwner` /
`inspectFinishedPerTurnRunnerdOwner`, verify `remoteExecutionHasStopped`
plus all existing committed-owner and controller-stop proofs, and
archive the prior root into `continuity-breaks` for a fresh session.
Keep unconfirmed stops fail-closed.
- `server/src/services/heartbeat-policy.ts`,
`server/src/services/heartbeat/queue.ts`, `server/src/routes/agents.ts`,
and `server/src/services/native-runtime/runtime-mode.ts`:
- Add `supportsUnscopedHeartbeat`, skip non-timer taskless wakes for
`paperclip_runner` agents with a `heartbeat.task_required` skipped
wakeup receipt, return `reason: "task_required"` in
`buildSkippedWakeupResponse`, and separate
`paperclip_runner_task_required` from
`paperclip_runner_issue_ineligible`.
- `doc/project-environment-compatibility.md`:
- Update the Core-storage-on-plugin-environment note to reflect early
refusal across all workspace strategies and fresh retries.
- Tests added across `workspace-preparation.test.ts`,
`environment-task-runtime.test.ts`,
`environment-task-authority.integration.test.ts`,
`run-completion.test.ts`, `native-session-executor.test.ts`,
`heartbeat-stale-queue-invalidation.test.ts`, `runtime-mode.test.ts`,
and `agent-live-run-routes.test.ts`.
- Note on file length: edits touch existing >1,000-line
lifecycle/executor modules (`workspace-preparation.ts`,
`native-session-executor.ts`, `queue.ts`, `run-completion.ts`,
`agents.ts`) with minimal, scoped additions directly at each invariant
boundary to avoid churn.

## Verification

- **RED (on base `2d065677959b585065ff3fec8718156a4cf6f41d` before
production edits):**
- Ran the 8 new focused tests across `workspace-preparation.test.ts`,
`environment-task-runtime.test.ts`, `run-completion.test.ts`,
`native-session-executor.test.ts`,
`heartbeat-stale-queue-invalidation.test.ts`, and
`runtime-mode.test.ts`: **8 failed | 1 control passed**, confirming
every bug reproduced before edits.
- **GREEN (on head `9c860ca51c4e9742a6594e12ae160895aab8dbdf`):**
- `pnpm --filter @paperclipai/server typecheck` (all 7 layers):
**PASS**.
- Unit suites (`environment-task-runtime.test.ts`,
`runtime-mode.test.ts`, `provider-fresh-workspace.test.ts`,
`native-exact-resume-failure.test.ts`): **4/4 files passed** (`100%`).
- `native-session-executor.test.ts` (focused plugin checkpoint +
unconfirmed checkpoint tests) and `agent-live-run-routes.test.ts`
(focused wakeup/invoke/task_required tests): **PASS**.
- Real embedded-Postgres integration suites
(`environment-task-authority.integration.test.ts` 11/11,
`ephemeral-server-data.test.ts` 6/6, `workspace-preparation.test.ts`
18/18 focused plugin/storage/reassignment/fresh-retry tests,
`heartbeat-stale-queue-invalidation.test.ts` + `run-completion.test.ts`
8/8 focused tests): **PASS**.
- `node scripts/check-test-budget.mjs --files <all 8 modified test
files>`: **PASS** (`110 nightly suites validated, 8 test file(s)
checked`).
- Broad repo-wide verification is supplied by sharded GitHub Actions CI.

## Risks

- Low risk. Cross-environment mismatches, local-workspace reuse on
plugin environments, and native restart recovery ownership checks remain
fail-closed (`plugin_workspace_owner_mismatch`).
- Only committed, provably stopped (`remoteExecutionHasStopped` +
controller-stop proof + settled journal) prior plugin tasks with
explicit provider `executionStopped: true, sessionStateAvailable: false`
retire into `continuity-breaks`; unconfirmed stops still fail closed.
- Sanitized plugin task errors only expose closed-enum operation,
errorCode, and RPC code names; raw worker messages and credentials
remain redacted.
- No database migrations or schema changes are required.

## Model Used

- Google Gemini (Antigravity agentic coding assistant) with tool use,
shell execution, and local embedded-PostgreSQL test verification. Exact
deployment model ID and context window are not exposed to the session.

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-11-25 15:32:20 -06:00
1 parent cc5136ca02
commit 71d7f86293
19 files changed
+725 -59

No files matched your search

@@ -1116,6 +1116,31 @@ describe("agent live run routes", () => {
expect(mockHeartbeatService.wakeup).toHaveBeenCalledWith(routeAgentId, expect.objectContaining({ manualUserWake: true }));
});
it.each([
["heartbeat.task_required", "task_required", "Paperclip Runner requires a task"],
["heartbeat.scheduling_suppressed", "wakeup_skipped", "Wakeup was skipped."],
])("reports %s skipped wakeup receipt accurately for a taskless Paperclip Runner agent", async (receiptReason, expectedReason, expectedMessage) => {
mockAgentService.getById.mockResolvedValue({
id: routeAgentId,
companyId: "company-1",
adapterType: "paperclip_runner",
status: "active",
});
mockHeartbeatService.wakeup.mockImplementationOnce(async (_id: string, opts?: { onSkip?: (reason: string) => void }) => {
opts?.onSkip?.(receiptReason);
return null;
});
const res = await requestApp(await createApp(), url => request(url)
.post(`/api/agents/${routeAgentId}/wakeup`)
.send({ source: "on_demand", triggerDetail: "manual" }));
expect(res.status, JSON.stringify(res.body)).toBe(202);
expect(res.body).toMatchObject({
status: "skipped",
reason: expectedReason,
message: expect.stringContaining(expectedMessage),
});
});
describe("exact native model-rejected review retry", () => {
const reviewContext = {
nativeReviewInteractionId: "55555555-5555-4555-8555-555555555555",
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { eq } from "drizzle-orm";
import { agents, companies, createDb, environmentLeases, environments, heartbeatRuns, plugins, sandboxCreationOperations } from "@paperclipai/db";
import { resolvePluginTaskResume } from "../services/environment-task-runtime.js";
import { isConfirmedStoppedUnavailablePluginCheckpoint, resolvePluginTaskResume } from "../services/environment-task-runtime.js";
import type { PluginTaskResumeRefusal } from "../services/plugin-task-resume.js";
import { hasBoundRemoteStopReceipt, hasRemoteTerminationReceipt, remoteExecutionHasReleased, remoteExecutionHasStopped,
remoteTerminationReceipt } from "../services/remote-execution-termination.js";
@@ -255,13 +255,16 @@ databaseSuite("environment task lease authority", () => {
await db.update(environmentLeases).set({ cleanupStatus: "failed" }).where(eq(environmentLeases.id, oldLeaseId));
await expect(authorize()).rejects.toThrow(refused("predecessor_not_stopped"));
await db.update(environmentLeases).set({ cleanupStatus: "success" }).where(eq(environmentLeases.id, oldLeaseId));
let sessionStateAvailable = false;
let sessionStateAvailable: boolean | undefined = false;
const operations: string[] = [];
const call = vi.fn(async (_id: string, _method: string, params: any) => ["read_state", "archive_state"].includes(params.operation.kind)
? { kind: "state", taskId: params.taskId, state: { schema: "paperclip.runner.durable.state.v1", lifecycle: "suspended",
...(params.operation.identity ?? params.operation.priorIdentity) } }
: params.operation.kind === "status"
? (operations.push("status"), { kind: "status", taskId: params.taskId, phase: "completed", executionStopped: true, sessionStateAvailable })
? (operations.push("status"), {
kind: "status", taskId: params.taskId, phase: "completed", executionStopped: true,
...(sessionStateAvailable !== undefined ? { sessionStateAvailable } : {}),
})
: { kind: "accepted", taskId: params.taskId });
const workers = { getWorker: () => ({ supportedMethods: ["environmentTask"] }), call } as unknown as PluginWorkerManager;
const runtime = environmentRuntimeService(db, { pluginWorkerManager: workers });
@@ -290,7 +293,18 @@ databaseSuite("environment task lease authority", () => {
const inspect = () => runtime.task({ companyId, leaseId: nextLeaseId, operation: {
kind: "read_state", identity: checkpointIdentity, resumeFrom: "old-task",
} });
await expect(inspect()).rejects.toThrow(refused("checkpoint_status_unconfirmed"));
const unconfirmed = await inspect().catch(caught => caught);
expect(unconfirmed).toBeInstanceOf(Error);
expect(unconfirmed.message).toContain(refused("checkpoint_status_unconfirmed"));
expect(unconfirmed.pluginTaskCheckpointStatus).toEqual({ executionStopped: true, sessionStateAvailable: false });
expect(isConfirmedStoppedUnavailablePluginCheckpoint(unconfirmed)).toBe(true);
sessionStateAvailable = undefined;
const unknownAvailability = await inspect().catch(caught => caught);
expect(unknownAvailability).toBeInstanceOf(Error);
expect(unknownAvailability.message).toContain(refused("checkpoint_status_unconfirmed"));
expect(unknownAvailability.pluginTaskCheckpointStatus).toEqual({ executionStopped: true });
expect(isConfirmedStoppedUnavailablePluginCheckpoint(unknownAvailability)).toBe(false);
sessionStateAvailable = false;
await expect(authorize()).rejects.toThrow(refused("predecessor_candidate_missing"));
// Discovery cannot launch, and cannot bypass the original termination receipt.
await expect(runtime.task({ companyId, leaseId: nextLeaseId, operation: {
@@ -298,11 +312,11 @@ databaseSuite("environment task lease authority", () => {
} })).rejects.toThrow("resume identity mismatch");
await db.update(environmentLeases).set({ cleanupStatus: "failed" }).where(eq(environmentLeases.id, oldLeaseId));
await expect(inspect()).rejects.toThrow(refused("predecessor_not_stopped"));
expect(operations).toEqual(["status"]);
expect(operations).toEqual(["status", "status"]);
await db.update(environmentLeases).set({ cleanupStatus: "success" }).where(eq(environmentLeases.id, oldLeaseId));
sessionStateAvailable = true;
await expect(inspect()).resolves.toMatchObject({ kind: "state" });
expect(operations).toEqual(["status", "status"]);
expect(operations).toEqual(["status", "status", "status"]);
await expect(authorize()).resolves.toBe("old-task");
for (const operation of [
{ kind: "read_state" as const, identity: checkpointIdentity, resumeFrom: "old-task" },
@@ -690,6 +690,28 @@ describe("plugin-provided Runner execution", () => {
workers.call.mockRejectedValue(new Error("The installed Runner does not match the expected revision"));
expect(readEnvironmentTaskErrorCode(await executeEnvironmentTask(database().db, workers as never, { companyId: "company", leaseId, operation: submit }).catch(caught => caught))).toBeNull();
});
it("preserves closed plugin operation and RPC error codes through worker error sanitization without leaking worker text", async () => {
const workers = worker();
workers.call.mockRejectedValueOnce(new JsonRpcCallError({ code: -32003, message: "secret-provider-token-123" }));
const timeoutError = await executeEnvironmentTask(database().db, workers as never, { companyId: "company", leaseId, operation: submit }).catch(caught => caught);
expect(timeoutError.message).toBe("Plugin-provided Runner execution operation unavailable; reconcile the same task before retrying");
expect(timeoutError.pluginTaskError).toEqual({ operation: "submit", rpcErrorCode: "timeout" });
expect(JSON.stringify({ ...timeoutError, message: timeoutError.message })).not.toContain("secret-provider-token-123");
expect(timeoutError.cause).toBeUndefined();
workers.call.mockRejectedValueOnce(new JsonRpcCallError({
code: -32002,
message: "secret-revision-token-456",
data: environmentTaskErrorCodeData(new PluginEnvironmentTaskError("runner_revision_mismatch")),
}));
const mismatchError = await executeEnvironmentTask(database().db, workers as never, { companyId: "company", leaseId, operation: submit }).catch(caught => caught);
expect(mismatchError.pluginTaskError).toEqual({
operation: "submit",
errorCode: "runner_revision_mismatch",
rpcErrorCode: "worker_error",
});
expect(JSON.stringify({ ...mismatchError, message: mismatchError.message })).not.toContain("secret-revision-token-456");
});
it("accepts PRP identity characters and length limits", () => {
for (const field of ["runnerId", "leaseId", "runId", "sessionId", "turnId", "itemId"]) {
for (const value of ["session:part.1", "a".repeat(160)]) {
@@ -563,6 +563,55 @@ describeEmbeddedPostgres("heartbeat stale queued-run invalidation", () => {
expect(runRows).toHaveLength(0);
});
it.each([
["empty payload", undefined],
["bare commentId without task", { commentId: randomUUID() }],
])("skips manual taskless on_demand wakes for Paperclip Runner agents (%s) with a task_required receipt instead of failing a run", async (_label, payload) => {
const { companyId, agentId } = await seedCompanyAndAgent();
await db
.update(agents)
.set({ adapterType: "paperclip_runner", adapterConfig: { provider: "codex" } })
.where(eq(agents.id, agentId));
let observedSkipReason: string | null = null;
const run = await heartbeat.wakeup(agentId, {
source: "on_demand",
triggerDetail: "manual",
manualUserWake: true,
payload,
onSkip: (skipReason) => {
observedSkipReason = skipReason;
},
requestedByActorType: "user",
requestedByActorId: "local-board",
});
expect(run).toBeNull();
expect(observedSkipReason).toBe("heartbeat.task_required");
expect(mockAdapterExecute).not.toHaveBeenCalled();
const [wakeup] = await db
.select({
status: agentWakeupRequests.status,
reason: agentWakeupRequests.reason,
payload: agentWakeupRequests.payload,
})
.from(agentWakeupRequests)
.where(eq(agentWakeupRequests.agentId, agentId));
const runRows = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns);
expect(wakeup).toMatchObject({
status: "skipped",
reason: "heartbeat.task_required",
});
expect(wakeup?.payload).toMatchObject({
heartbeatSkip: {
reason: expect.stringContaining("Paperclip Runner requires a task"),
},
});
expect(runRows).toHaveLength(0);
});
it("checks guarded issue status and assignee under the enqueue lock", async () => {
const { companyId, agentId } = await seedCompanyAndAgent();
const parkedIssueId = randomUUID();