From 173d6d2a71958b31ee9973f94ac71506f6f8dd68 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 1 Aug 2026 20:41:11 -0500 Subject: [PATCH] Reclaim isolated worktree instances during teardown (#10649) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Paperclip creates isolated instances for server-managed git worktrees. > - The worktree teardown path removes the git worktree but leaves its isolated instance directory behind. > - The leaked directory can retain an embedded PostgreSQL process and database files. > - Teardown must remove only the collision-resistant instance assigned to that exact worktree path. > - This pull request stops the verified embedded PostgreSQL process and removes the guarded instance directory. > - The benefit is complete worktree cleanup without risk to another, default, or live Paperclip instance. ## Linked Issues or Issue Description **What happened?** Closing a server-managed git worktree removed the git worktree and branch, but it left the isolated Paperclip instance directory behind. A live embedded PostgreSQL process could also keep running against that directory. **Expected behavior** Worktree teardown must stop the isolated embedded PostgreSQL process and remove only the instance assigned to that exact worktree. It must refuse mismatched instance IDs and all paths outside `PAPERCLIP_WORKTREES_DIR/instances/`. **Steps to reproduce** 1. Create a server-managed git worktree with a repo-local `.paperclip/.env` file. 2. Start its isolated embedded PostgreSQL instance. 3. Close the execution workspace. 4. Observe that the git worktree is removed but the isolated instance directory remains. **Paperclip version or commit** The bug reproduces on `master` before this change. **Deployment mode** Local development with a server-managed git worktree and embedded PostgreSQL. ## What Changed - Give server-managed worktrees collision-resistant instance IDs derived from their resolved absolute paths. - Capture the repo-local instance pointer before custom teardown commands can remove it. - Require the pointer's instance ID to match the exact worktree-derived ID. - Resolve and validate the instance path against the canonical managed worktree instance root. - Verify and stop the matching embedded PostgreSQL process before directory removal, including process-exit races. - Record successful and refused cleanup operations in the workspace operation log. - Add focused ownership, process-race, path-safety, and runtime integration tests. - Document automatic isolated-instance cleanup for server-managed worktrees. ## Verification - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/workspace-instance-cleanup.test.ts` — 9 tests passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/workspace-runtime.test.ts -t "records teardown and cleanup operations when a recorder is provided"` — 1 test passed and 99 tests skipped. - `node scripts/__tests__/provision-worktree-self-heal.test.mjs` — 4 tests passed. - `bash -n scripts/provision-worktree.sh` — passed. - `pnpm --filter @paperclipai/server build` — passed. - `git diff --check` — passed. ## Risks The main risk is removal of the wrong instance directory. Provisioning assigns a path-derived ID with a SHA-256 suffix, and cleanup requires that exact ID in addition to a safe instance identifier, an absolute configured home, a strict child path, canonical path checks, and a second canonical path check immediately before removal. It refuses legacy or mismatched IDs, symlink escapes, and all paths outside the managed worktree instance root. Cleanup failures become visible warnings and do not delete an unverified path. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used OpenAI Codex with GPT-5. The runtime does not expose the exact model snapshot or context-window size. The agent used reasoning, repository tools, GitHub tools, and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip Co-authored-by: Paperclip --- doc/DEVELOPING.md | 2 + scripts/provision-worktree.sh | 42 ++- .../workspace-instance-cleanup.test.ts | 279 ++++++++++++++ .../src/__tests__/workspace-runtime.test.ts | 24 +- .../services/workspace-instance-cleanup.ts | 345 ++++++++++++++++++ server/src/services/workspace-runtime.ts | 32 ++ 6 files changed, 709 insertions(+), 15 deletions(-) create mode 100644 server/src/__tests__/workspace-instance-cleanup.test.ts create mode 100644 server/src/services/workspace-instance-cleanup.ts diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index 821f864da3e..9c0576464e2 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -442,6 +442,8 @@ The server/UI use those values for worktree-specific branding such as the top ba Authenticated worktree servers also use the `PAPERCLIP_INSTANCE_ID` value to scope Better Auth cookie names. Browser cookies are shared by host rather than port, so this prevents logging into one `127.0.0.1:` worktree from replacing another worktree server's session cookie. +When Paperclip closes a server-managed git worktree, it also reclaims the isolated instance referenced by that worktree's repo-local `.paperclip/.env`. New server-managed worktrees use a collision-resistant instance id derived from the resolved absolute worktree path. Cleanup requires that exact id, stops a running embedded PostgreSQL process, and then removes the instance directory. The deletion guard only accepts canonical instance paths below `PAPERCLIP_WORKTREES_DIR/instances/`; legacy or mismatched ids, pointers to the default/live Paperclip home, and all other locations are logged and left untouched. + Print shell exports explicitly when needed: ```sh diff --git a/scripts/provision-worktree.sh b/scripts/provision-worktree.sh index fbfdda97b80..0c1f9a301ff 100644 --- a/scripts/provision-worktree.sh +++ b/scripts/provision-worktree.sh @@ -9,6 +9,22 @@ paperclip_dir="$worktree_cwd/.paperclip" worktree_config_path="$paperclip_dir/config.json" worktree_env_path="$paperclip_dir/.env" worktree_name="${PAPERCLIP_WORKSPACE_BRANCH:-$(basename "$worktree_cwd")}" +worktree_instance_id="$(WORKTREE_CWD="$worktree_cwd" node <<'EOF' +const crypto = require("node:crypto"); +const path = require("node:path"); + +const resolvedWorkspacePath = path.resolve(process.env.WORKTREE_CWD); +const normalized = path.basename(resolvedWorkspacePath) + .trim() + .toLowerCase() + .replace(/[^a-z0-9_-]+/g, "-") + .replace(/-+/g, "-") + .replace(/^[-_]+|[-_]+$/g, ""); +const prefix = (normalized || "worktree").slice(0, 48); +const pathHash = crypto.createHash("sha256").update(resolvedWorkspacePath).digest("hex").slice(0, 12); +process.stdout.write(`${prefix}-${pathHash}`); +EOF +)" if [[ ! -d "$base_cwd" ]]; then echo "Base workspace does not exist: $base_cwd" >&2 @@ -95,7 +111,7 @@ run_isolated_worktree_init() { if ensure_base_cli_healthy; then ( cd "$worktree_cwd" && - node "$base_cli_runner_path" "$base_cli_entry_path" worktree init --force --seed-mode minimal --name "$worktree_name" --from-config "$source_config_path" + node "$base_cli_runner_path" "$base_cli_entry_path" worktree init --force --seed-mode minimal --name "$worktree_name" --instance "$worktree_instance_id" --from-config "$source_config_path" ) return fi @@ -103,7 +119,7 @@ run_isolated_worktree_init() { if command -v pnpm >/dev/null 2>&1 && pnpm paperclipai --help >/dev/null 2>&1; then ( cd "$worktree_cwd" && - pnpm paperclipai worktree init --force --seed-mode minimal --name "$worktree_name" --from-config "$source_config_path" + pnpm paperclipai worktree init --force --seed-mode minimal --name "$worktree_name" --instance "$worktree_instance_id" --from-config "$source_config_path" ) return fi @@ -111,7 +127,7 @@ run_isolated_worktree_init() { if command -v paperclipai >/dev/null 2>&1; then ( cd "$worktree_cwd" && - paperclipai worktree init --force --seed-mode minimal --name "$worktree_name" --from-config "$source_config_path" + paperclipai worktree init --force --seed-mode minimal --name "$worktree_name" --instance "$worktree_instance_id" --from-config "$source_config_path" ) return fi @@ -138,6 +154,7 @@ paperclipai_command_available() { existing_worktree_config_is_usable() { WORKTREE_CONFIG_PATH="$worktree_config_path" \ WORKTREE_ENV_PATH="$worktree_env_path" \ + WORKTREE_INSTANCE_ID="$worktree_instance_id" \ node <<'EOF' const fs = require("node:fs"); const os = require("node:os"); @@ -187,9 +204,13 @@ if (envConfigPath && path.resolve(envConfigPath) !== configPath) { const homeDir = expandHomePrefix(env.PAPERCLIP_HOME); const instanceId = env.PAPERCLIP_INSTANCE_ID; +const expectedInstanceId = process.env.WORKTREE_INSTANCE_ID; if (!homeDir || !instanceId) { fail("existing worktree env is missing PAPERCLIP_HOME or PAPERCLIP_INSTANCE_ID"); } +if (instanceId !== expectedInstanceId) { + fail(`existing worktree env names legacy or mismatched instance ${instanceId}, expected ${expectedInstanceId}`); +} if (!fs.existsSync(homeDir)) { fail(`existing worktree home does not exist on this host: ${homeDir}`); } @@ -220,6 +241,7 @@ write_fallback_worktree_config() { PAPERCLIP_DIR="$paperclip_dir" \ SOURCE_CONFIG_PATH="$source_config_path" \ SOURCE_ENV_PATH="$source_env_path" \ + WORKTREE_INSTANCE_ID="$worktree_instance_id" \ PAPERCLIP_WORKTREES_DIR="${PAPERCLIP_WORKTREES_DIR:-}" \ node <<'EOF' const fs = require("node:fs"); @@ -238,15 +260,6 @@ function nonEmpty(value) { return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; } -function sanitizeInstanceId(value) { - const trimmed = String(value ?? "").trim().toLowerCase(); - const normalized = trimmed - .replace(/[^a-z0-9_-]+/g, "-") - .replace(/-+/g, "-") - .replace(/^[-_]+|[-_]+$/g, ""); - return normalized || "worktree"; -} - function parseEnvFile(contents) { const entries = {}; for (const rawLine of contents.split(/\r?\n/)) { @@ -334,7 +347,10 @@ async function main() { const sourceConfigPath = process.env.SOURCE_CONFIG_PATH; const sourceEnvPath = process.env.SOURCE_ENV_PATH; const worktreeHome = path.resolve(expandHomePrefix(nonEmpty(process.env.PAPERCLIP_WORKTREES_DIR) ?? "~/.paperclip-worktrees")); - const instanceId = sanitizeInstanceId(worktreeName); + const instanceId = process.env.WORKTREE_INSTANCE_ID; + if (!/^[A-Za-z0-9_-]+$/.test(instanceId ?? "")) { + throw new Error("WORKTREE_INSTANCE_ID is missing or unsafe"); + } const instanceRoot = path.resolve(worktreeHome, "instances", instanceId); const configPath = path.resolve(paperclipDir, "config.json"); const envPath = path.resolve(paperclipDir, ".env"); diff --git a/server/src/__tests__/workspace-instance-cleanup.test.ts b/server/src/__tests__/workspace-instance-cleanup.test.ts new file mode 100644 index 00000000000..8bf00660389 --- /dev/null +++ b/server/src/__tests__/workspace-instance-cleanup.test.ts @@ -0,0 +1,279 @@ +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + cleanupWorktreeInstanceArtifacts, + deriveWorktreeInstanceId, + readWorktreeInstancePointer, + stopEmbeddedPostgresIfRunning, +} from "../services/workspace-instance-cleanup.js"; +import type { WorkspaceOperation } from "@paperclipai/shared"; +import type { WorkspaceOperationRecorder } from "../services/workspace-operations.js"; + +const tempRoots = new Set(); + +async function makeTempRoot(prefix: string): Promise { + const root = await fs.mkdtemp(path.join(os.tmpdir(), prefix)); + tempRoots.add(root); + return root; +} + +async function writeWorkspaceEnv(workspacePath: string, homeDir: string, instanceId: string): Promise { + const envDir = path.join(workspacePath, ".paperclip"); + await fs.mkdir(envDir, { recursive: true }); + await fs.writeFile( + path.join(envDir, ".env"), + `PAPERCLIP_HOME=${JSON.stringify(homeDir)}\nPAPERCLIP_INSTANCE_ID=${JSON.stringify(instanceId)}\n`, + "utf8", + ); +} + +function createRecorderDouble() { + const operations: Array<{ + status: string; + metadata: Record | null; + system: string | null; + }> = []; + const recorder: WorkspaceOperationRecorder = { + attachExecutionWorkspaceId: async () => {}, + recordOperation: async (input) => { + const result = await input.run(); + operations.push({ + status: result.status ?? "succeeded", + metadata: input.metadata ?? null, + system: result.system ?? null, + }); + return { + id: `op-${operations.length}`, + companyId: "company-1", + executionWorkspaceId: null, + heartbeatRunId: null, + issueId: null, + phase: input.phase, + command: input.command ?? null, + cwd: input.cwd ?? null, + status: (result.status ?? "succeeded") as WorkspaceOperation["status"], + exitCode: result.exitCode ?? null, + logStore: null, + logRef: null, + logBytes: null, + logSha256: null, + logCompressed: false, + stdoutExcerpt: result.stdout ?? null, + stderrExcerpt: result.stderr ?? null, + metadata: input.metadata ?? null, + startedAt: new Date(), + finishedAt: new Date(), + createdAt: new Date(), + updatedAt: new Date(), + }; + }, + }; + return { recorder, operations }; +} + +afterEach(async () => { + await Promise.all(Array.from(tempRoots, (root) => fs.rm(root, { recursive: true, force: true }))); + tempRoots.clear(); + vi.restoreAllMocks(); +}); + +describe("worktree instance cleanup", () => { + it("derives different instance IDs for distinct paths with the same normalized name", () => { + const parent = path.join(os.tmpdir(), "paperclip-instance-id-collision"); + const plusPath = path.join(parent, "feature+cleanup"); + const dashPath = path.join(parent, "feature-cleanup"); + + expect(deriveWorktreeInstanceId(plusPath)).not.toBe(deriveWorktreeInstanceId(dashPath)); + expect(deriveWorktreeInstanceId(plusPath)).toMatch(/^feature-cleanup-[a-f0-9]{12}$/); + expect(deriveWorktreeInstanceId(dashPath)).toMatch(/^feature-cleanup-[a-f0-9]{12}$/); + }); + + it("removes an instance directory inside the managed worktree instances root", async () => { + const worktreesDir = await makeTempRoot("paperclip-managed-worktrees-"); + const workspacePath = await makeTempRoot("paperclip-cleanup-workspace-"); + const instanceId = "pap-16075"; + const instanceRoot = path.join(worktreesDir, "instances", instanceId); + await fs.mkdir(path.join(instanceRoot, "db"), { recursive: true }); + await fs.writeFile(path.join(instanceRoot, "marker"), "remove me", "utf8"); + await writeWorkspaceEnv(workspacePath, worktreesDir, instanceId); + + const pointer = await readWorktreeInstancePointer(workspacePath); + expect(pointer).not.toBeNull(); + const result = await cleanupWorktreeInstanceArtifacts({ + pointer: pointer!, + workspaceId: "workspace-1", + workspacePath, + expectedInstanceId: instanceId, + worktreesDir, + }); + + expect(result).toMatchObject({ status: "removed", postgresStopped: false }); + await expect(fs.stat(instanceRoot)).rejects.toMatchObject({ code: "ENOENT" }); + }); + + it("refuses and logs an instance pointer outside the managed worktree root", async () => { + const worktreesDir = await makeTempRoot("paperclip-managed-worktrees-"); + const liveHome = await makeTempRoot("paperclip-live-home-"); + const workspacePath = await makeTempRoot("paperclip-cleanup-workspace-"); + const liveInstanceRoot = path.join(liveHome, "instances", "default"); + await fs.mkdir(liveInstanceRoot, { recursive: true }); + await fs.writeFile(path.join(liveInstanceRoot, "marker"), "keep me", "utf8"); + await writeWorkspaceEnv(workspacePath, liveHome, "default"); + const { recorder, operations } = createRecorderDouble(); + const stopEmbeddedPostgres = vi.fn(async () => false); + const removeInstanceRoot = vi.fn(async () => {}); + + const pointer = await readWorktreeInstancePointer(workspacePath); + const result = await cleanupWorktreeInstanceArtifacts({ + pointer: pointer!, + workspaceId: "workspace-1", + workspacePath, + expectedInstanceId: "default", + worktreesDir, + recorder, + dependencies: { stopEmbeddedPostgres, removeInstanceRoot }, + }); + + expect(result).toMatchObject({ status: "refused", instanceRoot: liveInstanceRoot }); + expect(stopEmbeddedPostgres).not.toHaveBeenCalled(); + expect(removeInstanceRoot).not.toHaveBeenCalled(); + expect(await fs.readFile(path.join(liveInstanceRoot, "marker"), "utf8")).toBe("keep me"); + expect(operations).toEqual([ + expect.objectContaining({ + status: "skipped", + metadata: expect.objectContaining({ + cleanupAction: "remove_worktree_instance", + refusalReason: "outside_managed_instances_dir", + }), + }), + ]); + }); + + it("treats a missing repo-local env file as a no-op", async () => { + const workspacePath = await makeTempRoot("paperclip-cleanup-workspace-"); + await expect(readWorktreeInstancePointer(workspacePath)).resolves.toBeNull(); + }); + + it("stops embedded Postgres before deleting the instance root", async () => { + const worktreesDir = await makeTempRoot("paperclip-managed-worktrees-"); + const workspacePath = await makeTempRoot("paperclip-cleanup-workspace-"); + const instanceRoot = path.join(worktreesDir, "instances", "ordered-cleanup"); + await fs.mkdir(path.join(instanceRoot, "db"), { recursive: true }); + await writeWorkspaceEnv(workspacePath, worktreesDir, "ordered-cleanup"); + const calls: string[] = []; + + const pointer = await readWorktreeInstancePointer(workspacePath); + const result = await cleanupWorktreeInstanceArtifacts({ + pointer: pointer!, + workspaceId: "workspace-1", + workspacePath, + expectedInstanceId: "ordered-cleanup", + worktreesDir, + dependencies: { + stopEmbeddedPostgres: async (dataDir) => { + expect(dataDir).toBe(path.join(instanceRoot, "db")); + expect(await fs.stat(instanceRoot)).toBeDefined(); + calls.push("stop"); + return true; + }, + removeInstanceRoot: async (target) => { + calls.push("remove"); + await fs.rm(target, { recursive: true, force: true }); + }, + }, + }); + + expect(result).toMatchObject({ status: "removed", postgresStopped: true }); + expect(calls).toEqual(["stop", "remove"]); + }); + + it("refuses a managed-root symlink that canonically escapes the guard", async () => { + const worktreesDir = await makeTempRoot("paperclip-managed-worktrees-"); + const outsideRoot = await makeTempRoot("paperclip-outside-instance-"); + const workspacePath = await makeTempRoot("paperclip-cleanup-workspace-"); + const instancesDir = path.join(worktreesDir, "instances"); + await fs.mkdir(instancesDir, { recursive: true }); + await fs.symlink(outsideRoot, path.join(instancesDir, "escaped"), "dir"); + await writeWorkspaceEnv(workspacePath, worktreesDir, "escaped"); + + const pointer = await readWorktreeInstancePointer(workspacePath); + const result = await cleanupWorktreeInstanceArtifacts({ + pointer: pointer!, + workspaceId: "workspace-1", + workspacePath, + expectedInstanceId: "escaped", + worktreesDir, + }); + + expect(result).toMatchObject({ status: "refused" }); + expect((result as { warning: string }).warning).toContain("canonical path"); + await expect(fs.stat(outsideRoot)).resolves.toBeDefined(); + }); + + it("refuses when the managed instances directory itself is a symlink", async () => { + const worktreesDir = await makeTempRoot("paperclip-managed-worktrees-"); + const liveInstancesDir = await makeTempRoot("paperclip-live-instances-"); + const workspacePath = await makeTempRoot("paperclip-cleanup-workspace-"); + const liveInstanceRoot = path.join(liveInstancesDir, "default"); + await fs.mkdir(liveInstanceRoot, { recursive: true }); + await fs.symlink(liveInstancesDir, path.join(worktreesDir, "instances"), "dir"); + await writeWorkspaceEnv(workspacePath, worktreesDir, "default"); + + const pointer = await readWorktreeInstancePointer(workspacePath); + const result = await cleanupWorktreeInstanceArtifacts({ + pointer: pointer!, + workspaceId: "workspace-1", + workspacePath, + expectedInstanceId: "default", + worktreesDir, + }); + + expect(result).toMatchObject({ status: "refused" }); + expect((result as { warning: string }).warning).toContain("managed instances directory"); + await expect(fs.stat(liveInstanceRoot)).resolves.toBeDefined(); + }); + + it("refuses an instance pointer that belongs to a sibling worktree", async () => { + const worktreesDir = await makeTempRoot("paperclip-managed-worktrees-"); + const workspacePath = await makeTempRoot("paperclip-cleanup-workspace-"); + const siblingRoot = path.join(worktreesDir, "instances", "sibling-worktree"); + await fs.mkdir(siblingRoot, { recursive: true }); + await fs.writeFile(path.join(siblingRoot, "marker"), "keep me", "utf8"); + await writeWorkspaceEnv(workspacePath, worktreesDir, "sibling-worktree"); + const stopEmbeddedPostgres = vi.fn(async () => false); + const removeInstanceRoot = vi.fn(async () => {}); + + const pointer = await readWorktreeInstancePointer(workspacePath); + const result = await cleanupWorktreeInstanceArtifacts({ + pointer: pointer!, + workspaceId: "workspace-1", + workspacePath, + expectedInstanceId: "owned-worktree", + worktreesDir, + dependencies: { stopEmbeddedPostgres, removeInstanceRoot }, + }); + + expect(result).toMatchObject({ status: "refused", instanceRoot: siblingRoot }); + expect((result as { warning: string }).warning).toContain("does not match the expected workspace instance"); + expect(stopEmbeddedPostgres).not.toHaveBeenCalled(); + expect(removeInstanceRoot).not.toHaveBeenCalled(); + expect(await fs.readFile(path.join(siblingRoot, "marker"), "utf8")).toBe("keep me"); + }); + + it("treats an ESRCH signal race as an already-stopped PostgreSQL process", async () => { + const instanceRoot = await makeTempRoot("paperclip-postgres-exit-race-"); + const dataDir = path.join(instanceRoot, "db"); + await fs.mkdir(dataDir, { recursive: true }); + await fs.writeFile(path.join(dataDir, "postmaster.pid"), `4242\n${dataDir}\n`, "utf8"); + const signalError = Object.assign(new Error("process exited"), { code: "ESRCH" }); + + await expect(stopEmbeddedPostgresIfRunning(dataDir, { + processIsAlive: () => true, + readVerifiedPostgresCommand: async () => `postgres -D ${dataDir}`, + signalProcess: () => { throw signalError; }, + wait: async () => {}, + })).resolves.toBe(false); + }); +}); diff --git a/server/src/__tests__/workspace-runtime.test.ts b/server/src/__tests__/workspace-runtime.test.ts index 10dcb375074..a0fdd82118f 100644 --- a/server/src/__tests__/workspace-runtime.test.ts +++ b/server/src/__tests__/workspace-runtime.test.ts @@ -58,6 +58,7 @@ import type { Environment, EnvironmentLease } from "@paperclipai/shared"; import { resolvePaperclipConfigPath } from "../paths.ts"; import type { WorkspaceOperation } from "@paperclipai/shared"; import type { WorkspaceOperationRecorder } from "../services/workspace-operations.ts"; +import { deriveWorktreeInstanceId } from "../services/workspace-instance-cleanup.ts"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase, @@ -1377,7 +1378,7 @@ describe("realizeExecutionWorkspace", () => { const envContents = await fs.readFile(envPath, "utf8"); const configContents = JSON.parse(await fs.readFile(configPath, "utf8")); const configStats = await fs.lstat(configPath); - const expectedInstanceId = "pap-885-show-worktree-banner"; + const expectedInstanceId = deriveWorktreeInstanceId(workspace.cwd); const expectedInstanceRoot = path.join( isolatedWorktreeHome, "instances", @@ -3314,6 +3315,18 @@ describe("realizeExecutionWorkspace", () => { }, }); + const worktreesDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-cleanup-instances-")); + const instanceId = deriveWorktreeInstanceId(workspace.cwd); + const instanceRoot = path.join(worktreesDir, "instances", instanceId); + await fs.mkdir(path.join(instanceRoot, "db"), { recursive: true }); + await fs.mkdir(path.join(workspace.cwd, ".paperclip"), { recursive: true }); + await fs.writeFile( + path.join(workspace.cwd, ".paperclip", ".env"), + `PAPERCLIP_HOME=${JSON.stringify(worktreesDir)}\nPAPERCLIP_INSTANCE_ID=${JSON.stringify(instanceId)}\n`, + "utf8", + ); + process.env.PAPERCLIP_WORKTREES_DIR = worktreesDir; + await cleanupExecutionWorkspaceArtifacts({ workspace: { id: "execution-workspace-1", @@ -3338,17 +3351,24 @@ describe("realizeExecutionWorkspace", () => { }); expect(operations.map((operation) => operation.phase)).toEqual([ + "workspace_teardown", "workspace_teardown", "worktree_cleanup", "worktree_cleanup", ]); expect(operations[0]?.command).toBe("printf 'cleanup ok\\n'"); expect(operations[1]?.metadata).toMatchObject({ - cleanupAction: "worktree_remove", + cleanupAction: "remove_worktree_instance", + instanceRoot, }); expect(operations[2]?.metadata).toMatchObject({ + cleanupAction: "worktree_remove", + }); + expect(operations[3]?.metadata).toMatchObject({ cleanupAction: "branch_delete", }); + await expect(fs.stat(instanceRoot)).rejects.toMatchObject({ code: "ENOENT" }); + await fs.rm(worktreesDir, { recursive: true, force: true }); }); }); diff --git a/server/src/services/workspace-instance-cleanup.ts b/server/src/services/workspace-instance-cleanup.ts new file mode 100644 index 00000000000..8f8d65d63ec --- /dev/null +++ b/server/src/services/workspace-instance-cleanup.ts @@ -0,0 +1,345 @@ +import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; +import { promisify } from "node:util"; +import { parse as parseEnvContents } from "dotenv"; +import { expandHomePrefix } from "../home-paths.js"; +import type { WorkspaceOperationRecorder } from "./workspace-operations.js"; + +const execFileAsync = promisify(execFile); +const INSTANCE_ID_RE = /^[A-Za-z0-9_-]+$/; +const POSTGRES_STOP_TIMEOUT_MS = 10_000; + +export function deriveWorktreeInstanceId(workspacePath: string): string { + const resolvedWorkspacePath = path.resolve(workspacePath); + const normalized = path.basename(resolvedWorkspacePath) + .trim() + .toLowerCase() + .replace(/[^a-z0-9_-]+/g, "-") + .replace(/-+/g, "-") + .replace(/^[-_]+|[-_]+$/g, ""); + const prefix = (normalized || "worktree").slice(0, 48); + const pathHash = createHash("sha256").update(resolvedWorkspacePath).digest("hex").slice(0, 12); + return `${prefix}-${pathHash}`; +} + +export type WorktreeInstancePointer = { + envPath: string; + envContents: string; +}; + +export type WorktreeInstanceCleanupResult = + | { status: "not_configured" } + | { status: "already_absent"; instanceRoot: string } + | { status: "refused"; instanceRoot: string | null; warning: string } + | { status: "removed"; instanceRoot: string; postgresStopped: boolean }; + +export type WorktreeInstanceCleanupDependencies = { + stopEmbeddedPostgres: (dataDir: string) => Promise; + removeInstanceRoot: (instanceRoot: string) => Promise; +}; + +export type EmbeddedPostgresStopDependencies = { + processIsAlive: (pid: number) => boolean; + readVerifiedPostgresCommand: (pid: number, dataDir: string) => Promise; + signalProcess: (pid: number, signal: NodeJS.Signals) => void; + wait: (milliseconds: number) => Promise; +}; + +const defaultCleanupDependencies: WorktreeInstanceCleanupDependencies = { + stopEmbeddedPostgres: stopEmbeddedPostgresIfRunning, + removeInstanceRoot: async (instanceRoot) => { + await fs.rm(instanceRoot, { recursive: true, force: true }); + }, +}; + +const defaultPostgresStopDependencies: EmbeddedPostgresStopDependencies = { + processIsAlive, + readVerifiedPostgresCommand, + signalProcess: (pid, signal) => process.kill(pid, signal), + wait: delay, +}; + +function isStrictChildPath(candidatePath: string, rootPath: string): boolean { + const relative = path.relative(rootPath, candidatePath); + return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative); +} + +async function pathExists(value: string): Promise { + return fs.lstat(value).then(() => true).catch(() => false); +} + +function processIsAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch (error) { + return (error as NodeJS.ErrnoException).code === "EPERM"; + } +} + +async function readVerifiedPostgresCommand(pid: number, dataDir: string): Promise { + if (process.platform === "linux") { + const commandLinePath = `/proc/${pid}/cmdline`; + let commandLine: string; + try { + commandLine = await fs.readFile(commandLinePath, "utf8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + throw error; + } + const args = commandLine.split("\0").filter(Boolean); + const executable = path.basename(args[0] ?? ""); + const dataDirFlagIndex = args.indexOf("-D"); + const configuredDataDir = dataDirFlagIndex >= 0 ? args[dataDirFlagIndex + 1] : null; + if (!executable.includes("postgres") || !configuredDataDir) { + throw new Error(`Refusing to signal process ${pid}: it is not the expected embedded PostgreSQL process.`); + } + const canonicalConfiguredDataDir = await fs.realpath(configuredDataDir).catch(() => path.resolve(configuredDataDir)); + if (canonicalConfiguredDataDir !== dataDir) { + throw new Error(`Refusing to signal process ${pid}: its PostgreSQL data directory does not match ${dataDir}.`); + } + return args.join(" "); + } + + if (process.platform === "win32") { + throw new Error(`Refusing to signal process ${pid}: safe PostgreSQL process verification is unavailable on Windows.`); + } + + try { + const { stdout } = await execFileAsync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" }); + const command = stdout.trim(); + if (!command) return null; + if (!/(?:^|\/)postgres(?:\s|$)/.test(command) || !command.includes(dataDir)) { + throw new Error(`Refusing to signal process ${pid}: it is not the expected embedded PostgreSQL process.`); + } + return command; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ESRCH") return null; + throw error; + } +} + +export async function stopEmbeddedPostgresIfRunning( + dataDir: string, + dependencies: EmbeddedPostgresStopDependencies = defaultPostgresStopDependencies, +): Promise { + const postmasterPidPath = path.join(dataDir, "postmaster.pid"); + if (!await pathExists(postmasterPidPath)) return false; + + const canonicalDataDir = await fs.realpath(dataDir); + const pidContents = await fs.readFile(postmasterPidPath, "utf8"); + const pidLines = pidContents.split(/\r?\n/); + const pid = Number(pidLines[0]?.trim()); + const recordedDataDir = pidLines[1]?.trim(); + if (!Number.isInteger(pid) || pid <= 0 || !recordedDataDir) { + throw new Error(`Refusing to remove ${dataDir}: its postmaster.pid is malformed.`); + } + + const canonicalRecordedDataDir = await fs.realpath(recordedDataDir).catch(() => path.resolve(recordedDataDir)); + if (canonicalRecordedDataDir !== canonicalDataDir) { + throw new Error(`Refusing to remove ${dataDir}: postmaster.pid points at a different PostgreSQL data directory.`); + } + if (!dependencies.processIsAlive(pid)) return false; + if (await dependencies.readVerifiedPostgresCommand(pid, canonicalDataDir) === null) return false; + + try { + dependencies.signalProcess(pid, "SIGINT"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ESRCH") return false; + throw error; + } + const deadline = Date.now() + POSTGRES_STOP_TIMEOUT_MS; + while (Date.now() < deadline) { + if (!dependencies.processIsAlive(pid)) return true; + await dependencies.wait(100); + } + throw new Error(`Embedded PostgreSQL process ${pid} did not stop within ${POSTGRES_STOP_TIMEOUT_MS}ms.`); +} + +export async function readWorktreeInstancePointer(workspacePath: string): Promise { + const envPath = path.join(workspacePath, ".paperclip", ".env"); + try { + return { + envPath, + envContents: await fs.readFile(envPath, "utf8"), + }; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + throw error; + } +} + +function resolveConfiguredInstanceRoot(pointer: WorktreeInstancePointer, expectedInstanceId: string): + | { instanceRoot: string } + | { warning: string; instanceRoot: string | null; refusalReason: string | null } { + const env = parseEnvContents(pointer.envContents); + const configuredHome = env.PAPERCLIP_HOME?.trim(); + const instanceId = env.PAPERCLIP_INSTANCE_ID?.trim(); + if (!configuredHome || !instanceId) { + return { warning: "", instanceRoot: null, refusalReason: null }; + } + if (!INSTANCE_ID_RE.test(instanceId)) { + return { + instanceRoot: null, + warning: `Refusing worktree instance cleanup from ${pointer.envPath}: PAPERCLIP_INSTANCE_ID is not a safe path segment.`, + refusalReason: "unsafe_instance_id", + }; + } + + const expandedHome = expandHomePrefix(configuredHome); + if (!path.isAbsolute(expandedHome)) { + return { + instanceRoot: null, + warning: `Refusing worktree instance cleanup from ${pointer.envPath}: PAPERCLIP_HOME is not absolute.`, + refusalReason: "non_absolute_home", + }; + } + const instanceRoot = path.resolve(expandedHome, "instances", instanceId); + if (instanceId !== expectedInstanceId) { + return { + instanceRoot, + warning: `Refusing worktree instance cleanup from ${pointer.envPath}: PAPERCLIP_INSTANCE_ID "${instanceId}" does not match the expected workspace instance "${expectedInstanceId}".`, + refusalReason: "instance_id_mismatch", + }; + } + return { instanceRoot }; +} + +export async function cleanupWorktreeInstanceArtifacts(input: { + pointer: WorktreeInstancePointer; + workspaceId: string; + workspacePath: string; + expectedInstanceId: string; + recorder?: WorkspaceOperationRecorder | null; + worktreesDir?: string; + dependencies?: WorktreeInstanceCleanupDependencies; +}): Promise { + const configured = resolveConfiguredInstanceRoot(input.pointer, input.expectedInstanceId); + if ("warning" in configured && !configured.warning) return { status: "not_configured" }; + + const managedWorktreesDir = path.resolve( + expandHomePrefix(input.worktreesDir?.trim() || process.env.PAPERCLIP_WORKTREES_DIR?.trim() || path.join(os.homedir(), ".paperclip-worktrees")), + ); + const managedInstancesDir = path.join(managedWorktreesDir, "instances"); + const recordRefusal = async ( + instanceRoot: string | null, + refusalWarning: string, + metadata: Record, + ) => { + if (!input.recorder) return; + await input.recorder.recordOperation({ + phase: "workspace_teardown", + cwd: input.workspacePath, + metadata: { + workspaceId: input.workspaceId, + workspacePath: input.workspacePath, + instanceRoot, + managedInstancesDir, + cleanupAction: "remove_worktree_instance", + ...metadata, + }, + run: async () => ({ status: "skipped", system: `${refusalWarning}\n` }), + }); + }; + + if ("warning" in configured) { + await recordRefusal(configured.instanceRoot, configured.warning, { refusalReason: configured.refusalReason }); + return { status: "refused", instanceRoot: configured.instanceRoot, warning: configured.warning }; + } + + const configuredInstanceRoot = configured.instanceRoot; + let warning = ""; + + if (!isStrictChildPath(configuredInstanceRoot, managedInstancesDir)) { + warning = `Refusing to remove instance directory "${configuredInstanceRoot}" because it is outside "${managedInstancesDir}".`; + await recordRefusal(configuredInstanceRoot, warning, { refusalReason: "outside_managed_instances_dir" }); + return { status: "refused", instanceRoot: configuredInstanceRoot, warning }; + } + + if (!await pathExists(configuredInstanceRoot)) { + return { status: "already_absent", instanceRoot: configuredInstanceRoot }; + } + + let canonicalManagedWorktreesDir: string; + let canonicalManagedInstancesDir: string; + let canonicalInstanceRoot: string; + try { + [canonicalManagedWorktreesDir, canonicalManagedInstancesDir, canonicalInstanceRoot] = await Promise.all([ + fs.realpath(managedWorktreesDir, { encoding: "utf8" }), + fs.realpath(managedInstancesDir, { encoding: "utf8" }), + fs.realpath(configuredInstanceRoot, { encoding: "utf8" }), + ]); + } catch (error) { + warning = `Refusing to remove instance directory "${configuredInstanceRoot}" because its canonical path could not be verified: ${error instanceof Error ? error.message : String(error)}`; + await recordRefusal(configuredInstanceRoot, warning, { refusalReason: "canonical_path_unavailable" }); + return { status: "refused", instanceRoot: configuredInstanceRoot, warning }; + } + + if (canonicalManagedInstancesDir !== path.join(canonicalManagedWorktreesDir, "instances")) { + warning = `Refusing to remove instance directory "${configuredInstanceRoot}" because the managed instances directory resolves outside "${canonicalManagedWorktreesDir}".`; + await recordRefusal(configuredInstanceRoot, warning, { + canonicalInstanceRoot, + canonicalManagedInstancesDir, + refusalReason: "managed_instances_dir_symlink", + }); + return { status: "refused", instanceRoot: configuredInstanceRoot, warning }; + } + + if (!isStrictChildPath(canonicalInstanceRoot, canonicalManagedInstancesDir)) { + warning = `Refusing to remove instance directory "${configuredInstanceRoot}" because its canonical path "${canonicalInstanceRoot}" is outside "${canonicalManagedInstancesDir}".`; + await recordRefusal(configuredInstanceRoot, warning, { + canonicalInstanceRoot, + canonicalManagedInstancesDir, + refusalReason: "canonical_path_outside_managed_instances_dir", + }); + return { status: "refused", instanceRoot: configuredInstanceRoot, warning }; + } + + const dependencies = input.dependencies ?? defaultCleanupDependencies; + let postgresStopped = false; + const cleanup = async () => { + postgresStopped = await dependencies.stopEmbeddedPostgres(path.join(canonicalInstanceRoot, "db")); + const [currentManagedInstancesDir, currentInstanceRoot] = await Promise.all([ + fs.realpath(managedInstancesDir, { encoding: "utf8" }), + fs.realpath(configuredInstanceRoot, { encoding: "utf8" }), + ]); + if ( + currentManagedInstancesDir !== canonicalManagedInstancesDir + || currentInstanceRoot !== canonicalInstanceRoot + || !isStrictChildPath(currentInstanceRoot, currentManagedInstancesDir) + ) { + throw new Error(`Refusing to remove instance directory "${configuredInstanceRoot}" because its canonical path changed during cleanup.`); + } + await dependencies.removeInstanceRoot(currentInstanceRoot); + }; + + if (input.recorder) { + await input.recorder.recordOperation({ + phase: "workspace_teardown", + cwd: input.workspacePath, + metadata: { + workspaceId: input.workspaceId, + workspacePath: input.workspacePath, + instanceRoot: canonicalInstanceRoot, + managedInstancesDir: canonicalManagedInstancesDir, + cleanupAction: "remove_worktree_instance", + }, + run: async () => { + await cleanup(); + return { + status: "succeeded", + system: `Removed worktree instance directory ${canonicalInstanceRoot}\n`, + metadata: { postgresStopped }, + }; + }, + }); + } else { + await cleanup(); + } + + return { status: "removed", instanceRoot: canonicalInstanceRoot, postgresStopped }; +} diff --git a/server/src/services/workspace-runtime.ts b/server/src/services/workspace-runtime.ts index 2bbc0cb8d27..91e20795a5b 100644 --- a/server/src/services/workspace-runtime.ts +++ b/server/src/services/workspace-runtime.ts @@ -38,6 +38,12 @@ import type { WorkspaceOperationRecorder } from "./workspace-operations.js"; import { executionWorkspaceService, readExecutionWorkspaceConfig } from "./execution-workspaces.js"; import { logActivity } from "./activity-log.js"; import { readProjectWorkspaceRuntimeConfig } from "./project-workspace-runtime-config.js"; +import { + cleanupWorktreeInstanceArtifacts, + deriveWorktreeInstanceId, + readWorktreeInstancePointer, + type WorktreeInstancePointer, +} from "./workspace-instance-cleanup.js"; export function resolveShell(): string { const fallback = process.platform === "win32" ? "sh" : "/bin/sh"; @@ -3195,6 +3201,17 @@ export async function cleanupExecutionWorkspaceArtifacts(input: { workspace: input.workspace, projectWorkspaceCwd: input.projectWorkspace?.cwd ?? null, }); + let worktreeInstancePointer: WorktreeInstancePointer | null = null; + let expectedWorktreeInstanceId: string | null = null; + if (input.workspace.providerType === "git_worktree" && workspacePath) { + expectedWorktreeInstanceId = deriveWorktreeInstanceId(workspacePath); + try { + // Capture the pointer before custom cleanup commands can remove the repo-local env file. + worktreeInstancePointer = await readWorktreeInstancePointer(workspacePath); + } catch (err) { + warnings.push(`Could not read worktree instance pointer: ${err instanceof Error ? err.message : String(err)}`); + } + } const createdByRuntime = input.workspace.metadata?.createdByRuntime === true; const cleanupCommands = [ input.cleanupCommand ?? null, @@ -3230,6 +3247,21 @@ export async function cleanupExecutionWorkspaceArtifacts(input: { } } + if (worktreeInstancePointer && workspacePath && expectedWorktreeInstanceId) { + try { + const result = await cleanupWorktreeInstanceArtifacts({ + pointer: worktreeInstancePointer, + workspaceId: input.workspace.id, + workspacePath, + expectedInstanceId: expectedWorktreeInstanceId, + recorder: input.recorder, + }); + if (result.status === "refused") warnings.push(result.warning); + } catch (err) { + warnings.push(`Failed to clean worktree instance: ${err instanceof Error ? err.message : String(err)}`); + } + } + if (input.workspace.providerType === "git_worktree" && workspacePath) { const worktreeExists = await directoryExists(workspacePath); if (worktreeExists) {