diff --git a/server/src/__tests__/environment-routes.test.ts b/server/src/__tests__/environment-routes.test.ts index c2aa6f0316d..42f5863d1fd 100644 --- a/server/src/__tests__/environment-routes.test.ts +++ b/server/src/__tests__/environment-routes.test.ts @@ -13,9 +13,10 @@ const mockAccessService = vi.hoisted(() => ({ })); const mockComputerAttach = vi.hoisted(() => vi.fn()); +const mockComputerServiceDb = vi.hoisted(() => vi.fn()); vi.mock("../modules/computers/index.js", async (importOriginal) => ({ ...await importOriginal(), - computerService: () => ({ attach: mockComputerAttach }), + computerService: (db: unknown) => { mockComputerServiceDb(db); return { attach: mockComputerAttach }; }, })); const mockAgentService = vi.hoisted(() => ({ @@ -2708,6 +2709,50 @@ describe("environment routes", () => { if (!succeeds) expect(mockLogActivity).not.toHaveBeenCalled(); }); + it.each([false, true])("commits Boat key rotation only after attachment succeeds (%s)", async succeeds => { + const priorSecret = "11111111-1111-1111-1111-111111111111"; + const nextSecret = "22222222-2222-2222-2222-222222222222"; + let environment = { ...createEnvironment(), driver: "computer", status: "active", + config: { provider: "boat", sandboxId: "bx_retained", apiKeySecretRef: { type: "secret_ref", secretId: priorSecret } }, + metadata: { computerCompanyId: "company-1" } }; + let boundSecret = priorSecret; + let transactionOpen = false; + const transaction = vi.spyOn(routeDb, "transaction").mockImplementation(async fn => { + const before = environment, bindingBefore = boundSecret; + transactionOpen = true; + try { return await fn(routeDbTx); } + catch (error) { environment = before; boundSecret = bindingBefore; throw error; } + finally { transactionOpen = false; } + }); + mockEnvironmentService.getById.mockImplementation(async () => environment); + mockEnvironmentService.update.mockImplementation(async (_id, patch) => environment = { ...environment, ...patch }); + mockSecretService.replaceSecretRefsForInstanceTarget.mockImplementation(async (_target, _refs, options) => { + expect(options.db).toBe(routeDbTx); + boundSecret = environment.config.apiKeySecretRef.secretId; + return []; + }); + mockInstanceSettingsService.getExperimental.mockResolvedValue({ enableBoatEnvironments: true }); + mockComputerAttach.mockImplementation(async input => { + expect(transactionOpen).toBe(true); + expect(mockComputerServiceDb).toHaveBeenLastCalledWith(routeDbTx); + expect(boundSecret).toBe(nextSecret); + expect(input.apiKeySecretRef.secretId).toBe(nextSecret); + if (!succeeds) throw conflict("Boat rejected the replacement key"); + return { computerId: "computer-1" }; + }); + try { + const app = createApp({ type: "board", userId: "user-1", source: "local_implicit" }); + const res = await request(app).patch(`/api/environments/${environment.id}`).send({ + config: { apiKeySecretRef: { type: "secret_ref", secretId: nextSecret } }, + }); + expect(res.status, JSON.stringify(res.body)).toBe(succeeds ? 200 : 409); + expect(environment.config.apiKeySecretRef.secretId).toBe(succeeds ? nextSecret : priorSecret); + expect(boundSecret).toBe(succeeds ? nextSecret : priorSecret); + expect(mockComputerAttach).toHaveBeenCalledOnce(); + if (!succeeds) expect(mockLogActivity).not.toHaveBeenCalled(); + } finally { transaction.mockRestore(); } + }); + it("logs a redacted update summary instead of raw config or metadata", async () => { const environment = createEnvironment(); mockEnvironmentService.getById.mockResolvedValue(environment); diff --git a/server/src/modules/computers/adapters/boat.test.ts b/server/src/modules/computers/adapters/boat.test.ts index f2cd70e153d..e7f7c088fa1 100644 --- a/server/src/modules/computers/adapters/boat.test.ts +++ b/server/src/modules/computers/adapters/boat.test.ts @@ -771,6 +771,33 @@ process.stdout.write(result.stdout||"");process.stderr.write(result.stderr||""); expect(f.call({ ...input, branch: "another-branch" })).toEqual({ error: "conflict" }); expect(git("-C", result.remoteCwd, "status", "--short")).toContain("preserved"); }); + it.each([false, true])("attaches only the exact existing worktree branch (present: %s)", present => { + const f = fixture(), checkout = join(f.root, "checkout"); + mkdirSync(checkout, { recursive: true }); + const git = (...args: string[]) => { + const result = spawnSync("git", args, { cwd: checkout, encoding: "utf8" }); + if (result.status !== 0) throw new Error(result.stderr); + return result.stdout.trim(); + }; + git("init"); + git("-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "--allow-empty", "-m", "base"); + const expectedHead = git("rev-parse", "HEAD"), branch = "operator/retained"; + if (present) git("branch", branch); + git("-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "--allow-empty", "-m", "newer base"); + const input = { action: "workspace", mode: "worktree", taskId: "existing-task", branch, existingBranch: branch, baseRef: "HEAD" }; + const result = f.call(input); + if (present) { + expect(result.remoteCwd).toBe(join(f.root, "tasks", "existing-task")); + expect(git("-C", result.remoteCwd, "rev-parse", "HEAD")).toBe(expectedHead); + writeFileSync(join(result.remoteCwd, "retained-work"), "keep"); + expect(f.call(input).remoteCwd).toBe(result.remoteCwd); + expect(git("-C", result.remoteCwd, "status", "--short")).toContain("retained-work"); + } else { + expect(result).toEqual({ error: "command_failed" }); + expect(spawnSync("git", ["show-ref", "--verify", `refs/heads/${branch}`], { cwd: checkout }).status).not.toBe(0); + expect(existsSync(join(f.root, "tasks", "existing-task"))).toBe(false); + } + }); it("roundtrips binary bytes without interpreting text", () => { const f = fixture(); const bytes = Buffer.from([0, 255, 254, 13, 10, 128]); diff --git a/server/src/modules/computers/adapters/remote-program.ts b/server/src/modules/computers/adapters/remote-program.ts index 1d555baab02..638a267a152 100644 --- a/server/src/modules/computers/adapters/remote-program.ts +++ b/server/src/modules/computers/adapters/remote-program.ts @@ -71,7 +71,8 @@ if act=='workspace': info=os.fstat(workspace_lock.fileno()) if not stat.S_ISREG(info.st_mode) or info.st_nlink!=1:fail('invalid') fcntl.flock(workspace_lock,fcntl.LOCK_EX) - repo=p.get('repositoryUrl');branch=p.get('branch');task=p.get('taskId');base_ref=p.get('baseRef') + repo=p.get('repositoryUrl');branch=p.get('branch');task=p.get('taskId');base_ref=p.get('baseRef');existing_branch=p.get('existingBranch') + if existing_branch and (p.get('mode')!='worktree' or existing_branch!=branch):fail('invalid') if base_ref and (base_ref.startswith('-') or '\n' in base_ref):fail('invalid') checkout=os.path.join(root,'checkout') if repo: @@ -94,7 +95,10 @@ if act=='workspace': if not task:fail('invalid') target=os.path.join(root,'tasks',task);os.makedirs(os.path.dirname(target),exist_ok=True) task_branch=branch or 'paperclip/task-'+task - if not os.path.exists(target):run(['git','worktree','add','-b',task_branch,target,base_ref or 'HEAD'],checkout) + if existing_branch:run(['git','show-ref','--verify','refs/heads/'+existing_branch],checkout) + if not os.path.exists(target): + if existing_branch:run(['git','worktree','add',target,existing_branch],checkout) + else:run(['git','worktree','add','-b',task_branch,target,base_ref or 'HEAD'],checkout) run(['git','rev-parse','--show-toplevel'],target) if run(['git','symbolic-ref','--quiet','--short','HEAD'],target)!=task_branch:fail('conflict') else: diff --git a/server/src/modules/computers/adapters/repository.ts b/server/src/modules/computers/adapters/repository.ts index 7a827a260f6..6a886a4d4da 100644 --- a/server/src/modules/computers/adapters/repository.ts +++ b/server/src/modules/computers/adapters/repository.ts @@ -6,7 +6,8 @@ import { type Ledger, } from "../domain/ledger.js"; import type { ComputerRepository } from "../application/ports.js"; -export function computerRepository(db: Db): ComputerRepository { +export type ComputerDatabase = Db | Parameters[0]>[0]; +export function computerRepository(db: ComputerDatabase): ComputerRepository { const decode = (row: typeof computers.$inferSelect): ComputerRecord => ({ ...row, ledger: row.ledger as unknown as Ledger, diff --git a/server/src/modules/computers/application/service.ts b/server/src/modules/computers/application/service.ts index 53105fc78fe..8a2d1e85b95 100644 --- a/server/src/modules/computers/application/service.ts +++ b/server/src/modules/computers/application/service.ts @@ -901,6 +901,7 @@ finally: gitAuth?: { configArgs: string[]; env: Record }; branch?: string; baseRef?: string; + existingBranch?: string; mode: "shared" | "worktree"; }, ) { diff --git a/server/src/modules/computers/index.ts b/server/src/modules/computers/index.ts index 5ae73890c5a..a352404be51 100644 --- a/server/src/modules/computers/index.ts +++ b/server/src/modules/computers/index.ts @@ -1,6 +1,5 @@ -import type { Db } from "@paperclipai/db"; import { secretService } from "../../services/secrets.js"; -import { computerRepository } from "./adapters/repository.js"; +import { computerRepository, type ComputerDatabase } from "./adapters/repository.js"; import { boatBackend } from "./adapters/boat.js"; import { createComputerService } from "./application/service.js"; export { COMPUTER_RETIREMENT_GRACE_MS, ComputerError, ComputerStopPendingError } from "./domain/ledger.js"; @@ -10,8 +9,8 @@ export type { } from "./domain/ledger.js"; export type ComputerService = ReturnType; export type ComputerBinding = Awaited>; -const services = new WeakMap(); -export function computerService(db: Db): ComputerService { +const services = new WeakMap(); +export function computerService(db: ComputerDatabase): ComputerService { const existing = services.get(db); if (existing) return existing; const secrets = secretService(db); diff --git a/server/src/routes/environments.ts b/server/src/routes/environments.ts index 5794ecc5270..12cacd1e4e3 100644 --- a/server/src/routes/environments.ts +++ b/server/src/routes/environments.ts @@ -1252,7 +1252,7 @@ export function environmentRoutes( // ref that fails validation (e.g. a deleted secret) must roll the whole // save back instead of leaving the config re-pointed with stale bindings. let environment = await db.transaction(async (tx) => { - const updated = await svc.update(existing.id, patch, { db: tx }); + let updated = await svc.update(existing.id, patch, { db: tx }); if (!updated) return null; if (patch.config !== undefined || patch.driver !== undefined) { await secrets.replaceSecretRefsForInstanceTarget( @@ -1269,20 +1269,22 @@ export function environmentRoutes( { db: tx }, ); } + // The candidate binding must be visible to provider verification without + // retiring the old committed credential when attachment fails. Use this + // same transaction for the computer ledger and activation as well. + if (updated.driver === "computer" && (req.body.config !== undefined || req.body.status === "active")) { + const parsed = parseEnvironmentDriverConfig(updated); + if (parsed.driver !== "computer") throw unprocessable("Invalid Boat configuration."); + await computerService(tx).attach({ companyId: String(updated.metadata?.computerCompanyId), + environmentId: updated.id, sandboxId: parsed.config.sandboxId, apiKeySecretRef: parsed.config.apiKeySecretRef }); + if (req.body.status !== "archived") updated = (await svc.update(updated.id, { status: "active" }, { db: tx }))!; + } return updated; }); if (!environment) { res.status(404).json({ error: "Environment not found" }); return; } - if (environment.driver === "computer" && (req.body.config !== undefined || req.body.status === "active")) { - const computerCompanyId = String(environment.metadata?.computerCompanyId); - const parsed = parseEnvironmentDriverConfig(environment); - if (parsed.driver !== "computer") throw unprocessable("Invalid Boat configuration."); - await computerService(db).attach({ companyId: computerCompanyId, environmentId: environment.id, - sandboxId: parsed.config.sandboxId, apiKeySecretRef: parsed.config.apiKeySecretRef }); - if (req.body.status !== "archived") environment = (await svc.update(environment.id, { status: "active" }))!; - } let customImageReconciliation: Awaited< ReturnType > = { action: "none" }; diff --git a/server/src/services/computer-environment-driver.ts b/server/src/services/computer-environment-driver.ts index 845a9f0cbd0..5fc754af6e7 100644 --- a/server/src/services/computer-environment-driver.ts +++ b/server/src/services/computer-environment-driver.ts @@ -78,13 +78,14 @@ export function createComputerEnvironmentDriver(db: Db): EnvironmentRuntimeDrive return { providerLeaseId: lease.providerLeaseId, state: "stopped" }; }, async realizeWorkspace({ lease, workspace, gitAuth }) { - const request = workspace.metadata?.workspaceRealizationRequest as { source?: { projectId?: string; repoUrl?: string; repoRef?: string; branchName?: string; strategy?: string }; issueId?: string } | undefined; + const request = workspace.metadata?.workspaceRealizationRequest as { source?: { projectId?: string; repoUrl?: string; repoRef?: string; branchName?: string; existingBranch?: string; strategy?: string }; issueId?: string } | undefined; const result = await computers.realizeWorkspace({ ...scope(lease), owner: computerOwnerFromLease(lease), projectId: request?.source?.projectId ?? undefined, taskId: request?.issueId ?? undefined, repositoryUrl: request?.source?.repoUrl ?? undefined, gitAuth, branch: request?.source?.branchName ?? request?.source?.repoRef ?? undefined, baseRef: request?.source?.repoRef ?? undefined, + existingBranch: request?.source?.existingBranch, mode: request?.source?.strategy === "git_worktree" ? "worktree" : "shared" }); await leases.updateLeaseMetadata(lease.id, { ...lease.metadata, remoteCwd: result.remoteCwd, fileAuthority: { kind: "remote-persistent", placementId: result.placementId, root: result.remoteCwd, agentHome: result.agentHome } }); diff --git a/server/src/services/heartbeat/workspace-preparation.test.ts b/server/src/services/heartbeat/workspace-preparation.test.ts index c251f4e02a9..78d05d30faa 100644 --- a/server/src/services/heartbeat/workspace-preparation.test.ts +++ b/server/src/services/heartbeat/workspace-preparation.test.ts @@ -8,6 +8,9 @@ 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"; import { environmentRunOrchestrator } from "../environment-run-orchestrator.js"; +import { computerService } from "../../modules/computers/index.js"; +import { createComputerEnvironmentDriver } from "../computer-environment-driver.js"; +import { buildWorkspaceRealizationRequest, readWorkspaceRealizationRequest } from "../workspace-realization.js"; import { environmentService } from "../environments.js"; import { executionWorkspaceService } from "../execution-workspaces.js"; import { instanceSettingsService } from "../instance-settings.js"; @@ -219,6 +222,45 @@ describe.skipIf(!support.supported)("heartbeat workspace preparation boundary", expect(input.nativeRunnerPreparationSpans).toMatchObject([{ name: "environment.acquire", outcome: "failed" }]); }); + it("rejects an existing Boat branch with a shared workspace strategy before acquisition", async () => { + const { input, envOrchestrator } = await fixture(); + input.environment.selectedEnvironmentForConfig = { ...input.environment.selectedEnvironmentForConfig!, driver: "computer" }; + input.config.mergedConfig = { workspaceStrategy: { type: "project_primary", existingBranch: "operator/retained" } }; + const acquire = vi.spyOn(envOrchestrator, "acquireForRun"); + await expect(prepareHeartbeatWorkspace(db, input)).rejects.toMatchObject({ + resultJson: { workspaceValidation: { reason: "existing_branch_requires_git_worktree" } }, + }); + expect(acquire).not.toHaveBeenCalled(); + }); + + it.each([false, true])("preserves Boat workspace base and existing-branch selection (%s)", async existing => { + const { input, envOrchestrator } = await fixture(true); + input.environment.selectedEnvironmentForConfig = { ...input.environment.selectedEnvironmentForConfig!, driver: "computer" }; + input.config.mergedConfig = { workspaceStrategy: { type: "git_worktree", baseRef: "release-base", + ...(existing ? { existingBranch: "operator/retained" } : {}) } }; + const stopBeforeRemote = new Error("captured remote realization"); + const realize = vi.spyOn(envOrchestrator, "realizeForRun").mockRejectedValue(stopBeforeRemote); + await expect(prepareHeartbeatWorkspace(db, input)).rejects.toBe(stopBeforeRemote); + expect(realize).toHaveBeenCalledOnce(); + expect(realize.mock.calls[0]![0].executionWorkspace).toMatchObject({ + repoRef: "release-base", branchName: existing ? "operator/retained" : `paperclip/task-${input.task.issueId}`, + branchCreatedByRuntime: false, + }); + const args = realize.mock.calls[0]![0]; + const request = readWorkspaceRealizationRequest(buildWorkspaceRealizationRequest({ adapterType: input.agent.adapterType, + companyId: input.agent.companyId, environmentId: input.environment.selectedEnvironmentId, + executionWorkspaceId: null, issueId: input.task.issueId, heartbeatRunId: input.run.id, + requestedMode: "isolated_workspace", workspace: args.executionWorkspace, workspaceConfig: null }))!; + const remote = vi.spyOn(computerService(db), "realizeWorkspace").mockResolvedValue({ + remoteCwd: "/home/user/project/task", agentHome: "/home/user/agent", placementId: "placement" }); + await createComputerEnvironmentDriver(db).realizeWorkspace!({ environment: args.environment, + lease: { ...args.lease, providerLeaseId: "owner", metadata: { computerOwner: { computerId: "computer", ownerId: "owner", generation: 1 } } }, + workspace: { localPath: args.executionWorkspace.cwd, metadata: { workspaceRealizationRequest: request } } }); + expect(remote).toHaveBeenCalledWith(expect.objectContaining({ baseRef: "release-base", + branch: existing ? "operator/retained" : `paperclip/task-${input.task.issueId}`, + existingBranch: existing ? "operator/retained" : undefined })); + }); + it("binds a replacement workspace from realization and snapshots the restore lease", async () => { const { input, envOrchestrator, issue } = await fixture(); const realize = envOrchestrator.realizeForRun; diff --git a/server/src/services/heartbeat/workspace-preparation.ts b/server/src/services/heartbeat/workspace-preparation.ts index 39fccda9d68..4fd1ef03738 100644 --- a/server/src/services/heartbeat/workspace-preparation.ts +++ b/server/src/services/heartbeat/workspace-preparation.ts @@ -33,6 +33,7 @@ import { cleanupExecutionWorkspaceArtifacts, ensurePersistedExecutionWorkspaceAvailable, realizeExecutionWorkspace, + WorkspaceRuntimeValidationFailure, type ExecutionWorkspaceInput, type RealizedExecutionWorkspace, } from "../workspace-runtime.js"; @@ -468,6 +469,14 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspac agentId: agent.id, }, ); + const computerExistingBranch = selectedEnvironmentForConfig?.driver === "computer" + ? readNonEmptyString(workspaceStrategyForFingerprint.existingBranch) : null; + if (computerExistingBranch && latestWorkspaceStrategyType !== "git_worktree") { + throw new WorkspaceRuntimeValidationFailure("An existing branch requires the git_worktree workspace strategy.", { + workspaceValidation: { reason: "existing_branch_requires_git_worktree", requestedExistingBranch: computerExistingBranch, + strategyType: latestWorkspaceStrategyType }, + }); + } const { executionWorkspace, reusedExecutionWorkspace, @@ -477,8 +486,11 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspac ...executionWorkspaceBase, strategy: selectedEnvironmentForConfig?.driver === "computer" ? latestWorkspaceStrategyType : "project_primary", cwd: resolvedWorkspace.cwd, + repoRef: selectedEnvironmentForConfig?.driver === "computer" && latestWorkspaceStrategyType === "git_worktree" + ? readNonEmptyString(workspaceStrategyForFingerprint.baseRef) ?? executionWorkspaceBase.repoRef : executionWorkspaceBase.repoRef, branchName: selectedEnvironmentForConfig?.driver === "computer" && latestWorkspaceStrategyType === "git_worktree" && issueId - ? reusableExistingExecutionWorkspace?.branchName ?? `paperclip/task-${issueId}` : null, + ? computerExistingBranch ?? reusableExistingExecutionWorkspace?.branchName ?? `paperclip/task-${issueId}` : null, + ...(computerExistingBranch ? { existingBranch: computerExistingBranch } : {}), worktreePath: null, warnings: [], created: false, branchCreatedByRuntime: false, } as RealizedExecutionWorkspace, reusedExecutionWorkspace: false,