diff --git a/doc/experimental/issue-worktree-support.md b/doc/experimental/issue-worktree-support.md index 19614a3c36f..418ec56bafc 100644 --- a/doc/experimental/issue-worktree-support.md +++ b/doc/experimental/issue-worktree-support.md @@ -26,7 +26,7 @@ We are intentionally not shipping the UI for this yet. The runtime code remains 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. +When a repository-free task or conversation requests `isolated_workspace` without an explicit `workspaceStrategy` on local, sandbox, or plugin environments, Paperclip prepares a private isolated task directory instead of requiring a Git checkout. Explicit project policies, issue workspace strategies, and trust policy requirements still apply. A request for a Git worktree still requires a valid Git checkout; a missing or invalid checkout fails validation. ## Shared workspace concurrency policy diff --git a/server/src/__tests__/heartbeat-workspace-source-trust.test.ts b/server/src/__tests__/heartbeat-workspace-source-trust.test.ts index e7c8f5a005e..592f23a2dca 100644 --- a/server/src/__tests__/heartbeat-workspace-source-trust.test.ts +++ b/server/src/__tests__/heartbeat-workspace-source-trust.test.ts @@ -50,7 +50,9 @@ suite("heartbeat physical workspace source trust", () => { await db.insert(authUsers).values({ id: "responsible-user", name: "Fixture owner", email: "owner@example.test", createdAt: new Date(), updatedAt: new Date() }); heartbeat = heartbeatService(db); execute.mockImplementation(async (input) => { - await db.update(issues).set({ status: "done" }).where(eq(issues.id, input.context.issueId)); + if (!input.context.conversationMode) { + await db.update(issues).set({ status: "done" }).where(eq(issues.id, input.context.issueId)); + } return { exitCode: 0, signal: null, timedOut: false }; }); }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); @@ -235,4 +237,527 @@ suite("heartbeat physical workspace source trust", () => { else expect(await readFile(marker, "utf8")).toBe("host-script-ran"); }, 30_000); + it.each([ + { kind: "projectless_task", placement: "local", settings: { mode: "isolated_workspace" as const } }, + { kind: "projectless_task", placement: "sandbox", settings: { mode: "isolated_workspace" as const } }, + { kind: "projectless_chat", placement: "local", settings: { mode: "isolated_workspace" as const } }, + { kind: "projectless_chat", placement: "sandbox", settings: { mode: "isolated_workspace" as const } }, + { kind: "projectless_chat", placement: "local", settings: null }, + { kind: "projectless_chat", placement: "sandbox", settings: null }, + { kind: "repo_free_project_task", placement: "local", settings: null }, + { kind: "repo_free_project_task", placement: "sandbox", settings: null }, + ] as const)( + "runs $kind on $placement in a company with no repository when isolated workspaces by default is enabled (settings: $settings)", + async ({ kind, placement, settings }) => { + const companyId = randomUUID(); + const agentId = randomUUID(); + const issueId = randomUUID(); + const projectId = kind === "repo_free_project_task" ? randomUUID() : null; + await instanceSettingsService(db).updateExperimental({ + enableIsolatedWorkspaces: true, + enableIsolatedWorkspacesByDefault: true, + }); + await db.insert(companies).values({ + id: companyId, + name: "No-repo company", + issuePrefix: `NR${companyId.slice(0, 5).toUpperCase()}`, + defaultResponsibleUserId: "responsible-user", + }); + await db.insert(companyMemberships).values({ + companyId, + principalType: "user", + principalId: "responsible-user", + status: "active", + membershipRole: "owner", + }); + if (projectId) { + await db.insert(projects).values({ + id: projectId, + companyId, + name: "Docs project without repo", + executionWorkspacePolicy: { enabled: true, defaultMode: "isolated_workspace" }, + }); + } + const environmentId = placement === "sandbox" ? randomUUID() : null; + if (environmentId) { + await db.insert(environments).values({ + id: environmentId, + name: `Cloud sandbox ${companyId}`, + driver: "sandbox", + status: "active", + config: { provider: "fake", image: "fake:test" }, + }); + } + await db.insert(agents).values({ + id: agentId, + companyId, + name: "General worker", + status: "idle", + adapterType: "codex_local", + adapterConfig: {}, + defaultEnvironmentId: environmentId, + permissions: {}, + }); + await db.insert(companyMemberships).values({ + companyId, + principalType: "agent", + principalId: agentId, + status: "active", + membershipRole: "member", + }); + await db.insert(issues).values({ + id: issueId, + companyId, + projectId, + projectWorkspaceId: null, + title: kind === "projectless_chat" ? "Chat with General worker" : "No-repo isolated task", + status: kind === "projectless_chat" ? "in_review" : "todo", + assigneeAgentId: agentId, + responsibleUserId: "responsible-user", + ...(kind === "projectless_chat" + ? { + conversationAgentId: agentId, + conversationUserId: "responsible-user", + conversationState: "waiting", + } + : {}), + executionWorkspaceSettings: settings, + }); + + const driver = placement === "sandbox" + ? heartbeatService(db, { + environmentRuntime: { + ...environmentRuntimeService(db), + execute: async (input) => ({ + exitCode: 0, + stdout: execFileSync(input.command, input.args ?? [], { + cwd: root, + input: input.stdin, + encoding: "utf8", + env: { ...process.env, ...input.env }, + }), + stderr: "", + signal: null, + timedOut: false, + }), + }, + }) + : heartbeat; + + const expectIsolated = settings?.mode === "isolated_workspace" || kind === "repo_free_project_task"; + + for (let turn = 0; turn < 2; turn += 1) { + if (turn === 1 && kind !== "projectless_chat") { + await db.update(issues).set({ status: "todo" }).where(eq(issues.id, issueId)); + } + let wakeOptions: Parameters[1] = { + source: "on_demand", + triggerDetail: "manual", + contextSnapshot: { issueId }, + }; + if (kind === "projectless_chat") { + const comment = await issueService(db).addComment(issueId, `Chat turn ${turn + 1}`, { + userId: "responsible-user", + }); + wakeOptions = { + source: "assignment", + triggerDetail: "system", + reason: "issue_commented", + requestedByActorType: "user", + requestedByActorId: "responsible-user", + payload: { issueId, commentId: comment.id }, + contextSnapshot: { + issueId, + commentId: comment.id, + wakeCommentId: comment.id, + wakeReason: "issue_commented", + }, + }; + } + const run = await driver.wakeup(agentId, wakeOptions); + expect(run).not.toBeNull(); + await vi.waitFor( + async () => expect((await driver.getRun(run!.id))?.status).toMatch(/^(succeeded|failed)$/), + { timeout: 15_000 }, + ); + await drainHeartbeatRunsToQuiescence(db, driver); + expect(await driver.getRun(run!.id)).toMatchObject({ status: "succeeded", errorCode: null }); + + const expectedDir = path.join( + await realpath(resolvePaperclipInstanceRoot()), + "isolated-workspaces", + companyId, + issueId, + ); + const calls = execute.mock.calls.filter(([input]) => input.runId === run!.id); + expect(calls).toHaveLength(1); + expect(calls[0][0].context.paperclipEnvironment.driver).toBe(placement); + expect(await realpath(calls[0][0].context.paperclipWorkspace.cwd)).toBe(expectedDir); + expect(calls[0][0].context.paperclipWorkspace.strategy).toBe("project_primary"); + if (expectIsolated) { + expect(calls[0][0].context.paperclipWorkspace.mode).toBe("isolated_workspace"); + } + } + + const expectedDir = path.join( + await realpath(resolvePaperclipInstanceRoot()), + "isolated-workspaces", + companyId, + issueId, + ); + const [bound] = await db.select().from(issues).where(eq(issues.id, issueId)); + expect(bound.status).not.toBe("blocked"); + expect(bound.executionWorkspaceId).toBeTruthy(); + const [workspace] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, bound.executionWorkspaceId!)); + expect(workspace).toMatchObject({ + mode: expectIsolated ? "isolated_workspace" : "shared_workspace", + strategyType: "project_primary", + providerType: "local_fs", + sourceIssueId: issueId, + }); + expect(await realpath(workspace.cwd!)).toBe(expectedDir); + }, + 30_000, + ); + + it("still uses git_worktree for git-backed projects under default isolation and still blocks explicit projectless git_worktree", async () => { + const companyId = randomUUID(); + const projectId = randomUUID(); + const sourceId = randomUUID(); + const agentId = randomUUID(); + const gitIssueId = randomUUID(); + const explicitWorktreeIssueId = randomUUID(); + await instanceSettingsService(db).updateExperimental({ + enableIsolatedWorkspaces: true, + enableIsolatedWorkspacesByDefault: true, + }); + const repoCwd = path.join(root, companyId, "git-project"); + await mkdir(repoCwd, { recursive: true }); + await writeFile(path.join(repoCwd, "README.md"), "# repo\n"); + const git = (...args: string[]) => execFileSync("git", args, { cwd: repoCwd, stdio: "ignore" }); + git("init", "-b", "main"); + git("add", "."); + git("-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", "commit", "-m", "init"); + + await db.insert(companies).values({ + id: companyId, + name: "Git regression company", + issuePrefix: `GR${companyId.slice(0, 5).toUpperCase()}`, + defaultResponsibleUserId: "responsible-user", + }); + await db.insert(companyMemberships).values({ + companyId, + principalType: "user", + principalId: "responsible-user", + status: "active", + membershipRole: "owner", + }); + await db.insert(projects).values({ id: projectId, companyId, name: "Git project" }); + await db.insert(projectWorkspaces).values({ + id: sourceId, + companyId, + projectId, + name: "Primary repo", + sourceType: "local_path", + cwd: repoCwd, + isPrimary: true, + }); + await db.insert(agents).values({ + id: agentId, + companyId, + name: "Repo worker", + status: "idle", + adapterType: "codex_local", + adapterConfig: {}, + permissions: {}, + }); + await db.insert(companyMemberships).values({ + companyId, + principalType: "agent", + principalId: agentId, + status: "active", + membershipRole: "member", + }); + await db.insert(issues).values([ + { + id: gitIssueId, + companyId, + projectId, + projectWorkspaceId: sourceId, + title: "Git project task", + status: "todo", + assigneeAgentId: agentId, + responsibleUserId: "responsible-user", + issueNumber: 1, + identifier: `GR-1`, + }, + { + id: explicitWorktreeIssueId, + companyId, + projectId: null, + projectWorkspaceId: null, + title: "Explicit git worktree without project", + status: "todo", + assigneeAgentId: agentId, + responsibleUserId: "responsible-user", + issueNumber: 2, + identifier: `GR-2`, + executionWorkspaceSettings: { + mode: "isolated_workspace", + workspaceStrategy: { type: "git_worktree" }, + }, + }, + ]); + + const gitRun = await heartbeat.wakeup(agentId, { + source: "on_demand", + triggerDetail: "manual", + contextSnapshot: { issueId: gitIssueId }, + }); + expect(gitRun).not.toBeNull(); + await vi.waitFor( + async () => expect((await heartbeat.getRun(gitRun!.id))?.status).toMatch(/^(succeeded|failed)$/), + { timeout: 15_000 }, + ); + await drainHeartbeatRunsToQuiescence(db, heartbeat); + expect(await heartbeat.getRun(gitRun!.id)).toMatchObject({ status: "succeeded", errorCode: null }); + const gitCalls = execute.mock.calls.filter(([input]) => input.runId === gitRun!.id); + expect(gitCalls).toHaveLength(1); + const gitWorkspace = gitCalls[0][0].context.paperclipWorkspace; + expect(gitWorkspace.mode).toBe("isolated_workspace"); + expect(gitWorkspace.strategy).toBe("git_worktree"); + expect( + execFileSync("git", ["rev-parse", "--is-inside-work-tree"], { cwd: gitWorkspace.cwd, encoding: "utf8" }).trim(), + ).toBe("true"); + + const blockedRun = await heartbeat.wakeup(agentId, { + source: "on_demand", + triggerDetail: "manual", + contextSnapshot: { issueId: explicitWorktreeIssueId }, + }); + expect(blockedRun).toBeNull(); + const [blockedIssue] = await db.select().from(issues).where(eq(issues.id, explicitWorktreeIssueId)); + expect(blockedIssue.status).toBe("blocked"); + + const sshEnvId = randomUUID(); + const sshAgentId = randomUUID(); + const sshIssueId = randomUUID(); + await db.insert(environments).values({ + id: sshEnvId, + name: `SSH env ${companyId.slice(0, 6)}`, + driver: "ssh", + status: "active", + config: { host: "fixture.invalid", port: 22, username: "fixture", remoteWorkspacePath: "/home/fixture/work" }, + }); + await db.insert(agents).values({ + id: sshAgentId, + companyId, + name: "SSH worker", + status: "idle", + adapterType: "codex_local", + adapterConfig: {}, + permissions: {}, + defaultEnvironmentId: sshEnvId, + }); + await db.insert(companyMemberships).values({ + companyId, + principalType: "agent", + principalId: sshAgentId, + status: "active", + membershipRole: "member", + }); + await db.insert(issues).values({ + id: sshIssueId, + companyId, + projectId: null, + projectWorkspaceId: null, + title: "Projectless SSH isolated task", + status: "todo", + assigneeAgentId: sshAgentId, + responsibleUserId: "responsible-user", + issueNumber: 3, + identifier: `GR-3`, + executionWorkspaceSettings: { mode: "isolated_workspace" }, + }); + const sshBlockedRun = await heartbeat.wakeup(sshAgentId, { + source: "on_demand", + triggerDetail: "manual", + contextSnapshot: { issueId: sshIssueId }, + }); + expect(sshBlockedRun).toBeNull(); + const [sshBlockedIssue] = await db.select().from(issues).where(eq(issues.id, sshIssueId)); + expect(sshBlockedIssue.status).toBe("blocked"); + + const sandboxEnvId = randomUUID(); + const lowTrustSandboxIssueId = randomUUID(); + await db.insert(environments).values({ + id: sandboxEnvId, + name: `Low-trust sandbox ${companyId.slice(0, 6)}`, + driver: "sandbox", + status: "active", + config: { provider: "fake", image: "fake:test" }, + }); + await db.insert(issues).values({ + id: lowTrustSandboxIssueId, + companyId, + projectId: null, + projectWorkspaceId: null, + title: "Low-trust projectless sandbox task on SSH-default agent", + status: "todo", + assigneeAgentId: sshAgentId, + responsibleUserId: "responsible-user", + issueNumber: 4, + identifier: `GR-4`, + executionPolicy: { + trustPreset: "low_trust_review", + authorizationPolicy: { + trustPreset: "low_trust_review", + trustBoundary: { mode: "low_trust_review", companyId, issueIds: [lowTrustSandboxIssueId] }, + }, + }, + executionWorkspaceSettings: { + mode: "isolated_workspace", + environmentId: sandboxEnvId, + }, + }); + const sandboxHeartbeat = heartbeatService(db, { + environmentRuntime: { + ...environmentRuntimeService(db), + execute: async (input) => ({ + exitCode: 0, + stdout: execFileSync(input.command, input.args ?? [], { + cwd: root, + input: input.stdin, + encoding: "utf8", + env: { ...process.env, ...input.env }, + }), + stderr: "", + signal: null, + timedOut: false, + }), + }, + }); + const lowTrustRun = await sandboxHeartbeat.wakeup(sshAgentId, { + source: "on_demand", + triggerDetail: "manual", + contextSnapshot: { issueId: lowTrustSandboxIssueId }, + }); + expect(lowTrustRun).not.toBeNull(); + await vi.waitFor( + async () => expect((await sandboxHeartbeat.getRun(lowTrustRun!.id))?.status).toMatch(/^(succeeded|failed)$/), + { timeout: 15_000 }, + ); + await drainHeartbeatRunsToQuiescence(db, sandboxHeartbeat); + expect(await sandboxHeartbeat.getRun(lowTrustRun!.id)).toMatchObject({ status: "succeeded", errorCode: null }); + const lowTrustCalls = execute.mock.calls.filter(([input]) => input.runId === lowTrustRun!.id); + expect(lowTrustCalls).toHaveLength(1); + expect(lowTrustCalls[0][0].context.paperclipEnvironment.driver).toBe("sandbox"); + expect(lowTrustCalls[0][0].context.paperclipWorkspace.strategy).toBe("project_primary"); + const [lowTrustIssue] = await db.select().from(issues).where(eq(issues.id, lowTrustSandboxIssueId)); + expect(lowTrustIssue.status).not.toBe("blocked"); + + const otherTaskId = randomUUID(); + const archivedWorkspaceId = randomUUID(); + const archivedBindingIssueId = randomUUID(); + await db.insert(issues).values({ + id: otherTaskId, + companyId, + projectId: null, + projectWorkspaceId: null, + title: "Other task with archived directory", + status: "done", + responsibleUserId: "responsible-user", + issueNumber: 5, + identifier: `GR-5`, + }); + await db.insert(executionWorkspaces).values({ + id: archivedWorkspaceId, + companyId, + sourceIssueId: otherTaskId, + mode: "isolated_workspace", + strategyType: "project_primary", + providerType: "local_fs", + name: "Archived other-task directory", + status: "archived", + cleanupReason: "issue_terminal_done", + cwd: path.join(root, companyId, "archived-other-task"), + }); + await db.insert(issues).values({ + id: archivedBindingIssueId, + companyId, + projectId: null, + projectWorkspaceId: null, + executionWorkspaceId: archivedWorkspaceId, + executionWorkspacePreference: "reuse_existing", + title: "Projectless task bound to another task's archived workspace", + status: "todo", + assigneeAgentId: agentId, + responsibleUserId: "responsible-user", + issueNumber: 6, + identifier: `GR-6`, + executionWorkspaceSettings: { mode: "isolated_workspace" }, + }); + const archivedBlockedRun = await heartbeat.wakeup(agentId, { + source: "on_demand", + triggerDetail: "manual", + contextSnapshot: { issueId: archivedBindingIssueId }, + }); + expect(archivedBlockedRun).toBeNull(); + const [archivedBlockedIssue] = await db.select().from(issues).where(eq(issues.id, archivedBindingIssueId)); + expect(archivedBlockedIssue.status).toBe("blocked"); + + const ownArchivedIssueId = randomUUID(); + const ownArchivedWorkspaceId = randomUUID(); + const ownArchivedCwd = path.join( + await realpath(resolvePaperclipInstanceRoot()), + "isolated-workspaces", + companyId, + ownArchivedIssueId, + ); + await mkdir(ownArchivedCwd, { recursive: true }); + await db.insert(issues).values({ + id: ownArchivedIssueId, + companyId, + projectId: null, + projectWorkspaceId: null, + title: "Projectless task reopening its own archived directory", + status: "todo", + assigneeAgentId: agentId, + responsibleUserId: "responsible-user", + issueNumber: 7, + identifier: `GR-7`, + executionWorkspaceSettings: { mode: "isolated_workspace" }, + }); + await db.insert(executionWorkspaces).values({ + id: ownArchivedWorkspaceId, + companyId, + sourceIssueId: ownArchivedIssueId, + mode: "isolated_workspace", + strategyType: "project_primary", + providerType: "local_fs", + name: "Own archived directory", + status: "archived", + cleanupReason: "issue_terminal_done", + cwd: ownArchivedCwd, + }); + await db.update(issues).set({ + executionWorkspaceId: ownArchivedWorkspaceId, + executionWorkspacePreference: "reuse_existing", + }).where(eq(issues.id, ownArchivedIssueId)); + const ownArchivedRun = await heartbeat.wakeup(agentId, { + source: "on_demand", + triggerDetail: "manual", + contextSnapshot: { issueId: ownArchivedIssueId }, + }); + expect(ownArchivedRun).not.toBeNull(); + await vi.waitFor( + async () => expect((await heartbeat.getRun(ownArchivedRun!.id))?.status).toMatch(/^(succeeded|failed)$/), + { timeout: 15_000 }, + ); + await drainHeartbeatRunsToQuiescence(db, heartbeat); + expect(await heartbeat.getRun(ownArchivedRun!.id)).toMatchObject({ status: "succeeded", errorCode: null }); + const [reopenedIssue] = await db.select().from(issues).where(eq(issues.id, ownArchivedIssueId)); + expect(reopenedIssue.status).not.toBe("blocked"); + }, 30_000); + }); diff --git a/server/src/services/heartbeat/environment-selection.ts b/server/src/services/heartbeat/environment-selection.ts index 4d7f37fc046..a93ed80d0cc 100644 --- a/server/src/services/heartbeat/environment-selection.ts +++ b/server/src/services/heartbeat/environment-selection.ts @@ -20,7 +20,7 @@ import { import { assertTaskWorkspaceExecutionAccess, assertTaskWorkspaceSourceProjectAccess } from "../task-workspace-access.js"; import { isBoundIsolatedTaskDirectory, shouldUseIsolatedTaskDirectory } from "../isolated-task-directory.js"; import { readTaskDirectoryRetention } from "../isolated-task-directory-retention.js"; -import { isBoundFreshPluginTaskDirectory } from "../provider-fresh-workspace.js"; +import { isBoundPluginTaskDirectory } from "../provider-fresh-workspace.js"; import { findNativeChatWorkspaceScope, nativeChatWorkspaceCwd, @@ -544,7 +544,7 @@ export async function selectHeartbeatEnvironment(db: Db, input: HeartbeatEnviron (await isBoundIsolatedTaskDirectory({ companyId: agent.companyId, issueId, workspaceId: issueRef.executionWorkspaceId, workspace: reusableExistingExecutionWorkspace }) || (selectedEnvironmentForConfig?.driver === "plugin" && agent.adapterType === "paperclip_runner" && - isBoundFreshPluginTaskDirectory({ companyId: agent.companyId, issueId, + isBoundPluginTaskDirectory({ companyId: agent.companyId, issueId, workspaceId: issueRef.executionWorkspaceId, workspace: reusableExistingExecutionWorkspace, owner: { agentId: agent.id, environmentId: selectedEnvironmentForConfig.id, pluginKey: parseObject(selectedEnvironmentForConfig.config).pluginKey ?? null, @@ -562,6 +562,8 @@ export async function selectHeartbeatEnvironment(db: Db, input: HeartbeatEnviron mode: requestedExecutionWorkspaceMode, hasProjectWorkspace: workspaceProjectContext?.hasWorkspace ?? false, projectWorkspaceId: issueRef.projectWorkspaceId, + hasSelectedExecutionWorkspace: Boolean(issueRef.executionWorkspaceId || boundSourceWorkspace) || + requestedShouldReuseExisting || taskWorkspaceIntent?.selection.kind === "existing", workspaceStrategies: [ config.workspaceStrategy, issueAssigneeOverrides?.adapterConfig?.workspaceStrategy, diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index a47fcdb96f8..1e80a60937a 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -122,9 +122,11 @@ import { chatConversations, chatEndpoints, companies, + environments, executionWorkspaces, heartbeatRunEvents, heartbeatRuns, + instanceSettings as instanceSettingsTable, issueComments, issueRecoveryActions, issueRelations, @@ -190,6 +192,10 @@ import { WORKSPACE_WORKTREE_REQUIRES_PROJECT_MESSAGE, WORKSPACE_WORKTREE_REQUIRES_PROJECT_REMEDIATION, } from "../execution-workspace-policy.js"; +import { isExecutionForcedToKubernetes } from "../execution-allowlist.js"; +import { shouldUseIsolatedTaskDirectory } from "../isolated-task-directory.js"; +import { readTaskDirectoryRetention } from "../isolated-task-directory-retention.js"; +import { resolveCoreTrustPreset } from "../trust-preset-resolver.js"; import { readContinuationAttempt } from "../recovery/index.js"; import { AI_CONNECTION_POOL_WAIT_RETRY_REASON, allowsDependencyBlockedWake, extractWakeCommentIds, wakeChatConversationsConflict } from "../../modules/run-dispatch/index.js"; import { releaseProviderLimitWaits } from "./provider-limit-wait.js"; @@ -3343,9 +3349,11 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende if (projectId && !readNonEmptyString(enrichedContextSnapshot.projectId)) { enrichedContextSnapshot.projectId = projectId; } - const isolatedWorkspacesEnabled = issueId - ? (await instanceSettings.getExperimental()).enableIsolatedWorkspaces - : false; + const experimentalSettings = issueId + ? await instanceSettings.getExperimental() + : null; + const isolatedWorkspacesEnabled = + experimentalSettings?.enableIsolatedWorkspaces === true; let operatorResponsibleUserId: string | null = opts.manualUserWake ? opts.requestedByActorId! : null; const resolveQueuedResponsibleUserId = async (issueContext: IssueAttributionSnapshot | null) => { if (operatorResponsibleUserId) return operatorResponsibleUserId; @@ -4513,6 +4521,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende const issueSettings = parseIssueExecutionWorkspaceSettings( issue.executionWorkspaceSettings, ); + const agentConfig = parseObject(agent.adapterConfig); const resolvedMode = resolveExecutionWorkspaceMode({ projectPolicy: null, issueSettings, @@ -4520,7 +4529,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende }); const workspaceManagedConfig = buildExecutionWorkspaceAdapterConfig( { - agentConfig: parseObject(agent.adapterConfig), + agentConfig, projectPolicy: null, issueSettings, mode: resolvedMode, @@ -4531,9 +4540,19 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende resolvedMode, workspaceManagedConfig, ); - const existingExecutionWorkspaceStatus = issue.executionWorkspaceId + const existingExecutionWorkspace = issue.executionWorkspaceId ? await tx - .select({ status: executionWorkspaces.status }) + .select({ + status: executionWorkspaces.status, + sourceIssueId: executionWorkspaces.sourceIssueId, + projectWorkspaceId: executionWorkspaces.projectWorkspaceId, + mode: executionWorkspaces.mode, + strategyType: executionWorkspaces.strategyType, + repoUrl: executionWorkspaces.repoUrl, + branchName: executionWorkspaces.branchName, + cleanupReason: executionWorkspaces.cleanupReason, + metadata: executionWorkspaces.metadata, + }) .from(executionWorkspaces) .where( and( @@ -4541,8 +4560,10 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende eq(executionWorkspaces.companyId, issue.companyId), ), ) - .then((rows) => rows[0]?.status ?? null) + .then((rows) => rows[0] ?? null) : null; + const existingExecutionWorkspaceStatus = + existingExecutionWorkspace?.status ?? null; const reuseRequest = resolveExecutionWorkspaceReuseRequestForIssue({ issueExecutionWorkspaceId: issue.executionWorkspaceId, issueExecutionWorkspacePreference: @@ -4551,6 +4572,142 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende }); const hasResolvablePriorSessionWorkspace = await resolveHasResolvablePriorSessionWorkspace(); + let effectivePreflightStrategy: string | null = resolvedStrategy; + if ( + resolvedMode === "isolated_workspace" && + resolvedStrategy === "git_worktree" && + !(issue.projectId ?? projectId) && + !issue.projectWorkspaceId && + !reuseRequest.existingExecutionWorkspaceAvailable && + !hasResolvablePriorSessionWorkspace + ) { + const settingsRow = await tx + .select({ + defaultEnvironmentId: + instanceSettingsTable.defaultEnvironmentId, + general: instanceSettingsTable.general, + }) + .from(instanceSettingsTable) + .where(eq(instanceSettingsTable.singletonKey, "default")) + .then((rows) => rows[0] ?? null); + const issuePolicyRow = await tx + .select({ executionPolicy: issues.executionPolicy }) + .from(issues) + .where( + and( + eq(issues.id, issue.id), + eq(issues.companyId, issue.companyId), + ), + ) + .then((rows) => rows[0] ?? null); + const trustPreset = resolveCoreTrustPreset({ + companyId: agent.companyId, + agent: { + companyId: agent.companyId, + permissions: agent.permissions, + }, + issue: { + companyId: issue.companyId, + executionPolicy: issuePolicyRow?.executionPolicy ?? null, + }, + run: { + companyId: agent.companyId, + executionPolicy: enrichedContextSnapshot.executionPolicy, + }, + }); + const lowTrustIssueEnvironmentId = + trustPreset.kind === "low_trust_review" + ? (parseIssueExecutionWorkspaceSettings( + issue.executionWorkspaceSettings, + { includeEnvironmentId: true }, + )?.environmentId ?? null) + : null; + const executionMode = parseObject( + settingsRow?.general, + ).executionMode; + let environmentDriver: string | null = null; + if ( + isExecutionForcedToKubernetes({ + executionMode: + executionMode === "kubernetes" ? "kubernetes" : "any", + }) + ) { + environmentDriver = "sandbox"; + } else { + const selectedEnvironmentId = + lowTrustIssueEnvironmentId ?? + agent.defaultEnvironmentId ?? + settingsRow?.defaultEnvironmentId ?? + null; + if (selectedEnvironmentId) { + environmentDriver = await tx + .select({ driver: environments.driver }) + .from(environments) + .where(eq(environments.id, selectedEnvironmentId)) + .then((rows) => rows[0]?.driver ?? null); + } + if ( + experimentalSettings?.enableManagedSandboxOnly === true && + (environmentDriver === null || environmentDriver === "local") + ) { + environmentDriver = "sandbox"; + } + } + const candidateOwnArchivedTaskDirectory = Boolean( + issue.executionWorkspaceId && + existingExecutionWorkspace && + existingExecutionWorkspace.sourceIssueId === issue.id && + !existingExecutionWorkspace.projectWorkspaceId && + existingExecutionWorkspace.mode === "isolated_workspace" && + existingExecutionWorkspace.strategyType === + "project_primary" && + !existingExecutionWorkspace.repoUrl && + !existingExecutionWorkspace.branchName && + (existingExecutionWorkspace.status === "archived" || + existingExecutionWorkspace.status === "cleanup_failed") && + (readTaskDirectoryRetention(existingExecutionWorkspace) !== + null || + existingExecutionWorkspace.cleanupReason?.startsWith( + "issue_terminal", + ) === true), + ); + const reopenableOwnArchivedTaskDirectory = + candidateOwnArchivedTaskDirectory && + !(await tx + .select({ id: issues.id }) + .from(issues) + .where( + and( + eq(issues.companyId, issue.companyId), + eq( + issues.executionWorkspaceId, + issue.executionWorkspaceId!, + ), + ne(issues.id, issue.id), + ), + ) + .limit(1) + .then((rows) => rows.length > 0)); + if ( + shouldUseIsolatedTaskDirectory({ + trustPreset: trustPreset.kind, + environmentDriver, + mode: resolvedMode, + hasProjectWorkspace: false, + projectWorkspaceId: issue.projectWorkspaceId, + hasSelectedExecutionWorkspace: + (Boolean(issue.executionWorkspaceId) || + reuseRequest.requestedShouldReuseExisting) && + !reopenableOwnArchivedTaskDirectory, + workspaceStrategies: [ + agentConfig.workspaceStrategy, + issueSettings?.workspaceStrategy, + ], + }) + ) { + effectivePreflightStrategy = "project_primary"; + } + } if ( isUnrunnableWorktreeCombo({ @@ -4562,7 +4719,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende issue.executionWorkspacePreference, }, resolvedMode, - resolvedStrategy, + resolvedStrategy: effectivePreflightStrategy, reusableExecutionWorkspaceAvailable: reuseRequest.existingExecutionWorkspaceAvailable, hasResolvablePriorSessionWorkspace, diff --git a/server/src/services/heartbeat/workspace-preparation.test.ts b/server/src/services/heartbeat/workspace-preparation.test.ts index 0a4c09e3996..5c1ac3ac73e 100644 --- a/server/src/services/heartbeat/workspace-preparation.test.ts +++ b/server/src/services/heartbeat/workspace-preparation.test.ts @@ -1,7 +1,8 @@ +import { resolvePaperclipInstanceRoot } from "../../home-paths.js"; import { preparePluginWorkspace } from "../plugin-workspaces.js"; import { execFile as execFileCallback } from "node:child_process"; import { randomUUID } from "node:crypto"; -import { mkdtemp, mkdir, readFile, readdir, rm, writeFile, access, rename, symlink } from "node:fs/promises"; +import { mkdtemp, mkdir, readFile, readdir, realpath, rm, writeFile, access, rename, symlink } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; @@ -1512,6 +1513,132 @@ describe.skipIf(!support.supported && !externalDatabaseUrl)("heartbeat workspace expect((await readIssue(issue.id)).executionWorkspaceId).toBe(prepared.persistedExecutionWorkspace!.id); }); + it("prepares a repository-free local task directory without a Git worktree", async () => { + const { input, issue } = await fixture(); + await db.update(issues).set({ projectId: null, projectWorkspaceId: null }).where(eq(issues.id, issue.id)); + input.task.issueRef = await readIssue(issue.id); + input.task.context = { issueId: issue.id }; + input.policy.useIsolatedTaskDirectory = true; + input.policy.effectiveExecutionWorkspaceMode = "isolated_workspace"; + input.policy.requestedExecutionWorkspaceMode = "isolated_workspace"; + input.config.mergedConfig = { workspaceStrategy: { type: "git_worktree" } }; + const prepared = await prepareHeartbeatWorkspace(db, input); + expect(await realpath(prepared.executionWorkspace.cwd)).toBe( + join(await realpath(resolvePaperclipInstanceRoot()), "isolated-workspaces", input.agent.companyId, issue.id), + ); + expect(prepared.persistedExecutionWorkspace).toMatchObject({ + mode: "isolated_workspace", + strategyType: "project_primary", + sourceIssueId: issue.id, + }); + }); + + it("reuses a bound ordinary repository-free plugin task directory across turns without requiring a Git worktree", async () => { + const { input, issue, envOrchestrator } = await fixture(); + await db.update(issues).set({ projectId: null, projectWorkspaceId: null }).where(eq(issues.id, issue.id)); + await db.update(agents).set({ adapterType: "paperclip_runner" }).where(eq(agents.id, input.agent.id)); + const pluginEnvironment = await environmentService(db).create(input.agent.companyId, { + name: `Plugin task dir ${issue.id}`, + driver: "plugin", + status: "active", + envVars: {}, + config: { pluginKey: "test.tasks", driverKey: "tasks" }, + }); + await db.update(agents).set({ defaultEnvironmentId: pluginEnvironment.id }).where(eq(agents.id, input.agent.id)); + input.agent = { ...input.agent, adapterType: "paperclip_runner", defaultEnvironmentId: pluginEnvironment.id }; + input.task.context = { issueId: issue.id }; + input.policy.requestedExecutionWorkspaceMode = "isolated_workspace"; + input.policy.effectiveExecutionWorkspaceMode = "isolated_workspace"; + + const selectForTurn = async (issueExecutionWorkspaceSettings: typeof input.policy.issueExecutionWorkspaceSettings) => { + const currentIssue = await readIssue(issue.id); + return selectHeartbeatEnvironment(db, { + run: input.run, + agent: input.agent, + task: { + issueRef: currentIssue, + issueContext: currentIssue, + issueId: issue.id, + context: input.task.context, + executionProjectId: null, + workspaceProjectContext: { hasWorkspace: false }, + boundSourceWorkspace: null, + hasSelectedWorkspaceSource: false, + taskWorkspaceIntent: null, + responsibleUserId: null, + }, + policy: { + ...input.policy, + issueExecutionWorkspaceSettings, + }, + config: { + config: input.agent.adapterConfig, + sourceWorkspaceConfig: input.agent.adapterConfig, + issueAssigneeOverrides: null, + }, + services: { + environmentsSvc: environmentService(db), + executionWorkspacesSvc: executionWorkspaceService(db), + instanceSettings: instanceSettingsService(db), + findSharedWorkspaceHolder: async () => null, + findExecutionWorkspaceHolder: async () => null, + }, + }); + }; + + const stopped = new Error("Plugin task directory acquisition boundary"); + const acquire = vi.spyOn(envOrchestrator, "acquireForRun").mockRejectedValue(stopped); + + const turn1 = await selectForTurn({ mode: "isolated_workspace" }); + expect(turn1.useIsolatedTaskDirectory).toBe(true); + input.task.issueRef = await readIssue(issue.id); + input.policy.useIsolatedTaskDirectory = turn1.useIsolatedTaskDirectory; + input.environment = { + ...input.environment, + selectedEnvironmentId: turn1.selectedEnvironmentId, + selectedEnvironmentForConfig: turn1.selectedEnvironmentForConfig, + environmentResolution: turn1.environmentResolution, + resolvedInstanceSettings: turn1.resolvedInstanceSettings, + }; + input.config.mergedConfig = { workspaceStrategy: { type: "git_worktree" } }; + await expect(prepareHeartbeatWorkspace(db, input)).rejects.toBe(stopped); + + const boundId = (await readIssue(issue.id)).executionWorkspaceId!; + const [workspace] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, boundId)); + expect(workspace).toMatchObject({ + cwd: `/workspaces/${issue.id}`, + mode: "isolated_workspace", + strategyType: "project_primary", + providerType: "adapter_managed", + projectWorkspaceId: null, + sourceIssueId: issue.id, + }); + + const turn2 = await selectForTurn({ mode: "isolated_workspace" }); + expect(turn2.useIsolatedTaskDirectory).toBe(true); + input.task.issueRef = await readIssue(issue.id); + input.policy.useIsolatedTaskDirectory = turn2.useIsolatedTaskDirectory; + input.reuse.existingExecutionWorkspace = turn2.existingExecutionWorkspace; + input.reuse.reusableExistingExecutionWorkspace = turn2.reusableExistingExecutionWorkspace; + input.reuse.requestedShouldReuseExisting = turn2.requestedShouldReuseExisting; + input.reuse.workspaceReuseRequest = turn2.workspaceReuseRequest; + await expect(prepareHeartbeatWorkspace(db, input)).rejects.toBe(stopped); + expect((await readIssue(issue.id)).executionWorkspaceId).toBe(boundId); + expect(acquire).toHaveBeenCalledTimes(2); + + const turn2ExplicitGit = await selectForTurn({ + mode: "isolated_workspace", + workspaceStrategy: { type: "git_worktree" }, + }); + expect(turn2ExplicitGit.useIsolatedTaskDirectory).toBe(false); + input.policy.useIsolatedTaskDirectory = turn2ExplicitGit.useIsolatedTaskDirectory; + await expect(prepareHeartbeatWorkspace(db, input)).rejects.toMatchObject({ + code: "workspace_validation_failed", + resultJson: { reason: "plugin_workspace_strategy_unsupported" }, + }); + expect(acquire).toHaveBeenCalledTimes(2); + }); + it.each(["reuse", "explicit_git", "foreign_path", "missing_path", "symlink_path", "binding_changed", "canonical_retry", "canonical_warning", "canonical_unknown_warning", "canonical_provider_warning", "canonical_fresh", "canonical_lease", "canonical_result", "canonical_controller", "canonical_output", "canonical_measurement", "canonical_repaired_git"] as const)("recomputes ordinary-turn policy for a saved source-free fresh directory: %s", async scenario => { const { input, issue } = await fixture(); const userId = `directory-owner-${randomUUID()}`; diff --git a/server/src/services/heartbeat/workspace-preparation.ts b/server/src/services/heartbeat/workspace-preparation.ts index c75967d70fe..e5598fd3946 100644 --- a/server/src/services/heartbeat/workspace-preparation.ts +++ b/server/src/services/heartbeat/workspace-preparation.ts @@ -448,7 +448,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace return { cwd, source: "agent_home" as const, projectId: null, workspaceId: null, repoUrl: null, repoRef: null, workspaceHints: [], warnings: [], baseCwdFallback: false, materializationFailures: [], additionalWorkspaces: [], referencedProjectFailures: [] }; } - if (useIsolatedTaskDirectory && issueRef && !pluginTaskWorkspace) { + if (useIsolatedTaskDirectory && issueRef && !pluginTaskWorkspace && !(nativeChatWorkspaceScope && !nativeChatWorkspaceScope.projectId)) { // A completed fresh attempt becomes the current task directory. New // input reuses that binding; only another fresh attempt changes roots. let cwd: string; @@ -730,7 +730,9 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace acquireTaskLease, onTaskPrepared: ensure => { ensureTaskWorkspace = ensure; }, mode: requestedExecutionWorkspaceMode, - strategy: resolveEffectiveWorkspaceStrategyType(requestedExecutionWorkspaceMode, mergedConfig), + strategy: (fresh || useIsolatedTaskDirectory) && !remoteAuthority + ? "project_primary" + : resolveEffectiveWorkspaceStrategyType(requestedExecutionWorkspaceMode, mergedConfig), branchMode: typeof parseObject(mergedConfig.workspaceStrategy).existingBranch === "string" ? "existing" : "create", branchName: typeof parseObject(mergedConfig.workspaceStrategy).existingBranch === "string" ? String(parseObject(mergedConfig.workspaceStrategy).existingBranch) @@ -794,7 +796,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace const skipHostProvision = copyOnlyProvisioning || hostProvisionDriver === "sandbox" || hostProvisionDriver === "ssh" || hostProvisionDriver === "plugin"; const hostExecutionWorkspaceConfig = controllerOnly ? {} : stripHostWorkspaceProvision({ - config: fresh && !remoteAuthority ? { ...mergedConfig, workspaceStrategy: { type: "project_primary" } } : mergedConfig, + config: (fresh || useIsolatedTaskDirectory) && !remoteAuthority ? { ...mergedConfig, workspaceStrategy: { type: "project_primary" } } : mergedConfig, skipHostProvision, }); const executionWorkspaceBase = { diff --git a/server/src/services/isolated-task-directory.test.ts b/server/src/services/isolated-task-directory.test.ts index b2d4125f87b..e021f6b6e13 100644 --- a/server/src/services/isolated-task-directory.test.ts +++ b/server/src/services/isolated-task-directory.test.ts @@ -18,18 +18,34 @@ const policy = { workspaceStrategies: [undefined, null, {}], }; -describe("repository-free low-trust workspace selection", () => { - it("selects a private directory for sandbox tasks without a repository", () => { +describe("repository-free workspace selection", () => { + it("selects a private directory for low-trust sandbox tasks without a repository", () => { expect(shouldUseIsolatedTaskDirectory(policy)).toBe(true); + expect(shouldUseIsolatedTaskDirectory({ ...policy, hasSelectedExecutionWorkspace: true })).toBe(true); }); it.each([ - { trustPreset: "standard" }, - { environmentDriver: "local" }, + { trustPreset: "standard", environmentDriver: "local" }, + { trustPreset: "standard", environmentDriver: null }, + { trustPreset: "standard", environmentDriver: "sandbox" }, + { trustPreset: "standard", environmentDriver: "plugin" }, + ])("selects a private directory for standard repository-free tasks: %j", (override) => { + expect(shouldUseIsolatedTaskDirectory({ ...policy, ...override })).toBe(true); + }); + + it.each([ + { trustPreset: "low_trust_review", environmentDriver: "local" }, + { trustPreset: "low_trust_review", environmentDriver: "plugin" }, + { trustPreset: "low_trust_review", environmentDriver: null }, + { trustPreset: "denied", environmentDriver: "sandbox" }, { environmentDriver: "ssh" }, + { trustPreset: "standard", environmentDriver: "ssh" }, { mode: "shared_workspace" }, { hasProjectWorkspace: true }, { projectWorkspaceId: "workspace-1" }, + { trustPreset: "standard", environmentDriver: "local", hasSelectedExecutionWorkspace: true }, + { trustPreset: "standard", environmentDriver: "sandbox", hasSelectedExecutionWorkspace: true }, + { trustPreset: "standard", environmentDriver: "plugin", hasSelectedExecutionWorkspace: true }, { workspaceStrategies: [{ type: "git_worktree" }] }, { workspaceStrategies: [{ existingBranch: "main" }] }, { workspaceStrategies: [{ provisionCommand: "setup" }] }, diff --git a/server/src/services/isolated-task-directory.ts b/server/src/services/isolated-task-directory.ts index 65d0748b85e..c7dae291881 100644 --- a/server/src/services/isolated-task-directory.ts +++ b/server/src/services/isolated-task-directory.ts @@ -4,22 +4,34 @@ import type { ExecutionWorkspace } from "@paperclipai/shared"; import { parseObject } from "../adapters/utils.js"; import { resolvePaperclipInstanceRoot } from "../home-paths.js"; -/** A repository-free sandbox task needs isolation, but has no Git base. */ +export function hasExplicitWorkspaceStrategy(workspaceStrategies: unknown[]): boolean { + return workspaceStrategies.some((value) => Object.keys(parseObject(value)).length > 0); +} + +/** A repository-free task needs isolation, but has no Git base. */ export function shouldUseIsolatedTaskDirectory(input: { trustPreset: string; environmentDriver: string | null; mode: string; hasProjectWorkspace: boolean; projectWorkspaceId: string | null; + hasSelectedExecutionWorkspace?: boolean; workspaceStrategies: unknown[]; }): boolean { - return input.trustPreset === "low_trust_review" - && input.environmentDriver === "sandbox" + const supportedEnvironment = input.trustPreset === "low_trust_review" + ? input.environmentDriver === "sandbox" + : input.trustPreset === "standard" && + !input.hasSelectedExecutionWorkspace && + (input.environmentDriver === "local" || + input.environmentDriver === "sandbox" || + input.environmentDriver === "plugin" || + input.environmentDriver === null); + return supportedEnvironment && input.mode === "isolated_workspace" && !input.hasProjectWorkspace && !input.projectWorkspaceId // Never discard an explicit repository/branch requirement or setup hook. - && input.workspaceStrategies.every((value) => Object.keys(parseObject(value)).length === 0); + && !hasExplicitWorkspaceStrategy(input.workspaceStrategies); } /** Stable across turns, separate from project roots and shared agent homes. */ diff --git a/server/src/services/provider-fresh-workspace.test.ts b/server/src/services/provider-fresh-workspace.test.ts index e26fad13e89..70148f8a2e1 100644 --- a/server/src/services/provider-fresh-workspace.test.ts +++ b/server/src/services/provider-fresh-workspace.test.ts @@ -5,7 +5,7 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import type { Db } from "@paperclipai/db"; -import { isBoundFreshPluginTaskDirectory, releaseProviderRecoveryTransfers, stageProviderFreshWorkspace } from "./provider-fresh-workspace.js"; +import { isBoundFreshPluginTaskDirectory, isBoundPluginTaskDirectory, releaseProviderRecoveryTransfers, stageProviderFreshWorkspace } from "./provider-fresh-workspace.js"; import type { ExecutionWorkspace } from "@paperclipai/shared"; const state = vi.hoisted(() => ({ getObject: vi.fn() })); vi.mock("../storage/index.js", () => ({ getStorageService: () => ({ getObject: state.getObject }) })); @@ -31,6 +31,29 @@ describe("fresh provider recovery transfer staging", () => { if (scenario === "repository") workspace.repoUrl = "https://github.com/example/repo.git"; if (scenario === "strategy") workspace.strategyType = "git_worktree"; expect(isBoundFreshPluginTaskDirectory({ companyId, issueId, workspaceId, workspace, owner })).toBe(scenario === "valid"); + expect(isBoundPluginTaskDirectory({ companyId, issueId, workspaceId, workspace, owner })).toBe(scenario === "valid"); + }); + + it.each(["valid", "company", "task", "binding", "owner", "path", "projectWorkspace", "staleFresh", "closed", "repository", "strategy"])( + "recognizes only the bound ordinary plugin task directory: %s", scenario => { + const companyId = randomUUID(), issueId = randomUUID(), workspaceId = randomUUID(); + const owner = { agentId: randomUUID(), environmentId: randomUUID(), pluginKey: "test.tasks", driverKey: "tasks" }; + const workspace = { id: workspaceId, companyId, sourceIssueId: issueId, projectWorkspaceId: null, status: "active", + mode: "isolated_workspace", strategyType: "project_primary", providerType: "adapter_managed", + repoUrl: null, branchName: null, cwd: `/workspaces/${issueId}`, + metadata: { runnerTaskWorkspaceOwner: owner }, + } as unknown as ExecutionWorkspace; + if (scenario === "company") workspace.companyId = randomUUID(); + if (scenario === "task") workspace.sourceIssueId = randomUUID(); + if (scenario === "binding") workspace.id = randomUUID(); + if (scenario === "owner") workspace.metadata!.runnerTaskWorkspaceOwner = { ...owner, agentId: randomUUID() }; + if (scenario === "path") workspace.cwd = "/workspaces/other"; + if (scenario === "projectWorkspace") workspace.projectWorkspaceId = randomUUID(); + if (scenario === "staleFresh") workspace.metadata!.runnerTaskFreshWorkspace = { attemptId: randomUUID() }; + if (scenario === "closed") workspace.status = "archived"; + if (scenario === "repository") workspace.repoUrl = "https://github.com/example/repo.git"; + if (scenario === "strategy") workspace.strategyType = "git_worktree"; + expect(isBoundPluginTaskDirectory({ companyId, issueId, workspaceId, workspace, owner })).toBe(scenario === "valid"); }); it("verifies immutable transfer files and reuses stable descriptors after interruption", async () => { diff --git a/server/src/services/provider-fresh-workspace.ts b/server/src/services/provider-fresh-workspace.ts index 98a478a375d..75926dad994 100644 --- a/server/src/services/provider-fresh-workspace.ts +++ b/server/src/services/provider-fresh-workspace.ts @@ -35,6 +35,31 @@ export function isBoundFreshPluginTaskDirectory(input: { return fresh.success && fresh.data.attemptId === workspace.id; } +export function isBoundPluginTaskDirectory(input: { + companyId: string; issueId: string; workspaceId: string | null; + workspace: ExecutionWorkspace | null; + owner: { agentId: string; environmentId: string; pluginKey: unknown; driverKey: unknown }; +}): boolean { + if (isBoundFreshPluginTaskDirectory(input)) return true; + const workspace = input.workspace; + return Boolean( + workspace && + workspace.id === input.workspaceId && + workspace.companyId === input.companyId && + workspace.sourceIssueId === input.issueId && + workspace.status === "active" && + !workspace.projectWorkspaceId && + workspace.mode === "isolated_workspace" && + workspace.strategyType === "project_primary" && + workspace.providerType === "adapter_managed" && + !workspace.repoUrl && + !workspace.branchName && + workspace.cwd === `/workspaces/${input.issueId}` && + workspace.metadata?.runnerTaskFreshWorkspace === undefined && + isDeepStrictEqual(workspace.metadata?.runnerTaskWorkspaceOwner, input.owner), + ); +} + export async function stageProviderFreshWorkspace(input: { db: Db; companyId: string; issueId: string; attemptId: string; sourceRunId: string; previousWorkspaceId: string | null; existing?: PluginFreshWorkspace;