fix(workspaces): reconcile project-derived workspace bindings when a task moves projects (#23293)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - When a task is created in a project without explicit workspace
overrides, Paperclip derives `projectWorkspaceId`,
`executionWorkspaceSettings`, and a project-derived `workspaceSelection`
(`source: "project"`).
> - Moving that unbound task to a different project via `issues.update`
left the old project's `projectWorkspaceId` and `workspaceSelection`
behind.
> - Subsequent runs kept resolving back to the old project's workspace
and storage owner, causing repeated workspace validation or
storage-incompatibility failures even after the user moved the task to a
compatible project.
> - This pull request re-derives project-derived workspace bindings when
an unbound task moves projects, and reconciles already-moved unbound
tasks with stale `source: "project"` bindings at run admission while
preserving explicit workspace selections and bound execution workspaces.
> - The benefit is that moving an unbound task to a compatible project
immediately lets it run on the new project's workspace without hidden
stale-workspace failures.

## Linked Issues or Issue Description

Related: #17552, #22849.

**What happened?**

When a task was created in a project, `issues.create` automatically set
`projectWorkspaceId` and `workspaceSelection` with `source: "project"`.
If the task failed before binding an execution workspace
(`executionWorkspaceId === null`) and the user moved the task to a
different project (for example from a Core-storage project to a
plugin-storage project), `issues.update` updated `projectId` but left
`projectWorkspaceId` and `workspaceSelection` pointing to the old
project's workspace. Every subsequent run still resolved the old
project's workspace and storage policy and failed.

**Expected behavior**

- Moving an unbound task whose workspace binding is project-derived
(`source: "project"`, or a legacy `projectWorkspaceId` belonging to the
previous project with no `workspaceSelection`) re-derives
`projectWorkspaceId`, `workspaceSelection`, and
`executionWorkspaceSettings` from the new project (or clears them when
moving to no project or a sourceless project).
- Explicit workspace selections (`source !== "project"`), bound
execution workspaces (`executionWorkspaceId != null`), pending workspace
selections, and tasks with an active running run or pending workspace
recovery keep their current workspace binding.
- Tasks already moved on an older release with a stale `source:
"project"` binding pointing to a different project are reconciled at run
admission before workspace preparation.

**Steps to reproduce**

1. Create a Core-storage project A with a Git workspace and a
plugin-storage project B with a Git workspace.
2. Create an isolated task in project A (so `issues.create` sets
`workspaceSelection.source = "project"`).
3. Move the task to project B via `issueService.update(id, { projectId:
projectB.id })`.
4. Before this fix, `projectWorkspaceId` and
`workspaceSelection.selection.projectWorkspaceId` still point to project
A's workspace.

**Paperclip version or commit**

Reproduced against `origin/master` at `2d764bebc6ed`.

**Deployment mode**

Self-hosted / Cloud server. Verified locally on macOS arm64 with
embedded PostgreSQL.

## What Changed

- `server/src/services/project-move-workspace-reconciliation.ts`: add
focused helpers (`isProjectDerivedWorkspaceBindingStale`,
`deriveProjectDefaultWorkspaceBinding`,
`hasActiveTaskWorkspaceRunHolder`) shared between issue updates and run
admission.
- `server/src/services/execution-workspaces.ts`: add
`reconcileProjectWorkspaceForProjectMove` (used by `issues.update`) and
`reconcileStaleProjectWorkspaceAtAdmission` (used at run admission for
already-moved tasks with stale `source: "project"` bindings). Keeping
the shared reconciliation helpers in a sibling module avoids growing
`execution-workspaces.ts` and `issues.ts` unnecessarily.
- `server/src/services/issues.ts`: invoke
`reconcileProjectWorkspaceForProjectMove` inside `issues.update` after
`changesPrivacy` when `projectId` changes and no explicit workspace
fields were supplied.
- `server/src/services/heartbeat.ts`: invoke
`reconcileStaleProjectWorkspaceAtAdmission` alongside
`releaseAncestorWorkspaceBindingAtAdmission` at run admission, marking
`workspaceSelectionChanged = true` when reconciled.
- `server/src/__tests__/issue-project-move-workspace.test.ts`: add
red-green database regressions for moving to another project, moving to
a sourceless/null project, preserving explicit selections, preserving
bound `executionWorkspaceId`, deferring mid-run moves, and reconciling
already-moved tasks at admission.
- `server/src/__tests__/agent-project-access.test.ts`: use `source:
"explicit"` for the explicitly-retained-source denial test and add a
companion test verifying `source: "project"` re-derives on project move.

## Verification

- **Red (before production edits)**:
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-project-move-workspace.test.ts` failed on
`re-derives a project-derived workspace when moving an unbound task to
another project` and `clears a project-derived workspace when moving to
no project or a sourceless project` because `projectWorkspaceId` and
`workspaceSelection` stayed pinned to the old project.
- **Green (after production edits)**:
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-project-move-workspace.test.ts
src/__tests__/agent-project-access.test.ts` — 20/20 passed.
  - `pnpm --filter @paperclipai/server typecheck` — passed.
  - `pnpm --filter @paperclipai/server build` — passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/services/heartbeat/workspace-preparation.test.ts -t "names
incompatible Core project storage|rejects Core Git worktree
preparation"` — 2/2 passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/services/task-interruption-presentation.test.ts` — 82/82 passed.
- `pnpm verify --explain` selected 1978/2333 files due to touching
central server services; required GitHub Actions CI supplies the broad
suite coverage.
- Live deployment and recovery of previously affected tasks on hosted
instances are outside this PR's scope.

## Risks

- Low risk. Reconciliation is gated to unbound tasks
(`executionWorkspaceId == null`, `workspacePendingSelection == null`)
with no active run holder or pending workspace recovery, and never
alters explicit (`source !== "project"`) workspace selections or bound
files.
- Moving a task to a project whose trust boundary currently denies the
assigned agent will not fail the move; execution access remains enforced
at run admission.

## Model Used

- Google Gemini (Antigravity agentic coding assistant) with tool use,
shell execution, and local test verification. Exact deployment model ID
and context window are not exposed to the session.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
Dotta authored and GitHub committed 2026-11-30 15:44:28 +00:00
1 parent 2d764bebc6
commit e7ed0c2f93
6 files changed
+865 -45

No files matched your search

@@ -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,
@@ -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<string, unknown>).storageProviderPluginId,
trustPreset: "low_trust_review",
authorizationPolicy: {
trustBoundary: {
mode: "low_trust_review",
companyId: f.companyId,
projectIds: [f.pluginProject.id],
},
},
} as Record<string, unknown>,
}).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);
});
});
+90 -14
View File
@@ -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,
+3 -1
View File
@@ -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;
+44 -28
View File
@@ -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<string, unknown> | 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);
@@ -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<Parameters<Db["transaction"]>[0]>[0];
type DbReader = Db | DbTransaction;
export type ProjectDerivedWorkspaceBinding = {
projectWorkspaceId: string | null;
workspaceSelection: TaskWorkspaceIntent | null;
executionWorkspaceSettings: Record<string, unknown> | 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<string>;
export async function isProjectDerivedWorkspaceBindingStale(
tx: DbReader,
input: {
companyId: string;
task: Pick<
typeof issues.$inferSelect,
| "projectId"
| "executionWorkspaceId"
| "projectWorkspaceId"
| "workspaceSelection"
| "workspacePendingSelection"
>;
previousProjectId?: string | null;
},
): Promise<boolean> {
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<string, unknown> | null;
allowTrustDenial?: boolean;
resolveSourceWorkspaceStrategy: ResolveSourceStrategyFn;
},
): Promise<ProjectDerivedWorkspaceBinding> {
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<string, unknown> | 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<boolean> {
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);
}