diff --git a/doc/experimental/issue-worktree-support.md b/doc/experimental/issue-worktree-support.md index ea5244bc9c5..e52e620b6ce 100644 --- a/doc/experimental/issue-worktree-support.md +++ b/doc/experimental/issue-worktree-support.md @@ -22,6 +22,12 @@ We are intentionally not shipping the UI for this yet. The runtime code remains - seeded worktree instances can keep local-encrypted secrets working - seeded worktree instances can rebind same-repo project workspace paths onto the current git worktree +## Operator default isolation + +When both `enableIsolatedWorkspaces` and `enableIsolatedWorkspacesByDefault` are enabled, projects with a configured workspace and no stored execution workspace policy default to isolated worktrees. A project with no configured workspace keeps using its plain managed directory. Tasks without a project also keep their existing behavior. + +Explicit project policies and issue workspace settings still take precedence. A request for a Git worktree still requires a valid Git checkout; a missing or invalid checkout fails validation. Trust policy requirements still apply. + ## Shared workspace concurrency policy Projects and individual issues can set `sharedWorkspaceConcurrency` in their execution workspace policy/settings: diff --git a/server/src/__tests__/execution-workspace-policy.test.ts b/server/src/__tests__/execution-workspace-policy.test.ts index da911ff2150..07f61797313 100644 --- a/server/src/__tests__/execution-workspace-policy.test.ts +++ b/server/src/__tests__/execution-workspace-policy.test.ts @@ -540,13 +540,13 @@ describe("operator default isolated execution workspaces", () => { projectPolicy: Parameters< typeof applyDefaultIsolatedExecutionWorkspacePolicy >[0]["projectPolicy"], - hasProject = true, + hasProjectWorkspace = true, defaultIsolatedWorkspacesEnabled = true, ) => applyDefaultIsolatedExecutionWorkspacePolicy({ projectPolicy, defaultIsolatedWorkspacesEnabled, - hasProject, + hasProjectWorkspace, }); it("substitutes an isolated policy for a project that stores none", () => { @@ -566,6 +566,18 @@ describe("operator default isolated execution workspaces", () => { expect(withDefault(null, false)).toBeNull(); }); + it("keeps a project without a configured workspace on its existing behavior", () => { + const projectPolicy = withDefault(null, false); + expect(projectPolicy).toBeNull(); + expect(resolveExecutionWorkspaceMode({ + projectPolicy, + issueSettings: null, + legacyUseProjectWorkspace: null, + })).toBe("shared_workspace"); + expect(withDefault({ enabled: true, defaultMode: "isolated_workspace" }, false)) + .toEqual({ enabled: true, defaultMode: "isolated_workspace" }); + }); + it("never overrides a policy the project already stores", () => { expect(withDefault({ enabled: true, defaultMode: "shared_workspace" })).toEqual({ enabled: true, diff --git a/server/src/__tests__/heartbeat-project-repositories.test.ts b/server/src/__tests__/heartbeat-project-repositories.test.ts index 932c093d36a..f87ac2b11c4 100644 --- a/server/src/__tests__/heartbeat-project-repositories.test.ts +++ b/server/src/__tests__/heartbeat-project-repositories.test.ts @@ -11,6 +11,7 @@ import { runLocalGit, setExpensiveWorkspaceGitExecutor } from "@paperclipai/adap import { WorkspaceGitScanError } from "../services/workspace-git-operation-scheduler.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; import { heartbeatService } from "../services/heartbeat.ts"; +import { instanceSettingsService } from "../services/instance-settings.ts"; import { drainHeartbeatRunsToQuiescence } from "./helpers/drain-heartbeat-runs.js"; const execute = vi.hoisted(() => vi.fn(async (_input: any) => ({ exitCode: 0, signal: null, timedOut: false }))); @@ -49,8 +50,68 @@ suite("task project repository provisioning", () => { afterEach(async () => { await drainHeartbeatRunsToQuiescence(db, heartbeat); setExpensiveWorkspaceGitExecutor(null); + await instanceSettingsService(db).updateExperimental({ + enableIsolatedWorkspaces: false, + enableIsolatedWorkspacesByDefault: false, + }); }); + it.each([ + { scenario: "no configured workspace", configuredWorkspace: false, explicitIsolation: null }, + { scenario: "configured Git workspace", configuredWorkspace: true, explicitIsolation: null }, + { scenario: "explicit issue isolation without a workspace", configuredWorkspace: false, explicitIsolation: "issue" }, + { scenario: "explicit project isolation without a workspace", configuredWorkspace: false, explicitIsolation: "project" }, + ] as const)("applies default isolation safely with $scenario", async ({ configuredWorkspace, explicitIsolation }) => { + const companyId = randomUUID(), projectId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(); + await instanceSettingsService(db).updateExperimental({ + enableIsolatedWorkspaces: true, + enableIsolatedWorkspacesByDefault: true, + }); + await db.insert(companies).values({ id: companyId, name: "Research", issuePrefix: `R${companyId.slice(0, 6)}`, defaultResponsibleUserId: "responsible-user" }); + await db.insert(projects).values({ + id: projectId, companyId, name: "Research", status: "in_progress", + executionWorkspacePolicy: explicitIsolation === "project" ? { enabled: true, defaultMode: "isolated_workspace" } : null, + }); + if (configuredWorkspace) { + const source = path.join(root, companyId, "source"); + await mkdir(source, { recursive: true }); + const git = (...args: string[]) => execFileSync("git", args, { cwd: source, stdio: "ignore" }); + git("init", "-b", "main"); + await writeFile(path.join(source, "README.md"), "Research notes\n"); + git("add", "."); + git("-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "-m", "seed"); + await db.insert(projectWorkspaces).values({ + id: randomUUID(), companyId, projectId, name: "Research repository", sourceType: "local_path", cwd: source, isPrimary: true, + }); + } + await db.insert(agents).values({ id: agentId, companyId, name: "Researcher", role: "engineer", status: "idle", adapterType: "codex_local", adapterConfig: {}, runtimeConfig: {}, permissions: {} }); + await db.insert(issues).values({ + id: issueId, companyId, projectId, title: "Write a report", status: "todo", assigneeAgentId: agentId, + executionWorkspaceSettings: explicitIsolation === "issue" ? { mode: "isolated_workspace" } : null, + }); + const run = await heartbeat.wakeup(agentId, { source: "on_demand", triggerDetail: "manual", contextSnapshot: { issueId, projectId } }); + expect(run).not.toBeNull(); + await vi.waitFor(async () => { + const latest = await heartbeat.getRun(run!.id); + expect({ status: latest?.status, errorCode: latest?.errorCode }).toEqual({ + status: explicitIsolation ? "failed" : "succeeded", + errorCode: explicitIsolation ? "workspace_validation_failed" : null, + }); + }, { timeout: 15_000 }); + const calls = execute.mock.calls.filter(([input]) => input.runId === run!.id); + expect(calls).toHaveLength(explicitIsolation ? 0 : 1); + if (!explicitIsolation) { + const workspace = calls[0]![0].context.paperclipWorkspace; + expect(workspace.mode).toBe(configuredWorkspace ? "isolated_workspace" : "shared_workspace"); + if (configuredWorkspace) { + expect(workspace.strategy).toBe("git_worktree"); + expect(execFileSync("git", ["rev-parse", "--is-inside-work-tree"], { cwd: workspace.cwd, encoding: "utf8" }).trim()).toBe("true"); + } else { + expect(workspace.cwd).toContain(`${projectId}/_default`); + } + } + }, 25_000); + it.each([ { code: "workspace_git_scan_timeout", scenario: "temporary", retryable: true }, { code: "workspace_git_scan_saturated", scenario: "temporary", retryable: true }, diff --git a/server/src/services/execution-workspace-policy.ts b/server/src/services/execution-workspace-policy.ts index a2d308a4247..b430de18cc2 100644 --- a/server/src/services/execution-workspace-policy.ts +++ b/server/src/services/execution-workspace-policy.ts @@ -165,8 +165,8 @@ export function gateProjectExecutionWorkspacePolicy( } /** - * Operator default: a project that stores no policy of its own runs its tasks - * in an isolated per-task worktree instead of the shared project checkout. + * Operator default: a project with a configured workspace and no policy of its + * own runs its tasks in an isolated per-task worktree. * * This substitutes a policy rather than moving the terminal fallback in * `resolveExecutionWorkspaceMode`, and the distinction is load-bearing: @@ -176,7 +176,10 @@ export function gateProjectExecutionWorkspacePolicy( * an isolated + `git_worktree` task that has neither `projectId` nor * `projectWorkspaceId`. Moving the terminal fallback would resolve isolated * for project-less tasks (agent chat, for example) and strand them before - * dispatch. `hasProject` keeps them on the untouched path. + * dispatch. A project without a configured workspace also uses a plain + * managed directory, not a Git checkout. `hasProjectWorkspace` keeps both + * cases on their existing path; configured checkouts are still validated + * before a worktree is created. * - `buildExecutionWorkspaceAdapterConfig` only supplies the default * `git_worktree` strategy when some layer actually asserts workspace * control. A moved fallback would leave `hasWorkspaceControl` false and @@ -192,10 +195,10 @@ export function gateProjectExecutionWorkspacePolicy( export function applyDefaultIsolatedExecutionWorkspacePolicy(input: { projectPolicy: ProjectExecutionWorkspacePolicy | null; defaultIsolatedWorkspacesEnabled: boolean; - hasProject: boolean; + hasProjectWorkspace: boolean; }): ProjectExecutionWorkspacePolicy | null { if (!input.defaultIsolatedWorkspacesEnabled) return input.projectPolicy; - if (!input.hasProject) return input.projectPolicy; + if (!input.hasProjectWorkspace) return input.projectPolicy; if (input.projectPolicy) return input.projectPolicy; return { enabled: true, defaultMode: "isolated_workspace" }; } diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 291fcdf5a3e..bc81fabd19d 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -20302,6 +20302,14 @@ export function heartbeatService( .select({ id: projects.id, executionWorkspacePolicy: projects.executionWorkspacePolicy, + hasWorkspace: exists( + db.select({ id: projectWorkspaces.id }) + .from(projectWorkspaces) + .where(and( + eq(projectWorkspaces.projectId, projects.id), + eq(projectWorkspaces.companyId, agent.companyId), + )), + ).mapWith(Boolean), env: projects.env, updatedAt: projects.updatedAt, }) @@ -20433,10 +20441,9 @@ export function heartbeatService( isolatedWorkspacesEnabled, ), defaultIsolatedWorkspacesEnabled, - // A resolved project row, not the issue's raw `projectId`: the - // substituted policy must only reach a task whose repository the - // worktree can actually be cut from. - hasProject: Boolean(projectContext), + // Projects without workspace configuration get a plain managed + // directory. The operator default cannot turn it into a worktree. + hasProjectWorkspace: projectContext?.hasWorkspace ?? false, }); const retainedTrust = await resolveAndRetainRunTrustPreset(db, { companyId: agent.companyId,