diff --git a/server/src/__tests__/agent-project-access.test.ts b/server/src/__tests__/agent-project-access.test.ts index 8f4bf50eb38..489840fcc90 100644 --- a/server/src/__tests__/agent-project-access.test.ts +++ b/server/src/__tests__/agent-project-access.test.ts @@ -45,12 +45,12 @@ describe("additive project access", () => { } const board = { type: "board" as const, source: "local_implicit" as const }; - it("keeps a historical denial blocked after the task moves to an allowed project but retains its source", async () => { + it("keeps a historical denial blocked after the task moves to an allowed project but explicitly retains its source", async () => { const f = await seed(); const [source] = await db.insert(projectWorkspaces).values({ companyId: f.companyId, projectId: f.selected[1]!.id, name: "Original repository", cwd: "/tmp/project-access-original" }).returning(); await db.update(issues).set({ projectWorkspaceId: source!.id, - workspaceSelection: { version: 1, source: "project", selection: { + workspaceSelection: { version: 1, source: "explicit", selection: { kind: "configured_source", projectWorkspaceId: source!.id, mode: "managed_isolated", } } }).where(eq(issues.id, f.issue.id)); const moved = await issueService(db).update(f.issue.id, { projectId: f.selected[0]!.id }); @@ -67,6 +67,23 @@ describe("additive project access", () => { await expect(assertTaskWorkspaceExecutionAccess(db, actor, f.companyId, { issueId: f.issue.id })).resolves.toBeDefined(); }); + it("re-derives a project-derived workspace source when moving an unbound task to an allowed project", async () => { + const f = await seed(); + const [deniedSource] = await db.insert(projectWorkspaces).values({ companyId: f.companyId, projectId: f.selected[1]!.id, + name: "Original repository", cwd: "/tmp/project-access-original" }).returning(); + const [allowedSource] = await db.insert(projectWorkspaces).values({ companyId: f.companyId, projectId: f.selected[0]!.id, + name: "Allowed repository", cwd: "/tmp/project-access-allowed" }).returning(); + await db.update(issues).set({ projectWorkspaceId: deniedSource!.id, + workspaceSelection: { version: 1, source: "project", selection: { + kind: "configured_source", projectWorkspaceId: deniedSource!.id, mode: "managed_isolated", + } } }).where(eq(issues.id, f.issue.id)); + const moved = await issueService(db).update(f.issue.id, { projectId: f.selected[0]!.id }); + expect(moved).toMatchObject({ projectId: f.selected[0]!.id, projectWorkspaceId: allowedSource!.id }); + const actor = { type: "agent" as const, source: "agent_key" as const, agentId: f.agentId, companyId: f.companyId }; + await expect(assertTaskWorkspaceExecutionAccess(db, actor, f.companyId, { issueId: f.issue.id })).resolves.toBeDefined(); + expect(await taskInterruptionPresentation(db, moved!)).toMatchObject({ canRetry: true, projectAccess: { ready: true } }); + }); + it.each(["applied", "pending"] as const)("rechecks the selected source after an %s repair instead of the old denied project", async repair => { const f = await seed(); const [source] = await db.insert(projectWorkspaces).values({ companyId: f.companyId, projectId: f.selected[0]!.id, diff --git a/server/src/__tests__/issue-project-move-workspace.test.ts b/server/src/__tests__/issue-project-move-workspace.test.ts new file mode 100644 index 00000000000..76169aad80d --- /dev/null +++ b/server/src/__tests__/issue-project-move-workspace.test.ts @@ -0,0 +1,503 @@ +import { randomUUID } from "node:crypto"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { eq } from "drizzle-orm"; +import { + agents, + companies, + companyMemberships, + createDb, + executionWorkspaces, + heartbeatRuns, + instanceSettings, + issues, + plugins, + projects, + projectWorkspaces, + type Db, +} from "@paperclipai/db"; +import { startEmbeddedPostgresTestDatabase, type EmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { createPluginWorkspaceFixture } from "./helpers/plugin-workspaces.js"; +import { issueService } from "../services/issues.js"; +import { executionWorkspaceService } from "../services/execution-workspaces.js"; +import { assertTaskWorkspaceExecutionAccess } from "../services/task-workspace-access.js"; + +describe("project move workspace reconciliation", () => { + let pg: EmbeddedPostgresTestDatabase; + let db: Db; + + beforeAll(async () => { + pg = await startEmbeddedPostgresTestDatabase("paperclip-issue-project-move-"); + db = createDb(pg.connectionString); + }, 60_000); + + afterAll(async () => { + await pg?.cleanup(); + }, 30_000); + + async function seedTwoProjects() { + const companyId = randomUUID(); + const agentId = randomUUID(); + await db.insert(companies).values({ + id: companyId, + name: "Move Co", + issuePrefix: `M${companyId.slice(0, 5).toUpperCase()}`, + status: "active", + }); + await db.insert(instanceSettings).values({ + id: randomUUID(), + singletonKey: "default", + experimental: { enableIsolatedWorkspaces: true }, + }).onConflictDoUpdate({ + target: instanceSettings.singletonKey, + set: { experimental: { enableIsolatedWorkspaces: true }, updatedAt: new Date() }, + }); + await db.insert(agents).values({ + id: agentId, + companyId, + name: "Winston", + adapterType: "paperclip_runner", + status: "idle", + }); + + const storage = await createPluginWorkspaceFixture(db, companyId); + const [storagePlugin] = await db.select().from(plugins).where(eq(plugins.id, storage.pluginId)); + await db.update(plugins).set({ + manifestJson: { + ...storagePlugin!.manifestJson, + workspaceProvider: { + ...storagePlugin!.manifestJson.workspaceProvider!, + defaultForProjects: { mode: "isolated_workspace", strategy: "git_worktree" }, + }, + }, + }).where(eq(plugins.id, storage.pluginId)); + + const [coreProject] = await db.insert(projects).values({ + companyId, + name: "Paperclip (Deprecated)", + executionWorkspacePolicy: { + enabled: true, + defaultMode: "isolated_workspace", + workspaceStrategy: { type: "git_worktree" }, + }, + }).returning(); + const [coreWorkspace] = await db.insert(projectWorkspaces).values({ + companyId, + projectId: coreProject!.id, + name: "paperclipai/paperclip (core)", + sourceType: "git_repo", + repoUrl: "https://github.com/paperclipai/paperclip", + isPrimary: true, + }).returning(); + + const [pluginProject] = await db.insert(projects).values({ + companyId, + name: "Paperclip", + executionWorkspacePolicy: { + enabled: true, + storageProviderPluginId: storage.pluginId, + }, + }).returning(); + const [pluginWorkspace] = await db.insert(projectWorkspaces).values({ + companyId, + projectId: pluginProject!.id, + name: "paperclipai/paperclip (plugin)", + sourceType: "git_repo", + repoUrl: "https://github.com/paperclipai/paperclip", + isPrimary: true, + }).returning(); + + const [emptyProject] = await db.insert(projects).values({ + companyId, + name: "Notes Only", + }).returning(); + + return { + companyId, + agentId, + coreProject: coreProject!, + coreWorkspace: coreWorkspace!, + pluginProject: pluginProject!, + pluginWorkspace: pluginWorkspace!, + emptyProject: emptyProject!, + }; + } + + it("re-derives a project-derived workspace when moving an unbound task to another project", async () => { + const f = await seedTwoProjects(); + const svc = issueService(db); + const created = await svc.create(f.companyId, { + title: "Investigate duplicate routines", + projectId: f.coreProject.id, + assigneeAgentId: f.agentId, + status: "todo", + }); + expect(created.projectWorkspaceId).toBe(f.coreWorkspace.id); + expect(created.workspaceSelection).toMatchObject({ + version: 1, + source: "project", + selection: { + kind: "configured_source", + projectWorkspaceId: f.coreWorkspace.id, + mode: "managed_isolated", + }, + }); + + const moved = await svc.update(created.id, { projectId: f.pluginProject.id }); + expect(moved).toMatchObject({ + projectId: f.pluginProject.id, + projectWorkspaceId: f.pluginWorkspace.id, + workspaceBindingRevision: created.workspaceBindingRevision + 1, + workspaceSelection: { + version: 1, + source: "project", + selection: { + kind: "configured_source", + projectWorkspaceId: f.pluginWorkspace.id, + mode: "managed_isolated", + }, + }, + }); + }); + + it("clears a project-derived workspace when moving to no project or a sourceless project", async () => { + const f = await seedTwoProjects(); + const svc = issueService(db); + const created = await svc.create(f.companyId, { + title: "Move to sourceless", + projectId: f.coreProject.id, + assigneeAgentId: f.agentId, + status: "todo", + }); + + const movedToEmpty = await svc.update(created.id, { projectId: f.emptyProject.id }); + expect(movedToEmpty).toMatchObject({ + projectId: f.emptyProject.id, + projectWorkspaceId: null, + workspaceSelection: null, + }); + + const created2 = await svc.create(f.companyId, { + title: "Move to projectless", + projectId: f.coreProject.id, + assigneeAgentId: f.agentId, + status: "todo", + }); + const movedToNull = await svc.update(created2.id, { projectId: null }); + expect(movedToNull).toMatchObject({ + projectId: null, + projectWorkspaceId: null, + workspaceSelection: null, + executionWorkspaceSettings: null, + }); + }); + + it("preserves an explicit workspace selection when moving a task to another project", async () => { + const f = await seedTwoProjects(); + const svc = issueService(db); + const created = await svc.create(f.companyId, { + title: "Explicit workspace task", + projectId: f.coreProject.id, + assigneeAgentId: f.agentId, + status: "todo", + workspaceSelection: { + kind: "configured_source", + projectWorkspaceId: f.coreWorkspace.id, + mode: "managed_isolated", + }, + workspaceSelectionSource: "explicit", + }); + + const moved = await svc.update(created.id, { projectId: f.pluginProject.id }); + expect(moved).toMatchObject({ + projectId: f.pluginProject.id, + projectWorkspaceId: f.coreWorkspace.id, + workspaceSelection: { + version: 1, + source: "explicit", + selection: { + kind: "configured_source", + projectWorkspaceId: f.coreWorkspace.id, + mode: "managed_isolated", + }, + }, + }); + }); + + it("preserves a bound execution workspace when moving a task to another project", async () => { + const f = await seedTwoProjects(); + const svc = issueService(db); + const created = await svc.create(f.companyId, { + title: "Task with bound files", + projectId: f.coreProject.id, + assigneeAgentId: f.agentId, + status: "todo", + }); + const [boundWs] = await db.insert(executionWorkspaces).values({ + companyId: f.companyId, + projectId: f.coreProject.id, + projectWorkspaceId: f.coreWorkspace.id, + sourceIssueId: created.id, + name: "Bound worktree", + cwd: "/tmp/bound-worktree", + mode: "isolated_workspace", + strategyType: "git_worktree", + }).returning(); + await db.update(issues).set({ executionWorkspaceId: boundWs!.id }).where(eq(issues.id, created.id)); + + const moved = await svc.update(created.id, { projectId: f.pluginProject.id }); + expect(moved).toMatchObject({ + projectId: f.pluginProject.id, + executionWorkspaceId: boundWs!.id, + projectWorkspaceId: f.coreWorkspace.id, + }); + }); + + it("does not mutate workspace binding mid-run when moving a task with an active running run linked only by issueId", async () => { + const f = await seedTwoProjects(); + const svc = issueService(db); + const created = await svc.create(f.companyId, { + title: "Task with active run", + projectId: f.coreProject.id, + assigneeAgentId: f.agentId, + status: "in_progress", + }); + const runId = randomUUID(); + await db.insert(heartbeatRuns).values({ + id: runId, + companyId: f.companyId, + agentId: f.agentId, + issueId: created.id, + status: "running", + contextSnapshot: {}, + }); + + const moved = await svc.update(created.id, { projectId: f.pluginProject.id }); + expect(moved).toMatchObject({ + projectId: f.pluginProject.id, + projectWorkspaceId: f.coreWorkspace.id, + }); + }); + + it("re-derives a legacy projectWorkspaceId with no workspaceSelection when moving to another project", async () => { + const f = await seedTwoProjects(); + const svc = issueService(db); + const issueId = randomUUID(); + await db.insert(issues).values({ + id: issueId, + companyId: f.companyId, + title: "Legacy unbound task", + status: "todo", + projectId: f.coreProject.id, + projectWorkspaceId: f.coreWorkspace.id, + workspaceSelection: null, + assigneeAgentId: f.agentId, + }); + + const moved = await svc.update(issueId, { projectId: f.pluginProject.id }); + expect(moved).toMatchObject({ + projectId: f.pluginProject.id, + projectWorkspaceId: f.pluginWorkspace.id, + workspaceBindingRevision: 1, + workspaceSelection: { + version: 1, + source: "project", + selection: { + kind: "configured_source", + projectWorkspaceId: f.pluginWorkspace.id, + mode: "managed_isolated", + }, + }, + }); + }); + + it("honors an explicit projectWorkspaceId passed alongside a project move", async () => { + const f = await seedTwoProjects(); + const svc = issueService(db); + const created = await svc.create(f.companyId, { + title: "Move with explicit source", + projectId: f.coreProject.id, + assigneeAgentId: f.agentId, + status: "todo", + }); + + const moved = await svc.update(created.id, { + projectId: f.pluginProject.id, + projectWorkspaceId: f.coreWorkspace.id, + }); + expect(moved).toMatchObject({ + projectId: f.pluginProject.id, + projectWorkspaceId: f.coreWorkspace.id, + }); + }); + + it("allows moving an unbound task to a trust-denied project with workspaceSelectionActor while keeping execution access denied", async () => { + const f = await seedTwoProjects(); + const restrictedAgentId = randomUUID(); + await db.insert(agents).values({ + id: restrictedAgentId, + companyId: f.companyId, + name: "Restricted Reviewer", + adapterType: "process", + status: "idle", + permissions: { + trustPreset: "low_trust_review", + authorizationPolicy: { + trustBoundary: { + mode: "low_trust_review", + companyId: f.companyId, + projectIds: [f.coreProject.id], + }, + }, + }, + }); + await db.insert(companyMemberships).values({ + companyId: f.companyId, + principalType: "agent", + principalId: restrictedAgentId, + membershipRole: "member", + status: "active", + }); + const svc = issueService(db); + const board = { type: "board" as const, source: "local_implicit" as const }; + await db.update(projects).set({ + executionWorkspacePolicy: { + enabled: true, + storageProviderPluginId: (f.pluginProject.executionWorkspacePolicy as Record).storageProviderPluginId, + trustPreset: "low_trust_review", + authorizationPolicy: { + trustBoundary: { + mode: "low_trust_review", + companyId: f.companyId, + projectIds: [f.pluginProject.id], + }, + }, + } as Record, + }).where(eq(projects.id, f.pluginProject.id)); + const created = await svc.create(f.companyId, { + title: "Task moving to denied project", + projectId: f.coreProject.id, + assigneeAgentId: restrictedAgentId, + status: "todo", + workspaceSelectionActor: board, + }); + + const moved = await svc.update(created.id, { + projectId: f.pluginProject.id, + workspaceSelectionActor: board, + }); + expect(moved).toMatchObject({ + projectId: f.pluginProject.id, + projectWorkspaceId: f.pluginWorkspace.id, + workspaceSelection: null, + workspaceBindingRevision: created.workspaceBindingRevision + 1, + }); + + const agentActor = { + type: "agent" as const, + source: "agent_key" as const, + agentId: restrictedAgentId, + companyId: f.companyId, + }; + await expect( + assertTaskWorkspaceExecutionAccess(db, agentActor, f.companyId, { issueId: created.id }), + ).rejects.toMatchObject({ status: 403 }); + }); + + it("reconciles an already-moved task with a stale project-derived workspace at admission", async () => { + const f = await seedTwoProjects(); + const issueId = randomUUID(); + const runId = randomUUID(); + await db.insert(issues).values({ + id: issueId, + companyId: f.companyId, + title: "Already moved before fix", + status: "todo", + projectId: f.pluginProject.id, + projectWorkspaceId: f.coreWorkspace.id, + assigneeAgentId: f.agentId, + executionWorkspaceSettings: { mode: "isolated_workspace" }, + workspaceSelection: { + version: 1, + source: "project", + selection: { + kind: "configured_source", + projectWorkspaceId: f.coreWorkspace.id, + mode: "managed_isolated", + }, + }, + }); + await db.insert(heartbeatRuns).values({ + id: runId, + companyId: f.companyId, + agentId: f.agentId, + issueId, + status: "running", + contextSnapshot: { issueId }, + }); + + const wsSvc = executionWorkspaceService(db); + const reconciled = await wsSvc.reconcileStaleProjectWorkspaceAtAdmission({ + companyId: f.companyId, + issueId, + runId, + }); + expect(reconciled).toBe(true); + + const [after] = await db.select().from(issues).where(eq(issues.id, issueId)); + expect(after).toMatchObject({ + projectId: f.pluginProject.id, + projectWorkspaceId: f.pluginWorkspace.id, + workspaceBindingRevision: 1, + workspaceSelection: { + version: 1, + source: "project", + selection: { + kind: "configured_source", + projectWorkspaceId: f.pluginWorkspace.id, + mode: "managed_isolated", + }, + }, + }); + + // Re-running admission reconciliation once consistent is a no-op. + expect(await wsSvc.reconcileStaleProjectWorkspaceAtAdmission({ + companyId: f.companyId, + issueId, + runId, + })).toBe(false); + }); + + it("does not reconcile an explicit cross-project workspace selection at admission", async () => { + const f = await seedTwoProjects(); + const issueId = randomUUID(); + const runId = randomUUID(); + await db.insert(issues).values({ + id: issueId, + companyId: f.companyId, + title: "Explicit cross-project selection", + status: "todo", + projectId: f.pluginProject.id, + projectWorkspaceId: f.coreWorkspace.id, + assigneeAgentId: f.agentId, + workspaceSelection: { + version: 1, + source: "explicit", + selection: { + kind: "configured_source", + projectWorkspaceId: f.coreWorkspace.id, + mode: "managed_isolated", + }, + }, + }); + + const wsSvc = executionWorkspaceService(db); + expect(await wsSvc.reconcileStaleProjectWorkspaceAtAdmission({ + companyId: f.companyId, + issueId, + runId, + })).toBe(false); + + const [after] = await db.select().from(issues).where(eq(issues.id, issueId)); + expect(after?.projectWorkspaceId).toBe(f.coreWorkspace.id); + }); +}); diff --git a/server/src/services/execution-workspaces.ts b/server/src/services/execution-workspaces.ts index 9f122bb070f..8fec332aad9 100644 --- a/server/src/services/execution-workspaces.ts +++ b/server/src/services/execution-workspaces.ts @@ -1,5 +1,10 @@ import { notifyStatusCardIssueChange } from "./status-card-notifications.js"; import { effectiveProjectWorkspacePolicy } from "./project-workspace-provider.js"; +import { + deriveProjectDefaultWorkspaceBinding, + hasActiveTaskWorkspaceRunHolder, + isProjectDerivedWorkspaceBindingStale, +} from "./project-move-workspace-reconciliation.js"; import { readRemoteWorkspaceAuthority, readWorkspaceProviderBinding } from "@paperclipai/shared"; import { cleanupRemoteWorkspaceAllocation, inspectRemoteWorkspacePersistence, type DestroyRemoteWorkspaceLease } from "./remote-workspace-lifecycle.js"; import { inspectPluginWorkspace, removePluginWorkspace, restorePluginWorkspace, pluginWorkspaceSupportsMergeAncestry, type WorkspaceWorkers } from "./plugin-workspaces.js"; @@ -1550,13 +1555,9 @@ export async function releaseAncestorWorkspaceBinding(tx: DbTransaction, input: if (!await bindsRelativesExecutionWorkspace(tx, { companyId: input.companyId, executionWorkspaceId: task.executionWorkspaceId, task })) { return false; } - const [holder] = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( - eq(heartbeatRuns.companyId, input.companyId), input.runId ? ne(heartbeatRuns.id, input.runId) : undefined, - or(eq(heartbeatRuns.nativeIssueId, input.issueId), - sql`coalesce(${heartbeatRuns.contextSnapshot}->>'issueId', ${heartbeatRuns.contextSnapshot}->>'taskId') = ${input.issueId}`), - eq(heartbeatRuns.status, "running"), - )).limit(1); - if (holder) return false; + if (await hasActiveTaskWorkspaceRunHolder(tx, { + companyId: input.companyId, issueId: input.issueId, executionRunId: task.executionRunId, excludeRunId: input.runId, + })) return false; if (await hasPendingTaskWorkspaceRecovery(tx, { companyId: input.companyId, issueId: input.issueId, excludeRunId: input.runId })) return false; const selection = task.workspaceSelection; await notifyStatusCardIssueChange(tx, task.companyId); @@ -1824,6 +1825,84 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic return db.transaction(tx => releaseAncestorWorkspaceBinding(tx, input)); } + async function reconcileProjectWorkspaceForProjectMove(input: { + companyId: string; + task: typeof issues.$inferSelect; + nextProjectId: string | null; + assigneeAgentId?: string | null; + assigneeAdapterOverrides?: unknown; + executionPolicy?: unknown; + isolatedWorkspacesEnabled: boolean; + }, tx: DbTransaction) { + const stale = await isProjectDerivedWorkspaceBindingStale(tx, { + companyId: input.companyId, + task: { ...input.task, projectId: input.nextProjectId }, + previousProjectId: input.task.projectId, + }); + if (!stale) return {}; + const holder = await hasActiveTaskWorkspaceRunHolder(tx, { + companyId: input.companyId, issueId: input.task.id, executionRunId: input.task.executionRunId, + }); + if (holder || await hasPendingTaskWorkspaceRecovery(tx, { companyId: input.companyId, issueId: input.task.id })) return {}; + const derived = await deriveProjectDefaultWorkspaceBinding(tx, { + companyId: input.companyId, + projectId: input.nextProjectId, + assigneeAgentId: input.assigneeAgentId, + assigneeAdapterOverrides: input.assigneeAdapterOverrides, + executionPolicy: input.executionPolicy, + isolatedWorkspacesEnabled: input.isolatedWorkspacesEnabled, + allowTrustDenial: true, + resolveSourceWorkspaceStrategy, + }); + return { + ...derived, + workspaceBindingRevision: input.task.workspaceBindingRevision + 1, + }; + } + + /** Reconciles unbound tasks whose project-derived workspace still points to a previous project after a move on an older release. */ + async function reconcileStaleProjectWorkspaceAtAdmission(input: { companyId: string; issueId: string; runId: string }) { + const [candidate] = await db.select({ + projectId: issues.projectId, + executionWorkspaceId: issues.executionWorkspaceId, + projectWorkspaceId: issues.projectWorkspaceId, + workspaceSelection: issues.workspaceSelection, + workspacePendingSelection: issues.workspacePendingSelection, + }).from(issues).where(and(eq(issues.id, input.issueId), eq(issues.companyId, input.companyId))).limit(1); + if (!candidate || candidate.executionWorkspaceId != null || candidate.workspacePendingSelection != null + || candidate.workspaceSelection?.source !== "project" + || candidate.workspaceSelection.selection.kind !== "configured_source") return false; + if (!await isProjectDerivedWorkspaceBindingStale(db, { companyId: input.companyId, task: candidate })) return false; + const experimental = await instanceSettingsService(db).getExperimental(); + return db.transaction(async tx => { + const [task] = await measureRunPhase("workspace.row_lock", () => tx.select().from(issues).where(and( + eq(issues.id, input.issueId), eq(issues.companyId, input.companyId), + )).for("update")); + if (!task || !await isProjectDerivedWorkspaceBindingStale(tx, { companyId: input.companyId, task })) return false; + const holder = await hasActiveTaskWorkspaceRunHolder(tx, { + companyId: input.companyId, issueId: input.issueId, executionRunId: task.executionRunId, excludeRunId: input.runId, + }); + if (holder || await hasPendingTaskWorkspaceRecovery(tx, { companyId: input.companyId, issueId: input.issueId, excludeRunId: input.runId })) return false; + const derived = await deriveProjectDefaultWorkspaceBinding(tx, { + companyId: input.companyId, + projectId: task.projectId, + assigneeAgentId: task.assigneeAgentId, + assigneeAdapterOverrides: task.assigneeAdapterOverrides, + executionPolicy: task.executionPolicy, + isolatedWorkspacesEnabled: experimental.enableIsolatedWorkspaces, + allowTrustDenial: true, + resolveSourceWorkspaceStrategy, + }); + await notifyStatusCardIssueChange(tx, input.companyId); + await tx.update(issues).set({ + ...derived, + workspaceBindingRevision: task.workspaceBindingRevision + 1, + updatedAt: new Date(), + }).where(eq(issues.id, task.id)); + return true; + }); + } + async function bindTaskWorkspace(companyId: string, issueId: string, workspaceId: string, patch: TaskWorkspaceBindingPatch = {}) { return db.transaction(async tx => { const [task] = await measureRunPhase("workspace.row_lock", () => tx.select().from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, companyId))).for("no key update")); @@ -1892,12 +1971,9 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic task.executionWorkspaceId && input.patch.executionWorkspaceId !== null) { throw conflict("Task already has bound files; schedule a workspace selection or explicitly clear its binding when changing the source"); } - const [holder] = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( - eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.status, "running"), - or(eq(heartbeatRuns.nativeIssueId, input.issueId), - sql`coalesce(${heartbeatRuns.contextSnapshot}->>'issueId', ${heartbeatRuns.contextSnapshot}->>'taskId') = ${input.issueId}`, - task.executionRunId ? eq(heartbeatRuns.id, task.executionRunId) : undefined), - )).limit(1); + const holder = await hasActiveTaskWorkspaceRunHolder(tx, { + companyId: input.companyId, issueId: input.issueId, executionRunId: task.executionRunId, + }); const unsettled = await hasPendingTaskWorkspaceRecovery(tx, input); if (holder || unsettled) throw conflict("Task run still owns its workspace; schedule a workspace selection for the next admission"); const [selectedWorkspace] = input.patch.executionWorkspaceId @@ -2931,7 +3007,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic assertTaskRepositoryPublicationAllowed: executionWorkspaceRepositoryService(db).assertPublicationAllowed, prepareConfiguredRepositoryCopy: executionWorkspaceRepositoryService(db).prepareConfiguredRepositoryCopy, assertTaskRepositoryRecoveryBinding: executionWorkspaceRepositoryService(db).assertRecoveryBinding, - resolveSourceWorkspaceStrategy, validateSelection, validateStoredSelectionForRun, inspectTaskWorkspace, selectTaskWorkspace, applyPendingTaskWorkspaceSelection, releaseAncestorWorkspaceBindingAtAdmission, bindTaskWorkspace, prepareTaskWorkspaceUpdate, assertTaskWorkspaceUpdateAccess, + resolveSourceWorkspaceStrategy, validateSelection, validateStoredSelectionForRun, inspectTaskWorkspace, selectTaskWorkspace, applyPendingTaskWorkspaceSelection, releaseAncestorWorkspaceBindingAtAdmission, reconcileProjectWorkspaceForProjectMove, reconcileStaleProjectWorkspaceAtAdmission, bindTaskWorkspace, prepareTaskWorkspaceUpdate, assertTaskWorkspaceUpdateAccess, listOverview: async ( companyId: string, filters: WorkspaceOverviewQuery, diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index dcdc06a6447..3bdd1d4453c 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -2379,7 +2379,9 @@ export function heartbeatService( // workspace still finishes the interrupted attempt there first. const released = run.processLossRetryCount > 0 || (readiness && readiness.mode !== "fresh_isolated_workspace") ? false : await executionWorkspacesSvc.releaseAncestorWorkspaceBindingAtAdmission({ companyId: agent.companyId, issueId, runId: run.id }); - if (changed || released) { + const reconciledProjectWorkspace = run.processLossRetryCount > 0 ? false + : await executionWorkspacesSvc.reconcileStaleProjectWorkspaceAtAdmission({ companyId: agent.companyId, issueId, runId: run.id }); + if (changed || released || reconciledProjectWorkspace) { delete context.resumeSessionParams; delete context.resumeSessionDisplayId; context.workspaceSelectionChanged = true; diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index 227138ad426..31b2992e32a 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -38,6 +38,7 @@ import { assertNoCaseHandoffMutation, cancelCaseHandoffsForIssue, completeTermin import { measureRunPhase } from "./execution-preparation-timing.js"; import { automaticReadRecoveryCleanupCondition, directHumanCommentCondition, humanCreatedIssueCondition, pendingUserRequestCondition, pendingUserRequestRowCondition, touchedByUserCondition, userParticipationActivityCondition } from "./issue-participation.js"; import { resolveProjectDefaultWorkspaceId } from "./project-default-workspace.js"; +import { deriveProjectDefaultWorkspaceBinding } from "./project-move-workspace-reconciliation.js"; import { type AuthorizationActor, canActorReadIssuePrivacy, executionWorkspaceReadSqlCondition, projectReadSqlCondition } from "./authorization.js"; import { assertExecutionWorkspaceRecordAccess, assertTaskWorkspaceSourceProjectAccess } from "./task-workspace-access.js"; import { type TaskWorkspaceSelection, type TaskWorkspaceIntent } from "@paperclipai/shared"; @@ -11013,32 +11014,19 @@ export function issueService(db: Db) { ) as Record | null; } if (!executionWorkspaceId && !projectWorkspaceId && issueData.projectId && workspaceIntent?.selection.kind !== "task_directory") { - const project = await tx - .select({ - executionWorkspacePolicy: projects.executionWorkspacePolicy, - }) - .from(projects) - .where( - and( - eq(projects.id, issueData.projectId), - eq(projects.companyId, companyId), - ), - ) - .then((rows) => rows[0] ?? null); - const projectPolicy = parseProjectExecutionWorkspacePolicy( - project?.executionWorkspacePolicy, - ); - projectWorkspaceId = await resolveProjectDefaultWorkspaceId(tx, { - companyId, projectId: issueData.projectId, policy: projectPolicy, + const derived = await deriveProjectDefaultWorkspaceBinding(tx, { + companyId, + projectId: issueData.projectId, + assigneeAgentId: issueData.assigneeAgentId, + assigneeAdapterOverrides: issueData.assigneeAdapterOverrides, + executionPolicy: issueData.executionPolicy, + isolatedWorkspacesEnabled, + existingExecutionWorkspaceSettings: executionWorkspaceSettings, + resolveSourceWorkspaceStrategy: (input, reader) => + executionWorkspaceService(db).resolveSourceWorkspaceStrategy(input, reader), }); - if (projectWorkspaceId && isolatedWorkspacesEnabled) { - const sourceStrategy = await executionWorkspaceService(db).resolveSourceWorkspaceStrategy({ companyId, - assigneeAgentId: issueData.assigneeAgentId, assigneeAdapterOverrides: issueData.assigneeAdapterOverrides, - executionWorkspaceSettings, executionWorkspacePolicy: projectPolicy, sourceWorkspaceId: projectWorkspaceId, - typedSelection: false, projectId: issueData.projectId, executionPolicy: issueData.executionPolicy }, tx); - if (sourceStrategy === "git_worktree") workspaceIntent = { version: 1, source: "project", - selection: { kind: "configured_source", projectWorkspaceId, mode: "managed_isolated" } }; - } + projectWorkspaceId = derived.projectWorkspaceId; + if (derived.workspaceSelection) workspaceIntent = derived.workspaceSelection; } if (projectWorkspaceId && workspaceSelectionActor) { const [readableSource] = await tx.select({ id: projectWorkspaces.id, projectId: projectWorkspaces.projectId, executionWorkspacePolicy: projects.executionWorkspacePolicy }).from(projectWorkspaces) @@ -12144,8 +12132,12 @@ export function issueService(db: Db) { } Object.assign(patch, transition.patch); } - if (issueData.executionWorkspaceId !== undefined || issueData.projectWorkspaceId !== undefined || - issueData.executionWorkspacePreference !== undefined || issueData.executionWorkspaceSettings !== undefined) { + const explicitWorkspaceFieldsChanged = + issueData.executionWorkspaceId !== undefined || + issueData.projectWorkspaceId !== undefined || + issueData.executionWorkspacePreference !== undefined || + issueData.executionWorkspaceSettings !== undefined; + if (explicitWorkspaceFieldsChanged) { Object.assign(patch, await executionWorkspaceService(db).prepareTaskWorkspaceUpdate({ companyId: receiptExisting.companyId, issueId: receiptExisting.id, patch, }, tx)); @@ -12188,6 +12180,30 @@ export function issueService(db: Db) { patch.privacyRootIssueId = receiptExisting.id; } } + const effectiveNextProjectId = patch.projectId !== undefined ? patch.projectId : receiptExisting.projectId; + if (effectiveNextProjectId !== receiptExisting.projectId && !explicitWorkspaceFieldsChanged) { + Object.assign( + patch, + await executionWorkspaceService(db).reconcileProjectWorkspaceForProjectMove( + { + companyId: receiptExisting.companyId, + task: receiptExisting, + nextProjectId: effectiveNextProjectId ?? null, + assigneeAgentId: nextAssigneeAgentId, + assigneeAdapterOverrides: + issueData.assigneeAdapterOverrides !== undefined + ? issueData.assigneeAdapterOverrides + : receiptExisting.assigneeAdapterOverrides, + executionPolicy: + issueData.executionPolicy !== undefined + ? issueData.executionPolicy + : receiptExisting.executionPolicy, + isolatedWorkspacesEnabled, + }, + tx, + ), + ); + } if (actorAgentId && actorRunId) { // Recheck under a run lock: a request admitted before Stop must not // commit a late Done after cancellation revoked its credentials. @@ -12368,7 +12384,7 @@ export function issueService(db: Db) { await completeTerminalCaseHandoffsForIssue(tx, { companyId: updated.companyId, issueId: updated.id, publications: activityPublications }); } - if (workspaceSelectionActor && updated.workspaceBindingRevision !== receiptExisting.workspaceBindingRevision) { + if (explicitWorkspaceFieldsChanged && workspaceSelectionActor && updated.workspaceBindingRevision !== receiptExisting.workspaceBindingRevision) { await executionWorkspaceService(db).assertTaskWorkspaceUpdateAccess({ task: updated, actor: workspaceSelectionActor, }, tx); diff --git a/server/src/services/project-move-workspace-reconciliation.ts b/server/src/services/project-move-workspace-reconciliation.ts new file mode 100644 index 00000000000..034f5a56843 --- /dev/null +++ b/server/src/services/project-move-workspace-reconciliation.ts @@ -0,0 +1,206 @@ +import { and, eq, ne, or, sql } from "drizzle-orm"; +import { + heartbeatRuns, + issues, + projects, + projectWorkspaces, + type Db, +} from "@paperclipai/db"; +import type { TaskWorkspaceIntent } from "@paperclipai/shared"; +import { HttpError } from "../errors.js"; +import { + defaultIssueExecutionWorkspaceSettingsForProject, + gateProjectExecutionWorkspacePolicy, + parseProjectExecutionWorkspacePolicy, +} from "./execution-workspace-policy.js"; +import { resolveProjectDefaultWorkspaceId } from "./project-default-workspace.js"; + +type DbTransaction = Parameters[0]>[0]; +type DbReader = Db | DbTransaction; + +export type ProjectDerivedWorkspaceBinding = { + projectWorkspaceId: string | null; + workspaceSelection: TaskWorkspaceIntent | null; + executionWorkspaceSettings: Record | null; +}; + +type ResolveSourceStrategyFn = ( + input: { + companyId: string; + assigneeAgentId?: string | null; + assigneeAdapterOverrides?: unknown; + executionWorkspaceSettings: unknown; + executionWorkspacePolicy: unknown; + sourceWorkspaceId: string; + typedSelection: boolean; + projectId: string; + executionPolicy?: unknown; + }, + reader: DbReader, +) => Promise; + +export async function isProjectDerivedWorkspaceBindingStale( + tx: DbReader, + input: { + companyId: string; + task: Pick< + typeof issues.$inferSelect, + | "projectId" + | "executionWorkspaceId" + | "projectWorkspaceId" + | "workspaceSelection" + | "workspacePendingSelection" + >; + previousProjectId?: string | null; + }, +): Promise { + const { task } = input; + if (task.executionWorkspaceId != null || task.workspacePendingSelection != null) { + return false; + } + const intent = task.workspaceSelection; + if (intent != null) { + if (intent.source !== "project" || intent.selection.kind !== "configured_source") { + return false; + } + const [source] = await tx + .select({ projectId: projectWorkspaces.projectId }) + .from(projectWorkspaces) + .where( + and( + eq(projectWorkspaces.id, intent.selection.projectWorkspaceId), + eq(projectWorkspaces.companyId, input.companyId), + ), + ) + .limit(1); + return (source?.projectId ?? null) !== (task.projectId ?? null); + } + // Without a typed workspaceSelection, only reconcile on an explicit project + // move when the stored projectWorkspaceId belonged to the previous project. + if (input.previousProjectId === undefined || !task.projectWorkspaceId) { + return false; + } + const [source] = await tx + .select({ projectId: projectWorkspaces.projectId }) + .from(projectWorkspaces) + .where( + and( + eq(projectWorkspaces.id, task.projectWorkspaceId), + eq(projectWorkspaces.companyId, input.companyId), + ), + ) + .limit(1); + if (!source) return false; + return source.projectId === input.previousProjectId && source.projectId !== (task.projectId ?? null); +} + +export async function deriveProjectDefaultWorkspaceBinding( + tx: DbReader, + input: { + companyId: string; + projectId: string | null; + assigneeAgentId?: string | null; + assigneeAdapterOverrides?: unknown; + executionPolicy?: unknown; + isolatedWorkspacesEnabled: boolean; + existingExecutionWorkspaceSettings?: Record | null; + allowTrustDenial?: boolean; + resolveSourceWorkspaceStrategy: ResolveSourceStrategyFn; + }, +): Promise { + if (!input.projectId) { + return { + projectWorkspaceId: null, + workspaceSelection: null, + executionWorkspaceSettings: null, + }; + } + const [project] = await tx + .select({ executionWorkspacePolicy: projects.executionWorkspacePolicy }) + .from(projects) + .where(and(eq(projects.id, input.projectId), eq(projects.companyId, input.companyId))) + .limit(1); + const projectPolicy = parseProjectExecutionWorkspacePolicy(project?.executionWorkspacePolicy); + const executionWorkspaceSettings = + input.existingExecutionWorkspaceSettings !== undefined + ? input.existingExecutionWorkspaceSettings + : (defaultIssueExecutionWorkspaceSettingsForProject( + gateProjectExecutionWorkspacePolicy(projectPolicy, input.isolatedWorkspacesEnabled), + ) as Record | null); + const projectWorkspaceId = await resolveProjectDefaultWorkspaceId(tx, { + companyId: input.companyId, + projectId: input.projectId, + policy: projectPolicy, + }); + let workspaceSelection: TaskWorkspaceIntent | null = null; + if (projectWorkspaceId && input.isolatedWorkspacesEnabled) { + try { + const sourceStrategy = await input.resolveSourceWorkspaceStrategy( + { + companyId: input.companyId, + assigneeAgentId: input.assigneeAgentId, + assigneeAdapterOverrides: input.assigneeAdapterOverrides, + executionWorkspaceSettings, + executionWorkspacePolicy: projectPolicy, + sourceWorkspaceId: projectWorkspaceId, + typedSelection: false, + projectId: input.projectId, + executionPolicy: input.executionPolicy, + }, + tx, + ); + if (sourceStrategy === "git_worktree") { + workspaceSelection = { + version: 1, + source: "project", + selection: { + kind: "configured_source", + projectWorkspaceId, + mode: "managed_isolated", + }, + }; + } + } catch (error) { + // On project moves, do not block moving a task to a project whose trust + // boundary currently denies the assigned agent; execution access still + // gates the run. + if (!input.allowTrustDenial || !(error instanceof HttpError) || error.status !== 403) { + throw error; + } + } + } + return { + projectWorkspaceId, + workspaceSelection, + executionWorkspaceSettings, + }; +} + +export async function hasActiveTaskWorkspaceRunHolder( + tx: DbReader, + input: { + companyId: string; + issueId: string; + executionRunId?: string | null; + excludeRunId?: string; + }, +): Promise { + const [holder] = await tx + .select({ id: heartbeatRuns.id }) + .from(heartbeatRuns) + .where( + and( + eq(heartbeatRuns.companyId, input.companyId), + eq(heartbeatRuns.status, "running"), + input.excludeRunId ? ne(heartbeatRuns.id, input.excludeRunId) : undefined, + or( + eq(heartbeatRuns.issueId, input.issueId), + eq(heartbeatRuns.nativeIssueId, input.issueId), + sql`coalesce(${heartbeatRuns.contextSnapshot}->>'issueId', ${heartbeatRuns.contextSnapshot}->>'taskId') = ${input.issueId}`, + input.executionRunId ? eq(heartbeatRuns.id, input.executionRunId) : undefined, + ), + ), + ) + .limit(1); + return Boolean(holder); +}