mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 14:20:12 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Hosted stacks move from a volume to volume-free storage, and Core must move every local workspace before the stack can move > - Some archived workspaces have no files left on the volume and no local repository that can rebuild them > - Both the offline and the online migration refuse these workspaces with `archived_git_source_unavailable` and `local_source_unsafe_or_missing`, so the stack stays on its volume forever > - Nothing can ever move those files, because the files do not exist > - This pull request records a "files gone" outcome for such a workspace and moves the record without a snapshot > - The benefit is that the stack can move, the record stays, and a later reopen tells the user plainly that the files were not available ## Linked Issues or Issue Description **What happened?** An archived workspace whose folder and whose possible git sources are all absent blocks the durable-data migration. The online pass reports `workspaces:archived_git_source_unavailable` and `workspaces:local_source_unsafe_or_missing` on every cycle. The offline maintenance pass fails. Two archived workspaces on one staging stack are in this state. **Expected behavior** A workspace whose files are provably gone does not block the move. The workspace record stays. Reopen says that its files were not available at migration time. A workspace whose files may still exist stays blocked. **Steps to reproduce** 1. Archive a local workspace. 2. Delete its folder (and any local repository it was made from). 3. Run the online or offline durable-data migration. 4. See the workspace deferred with the two codes on every pass. ## What Changed - `inspect` in `remote-workspace-migration.ts` marks a workspace as "files gone" only when all of these are true: the workspace is archived, it has no saved file reference (no `gitCacheRestoration` and no task-directory retention record), its folder does not exist (`ENOENT`, not a symlink or file), no retained restore point or archived git source exists, the restore point did not expire or fail validation, and every possible local source for its files is absent (the folder, the provider path, the private repository source, the managed project caches, a `file:` repository, and the project workspace folder). - For such a workspace, the two codes leave the blocker list. Every other blocker (writers, recovery, runtime leases, task binding) still applies. - `reserveMigration` then writes a remote authority with `snapshotId: null` and no location, a `workspaceFilesUnavailable` record with the old local path and time, and a `workspace.files_unavailable_at_migration` activity log entry in the same company-scoped transaction. No snapshot or operation journal is created. Cohorts, resumed journals, native continuity and recovery sources keep the workspace blocked. - `inspectRemoteWorkspacePersistence` (used by reopen) returns a plain message for this record: "This workspace's files were not available when it moved to new storage, so they cannot be restored. Continue the task in a new workspace." - `cleanupRemoteWorkspaceAllocation` treats such a record with no allocation as already clean. - The online pass counts these workspaces as moved and also as `workspacesFilesUnavailable`. The offline pass uses the same owner, so the rule is the same for both. - Stays blocked with the existing codes: a folder that exists but is a symlink or a file, an active or idle workspace with a missing folder, and an archived workspace whose repository or cache still exists on disk. ## Verification - `cd server && npx vitest run src/services/remote-workspace-migration.test.ts src/services/online-durable-data-migration.test.ts` (254 passed, embedded Postgres, real files). - `cd server && npx vitest run remote-workspace-lifecycle remote-workspace-migration-concurrency remote-workspace-cohort-migration` (pass). - Red/green: a fifth test moves an archived project task workspace whose managed repository cache is also gone (the archived Git check fails with a git command error there); it fails before and passes now. - Red/green: a fourth test keeps a workspace with a broken saved Git or task-directory reference blocked; it fails on the first commit and passes now. - Red/green: the two new "files are already gone" tests fail on `origin/master` (the migration throws the two codes) and pass with this change. The "files may still exist" guard test passes before and after. - `cd server && npx tsc --noEmit -p .` passes. ## Risks - The proof is conservative. If any possible source path exists, the workspace stays blocked, so some archived workspaces may still need another fix. - The move is not reversible by the migration. It deletes no bytes, because it acts only when nothing exists on disk. - A reopen of such a workspace now fails with the plain message. Before this change, the workspace could not move at all. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, agentic coding with tool use (shell, file edits, test runs) in Claude Code. ## 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
115 lines
8.3 KiB
TypeScript
115 lines
8.3 KiB
TypeScript
import { and, eq, sql } from "drizzle-orm";
|
|
import { environmentLeases, heartbeatRuns, executionWorkspaces, executionWorkspaceSnapshots, type Db } from "@paperclipai/db";
|
|
import { readRemoteWorkspaceAuthority, remoteWorkspaceRunReferenceSchema, type EnvironmentLease } from "@paperclipai/shared";
|
|
import { hasRemoteTerminationReceipt } from "./remote-execution-termination.js";
|
|
import { readWorkspaceFilesUnavailable, WORKSPACE_FILES_UNAVAILABLE_MESSAGE } from "./workspace-files-unavailable.js";
|
|
|
|
type Workspace = Pick<typeof executionWorkspaces.$inferSelect, "id" | "companyId" | "metadata">;
|
|
type Transaction = Parameters<Parameters<Db["transaction"]>[0]>[0];
|
|
export type DestroyRemoteWorkspaceLease = (input: {
|
|
companyId: string; workspaceId: string; leaseId: string; environmentId: string; providerLeaseId: string;
|
|
}) => Promise<EnvironmentLease | null>;
|
|
|
|
export type WorkspaceSourceLease = Pick<typeof environmentLeases.$inferSelect,
|
|
"id" | "companyId" | "heartbeatRunId" | "provider" | "providerLeaseId">;
|
|
|
|
export async function preparedRemoteWorkspaceSource(db: Db, lease: WorkspaceSourceLease) {
|
|
if (!lease.heartbeatRunId || !lease.provider || lease.provider === "local" || !lease.providerLeaseId) return null;
|
|
const [bound] = await db.select({ lease: environmentLeases, run: {
|
|
id: heartbeatRuns.id, runtimeMode: heartbeatRuns.runtimeMode,
|
|
controllerBootId: heartbeatRuns.controllerBootId,
|
|
issueId: sql<string | null>`coalesce(${heartbeatRuns.nativeIssueId}::text, ${heartbeatRuns.issueId}::text,
|
|
${heartbeatRuns.contextSnapshot}->>'issueId')`,
|
|
reference: sql<unknown>`${heartbeatRuns.runnerProfileJson}->'remoteWorkspace'`,
|
|
legacyReference: sql<unknown>`${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync'`,
|
|
} }).from(environmentLeases)
|
|
.innerJoin(heartbeatRuns, and(eq(heartbeatRuns.id, environmentLeases.heartbeatRunId),
|
|
eq(heartbeatRuns.companyId, environmentLeases.companyId)))
|
|
.where(and(eq(environmentLeases.id, lease.id), eq(environmentLeases.companyId, lease.companyId),
|
|
eq(environmentLeases.heartbeatRunId, lease.heartbeatRunId), eq(environmentLeases.provider, lease.provider),
|
|
eq(environmentLeases.providerLeaseId, lease.providerLeaseId),
|
|
sql`${heartbeatRuns.runnerProfileJson}->'remoteWorkspace'->>'state' = 'prepared'`)).limit(1);
|
|
if (!bound) return null;
|
|
const parsed = remoteWorkspaceRunReferenceSchema.safeParse(bound.run.reference);
|
|
if (!parsed.success || parsed.data.state !== "prepared" || bound.run.legacyReference != null) return null;
|
|
const [workspace] = await db.select().from(executionWorkspaces).where(and(
|
|
eq(executionWorkspaces.companyId, lease.companyId), eq(executionWorkspaces.id, parsed.data.workspaceId))).limit(1);
|
|
return matchPreparedRemoteWorkspaceSource(bound, workspace);
|
|
}
|
|
|
|
type PreparedSourceBinding = {
|
|
lease: Pick<typeof environmentLeases.$inferSelect, "id" | "companyId" | "heartbeatRunId" | "provider" | "providerLeaseId"
|
|
| "issueId" | "executionWorkspaceId" | "environmentId" | "metadata">;
|
|
run: { id: string; runtimeMode: string; controllerBootId: string | null; issueId: string | null;
|
|
reference: unknown; legacyReference: unknown };
|
|
};
|
|
|
|
/** Shared binding proof for single-source inspection and batched allocation fencing. */
|
|
export function matchPreparedRemoteWorkspaceSource<T extends PreparedSourceBinding>(bound: T,
|
|
workspace: Pick<typeof executionWorkspaces.$inferSelect, "id" | "companyId" | "sourceIssueId" | "mode" | "metadata"> | null | undefined) {
|
|
const parsed = remoteWorkspaceRunReferenceSchema.safeParse(bound.run.reference);
|
|
if (!parsed.success || parsed.data.state !== "prepared" || bound.run.legacyReference != null) return null;
|
|
const reference = parsed.data;
|
|
const issueId = bound.run.issueId;
|
|
if (typeof issueId !== "string" || bound.lease.issueId !== issueId || reference.leaseId !== bound.lease.id
|
|
|| reference.providerLeaseId !== bound.lease.providerLeaseId || reference.remoteCwd !== bound.lease.metadata?.remoteCwd
|
|
|| bound.lease.executionWorkspaceId && bound.lease.executionWorkspaceId !== reference.workspaceId) return null;
|
|
const authority = readRemoteWorkspaceAuthority(workspace?.metadata);
|
|
if (!workspace || workspace.companyId !== bound.lease.companyId || workspace.id !== reference.workspaceId
|
|
|| workspace.sourceIssueId !== issueId && workspace.mode !== "shared_workspace"
|
|
|| !authority || !authority.dirty || authority.writerRunId !== bound.run.id || authority.epoch !== reference.epoch
|
|
|| authority.snapshotId !== reference.snapshotId || !authority.location
|
|
|| authority.location.environmentId !== bound.lease.environmentId || authority.location.leaseId !== bound.lease.id
|
|
|| authority.location.providerLeaseId !== bound.lease.providerLeaseId || authority.location.remoteCwd !== reference.remoteCwd) return null;
|
|
return { ...bound, workspace, reference, issueId };
|
|
}
|
|
|
|
export async function inspectRemoteWorkspacePersistence(db: Db | Transaction, workspace: Workspace) {
|
|
const authority = readRemoteWorkspaceAuthority(workspace.metadata);
|
|
if (authority && !authority.snapshotId && readWorkspaceFilesUnavailable(workspace.metadata)) {
|
|
return { ready: false, reason: WORKSPACE_FILES_UNAVAILABLE_MESSAGE, authority, filesUnavailable: true };
|
|
}
|
|
if (!authority || authority.dirty || authority.writerRunId || !authority.snapshotId) {
|
|
return { ready: false, reason: "The workspace still has unsaved work or an unfinished writer.", authority };
|
|
}
|
|
const [snapshot] = await db.select({ id: executionWorkspaceSnapshots.id }).from(executionWorkspaceSnapshots).where(and(
|
|
eq(executionWorkspaceSnapshots.companyId, workspace.companyId), eq(executionWorkspaceSnapshots.executionWorkspaceId, workspace.id),
|
|
eq(executionWorkspaceSnapshots.id, authority.snapshotId), eq(executionWorkspaceSnapshots.status, "committed"),
|
|
));
|
|
return { ready: Boolean(snapshot), reason: snapshot ? null : "The saved workspace is unavailable. Its remote files were retained.", authority };
|
|
}
|
|
|
|
/** Called within the workspace lifecycle fence; the saved workspace remains durable. */
|
|
export async function cleanupRemoteWorkspaceAllocation(input: {
|
|
db: Db; workspace: Workspace; destroyLease: DestroyRemoteWorkspaceLease;
|
|
}) {
|
|
const [workspace] = await input.db.select().from(executionWorkspaces).where(and(
|
|
eq(executionWorkspaces.companyId, input.workspace.companyId), eq(executionWorkspaces.id, input.workspace.id),
|
|
));
|
|
if (!workspace || !["archived", "cleanup_failed"].includes(workspace.status)) throw new Error("remote_workspace_cleanup_binding_changed");
|
|
const persistence = await inspectRemoteWorkspacePersistence(input.db, workspace);
|
|
if ("filesUnavailable" in persistence && !persistence.authority?.location && !persistence.authority?.writerRunId) {
|
|
return { cleaned: true, warnings: [] as string[] };
|
|
}
|
|
if (!persistence.ready || !persistence.authority) throw new Error(persistence.reason ?? "remote_workspace_saved_state_required");
|
|
const location = persistence.authority.location;
|
|
if (location) {
|
|
const destroyed = (lease: Parameters<typeof hasRemoteTerminationReceipt>[0] | null | undefined) => Boolean(lease && hasRemoteTerminationReceipt(lease)
|
|
&& (lease.metadata?.remoteExecutionTermination as { state?: unknown } | undefined)?.state === "destroyed");
|
|
const [stored] = await input.db.select().from(environmentLeases).where(and(
|
|
eq(environmentLeases.companyId, workspace.companyId), eq(environmentLeases.id, location.leaseId),
|
|
eq(environmentLeases.environmentId, location.environmentId), eq(environmentLeases.providerLeaseId, location.providerLeaseId),
|
|
));
|
|
if (!destroyed(stored)) {
|
|
const released = await input.destroyLease({ companyId: workspace.companyId, workspaceId: workspace.id,
|
|
leaseId: location.leaseId, environmentId: location.environmentId, providerLeaseId: location.providerLeaseId });
|
|
if (!destroyed(released)) throw new Error("remote_workspace_cleanup_unconfirmed");
|
|
}
|
|
await input.db.update(executionWorkspaces)
|
|
.set({ metadata: sql`jsonb_set(${executionWorkspaces.metadata}, '{remoteWorkspace,location}', 'null'::jsonb)`, updatedAt: new Date() })
|
|
.where(and(eq(executionWorkspaces.companyId, workspace.companyId), eq(executionWorkspaces.id, workspace.id),
|
|
sql`${executionWorkspaces.metadata}->'remoteWorkspace'->'location' = ${JSON.stringify(location)}::jsonb`));
|
|
}
|
|
return { cleaned: true, warnings: [] as string[] };
|
|
}
|