Skip to content

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

fix(worktrees): quarantine cloned runtime services (#11653)

Dotta4b968d8c052f
diff --git a/cli/src/__tests__/worktree.test.ts b/cli/src/__tests__/worktree.test.ts
index dab7f78bfd..ad0edc4a46 100644
--- a/cli/src/__tests__/worktree.test.ts
+++ b/cli/src/__tests__/worktree.test.ts
@@ -11,11 +11,14 @@ import {
authUsers,
companies,
createDb,
+ executionWorkspaces,
issueComments,
issues,
+ projectWorkspaces,
projects,
routines,
routineTriggers,
+ workspaceRuntimeServices,
} from "@paperclipai/db";
import {
copyGitHooksToWorktreeGitDir,
@@ -434,6 +437,9 @@ describe("worktree helpers", () => {
quarantinedInProgressIssues: 1,
unassignedTodoIssues: 1,
unassignedReviewIssues: 1,
+ stoppedProjectWorkspaceRuntimes: 0,
+ stoppedExecutionWorkspaceRuntimes: 0,
+ stoppedRuntimeServices: 0,
},
reboundWorkspaces: [],
});
@@ -540,6 +546,9 @@ describe("worktree helpers", () => {
quarantinedInProgressIssues: 0,
unassignedTodoIssues: 0,
unassignedReviewIssues: 0,
+ stoppedProjectWorkspaceRuntimes: 0,
+ stoppedExecutionWorkspaceRuntimes: 0,
+ stoppedRuntimeServices: 0,
},
reboundWorkspaces: [],
};
@@ -599,6 +608,10 @@ describe("worktree helpers", () => {
const todoIssueId = randomUUID();
const reviewIssueId = randomUUID();
const userIssueId = randomUUID();
+ const projectId = randomUUID();
+ const projectWorkspaceId = randomUUID();
+ const executionWorkspaceId = randomUUID();
+ const runtimeServiceId = randomUUID();
try {
await db.insert(companies).values({
@@ -634,6 +647,64 @@ describe("worktree helpers", () => {
permissions: {},
},
]);
+ await db.insert(projects).values({
+ id: projectId,
+ companyId,
+ name: "Runtime quarantine",
+ status: "in_progress",
+ });
+ await db.insert(projectWorkspaces).values({
+ id: projectWorkspaceId,
+ companyId,
+ projectId,
+ name: "Primary workspace",
+ cwd: "/source/project",
+ metadata: {
+ keep: "project-metadata",
+ runtimeConfig: {
+ workspaceRuntime: { services: [{ name: "paperclip-dev" }] },
+ desiredState: "running",
+ serviceStates: { "0": "running", "1": "manual" },
+ },
+ },
+ });
+ await db.insert(executionWorkspaces).values({
+ id: executionWorkspaceId,
+ companyId,
+ projectId,
+ projectWorkspaceId,
+ mode: "isolated_workspace",
+ strategyType: "git_worktree",
+ name: "Copied runtime workspace",
+ cwd: "/source/worktree",
+ providerType: "git_worktree",
+ metadata: {
+ keep: "execution-metadata",
+ config: {
+ environmentId: "environment-1",
+ desiredState: "running",
+ serviceStates: { "0": "running" },
+ },
+ },
+ });
+ await db.insert(workspaceRuntimeServices).values({
+ id: runtimeServiceId,
+ companyId,
+ projectId,
+ projectWorkspaceId,
+ executionWorkspaceId,
+ scopeType: "project_workspace",
+ scopeId: projectWorkspaceId,
+ serviceName: "paperclip-dev",
+ status: "running",
+ lifecycle: "shared",
+ provider: "local_process",
+ providerRef: "12345",
+ ownerAgentId: agentId,
+ port: 42013,
+ url: "https://paperclip-dev.example.test:42013",
+ healthStatus: "healthy",
+ });
await db.insert(issues).values([
{
id: inProgressIssueId,
@@ -685,6 +756,9 @@ describe("worktree helpers", () => {
quarantinedInProgressIssues: 1,
unassignedTodoIssues: 1,
unassignedReviewIssues: 1,
+ stoppedProjectWorkspaceRuntimes: 1,
+ stoppedExecutionWorkspaceRuntimes: 1,
+ stoppedRuntimeServices: 1,
});
const [quarantinedAgent] = await db.select().from(agents).where(eq(agents.id, agentId));
@@ -715,6 +789,47 @@ describe("worktree helpers", () => {
const comments = await db.select().from(issueComments).where(eq(issueComments.issueId, inProgressIssueId));
expect(comments).toHaveLength(1);
expect(comments[0]?.body).toContain("Quarantined during worktree seed");
+
+ const [projectWorkspace] = await db
+ .select()
+ .from(projectWorkspaces)
+ .where(eq(projectWorkspaces.id, projectWorkspaceId));
+ expect(projectWorkspace?.metadata).toEqual({
+ keep: "project-metadata",
+ runtimeConfig: {
+ workspaceRuntime: { services: [{ name: "paperclip-dev" }] },
+ desiredState: "stopped",
+ serviceStates: { "0": "stopped", "1": "manual" },
+ },
+ });
+
+ const [executionWorkspace] = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, executionWorkspaceId));
+ expect(executionWorkspace?.metadata).toEqual({
+ keep: "execution-metadata",
+ config: {
+ environmentId: "environment-1",
+ desiredState: "stopped",
+ serviceStates: { "0": "stopped" },
+ },
+ });
+
+ const [runtimeService] = await db
+ .select()
+ .from(workspaceRuntimeServices)
+ .where(eq(workspaceRuntimeServices.id, runtimeServiceId));
+ expect(runtimeService).toMatchObject({
+ status: "stopped",
+ healthStatus: "unknown",
+ providerRef: null,
+ ownerAgentId: null,
+ startedByRunId: null,
+ port: null,
+ url: null,
+ });
+ expect(runtimeService?.stoppedAt).toBeInstanceOf(Date);
} finally {
await db.$client?.end?.({ timeout: 5 }).catch(() => undefined);
await tempDb.cleanup();
diff --git a/cli/src/commands/worktree.ts b/cli/src/commands/worktree.ts
index fe07f3ce61..7adee70c8a 100644
--- a/cli/src/commands/worktree.ts
+++ b/cli/src/commands/worktree.ts
@@ -30,6 +30,7 @@ import {
documentRevisions,
documents,
ensurePostgresDatabase,
+ executionWorkspaces,
formatDatabaseBackupResult,
goals,
heartbeatRuns,
@@ -45,6 +46,7 @@ import {
runDatabaseBackup,
runDatabaseRestore,
resetPostgresDatabase,
+ workspaceRuntimeServices,
createEmbeddedPostgresLogBuffer,
formatEmbeddedPostgresError,
prepareEmbeddedPostgresNativeRuntime,
@@ -233,6 +235,9 @@ export type SeededWorktreeExecutionQuarantineSummary = {
quarantinedInProgressIssues: number;
unassignedTodoIssues: number;
unassignedReviewIssues: number;
+ stoppedProjectWorkspaceRuntimes: number;
+ stoppedExecutionWorkspaceRuntimes: number;
+ stoppedRuntimeServices: number;
};
function nonEmpty(value: string | null | undefined): string | null {
@@ -256,6 +261,9 @@ function formatSeededWorktreeExecutionQuarantineSummary(
`quarantined in-progress issues: ${summary.quarantinedInProgressIssues}`,
`unassigned todo issues: ${summary.unassignedTodoIssues}`,
`unassigned review issues: ${summary.unassignedReviewIssues}`,
+ `stopped project workspace runtimes: ${summary.stoppedProjectWorkspaceRuntimes}`,
+ `stopped execution workspace runtimes: ${summary.stoppedExecutionWorkspaceRuntimes}`,
+ `stopped runtime services: ${summary.stoppedRuntimeServices}`,
].join(", ");
}
@@ -1187,6 +1195,9 @@ const EMPTY_SEEDED_WORKTREE_EXECUTION_QUARANTINE_SUMMARY: SeededWorktreeExecutio
quarantinedInProgressIssues: 0,
unassignedTodoIssues: 0,
unassignedReviewIssues: 0,
+ stoppedProjectWorkspaceRuntimes: 0,
+ stoppedExecutionWorkspaceRuntimes: 0,
+ stoppedRuntimeServices: 0,
};
function isRecord(value: unknown): value is Record<string, unknown> {
@@ -1218,6 +1229,36 @@ function normalizeWorktreeRuntimeConfig(runtimeConfig: unknown): {
return { runtimeConfig: nextRuntimeConfig, disabledTimerHeartbeat: false, changed: false };
}
+function stopSeededWorkspaceRuntime(
+ metadata: unknown,
+ configKey: "config" | "runtimeConfig",
+): { metadata: Record<string, unknown>; changed: boolean } {
+ const nextMetadata = isRecord(metadata) ? { ...metadata } : {};
+ const currentConfig = isRecord(nextMetadata[configKey])
+ ? { ...(nextMetadata[configKey] as Record<string, unknown>) }
+ : null;
+ if (!currentConfig) return { metadata: nextMetadata, changed: false };
+
+ let changed = false;
+ if (currentConfig.desiredState === "running") {
+ currentConfig.desiredState = "stopped";
+ changed = true;
+ }
+
+ if (isRecord(currentConfig.serviceStates)) {
+ const nextServiceStates = { ...currentConfig.serviceStates };
+ for (const [serviceIndex, state] of Object.entries(nextServiceStates)) {
+ if (state !== "running") continue;
+ nextServiceStates[serviceIndex] = "stopped";
+ changed = true;
+ }
+ if (changed) currentConfig.serviceStates = nextServiceStates;
+ }
+
+ if (changed) nextMetadata[configKey] = currentConfig;
+ return { metadata: nextMetadata, changed };
+}
+
export async function quarantineSeededWorktreeExecutionState(
connectionString: string,
): Promise<SeededWorktreeExecutionQuarantineSummary> {
@@ -1300,6 +1341,50 @@ export async function quarantineSeededWorktreeExecutionState(
summary.unassignedReviewIssues += 1;
}
}
+
+ const seededProjectWorkspaces = await tx
+ .select({ id: projectWorkspaces.id, metadata: projectWorkspaces.metadata })
+ .from(projectWorkspaces);
+ for (const workspace of seededProjectWorkspaces) {
+ const stopped = stopSeededWorkspaceRuntime(workspace.metadata, "runtimeConfig");
+ if (!stopped.changed) continue;
+ await tx
+ .update(projectWorkspaces)
+ .set({ metadata: stopped.metadata, updatedAt: new Date() })
+ .where(eq(projectWorkspaces.id, workspace.id));
+ summary.stoppedProjectWorkspaceRuntimes += 1;
+ }
+
+ const seededExecutionWorkspaces = await tx
+ .select({ id: executionWorkspaces.id, metadata: executionWorkspaces.metadata })
+ .from(executionWorkspaces);
+ for (const workspace of seededExecutionWorkspaces) {
+ const stopped = stopSeededWorkspaceRuntime(workspace.metadata, "config");
+ if (!stopped.changed) continue;
+ await tx
+ .update(executionWorkspaces)
+ .set({ metadata: stopped.metadata, updatedAt: new Date() })
+ .where(eq(executionWorkspaces.id, workspace.id));
+ summary.stoppedExecutionWorkspaceRuntimes += 1;
+ }
+
+ const now = new Date();
+ const stoppedRuntimeServices = await tx
+ .update(workspaceRuntimeServices)
+ .set({
+ status: "stopped",
+ healthStatus: "unknown",
+ providerRef: null,
+ ownerAgentId: null,
+ startedByRunId: null,
+ port: null,
+ url: null,
+ stoppedAt: now,
+ lastUsedAt: now,
+ updatedAt: now,
+ })
+ .returning({ id: workspaceRuntimeServices.id });
+ summary.stoppedRuntimeServices = stoppedRuntimeServices.length;
});
return summary;
@@ -3593,7 +3678,7 @@ export function registerWorktreeCommands(program: Command): void {
.option("--server-port <port>", "Preferred server port", (value) => Number(value))
.option("--db-port <port>", "Preferred embedded Postgres port", (value) => Number(value))
.option("--seed-mode <mode>", "Seed profile: minimal or full (default: minimal)", "minimal")
- .option("--preserve-live-work", "Do not quarantine copied agent timers or assigned open issues in the seeded worktree", false)
+ .option("--preserve-live-work", "Do not quarantine copied agent work or workspace runtime services in the seeded worktree", false)
.option("--no-seed", "Skip database seeding from the source instance")
.option("--force", "Replace existing repo-local config and isolated instance data", false)
.action(worktreeMakeCommand);
@@ -3610,7 +3695,7 @@ export function registerWorktreeCommands(program: Command): void {
.option("--server-port <port>", "Preferred server port", (value) => Number(value))
.option("--db-port <port>", "Preferred embedded Postgres port", (value) => Number(value))
.option("--seed-mode <mode>", "Seed profile: minimal or full (default: minimal)", "minimal")
- .option("--preserve-live-work", "Do not quarantine copied agent timers or assigned open issues in the seeded worktree", false)
+ .option("--preserve-live-work", "Do not quarantine copied agent work or workspace runtime services in the seeded worktree", false)
.option("--no-seed", "Skip database seeding from the source instance")
.option("--force", "Replace existing repo-local config and isolated instance data", false)
.action(worktreeInitCommand);
@@ -3629,7 +3714,7 @@ export function registerWorktreeCommands(program: Command): void {
.option("--from-config <path>", "Source config.json to seed from (defaults to the seed-pending marker)")
.option("--from-data-dir <path>", "Source PAPERCLIP_HOME used when deriving the source config")
.option("--from-instance <id>", "Source instance id when deriving the source config")
- .option("--preserve-live-work", "Do not quarantine copied agent timers or assigned open issues", false)
+ .option("--preserve-live-work", "Do not quarantine copied agent work or workspace runtime services", false)
.action(worktreeEnsureSeededCommand);
program
@@ -3660,7 +3745,7 @@ export function registerWorktreeCommands(program: Command): void {
.option("--from-data-dir <path>", "Source PAPERCLIP_HOME used when deriving the source config")
.option("--from-instance <id>", "Source instance id when deriving the source config")
.option("--seed-mode <mode>", "Seed profile: minimal or full (default: full)", "full")
- .option("--preserve-live-work", "Do not quarantine copied agent timers or assigned open issues in the seeded worktree", false)
+ .option("--preserve-live-work", "Do not quarantine copied agent work or workspace runtime services in the seeded worktree", false)
.option("--yes", "Skip the destructive confirmation prompt", false)
.option("--allow-live-target", "Override the guard that requires the target worktree DB to be stopped first", false)
.action(worktreeReseedCommand);
@@ -3674,7 +3759,7 @@ export function registerWorktreeCommands(program: Command): void {
.option("--from-data-dir <path>", "Source PAPERCLIP_HOME used when deriving the source config")
.option("--from-instance <id>", "Source instance id when deriving the source config (default: default)")
.option("--seed-mode <mode>", "Seed profile: minimal or full (default: minimal)", "minimal")
- .option("--preserve-live-work", "Do not quarantine copied agent timers or assigned open issues in the seeded worktree", false)
+ .option("--preserve-live-work", "Do not quarantine copied agent work or workspace runtime services in the seeded worktree", false)
.option("--no-seed", "Repair metadata only and skip reseeding when bootstrapping a missing worktree config", false)
.option("--allow-live-target", "Override the guard that requires the target worktree DB to be stopped first", false)
.action(worktreeRepairCommand);
diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md
index b2bf7cc7d4..4c448aaa38 100644
--- a/doc/DEVELOPING.md
+++ b/doc/DEVELOPING.md
@@ -469,6 +469,8 @@ Seed modes:
Seeded worktree instances quarantine copied live execution by default for both `minimal` and `full` seeds. During restore, Paperclip disables copied agent timer heartbeats, resets copied `running` agents to `idle`, blocks and unassigns copied agent-owned `in_progress` issues, and unassigns copied agent-owned `todo`/`in_review` issues. This keeps a freshly booted worktree from starting agents for work already owned by the source instance. Pass `--preserve-live-work` only when you intentionally want the isolated worktree to resume copied assignments.
+The same quarantine stops copied project/execution-workspace runtime desired states and clears copied runtime process claims. Without this reset, booting the cloned Paperclip database could restart a source workspace's dev service from the isolated instance, creating duplicate runners, port reassignment, and stale public URLs.
+
After `worktree init`, both the server and the CLI auto-load the repo-local `.paperclip/.env` when run inside that worktree, so normal commands like `pnpm dev`, `paperclipai doctor`, and `paperclipai db:backup` stay scoped to the worktree instance.
`pnpm dev` now fails fast in a linked git worktree when `.paperclip/.env` is missing, instead of silently booting against the default instance/port. If that happens, run `paperclipai worktree init` in the worktree first.