Skip to content

The open-source app everyone uses to manage agents at work

Add plugin-owned project storage and task workspaces (#17001)

Nicky Leach8b4ab65b1c3d
diff --git a/packages/plugins/sdk/README.md b/packages/plugins/sdk/README.md
index 23f4a0311b..5448ba6af9 100644
--- a/packages/plugins/sdk/README.md
+++ b/packages/plugins/sdk/README.md
@@ -1305,3 +1305,71 @@ An `appShellOverlay` slot uses `ui.action.register` and the standard
`PluginWidgetProps` context. It survives navigation and unmounts on account or
company changes, sign-out and onboarding. Plugins own panel accessibility and
request cleanup. See [the distribution and lifecycle contract](../../../doc/plugins/DISTRIBUTION-PLUGINS.md).
+
+## Project storage and task workspaces
+
+A storage provider declares `workspaceProvider: { modes: ["isolated_workspace"],
+strategies: ["git_worktree"] }`, `workspaces.manage`, and
+`resourceLifecycle: ["project"]` (with `events.subscribe`). The same plugin must
+implement `onResourceLifecycle` and `onWorkspaceOperation`. Project lifecycle
+creates and retains the storage; workspace operations manage task checkouts in
+that storage. Execution remains a separate environment driver contract.
+
+Set `project.executionWorkspacePolicy.storageProviderPluginId` to the installed
+plugin's UUID. Core then reserves an execution-workspace row and binds the task
+before it calls `onWorkspaceOperation`. Projects without this setting keep their
+current local behavior. Existing managed workspaces retain their original owner.
+
+The hook receives a company, project, source revision, execution-workspace ID,
+lifecycle generation, deadline, and stable operation ID. Run and agent IDs are
+optional context. A storage hook must work without an environment lease, a live
+agent, or a filesystem mount on Core. It must reconcile ambiguous retries before
+repeating side effects. Use the workspace ID and generation to fence provider
+operations; the operation ID identifies a retry of the same request.
+Fresh inspections get a new operation ID so provider result caches cannot reuse
+an earlier checkout status. Prepare and removal retries retain their IDs.
+
+- `prepare` creates or restores the checkout. It returns an opaque, durable
+ `WorkspaceProviderBinding`, a branch, and the starting commit. `branchMode:
+ "existing"` must use an existing logical branch and must never reset its history.
+ A provider may materialize a local ref from a confirmed existing remote branch. Retried preparation must keep
+ local work. Providers may reject modes or strategies they do not support.
+- `inspect` reports tracked, untracked, and ignored/local-only changes, the
+ current commit, merge state, and whether remote storage can recover it. Use
+ `null` when a remote recovery or merge check is unknown.
+- `remove` checks the expected commit again and confirms removal. Busy, failed,
+ unsafe, and uncertain removal must throw. Core requires a clean checkout and
+ affirmative remote recovery or merge evidence before requesting removal.
+
+References contain the installed plugin ID, project/source/workspace IDs, source
+revision, and opaque provider coordinates. They must not contain secrets. Core
+stores no local `cwd` for managed rows. `/workspaces/<id>` is a logical path in
+Core's existing run metadata; Core must not use it for filesystem access.
+
+For the initial execution integration, select a task-capable environment driver
+from the same plugin. Core validates declared modes and strategies before it
+reserves a workspace. Core pins the binding on the environment lease and supplies
+it as `PluginEnvironmentTaskParams.workspace`. The execution hook resolves the
+provider reference to guest mounts and the actual working directory. Core rejects
+an execution driver from a different plugin. Native execution also requires the
+plugin Runner task bridge; Core refuses to fall back to a host Runner when that
+bridge is unavailable. This does not require merging the
+storage and execution interfaces.
+
+Core's existing archive, reopen, and terminal cleanup fences also cover provider
+workspaces. The plugin must prevent project storage retirement while its task
+workspaces still contain local data. Repository source and storage owner changes
+are blocked while live managed workspaces depend on them. An authorized storage
+owner or source edit retires closed workspaces whose provider removal is confirmed;
+retired records cannot reopen. Inspection reconciles a pending restoration with
+its recorded request, advances its generation, and keeps the Core row closed.
+Cleanup must then inspect that generation afresh; it cannot reuse an earlier
+removal receipt. Direct removal refuses unresolved restoration intent.
+Core commits storage intent and recovery results with cleanup notifications so
+incremental terminal-workspace sweeps revisit changed records.
+Pending deletion is replayed before inspection, including after a lost removal
+result. File browsing and
+other Core-host filesystem operations are unavailable for managed storage.
+
+Use `createWorkspaceProviderHarness` from `@paperclipai/plugin-sdk/testing` to
+validate hook inputs and outputs without allocating an execution environment.
diff --git a/packages/plugins/sdk/src/define-plugin.ts b/packages/plugins/sdk/src/define-plugin.ts
index 13096cbcf8..60ce90ac3d 100644
--- a/packages/plugins/sdk/src/define-plugin.ts
+++ b/packages/plugins/sdk/src/define-plugin.ts
@@ -1,3 +1,4 @@
+import type { PluginWorkspaceParams, PluginWorkspaceResult } from "./workspace-provider.js";
import type { PluginEnvironmentTaskParams, PluginEnvironmentTaskResult } from "./environment-tasks.js";
import type { AgentLifecycleRequest, AgentLifecycleResult } from "@paperclipai/shared";
import type { AiConnectionRouterRequest, AiConnectionRouterResult } from "@paperclipai/shared";
@@ -402,6 +403,9 @@ export interface PluginDefinition {
params: PluginEnvironmentValidateConfigParams,
): Promise<PluginEnvironmentValidationResult>;
+ /** Required with manifest.workspaceProvider, together with project resource lifecycle. */
+ onWorkspaceOperation?(params: PluginWorkspaceParams): Promise<PluginWorkspaceResult>;
+
/** Provide Runner execution: prepare resources, start Runner, connect via PRP, and manage task lifecycle. */
onEnvironmentTask?(params: PluginEnvironmentTaskParams): Promise<PluginEnvironmentTaskResult>;
diff --git a/packages/plugins/sdk/src/environment-tasks.ts b/packages/plugins/sdk/src/environment-tasks.ts
index 350b36fbb5..1aaa10abae 100644
--- a/packages/plugins/sdk/src/environment-tasks.ts
+++ b/packages/plugins/sdk/src/environment-tasks.ts
@@ -135,6 +135,7 @@ export interface PluginEnvironmentTaskParams extends Omit<PluginEnvironmentDrive
agentId: string | null;
/** Company-validated projects to prepare on submit; empty during cleanup. */
projectIds: string[];
+ workspace?: import("@paperclipai/shared").WorkspaceProviderBinding;
operation: PluginEnvironmentTaskOperation;
}
diff --git a/packages/plugins/sdk/src/index.ts b/packages/plugins/sdk/src/index.ts
index 22bd7efce9..9eecc930a3 100644
--- a/packages/plugins/sdk/src/index.ts
+++ b/packages/plugins/sdk/src/index.ts
@@ -468,3 +468,5 @@ export type { PluginEnvironmentTaskOperation, PluginEnvironmentTaskParams, Plugi
export type { AgentLifecycleRequest, AgentLifecycleResult } from "@paperclipai/shared";
export type { PluginEnvironmentRunnerLaunchRequirements, PluginEnvironmentPreparedLaunch } from "./environment-tasks.js";
+
+export * from "./workspace-provider.js";
diff --git a/packages/plugins/sdk/src/protocol.ts b/packages/plugins/sdk/src/protocol.ts
index b6cb01a679..c8770fde64 100644
--- a/packages/plugins/sdk/src/protocol.ts
+++ b/packages/plugins/sdk/src/protocol.ts
@@ -1,3 +1,4 @@
+import type { PluginWorkspaceParams, PluginWorkspaceResult } from "./workspace-provider.js";
import type { PluginEnvironmentTaskParams, PluginEnvironmentTaskResult } from "./environment-tasks.js";
import type { PluginAgentRuntimeState } from "./types.js";
import type { AgentLifecycleRequest, AgentLifecycleResult } from "@paperclipai/shared";
@@ -1394,6 +1395,7 @@ export interface HostToWorkerMethods {
params: PluginEnvironmentValidateConfigParams,
result: PluginEnvironmentValidationResult,
];
+ workspaceOperation: [params: PluginWorkspaceParams, result: PluginWorkspaceResult];
environmentTask: [params: PluginEnvironmentTaskParams, result: PluginEnvironmentTaskResult];
environmentProbe: [
params: PluginEnvironmentProbeParams,
@@ -1515,6 +1517,7 @@ export const HOST_TO_WORKER_OPTIONAL_METHODS: readonly HostToWorkerMethodName[]
"handleApiRequest",
"agentLifecycle",
"resourceLifecycle",
+ "workspaceOperation",
"getData",
"performAction",
"executeTool",
diff --git a/packages/plugins/sdk/src/testing.ts b/packages/plugins/sdk/src/testing.ts
index cbfdca2114..58f2bcf85c 100644
--- a/packages/plugins/sdk/src/testing.ts
+++ b/packages/plugins/sdk/src/testing.ts
@@ -2837,3 +2837,12 @@ export function createEnvironmentTestHarness(options: EnvironmentTestHarnessOpti
return envHarness;
}
+
+/** Run the same operation/result validation as the worker RPC boundary. */
+export function createWorkspaceProviderHarness(handler: (params: import("./workspace-provider.js").PluginWorkspaceParams) => Promise<import("./workspace-provider.js").PluginWorkspaceResult>) {
+ return { async operation(params: import("./workspace-provider.js").PluginWorkspaceParams) {
+ const { pluginWorkspaceParamsSchema, parseWorkspaceProviderResult } = await import("./workspace-provider.js");
+ pluginWorkspaceParamsSchema.parse(params);
+ return parseWorkspaceProviderResult(params, await handler(params));
+ } };
+}
diff --git a/packages/plugins/sdk/src/worker-rpc-host.ts b/packages/plugins/sdk/src/worker-rpc-host.ts
index 8b98a83e64..0dbaad6e88 100644
--- a/packages/plugins/sdk/src/worker-rpc-host.ts
+++ b/packages/plugins/sdk/src/worker-rpc-host.ts
@@ -1,3 +1,5 @@
+import { workspaceProviderBindingSchema } from "@paperclipai/shared";
+import { pluginWorkspaceParamsSchema, parseWorkspaceProviderResult } from "./workspace-provider.js";
import { environmentTaskOperationSchema, parseEnvironmentTaskResult, type PluginEnvironmentTaskParams } from "./environment-tasks.js";
import type { AgentLifecycleRequest, AgentLifecycleResult } from "@paperclipai/shared";
import type { AiConnectionRouterRequest, AiConnectionRouterResult } from "@paperclipai/shared";
@@ -1666,6 +1668,11 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
return handleExecuteTool(params as ExecuteToolParams);
case "detectExternalObjects":
return handleDetectExternalObjects(params as DetectExternalObjectsParams);
+ case "workspaceOperation": {
+ if (!plugin.definition.onWorkspaceOperation) throw methodNotImplemented("workspaceOperation");
+ const input = pluginWorkspaceParamsSchema.parse(params);
+ return parseWorkspaceProviderResult(input, await plugin.definition.onWorkspaceOperation(input));
+ }
case "resourceLifecycle":
if (!plugin.definition.onResourceLifecycle) throw methodNotImplemented("resourceLifecycle");
return plugin.definition.onResourceLifecycle(params as ResourceLifecycleEvent);
@@ -1686,6 +1693,7 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
case "environmentTask": {
if (!plugin.definition.onEnvironmentTask) throw methodNotImplemented("environmentTask");
const input = params as PluginEnvironmentTaskParams;
+ if (input.workspace !== undefined) workspaceProviderBindingSchema.parse(input.workspace);
const operation = environmentTaskOperationSchema.parse(input.operation);
return parseEnvironmentTaskResult(operation, input.taskId, await plugin.definition.onEnvironmentTask({ ...input, operation }));
}
@@ -1786,6 +1794,9 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
}
manifest = params.manifest;
+ if (manifest.workspaceProvider && (!plugin.definition.onWorkspaceOperation || !plugin.definition.onResourceLifecycle)) {
+ throw new Error("Workspace provider requires workspace operations and project lifecycle handlers");
+ }
currentConfig = params.config;
databaseNamespace = params.databaseNamespace ?? null;
@@ -1803,6 +1814,7 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
if (plugin.definition.onIdleDrain) supportedMethods.push("prepareIdleSleep", "releaseIdleSleep");
if (plugin.definition.onApiRequest) supportedMethods.push("handleApiRequest");
if (plugin.definition.onDetectExternalObjects) supportedMethods.push("detectExternalObjects");
+ if (plugin.definition.onWorkspaceOperation) supportedMethods.push("workspaceOperation");
if (plugin.definition.onResourceLifecycle) supportedMethods.push("resourceLifecycle");
if (plugin.definition.onAgentLifecycle) supportedMethods.push("agentLifecycle");
if (plugin.definition.onRouteAiConnection) supportedMethods.push("routeAiConnection");
diff --git a/packages/plugins/sdk/src/workspace-provider.ts b/packages/plugins/sdk/src/workspace-provider.ts
new file mode 100644
index 0000000000..795c59981b
--- /dev/null
+++ b/packages/plugins/sdk/src/workspace-provider.ts
@@ -0,0 +1,132 @@
+import { z } from "zod";
+import { workspaceProviderBindingSchema } from "@paperclipai/shared";
+
+const sha = z.string().regex(/^[a-f0-9]{40,64}$/);
+export const workspaceProviderOperationSchema = z.discriminatedUnion("kind", [
+ z
+ .object({
+ kind: z.literal("prepare"),
+ source: z
+ .object({
+ id: z.string().uuid(),
+ revision: z.string().min(1).max(256),
+ repoUrl: z.string().url().nullable(),
+ repoRef: z.string().nullable(),
+ defaultRef: z.string().nullable(),
+ })
+ .strict(),
+ mode: z.enum([
+ "shared_workspace",
+ "isolated_workspace",
+ "operator_branch",
+ ]),
+ strategy: z.enum(["project_primary", "git_worktree"]),
+ branchName: z.string().min(1).max(256).nullable(),
+ branchMode: z.enum(["create", "existing"]).optional(),
+ baseRef: z.string().nullable(),
+ existing: workspaceProviderBindingSchema.nullable(),
+ })
+ .strict(),
+ z
+ .object({
+ kind: z.literal("inspect"),
+ binding: workspaceProviderBindingSchema,
+ })
+ .strict(),
+ z
+ .object({
+ kind: z.literal("remove"),
+ binding: workspaceProviderBindingSchema,
+ expectedHeadSha: sha.nullable(),
+ })
+ .strict(),
+]);
+export const workspaceProviderResultSchema = z.discriminatedUnion("kind", [
+ z
+ .object({
+ kind: z.literal("prepared"),
+ binding: workspaceProviderBindingSchema,
+ branchName: z.string().min(1).max(256).nullable(),
+ baseSha: sha.nullable(),
+ created: z.boolean(),
+ branchCreatedByRuntime: z.boolean(),
+ })
+ .strict(),
+ z
+ .object({
+ kind: z.literal("inspection"),
+ headSha: sha.nullable(),
+ branchName: z.string().nullable(),
+ hasDirtyTrackedFiles: z.boolean(),
+ hasUntrackedFiles: z.boolean(),
+ hasLocalOnlyData: z.boolean(),
+ isMergedIntoBase: z.boolean().nullable(),
+ remotelyRecoverable: z.boolean().nullable(),
+ })
+ .strict(),
+ // Return only after removal is confirmed. Busy, failed and uncertain operations must throw.
+ z.object({ kind: z.literal("removed") }).strict(),
+]);
+export type PluginWorkspaceOperation = z.infer<
+ typeof workspaceProviderOperationSchema
+>;
+export type PluginWorkspaceResult = z.infer<
+ typeof workspaceProviderResultSchema
+>;
+export const pluginWorkspaceParamsSchema = z
+ .object({
+ pluginId: z.string().uuid(),
+ companyId: z.string().uuid(),
+ projectId: z.string().uuid(),
+ executionWorkspaceId: z.string().uuid(),
+ /** Stable across ambiguous retries; reconcile before repeating effects. */
+ operationId: z.string().min(1).max(256),
+ generation: z.number().int().nonnegative(),
+ deadline: z.string().datetime(),
+ runId: z.string().uuid().nullable(),
+ agentId: z.string().uuid().nullable(),
+ operation: workspaceProviderOperationSchema,
+ })
+ .strict();
+/** Run and agent are optional context. Storage operations never require an execution lease. */
+export type PluginWorkspaceParams = z.infer<typeof pluginWorkspaceParamsSchema>;
+
+export function parseWorkspaceProviderResult(
+ params: PluginWorkspaceParams,
+ value: unknown,
+): PluginWorkspaceResult {
+ const result = workspaceProviderResultSchema.parse(value);
+ const expected =
+ params.operation.kind === "prepare"
+ ? "prepared"
+ : params.operation.kind === "inspect"
+ ? "inspection"
+ : "removed";
+ if (result.kind !== expected)
+ throw new Error("Workspace provider returned the wrong operation result");
+ if (
+ result.kind === "prepared" &&
+ (result.binding.pluginId !== params.pluginId ||
+ result.binding.executionWorkspaceId !== params.executionWorkspaceId ||
+ result.binding.projectId !== params.projectId ||
+ result.binding.projectWorkspaceId !==
+ (params.operation.kind === "prepare"
+ ? params.operation.source.id
+ : undefined) ||
+ result.binding.sourceRevision !==
+ (params.operation.kind === "prepare"
+ ? params.operation.source.revision
+ : undefined))
+ ) {
+ throw new Error("Workspace provider returned a different source binding");
+ }
+ if (
+ result.kind === "prepared" &&
+ params.operation.kind === "prepare" &&
+ params.operation.branchName &&
+ result.branchName !== params.operation.branchName
+ ) {
+ throw new Error("Workspace provider returned a different branch");
+ }
+ return result;
+}
diff --git a/packages/plugins/sdk/tests/workspace-provider.test.ts b/packages/plugins/sdk/tests/workspace-provider.test.ts
new file mode 100644
index 0000000000..14b9f6af83
--- /dev/null
+++ b/packages/plugins/sdk/tests/workspace-provider.test.ts
@@ -0,0 +1,119 @@
+import { describe, expect, it } from "vitest";
+import {
+ workspaceProviderOperationSchema,
+ parseWorkspaceProviderResult,
+ type PluginWorkspaceParams,
+} from "../src/workspace-provider.js";
+import { createWorkspaceProviderHarness } from "../src/testing.js";
+import { pluginManifestV1Schema } from "@paperclipai/shared";
+const id = (n: number) =>
+ `10000000-0000-4000-8000-${String(n).padStart(12, "0")}`;
+const params: PluginWorkspaceParams = {
+ pluginId: id(1),
+ companyId: id(2),
+ projectId: id(3),
+ executionWorkspaceId: id(4),
+ operationId: "stable",
+ generation: 0,
+ deadline: "2099-01-01T00:00:00Z",
+ runId: null,
+ agentId: null,
+ operation: {
+ kind: "prepare",
+ source: {
+ id: id(5),
+ revision: "source-v1",
+ repoUrl: "https://github.com/example/repo.git",
+ repoRef: null,
+ defaultRef: "main",
+ },
+ mode: "isolated_workspace",
+ strategy: "git_worktree",
+ branchName: "task",
+ baseRef: "main",
+ existing: null,
+ },
+};
+const result = {
+ kind: "prepared" as const,
+ binding: {
+ pluginId: id(1),
+ projectId: id(3),
+ executionWorkspaceId: id(4),
+ projectWorkspaceId: id(5),
+ sourceRevision: "source-v1",
+ workspaceRef: "opaque",
+ },
+ branchName: "task",
+ baseSha: "a".repeat(40),
+ created: true,
+ branchCreatedByRuntime: true,
+};
+describe("workspace provider SDK", () => {
+ it("prepares without a VM, lease, or host path", async () => {
+ const harness = createWorkspaceProviderHarness(async (input) => {
+ expect(input.agentId).toBeNull();
+ expect(input).not.toHaveProperty("lease");
+ expect(input.operation).not.toHaveProperty("localPath");
+ return result;
+ });
+ expect(await harness.operation(params)).toEqual(result);
+ });
+ it("rejects unrelated operation results and changed source revisions", () => {
+ expect(() =>
+ parseWorkspaceProviderResult(params, { kind: "removed" }),
+ ).toThrow();
+ expect(() =>
+ parseWorkspaceProviderResult(params, {
+ ...result,
+ binding: { ...result.binding, sourceRevision: "other" },
+ }),
+ ).toThrow();
+ expect(() =>
+ parseWorkspaceProviderResult(params, {
+ ...result,
+ binding: { ...result.binding, executionWorkspaceId: id(99) },
+ }),
+ ).toThrow();
+ expect(() =>
+ parseWorkspaceProviderResult(params, { ...result, branchName: "wrong" }),
+ ).toThrow();
+ expect(() =>
+ workspaceProviderOperationSchema.parse({
+ ...params.operation,
+ shell: "arbitrary",
+ }),
+ ).toThrow();
+ });
+ it("requires project lifecycle and storage management as one contract", () => {
+ const manifest = {
+ id: "test.storage",
+ apiVersion: 1,
+ version: "1.0.0",
+ displayName: "Storage",
+ description: "Storage",
+ author: "Test",
+ categories: ["workspace"],
+ entrypoints: { worker: "./worker.js" },
+ workspaceProvider: {
+ modes: ["isolated_workspace", "operator_branch"],
+ strategies: ["git_worktree"],
+ },
+ capabilities: ["workspaces.manage", "events.subscribe"],
+ resourceLifecycle: ["project"],
+ };
+ expect(pluginManifestV1Schema.safeParse(manifest).success).toBe(true);
+ expect(
+ pluginManifestV1Schema.safeParse({
+ ...manifest,
+ resourceLifecycle: ["agent"],
+ }).success,
+ ).toBe(false);
+ expect(
+ pluginManifestV1Schema.safeParse({
+ ...manifest,
+ capabilities: ["events.subscribe"],
+ }).success,
+ ).toBe(false);
+ });
+});
diff --git a/packages/shared/src/constants.ts b/packages/shared/src/constants.ts
index 75e600397e..5bb9bf3484 100644
--- a/packages/shared/src/constants.ts
+++ b/packages/shared/src/constants.ts
@@ -1325,6 +1325,7 @@ export const PLUGIN_CAPABILITIES = [
"projects.read",
"project.workspaces.read",
"execution.workspaces.read",
+ "workspaces.manage",
"issues.read",
"issue.relations.read",
"issue.subtree.read",
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index a197a46de5..ed30d7c210 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -2832,3 +2832,5 @@ export { HUMAN_TASK_ORIGIN_KINDS, isAgentCreatedIssue, type IssueCreationSourceF
export * from "./grok-bot.js";
export * from "./agent-observability.js";
export * from "./prompt-injection-prevention.js";
+
+export * from "./workspace-provider.js";
diff --git a/packages/shared/src/types/plugin.ts b/packages/shared/src/types/plugin.ts
index bbfb2c97a0..9fe0b39a7d 100644
--- a/packages/shared/src/types/plugin.ts
+++ b/packages/shared/src/types/plugin.ts
@@ -691,6 +691,11 @@ export interface PaperclipPluginManifestV1 {
capabilities: PluginCapability[];
/** Required participant in agent preparation, stop, resume, and cleanup. */
agentLifecycle?: true;
+ /** Own project storage and durable workspace operations as one contract. */
+ workspaceProvider?: {
+ modes: Array<"shared_workspace" | "isolated_workspace" | "operator_branch">;
+ strategies: Array<"project_primary" | "git_worktree">;
+ };
/** Durable, acknowledged resource events delivered to onResourceLifecycle. Requires events.subscribe. */
resourceLifecycle?: Array<"agent" | "project" | "agent_runtime">;
/** Opt into the native pooled-connection catalog, setup, and management UI. */
diff --git a/packages/shared/src/types/workspace-runtime.ts b/packages/shared/src/types/workspace-runtime.ts
index b6a3fe7552..88d81fec11 100644
--- a/packages/shared/src/types/workspace-runtime.ts
+++ b/packages/shared/src/types/workspace-runtime.ts
@@ -24,6 +24,7 @@ export type ExecutionWorkspaceMode =
export type SharedWorkspaceConcurrency = "auto" | "serialize" | "allow";
export type ExecutionWorkspaceProviderType =
+ | "plugin"
| "local_fs"
| "git_worktree"
| "adapter_managed"
@@ -52,6 +53,7 @@ export type ExecutionWorkspaceCloseActionKind =
| "stop_runtime_services"
| "cleanup_command"
| "teardown_command"
+ | "remove_provider_workspace"
| "git_worktree_remove"
| "git_branch_delete"
| "remove_local_directory";
@@ -98,6 +100,7 @@ export interface ExecutionWorkspaceStrategy {
export interface ExecutionWorkspaceConfig {
environmentId?: string | null;
+ storageProviderPluginId?: string | null;
provisionCommand: string | null;
runtimeProvisionCommand?: string | null;
teardownCommand: string | null;
@@ -135,6 +138,8 @@ export interface ExecutionWorkspaceCloseLinkedIssue {
}
export interface ExecutionWorkspaceCloseGitReadiness {
+ /** Verified remotely for provider-managed workspaces. */
+ headSha?: string | null;
repoRoot: string | null;
workspacePath: string | null;
branchName: string | null;
@@ -345,6 +350,8 @@ export interface WorkspaceRealizationRequest {
source: {
kind: "project_primary" | "task_session" | "agent_home";
localPath: string;
+ /** When present, localPath is a logical execution location, never a Core filesystem root. */
+ providerBinding?: import("../workspace-provider.js").WorkspaceProviderBinding;
projectId: string | null;
projectWorkspaceId: string | null;
repoUrl: string | null;
diff --git a/packages/shared/src/validators/execution-workspace.ts b/packages/shared/src/validators/execution-workspace.ts
index 5f8874e5a0..debae3727a 100644
--- a/packages/shared/src/validators/execution-workspace.ts
+++ b/packages/shared/src/validators/execution-workspace.ts
@@ -64,6 +64,7 @@ export const executionWorkspaceCloseActionKindSchema = z.enum([
"stop_runtime_services",
"cleanup_command",
"teardown_command",
+ "remove_provider_workspace",
"git_worktree_remove",
"git_branch_delete",
"remove_local_directory",
@@ -97,6 +98,7 @@ export const executionWorkspaceCloseGitReadinessSchema = z.object({
behindCount: z.number().int().nonnegative().nullable(),
isMergedIntoBase: z.boolean().nullable(),
createdByRuntime: z.boolean(),
+ headSha: z.string().nullable().optional(),
}).strict();
export const workspaceRuntimeServiceSchema = z.object({
diff --git a/packages/shared/src/validators/plugin.ts b/packages/shared/src/validators/plugin.ts
index 5cc7d174c4..3f9b33dd60 100644
--- a/packages/shared/src/validators/plugin.ts
+++ b/packages/shared/src/validators/plugin.ts
@@ -784,6 +784,10 @@ export const pluginManifestV1Schema = z.object({
).optional(),
capabilities: z.array(z.enum(PLUGIN_CAPABILITIES)).min(1),
agentLifecycle: z.literal(true).optional(),
+ workspaceProvider: z.object({
+ modes: z.array(z.enum(["shared_workspace", "isolated_workspace", "operator_branch"])).min(1).max(3),
+ strategies: z.array(z.enum(["project_primary", "git_worktree"])).min(1).max(2),
+ }).strict().optional(),
resourceLifecycle: z.array(z.enum(["agent", "project", "agent_runtime"])).min(1).max(3).optional(),
aiConnectionRouter: z.object({ name: z.string().trim().min(1).max(100), description: z.string().trim().min(1).max(500) }).strict().optional(),
entrypoints: z.object({
@@ -813,6 +817,9 @@ export const pluginManifestV1Schema = z.object({
ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Agent lifecycle participation requires agents.lifecycle.manage", path: ["capabilities"] });
}
+ if (manifest.workspaceProvider && (!manifest.capabilities.includes("workspaces.manage") || !manifest.resourceLifecycle?.includes("project"))) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["workspaceProvider"], message: "Workspace providers require workspaces.manage and project resource lifecycle" });
+ }
if (manifest.resourceLifecycle && !manifest.capabilities.includes("events.subscribe")) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Resource lifecycle delivery requires events.subscribe", path: ["capabilities"] });
}
diff --git a/packages/shared/src/validators/project.ts b/packages/shared/src/validators/project.ts
index 11b8eb7d83..61839f7a1b 100644
--- a/packages/shared/src/validators/project.ts
+++ b/packages/shared/src/validators/project.ts
@@ -29,6 +29,7 @@ export const projectExecutionWorkspacePolicySchema = z
allowIssueOverride: z.boolean().optional(),
defaultProjectWorkspaceId: z.string().guid().optional().nullable(),
environmentId: z.string().guid().optional().nullable(),
+ storageProviderPluginId: z.string().uuid().optional().nullable(),
workspaceStrategy: executionWorkspaceStrategySchema.optional().nullable(),
workspaceRuntime: z.record(z.string(), z.unknown()).optional().nullable(),
branchPolicy: z.record(z.string(), z.unknown()).optional().nullable(),
diff --git a/packages/shared/src/workspace-provider.ts b/packages/shared/src/workspace-provider.ts
new file mode 100644
index 0000000000..d1451e2b5c
--- /dev/null
+++ b/packages/shared/src/workspace-provider.ts
@@ -0,0 +1,25 @@
+import { z } from "zod";
+
+/** Durable addressing only. Credentials and execution-host paths are never part of this record. */
+export const workspaceProviderBindingSchema = z
+ .object({
+ pluginId: z.string().uuid(),
+ projectId: z.string().uuid(),
+ executionWorkspaceId: z.string().uuid(),
+ projectWorkspaceId: z.string().uuid(),
+ sourceRevision: z.string().min(1).max(256),
+ workspaceRef: z.string().min(1).max(4096),
+ })
+ .strict();
+export type WorkspaceProviderBinding = z.infer<
+ typeof workspaceProviderBindingSchema
+>;
+
+export function readWorkspaceProviderBinding(
+ metadata: Record<string, unknown> | null | undefined,
+): WorkspaceProviderBinding | null {
+ const parsed = workspaceProviderBindingSchema.safeParse(
+ metadata?.workspaceProvider,
+ );
+ return parsed.success ? parsed.data : null;
+}
diff --git a/server/src/__tests__/environment-task-runtime.test.ts b/server/src/__tests__/environment-task-runtime.test.ts
index b49cb3776d..eb5f7b6378 100644
--- a/server/src/__tests__/environment-task-runtime.test.ts
+++ b/server/src/__tests__/environment-task-runtime.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { PgDialect } from "drizzle-orm/pg-core";
-import type { Db } from "@paperclipai/db";
+import { executionWorkspaces, type Db } from "@paperclipai/db";
import { environmentTaskOperationSchema, parseEnvironmentTaskResult } from "@paperclipai/plugin-sdk";
import { executeEnvironmentTask } from "../services/environment-task-runtime.js";
@@ -15,9 +15,10 @@ const row = () => ({
environment: { id: "environment", config: { pluginKey: "test.provider", driverKey: "tasks", driverConfig: {} } } as { id: string; config: Record<string, unknown> } | null,
run: { id: "run", agentId: "agent", status: "running" } as { id: string; agentId: string; status: string } | null,
});
-function database(value: ReturnType<typeof row> | null = row(), projectRows = [{ id: projectId }]) {
+function database(value: ReturnType<typeof row> | null = row(), projectRows = [{ id: projectId }], workspaceRows: unknown[] = []) {
+ let selectedRows: unknown[] = projectRows;
const results = [value ? [value] : [], [{ id: "issue" }]];
- const query: any = { from: () => query, leftJoin: () => query, where: vi.fn(() => query), limit: () => Promise.resolve(results.shift()), then: (resolve: (rows: typeof projectRows) => unknown) => Promise.resolve(projectRows).then(resolve) };
+ const query: any = { from: (table: unknown) => { selectedRows = table === executionWorkspaces ? workspaceRows : projectRows; return query; }, leftJoin: () => query, where: vi.fn(() => query), limit: () => Promise.resolve(results.shift()), then: (resolve: (rows: typeof projectRows) => unknown) => Promise.resolve(selectedRows).then(resolve as (rows: unknown[]) => unknown) };
const update: any = { set: () => update, where: () => update,
returning: async () => [{ id: leaseId }], then: (resolve: (value: unknown) => unknown) => Promise.resolve([]).then(resolve) };
return { db: { select: () => query, update: () => update } as unknown as Db, query };
@@ -31,6 +32,22 @@ beforeEach(() => {
state.plugin = { id: "original", pluginKey: "test.provider", status: "ready", manifestJson: { capabilities: ["environment.drivers.register"], environmentDrivers: [{ driverKey: "tasks", supportsTasks: true }] } };
});
describe("plugin-provided Runner execution", () => {
+ it("passes only the workspace binding pinned to this lease and provider", async () => {
+ const value = row();
+ const binding = { pluginId: leaseId, projectId, executionWorkspaceId: secondProjectId, projectWorkspaceId: projectId,
+ sourceRevision: "revision", workspaceRef: "provider:checkout" };
+ state.plugin.id = binding.pluginId;
+ Object.assign(value.lease, { executionWorkspaceId: binding.executionWorkspaceId });
+ Object.assign(value.lease.metadata, { pluginId: binding.pluginId, workspaceProvider: binding });
+ const workspace = { id: binding.executionWorkspaceId, companyId: "company", providerType: "plugin", providerRef: binding.workspaceRef,
+ status: "active", metadata: { workspaceProvider: binding } };
+ const workers = worker();
+ await executeEnvironmentTask(database(value, [], [workspace]).db, workers as never, { companyId: "company", leaseId, operation: { ...submit, projectIds: [] } });
+ expect(workers.call).toHaveBeenCalledWith(binding.pluginId, "environmentTask", expect.objectContaining({ workspace: binding }), 15_000);
+ const denied = worker(); workspace.providerRef = "foreign";
+ await expect(executeEnvironmentTask(database(value, [], [workspace]).db, denied as never, { companyId: "company", leaseId, operation: { ...submit, projectIds: [] } })).rejects.toThrow("binding changed");
+ expect(denied.call).not.toHaveBeenCalled();
+ });
it("accepts artifact identity and excludes filesystem transfer from the contract", () => {
const operation = environmentTaskOperationSchema.parse({ kind: "describe" });
const description = { kind: "description", taskId: "attempt-1", runner: { version: "fixture", digest: `sha256:${"a".repeat(64)}` } };
diff --git a/server/src/__tests__/helpers/plugin-workspaces.ts b/server/src/__tests__/helpers/plugin-workspaces.ts
new file mode 100644
index 0000000000..31cc69c154
--- /dev/null
+++ b/server/src/__tests__/helpers/plugin-workspaces.ts
@@ -0,0 +1,194 @@
+import { randomUUID } from "node:crypto";
+import { expect } from "vitest";
+import {
+ agents,
+ companies,
+ createDb,
+ heartbeatRuns,
+ issues,
+ plugins,
+ projects,
+ projectWorkspaces,
+} from "@paperclipai/db";
+import type { WorkspaceWorkers } from "../../services/plugin-workspaces.js";
+
+export async function createPluginWorkspaceFixture(
+ db: ReturnType<typeof createDb>,
+ existingCompanyId?: string,
+) {
+ const companyId = existingCompanyId ?? randomUUID(),
+ agentId = randomUUID(),
+ projectId = randomUUID(),
+ sourceId = randomUUID(),
+ pluginId = randomUUID(),
+ issueId = randomUUID(),
+ runId = randomUUID();
+ if (!existingCompanyId)
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Storage fixture",
+ issuePrefix: companyId.slice(0, 8).toUpperCase(),
+ });
+ await db.insert(agents).values({
+ id: agentId,
+ companyId,
+ name: "Worker",
+ role: "engineer",
+ status: "idle",
+ adapterType: "paperclip_runner",
+ });
+ await db.insert(plugins).values({
+ id: pluginId,
+ pluginKey: `test.${pluginId}`,
+ packageName: "test-storage",
+ version: "1.0.0",
+ apiVersion: 1,
+ status: "ready",
+ categories: ["workspace"],
+ manifestJson: {
+ id: `test.${pluginId}`,
+ apiVersion: 1,
+ version: "1.0.0",
+ displayName: "Storage",
+ description: "Storage",
+ author: "Test",
+ categories: ["workspace"],
+ capabilities: ["workspaces.manage", "events.subscribe"],
+ resourceLifecycle: ["project"],
+ workspaceProvider: {
+ modes: ["isolated_workspace", "operator_branch"],
+ strategies: ["git_worktree"],
+ },
+ entrypoints: { worker: "./worker.js" },
+ },
+ });
+ await db.insert(projects).values({
+ id: projectId,
+ companyId,
+ name: "Project",
+ status: "in_progress",
+ executionWorkspacePolicy: {
+ enabled: true,
+ storageProviderPluginId: pluginId,
+ },
+ });
+ await db.insert(projectWorkspaces).values({
+ id: sourceId,
+ companyId,
+ projectId,
+ name: "Repository",
+ sourceType: "remote_managed",
+ repoUrl: "https://github.com/example/repo.git",
+ cwd: null,
+ isPrimary: true,
+ });
+ await db.insert(issues).values({
+ id: issueId,
+ companyId,
+ projectId,
+ projectWorkspaceId: sourceId,
+ title: "Task",
+ status: "in_progress",
+ assigneeAgentId: agentId,
+ });
+ await db.insert(heartbeatRuns).values({
+ id: runId,
+ companyId,
+ agentId,
+ issueId,
+ invocationSource: "manual",
+ status: "running",
+ });
+ const calls: any[] = [];
+ let loseResponse = false,
+ dirty = false,
+ removed = false,
+ loseRemovalResponse = false,
+ workspaceRefSuffix = "";
+ const workers = {
+ getWorker: (id: string) =>
+ id === pluginId
+ ? { supportedMethods: ["workspaceOperation"] }
+ : undefined,
+ call: async (_id: string, method: string, params: any) => {
+ expect(method).toBe("workspaceOperation");
+ expect(params).not.toHaveProperty("lease");
+ calls.push(params);
+ if (loseResponse) {
+ loseResponse = false;
+ throw new Error("lost result");
+ }
+ if (params.operation.kind === "prepare") {
+ removed = false;
+ return {
+ kind: "prepared",
+ binding: {
+ pluginId,
+ projectId,
+ executionWorkspaceId: params.executionWorkspaceId,
+ projectWorkspaceId: sourceId,
+ sourceRevision: params.operation.source.revision,
+ workspaceRef: `checkout:${params.executionWorkspaceId}${workspaceRefSuffix}`,
+ },
+ branchName: params.operation.branchName,
+ baseSha: "a".repeat(40),
+ created: true,
+ branchCreatedByRuntime: true,
+ };
+ }
+ if (params.operation.kind === "inspect") {
+ if (removed) throw new Error("checkout missing");
+ return {
+ kind: "inspection",
+ headSha: "a".repeat(40),
+ branchName: "work",
+ hasDirtyTrackedFiles: dirty,
+ hasUntrackedFiles: false,
+ hasLocalOnlyData: false,
+ isMergedIntoBase: true,
+ remotelyRecoverable: true,
+ };
+ }
+ removed = true;
+ if (loseRemovalResponse) {
+ loseRemovalResponse = false;
+ throw new Error("lost removal response");
+ }
+ return { kind: "removed" };
+ },
+ } as unknown as WorkspaceWorkers;
+ const input = {
+ companyId,
+ projectId,
+ projectWorkspaceId: sourceId,
+ issueId,
+ runId,
+ agentId,
+ responsibleUserId: null,
+ existingWorkspaceId: null as string | null,
+ mode: "isolated_workspace",
+ strategy: "git_worktree",
+ branchName: "work",
+ };
+ return {
+ companyId,
+ pluginId,
+ issueId,
+ runId,
+ input,
+ calls,
+ workers,
+ relocate: () => {
+ workspaceRefSuffix = ":restored";
+ },
+ loseRemoval: () => {
+ loseRemovalResponse = true;
+ },
+ lose: () => {
+ loseResponse = true;
+ },
+ dirty: () => {
+ dirty = true;
+ },
+ };
+}
diff --git a/server/src/__tests__/plugin-workspaces.integration.test.ts b/server/src/__tests__/plugin-workspaces.integration.test.ts
new file mode 100644
index 0000000000..7f3952b5f8
--- /dev/null
+++ b/server/src/__tests__/plugin-workspaces.integration.test.ts
@@ -0,0 +1,973 @@
+import { createPluginWorkspaceFixture } from "./helpers/plugin-workspaces.js";
+import { randomUUID } from "node:crypto";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { and, eq, sql } from "drizzle-orm";
+import {
+ createDb,
+ subscribeDatabaseWork,
+ executionWorkspaces,
+ heartbeatRuns,
+ issues,
+ plugins,
+ pluginCompanySettings,
+} from "@paperclipai/db";
+import {
+ preparePluginWorkspace,
+ inspectPluginWorkspace,
+ removePluginWorkspace,
+ type WorkspaceWorkers,
+} from "../services/plugin-workspaces.js";
+import { executionWorkspaceService } from "../services/execution-workspaces.js";
+import { projectService } from "../services/projects.js";
+import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
+import {
+ getEmbeddedPostgresTestSupport,
+ startEmbeddedPostgresTestDatabase,
+} from "./helpers/embedded-postgres.js";
+const support = await getEmbeddedPostgresTestSupport();
+(support.supported ? describe : describe.skip)(
+ "plugin workspace ownership",
+ () => {
+ let db: ReturnType<typeof createDb>,
+ stopDb: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ const started =
+ await startEmbeddedPostgresTestDatabase("plugin-workspaces");
+ db = createDb(started.connectionString, { maxConnections: 1 });
+ stopDb = started.stop;
+ });
+ afterAll(async () => {
+ await db?.$client.end();
+ await stopDb?.();
+ });
+ const fixture = (companyId?: string) =>
+ createPluginWorkspaceFixture(db, companyId);
+ it("keeps the single-connection pool responsive while provider preparation holds its lifecycle lock", async () => {
+ const f = await fixture();
+ let entered!: () => void, release!: () => void;
+ const started = new Promise<void>((resolve) => {
+ entered = resolve;
+ });
+ const resume = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const call = f.workers.call.bind(f.workers);
+ f.workers.call = async (...args) => {
+ if ((args[2] as any).operation.kind === "prepare") {
+ entered();
+ await resume;
+ }
+ return call(...args);
+ };
+ const preparing = preparePluginWorkspace(db, f.workers, f.input);
+ await started;
+ try {
+ await expect(
+ projectService(db).updateWorkspace(
+ f.input.projectId,
+ f.input.projectWorkspaceId,
+ { repoRef: "next" },
+ ),
+ ).rejects.toThrow("Workspace lifecycle is busy");
+ expect(await db.execute(sql`select 1 as usable`)).toMatchObject([
+ { usable: 1 },
+ ]);
+ } finally {
+ release();
+ }
+ const workspace = await preparing;
+ await expect(
+ inspectPluginWorkspace(db, f.workers, workspace!),
+ ).resolves.toMatchObject({ kind: "inspection" });
+ });
+ it("preserves a scheduled selection through the first provider binding and next admission", async () => {
+ const f = await fixture();
+ const svc = executionWorkspaceService(db, {
+ pluginWorkerManager: f.workers,
+ });
+ const actor = {
+ type: "board" as const,
+ source: "local_implicit" as const,
+ isInstanceAdmin: true,
+ };
+ const request = {
+ companyId: f.companyId,
+ issueId: f.issueId,
+ actor,
+ selection: { kind: "task_directory" as const },
+ expectedBindingRevision: 0,
+ requestKey: "during-prepare",
+ };
+ await svc.selectTaskWorkspace(request);
+ await preparePluginWorkspace(db, f.workers, f.input);
+ expect(
+ await svc.inspectTaskWorkspace(f.companyId, f.issueId, actor),
+ ).toMatchObject({
+ bindingRevision: 2,
+ pendingSelection: {
+ expectedBindingRevision: 2,
+ intent: { request: { expectedBindingRevision: 0 } },
+ },
+ });
+ await db
+ .update(heartbeatRuns)
+ .set({ status: "succeeded" })
+ .where(eq(heartbeatRuns.id, f.runId));
+ expect(
+ await svc.applyPendingTaskWorkspaceSelection({
+ companyId: f.companyId,
+ issueId: f.issueId,
+ runId: randomUUID(),
+ actor,
+ }),
+ ).toBe(true);
+ expect(await svc.selectTaskWorkspace(request)).toMatchObject({
+ kind: "applied",
+ });
+ });
+ it("does not retire reusable storage for rejected or normalized unchanged source edits", async () => {
+ const f = await fixture(),
+ workspace = await preparePluginWorkspace(db, f.workers, f.input);
+ await db
+ .update(executionWorkspaces)
+ .set({ status: "archived", closedAt: new Date() })
+ .where(eq(executionWorkspaces.id, workspace!.id));
+ await removePluginWorkspace(db, f.workers, workspace!, "a".repeat(40));
+ expect(
+ await projectService(db).updateWorkspace(
+ f.input.projectId,
+ f.input.projectWorkspaceId,
+ { repoRef: " " },
+ ),
+ ).toMatchObject({ repoRef: null });
+ expect(
+ await projectService(db).updateWorkspace(
+ f.input.projectId,
+ f.input.projectWorkspaceId,
+ { repoUrl: null },
+ ),
+ ).toBeNull();
+ const [row] = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, workspace!.id));
+ expect(row.metadata?.workspaceProviderRetired).not.toBe(true);
+ expect(
+ await executionWorkspaceService(db, {
+ pluginWorkerManager: f.workers,
+ }).reopenClosedIsolatedExecutionWorkspaceForIssue({
+ workspaceId: workspace!.id,
+ issue: {
+ id: f.issueId,
+ companyId: f.companyId,
+ projectId: f.input.projectId,
+ },
+ actor: { actorType: "user", agentId: null },
+ authorizationActor: {
+ type: "board",
+ source: "local_implicit",
+ isInstanceAdmin: true,
+ },
+ }),
+ ).toMatchObject({ ok: true, reopened: true });
+ });
+ it("uses new inspection identities even when the provider caches operation results", async () => {
+ const f = await fixture(),
+ workspace = await preparePluginWorkspace(db, f.workers, f.input);
+ const call = f.workers.call.bind(f.workers),
+ cache = new Map<string, unknown>();
+ f.workers.call = async (...args) => {
+ const params = args[2] as any;
+ if (cache.has(params.operationId))
+ return cache.get(params.operationId) as any;
+ const result = await call(...args);
+ cache.set(params.operationId, result);
+ return result;
+ };
+ expect(
+ await inspectPluginWorkspace(db, f.workers, workspace!),
+ ).toMatchObject({ hasDirtyTrackedFiles: false });
+ f.dirty();
+ expect(
+ await inspectPluginWorkspace(db, f.workers, workspace!),
+ ).toMatchObject({ hasDirtyTrackedFiles: true });
+ expect(cache.size).toBe(2);
+ });
+ it("retries closed storage cleanup when the pre-delete inspection failed before recording removal", async () => {
+ const f = await fixture(),
+ workspace = await preparePluginWorkspace(db, f.workers, f.input);
+ await db
+ .update(issues)
+ .set({ status: "done", completedAt: new Date() })
+ .where(eq(issues.id, f.issueId));
+ await db
+ .update(heartbeatRuns)
+ .set({ status: "succeeded" })
+ .where(eq(heartbeatRuns.id, f.runId));
+ const call = f.workers.call.bind(f.workers);
+ let inspections = 0;
+ const workers = {
+ getWorker: (id: string) =>
+ id === f.pluginId
+ ? { supportedMethods: ["workspaceOperation"] }
+ : undefined,
+ call: async (...args: Parameters<WorkspaceWorkers["call"]>) => {
+ if (
+ (args[2] as any).operation.kind === "inspect" &&
+ ++inspections === 2
+ )
+ throw new Error("temporary inspection outage");
+ return call(...args);
+ },
+ } as unknown as WorkspaceWorkers;
+ const svc = executionWorkspaceService(db, {
+ pluginWorkerManager: workers,
+ workspaceReaperCooldownDays: 0,
+ });
+ const sweep = () => svc.sweepTerminalWorkspaces(100);
+ expect(await sweep()).toMatchObject({ cleanupFailed: 1 });
+ const [failed] = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, workspace!.id));
+ expect(failed.status).toBe("cleanup_failed");
+ expect(failed.metadata?.workspaceProviderRemoval).toBeUndefined();
+ expect(await svc.nextTerminalWorkspaceSweepAt()).not.toBeNull();
+ await sweep();
+ const [removed] = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, workspace!.id));
+ expect(removed.metadata?.workspaceProviderRemoved).toBe(true);
+ expect(removed.status).toBe("archived");
+ });
+ it("prepares a durable reference without a local checkout or agent allocation", async () => {
+ const f = await fixture();
+ const workspace = await preparePluginWorkspace(db, f.workers, f.input);
+ expect(workspace).toMatchObject({
+ providerType: "plugin",
+ cwd: null,
+ status: "active",
+ });
+ expect(f.calls[0].operation.source).not.toHaveProperty("cwd");
+ const [task] = await db
+ .select()
+ .from(issues)
+ .where(eq(issues.id, f.issueId));
+ expect(task.executionWorkspaceId).toBe(workspace!.id);
+ expect(
+ await inspectPluginWorkspace(db, f.workers, workspace!),
+ ).toMatchObject({ remotelyRecoverable: true });
+ });
+ it("retains the reservation and retries the same operation after a lost response", async () => {
+ const f = await fixture();
+ f.lose();
+ await expect(
+ preparePluginWorkspace(db, f.workers, f.input),
+ ).rejects.toThrow("incomplete");
+ const [task] = await db
+ .select()
+ .from(issues)
+ .where(eq(issues.id, f.issueId));
+ const result = await preparePluginWorkspace(db, f.workers, {
+ ...f.input,
+ existingWorkspaceId: task.executionWorkspaceId,
+ });
+ expect(result!.id).toBe(task.executionWorkspaceId);
+ expect(f.calls[1].operationId).toBe(f.calls[0].operationId);
+ });
+ it("reconciles a lost preparation result after the task run stops", async () => {
+ const f = await fixture();
+ f.lose();
+ await expect(
+ preparePluginWorkspace(db, f.workers, f.input),
+ ).rejects.toThrow("incomplete");
+ await db
+ .update(heartbeatRuns)
+ .set({ status: "cancelled" })
+ .where(eq(heartbeatRuns.id, f.runId));
+ const [task] = await db
+ .select()
+ .from(issues)
+ .where(eq(issues.id, f.issueId));
+ const [reservation] = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, task.executionWorkspaceId!));
+ expect(reservation.providerRef).toBeNull();
+ await expect(
+ inspectPluginWorkspace(db, f.workers, reservation),
+ ).resolves.toMatchObject({ remotelyRecoverable: true });
+ expect(f.calls[1]).toMatchObject({
+ runId: null,
+ agentId: null,
+ operation: { kind: "prepare" },
+ });
+ expect(f.calls[1].operationId).toBe(f.calls[0].operationId);
+ const [recorded] = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, reservation.id));
+ expect(recorded.providerRef).not.toBeNull();
+ });
+ it("fails closed for a disabled plugin, stopped run, and cross-company source", async () => {
+ const f = await fixture();
+ await db.insert(pluginCompanySettings).values({
+ pluginId: f.pluginId,
+ companyId: f.companyId,
+ enabled: false,
+ });
+ await expect(
+ preparePluginWorkspace(db, f.workers, f.input),
+ ).rejects.toThrow("unavailable");
+ await db
+ .update(pluginCompanySettings)
+ .set({ enabled: true })
+ .where(eq(pluginCompanySettings.pluginId, f.pluginId));
+ await db
+ .update(heartbeatRuns)
+ .set({ status: "cancelled" })
+ .where(eq(heartbeatRuns.id, f.runId));
+ await expect(
+ preparePluginWorkspace(db, f.workers, f.input),
+ ).rejects.toThrow();
+ expect(f.calls).toHaveLength(0);
+ await expect(
+ preparePluginWorkspace(db, f.workers, {
+ ...f.input,
+ companyId: randomUUID(),
+ }),
+ ).resolves.toBeNull();
+ });
+ it("keeps source ownership immutable and preserves bindings through metadata edits", async () => {
+ const f = await fixture();
+ const workspace = await preparePluginWorkspace(db, f.workers, f.input);
+ const svc = projectService(db);
+ await expect(
+ svc.update(f.input.projectId, { executionWorkspacePolicy: {} }),
+ ).rejects.toThrow("storage owner");
+ await expect(
+ svc.updateWorkspace(f.input.projectId, f.input.projectWorkspaceId, {
+ repoUrl: "https://github.com/example/other.git",
+ }),
+ ).rejects.toThrow("repository source");
+ await expect(
+ svc.removeWorkspace(f.input.projectId, f.input.projectWorkspaceId),
+ ).rejects.toThrow("repository source");
+ const execution = executionWorkspaceService(db);
+ const updated = await execution.update(workspace!.id, {
+ metadata: {
+ note: "caller edit",
+ workspaceProvider: { workspaceRef: "foreign" },
+ },
+ });
+ expect(updated!.metadata?.workspaceProvider).toEqual(
+ workspace!.metadata?.workspaceProvider,
+ );
+ await expect(
+ execution.update(workspace!.id, { providerType: "local_fs" }),
+ ).rejects.toThrow("storage plugin");
+ });
+ it("describes provider removal without promising host cleanup commands", async () => {
+ const f = await fixture();
+ const workspace = await preparePluginWorkspace(db, f.workers, f.input);
+ await db
+ .update(issues)
+ .set({ status: "done" })
+ .where(eq(issues.id, f.issueId));
+ const readiness = await executionWorkspaceService(db, {
+ pluginWorkerManager: f.workers,
+ }).getCloseReadiness(workspace!.id);
+ expect(readiness!.plannedActions).toContainEqual(
+ expect.objectContaining({
+ kind: "remove_provider_workspace",
+ command: null,
+ }),
+ );
+ expect(
+ readiness!.plannedActions.some(
+ (action) => action.kind === "git_branch_delete",
+ ),
+ ).toBe(false);
+ });
+ it("reopens through the same provider without requiring a live run or a host checkout", async () => {
+ const f = await fixture();
+ const workspace = await preparePluginWorkspace(db, f.workers, f.input);
+ await db
+ .update(heartbeatRuns)
+ .set({ status: "succeeded" })
+ .where(eq(heartbeatRuns.id, f.runId));
+ await db
+ .update(executionWorkspaces)
+ .set({ status: "archived", closedAt: new Date() })
+ .where(eq(executionWorkspaces.id, workspace!.id));
+ const result = await executionWorkspaceService(db, {
+ pluginWorkerManager: f.workers,
+ }).reopenClosedIsolatedExecutionWorkspaceForIssue({
+ workspaceId: workspace!.id,
+ issue: {
+ id: f.issueId,
+ companyId: f.companyId,
+ projectId: f.input.projectId,
+ },
+ actor: { actorType: "user", agentId: null },
+ authorizationActor: {
+ type: "board",
+ source: "local_implicit",
+ isInstanceAdmin: true,
+ },
+ });
+ expect(result).toMatchObject({
+ ok: true,
+ reopened: true,
+ generation: 1,
+ workspace: { cwd: null, providerType: "plugin" },
+ });
+ expect(f.calls.at(-1)).toMatchObject({
+ runId: null,
+ agentId: null,
+ operation: { kind: "prepare", branchMode: "existing" },
+ });
+ expect(f.calls.at(-1).operation.existing.workspaceRef).toBe(
+ workspace!.providerRef,
+ );
+ });
+ it("keeps a relocated restoration reference consistent through subsequent removal", async () => {
+ const f = await fixture();
+ const workspace = await preparePluginWorkspace(db, f.workers, f.input);
+ await db
+ .update(heartbeatRuns)
+ .set({ status: "succeeded" })
+ .where(eq(heartbeatRuns.id, f.runId));
+ await db
+ .update(executionWorkspaces)
+ .set({ status: "archived", closedAt: new Date() })
+ .where(eq(executionWorkspaces.id, workspace!.id));
+ await removePluginWorkspace(db, f.workers, workspace!, "a".repeat(40));
+ f.relocate();
+ const svc = executionWorkspaceService(db, {
+ pluginWorkerManager: f.workers,
+ });
+ const result = await svc.reopenClosedIsolatedExecutionWorkspaceForIssue({
+ workspaceId: workspace!.id,
+ issue: {
+ id: f.issueId,
+ companyId: f.companyId,
+ projectId: f.input.projectId,
+ },
+ actor: { actorType: "user", agentId: null },
+ authorizationActor: {
+ type: "board",
+ source: "local_implicit",
+ isInstanceAdmin: true,
+ },
+ });
+ expect(result).toMatchObject({ ok: true, reopened: true });
+ const [restored] = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, workspace!.id));
+ expect(restored.providerRef).toBe(`${workspace!.providerRef}:restored`);
+ expect(restored.metadata?.workspaceProvider).toMatchObject({
+ workspaceRef: restored.providerRef,
+ });
+ await removePluginWorkspace(db, f.workers, restored, "a".repeat(40));
+ expect(f.calls.at(-1).operation).toMatchObject({
+ kind: "remove",
+ binding: { workspaceRef: restored.providerRef },
+ });
+ });
+ it("uses provider inspection for remote workspace display and shares repeated reads", async () => {
+ const f = await fixture();
+ const workspace = await preparePluginWorkspace(db, f.workers, f.input);
+ await db
+ .update(issues)
+ .set({ status: "done" })
+ .where(eq(issues.id, f.issueId));
+ const svc = executionWorkspaceService(db, {
+ pluginWorkerManager: f.workers,
+ inspectGitCloseReadiness: async () => {
+ throw new Error("Host inspection must not run for provider storage");
+ },
+ });
+ expect(await svc.getById(workspace!.id)).toMatchObject({
+ deliveryState: "merged_by_ancestry",
+ });
+ expect(await svc.getById(workspace!.id)).toMatchObject({
+ deliveryState: "merged_by_ancestry",
+ });
+ expect(
+ f.calls.filter((call) => call.operation.kind === "inspect"),
+ ).toHaveLength(1);
+ });
+ it("replays a durable removal after a lost result without inspecting the missing checkout", async () => {
+ const f = await fixture();
+ const workspace = await preparePluginWorkspace(db, f.workers, f.input);
+ f.loseRemoval();
+ await expect(
+ removePluginWorkspace(db, f.workers, workspace!, "a".repeat(40)),
+ ).rejects.toThrow("incomplete");
+ const inspections = f.calls.filter(
+ (call) => call.operation.kind === "inspect",
+ ).length;
+ await removePluginWorkspace(db, f.workers, workspace!, null);
+ expect(
+ f.calls.filter((call) => call.operation.kind === "inspect"),
+ ).toHaveLength(inspections);
+ const removals = f.calls.filter(
+ (call) => call.operation.kind === "remove",
+ );
+ expect(removals).toHaveLength(2);
+ expect(removals[0].operationId).toBe(removals[1].operationId);
+ const [row] = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, workspace!.id));
+ expect(row.metadata).toMatchObject({
+ workspaceProviderRemoved: true,
+ workspaceProviderRemoval: null,
+ });
+ });
+ it("retires cleaned historical bindings when the storage source changes and refuses later reopen", async () => {
+ const f = await fixture();
+ const workspace = await preparePluginWorkspace(db, f.workers, f.input);
+ await db
+ .update(executionWorkspaces)
+ .set({ status: "archived", closedAt: new Date() })
+ .where(eq(executionWorkspaces.id, workspace!.id));
+ await removePluginWorkspace(db, f.workers, workspace!, "a".repeat(40));
+ await expect(
+ projectService(db).updateWorkspace(
+ f.input.projectId,
+ f.input.projectWorkspaceId,
+ { repoUrl: "https://github.com/example/new.git" },
+ ),
+ ).resolves.not.toBeNull();
+ const before = f.calls.length;
+ const result = await executionWorkspaceService(db, {
+ pluginWorkerManager: f.workers,
+ }).reopenClosedIsolatedExecutionWorkspaceForIssue({
+ workspaceId: workspace!.id,
+ issue: {
+ id: f.issueId,
+ companyId: f.companyId,
+ projectId: f.input.projectId,
+ },
+ actor: { actorType: "user", agentId: null },
+ authorizationActor: {
+ type: "board",
+ source: "local_implicit",
+ isInstanceAdmin: true,
+ },
+ });
+ expect(result).toMatchObject({ ok: false, code: "not_reopenable" });
+ expect(f.calls).toHaveLength(before);
+ await expect(
+ projectService(db).update(f.input.projectId, {
+ executionWorkspacePolicy: {},
+ }),
+ ).resolves.not.toBeNull();
+ await expect(
+ projectService(db).removeWorkspace(
+ f.input.projectId,
+ f.input.projectWorkspaceId,
+ ),
+ ).resolves.not.toBeNull();
+ });
+ it("keeps sweeping later workspaces when one storage plugin is unavailable", async () => {
+ const first = await fixture(),
+ second = await fixture();
+ await preparePluginWorkspace(db, first.workers, first.input);
+ await preparePluginWorkspace(db, second.workers, second.input);
+ await db.insert(pluginCompanySettings).values({
+ pluginId: first.pluginId,
+ companyId: first.companyId,
+ enabled: false,
+ });
+ for (const f of [first, second])
+ await db
+ .update(issues)
+ .set({ status: "done", completedAt: new Date() })
+ .where(eq(issues.id, f.issueId));
+ const workers = {
+ getWorker: (id: string) =>
+ [first.pluginId, second.pluginId].includes(id)
+ ? { supportedMethods: ["workspaceOperation"] }
+ : undefined,
+ call: (id: string, ...args: unknown[]) =>
+ (id === first.pluginId ? first.workers : second.workers).call(
+ id,
+ ...(args as [any, any, any]),
+ ),
+ } as unknown as WorkspaceWorkers;
+ await expect(
+ executionWorkspaceService(db, {
+ pluginWorkerManager: workers,
+ workspaceReaperCooldownDays: 0,
+ }).sweepTerminalWorkspaces(100),
+ ).resolves.toBeDefined();
+ expect(
+ second.calls.some((call) => call.operation.kind === "inspect"),
+ ).toBe(true);
+ });
+ it("retries an ambiguous deletion through the existing terminal sweep", async () => {
+ const f = await fixture();
+ const workspace = await preparePluginWorkspace(db, f.workers, f.input);
+ f.loseRemoval();
+ await db
+ .update(executionWorkspaces)
+ .set({ status: "cleanup_failed", closedAt: new Date() })
+ .where(eq(executionWorkspaces.id, workspace!.id));
+ await db
+ .update(issues)
+ .set({ status: "done", completedAt: new Date() })
+ .where(eq(issues.id, f.issueId));
+ await db
+ .update(heartbeatRuns)
+ .set({ status: "cancelled" })
+ .where(eq(heartbeatRuns.id, f.runId));
+ await expect(
+ removePluginWorkspace(db, f.workers, workspace!, "a".repeat(40)),
+ ).rejects.toThrow("incomplete");
+ const workers = {
+ getWorker: (id: string) =>
+ id === f.pluginId
+ ? { supportedMethods: ["workspaceOperation"] }
+ : undefined,
+ call: f.workers.call.bind(f.workers),
+ } as unknown as WorkspaceWorkers;
+ await executionWorkspaceService(db, {
+ pluginWorkerManager: workers,
+ workspaceReaperCooldownDays: 0,
+ }).sweepTerminalWorkspaces(100);
+ const [row] = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, workspace!.id));
+ expect(row).toMatchObject({
+ status: "archived",
+ metadata: {
+ workspaceProviderRemoved: true,
+ workspaceProviderRemoval: null,
+ },
+ });
+ expect(
+ f.calls.filter((call) => call.operation.kind === "remove"),
+ ).toHaveLength(2);
+ });
+ it("keeps restoration intent durable when reopening loses the provider response", async () => {
+ const f = await fixture();
+ const workspace = await preparePluginWorkspace(db, f.workers, f.input);
+ await db
+ .update(executionWorkspaces)
+ .set({ status: "archived", closedAt: new Date() })
+ .where(eq(executionWorkspaces.id, workspace!.id));
+ await removePluginWorkspace(db, f.workers, workspace!, "a".repeat(40));
+ f.lose();
+ const request = {
+ workspaceId: workspace!.id,
+ issue: {
+ id: f.issueId,
+ companyId: f.companyId,
+ projectId: f.input.projectId,
+ },
+ actor: { actorType: "user", agentId: null },
+ authorizationActor: {
+ type: "board" as const,
+ source: "local_implicit" as const,
+ isInstanceAdmin: true,
+ },
+ };
+ const svc = executionWorkspaceService(db, {
+ pluginWorkerManager: f.workers,
+ });
+ expect(
+ await svc.reopenClosedIsolatedExecutionWorkspaceForIssue(request),
+ ).toMatchObject({ ok: false, code: "rebuild_failed" });
+ const [pending] = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, workspace!.id));
+ expect(pending.metadata).toMatchObject({
+ workspaceProviderRemoved: false,
+ workspaceProviderRestoration: { generation: 1 },
+ });
+ await expect(
+ projectService(db).updateWorkspace(
+ f.input.projectId,
+ f.input.projectWorkspaceId,
+ { repoRef: "new" },
+ ),
+ ).rejects.toThrow("storage owner");
+ expect(
+ await svc.reopenClosedIsolatedExecutionWorkspaceForIssue(request),
+ ).toMatchObject({ ok: true, generation: 1 });
+ });
+ it("reconciles a remotely completed restoration before reaping and never reuses an older removal receipt", async () => {
+ const f = await fixture();
+ const call = f.workers.call.bind(f.workers),
+ cache = new Map<string, unknown>();
+ let loseRestoreReply = false;
+ f.workers.call = async (...args) => {
+ const params = args[2] as any;
+ if (params.operation.kind === "inspect") return call(...args);
+ if (cache.has(params.operationId))
+ return cache.get(params.operationId) as any;
+ const result = await call(...args);
+ cache.set(params.operationId, result);
+ if (
+ loseRestoreReply &&
+ params.operation.kind === "prepare" &&
+ params.operation.existing
+ ) {
+ loseRestoreReply = false;
+ throw new Error("lost completed restoration reply");
+ }
+ return result;
+ };
+ const workspace = await preparePluginWorkspace(db, f.workers, f.input);
+ await db
+ .update(heartbeatRuns)
+ .set({ status: "succeeded" })
+ .where(eq(heartbeatRuns.id, f.runId));
+ await db
+ .update(issues)
+ .set({ status: "done", completedAt: new Date() })
+ .where(eq(issues.id, f.issueId));
+ const svc = executionWorkspaceService(db, {
+ pluginWorkerManager: f.workers,
+ workspaceReaperCooldownDays: 0,
+ });
+ await svc.archiveWorkspaceUnderLifecycleLock({
+ id: workspace!.id,
+ patch: {},
+ closedAt: new Date(),
+ });
+ const read = () =>
+ db
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, workspace!.id))
+ .then((rows) => rows[0]!);
+ await removePluginWorkspace(db, f.workers, await read(), "a".repeat(40));
+ const firstRemoval = f.calls.find(
+ (call) => call.operation.kind === "remove",
+ );
+ loseRestoreReply = true;
+ const restoreEvents: string[] = [];
+ const stopRestoreEvents = subscribeDatabaseWork(
+ db,
+ DELIVERY_QUEUES.terminalWorkspaces,
+ (event, hints) => {
+ if (hints?.has(`workspace:${workspace!.id}`))
+ restoreEvents.push(event);
+ },
+ );
+ try {
+ expect(
+ await svc.reopenClosedIsolatedExecutionWorkspaceForIssue({
+ workspaceId: workspace!.id,
+ issue: {
+ id: f.issueId,
+ companyId: f.companyId,
+ projectId: f.input.projectId,
+ },
+ actor: { actorType: "user", agentId: null },
+ authorizationActor: {
+ type: "board",
+ source: "local_implicit",
+ isInstanceAdmin: true,
+ },
+ }),
+ ).toMatchObject({ ok: false, code: "rebuild_failed" });
+ } finally {
+ stopRestoreEvents();
+ }
+ expect(restoreEvents).toEqual(["intent", "settled"]);
+ const pending = await read();
+ expect(pending.metadata?.workspaceProviderRestoration).toMatchObject({
+ generation: firstRemoval.generation + 1,
+ });
+ await expect(
+ removePluginWorkspace(db, f.workers, pending, "a".repeat(40)),
+ ).rejects.toThrow("restoration");
+ const settled: Array<ReturnType<typeof read>> = [];
+ const events: string[] = [];
+ const unsubscribe = subscribeDatabaseWork(
+ db,
+ DELIVERY_QUEUES.terminalWorkspaces,
+ (event, hints) => {
+ if (!hints?.has(`workspace:${workspace!.id}`)) return;
+ events.push(event);
+ if (event === "settled") settled.push(read());
+ },
+ );
+ try {
+ await svc.sweepTerminalWorkspaces(100);
+ } finally {
+ unsubscribe();
+ }
+ expect(events).toEqual(["intent", "settled"]);
+ expect(await settled[0]).toMatchObject({
+ metadata: {
+ workspaceProviderRestoration: null,
+ lifecycleGeneration: firstRemoval.generation + 1,
+ workspaceProviderRemoved: false,
+ },
+ });
+ const recovered = await read();
+ expect(recovered.metadata).toMatchObject({
+ workspaceProviderRemoved: false,
+ workspaceProviderRestoration: null,
+ lifecycleGeneration: firstRemoval.generation + 1,
+ });
+ await expect(
+ projectService(db).updateWorkspace(
+ f.input.projectId,
+ f.input.projectWorkspaceId,
+ { repoRef: "after-recovery" },
+ ),
+ ).rejects.toThrow("storage owner");
+ await svc.sweepTerminalWorkspaces(100);
+ expect((await read()).metadata?.workspaceProviderRemoved).toBe(true);
+ const removals = f.calls.filter(
+ (call) => call.operation.kind === "remove",
+ );
+ expect(removals).toHaveLength(2);
+ expect(removals[1].generation).toBe(firstRemoval.generation + 1);
+ expect(removals[1].operationId).not.toBe(firstRemoval.operationId);
+ });
+ it("rejects unsupported provider modes before making a reservation", async () => {
+ const f = await fixture();
+ await expect(
+ preparePluginWorkspace(db, f.workers, {
+ ...f.input,
+ mode: "shared_workspace",
+ strategy: "project_primary",
+ }),
+ ).rejects.toThrow("does not support");
+ const [task] = await db
+ .select()
+ .from(issues)
+ .where(eq(issues.id, f.issueId));
+ expect(task.executionWorkspaceId).toBeNull();
+ expect(f.calls).toHaveLength(0);
+ });
+ it("checks the saved mode when project defaults change on a reused workspace", async () => {
+ const f = await fixture();
+ const workspace = await preparePluginWorkspace(db, f.workers, f.input);
+ const reused = await preparePluginWorkspace(db, f.workers, {
+ ...f.input,
+ existingWorkspaceId: workspace!.id,
+ mode: "shared_workspace",
+ strategy: "project_primary",
+ });
+ expect(reused!.id).toBe(workspace!.id);
+ expect(f.calls.at(-1).operation).toMatchObject({
+ mode: "isolated_workspace",
+ strategy: "git_worktree",
+ });
+ });
+ it("preserves a saved null branch when reuse defaults change", async () => {
+ const f = await fixture();
+ const [plugin] = await db
+ .select()
+ .from(plugins)
+ .where(eq(plugins.id, f.pluginId));
+ await db
+ .update(plugins)
+ .set({
+ manifestJson: {
+ ...plugin.manifestJson,
+ workspaceProvider: {
+ modes: ["shared_workspace", "isolated_workspace"],
+ strategies: ["project_primary", "git_worktree"],
+ },
+ },
+ })
+ .where(eq(plugins.id, f.pluginId));
+ const workspace = await preparePluginWorkspace(db, f.workers, {
+ ...f.input,
+ mode: "shared_workspace",
+ strategy: "project_primary",
+ branchName: null,
+ });
+ expect(workspace!.branchName).toBeNull();
+ await preparePluginWorkspace(db, f.workers, {
+ ...f.input,
+ existingWorkspaceId: workspace!.id,
+ branchName: "new-default",
+ });
+ expect(f.calls.at(-1).operation).toMatchObject({
+ mode: "shared_workspace",
+ strategy: "project_primary",
+ branchName: null,
+ });
+ });
+ it("does not share inspection results across opaque references owned by different providers", async () => {
+ const first = await fixture(),
+ second = await fixture(first.companyId);
+ for (const f of [first, second]) {
+ const workers = {
+ getWorker: f.workers.getWorker.bind(f.workers),
+ call: async (...args: any[]) => {
+ const result = await (f.workers.call as any)(...args);
+ return result.kind === "prepared"
+ ? {
+ ...result,
+ binding: { ...result.binding, workspaceRef: "opaque" },
+ }
+ : result;
+ },
+ } as unknown as WorkspaceWorkers;
+ await preparePluginWorkspace(db, workers, f.input);
+ await db
+ .update(issues)
+ .set({ status: "done", completedAt: new Date() })
+ .where(eq(issues.id, f.issueId));
+ await db
+ .update(heartbeatRuns)
+ .set({ status: "cancelled" })
+ .where(eq(heartbeatRuns.id, f.runId));
+ }
+ second.dirty();
+ const workers = {
+ getWorker: (id: string) =>
+ [first.pluginId, second.pluginId].includes(id)
+ ? { supportedMethods: ["workspaceOperation"] }
+ : undefined,
+ call: (id: string, ...args: any[]) =>
+ (
+ (id === first.pluginId ? first.workers : second.workers).call as any
+ )(id, ...args),
+ } as unknown as WorkspaceWorkers;
+ await executionWorkspaceService(db, {
+ pluginWorkerManager: workers,
+ workspaceReaperCooldownDays: 0,
+ }).sweepTerminalWorkspaces(100);
+ const [task] = await db
+ .select()
+ .from(issues)
+ .where(eq(issues.id, second.issueId));
+ const [retained] = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, task.executionWorkspaceId!));
+ expect(retained.status).toBe("active");
+ expect(
+ second.calls.some((call) => call.operation.kind === "inspect"),
+ ).toBe(true);
+ });
+ it("never removes a checkout with local-only changes", async () => {
+ const f = await fixture();
+ const workspace = await preparePluginWorkspace(db, f.workers, f.input);
+ f.dirty();
+ await expect(
+ removePluginWorkspace(db, f.workers, workspace!, "a".repeat(40)),
+ ).rejects.toThrow("local changes");
+ expect(f.calls.some((call) => call.operation.kind === "remove")).toBe(
+ false,
+ );
+ });
+ },
+);
diff --git a/server/src/index.ts b/server/src/index.ts
index 17c187f060..287ae6c34b 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -1477,6 +1477,7 @@ async function startServerWithDatabaseTeardown(
wakeup: heartbeat.wakeup,
});
const terminalWorkspaces = executionWorkspaceService(db as any, {
+ pluginWorkerManager,
gitCacheExpirationEnabled: config.gitCacheExpirationEnabled,
gitBaseExpirationEnabled: config.gitBaseExpirationEnabled,
gitCacheExpirationDryRun: config.gitCacheExpirationDryRun,
diff --git a/server/src/routes/execution-workspaces.ts b/server/src/routes/execution-workspaces.ts
index 71a14a7f48..e87fbbeea6 100644
--- a/server/src/routes/execution-workspaces.ts
+++ b/server/src/routes/execution-workspaces.ts
@@ -1,3 +1,4 @@
+import { removePluginWorkspace } from "../services/plugin-workspaces.js";
import { canActorReadWorkspaceOperation } from "../services/heartbeat-run-privacy.js";
import { canActorReadExecutionWorkspace, executionWorkspaceReadSqlCondition } from "../services/authorization.js";
import { spawn } from "node:child_process";
@@ -87,7 +88,7 @@ function resolveFallbackSeedSourceConfigPath(baseWorkspaceCwd: string): string |
export function executionWorkspaceRoutes(db: Db, opts: { pluginWorkerManager?: PluginWorkerManager } = {}) {
const router = Router();
- const svc = executionWorkspaceService(db);
+ const svc = executionWorkspaceService(db, { pluginWorkerManager: opts.pluginWorkerManager });
const access = accessService(db);
const workspaceOperationsSvc = workspaceOperationService(db);
const runtimeLeases = workspaceRuntimeLeaseService(db);
@@ -1305,6 +1306,10 @@ export function executionWorkspaceRoutes(db: Db, opts: { pluginWorkerManager?: P
executionWorkspaceId: existing.id,
workspaceCwd: existing.cwd,
});
+ if (workspace.providerType === "plugin") {
+ await removePluginWorkspace(db, opts.pluginWorkerManager, workspace, readiness.git?.headSha ?? null);
+ return { cleaned: true, warnings: [] };
+ }
return cleanupExecutionWorkspaceArtifacts({
workspace: existing,
projectWorkspace,
diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts
index 34417695a8..164f553edd 100644
--- a/server/src/routes/issues.ts
+++ b/server/src/routes/issues.ts
@@ -3434,7 +3434,7 @@ export function issueRoutes(
const goalsSvc = goalService(db);
const issueApprovalsSvc = issueApprovalService(db);
const recoveryActionsSvc = issueRecoveryActionService(db);
- const executionWorkspacesSvc = executionWorkspaceServiceDirect(db);
+ const executionWorkspacesSvc = executionWorkspaceServiceDirect(db, { pluginWorkerManager: opts.pluginWorkerManager });
const workProductsSvc = workProductService(db);
const documentsSvc = documentService(db);
const artifactReviewDocumentsSvc = artifactReviewDocumentService(db, storage);
diff --git a/server/src/services/environment-run-orchestrator.ts b/server/src/services/environment-run-orchestrator.ts
index 8df0e41f2b..8016bb567a 100644
--- a/server/src/services/environment-run-orchestrator.ts
+++ b/server/src/services/environment-run-orchestrator.ts
@@ -401,6 +401,15 @@ export function environmentRunOrchestrator(
} = input;
let { lease, persistedExecutionWorkspace } = input;
+ if (executionWorkspace.providerBinding) {
+ const binding = executionWorkspace.providerBinding;
+ if (environment.driver !== "plugin" || adapterType !== "paperclip_runner" || lease.metadata?.pluginId !== binding.pluginId || !await environmentRuntime.supportsTasks({ lease })) {
+ throw new EnvironmentRunError("workspace_realization_failed", "The execution plugin cannot access this managed workspace.", { environmentId: environment.id });
+ }
+ const updated = await environmentsSvc.updateLeaseMetadata(lease.id, { ...lease.metadata, workspaceProvider: binding });
+ if (!updated) throw new Error("Workspace execution lease disappeared");
+ lease = updated;
+ }
// Step 1: Build workspace realization request
const workspaceRealizationRequest = buildWorkspaceRealizationRequest({
adapterType,
@@ -481,7 +490,7 @@ export function environmentRunOrchestrator(
"Skip host provisionCommand for sandbox-driver environment; the adapter stage.sync step delivers the provisioned tree",
);
}
- if (provisionCommand && !driverSkipsHostProvision) {
+ if (provisionCommand && !executionWorkspace.providerBinding && !driverSkipsHostProvision) {
try {
const provisionResult = await environmentRuntime.execute({
environment,
@@ -555,6 +564,11 @@ export function environmentRunOrchestrator(
environmentRuntime,
duplexObservabilityRecorder: input.duplexObservabilityRecorder ?? null,
});
+ // The native plugin task bridge owns guest paths. Never fall back to host execution.
+ if (executionWorkspace.providerBinding && (executionTarget?.kind !== "remote" ||
+ !("runnerTask" in executionTarget) || typeof executionTarget.runnerTask !== "function")) {
+ throw new Error("Managed workspace execution requires the native plugin task bridge");
+ }
const realizationMode = workspaceRealization.mode === "in_place" ? "in_place" : "copy";
const authoritativeRoot =
typeof workspaceRealization.authoritativeRoot === "string" && workspaceRealization.authoritativeRoot.trim().length > 0
diff --git a/server/src/services/environment-task-runtime.ts b/server/src/services/environment-task-runtime.ts
index 4f46bd0afe..31ce970e65 100644
--- a/server/src/services/environment-task-runtime.ts
+++ b/server/src/services/environment-task-runtime.ts
@@ -1,6 +1,7 @@
+import { readWorkspaceProviderBinding } from "@paperclipai/shared";
import { settlePluginTaskCredentialHandoff } from "./plugin-task-credential-writeback.js";
import { and, eq, inArray, or, sql } from "drizzle-orm";
-import { environmentLeases, environments, heartbeatRuns, issues, projects, type Db } from "@paperclipai/db";
+import { environmentLeases, executionWorkspaces, environments, heartbeatRuns, issues, projects, type Db } from "@paperclipai/db";
import { environmentTaskOperationSchema, parseEnvironmentTaskResult, type PluginEnvironmentTaskOperation } from "@paperclipai/plugin-sdk";
import { pluginRegistryService } from "./plugin-registry.js";
import { hasRemoteTerminationReceipt, remoteExecutionHasStopped } from "./remote-execution-termination.js";
@@ -79,6 +80,18 @@ export async function executeEnvironmentTask(db: Db, workers: PluginWorkerManage
const issue = launches && lease.issueId ? await db.select({ id: issues.id }).from(issues)
.where(and(eq(issues.id, lease.issueId), eq(issues.companyId, input.companyId))).limit(1).then(rows => rows[0]) : null;
if (launches && lease.issueId && !issue) throw new Error("Plugin-provided Runner execution issue unavailable");
+ const workspaceBinding = readWorkspaceProviderBinding(lease.metadata);
+ if (metadata.workspaceProvider !== undefined && !workspaceBinding) throw new Error("Invalid managed workspace binding");
+ if (workspaceBinding) {
+ const [workspace] = await db.select().from(executionWorkspaces).where(and(
+ eq(executionWorkspaces.id, workspaceBinding.executionWorkspaceId), eq(executionWorkspaces.companyId, input.companyId)));
+ const saved = readWorkspaceProviderBinding(workspace?.metadata);
+ if (!workspace || workspace.id !== lease.executionWorkspaceId || workspace.providerType !== "plugin" || workspace.providerRef !== workspaceBinding.workspaceRef ||
+ (launches && !["active", "idle", "in_review"].includes(workspace.status)) ||
+ workspaceBinding.pluginId !== plugin.id || !saved || JSON.stringify(saved) !== JSON.stringify(workspaceBinding)) {
+ throw new Error("Managed workspace execution binding changed");
+ }
+ }
const projectIds = launches ? operation.projectIds : [];
if (projectIds.length > 0) {
const authorizedProjects = await db.select({ id: projects.id }).from(projects)
@@ -119,7 +132,8 @@ export async function executeEnvironmentTask(db: Db, workers: PluginWorkerManage
driverKey: metadata.driverKey, companyId: input.companyId, environmentId: environment?.id ?? null,
issueId: lease.issueId, config: driverConfig,
taskId, runId: run?.id ?? (activeProbe ? String(probe.runId) : null), agentId: run?.agentId ?? null, projectIds,
- lease: { providerLeaseId: lease.providerLeaseId, metadata: lease.metadata ?? undefined }, operation,
+ lease: { providerLeaseId: lease.providerLeaseId, metadata: lease.metadata ?? undefined },
+ ...(workspaceBinding ? { workspace: workspaceBinding } : {}), operation,
}, 15_000);
const parsed = parseEnvironmentTaskResult(operation, taskId, result);
if (parsed.kind === "status" && parsed.executionStopped === true) {
diff --git a/server/src/services/execution-workspace-lifecycle-lock.ts b/server/src/services/execution-workspace-lifecycle-lock.ts
new file mode 100644
index 0000000000..286dfc3f06
--- /dev/null
+++ b/server/src/services/execution-workspace-lifecycle-lock.ts
@@ -0,0 +1,34 @@
+import { withDedicatedDbConnection, type Db } from "@paperclipai/db";
+import { sql } from "drizzle-orm";
+import { withWorkspaceLockKeepalive } from "./native-runtime/native-workspace-lock-keepalive.js";
+
+type Transaction = Parameters<Parameters<Db["transaction"]>[0]>[0];
+
+export async function acquireExecutionWorkspaceLifecycleLock(
+ tx: Transaction,
+ workspaceId: string,
+) {
+ await tx.execute(
+ sql`select pg_advisory_xact_lock(hashtextextended(${`execution_workspace_lifecycle:${workspaceId}`}, 0))`,
+ );
+}
+
+export function withExecutionWorkspaceLifecycleLock<T>(
+ db: Db,
+ workspaceId: string,
+ work: (tx: Transaction) => Promise<T>,
+): Promise<T> {
+ return withDedicatedDbConnection(db, (connection) =>
+ connection.transaction(async (tx) => {
+ await acquireExecutionWorkspaceLifecycleLock(tx, workspaceId);
+ const rows = await tx.execute(
+ sql`select setting::bigint as idle_timeout_ms from pg_settings where name = 'idle_in_transaction_session_timeout'`,
+ );
+ return withWorkspaceLockKeepalive(
+ tx,
+ Number(rows[0]?.idle_timeout_ms),
+ () => work(tx),
+ );
+ }),
+ );
+}
diff --git a/server/src/services/execution-workspace-policy.ts b/server/src/services/execution-workspace-policy.ts
index 4cf8506c67..37fc7a7ff8 100644
--- a/server/src/services/execution-workspace-policy.ts
+++ b/server/src/services/execution-workspace-policy.ts
@@ -130,6 +130,7 @@ export function parseProjectExecutionWorkspacePolicy(raw: unknown): ProjectExecu
})();
return {
enabled,
+ ...(typeof parsed.storageProviderPluginId === "string" ? { storageProviderPluginId: parsed.storageProviderPluginId } : {}),
...(sharedWorkspaceConcurrency ? { sharedWorkspaceConcurrency } : {}),
...(normalizedDefaultMode ? { defaultMode: normalizedDefaultMode } : {}),
...(allowIssueOverride !== undefined ? { allowIssueOverride } : {}),
diff --git a/server/src/services/execution-workspaces.ts b/server/src/services/execution-workspaces.ts
index c6c48f734a..91f7a0d03d 100644
--- a/server/src/services/execution-workspaces.ts
+++ b/server/src/services/execution-workspaces.ts
@@ -1,3 +1,5 @@
+import { inspectPluginWorkspace, removePluginWorkspace, restorePluginWorkspace, type WorkspaceWorkers } from "./plugin-workspaces.js";
+import { acquireExecutionWorkspaceLifecycleLock, withExecutionWorkspaceLifecycleLock } from "./execution-workspace-lifecycle-lock.js";
import { measureRunTransaction } from "./execution-transaction-timing.js";
import { measureRunPhase } from "./execution-preparation-timing.js";
import { assertExecutionWorkspaceRecordAccess, assertTaskWorkspaceExecutionAccess, assertTaskWorkspaceSourceProjectAccess } from "./task-workspace-access.js";
@@ -17,7 +19,7 @@ import { taskWorkspaceSelectionSchema, type TaskWorkspaceSelection, type TaskWor
import { authorizationService, executionWorkspaceReadSqlCondition, projectReadSqlCondition, issueReadSqlCondition, type AuthorizationActor } from "./authorization.js";
import type { SQL } from "drizzle-orm";
import { createWorkspaceGitInspectionCache } from "./workspace-git-inspection-cache.js";
-import { notifyTerminalWorkspaceWork } from "./terminal-workspace-work.js";
+import { notifyTerminalWorkspaceWork, TERMINAL_WORKSPACE_RETRY_MS } from "./terminal-workspace-work.js";
import {
deleteWorkspaceCompactionTrash,
findRegenerableWorkspaceDirs,
@@ -237,26 +239,24 @@ export function clearMetadataReopenPendingConsumption(
return next;
}
-// Acquire the per-workspace, transaction-scoped Postgres advisory lock. Postgres
-// releases the lock when the transaction that holds `tx` commits or rolls back.
-// Both the reopen path and the destructive cleanup path acquire the same lock,
-// so they never run against the same workspace at the same time, even on
-// different server processes.
-async function acquireExecutionWorkspaceLifecycleLock(
- tx: DbTransaction,
- workspaceId: string,
-): Promise<void> {
- await tx.execute(
- sql`select pg_advisory_xact_lock(hashtextextended(${`execution_workspace_lifecycle:${workspaceId}`}, 0))`,
- );
-}
-
-const workspaceSourceKeys = ["cwd", "projectId", "projectWorkspaceId", "sourceIssueId"] as const;
+const workspaceSourceKeys = ["providerType", "cwd", "providerRef", "projectId", "projectWorkspaceId", "sourceIssueId", "mode", "strategyType", "branchName", "repoUrl", "baseRef"] as const;
function preserveWorkspaceMetadataForPatch(
current: typeof executionWorkspaces.$inferSelect, patch: Partial<typeof executionWorkspaces.$inferInsert>,
) {
const nextPatch = { ...patch };
+ if (current.providerType === "plugin") {
+ for (const key of workspaceSourceKeys) {
+ if (patch[key] !== undefined && patch[key] !== current[key]) throw conflict("Managed workspace coordinates belong to its storage plugin");
+ }
+ if (patch.metadata !== undefined) {
+ nextPatch.metadata = { ...patch.metadata };
+ for (const key of ["workspaceProvider", "workspaceProviderOwner", "workspaceProviderSource", "workspaceProviderBaseSha", "workspaceProviderRemoved", "workspaceProviderBranchMode", "workspaceProviderRemoval", "workspaceProviderRetired", "workspaceProviderRestoration", "lifecycleGeneration", "reopenPendingConsumption", "reopenPendingConsumptionSince"] as const) {
+ if (current.metadata?.[key] !== undefined) nextPatch.metadata[key] = current.metadata[key];
+ else delete nextPatch.metadata[key];
+ }
+ }
+ }
const retainedSources = {
...parseObject(parseObject(patch.metadata)._issuePrivacySources),
...parseObject(current.metadata?._issuePrivacySources),
@@ -266,7 +266,7 @@ function preserveWorkspaceMetadataForPatch(
}
if (Object.keys(retainedSources).length > 0) {
nextPatch.metadata = {
- ...(patch.metadata !== undefined ? patch.metadata ?? {} : current.metadata ?? {}),
+ ...(nextPatch.metadata !== undefined ? nextPatch.metadata ?? {} : current.metadata ?? {}),
_issuePrivacySources: retainedSources,
};
}
@@ -285,6 +285,7 @@ export type ReopenClosedIsolatedExecutionWorkspaceResult =
| { ok: false; code: "not_reopenable" | "rebuild_failed"; message: string };
export type ExecutionWorkspaceServiceOptions = {
+ pluginWorkerManager?: WorkspaceWorkers;
gitCacheExpirationEnabled?: boolean;
gitBaseExpirationEnabled?: boolean;
gitCacheExpirationDryRun?: boolean;
@@ -1382,6 +1383,23 @@ const WORKSPACE_COMPACTION_TRASH_STALE_MS = 60 * 60 * 1000;
const WORKSPACE_COMPACTION_TRASH_PURGE_INTERVAL_MS = 30 * 60 * 1000;
export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServiceOptions = {}) {
+ async function inspectWorkspace(workspace: ExecutionWorkspace) {
+ if (workspace.providerType !== "plugin") return inspectGitCloseReadiness(workspace);
+ const [row] = await db.select().from(executionWorkspaces).where(and(eq(executionWorkspaces.id, workspace.id), eq(executionWorkspaces.companyId, workspace.companyId)));
+ if (!row) throw notFound("Workspace is unavailable");
+ let state;
+ try { state = await inspectPluginWorkspace(db, opts.pluginWorkerManager, row); }
+ catch { return { statusInspectionSucceeded: false, warnings: ["Workspace storage inspection is unavailable; data was retained."], git: null }; }
+ return { statusInspectionSucceeded: true, warnings: [], git: {
+ repoRoot: `/workspaces/${workspace.id}`, workspacePath: `/workspaces/${workspace.id}`,
+ branchName: state.branchName, baseRef: workspace.baseRef,
+ hasDirtyTrackedFiles: state.hasDirtyTrackedFiles || state.hasLocalOnlyData,
+ hasUntrackedFiles: state.hasUntrackedFiles, dirtyEntryCount: state.hasDirtyTrackedFiles ? 1 : 0,
+ untrackedEntryCount: state.hasUntrackedFiles ? 1 : 0, aheadCount: null, behindCount: null,
+ isMergedIntoBase: state.isMergedIntoBase, createdByRuntime: workspace.metadata?.createdByRuntime === true,
+ headSha: state.headSha,
+ } };
+ }
async function resolveSourceWorkspaceConfiguration(input: {
companyId: string; issueId?: string | null; assigneeAgentId?: string | null;
assigneeAdapterOverrides?: unknown; executionWorkspaceSettings?: unknown;
@@ -1651,9 +1669,13 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
...(selectedWorkspace ? { projectWorkspaceId: selectedWorkspace.projectWorkspaceId } : {}) };
}
- const inspectDisplay = opts.inspectGitCloseReadiness
+ const inspectLocalDisplay = opts.inspectGitCloseReadiness
? createWorkspaceGitInspectionCache(opts.inspectGitCloseReadiness)
: inspectGitForDisplay;
+ const inspectProviderDisplay = createWorkspaceGitInspectionCache(inspectWorkspace);
+ const inspectDisplay = (workspace: ExecutionWorkspace) => workspace.providerType === "plugin"
+ ? inspectProviderDisplay(workspace)
+ : inspectLocalDisplay(workspace);
const recoveryActionsSvc = issueRecoveryActionService(db);
const resolvePullRequestDetails = opts.resolvePullRequestDetails ?? createPullRequestMergeDetailsResolver(db);
const now = opts.now ?? (() => new Date());
@@ -1796,7 +1818,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
}
let mergedPullRequest = false;
let pullRequestStateUnknown = false;
- const workspaceHeadSha = sourceIssueTerminal && git?.repoRoot && git.workspacePath
+ const workspaceHeadSha = workspace.providerType === "plugin" ? git?.headSha ?? null : sourceIssueTerminal && git?.repoRoot && git.workspacePath
? await runGit(["rev-parse", "HEAD"], git.workspacePath)
.then((result) => result.stdout.trim() || null)
.catch(() => null)
@@ -1874,7 +1896,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
}
const [current, currentHeadSha, currentBranchName] = await Promise.all([
- inspectGitCloseReadiness(toExecutionWorkspace(workspace)),
+ inspectWorkspace(toExecutionWorkspace(workspace)),
readGitStdout(["rev-parse", "HEAD"], workspacePath).catch(() => null),
readGitStdout(["symbolic-ref", "--quiet", "--short", "HEAD"], workspacePath).catch(() => null),
]);
@@ -1952,8 +1974,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
skipLog?: { event: string; message: string };
write: (context: { tx: DbTransaction; fresh: FenceableWorkspaceRow }) => Promise<T>;
}): Promise<T> {
- return db.transaction(async (tx) => {
- await acquireExecutionWorkspaceLifecycleLock(tx, input.workspaceId);
+ return withExecutionWorkspaceLifecycleLock(db, input.workspaceId, async (tx) => {
const row = await tx
.select({ status: executionWorkspaces.status, metadata: executionWorkspaces.metadata })
.from(executionWorkspaces)
@@ -2297,6 +2318,11 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
}
async function runTerminalWorkspaceCleanup(workspace: ExecutionWorkspaceRow, expectedHeadSha: string | null) {
+ if (workspace.providerType === "plugin") {
+ if (await workspaceHasActiveRun(workspace)) throw conflict("Workspace still has active execution");
+ await removePluginWorkspace(db, opts.pluginWorkerManager, workspace, expectedHeadSha);
+ return { cleaned: true, warnings: [] };
+ }
const [
{
acquireGitWorktreeCleanupLock,
@@ -2959,7 +2985,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
git,
warnings: gitWarnings,
statusInspectionSucceeded,
- } = await inspectGitCloseReadiness(executionWorkspace);
+ } = await inspectWorkspace(executionWorkspace);
const { deliveryState } = await assessDelivery(workspace, git);
const warnings = [...gitWarnings];
const blockingReasons: string[] = [];
@@ -3077,12 +3103,12 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
},
];
for (const action of configuredCleanupCommands) {
- if (!action.command) continue;
+ if (!action.command || executionWorkspace.providerType === "plugin") continue;
plannedActions.push(action);
}
const teardownCommand = config?.teardownCommand ?? projectPolicy?.workspaceStrategy?.teardownCommand ?? null;
- if (teardownCommand) {
+ if (teardownCommand && executionWorkspace.providerType !== "plugin") {
plannedActions.push({
kind: "teardown_command",
label: "Run teardown command",
@@ -3091,6 +3117,11 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
});
}
+ if (executionWorkspace.providerType === "plugin") {
+ plannedActions.push({ kind: "remove_provider_workspace", label: "Remove provider workspace",
+ description: "The storage plugin will verify remote recovery and remove the workspace.", command: null });
+ }
+
if (executionWorkspace.providerType === "git_worktree" && workspacePath) {
plannedActions.push({
kind: "git_worktree_remove",
@@ -3100,7 +3131,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
});
}
- if (git?.createdByRuntime && executionWorkspace.branchName) {
+ if (executionWorkspace.providerType !== "plugin" && git?.createdByRuntime && executionWorkspace.branchName) {
plannedActions.push({
kind: "git_branch_delete",
label: "Delete runtime-created branch",
@@ -3186,6 +3217,8 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
const baseCandidateFilter = and(
sql<boolean>`${executionWorkspaces.sourceIssueId} IS NOT NULL`,
or(and(inArray(executionWorkspaces.status, ["active", "idle", "in_review"]), isNull(executionWorkspaces.closedAt)),
+ and(eq(executionWorkspaces.providerType, "plugin"), inArray(executionWorkspaces.status, ["archived", "cleanup_failed"]),
+ sql`(${executionWorkspaces.metadata}->>'workspaceProviderRemoved') IS DISTINCT FROM 'true'`),
opts.gitCacheExpirationEnabled ? and(inArray(executionWorkspaces.status, ["archived", "cleanup_failed"]),
sql`${executionWorkspaces.metadata}->'gitCacheExpiration'->>'completed' = 'false'`) : undefined),
);
@@ -3305,7 +3338,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
);
}
}
- if (opts.gitCacheExpirationEnabled && (hasPendingGitExpiration(workspace)
+ if (workspace.providerType !== "plugin" && opts.gitCacheExpirationEnabled && (hasPendingGitExpiration(workspace)
|| (workspace.mode === "isolated_workspace" && workspace.strategyType === "git_worktree"))) {
const expiration = await expireReconstructableGitWorkspace(db, workspace, {
dryRun: opts.gitCacheExpirationDryRun ?? false, expireBase: opts.gitBaseExpirationEnabled ?? false,
@@ -3351,12 +3384,12 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
const createdByRuntime = workspace.providerType === "git_worktree"
? isRuntimeOwnedGitBranch(workspace.metadata)
: workspace.metadata?.createdByRuntime === true;
- const readinessKey = workspacePath
+ const readinessKey = workspace.providerType === "plugin" ? `plugin:${workspace.id}:${readExecutionWorkspaceLifecycleGeneration(workspace.metadata)}` : workspacePath
? JSON.stringify([workspace.companyId, workspacePath, workspace.baseRef, workspace.branchName, createdByRuntime])
: `workspace:${workspace.id}`;
let inspection = readinessByWorkingTree.get(readinessKey);
if (!inspection) {
- inspection = inspectGitCloseReadiness(toExecutionWorkspace(workspace));
+ inspection = inspectWorkspace(toExecutionWorkspace(workspace));
readinessByWorkingTree.set(readinessKey, inspection);
}
const { git, statusInspectionSucceeded } = await inspection;
@@ -3469,6 +3502,22 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
continue;
}
result.eligible += 1;
+ if (workspace.providerType === "plugin" && isClosedExecutionWorkspaceStatus(workspace.status)) {
+ const generation = readExecutionWorkspaceLifecycleGeneration(workspace.metadata);
+ try {
+ const cleanup = await cleanupTerminalWorkspace(workspace, assessment.workspaceHeadSha, generation);
+ if (cleanup.skippedReopened) result.skippedReopened += 1;
+ else if (!cleanup.cleaned) result.cleanupFailed += 1;
+ else { result.archived += 1; terminalWorkspaceDeadlines.delete(workspace.id); }
+ } catch (error) {
+ result.cleanupFailed += 1;
+ terminalWorkspaceDeadlines.set(workspace.id, now().getTime() + TERMINAL_WORKSPACE_RETRY_MS);
+ await markTerminalCleanupFailedFenced({ workspaceId: workspace.id, capturedGeneration: generation,
+ cleanupReason: `${ISSUE_TERMINAL_WORKSPACE_CLEANUP_REASON} | ${error instanceof Error ? error.message : String(error)}` });
+ logger.warn({ err: error, executionWorkspaceId: workspace.id }, "workspace storage cleanup remains pending");
+ }
+ continue;
+ }
const closedAt = now();
// Raise the lifecycle generation on archive. The cleanup below captures
// this generation and re-checks it before it deletes the worktree, so a
@@ -3481,8 +3530,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
// checks and the archive write. The archive statement re-checks the
// status, the terminal predicates, and the reopen-pending flag under the
// lock, so it never archives a workspace that a reopen just restored.
- const archived = await db.transaction(async (tx) => {
- await acquireExecutionWorkspaceLifecycleLock(tx, workspace.id);
+ const archived = await withExecutionWorkspaceLifecycleLock(db, workspace.id, async (tx) => {
return tx
.update(executionWorkspaces)
.set({
@@ -3597,6 +3645,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
else result.archived += 1;
} catch (error) {
result.cleanupFailed += 1;
+ if (archived.providerType === "plugin") terminalWorkspaceDeadlines.set(archived.id, now().getTime() + TERMINAL_WORKSPACE_RETRY_MS);
const failure = error instanceof Error ? error.message : String(error);
// Mark cleanup_failed only while the row is still closed at the
// generation this sweep captured. A reopen that raced after the failure
@@ -3718,6 +3767,28 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
return { ok: false, code: "not_reopenable", message: "Execution workspace source changed during reopen" };
}
const snapshot = freshSnapshot;
+ if (snapshot.providerType === "plugin") {
+ return withExecutionWorkspaceLifecycleLock(db, snapshot.id, async tx => {
+ const [row] = await tx.select().from(executionWorkspaces).where(and(
+ eq(executionWorkspaces.id, snapshot.id), eq(executionWorkspaces.companyId, issue.companyId)));
+ if (!row || row.sourceIssueId !== sourceIssueId || row.metadata?.workspaceProviderRetired === true) return { ok: false, code: "not_reopenable", message: "Workspace source changed" };
+ await assertTaskWorkspaceExecutionAccess(tx, input.authorizationActor, issue.companyId, { issueId: issue.id, workspaceId: row.id });
+ const generation = readExecutionWorkspaceLifecycleGeneration(row.metadata);
+ if (!isClosedExecutionWorkspaceStatus(row.status)) return { ok: true, reopened: false, workspace: toExecutionWorkspace(row), generation };
+ try {
+ const metadata = await restorePluginWorkspace(db, opts.pluginWorkerManager, row);
+ const [active] = await tx.update(executionWorkspaces).set({ status: "active", closedAt: null,
+ providerRef: metadata.workspaceProvider.workspaceRef,
+ cleanupReason: null, cleanupEligibleAt: null, lastUsedAt: now(), updatedAt: now(),
+ metadata: setMetadataReopenPendingConsumption(bumpExecutionWorkspaceLifecycleGeneration(metadata), now()),
+ }).where(eq(executionWorkspaces.id, row.id)).returning();
+ await notifyTerminalWorkspaceWork(tx, `workspace:${row.id}`);
+ return { ok: true, reopened: true, workspace: toExecutionWorkspace(active!), generation: generation + 1 };
+ } catch {
+ return { ok: false, code: "rebuild_failed", message: "Workspace storage restoration is incomplete; retry reopening" };
+ }
+ });
+ }
await assertTaskWorkspaceExecutionAccess(db, input.authorizationActor, issue.companyId, { issueId: issue.id, workspaceId: snapshot.id });
let recipe: ReturnType<typeof readGitCacheRestoration>;
try { recipe = readGitCacheRestoration(snapshot); }
@@ -4193,8 +4264,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
const [identity] = await db.select({ companyId: executionWorkspaces.companyId }).from(executionWorkspaces)
.where(eq(executionWorkspaces.id, input.id));
if (!identity) return null;
- return db.transaction(async (tx) => {
- await acquireExecutionWorkspaceLifecycleLock(tx, input.id);
+ return withExecutionWorkspaceLifecycleLock(db, input.id, async (tx) => {
const fresh = await measureRunPhase("workspace.row_lock", () => tx
.select()
.from(executionWorkspaces)
@@ -4343,6 +4413,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
.where(eq(executionWorkspaces.id, id))
.then((rows) => rows[0] ?? null);
if (!existingRow) throw notFound("Execution workspace not found");
+ if (existingRow.providerType === "plugin") throw conflict("Branch repair belongs to the workspace storage plugin");
const existing = toExecutionWorkspace(existingRow);
if (!existing.sourceIssueId) {
diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts
index bbf04be5ed..e787fec903 100644
--- a/server/src/services/heartbeat.ts
+++ b/server/src/services/heartbeat.ts
@@ -907,7 +907,7 @@ export function heartbeatService(
const companySkills = companySkillService(db);
const issuesSvc = issueService(db);
const treeControlSvc = issueTreeControlService(db);
- const executionWorkspacesSvc = executionWorkspaceService(db);
+ const executionWorkspacesSvc = executionWorkspaceService(db, { pluginWorkerManager: options.pluginWorkerManager });
const environmentsSvc = environmentService(db);
const environmentRuntime =
options.environmentRuntime ??
@@ -2697,6 +2697,7 @@ export function heartbeatService(
runOptions,
},
services: {
+ workspaceWorkers: options.pluginWorkerManager,
envOrchestrator,
executionWorkspacesSvc,
workspaceOperationsSvc,
diff --git a/server/src/services/heartbeat/workspace-preparation.test.ts b/server/src/services/heartbeat/workspace-preparation.test.ts
index f076dee305..a4d6225e7d 100644
--- a/server/src/services/heartbeat/workspace-preparation.test.ts
+++ b/server/src/services/heartbeat/workspace-preparation.test.ts
@@ -6,7 +6,7 @@ import { pathToFileURL } from "node:url";
import { promisify } from "node:util";
import { captureDirectorySnapshot, directorySnapshotSha256, serializeDirectorySnapshot } from "@paperclipai/adapter-utils/workspace-restore-merge";
import type { AdapterExecutionTarget } from "@paperclipai/adapter-utils/execution-target";
-import { agents, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, environmentLeases, executionWorkspaces, executionWorkspaceRepositoryAccess, heartbeatRuns, issues, issueAccessGrants, projects, projectWorkspaces, type Db } from "@paperclipai/db";
+import { agents, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, environmentLeases, executionWorkspaces, executionWorkspaceRepositoryAccess, heartbeatRuns, issues, issueAccessGrants, plugins, projects, projectWorkspaces, type Db } from "@paperclipai/db";
import { eq, sql } from "drizzle-orm";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
@@ -94,6 +94,37 @@ describe.skipIf(!support.supported)("heartbeat workspace preparation boundary",
};
return { input, source, issue, run, envOrchestrator };
}
+ it("prepares managed storage before acquisition without touching a Core checkout", async () => {
+ const { input, source, issue } = await fixture(true);
+ const [plugin] = await db.insert(plugins).values({ pluginKey: "test.managed-storage", packageName: "test-storage", version: "1.0.0", apiVersion: 1, status: "ready", categories: ["workspace"],
+ manifestJson: { id: "test.managed-storage", apiVersion: 1, version: "1.0.0", displayName: "Storage", description: "Storage", author: "Test", categories: ["workspace"],
+ workspaceProvider: { modes: ["isolated_workspace", "operator_branch"], strategies: ["git_worktree"] }, capabilities: ["workspaces.manage", "events.subscribe"], resourceLifecycle: ["project"], entrypoints: { worker: "./worker.js" } } }).returning();
+ await db.update(projects).set({ executionWorkspacePolicy: { enabled: true, storageProviderPluginId: plugin.id } }).where(eq(projects.id, issue.projectId!));
+ await db.update(projectWorkspaces).set({ cwd: null, sourceType: "remote_managed", repoUrl: "https://github.com/example/repo.git" }).where(eq(projectWorkspaces.id, issue.projectWorkspaceId!));
+ await rm(source, { recursive: true });
+ const sequence: string[] = [];
+ input.services.workspaceWorkers = { getWorker: () => ({ supportedMethods: ["workspaceOperation"] }), call: async (_: string, __: string, params: any) => {
+ sequence.push("prepare");
+ return { kind: "prepared", binding: { pluginId: plugin.id, projectId: issue.projectId, executionWorkspaceId: params.executionWorkspaceId,
+ projectWorkspaceId: issue.projectWorkspaceId, sourceRevision: params.operation.source.revision, workspaceRef: "provider:checkout" },
+ branchName: params.operation.branchName, baseSha: "a".repeat(40), created: true, branchCreatedByRuntime: true };
+ } } as any;
+ const acquire = input.services.envOrchestrator.acquireForRun;
+ vi.spyOn(input.services.envOrchestrator, "acquireForRun").mockImplementation(async args => {
+ sequence.push("acquire"); expect(args.persistedExecutionWorkspace).toMatchObject({ providerType: "plugin", cwd: null });
+ return acquire(args);
+ });
+ vi.spyOn(input.services.envOrchestrator, "realizeForRun").mockImplementation(async args => {
+ expect(args.executionWorkspace.providerBinding?.workspaceRef).toBe("provider:checkout");
+ throw new Error("reached execution handoff");
+ });
+ await expect(prepareHeartbeatWorkspace(db, input)).rejects.toThrow("reached execution handoff");
+ expect(sequence).toEqual(["prepare", "acquire"]);
+ await expect(access(source)).rejects.toThrow();
+ const [task] = await db.select().from(issues).where(eq(issues.id, issue.id));
+ const [workspace] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, task.executionWorkspaceId!));
+ expect(workspace).toMatchObject({ providerType: "plugin", cwd: null, branchName: "test-WSP-1" });
+ });
const readIssue = (id: string) => db.select().from(issues).where(eq(issues.id, id)).then(rows => rows[0]!);
const readRun = (id: string) => db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, id)).then(rows => rows[0]!);
const leases = (id: string) => db.select().from(environmentLeases).where(eq(environmentLeases.heartbeatRunId, id));
diff --git a/server/src/services/heartbeat/workspace-preparation.ts b/server/src/services/heartbeat/workspace-preparation.ts
index 561d86b3f5..8109302b82 100644
--- a/server/src/services/heartbeat/workspace-preparation.ts
+++ b/server/src/services/heartbeat/workspace-preparation.ts
@@ -1,3 +1,5 @@
+import { preparePluginWorkspace, type WorkspaceWorkers } from "../plugin-workspaces.js";
+import { readWorkspaceProviderBinding } from "@paperclipai/shared";
import { nativeExecutionUsesTaskWorkspace } from "./external-provider.js";
import { readGitCacheRestoration } from "../git-workspace-restoration.js";
import { createHeartbeatPreparationTiming } from "./preparation-timing.js";
@@ -37,6 +39,7 @@ import {
cleanupExecutionWorkspaceArtifacts,
ensurePersistedExecutionWorkspaceAvailable,
realizeExecutionWorkspace,
+ renderWorkspaceTemplate, sanitizeBranchName,
type ExecutionWorkspaceInput,
type RealizedExecutionWorkspace,
} from "../workspace-runtime.js";
@@ -131,6 +134,7 @@ export interface HeartbeatWorkspacePreparationInput {
runOptions: { nativeRestartRecovery?: NativeRestartRecoveryClaim };
};
services: {
+ workspaceWorkers?: WorkspaceWorkers;
envOrchestrator: Pick<ReturnType<typeof environmentRunOrchestrator>, "resolveEnvironment" | "acquireForRun" | "realizeForRun">;
executionWorkspacesSvc: Pick<ReturnType<typeof executionWorkspaceService>, "create" | "update" | "bindTaskWorkspace" | "prepareTaskRepositoriesForAdmission" | "assertTaskRepositoryPublicationAllowed" | "prepareConfiguredRepositoryCopy" | "assertTaskRepositoryRecoveryBinding">;
workspaceOperationsSvc: Pick<ReturnType<typeof workspaceOperationService>, "createRecorder">;
@@ -338,7 +342,22 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
},
}));
const hostProvisionDriver = selectedEnvironmentForConfig?.driver ?? lowTrustPreflightEnvironmentDriver;
- const copyOnlyProvisioning = await timeWorkspace("workspace_provision_policy", () => workspaceRequiresCopyOnlyProvisioning(db, {
+ const pluginPrepared = isDotRun ? null : await preparePluginWorkspace(db, input.services.workspaceWorkers, {
+ companyId: agent.companyId, projectId: resolvedWorkspace.projectId, projectWorkspaceId: resolvedWorkspace.workspaceId,
+ issueId, runId: run.id, agentId: agent.id, responsibleUserId,
+ existingWorkspaceId: reusableExistingExecutionWorkspace?.id ?? issueRef?.executionWorkspaceId ?? null,
+ mode: requestedExecutionWorkspaceMode,
+ strategy: resolveEffectiveWorkspaceStrategyType(requestedExecutionWorkspaceMode, mergedConfig),
+ branchMode: typeof parseObject(mergedConfig.workspaceStrategy).existingBranch === "string" ? "existing" : "create",
+ branchName: typeof parseObject(mergedConfig.workspaceStrategy).existingBranch === "string"
+ ? String(parseObject(mergedConfig.workspaceStrategy).existingBranch)
+ : resolveEffectiveWorkspaceStrategyType(requestedExecutionWorkspaceMode, mergedConfig) === "git_worktree" ? sanitizeBranchName(renderWorkspaceTemplate(String(parseObject(mergedConfig.workspaceStrategy).branchTemplate ?? "{{issue.identifier}}-{{slug}}"), {
+ issue: issueRef, agent, projectId: resolvedWorkspace.projectId, repoRef: resolvedWorkspace.repoRef,
+ })) : null,
+ baseRef: typeof parseObject(mergedConfig.workspaceStrategy).baseRef === "string"
+ ? String(parseObject(mergedConfig.workspaceStrategy).baseRef) : null,
+ });
+ const copyOnlyProvisioning = pluginPrepared ? true : await timeWorkspace("workspace_provision_policy", () => workspaceRequiresCopyOnlyProvisioning(db, {
companyId: agent.companyId,
task: issueRef ? { ...issueRef, workspaceSelection: input.task.workspaceSelection } : null,
sourceProjectId: resolvedWorkspace.projectId,
@@ -360,7 +379,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
repoRef: resolvedWorkspace.repoRef,
additionalWorkspaces: resolvedWorkspace.additionalWorkspaces,
} satisfies ExecutionWorkspaceInput;
- await timeWorkspace("workspace_base_validation", () => assertGitWorktreeBaseWorkspaceReady({
+ if (!pluginPrepared) await timeWorkspace("workspace_base_validation", () => assertGitWorktreeBaseWorkspaceReady({
requestedExecutionWorkspaceMode,
config: hostExecutionWorkspaceConfig,
issue: issueRef,
@@ -495,7 +514,14 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
executionWorkspace,
reusedExecutionWorkspace,
policy: resolvedWorkspaceReusePolicy,
- } = isDotRun ? { executionWorkspace: { ...executionWorkspaceBase, strategy: "project_primary" as const, cwd: resolvedWorkspace.cwd, branchName: null, worktreePath: null, warnings: [], created: false, branchCreatedByRuntime: false } as RealizedExecutionWorkspace, reusedExecutionWorkspace: false, policy: workspaceReuseProvisioningPolicy } : await timeWorkspace("workspace_provision", () => provisionExecutionWorkspaceForFreshnessDecision<RealizedExecutionWorkspace>(
+ } = pluginPrepared ? { executionWorkspace: { ...executionWorkspaceBase,
+ providerBinding: readWorkspaceProviderBinding(pluginPrepared.metadata)!,
+ strategy: pluginPrepared.strategyType as "git_worktree" | "project_primary",
+ cwd: `/workspaces/${pluginPrepared.id}`, branchName: pluginPrepared.branchName, worktreePath: null,
+ warnings: [], created: false, branchCreatedByRuntime: false,
+ baseRefSha: pluginPrepared.metadata?.workspaceProviderBaseSha as string | null,
+ } as RealizedExecutionWorkspace, reusedExecutionWorkspace: Boolean(reusableExistingExecutionWorkspace), policy: workspaceReuseProvisioningPolicy }
+ : isDotRun ? { executionWorkspace: { ...executionWorkspaceBase, strategy: "project_primary" as const, cwd: resolvedWorkspace.cwd, branchName: null, worktreePath: null, warnings: [], created: false, branchCreatedByRuntime: false } as RealizedExecutionWorkspace, reusedExecutionWorkspace: false, policy: workspaceReuseProvisioningPolicy } : await timeWorkspace("workspace_provision", () => provisionExecutionWorkspaceForFreshnessDecision<RealizedExecutionWorkspace>(
{
requestedShouldReuseExisting,
existingExecutionWorkspaceId:
@@ -704,7 +730,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
]
: null;
if (
- !persistedWorktreeInstanceRoot &&
+ !pluginPrepared && !persistedWorktreeInstanceRoot &&
executionWorkspace.strategy === "git_worktree" &&
executionWorkspace.worktreePath
) {
@@ -729,6 +755,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
}
const nextExecutionWorkspaceMetadata = {
...baseExecutionWorkspaceMetadata,
+ ...(pluginPrepared?.metadata ?? {}),
...(copyOnlyProvisioning ? { [CONTROLLER_PROVISION_COPY_ONLY]: true } : {}),
...(persistedWorktreeInstanceRoot
? {
@@ -744,6 +771,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
executionWorkspace.branchName;
try {
persistedExecutionWorkspace =
+ pluginPrepared ? await executionWorkspacesSvc.update(pluginPrepared.id, { metadata: nextExecutionWorkspaceMetadata }) :
resolvedWorkspaceReusePolicy.shouldRestoreExistingWorkspace &&
reusableExistingExecutionWorkspace
? await timeWorkspace("workspace_record_update", () => executionWorkspacesSvc.update(
@@ -891,14 +919,14 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
}
await bindIssueToPersistedExecutionWorkspace(persistedExecutionWorkspace);
const projectRepositoryPaths: string[] = [];
- if (!isDotRun && persistedExecutionWorkspace && issueId && !persistedNativeExecutionInput && !nativeRecoveryExecutionWorkspaceId) {
+ if (!pluginPrepared && !isDotRun && persistedExecutionWorkspace && issueId && !persistedNativeExecutionInput && !nativeRecoveryExecutionWorkspaceId) {
const taskRepositories = await timeWorkspace("workspace_repository_admission", () =>
executionWorkspacesSvc.prepareTaskRepositoriesForAdmission({ companyId: agent.companyId,
issueId, workspaceId: persistedExecutionWorkspace!.id, cwd: executionWorkspace.cwd,
agentId: agent.id, runId: run.id, responsibleUserId }));
projectRepositoryPaths.push(...taskRepositories.map(repository => repository.relativePath));
}
- if (executionWorkspace.projectId
+ if (!pluginPrepared && executionWorkspace.projectId
&& (resolvedWorkspace.source === "project_primary" || Boolean(reusableExistingExecutionWorkspace?.projectWorkspaceId))
&& !resolvedWorkspace.baseCwdFallback && !persistedNativeExecutionInput && !nativeRecoveryExecutionWorkspaceId) {
const repositoryRows = await db.select().from(projectWorkspaces).where(and(
@@ -1095,7 +1123,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
await bindIssueToPersistedExecutionWorkspace(persistedExecutionWorkspace);
const workspaceRealization = realizationResult.workspaceRealization;
const executionTarget = realizationResult.executionTarget;
- if (!isDotRun && issueId && (persistedNativeExecutionInput || nativeRecoveryExecutionWorkspaceId)
+ if (!pluginPrepared && !isDotRun && issueId && (persistedNativeExecutionInput || nativeRecoveryExecutionWorkspaceId)
&& !(executionTarget?.kind === "remote" && executionTarget.transport === "ssh")) {
const workspaceId = persistedNativeExecutionInput?.binding.executionWorkspaceId ?? nativeRecoveryExecutionWorkspaceId!;
const reference = readNativeWorkspaceSyncReference(parseObject(run.runnerProfileJson).nativeWorkspaceSync);
diff --git a/server/src/services/heartbeat/workspaces.test.ts b/server/src/services/heartbeat/workspaces.test.ts
index f06a1ba116..bad33936d0 100644
--- a/server/src/services/heartbeat/workspaces.test.ts
+++ b/server/src/services/heartbeat/workspaces.test.ts
@@ -97,8 +97,8 @@ describe("heartbeat workspace module", () => {
]);
expect(firstResult).toMatchObject({ cwd: firstCwd, projectId: "project-one", workspaceId: "workspace-one", source: "project_primary", additionalWorkspaces: [] });
expect(secondResult).toMatchObject({ cwd: secondCwd, projectId: "project-two", workspaceId: "workspace-two", source: "project_primary", additionalWorkspaces: [] });
- expect(first.select).toHaveBeenCalledTimes(1);
- expect(second.select).toHaveBeenCalledTimes(1);
+ expect(first.select).toHaveBeenCalledTimes(2);
+ expect(second.select).toHaveBeenCalledTimes(2);
});
it("uses the current issue's project and selected workspace over stale context", async () => {
@@ -115,7 +115,16 @@ describe("heartbeat workspace module", () => {
null,
);
expect(result).toMatchObject({ cwd: selectedCwd, projectId: "current-project", workspaceId: "selected-workspace", warnings: [], baseCwdFallback: false });
- expect(database.select).toHaveBeenCalledTimes(3);
+ expect(database.select).toHaveBeenCalledTimes(4);
+ });
+
+ it("resolves plugin storage without creating or reading a Core checkout", async () => {
+ const missingCwd = path.join(testRoot, "provider-only-repository");
+ const database = databaseWithResults([workspace("remote-source", "project-one", missingCwd)],
+ [{ policy: { storageProviderPluginId: "10000000-0000-4000-8000-000000000001" } }]);
+ const result = await createHeartbeatWorkspaceResolver(database.db).resolveWorkspaceForRun(agent(), { projectId: "project-one" }, null);
+ expect(result).toMatchObject({ cwd: "/workspaces/remote-source", workspaceId: "remote-source", projectId: "project-one", source: "project_primary" });
+ expect(await fs.stat(missingCwd).catch(() => null)).toBeNull();
});
it("fails closed with workspace diagnostics when a configured directory is unavailable", async () => {
diff --git a/server/src/services/heartbeat/workspaces.ts b/server/src/services/heartbeat/workspaces.ts
index f14537205f..90ac28d9f0 100644
--- a/server/src/services/heartbeat/workspaces.ts
+++ b/server/src/services/heartbeat/workspaces.ts
@@ -3324,6 +3324,12 @@ export function createHeartbeatWorkspaceResolver(db: Db) {
immutableNativeBinding: boolean;
}): Promise<ResolvedAnchorWorkspaceForRun> {
const { workspace, agent } = input;
+ if (workspace.providerType === "plugin") {
+ return { cwd: `/workspaces/${workspace.id}`, source: "task_session" as const,
+ projectId: workspace.projectId, workspaceId: workspace.projectWorkspaceId,
+ repoUrl: workspace.repoUrl, repoRef: workspace.baseRef, workspaceHints: [], warnings: [],
+ baseCwdFallback: false, materializationFailures: [] };
+ }
// Configuration preparation may have awaited credentials and skills since
// issueRef was read. Match the ordinary anchor resolver's fresh selection
// check; only an already-admitted native input owns immutable source scope.
@@ -3480,7 +3486,14 @@ export function createHeartbeatWorkspaceResolver(db: Db) {
if (preferredProjectWorkspaceId && !preferredWorkspace) {
preferredWorkspaceWarning = `Selected project workspace "${preferredProjectWorkspaceId}" is not available on this project.`;
}
+ const [sourceProject] = projectWorkspaceRows.length ? await db.select({ policy: projects.executionWorkspacePolicy }).from(projects)
+ .where(and(eq(projects.id, workspaceProjectId!), eq(projects.companyId, agent.companyId))) : [];
for (const workspace of projectWorkspaceRows) {
+ if (sourceProject?.policy?.storageProviderPluginId) {
+ return { cwd: `/workspaces/${workspace.id}`, source: "project_primary" as const,
+ projectId: workspace.projectId, workspaceId: workspace.id, repoUrl: workspace.repoUrl,
+ repoRef: workspace.repoRef, workspaceHints, warnings: [], baseCwdFallback: false, materializationFailures: [] };
+ }
let projectCwd: string;
let managedWorkspaceWarning: string | null = null;
try {
diff --git a/server/src/services/plugin-capability-validator.ts b/server/src/services/plugin-capability-validator.ts
index e015a9a8b5..2fb9a5d4ec 100644
--- a/server/src/services/plugin-capability-validator.ts
+++ b/server/src/services/plugin-capability-validator.ts
@@ -134,6 +134,7 @@ const OPERATION_CAPABILITIES: Record<string, readonly PluginCapability[]> = {
"agent.tools.execute": ["agent.tools.register"],
// Environment runtime drivers
+ "workspace.operation": ["workspaces.manage"],
"environment.validateConfig": ["environment.drivers.register"],
"environment.probe": ["environment.drivers.register"],
"environment.acquireLease": ["environment.drivers.register"],
@@ -206,6 +207,7 @@ const FEATURE_CAPABILITIES: Record<string, PluginCapability> = {
webhooks: "webhooks.receive",
database: "database.namespace.migrate",
environmentDrivers: "environment.drivers.register",
+ workspaceProvider: "workspaces.manage",
agents: "agents.managed",
projects: "projects.managed",
routines: "routines.managed",
diff --git a/server/src/services/plugin-workspaces.ts b/server/src/services/plugin-workspaces.ts
new file mode 100644
index 0000000000..70715598d9
--- /dev/null
+++ b/server/src/services/plugin-workspaces.ts
@@ -0,0 +1,904 @@
+import { randomUUID, createHash } from "node:crypto";
+import { and, eq, sql } from "drizzle-orm";
+import {
+ executionWorkspaces,
+ heartbeatRuns,
+ issues,
+ pluginCompanySettings,
+ plugins,
+ projects,
+ projectWorkspaces,
+ type Db,
+} from "@paperclipai/db";
+import {
+ readWorkspaceProviderBinding,
+ type WorkspaceProviderBinding,
+} from "@paperclipai/shared";
+import {
+ parseWorkspaceProviderResult,
+ workspaceProviderOperationSchema,
+ type PluginWorkspaceOperation,
+ type PluginWorkspaceParams,
+} from "@paperclipai/plugin-sdk";
+import type { PluginWorkerManager } from "./plugin-worker-manager.js";
+import { notifyTerminalWorkspaceWork } from "./terminal-workspace-work.js";
+import { withExecutionWorkspaceLifecycleLock } from "./execution-workspace-lifecycle-lock.js";
+import {
+ assertTaskWorkspaceExecutionAccess,
+ assertTaskWorkspaceSourceProjectAccess,
+} from "./task-workspace-access.js";
+import { forbidden, conflict } from "../errors.js";
+
+export type WorkspaceWorkers = Pick<PluginWorkerManager, "call" | "getWorker">;
+type Workspace = typeof executionWorkspaces.$inferSelect;
+
+async function provider(
+ db: Db,
+ workers: WorkspaceWorkers | undefined,
+ companyId: string,
+ pluginId: string,
+) {
+ const [plugin] = await db
+ .select()
+ .from(plugins)
+ .where(eq(plugins.id, pluginId));
+ const [settings] = await db
+ .select()
+ .from(pluginCompanySettings)
+ .where(
+ and(
+ eq(pluginCompanySettings.pluginId, pluginId),
+ eq(pluginCompanySettings.companyId, companyId),
+ ),
+ );
+ if (
+ !workers ||
+ !plugin ||
+ plugin.status !== "ready" ||
+ settings?.enabled === false ||
+ !plugin.manifestJson.workspaceProvider ||
+ !plugin.manifestJson.capabilities.includes("workspaces.manage") ||
+ !plugin.manifestJson.resourceLifecycle?.includes("project") ||
+ !workers
+ .getWorker(pluginId)
+ ?.supportedMethods?.includes("workspaceOperation")
+ ) {
+ throw conflict("The workspace storage plugin is unavailable");
+ }
+ return plugin;
+}
+
+/** No paths or provider credentials are accepted from task callers. */
+export async function callWorkspaceProvider(
+ db: Db,
+ workers: WorkspaceWorkers | undefined,
+ input: {
+ workspace: Workspace;
+ operation: PluginWorkspaceOperation;
+ pluginId?: string;
+ advanceGeneration?: boolean;
+ runId?: string | null;
+ agentId?: string | null;
+ },
+) {
+ const { workspace } = input;
+ const binding = readWorkspaceProviderBinding(workspace.metadata);
+ const pluginId = binding?.pluginId ?? input.pluginId;
+ if (!pluginId || !workspace.projectId)
+ throw conflict("Workspace storage ownership is missing");
+ await provider(db, workers, workspace.companyId, pluginId);
+ const generation =
+ typeof workspace.metadata?.lifecycleGeneration === "number"
+ ? workspace.metadata.lifecycleGeneration
+ : 0;
+ const operationGeneration = generation + (input.advanceGeneration ? 1 : 0);
+ const operation = workspaceProviderOperationSchema.parse(input.operation);
+ const params: PluginWorkspaceParams = {
+ pluginId,
+ companyId: workspace.companyId,
+ projectId: workspace.projectId,
+ executionWorkspaceId: workspace.id,
+ operationId:
+ operation.kind === "inspect"
+ ? randomUUID()
+ : createHash("sha256")
+ .update(
+ JSON.stringify([workspace.id, operationGeneration, operation]),
+ )
+ .digest("hex"),
+ generation: operationGeneration,
+ deadline: new Date(Date.now() + 300_000).toISOString(),
+ runId: input.runId ?? null,
+ agentId: input.agentId ?? null,
+ operation,
+ };
+ let value: unknown;
+ try {
+ value = await workers!.call(
+ pluginId,
+ "workspaceOperation",
+ params,
+ 310_000,
+ );
+ } catch {
+ throw conflict(
+ "Workspace storage operation is incomplete; retry the same workspace",
+ );
+ }
+ // Recheck enablement and ownership after an external effect, including an ambiguous retry.
+ await provider(db, workers, workspace.companyId, pluginId);
+ const [fresh] = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(
+ and(
+ eq(executionWorkspaces.id, workspace.id),
+ eq(executionWorkspaces.companyId, workspace.companyId),
+ ),
+ );
+ if (
+ !fresh ||
+ fresh.status !== workspace.status ||
+ (fresh.metadata?.lifecycleGeneration ?? 0) !== generation ||
+ fresh.providerRef !== workspace.providerRef
+ ) {
+ throw conflict("Workspace changed during storage preparation");
+ }
+ const result = parseWorkspaceProviderResult(params, value);
+ if (result.kind === "prepared" && result.binding.pluginId !== pluginId)
+ throw conflict("Workspace provider ownership changed");
+ return result;
+}
+
+export async function preparePluginWorkspace(
+ db: Db,
+ workers: WorkspaceWorkers | undefined,
+ input: {
+ companyId: string;
+ projectId: string | null;
+ projectWorkspaceId: string | null;
+ issueId: string | null;
+ runId: string;
+ agentId: string;
+ responsibleUserId: string | null;
+ existingWorkspaceId: string | null;
+ mode: string;
+ strategy: string;
+ branchMode?: "create" | "existing";
+ branchName?: string | null;
+ baseRef?: string | null;
+ },
+) {
+ const [existing] = input.existingWorkspaceId
+ ? await db
+ .select()
+ .from(executionWorkspaces)
+ .where(
+ and(
+ eq(executionWorkspaces.id, input.existingWorkspaceId),
+ eq(executionWorkspaces.companyId, input.companyId),
+ ),
+ )
+ : [];
+ if (
+ existing?.metadata?.workspaceProviderRetired === true ||
+ existing?.metadata?.workspaceProviderRemoval
+ )
+ throw conflict("Workspace storage is retired or awaiting cleanup");
+ const saved = readWorkspaceProviderBinding(existing?.metadata);
+ const mode = existing?.mode ?? input.mode,
+ strategy = existing?.strategyType ?? input.strategy;
+ const projectId = saved?.projectId ?? input.projectId;
+ const [project] = projectId
+ ? await db
+ .select()
+ .from(projects)
+ .where(
+ and(
+ eq(projects.id, projectId),
+ eq(projects.companyId, input.companyId),
+ ),
+ )
+ : [];
+ const owner =
+ saved?.pluginId ??
+ existing?.metadata?.workspaceProviderOwner ??
+ project?.executionWorkspacePolicy?.storageProviderPluginId;
+ const pluginId = typeof owner === "string" ? owner : null;
+ if (!pluginId) {
+ if (existing?.providerType === "plugin")
+ throw conflict("Workspace storage ownership is missing");
+ return null;
+ }
+ if (
+ !input.issueId ||
+ !project ||
+ project.archivedAt ||
+ !input.projectWorkspaceId
+ )
+ throw conflict(
+ "Managed storage requires a task and an available project source",
+ );
+ if (
+ !["shared_workspace", "isolated_workspace", "operator_branch"].includes(
+ input.mode,
+ ) ||
+ !["project_primary", "git_worktree"].includes(strategy)
+ )
+ throw conflict("Unsupported managed workspace strategy");
+ if (existing && existing.providerType !== "plugin")
+ throw conflict(
+ "An existing local workspace cannot change storage providers",
+ );
+ const selectedProvider = await provider(
+ db,
+ workers,
+ input.companyId,
+ pluginId,
+ );
+ const declaration = selectedProvider.manifestJson.workspaceProvider!;
+ if (
+ !declaration.modes.includes(mode as "isolated_workspace") ||
+ !declaration.strategies.includes(strategy as "git_worktree")
+ ) {
+ throw conflict(
+ "The storage plugin does not support this workspace mode or strategy",
+ );
+ }
+ const actor = {
+ type: "agent" as const,
+ source: "agent_jwt" as const,
+ companyId: input.companyId,
+ agentId: input.agentId,
+ runId: input.runId,
+ onBehalfOfUserId:
+ input.responsibleUserId === "local-board"
+ ? null
+ : input.responsibleUserId,
+ };
+ const authorize = async () => {
+ await assertTaskWorkspaceExecutionAccess(db, actor, input.companyId, {
+ issueId: input.issueId!,
+ ...(existing
+ ? { workspaceId: existing.id }
+ : { projectWorkspaceId: input.projectWorkspaceId }),
+ });
+ await assertTaskWorkspaceSourceProjectAccess(
+ db,
+ actor,
+ input.companyId,
+ project.id,
+ );
+ const [run] = await db
+ .select()
+ .from(heartbeatRuns)
+ .where(
+ and(
+ eq(heartbeatRuns.id, input.runId),
+ eq(heartbeatRuns.companyId, input.companyId),
+ ),
+ );
+ if (
+ !run ||
+ run.agentId !== input.agentId ||
+ ![run.issueId, run.nativeIssueId].includes(input.issueId!) ||
+ run.status !== "running"
+ )
+ throw forbidden("Workspace preparation no longer has an active run");
+ };
+ await authorize();
+ const [source] = await db
+ .select()
+ .from(projectWorkspaces)
+ .where(
+ and(
+ eq(
+ projectWorkspaces.id,
+ saved?.projectWorkspaceId ?? input.projectWorkspaceId,
+ ),
+ eq(projectWorkspaces.projectId, project.id),
+ eq(projectWorkspaces.companyId, input.companyId),
+ ),
+ );
+ if (!source) throw conflict("Workspace repository source is unavailable");
+ const sourceInput = (existing?.metadata?.workspaceProviderSource as
+ | Extract<PluginWorkspaceOperation, { kind: "prepare" }>["source"]
+ | undefined) ?? {
+ id: source.id,
+ revision:
+ saved?.sourceRevision ??
+ createHash("sha256")
+ .update(
+ JSON.stringify([
+ source.id,
+ source.repoUrl,
+ source.repoRef,
+ source.defaultRef,
+ ]),
+ )
+ .digest("hex"),
+ repoUrl: existing?.repoUrl ?? source.repoUrl,
+ repoRef: existing?.baseRef ?? source.repoRef,
+ defaultRef: source.defaultRef,
+ };
+ const branchName = existing
+ ? existing.branchName
+ : (input.branchName ??
+ (strategy === "git_worktree" ? `workspace-${randomUUID()}` : null));
+ // Reserve and bind before calling the provider. A crash must not orphan a created checkout.
+ const workspace =
+ existing ??
+ (await db.transaction(async (tx) => {
+ const [currentProject] = await tx
+ .select()
+ .from(projects)
+ .where(eq(projects.id, project.id))
+ .for("update");
+ const [currentSource] = await tx
+ .select()
+ .from(projectWorkspaces)
+ .where(eq(projectWorkspaces.id, source.id));
+ if (
+ !currentProject ||
+ currentProject.archivedAt ||
+ currentProject.executionWorkspacePolicy?.storageProviderPluginId !==
+ pluginId ||
+ !currentSource ||
+ currentSource.repoUrl !== source.repoUrl ||
+ currentSource.repoRef !== source.repoRef ||
+ currentSource.defaultRef !== source.defaultRef
+ ) {
+ throw conflict(
+ "Project storage configuration changed; retry preparation",
+ );
+ }
+ const [task] = await tx
+ .select()
+ .from(issues)
+ .where(
+ and(
+ eq(issues.id, input.issueId!),
+ eq(issues.companyId, input.companyId),
+ ),
+ )
+ .for("update");
+ if (!task || task.executionWorkspaceId)
+ throw conflict("Task workspace binding changed; retry preparation");
+ const id = randomUUID();
+ await notifyTerminalWorkspaceWork(tx, `workspace:${id}`);
+ const [row] = await tx
+ .insert(executionWorkspaces)
+ .values({
+ id,
+ companyId: input.companyId,
+ projectId: project.id,
+ projectWorkspaceId: source.id,
+ sourceIssueId: input.issueId,
+ mode: input.mode,
+ strategyType: input.strategy,
+ name: branchName ?? source.name,
+ providerType: "plugin",
+ providerRef: null,
+ cwd: null,
+ branchName,
+ repoUrl: source.repoUrl,
+ baseRef: input.baseRef ?? source.repoRef,
+ status: "idle",
+ metadata: {
+ workspaceProviderOwner: pluginId,
+ workspaceProviderSource: sourceInput,
+ workspaceProviderBranchMode: input.branchMode ?? "create",
+ },
+ })
+ .returning();
+ await tx
+ .update(issues)
+ .set({
+ executionWorkspaceId: id,
+ executionWorkspacePreference: "reuse_existing",
+ workspaceBindingRevision: task.workspaceBindingRevision + 1,
+ workspacePendingSelection:
+ task.workspacePendingSelection?.expectedBindingRevision ===
+ task.workspaceBindingRevision
+ ? {
+ ...task.workspacePendingSelection,
+ expectedBindingRevision: task.workspaceBindingRevision + 1,
+ }
+ : task.workspacePendingSelection,
+ updatedAt: new Date(),
+ })
+ .where(eq(issues.id, task.id));
+ return row!;
+ }));
+ return withExecutionWorkspaceLifecycleLock(db, workspace.id, async (tx) => {
+ const [current] = await tx
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, workspace.id));
+ if (
+ !current ||
+ !["active", "idle", "in_review"].includes(current.status) ||
+ current.metadata?.workspaceProviderRetired === true ||
+ current.metadata?.workspaceProviderRemoval ||
+ current.providerRef !== workspace.providerRef ||
+ (current.metadata?.lifecycleGeneration ?? 0) !==
+ (workspace.metadata?.lifecycleGeneration ?? 0)
+ ) {
+ throw conflict("Workspace lifecycle changed; reopen before preparing");
+ }
+ const result = await callWorkspaceProvider(tx as unknown as Db, workers, {
+ workspace,
+ pluginId,
+ runId: input.runId,
+ agentId: input.agentId,
+ operation: {
+ kind: "prepare",
+ source: sourceInput,
+ mode: workspace.mode as "isolated_workspace",
+ strategy: workspace.strategyType as "git_worktree",
+ branchName,
+ branchMode:
+ (workspace.metadata?.workspaceProviderBranchMode as
+ | "create"
+ | "existing"
+ | undefined) ??
+ input.branchMode ??
+ "create",
+ baseRef: workspace.baseRef,
+ existing: saved,
+ },
+ });
+ if (result.kind !== "prepared")
+ throw conflict("Workspace preparation is incomplete");
+ await authorize();
+ const [currentProject] = await tx
+ .select()
+ .from(projects)
+ .where(eq(projects.id, project.id));
+ if (!currentProject || currentProject.archivedAt)
+ throw conflict("Project was archived during workspace preparation");
+ const [task] = await tx
+ .select()
+ .from(issues)
+ .where(eq(issues.id, input.issueId!));
+ if (task?.executionWorkspaceId !== workspace.id)
+ throw conflict("Task workspace binding changed during preparation");
+ await notifyTerminalWorkspaceWork(tx, `workspace:${workspace.id}`);
+ const [updated] = await tx
+ .update(executionWorkspaces)
+ .set({
+ providerRef: result.binding.workspaceRef,
+ branchName: result.branchName,
+ status: "active",
+ lastUsedAt: new Date(),
+ updatedAt: new Date(),
+ metadata: {
+ ...workspace.metadata,
+ workspaceProvider: result.binding,
+ workspaceProviderBaseSha: result.baseSha,
+ workspaceProviderSource: sourceInput,
+ workspaceProviderRemoved: false,
+ createdByRuntime: result.branchCreatedByRuntime,
+ },
+ })
+ .where(
+ and(
+ eq(executionWorkspaces.id, workspace.id),
+ eq(executionWorkspaces.companyId, input.companyId),
+ sql`coalesce((${executionWorkspaces.metadata}->>'lifecycleGeneration')::int, 0) = ${workspace.metadata?.lifecycleGeneration ?? 0}`,
+ sql`${executionWorkspaces.providerRef} IS NOT DISTINCT FROM ${workspace.providerRef}`,
+ ),
+ )
+ .returning();
+ if (!updated)
+ throw conflict("Workspace changed before preparation could be recorded");
+ return updated!;
+ });
+}
+
+/** Recover a lost prepare result even when the originating run has already stopped. */
+async function reconcilePluginWorkspaceReservation(
+ db: Db,
+ workers: WorkspaceWorkers | undefined,
+ snapshot: Workspace,
+): Promise<Workspace> {
+ const [workspace] = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(
+ and(
+ eq(executionWorkspaces.id, snapshot.id),
+ eq(executionWorkspaces.companyId, snapshot.companyId),
+ ),
+ );
+ if (!workspace) throw conflict("Workspace is unavailable");
+ if (readWorkspaceProviderBinding(workspace.metadata)) return workspace;
+ const owner = workspace.metadata?.workspaceProviderOwner;
+ if (typeof owner !== "string" || !workspace.metadata?.workspaceProviderSource)
+ throw conflict("Workspace storage reservation is unavailable");
+ const operation = workspaceProviderOperationSchema.parse({
+ kind: "prepare",
+ source: workspace.metadata.workspaceProviderSource,
+ mode: workspace.mode,
+ strategy: workspace.strategyType,
+ branchName: workspace.branchName,
+ branchMode: workspace.metadata.workspaceProviderBranchMode ?? "create",
+ baseRef: workspace.baseRef,
+ existing: null,
+ });
+ const result = await callWorkspaceProvider(db, workers, {
+ workspace,
+ pluginId: owner,
+ operation,
+ });
+ if (result.kind !== "prepared")
+ throw conflict("Workspace reconciliation is incomplete");
+ const [updated] = await db.transaction(async (tx) => {
+ await notifyTerminalWorkspaceWork(tx, `workspace:${workspace.id}`);
+ return tx
+ .update(executionWorkspaces)
+ .set({
+ providerRef: result.binding.workspaceRef,
+ branchName: result.branchName,
+ updatedAt: new Date(),
+ metadata: {
+ ...workspace.metadata,
+ workspaceProvider: result.binding,
+ workspaceProviderBaseSha: result.baseSha,
+ createdByRuntime: result.branchCreatedByRuntime,
+ },
+ })
+ .where(
+ and(
+ eq(executionWorkspaces.id, workspace.id),
+ eq(executionWorkspaces.companyId, workspace.companyId),
+ sql`${executionWorkspaces.providerRef} IS NULL`,
+ sql`coalesce((${executionWorkspaces.metadata}->>'lifecycleGeneration')::int, 0) = ${workspace.metadata?.lifecycleGeneration ?? 0}`,
+ ),
+ )
+ .returning();
+ });
+ if (!updated)
+ throw conflict("Workspace changed during reconciliation; retry inspection");
+ return updated;
+}
+
+async function inspectBinding(
+ db: Db,
+ workers: WorkspaceWorkers | undefined,
+ workspace: Workspace,
+) {
+ const binding = readWorkspaceProviderBinding(workspace.metadata);
+ if (!binding) throw conflict("Workspace storage binding is unavailable");
+ const result = await callWorkspaceProvider(db, workers, {
+ workspace,
+ operation: { kind: "inspect", binding },
+ });
+ if (result.kind !== "inspection")
+ throw conflict("Workspace inspection is incomplete");
+ return result;
+}
+
+export async function inspectPluginWorkspace(
+ db: Db,
+ workers: WorkspaceWorkers | undefined,
+ workspace: Workspace,
+) {
+ return withExecutionWorkspaceLifecycleLock(db, workspace.id, async () => {
+ // Keep recovery intent/results durable across an ambiguous provider response.
+ workspace = await reconcilePluginWorkspaceReservation(
+ db,
+ workers,
+ workspace,
+ );
+ if (workspace.metadata?.workspaceProviderRestoration)
+ workspace = await finishPendingRestoration(db, workers, workspace);
+ if (workspace.metadata?.workspaceProviderRemoval)
+ workspace = await finishPendingRemoval(db, workers, workspace);
+ if (workspace.metadata?.workspaceProviderRemoved === true)
+ return removedInspection();
+ return inspectBinding(db, workers, workspace);
+ });
+}
+
+const removedInspection = () => ({
+ kind: "inspection" as const,
+ headSha: null,
+ branchName: null,
+ hasDirtyTrackedFiles: false,
+ hasUntrackedFiles: false,
+ hasLocalOnlyData: false,
+ isMergedIntoBase: null,
+ remotelyRecoverable: true,
+});
+
+async function finishPendingRestoration(
+ db: Db,
+ workers: WorkspaceWorkers | undefined,
+ workspace: Workspace,
+): Promise<Workspace> {
+ const pending = workspace.metadata?.workspaceProviderRestoration as {
+ generation?: unknown;
+ operation?: unknown;
+ };
+ const operation = workspaceProviderOperationSchema.safeParse(
+ pending?.operation,
+ );
+ const generation =
+ (workspace.metadata?.lifecycleGeneration as number | undefined) ?? 0;
+ if (
+ !operation.success ||
+ operation.data.kind !== "prepare" ||
+ pending.generation !== generation + 1 ||
+ JSON.stringify(operation.data.existing) !==
+ JSON.stringify(readWorkspaceProviderBinding(workspace.metadata)) ||
+ !["archived", "cleanup_failed"].includes(workspace.status)
+ )
+ throw conflict("Workspace restoration intent is unavailable or stale");
+ const result = await callWorkspaceProvider(db, workers, {
+ workspace,
+ operation: operation.data,
+ advanceGeneration: true,
+ });
+ if (result.kind !== "prepared")
+ throw conflict("Workspace restoration is incomplete");
+ const [updated] = await db.transaction(async (tx) => {
+ await notifyTerminalWorkspaceWork(tx, `workspace:${workspace.id}`);
+ return tx
+ .update(executionWorkspaces)
+ .set({
+ providerRef: result.binding.workspaceRef,
+ branchName: result.branchName,
+ updatedAt: new Date(),
+ metadata: {
+ ...workspace.metadata,
+ lifecycleGeneration: generation + 1,
+ workspaceProvider: result.binding,
+ workspaceProviderBaseSha: result.baseSha,
+ workspaceProviderRemoved: false,
+ workspaceProviderRestoration: null,
+ },
+ })
+ .where(
+ and(
+ eq(executionWorkspaces.id, workspace.id),
+ eq(executionWorkspaces.companyId, workspace.companyId),
+ eq(executionWorkspaces.status, workspace.status),
+ sql`coalesce((${executionWorkspaces.metadata}->>'lifecycleGeneration')::int, 0) = ${generation}`,
+ sql`${executionWorkspaces.metadata}->'workspaceProviderRestoration' = ${JSON.stringify(pending)}::jsonb`,
+ ),
+ )
+ .returning();
+ });
+ if (!updated)
+ throw conflict("Workspace changed during restoration reconciliation");
+ return updated;
+}
+
+/** Replay the recorded delete before trying to inspect a checkout that may already be gone. */
+async function finishPendingRemoval(
+ db: Db,
+ workers: WorkspaceWorkers | undefined,
+ workspace: Workspace,
+): Promise<Workspace> {
+ if (workspace.metadata?.workspaceProviderRemoved === true) return workspace;
+ const pending = workspace.metadata?.workspaceProviderRemoval as
+ | { generation?: unknown; operation?: unknown }
+ | undefined;
+ const parsed = workspaceProviderOperationSchema.safeParse(pending?.operation);
+ const binding = readWorkspaceProviderBinding(workspace.metadata);
+ if (
+ !parsed.success ||
+ parsed.data.kind !== "remove" ||
+ pending?.generation !== (workspace.metadata?.lifecycleGeneration ?? 0) ||
+ JSON.stringify(parsed.data.binding) !== JSON.stringify(binding)
+ )
+ throw conflict("Workspace removal intent is unavailable or stale");
+ const result = await callWorkspaceProvider(db, workers, {
+ workspace,
+ operation: parsed.data,
+ });
+ if (result.kind !== "removed")
+ throw conflict("Workspace removal is incomplete");
+ const [updated] = await db.transaction(async (tx) => {
+ await notifyTerminalWorkspaceWork(tx, `workspace:${workspace.id}`);
+ return tx
+ .update(executionWorkspaces)
+ .set({
+ ...(workspace.status === "cleanup_failed"
+ ? { status: "archived", cleanupReason: null }
+ : {}),
+ metadata: {
+ ...workspace.metadata,
+ workspaceProviderRemoval: null,
+ workspaceProviderRemoved: true,
+ },
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(executionWorkspaces.id, workspace.id),
+ eq(executionWorkspaces.companyId, workspace.companyId),
+ sql`coalesce((${executionWorkspaces.metadata}->>'lifecycleGeneration')::int, 0) = ${pending!.generation}`,
+ ),
+ )
+ .returning();
+ });
+ if (!updated)
+ throw conflict("Workspace changed during removal reconciliation");
+ return updated;
+}
+
+export async function removePluginWorkspace(
+ db: Db,
+ workers: WorkspaceWorkers | undefined,
+ workspace: Workspace,
+ expectedHeadSha: string | null,
+) {
+ workspace = await reconcilePluginWorkspaceReservation(db, workers, workspace);
+ if (workspace.metadata?.workspaceProviderRestoration)
+ throw conflict("Workspace restoration must be reconciled before removal");
+ if (workspace.metadata?.workspaceProviderRemoved === true) return;
+ if (workspace.metadata?.workspaceProviderRemoval) {
+ await finishPendingRemoval(db, workers, workspace);
+ return;
+ }
+ const binding = readWorkspaceProviderBinding(workspace.metadata);
+ if (!binding) throw conflict("Workspace storage binding is unavailable");
+ const inspection = await inspectBinding(db, workers, workspace);
+ if (
+ inspection.hasDirtyTrackedFiles ||
+ inspection.hasUntrackedFiles ||
+ inspection.hasLocalOnlyData ||
+ inspection.headSha !== expectedHeadSha ||
+ (inspection.remotelyRecoverable !== true &&
+ inspection.isMergedIntoBase !== true)
+ ) {
+ throw conflict(
+ "Workspace has local changes or cannot be recovered remotely",
+ );
+ }
+ const generation = workspace.metadata?.lifecycleGeneration ?? 0;
+ const operation = { kind: "remove" as const, binding, expectedHeadSha };
+ const [pending] = await db.transaction(async (tx) => {
+ await notifyTerminalWorkspaceWork(tx, `workspace:${workspace.id}`);
+ return tx
+ .update(executionWorkspaces)
+ .set({
+ metadata: {
+ ...workspace.metadata,
+ workspaceProviderRemoval: { generation, operation },
+ },
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(executionWorkspaces.id, workspace.id),
+ eq(executionWorkspaces.companyId, workspace.companyId),
+ sql`coalesce((${executionWorkspaces.metadata}->>'lifecycleGeneration')::int, 0) = ${generation}`,
+ eq(executionWorkspaces.providerRef, binding.workspaceRef),
+ ),
+ )
+ .returning();
+ });
+ if (!pending)
+ throw conflict("Workspace changed before removal could be recorded");
+ await finishPendingRemoval(db, workers, pending);
+}
+
+/** An authorized storage edit atomically retires closed, removed dependencies under the reopen fence. */
+export async function retireRemovedPluginWorkspaceDependents(
+ db: Db,
+ projectId: string,
+ sourceId?: string,
+) {
+ const rows = await db
+ .select({ id: executionWorkspaces.id })
+ .from(executionWorkspaces)
+ .where(
+ and(
+ eq(executionWorkspaces.projectId, projectId),
+ eq(executionWorkspaces.providerType, "plugin"),
+ sourceId
+ ? eq(executionWorkspaces.projectWorkspaceId, sourceId)
+ : undefined,
+ ),
+ );
+ for (const { id } of rows.sort((a, b) => a.id.localeCompare(b.id))) {
+ const acquired = await db.execute(
+ sql`select pg_try_advisory_xact_lock(hashtextextended(${`execution_workspace_lifecycle:${id}`}, 0)) as acquired`,
+ );
+ if (!acquired[0]?.acquired)
+ throw conflict("Workspace lifecycle is busy; retry the source edit");
+ const [row] = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, id));
+ if (!row || row.metadata?.workspaceProviderRetired === true) continue;
+ if (
+ row.metadata?.workspaceProviderRemoved !== true ||
+ row.metadata?.workspaceProviderRestoration ||
+ !["archived", "cleanup_failed"].includes(row.status)
+ ) {
+ throw conflict(
+ "Retire managed execution workspaces before changing their storage owner or repository source",
+ );
+ }
+ await db
+ .update(executionWorkspaces)
+ .set({
+ metadata: { ...row.metadata, workspaceProviderRetired: true },
+ updatedAt: new Date(),
+ })
+ .where(eq(executionWorkspaces.id, row.id));
+ }
+}
+
+/** Called inside Core's existing lifecycle fence after task authorization. */
+export async function restorePluginWorkspace(
+ db: Db,
+ workers: WorkspaceWorkers | undefined,
+ workspace: Workspace,
+) {
+ workspace = await reconcilePluginWorkspaceReservation(db, workers, workspace);
+ if (workspace.metadata?.workspaceProviderRetired === true)
+ throw conflict("Workspace storage was retired");
+ if (workspace.metadata?.workspaceProviderRemoval)
+ workspace = await finishPendingRemoval(db, workers, workspace);
+ const binding = readWorkspaceProviderBinding(workspace.metadata);
+ const source = workspace.metadata?.workspaceProviderSource;
+ if (!binding || !source)
+ throw conflict("Workspace restoration recipe is unavailable");
+ const operation = workspaceProviderOperationSchema.parse({
+ kind: "prepare",
+ source,
+ mode: workspace.mode,
+ strategy: workspace.strategyType,
+ branchName: workspace.branchName,
+ branchMode: "existing",
+ baseRef: workspace.baseRef,
+ existing: binding,
+ });
+ const [pending] = await db.transaction(async (tx) => {
+ await notifyTerminalWorkspaceWork(tx, `workspace:${workspace.id}`);
+ return tx
+ .update(executionWorkspaces)
+ .set({
+ metadata: {
+ ...workspace.metadata,
+ workspaceProviderRemoved: false,
+ workspaceProviderRestoration: {
+ generation:
+ ((workspace.metadata?.lifecycleGeneration as number) ?? 0) + 1,
+ operation,
+ },
+ },
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(executionWorkspaces.id, workspace.id),
+ eq(executionWorkspaces.companyId, workspace.companyId),
+ sql`coalesce((${executionWorkspaces.metadata}->>'lifecycleGeneration')::int, 0) = ${workspace.metadata?.lifecycleGeneration ?? 0}`,
+ ),
+ )
+ .returning();
+ });
+ if (!pending)
+ throw conflict("Workspace changed before restoration could be recorded");
+ workspace = pending;
+ const result = await callWorkspaceProvider(db, workers, {
+ workspace,
+ operation,
+ advanceGeneration: true,
+ });
+ if (result.kind !== "prepared")
+ throw conflict("Workspace restoration is incomplete");
+ return {
+ ...workspace.metadata,
+ workspaceProvider: result.binding,
+ workspaceProviderRemoved: false,
+ workspaceProviderRestoration: null,
+ workspaceProviderBaseSha: result.baseSha,
+ };
+}
diff --git a/server/src/services/projects.ts b/server/src/services/projects.ts
index 3c490e04ee..acb4121a6d 100644
--- a/server/src/services/projects.ts
+++ b/server/src/services/projects.ts
@@ -1,3 +1,4 @@
+import { retireRemovedPluginWorkspaceDependents } from "./plugin-workspaces.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
import { enqueueProjectSkillSource, detachProjectSkillSource } from "./project-skill-source-bindings.js";
import { and, asc, desc, eq, gt, inArray, isNull, or, sql } from "drizzle-orm";
@@ -966,11 +967,15 @@ export function projectService(db: Db, options: { captureWorkspaceUpdates?: bool
const { goalIds: inputGoalIds, ...projectData } = data;
const ids = resolveGoalIds({ goalIds: inputGoalIds, goalId: projectData.goalId });
const existingProject = await db
- .select({ id: projects.id, companyId: projects.companyId, name: projects.name, archivedAt: projects.archivedAt })
+ .select({ id: projects.id, companyId: projects.companyId, name: projects.name, archivedAt: projects.archivedAt, executionWorkspacePolicy: projects.executionWorkspacePolicy })
.from(projects)
.where(eq(projects.id, id)).for("update")
.then((rows) => rows[0] ?? null);
if (!existingProject) return null;
+ if (projectData.executionWorkspacePolicy !== undefined &&
+ projectData.executionWorkspacePolicy?.storageProviderPluginId !== existingProject.executionWorkspacePolicy?.storageProviderPluginId) {
+ await retireRemovedPluginWorkspaceDependents(db, id);
+ }
if (ids && ids.length > 0) {
await assertGoalsBelongToCompany(db, existingProject.companyId, ids);
}
@@ -1201,7 +1206,6 @@ export function projectService(db: Db, options: { captureWorkspaceUpdates?: bool
.for("update")
.then((rows) => rows[0] ?? null);
if (!existing) return null;
-
const nextCwd =
data.cwd !== undefined
? normalizeWorkspaceCwd(data.cwd)
@@ -1223,7 +1227,6 @@ export function projectService(db: Db, options: { captureWorkspaceUpdates?: bool
} else if (!nextCwd && !nextRepoUrl) {
return null;
}
-
const patch: Partial<typeof projectWorkspaces.$inferInsert> = {
updatedAt: new Date(),
};
@@ -1256,6 +1259,10 @@ export function projectService(db: Db, options: { captureWorkspaceUpdates?: bool
: data.metadata;
}
+ if (["repoUrl", "repoRef", "defaultRef", "sourceType", "remoteProvider", "remoteWorkspaceRef"].some(key =>
+ key in patch && patch[key as keyof typeof patch] !== existing[key as keyof typeof existing])) {
+ await retireRemovedPluginWorkspaceDependents(db, projectId, workspaceId);
+ }
const updated = await db.transaction(async (tx) => {
if (data.isPrimary === true) {
await tx
@@ -1358,6 +1365,7 @@ export function projectService(db: Db, options: { captureWorkspaceUpdates?: bool
.for("update")
.then((rows) => rows[0] ?? null);
if (!existing) return null;
+ await retireRemovedPluginWorkspaceDependents(db, projectId, workspaceId);
const removed = await db.transaction(async (tx) => {
await detachProjectSkillSource(tx as unknown as Db, existing.companyId, workspaceId);
diff --git a/server/src/services/workspace-realization.ts b/server/src/services/workspace-realization.ts
index f69e393174..ecf1db7a22 100644
--- a/server/src/services/workspace-realization.ts
+++ b/server/src/services/workspace-realization.ts
@@ -1,3 +1,4 @@
+import { workspaceProviderBindingSchema } from "@paperclipai/shared";
import type {
Environment,
EnvironmentLease,
@@ -87,6 +88,7 @@ export function readWorkspaceRealizationRequest(value: unknown): WorkspaceRealiz
? source.kind
: "project_primary",
localPath,
+ ...(source.providerBinding ? { providerBinding: workspaceProviderBindingSchema.parse(source.providerBinding) } : {}),
projectId: readString(source.projectId),
projectWorkspaceId: readString(source.projectWorkspaceId),
repoUrl: readString(source.repoUrl),
@@ -129,6 +131,7 @@ export function buildWorkspaceRealizationRequest(input: {
heartbeatRunId: input.heartbeatRunId,
requestedMode: input.requestedMode,
source: {
+ ...(input.workspace.providerBinding ? { providerBinding: input.workspace.providerBinding } : {}),
kind: input.workspace.source,
localPath: input.workspace.cwd,
projectId: input.workspace.projectId,
diff --git a/server/src/services/workspace-runtime.ts b/server/src/services/workspace-runtime.ts
index b82f7bc140..4fd0db5226 100644
--- a/server/src/services/workspace-runtime.ts
+++ b/server/src/services/workspace-runtime.ts
@@ -134,6 +134,7 @@ export interface ExecutionWorkspaceAdditionalInput {
}
export interface ExecutionWorkspaceInput {
+ providerBinding?: import("@paperclipai/shared").WorkspaceProviderBinding;
baseCwd: string;
source: "project_primary" | "task_session" | "agent_home";
projectId: string | null;
@@ -757,7 +758,7 @@ function sanitizeSlugPart(value: string | null | undefined, fallback: string): s
return normalized.length > 0 ? normalized : fallback;
}
-function renderWorkspaceTemplate(template: string, input: {
+export function renderWorkspaceTemplate(template: string, input: {
issue: ExecutionWorkspaceIssueRef | null;
agent: ExecutionWorkspaceAgentRef;
projectId: string | null;
@@ -785,7 +786,7 @@ function renderWorkspaceTemplate(template: string, input: {
});
}
-function sanitizeBranchName(value: string): string {
+export function sanitizeBranchName(value: string): string {
return value
.trim()
.replace(/[^A-Za-z0-9._/-]+/g, "-")
@@ -4234,6 +4235,7 @@ export async function cleanupExecutionWorkspaceArtifacts(input: {
runCleanupCommands?: boolean;
forceWorktreeRemoval?: boolean;
}) {
+ if (input.workspace.providerType === "plugin") throw new Error("Managed workspace cleanup requires its storage plugin");
const warnings: string[] = [];
const workspacePath = input.workspace.providerRef ?? input.workspace.cwd;
const isolatedSource = await verifiedRecordedIsolatedRemoteSource(input.workspace);