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

+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,