mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 10:07:24 +01:00
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:
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();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { resolveLoginEnvironmentTarget } from "../services/login-environment.js";
|
||||
import { supportsUnscopedHeartbeat } from "../services/heartbeat-policy.js";
|
||||
import { checkAgentProtectedEnvironmentKeys } from "../services/protected-environment-keys.js";
|
||||
import { assertProviderApiPlacementPolicy, managedCursorApiDefaultEnabled, resolveProviderApiPlacement } from "../services/native-runtime/provider-api-placement.js";
|
||||
import { isObjectJournalBusyError } from "../services/object-byte-journal.js";
|
||||
@@ -1761,9 +1762,21 @@ export function agentRoutes(
|
||||
async function buildSkippedWakeupResponse(
|
||||
agent: NonNullable<Awaited<ReturnType<typeof svc.getById>>>,
|
||||
payload: Record<string, unknown> | null | undefined,
|
||||
skipReason?: string | null,
|
||||
) {
|
||||
const issueId = typeof payload?.issueId === "string" && payload.issueId.trim() ? payload.issueId : null;
|
||||
if (!issueId) {
|
||||
if (skipReason === "heartbeat.task_required" && !supportsUnscopedHeartbeat(agent)) {
|
||||
return {
|
||||
status: "skipped" as const,
|
||||
reason: "task_required",
|
||||
message: "Paperclip Runner requires a task to run. Assign or open a task for this agent instead of starting a standalone heartbeat.",
|
||||
issueId: null,
|
||||
executionRunId: null,
|
||||
executionAgentId: null,
|
||||
executionAgentName: null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
status: "skipped" as const,
|
||||
reason: "wakeup_skipped",
|
||||
@@ -6311,7 +6324,11 @@ export function agentRoutes(
|
||||
type HeartbeatSource = "timer" | "assignment" | "on_demand" | "automation";
|
||||
type WakeupRouteOpts = {
|
||||
source: HeartbeatSource | undefined;
|
||||
skippedResponse: (agent: NonNullable<Awaited<ReturnType<typeof svc.getById>>>, payload: Record<string, unknown> | null) => unknown | Promise<unknown>;
|
||||
skippedResponse: (
|
||||
agent: NonNullable<Awaited<ReturnType<typeof svc.getById>>>,
|
||||
payload: Record<string, unknown> | null,
|
||||
skipReason: string | null,
|
||||
) => unknown | Promise<unknown>;
|
||||
};
|
||||
const handleWakeupRoute = async (
|
||||
req: Request,
|
||||
@@ -6506,9 +6523,13 @@ export function agentRoutes(
|
||||
),
|
||||
);
|
||||
}
|
||||
let wakeSkipReason: string | null = null;
|
||||
const run = await heartbeat.wakeup(id, {
|
||||
failedRunId: req.body.failedRunId ?? null,
|
||||
...(req.actor.type === "board" && !req.body.failedRunId ? { manualUserWake: true } : {}),
|
||||
onSkip: (skipReason) => {
|
||||
wakeSkipReason = skipReason;
|
||||
},
|
||||
source: opts.source,
|
||||
triggerDetail: req.body.triggerDetail ?? "manual",
|
||||
reason: req.body.reason ?? null,
|
||||
@@ -6542,7 +6563,7 @@ export function agentRoutes(
|
||||
});
|
||||
|
||||
if (!run) {
|
||||
res.status(202).json(await opts.skippedResponse(agent, wakePayload));
|
||||
res.status(202).json(await opts.skippedResponse(agent, wakePayload, wakeSkipReason));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -6582,7 +6603,7 @@ export function agentRoutes(
|
||||
router.post("/agents/:id/wakeup", validate(wakeAgentSchema), async (req, res) => {
|
||||
await handleWakeupRoute(req, res, {
|
||||
source: req.body.source,
|
||||
skippedResponse: (agent, payload) => buildSkippedWakeupResponse(agent, payload),
|
||||
skippedResponse: (agent, payload, skipReason) => buildSkippedWakeupResponse(agent, payload, skipReason),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -10,8 +10,9 @@ import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { environmentLeases, executionWorkspaces, environments, heartbeatRuns, issues, projects, type Db } from "@paperclipai/db";
|
||||
import { freshWorkspaceSchema, environmentTaskOperationSchema, parseEnvironmentTaskResult,
|
||||
environmentTaskErrorData, readEnvironmentTaskErrorDiagnostic, JsonRpcCallError, PLUGIN_RPC_ERROR_CODES,
|
||||
environmentTaskErrorCodeData, PluginEnvironmentTaskError, readEnvironmentTaskErrorCode,
|
||||
type HostToWorkerMethodName, type HostToWorkerMethods, type PluginEnvironmentTaskOperation, type PluginEnvironmentTaskResult } from "@paperclipai/plugin-sdk";
|
||||
environmentTaskErrorCodeData, PluginEnvironmentTaskError, readEnvironmentTaskErrorCode, ENVIRONMENT_TASK_ERROR_CODES,
|
||||
type HostToWorkerMethodName, type HostToWorkerMethods, type PluginEnvironmentTaskOperation, type PluginEnvironmentTaskResult,
|
||||
type PluginEnvironmentTaskErrorCode } from "@paperclipai/plugin-sdk";
|
||||
import { pluginRegistryService } from "./plugin-registry.js";
|
||||
import { remoteTerminationReceipt } from "./remote-execution-termination.js";
|
||||
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
|
||||
@@ -23,6 +24,109 @@ import { assertPluginTaskOwnershipDispatch, PluginTaskOwnershipPendingError, rea
|
||||
|
||||
export type PluginTaskDescription = Extract<PluginEnvironmentTaskResult, { kind: "description" }>;
|
||||
|
||||
const PLUGIN_RPC_ERROR_CODE_NAMES: Readonly<Record<number, PluginTaskRpcErrorCodeName>> = {
|
||||
[PLUGIN_RPC_ERROR_CODES.WORKER_UNAVAILABLE]: "worker_unavailable",
|
||||
[PLUGIN_RPC_ERROR_CODES.CAPABILITY_DENIED]: "capability_denied",
|
||||
[PLUGIN_RPC_ERROR_CODES.WORKER_ERROR]: "worker_error",
|
||||
[PLUGIN_RPC_ERROR_CODES.TIMEOUT]: "timeout",
|
||||
[PLUGIN_RPC_ERROR_CODES.METHOD_NOT_IMPLEMENTED]: "method_not_implemented",
|
||||
[PLUGIN_RPC_ERROR_CODES.INVOCATION_SCOPE_DENIED]: "invocation_scope_denied",
|
||||
[PLUGIN_RPC_ERROR_CODES.CROSS_TENANT_CONFIG]: "cross_tenant_config",
|
||||
[PLUGIN_RPC_ERROR_CODES.UNKNOWN]: "unknown",
|
||||
};
|
||||
|
||||
export type PluginTaskRpcErrorCodeName =
|
||||
| "worker_unavailable"
|
||||
| "capability_denied"
|
||||
| "worker_error"
|
||||
| "timeout"
|
||||
| "method_not_implemented"
|
||||
| "invocation_scope_denied"
|
||||
| "cross_tenant_config"
|
||||
| "unknown";
|
||||
|
||||
const PLUGIN_RPC_ERROR_CODE_NAME_SET: ReadonlySet<string> = new Set(Object.values(PLUGIN_RPC_ERROR_CODE_NAMES));
|
||||
|
||||
const PLUGIN_TASK_OPERATION_KINDS: ReadonlySet<string> = new Set(
|
||||
environmentTaskOperationSchema.options.map(option => option.shape.kind.value),
|
||||
);
|
||||
|
||||
export interface PluginTaskOperationErrorMetadata {
|
||||
operation: PluginEnvironmentTaskOperation["kind"];
|
||||
errorCode?: PluginEnvironmentTaskErrorCode;
|
||||
rpcErrorCode?: PluginTaskRpcErrorCodeName;
|
||||
}
|
||||
|
||||
export interface PluginTaskCheckpointStatusMetadata {
|
||||
executionStopped: boolean;
|
||||
sessionStateAvailable?: boolean;
|
||||
}
|
||||
|
||||
const unconfirmedPluginCheckpointStatuses = new WeakMap<Error, PluginTaskCheckpointStatusMetadata>();
|
||||
|
||||
export function createUnconfirmedPluginCheckpointError(status: PluginTaskCheckpointStatusMetadata): Error {
|
||||
const metadata: PluginTaskCheckpointStatusMetadata = {
|
||||
executionStopped: status.executionStopped === true,
|
||||
...(typeof status.sessionStateAvailable === "boolean"
|
||||
? { sessionStateAvailable: status.sessionStateAvailable }
|
||||
: {}),
|
||||
};
|
||||
const error = Object.assign(pluginTaskResumeRefused("checkpoint_status_unconfirmed"), {
|
||||
pluginTaskCheckpointStatus: metadata,
|
||||
});
|
||||
unconfirmedPluginCheckpointStatuses.set(error, metadata);
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true only when `executeEnvironmentTask` refused `checkpoint_status_unconfirmed`
|
||||
* after the provider explicitly attested both `executionStopped: true` and
|
||||
* `sessionStateAvailable: false`. An omitted `sessionStateAvailable` remains unknown
|
||||
* and fails closed.
|
||||
*/
|
||||
export function isConfirmedStoppedUnavailablePluginCheckpoint(error: unknown): boolean {
|
||||
if (!(error instanceof Error)) return false;
|
||||
const status = unconfirmedPluginCheckpointStatuses.get(error);
|
||||
return status?.executionStopped === true && status.sessionStateAvailable === false;
|
||||
}
|
||||
|
||||
function readPluginRpcErrorCodeName(error: unknown): PluginTaskRpcErrorCodeName | null {
|
||||
for (let current: unknown = error, depth = 0; current && depth < 5; depth++) {
|
||||
if (current instanceof JsonRpcCallError && Object.prototype.hasOwnProperty.call(PLUGIN_RPC_ERROR_CODE_NAMES, current.code)) {
|
||||
return PLUGIN_RPC_ERROR_CODE_NAMES[current.code]!;
|
||||
}
|
||||
current = typeof current === "object" ? (current as { cause?: unknown }).cause : undefined;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Reads only closed-enum plugin task error metadata; never forwards raw worker text. */
|
||||
export function readPluginTaskError(error: unknown): PluginTaskOperationErrorMetadata | null {
|
||||
for (let current: unknown = error, depth = 0; current && depth < 5; depth++) {
|
||||
const raw = typeof current === "object" ? (current as { pluginTaskError?: unknown }).pluginTaskError : undefined;
|
||||
if (raw && typeof raw === "object" && !Array.isArray(raw)) {
|
||||
const record = raw as Record<string, unknown>;
|
||||
const operation = typeof record.operation === "string" && PLUGIN_TASK_OPERATION_KINDS.has(record.operation)
|
||||
? record.operation as PluginEnvironmentTaskOperation["kind"] : null;
|
||||
if (operation) {
|
||||
const errorCode = typeof record.errorCode === "string"
|
||||
&& (ENVIRONMENT_TASK_ERROR_CODES as readonly string[]).includes(record.errorCode)
|
||||
? record.errorCode as PluginEnvironmentTaskErrorCode : undefined;
|
||||
const rpcErrorCode = typeof record.rpcErrorCode === "string"
|
||||
&& PLUGIN_RPC_ERROR_CODE_NAME_SET.has(record.rpcErrorCode)
|
||||
? record.rpcErrorCode as PluginTaskRpcErrorCodeName : undefined;
|
||||
return {
|
||||
operation,
|
||||
...(errorCode ? { errorCode } : {}),
|
||||
...(rpcErrorCode ? { rpcErrorCode } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
current = typeof current === "object" ? (current as { cause?: unknown }).cause : undefined;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function isSettledReadyRunnerState(state: Record<string, unknown>): boolean {
|
||||
const commands = state.processedCommands;
|
||||
return state.schema === "paperclip.runner.durable.state.v1" && state.lifecycle === "ready" &&
|
||||
@@ -206,7 +310,12 @@ export async function executeEnvironmentTask(db: Db, workers: Pick<PluginWorkerM
|
||||
const status = await executeEnvironmentTask(db, workers, { companyId: input.companyId,
|
||||
leaseId: sources[0]!.id, operation: { kind: "status" } });
|
||||
if (status.kind !== "status" || status.executionStopped !== true || status.sessionStateAvailable !== true) {
|
||||
throw pluginTaskResumeRefused("checkpoint_status_unconfirmed");
|
||||
throw createUnconfirmedPluginCheckpointError({
|
||||
executionStopped: status.kind === "status" && status.executionStopped === true,
|
||||
...(status.kind === "status" && typeof status.sessionStateAvailable === "boolean"
|
||||
? { sessionStateAvailable: status.sessionStateAvailable }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
if (resumeFrom !== await resolvePluginTaskResume(db, { companyId: input.companyId, leaseId: lease.id,
|
||||
priorIdentity: { runnerInstanceId: runner.runnerId, environmentLeaseId: runner.leaseId,
|
||||
@@ -601,8 +710,17 @@ export async function executeEnvironmentTask(db: Db, workers: Pick<PluginWorkerM
|
||||
});
|
||||
// Worker errors and schema diagnostics can contain request credentials.
|
||||
const code = readEnvironmentTaskErrorCode(error);
|
||||
const rpcErrorCode = readPluginRpcErrorCodeName(error);
|
||||
const pluginTaskError: PluginTaskOperationErrorMetadata = {
|
||||
operation: operation.kind,
|
||||
...(code ? { errorCode: code } : {}),
|
||||
...(rpcErrorCode ? { rpcErrorCode } : {}),
|
||||
};
|
||||
throw Object.assign(new Error("Plugin-provided Runner execution operation unavailable; reconcile the same task before retrying"),
|
||||
code ? { data: environmentTaskErrorCodeData(new PluginEnvironmentTaskError(code)) } : {});
|
||||
{
|
||||
...(code ? { data: environmentTaskErrorCodeData(new PluginEnvironmentTaskError(code)) } : {}),
|
||||
pluginTaskError,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
import { agents } from "@paperclipai/db";
|
||||
import { asBoolean, parseObject } from "../adapters/utils.js";
|
||||
|
||||
/** Runner work needs a task; generic interval heartbeats have no task owner.
|
||||
/** Runner work needs a task; unscoped heartbeats (timer or manual) have no task owner.
|
||||
* Task-bound schedules, monitors and external-provider assignments use their
|
||||
* existing wake paths and are unaffected by this interval policy.
|
||||
* existing wake paths and are unaffected by this policy.
|
||||
*/
|
||||
export function supportsUnscopedTimerHeartbeat(
|
||||
export function supportsUnscopedHeartbeat(
|
||||
agent: Pick<typeof agents.$inferSelect, "adapterType">,
|
||||
) {
|
||||
return agent.adapterType !== "paperclip_runner";
|
||||
}
|
||||
|
||||
export function supportsUnscopedTimerHeartbeat(
|
||||
agent: Pick<typeof agents.$inferSelect, "adapterType">,
|
||||
) {
|
||||
return supportsUnscopedHeartbeat(agent);
|
||||
}
|
||||
|
||||
export function isHeartbeatWakeOnDemandEnabled(
|
||||
agent: Pick<typeof agents.$inferSelect, "runtimeConfig">,
|
||||
) {
|
||||
|
||||
@@ -206,7 +206,7 @@ import {
|
||||
shouldCancelRunsForNonInvokableAgent,
|
||||
type AgentOrgRow,
|
||||
} from "../agent-invokability.js";
|
||||
import { supportsUnscopedTimerHeartbeat } from "../heartbeat-policy.js";
|
||||
import { supportsUnscopedHeartbeat, supportsUnscopedTimerHeartbeat } from "../heartbeat-policy.js";
|
||||
import { ISSUE_BLOCKER_STALLED_WAKE_REASON, isUuidLike } from "@paperclipai/shared";
|
||||
import { retryChatControlAdmission } from "../chat-control-admission-retry.js";
|
||||
|
||||
@@ -3089,6 +3089,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
|
||||
// A temporary refusal must leave the handoff retryable, without burning
|
||||
// its one durable receipt ID on a skipped wake.
|
||||
if (caseRequest) return { created: false };
|
||||
opts.onSkip?.(skipReason);
|
||||
if (executionWaitRequestId) {
|
||||
const waitSaved = await writeDeferredExecutionWait(db, { companyId: agent.companyId, requestId: executionWaitRequestId }, {
|
||||
reason: skipReason, message: patch.error ?? (skipReason === "issue_tree_hold_active"
|
||||
@@ -3264,15 +3265,27 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
|
||||
}
|
||||
const effectiveTaskKey =
|
||||
readNonEmptyString(enrichedContextSnapshot.taskKey) ?? taskKey;
|
||||
const genericTimerWake =
|
||||
source === "timer" &&
|
||||
!issueId &&
|
||||
!wakeCommentId &&
|
||||
!readNonEmptyString(enrichedContextSnapshot.taskId) &&
|
||||
!effectiveTaskKey;
|
||||
const hasTaskScope = Boolean(
|
||||
issueId ||
|
||||
readNonEmptyString(enrichedContextSnapshot.taskId) ||
|
||||
effectiveTaskKey,
|
||||
);
|
||||
const genericTimerWake = source === "timer" && !hasTaskScope && !wakeCommentId;
|
||||
// Old or direct timer producers cannot create a doomed taskless Runner
|
||||
// run. Explicit session restoration above can supply a real task scope.
|
||||
if (genericTimerWake && !supportsUnscopedTimerHeartbeat(agent)) return null;
|
||||
if (genericTimerWake && !supportsUnscopedTimerHeartbeat(agent)) {
|
||||
opts.onSkip?.("heartbeat.task_required");
|
||||
return null;
|
||||
}
|
||||
if (!hasTaskScope && !supportsUnscopedHeartbeat(agent)) {
|
||||
await writeSkippedHeartbeatRequest("heartbeat.task_required", {
|
||||
reason:
|
||||
"Paperclip Runner requires a task to run. Assign or open a task for this agent instead of starting a standalone heartbeat.",
|
||||
adapterType: agent.adapterType,
|
||||
source,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
const resolveSessionBefore = async (tx: Pick<Db, "select">) =>
|
||||
explicitResumeSession?.sessionDisplayId ??
|
||||
resolveSessionBeforeForWakeup(agent, effectiveTaskKey, tx);
|
||||
|
||||
@@ -1118,6 +1118,19 @@ describe.skipIf(!support.supported && !process.env.PAPERCLIP_TEST_DATABASE_URL)(
|
||||
expect(failed).toMatchObject({ status: "failed", errorCode: "adapter_failed", error: refusal });
|
||||
expect(failed.resultJson).not.toHaveProperty("nativeExactResumeRefusal");
|
||||
});
|
||||
|
||||
it("persists safe closed-enum pluginTaskError metadata on failed runs without leaking worker text", async () => {
|
||||
const f = await fixture({ runtimeMode: "native" });
|
||||
const err = Object.assign(
|
||||
new Error("Plugin-provided Runner execution operation unavailable; reconcile the same task before retrying"),
|
||||
{ pluginTaskError: { operation: "read_state", rpcErrorCode: "timeout", errorCode: "runner_revision_mismatch" } },
|
||||
);
|
||||
await f.completion.failRun(f.failure(err));
|
||||
const failed = await read(f.run.id);
|
||||
expect(failed.resultJson).toMatchObject({
|
||||
pluginTaskError: { operation: "read_state", rpcErrorCode: "timeout", errorCode: "runner_revision_mismatch" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("persists a project denial without provider work or an automatic retry", async () => {
|
||||
|
||||
@@ -30,6 +30,7 @@ import { ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE, findEnvironmentProviderUnavailab
|
||||
import { REPOSITORY_CATALOG_UNAVAILABLE_CODE, findRepositoryCatalogUnavailableError } from "../repository-catalog-unavailable-error.js";
|
||||
import { findWorkspaceProviderFailure } from "../workspace-provider-failure.js";
|
||||
import { isRunnerRevisionMismatch, RUNNER_REVISION_MISMATCH_CODE, RUNNER_REVISION_MISMATCH_RETRY } from "../runner-revision-mismatch.js";
|
||||
import { readPluginTaskError } from "../environment-task-runtime.js";
|
||||
import { isStorageUnavailableError, STORAGE_CREDENTIALS_REJECTED_MESSAGE, STORAGE_UNAVAILABLE_CODE, STORAGE_UNAVAILABLE_EXHAUSTED_MESSAGE, STORAGE_UNAVAILABLE_MESSAGE, STORAGE_UNAVAILABLE_RETRY, storageUnavailableHeldMessage, storageUnavailableMessage } from "../../storage/storage-unavailable.js";
|
||||
import { type RunSessionOutcome, resolveNextSessionState, normalizeUsageTotals, resolveCacheAdjustedCostUsd, resolveLedgerBiller, resolveLedgerCostStatus, normalizeLedgerBillingType } from "./run-state.js";
|
||||
import { readGitConnectionFailure } from "../git-connection-failure.js";
|
||||
@@ -1392,6 +1393,7 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC
|
||||
const stoppedDuringFailure = signal.aborted;
|
||||
const stopSnapshot = stoppedDuringFailure ? await getRun(run.id) : null;
|
||||
const failureOutcome = stoppedDuringFailure ? "cancelled" : "failed";
|
||||
const pluginTaskError = !stoppedDuringFailure ? readPluginTaskError(err) : null;
|
||||
const nativePreDispatchFailure = !stoppedDuringFailure && nativeTerminalFailureCode === null
|
||||
? await nativePreDispatchFailureResult(run.id, nativeDispatchMayHaveStarted) : null;
|
||||
const failedRunWrite = await measureRunPhase("completion.terminal_write", () => setRunStatusIfRunning(run.id, failureOutcome, {
|
||||
@@ -1404,6 +1406,7 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC
|
||||
resultJson: {
|
||||
...parseObject(stopSnapshot?.resultJson),
|
||||
...(failureCause && !stoppedDuringFailure ? { failureCause } : {}),
|
||||
...(pluginTaskError ? { pluginTaskError } : {}),
|
||||
...(providerFailure ? { providerFailure: { ...providerFailure,
|
||||
message: redactCurrentUserText(identityRedactor.redact(providerFailure.message), currentUserRedactionOptions) } } : {}),
|
||||
...(interruptedExactResume ? { nativeExactResumeRefusal: {
|
||||
|
||||
@@ -798,6 +798,8 @@ export interface WakeupOptions {
|
||||
durableCaseHandoffRequest?: { handoffId: string; wakeupRequestId: string; issueId: string; expectedIssueStatusVersion: number };
|
||||
/** Set only by authenticated board wake routes; never copied from caller payloads. */
|
||||
manualUserWake?: boolean;
|
||||
/** Optional observer called with the exact skip reason when this wake is skipped. */
|
||||
onSkip?: (reason: string) => void;
|
||||
/** Internal resume of a queue with persisted board interruption intent. */
|
||||
queuedCommentInterruptId?: string;
|
||||
/** Internal delivery of an existing undelivered user comment. */
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { resolvePaperclipInstanceRoot } from "../../home-paths.js";
|
||||
import { preparePluginWorkspace } from "../plugin-workspaces.js";
|
||||
import { inspectPluginWorkspaceForFinalization } from "../native-runtime/native-plugin-workspace-finalization.js";
|
||||
import { execFile as execFileCallback } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtemp, mkdir, readFile, readdir, realpath, rm, writeFile, access, rename, symlink } from "node:fs/promises";
|
||||
@@ -2101,6 +2102,79 @@ describe.skipIf(!support.supported && !externalDatabaseUrl)("heartbeat workspace
|
||||
expect(await readFile(join(source, "README.md"), "utf8")).toBe("source content\n");
|
||||
});
|
||||
|
||||
it("provisions a separate plugin workspace when a task is reassigned or reviewed by another agent on the same plugin environment", async () => {
|
||||
const { input, issue, envOrchestrator } = await fixture();
|
||||
input.agent.adapterType = "paperclip_runner";
|
||||
const pluginEnvironment = { ...input.environment.localEnvironment, driver: "plugin" as const, config: { pluginKey: "test.computer", driverKey: "tasks" } };
|
||||
input.environment.selectedEnvironmentForConfig = pluginEnvironment;
|
||||
const stopped = new Error("Plugin realization boundary");
|
||||
const realize = vi.spyOn(envOrchestrator, "realizeForRun").mockRejectedValue(stopped);
|
||||
|
||||
// Agent A runs first and binds workspace W_A owned by Agent A.
|
||||
await expect(prepareHeartbeatWorkspace(db, input)).rejects.toBe(stopped);
|
||||
const firstId = (await readIssue(issue.id)).executionWorkspaceId!;
|
||||
const [workspaceA] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, firstId));
|
||||
expect(workspaceA.metadata?.runnerTaskWorkspaceOwner).toMatchObject({ agentId: input.agent.id, environmentId: pluginEnvironment.id });
|
||||
|
||||
// Create Agent B in the same company on the same plugin environment.
|
||||
const [agentB] = await db.insert(agents).values({
|
||||
companyId: issue.companyId, name: "Agent B", adapterType: "paperclip_runner", status: "active",
|
||||
}).returning();
|
||||
const [runB] = await db.insert(heartbeatRuns).values({
|
||||
companyId: issue.companyId, agentId: agentB.id, invocationSource: "on_demand", status: "running",
|
||||
}).returning();
|
||||
|
||||
// Reviewer case: Agent B reviews Agent A's task (wasIssueAssignee = false).
|
||||
await reuse(input, toExecutionWorkspace(workspaceA));
|
||||
const reviewerInput: HeartbeatWorkspacePreparationInput = {
|
||||
...input,
|
||||
agent: agentB,
|
||||
run: runB,
|
||||
task: { ...input.task, wasIssueAssignee: false },
|
||||
};
|
||||
await expect(prepareHeartbeatWorkspace(db, reviewerInput)).rejects.toBe(stopped);
|
||||
// Issue stays bound to Agent A's workspace so Agent A's follow-up turns are undisturbed.
|
||||
expect((await readIssue(issue.id)).executionWorkspaceId).toBe(firstId);
|
||||
const afterReview = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.companyId, issue.companyId));
|
||||
const reviewerWorkspace = afterReview.find(w => w.id !== firstId);
|
||||
expect(reviewerWorkspace).toBeDefined();
|
||||
expect(reviewerWorkspace!.providerType).toBe("adapter_managed");
|
||||
expect(reviewerWorkspace!.metadata?.runnerTaskWorkspaceOwner).toMatchObject({ agentId: agentB.id, environmentId: pluginEnvironment.id });
|
||||
await expect(inspectPluginWorkspaceForFinalization(db, undefined, reviewerWorkspace!, agentB.id, runB.id)).resolves.toMatchObject({
|
||||
providerType: "adapter_managed", owner: { agentId: agentB.id },
|
||||
});
|
||||
|
||||
// Reassignment case: task is reassigned to Agent B (wasIssueAssignee = true).
|
||||
await db.update(issues).set({ assigneeAgentId: agentB.id }).where(eq(issues.id, issue.id));
|
||||
await reuse(input, toExecutionWorkspace(workspaceA));
|
||||
const [runC] = await db.insert(heartbeatRuns).values({
|
||||
companyId: issue.companyId, agentId: agentB.id, invocationSource: "assignment", status: "running",
|
||||
}).returning();
|
||||
const reassignedInput: HeartbeatWorkspacePreparationInput = {
|
||||
...input,
|
||||
agent: agentB,
|
||||
run: runC,
|
||||
task: { ...input.task, wasIssueAssignee: true },
|
||||
};
|
||||
await expect(prepareHeartbeatWorkspace(db, reassignedInput)).rejects.toBe(stopped);
|
||||
const reassignedId = (await readIssue(issue.id)).executionWorkspaceId!;
|
||||
expect(reassignedId).not.toBe(firstId);
|
||||
const [workspaceB] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, reassignedId));
|
||||
expect(workspaceB.providerType).toBe("adapter_managed");
|
||||
expect(workspaceB.metadata?.runnerTaskWorkspaceOwner).toMatchObject({ agentId: agentB.id, environmentId: pluginEnvironment.id });
|
||||
await expect(inspectPluginWorkspaceForFinalization(db, undefined, workspaceB, agentB.id, runC.id)).resolves.toMatchObject({
|
||||
providerType: "adapter_managed", owner: { agentId: agentB.id },
|
||||
});
|
||||
// Agent A's original workspace record keeps its original owner untouched.
|
||||
const [workspaceAAfter] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, firstId));
|
||||
expect(workspaceAAfter.metadata?.runnerTaskWorkspaceOwner).toMatchObject({ agentId: input.agent.id });
|
||||
// Subsequent run for Agent B reuses Agent B's newly bound workspace cleanly.
|
||||
await reuse(reassignedInput, toExecutionWorkspace(workspaceB));
|
||||
await expect(prepareHeartbeatWorkspace(db, reassignedInput)).rejects.toBe(stopped);
|
||||
expect((await readIssue(issue.id)).executionWorkspaceId).toBe(reassignedId);
|
||||
expect(realize).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
|
||||
it.each(["services", "fresh"] as const)("rejects unsupported %s before plugin workspace preparation or acquisition", async mode => {
|
||||
const { input, envOrchestrator } = await fixture();
|
||||
input.agent.adapterType = "paperclip_runner";
|
||||
@@ -2218,6 +2292,61 @@ describe.skipIf(!support.supported && !externalDatabaseUrl)("heartbeat workspace
|
||||
expect(acquire).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["fresh_retry", "project_primary"] as const)(
|
||||
"refuses a %s run for a Core-storage project on a storage-plugin environment without reserving an empty workspace",
|
||||
async scenario => {
|
||||
const { input, issue, envOrchestrator } = await fixture(scenario === "fresh_retry");
|
||||
const storage = await createPluginWorkspaceFixture(db, input.agent.companyId);
|
||||
const [plugin] = await db.select().from(plugins).where(eq(plugins.id, storage.pluginId));
|
||||
await db.update(plugins).set({
|
||||
manifestJson: {
|
||||
...plugin.manifestJson,
|
||||
capabilities: [...plugin.manifestJson.capabilities, "environment.drivers.register"],
|
||||
environmentDrivers: [{
|
||||
driverKey: "tasks", supportsTasks: true, freshWorkspaceVersion: 1,
|
||||
displayName: "Agent Computer", configSchema: { type: "object", properties: {} },
|
||||
}],
|
||||
},
|
||||
}).where(eq(plugins.id, storage.pluginId));
|
||||
input.agent.adapterType = "paperclip_runner";
|
||||
const pluginEnvironment = {
|
||||
...input.environment.localEnvironment,
|
||||
id: randomUUID(),
|
||||
name: "Agent Computer",
|
||||
driver: "plugin" as const,
|
||||
config: { pluginKey: plugin.pluginKey, driverKey: "tasks", driverConfig: {} },
|
||||
};
|
||||
input.environment.selectedEnvironmentId = pluginEnvironment.id;
|
||||
input.environment.selectedEnvironmentForConfig = pluginEnvironment;
|
||||
if (scenario === "fresh_retry") {
|
||||
input.task.freshWorkspace = {
|
||||
mode: "fresh_isolated_workspace", retryIntentId: input.run.id, sourceRunId: input.run.id, retainedSourceIds: [],
|
||||
};
|
||||
} else {
|
||||
input.policy.requestedExecutionWorkspaceMode = "shared_workspace";
|
||||
input.policy.effectiveExecutionWorkspaceMode = "shared_workspace";
|
||||
input.config.mergedConfig = { workspaceStrategy: { type: "project_primary" } };
|
||||
}
|
||||
const acquire = vi.spyOn(envOrchestrator, "acquireForRun");
|
||||
|
||||
await expect(prepareHeartbeatWorkspace(db, input)).rejects.toMatchObject({
|
||||
name: "ConfigurationIncompleteFailure",
|
||||
code: "configuration_incomplete",
|
||||
resultJson: {
|
||||
configurationIncomplete: {
|
||||
reason: "project_storage_environment_incompatible",
|
||||
projectId: issue.projectId,
|
||||
storageProviderPluginId: null,
|
||||
environmentId: pluginEnvironment.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(acquire).not.toHaveBeenCalled();
|
||||
expect(await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.companyId, input.agent.companyId))).toHaveLength(0);
|
||||
expect((await readIssue(issue.id)).executionWorkspaceId).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it.each([true, false])("forwards only authorized plugin project IDs without staging (remote enabled: %s)", async enabled => {
|
||||
const { input, issue, envOrchestrator } = await fixture();
|
||||
vi.stubEnv("PAPERCLIP_MULTI_PROJECT_WORKSPACE_SYNC", "true");
|
||||
|
||||
@@ -240,10 +240,12 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
|
||||
resolvedInstanceSettings,
|
||||
} = input.environment;
|
||||
const { mergedConfig, configSnapshot, secretManifest } = input.config;
|
||||
const {
|
||||
let {
|
||||
requestedShouldReuseExisting,
|
||||
existingExecutionWorkspace,
|
||||
reusableExistingExecutionWorkspace,
|
||||
} = input.reuse;
|
||||
const {
|
||||
workspaceReuseRequest,
|
||||
nativeRecoveryExecutionWorkspaceId,
|
||||
persistedNativeExecutionInput,
|
||||
@@ -355,14 +357,38 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
|
||||
}
|
||||
const taskWorkspaceOwner = pluginTaskWorkspace ? { agentId: agent.id, environmentId: selectedEnvironmentForConfig.id,
|
||||
pluginKey: pluginConfig.pluginKey ?? null, driverKey: pluginConfig.driverKey ?? null } : null;
|
||||
let detachedForeignAgentPluginWorkspace = false;
|
||||
let detachedForeignAgentWorkspaceId: string | null = null;
|
||||
for (const workspace of [existingExecutionWorkspace, reusableExistingExecutionWorkspace]) {
|
||||
const owner = parseObject(workspace?.metadata?.runnerTaskWorkspaceOwner);
|
||||
if ((pluginTaskWorkspace && workspace && workspace.providerType !== "plugin" && Object.keys(owner).length === 0)
|
||||
|| (Object.keys(owner).length > 0 && (!taskWorkspaceOwner || Object.entries(taskWorkspaceOwner).some(([key, value]) => owner[key] !== value)))) {
|
||||
const hasOwner = Object.keys(owner).length > 0;
|
||||
const foreignAgentSamePluginEnv = Boolean(
|
||||
pluginTaskWorkspace && workspace && workspace.providerType === "adapter_managed" && hasOwner
|
||||
&& taskWorkspaceOwner && !nativeRecoveryExecutionWorkspaceId && !persistedNativeExecutionInput
|
||||
&& typeof owner.agentId === "string" && owner.agentId !== taskWorkspaceOwner.agentId
|
||||
&& owner.environmentId === taskWorkspaceOwner.environmentId
|
||||
&& owner.pluginKey === taskWorkspaceOwner.pluginKey
|
||||
&& owner.driverKey === taskWorkspaceOwner.driverKey,
|
||||
);
|
||||
if (foreignAgentSamePluginEnv) {
|
||||
// A reassigned assignee or reviewer on the same plugin environment cannot
|
||||
// reuse another agent's private adapter-managed workspace; detach it so
|
||||
// this run provisions its own agent-owned workspace cleanly.
|
||||
detachedForeignAgentPluginWorkspace = true;
|
||||
detachedForeignAgentWorkspaceId = workspace!.id;
|
||||
continue;
|
||||
}
|
||||
if ((pluginTaskWorkspace && workspace && workspace.providerType !== "plugin" && !hasOwner)
|
||||
|| (hasOwner && (!taskWorkspaceOwner || Object.entries(taskWorkspaceOwner).some(([key, value]) => owner[key] !== value)))) {
|
||||
throw new WorkspaceValidationFailure("The retained workspace belongs to a different agent, environment, or storage provider.",
|
||||
{ reason: "plugin_workspace_owner_mismatch" });
|
||||
}
|
||||
}
|
||||
if (detachedForeignAgentPluginWorkspace) {
|
||||
existingExecutionWorkspace = null;
|
||||
reusableExistingExecutionWorkspace = null;
|
||||
requestedShouldReuseExisting = false;
|
||||
}
|
||||
const workspaceServices = parseObject(mergedConfig.workspaceRuntime).services;
|
||||
if (pluginTaskWorkspace && Array.isArray(workspaceServices) && workspaceServices.length > 0) {
|
||||
throw new WorkspaceValidationFailure("The selected plugin environment does not support Core workspace services.",
|
||||
@@ -723,7 +749,11 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
|
||||
const pluginPrepareInput: Parameters<typeof preparePluginWorkspace>[2] = {
|
||||
companyId: agent.companyId, projectId: resolvedWorkspace.projectId, projectWorkspaceId: resolvedWorkspace.workspaceId,
|
||||
issueId, runId: run.id, agentId: agent.id, responsibleUserId,
|
||||
existingWorkspaceId: providerFresh ? providerFresh.previousWorkspaceId : reusableExistingExecutionWorkspace?.id ?? issueRef?.executionWorkspaceId ?? null,
|
||||
existingWorkspaceId: providerFresh
|
||||
? providerFresh.previousWorkspaceId
|
||||
: detachedForeignAgentPluginWorkspace
|
||||
? null
|
||||
: reusableExistingExecutionWorkspace?.id ?? issueRef?.executionWorkspaceId ?? null,
|
||||
...(providerFresh ? { fresh: providerFresh, expectedBindingRevision: previousProviderBindingRevision } : {}),
|
||||
selectedProviderPluginId: projectExecutionWorkspacePolicy?.storageProviderPluginId ?? null,
|
||||
environment: selectedEnvironmentForConfig,
|
||||
@@ -780,6 +810,23 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
|
||||
}
|
||||
const pluginPrepared = controllerOnly || remoteAuthority ? null : await preparePluginWorkspace(db, input.services.workspaceWorkers, pluginPrepareInput);
|
||||
|
||||
if (pluginTaskWorkspace && !pluginPrepared && !controllerOnly && !remoteAuthority
|
||||
&& selectedEnvironmentForConfig && !projectExecutionWorkspacePolicy?.storageProviderPluginId
|
||||
&& resolvedWorkspace.projectId && resolvedWorkspace.workspaceId) {
|
||||
const environmentStorage = projectStorageForEnvironment(
|
||||
selectedEnvironmentForConfig,
|
||||
await listProjectWorkspaceProviders(db, agent.companyId),
|
||||
);
|
||||
if (environmentStorage?.pluginId) {
|
||||
throw projectStorageEnvironmentIncompleteFailure({
|
||||
message: `This project's workspace storage (Core / local) does not support the environment "${selectedEnvironmentForConfig.name}". Use an agent in a compatible environment, or choose a workspace source from a project for this environment.`,
|
||||
projectId: resolvedWorkspace.projectId,
|
||||
storageProviderPluginId: null,
|
||||
environmentId: selectedEnvironmentForConfig.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const freshTaskReservationId = providerFresh && pluginTaskWorkspace && !pluginPrepared && issueId
|
||||
? await reserveFreshPluginTaskWorkspace({ db, companyId: agent.companyId, issueId, runId: run.id, agentId: agent.id,
|
||||
fresh: providerFresh, responsibleUserId, expectedBindingRevision: previousProviderBindingRevision, owner: taskWorkspaceOwner!,
|
||||
@@ -810,21 +857,6 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
|
||||
} satisfies ExecutionWorkspaceInput;
|
||||
const latestWorkspaceStrategyType = resolveEffectiveWorkspaceStrategyType(requestedExecutionWorkspaceMode, hostExecutionWorkspaceConfig);
|
||||
if (pluginTaskWorkspace && !pluginPrepared && latestWorkspaceStrategyType === "git_worktree") {
|
||||
if (selectedEnvironmentForConfig && !projectExecutionWorkspacePolicy?.storageProviderPluginId
|
||||
&& resolvedWorkspace.projectId && resolvedWorkspace.workspaceId) {
|
||||
const environmentStorage = projectStorageForEnvironment(
|
||||
selectedEnvironmentForConfig,
|
||||
await listProjectWorkspaceProviders(db, agent.companyId),
|
||||
);
|
||||
if (environmentStorage?.pluginId) {
|
||||
throw projectStorageEnvironmentIncompleteFailure({
|
||||
message: `This project's workspace storage (Core / local) does not support the environment "${selectedEnvironmentForConfig.name}". Use an agent in a compatible environment, or choose a workspace source from a project for this environment.`,
|
||||
projectId: resolvedWorkspace.projectId,
|
||||
storageProviderPluginId: null,
|
||||
environmentId: selectedEnvironmentForConfig.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
throw new WorkspaceValidationFailure("The selected plugin environment does not support Core Git worktree preparation.",
|
||||
{ reason: "plugin_workspace_strategy_unsupported" });
|
||||
}
|
||||
@@ -1147,7 +1179,10 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
|
||||
const bindIssueToPersistedExecutionWorkspace = async (
|
||||
workspace: ExecutionWorkspace | null,
|
||||
) => {
|
||||
if (controllerOnly || !issueId || !workspace || nativeRecoveryExecutionWorkspaceId) {
|
||||
if (
|
||||
controllerOnly || !issueId || !workspace || nativeRecoveryExecutionWorkspaceId ||
|
||||
(detachedForeignAgentPluginWorkspace && !input.task.wasIssueAssignee)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const nextIssueWorkspaceMode =
|
||||
@@ -1454,6 +1489,21 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
|
||||
},
|
||||
));
|
||||
}
|
||||
if (
|
||||
detachedForeignAgentPluginWorkspace &&
|
||||
input.task.wasIssueAssignee &&
|
||||
detachedForeignAgentWorkspaceId &&
|
||||
persistedExecutionWorkspace &&
|
||||
detachedForeignAgentWorkspaceId !== persistedExecutionWorkspace.id
|
||||
) {
|
||||
await timeWorkspace("workspace_record_update", () => executionWorkspacesSvc.update(
|
||||
detachedForeignAgentWorkspaceId!,
|
||||
{
|
||||
status: "idle",
|
||||
cleanupReason: null,
|
||||
},
|
||||
));
|
||||
}
|
||||
await bindIssueToPersistedExecutionWorkspace(persistedExecutionWorkspace);
|
||||
const projectRepositoryPaths: string[] = [];
|
||||
if (remoteAuthority) projectRepositoryPaths.push(...(remoteSourceState.value?.source.repositories ?? [])
|
||||
|
||||
@@ -19987,6 +19987,149 @@ describe("runnerd provider runtime wiring", () => {
|
||||
} finally { owner.mockRestore(); resume.mockRestore(); }
|
||||
});
|
||||
|
||||
it.each([
|
||||
"stopped-state-unavailable",
|
||||
"stopped-availability-omitted",
|
||||
"stop-unconfirmed",
|
||||
"stopped-lease-unreleased",
|
||||
] as const)(
|
||||
"handles unconfirmed plugin checkpoint status on replacement lease: %s",
|
||||
async mode => {
|
||||
const first = {
|
||||
...scopedNativeExecution(`plugin-checkpoint-unconfirmed-${mode}`),
|
||||
schema: "paperclip.native-execution-input.v5", executionMode: "default", planningContext: null, runtimeContext: nativeRuntimeContextFixture(),
|
||||
provider: { kind: "codex", model: null, approvalPolicy: "never" },
|
||||
session: { ...execution.session, driverKind: "codex_app_server",
|
||||
normalizedSessionId: `plugin-checkpoint-unconfirmed-${mode}`, lifecyclePolicy: { mode: "warm", idleTimeoutMs: 60_000 } },
|
||||
} as NativeExecutionInput;
|
||||
parseNativeExecutionInput(first);
|
||||
const next = { ...first, binding: { ...first.binding, runId: `${first.binding.runId}-followup` } };
|
||||
const identity = {
|
||||
runId: first.binding.runId, normalizedSessionId: first.session.normalizedSessionId!,
|
||||
runnerInstanceId: "plugin-runner", environmentLeaseId: "old-lease", turnId: "old-turn", itemId: "old-item",
|
||||
};
|
||||
const scoped = await initializeScopedRunnerRoot(first, identity.runnerInstanceId);
|
||||
await mkdir(join(scoped, "control-plane"), { recursive: true });
|
||||
const journal = JSON.stringify({
|
||||
...durableControlPlaneState(identity),
|
||||
commands: [{ type: "turn.start", status: "completed" }],
|
||||
committedEvents: [{ eventType: "run.terminal", envelope: { ...identity, payload: { reportedWorkDisposition: "done" } } }],
|
||||
});
|
||||
await writeFile(join(scoped, "control-plane/control-plane-state.json"), journal);
|
||||
|
||||
const db = leaseDb(next);
|
||||
const ordinarySelect = db.select.bind(db);
|
||||
const { currentNativeControllerIdentity } = await import("./native-restart-recovery.js");
|
||||
const controller = await currentNativeControllerIdentity();
|
||||
const committedPrior = {
|
||||
run: {
|
||||
id: first.binding.runId, companyId: first.binding.companyId, agentId: first.binding.agentId,
|
||||
nativeIssueId: first.binding.issueId, runtimeMode: "native", status: "succeeded",
|
||||
runnerProfileJson: { nativeExecutionInput: first },
|
||||
processPid: null, processGroupId: null, processStartedAt: null,
|
||||
},
|
||||
owner: {
|
||||
runId: first.binding.runId, companyId: first.binding.companyId, issueId: first.binding.issueId,
|
||||
phase: "committed", resultId: "result-1", leaseOwner: null, recoveryState: null,
|
||||
controllerPid: controller.pid, controllerProcessStartedAt: controller.processStartedAt,
|
||||
controllerBootId: controller.bootId,
|
||||
},
|
||||
};
|
||||
const priorEndedLease = {
|
||||
id: "old-lease", companyId: first.binding.companyId, heartbeatRunId: first.binding.runId,
|
||||
status: mode === "stopped-lease-unreleased" ? "active" : "released",
|
||||
releasedAt: mode === "stopped-lease-unreleased" ? null : new Date(),
|
||||
cleanupStatus: mode === "stopped-lease-unreleased" ? null : "success",
|
||||
provider: "plugin:test:tasks", providerLeaseId: "old-task",
|
||||
metadata: {
|
||||
driver: "plugin",
|
||||
runnerTaskExecutionStopped: true,
|
||||
runnerTaskSessionRetained: false,
|
||||
remoteExecutionTermination: {
|
||||
schema: "paperclip.remote-termination.v1",
|
||||
companyId: first.binding.companyId,
|
||||
runId: first.binding.runId,
|
||||
leaseId: "old-lease",
|
||||
provider: "plugin:test:tasks",
|
||||
providerLeaseId: "old-task",
|
||||
state: "stopped",
|
||||
confirmedAt: new Date().toISOString(),
|
||||
},
|
||||
},
|
||||
};
|
||||
db.select = ((fields?: Record<string, unknown>) => {
|
||||
if (fields?.status === heartbeatRuns.status && fields?.runnerProfileJson === heartbeatRuns.runnerProfileJson) {
|
||||
return priorNativeRunDb(first, "succeeded").select(fields as never);
|
||||
}
|
||||
if (fields && "run" in fields && "owner" in fields) {
|
||||
return {
|
||||
from: () => ({
|
||||
innerJoin: () => ({
|
||||
where: () => ({ limit: async () => [committedPrior] }),
|
||||
}),
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (fields && "providerLeaseId" in fields && "status" in fields) {
|
||||
return { from: () => ({ where: async () => [priorEndedLease] }) };
|
||||
}
|
||||
if (fields === undefined) {
|
||||
return {
|
||||
from: (table: unknown) => table === environmentLeases
|
||||
? { where: async () => [priorEndedLease] }
|
||||
: ordinarySelect().from(table as never),
|
||||
};
|
||||
}
|
||||
return ordinarySelect(fields as never);
|
||||
}) as Db["select"];
|
||||
|
||||
const resume = vi.spyOn(environmentTaskRuntime, "resolvePluginTaskResume").mockResolvedValue("old-task");
|
||||
const task = vi.fn(async (operation: any) => {
|
||||
environmentTaskOperationSchema.parse(operation);
|
||||
if (operation.kind === "read_state") {
|
||||
throw environmentTaskRuntime.createUnconfirmedPluginCheckpointError({
|
||||
executionStopped: mode !== "stop-unconfirmed",
|
||||
...(mode === "stopped-availability-omitted" ? {} : { sessionStateAvailable: false }),
|
||||
});
|
||||
}
|
||||
return {
|
||||
kind: "description", taskId: "replacement-task", launchPreparationVersion: 1, projectAuthCheckVersion: 1, warmTaskVersion: 1,
|
||||
runner: { version: "fixture", digest: `sha256:${"a".repeat(64)}` },
|
||||
};
|
||||
});
|
||||
state.createBackend.mockClear();
|
||||
const home = join(isolatedStateDirectory, `checkpoint-unconfirmed-${mode}`);
|
||||
await mkdir(home, { recursive: true });
|
||||
await writeFile(join(home, "auth.json"), JSON.stringify({ OPENAI_API_KEY: "synthetic-fixture" }), { mode: 0o600 });
|
||||
try {
|
||||
const launch = {
|
||||
db, execution: next, runnerInstanceId: "replacement-runner", runnerIngressAuthorized: true,
|
||||
managedAiCredentialHome: home, managedAiCredentialIdentity: "revision", managedAiAccountIdentity: "account",
|
||||
runnerEnvironment: { ANTHROPIC_API_KEY: "synthetic-fixture" },
|
||||
runnerExecutionTarget: {
|
||||
kind: "remote", transport: "sandbox", remoteCwd: ".", leaseId: "replacement-lease", runnerTask: task,
|
||||
sandboxLeaseAcquisition: { outcome: "replacement", providerLeaseId: "replacement-task" },
|
||||
} as never,
|
||||
};
|
||||
if (mode === "stopped-state-unavailable") {
|
||||
await expect(createRunnerdBackend(launch)).resolves.toBeDefined();
|
||||
expect(state.createBackend).toHaveBeenCalledOnce();
|
||||
expect(existsSync(join(scoped, "continuity-breaks"))).toBe(true);
|
||||
} else if (mode === "stopped-lease-unreleased") {
|
||||
await expect(createRunnerdBackend(launch)).rejects.toThrow("retirement_refused=prior_lease_active");
|
||||
expect(state.createBackend).not.toHaveBeenCalled();
|
||||
expect(existsSync(join(scoped, "continuity-breaks"))).toBe(false);
|
||||
} else {
|
||||
await expect(createRunnerdBackend(launch)).rejects.toThrow("checkpoint_status_unconfirmed");
|
||||
expect(state.createBackend).not.toHaveBeenCalled();
|
||||
expect(existsSync(join(scoped, "continuity-breaks"))).toBe(false);
|
||||
}
|
||||
} finally {
|
||||
resume.mockRestore();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["verified", "wrong-state", "no-stop-proof", "disposition-retry", "disposition-wrong-state", "disposition-no-stop-proof"] as const)("admits only an authorized same-run plugin checkpoint: %s", async mode => {
|
||||
const current = scopedNativeExecution(`plugin-crash-${mode}`);
|
||||
const identity = { runId: current.binding.runId, normalizedSessionId: current.session.normalizedSessionId!,
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { currentControllerProcess } from "../controller-process-identity.js";
|
||||
import { isConfirmedStoppedUnavailablePluginCheckpoint } from "../environment-task-runtime.js";
|
||||
import { remoteExecutionHasStopped } from "../remote-execution-termination.js";
|
||||
import { isAntigravitySwarmExecution } from "../antigravity-swarm.js";
|
||||
import { applyNativeAcceptedOutcome, nativeRetainsWarmSession, readNativeAcceptedOutcome, type NativeAcceptedOutcome } from "./native-accepted-outcome.js";
|
||||
import { settleReattachRun } from "../heartbeat/run-admission.js";
|
||||
@@ -6032,7 +6034,7 @@ async function recoverPluginRunnerCheckpoint(input: {
|
||||
db: Db;
|
||||
execution: NativeExecutionInput;
|
||||
runnerExecutionTarget?: AdapterExecutionTarget | null;
|
||||
}, scoped: string): Promise<void> {
|
||||
}, scoped: string): Promise<{ checkpointUnavailable?: true } | void> {
|
||||
const target = input.runnerExecutionTarget;
|
||||
if (target?.kind !== "remote" || target.transport !== "sandbox" || !target.runnerTask || !target.leaseId ||
|
||||
target.sandboxLeaseAcquisition?.outcome === "resumed") return;
|
||||
@@ -6078,7 +6080,18 @@ async function recoverPluginRunnerCheckpoint(input: {
|
||||
if (!isSettledRemoteWarmControlState(control, identity)) return deny("journal_not_settled");
|
||||
const resumeFrom = await resolvePluginTaskResume(input.db, { companyId: input.execution.binding.companyId,
|
||||
leaseId: target.leaseId, priorIdentity: identity, inspectCheckpoint: true });
|
||||
const checkpoint = environmentTaskResultSchema.parse(await target.runnerTask({ kind: "read_state", identity, resumeFrom }));
|
||||
let checkpoint: ReturnType<typeof environmentTaskResultSchema.parse>;
|
||||
try {
|
||||
checkpoint = environmentTaskResultSchema.parse(await target.runnerTask({ kind: "read_state", identity, resumeFrom }));
|
||||
} catch (error) {
|
||||
// When the provider explicitly attests that the prior task stopped and its
|
||||
// retained session state is no longer available, allow the caller to retire
|
||||
// the settled prior root cleanly into a fresh session instead of failing.
|
||||
if (!quarantined && isConfirmedStoppedUnavailablePluginCheckpoint(error)) {
|
||||
return { checkpointUnavailable: true };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (checkpoint.kind !== "state" || checkpoint.state.lifecycle !== "suspended" ||
|
||||
!Array.isArray(checkpoint.state.outbox) || checkpoint.state.outbox.length !== 0 ||
|
||||
checkpoint.state.pendingTerminalDelivery != null || checkpoint.state.pendingProviderCleanup != null ||
|
||||
@@ -6237,18 +6250,27 @@ async function inspectFinishedPerTurnRunnerdOwner(input: {
|
||||
execution: NativeExecutionInput;
|
||||
projectedControlBytes?: string;
|
||||
runnerExecutionTarget?: AdapterExecutionTarget | null;
|
||||
pluginCheckpointUnavailableConfirmed?: boolean;
|
||||
onLog?: (stream: "stdout" | "stderr", chunk: string) => Promise<void>;
|
||||
}): Promise<{ finished: true; run: typeof heartbeatRuns.$inferSelect; recheck: () => Promise<string | null> }
|
||||
| { finished: false; refused: string }> {
|
||||
const target = input.runnerExecutionTarget;
|
||||
// A resumed sandbox still holds the prior Runner's own lifecycle, which its
|
||||
// existing recovery path reads. Plugin tasks own a separate saved checkpoint.
|
||||
// existing recovery path reads. Plugin tasks own a separate saved checkpoint,
|
||||
// unless the provider explicitly confirmed it is stopped and no state remains.
|
||||
const refuse = (refused: string) => ({ finished: false as const, refused });
|
||||
const lifecycle = input.execution.session.lifecyclePolicy.mode;
|
||||
const localRunner = !target || target.kind === "local";
|
||||
if (lifecycle !== "per_turn" && !(lifecycle === "warm" && !localRunner)) return refuse("lifecycle_not_per_turn");
|
||||
let confirmedGonePluginTask = false;
|
||||
if (!localRunner) {
|
||||
if (target.kind !== "remote" || target.transport !== "sandbox" || !target.runner || target.runnerTask) {
|
||||
confirmedGonePluginTask = Boolean(
|
||||
input.pluginCheckpointUnavailableConfirmed
|
||||
&& target.kind === "remote" && target.transport === "sandbox" && target.runnerTask
|
||||
&& await remoteExecutionHasStopped(input.db, input.execution.binding.companyId, input.identity.runId),
|
||||
);
|
||||
if (target.kind !== "remote" || target.transport !== "sandbox"
|
||||
|| (!confirmedGonePluginTask && (!target.runner || target.runnerTask))) {
|
||||
return refuse("target_not_sandbox_runner");
|
||||
}
|
||||
if (!["created", "replacement"].includes(target.sandboxLeaseAcquisition?.outcome ?? "")) {
|
||||
@@ -6272,6 +6294,9 @@ async function inspectFinishedPerTurnRunnerdOwner(input: {
|
||||
currentProviderLeaseId: target?.kind === "remote" && target.transport === "sandbox"
|
||||
? target.sandboxLeaseAcquisition?.providerLeaseId : undefined,
|
||||
});
|
||||
if (confirmedGonePluginTask && !remoteRunnerGone) {
|
||||
return refuse("prior_lease_active");
|
||||
}
|
||||
const parkedGovernedWait = remoteRunnerGone && await priorRunParkedOnGovernedWait(input.db, {
|
||||
companyId: binding.companyId, issueId: binding.issueId, runId: identity.runId });
|
||||
const projectionOptions = { localRunner, controlBytes: input.projectedControlBytes, remoteRunnerGone, parkedGovernedWait };
|
||||
@@ -6529,6 +6554,7 @@ async function migrateRunnerdStateRootForExecution(input: {
|
||||
restartRecovery?: NativeRestartRecoveryClaim;
|
||||
runnerExecutionTarget?: AdapterExecutionTarget | null;
|
||||
bootstrapRetryLeaseOwner?: string;
|
||||
pluginCheckpointUnavailableConfirmed?: boolean;
|
||||
}): Promise<VerifiedWarmTransitionBinding | undefined> {
|
||||
const scoped = scopedRunnerdStateRoot(input.execution);
|
||||
await restoreWarmRunnerdController(input);
|
||||
@@ -6541,8 +6567,10 @@ async function migrateRunnerdStateRootForExecution(input: {
|
||||
issueId: input.execution.binding.issueId,
|
||||
stateKey: basename(scoped),
|
||||
});
|
||||
if (!input.restartRecovery && !input.retainedWarmOwnerRunId) {
|
||||
await recoverPluginRunnerCheckpoint(input, scoped);
|
||||
let pluginCheckpointUnavailableConfirmed = input.pluginCheckpointUnavailableConfirmed === true;
|
||||
if (!input.restartRecovery && !input.retainedWarmOwnerRunId && !pluginCheckpointUnavailableConfirmed) {
|
||||
const recovered = await recoverPluginRunnerCheckpoint(input, scoped);
|
||||
if (recovered?.checkpointUnavailable) pluginCheckpointUnavailableConfirmed = true;
|
||||
}
|
||||
if (
|
||||
input.allowLocalRecovery &&
|
||||
@@ -6698,7 +6726,7 @@ async function migrateRunnerdStateRootForExecution(input: {
|
||||
let retirementRefusal = "";
|
||||
if (verification === "terminal_state_indeterminate" && !input.retainedWarmOwnerRunId
|
||||
&& (!input.restartRecovery || input.restartRecovery.kind === "bootstrap_incomplete")) {
|
||||
const retirement = await retireFinishedPerTurnRunnerdOwner({ ...input, root: scoped, identity });
|
||||
const retirement = await retireFinishedPerTurnRunnerdOwner({ ...input, root: scoped, identity, pluginCheckpointUnavailableConfirmed });
|
||||
if (retirement.retired) return;
|
||||
if (retirement.refused !== "lifecycle_not_per_turn") retirementRefusal = `; retirement_refused=${retirement.refused}`;
|
||||
}
|
||||
@@ -11246,6 +11274,7 @@ async function executePaperclipNativeSessionAttempt(
|
||||
} finally { cachedReleasedOwner.busy = wasBusy; }
|
||||
} else releasedWarmSource(input, cachedReleasedOwner.pluginTaskId ?? null);
|
||||
}
|
||||
let pluginCheckpointUnavailableConfirmed = false;
|
||||
if (input.useRunnerd && canRecoverWarmOwner && !input.backend &&
|
||||
input.runnerExecutionTarget?.kind === "remote" &&
|
||||
input.execution.session.lifecyclePolicy.mode === "warm" &&
|
||||
@@ -11262,7 +11291,8 @@ async function executePaperclipNativeSessionAttempt(
|
||||
pluginTaskDescription = description;
|
||||
}
|
||||
if (taskTarget.sandboxLeaseAcquisition?.outcome !== "resumed" && !portableSource) {
|
||||
await recoverPluginRunnerCheckpoint(input, root);
|
||||
const recovered = await recoverPluginRunnerCheckpoint(input, root);
|
||||
if (recovered?.checkpointUnavailable) pluginCheckpointUnavailableConfirmed = true;
|
||||
}
|
||||
}
|
||||
if (durableIdentityMatchesSession(identity, input.execution) && identity.runId !== input.execution.binding.runId) {
|
||||
@@ -11319,6 +11349,7 @@ async function executePaperclipNativeSessionAttempt(
|
||||
restartRecovery: input.restartRecovery,
|
||||
runnerExecutionTarget: input.runnerExecutionTarget,
|
||||
bootstrapRetryLeaseOwner: input.leaseOwner,
|
||||
pluginCheckpointUnavailableConfirmed,
|
||||
}));
|
||||
}
|
||||
const durableRunnerBinding = input.useRunnerd
|
||||
|
||||
@@ -223,6 +223,20 @@ describe("resolveNativeRuntimeMode", () => {
|
||||
}));
|
||||
});
|
||||
|
||||
it("distinguishes missing task from ineligible workMode for Paperclip Runner", () => {
|
||||
expect(() => resolveNativeRuntimeMode({ ...eligible, issue: null })).toThrow(expect.objectContaining({
|
||||
code: "paperclip_runner_task_required",
|
||||
message: expect.stringContaining("requires a task"),
|
||||
}));
|
||||
expect(() => resolveNativeRuntimeMode({
|
||||
...eligible,
|
||||
issue: { id: "issue", workMode: "unsupported_mode" },
|
||||
})).toThrow(expect.objectContaining({
|
||||
code: "paperclip_runner_issue_ineligible",
|
||||
message: "Paperclip Runner requires a standard, planning, ask, or skill test task.",
|
||||
}));
|
||||
});
|
||||
|
||||
it("uses adapterConfig as the fresh provider authority", () => {
|
||||
expect(resolveNativeRuntimeMode({
|
||||
...eligible,
|
||||
|
||||
@@ -149,8 +149,14 @@ export function resolveNativeRuntimeMode(input: {
|
||||
if (runnerProfile.provider === "cursor_cloud" && (input.target?.kind ?? "local") !== "local") {
|
||||
throw ineligible("paperclip_runner_cursor_cloud_local_controller_required", "Cursor Cloud currently requires a local Paperclip controller. Cursor hosts its execution environment.");
|
||||
}
|
||||
if (!input.issue) {
|
||||
throw ineligible(
|
||||
"paperclip_runner_task_required",
|
||||
"Paperclip Runner requires a task to run. Assign or open a task for this agent.",
|
||||
);
|
||||
}
|
||||
const allowedWorkModes = ["standard", "planning", "ask", "skill_test"];
|
||||
if (!input.issue || !allowedWorkModes.includes(input.issue.workMode)) {
|
||||
if (!allowedWorkModes.includes(input.issue.workMode)) {
|
||||
throw ineligible(
|
||||
"paperclip_runner_issue_ineligible",
|
||||
"Paperclip Runner requires a standard, planning, ask, or skill test task.",
|
||||
|
||||
Reference in new issue
Block a user