mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 14:20:12 +01:00
fix(workspaces): move an archived workspace whose files are already gone (#22697)
## 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>
This commit is contained in:
1 parent
b908678ea3
commit
eddaf14504
6 files changed
+215
-11
No files matched your search
@@ -407,6 +407,15 @@ describe("online durable-data migration pass", () => {
|
||||
expect(migrateWorkspace.mock.calls[0]).not.toEqual([expect.objectContaining({ writersStopped: expect.anything() })]);
|
||||
});
|
||||
|
||||
it("counts a workspace moved without files as moved and names it separately", async () => {
|
||||
const migrateWorkspace = vi.fn(async (input: { workspaceId: string }) => ({ alreadyMigrated: true, reasons: [],
|
||||
...(input.workspaceId === "w2" ? { filesUnavailable: true } : {}) }));
|
||||
const fixture = owners({ localWorkspaces: async () => [workspace(1), workspace(2)], migrateWorkspace });
|
||||
const result = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners);
|
||||
expect(result.counts).toMatchObject({ workspaces: 2, workspacesFilesUnavailable: 1 });
|
||||
expect(Object.keys(result.deferred).filter(key => key.startsWith("workspaces:"))).toEqual([]);
|
||||
});
|
||||
|
||||
it("defers busy and unsupported workspaces with their owner reasons and does not force them", async () => {
|
||||
const reasons: Record<string, string[]> = { w1: ["active_execution"], w2: ["task_binding_required", "workspace_provider_unsupported"], w3: [] };
|
||||
const migrateWorkspace = vi.fn(async () => ({ alreadyMigrated: true, reasons: [] }));
|
||||
|
||||
@@ -45,7 +45,7 @@ type Owners = {
|
||||
localWorkspaces: typeof listLocalWorkspaces;
|
||||
inventoryWorkspace: (db: Db, input: { companyId: string; workspaceId: string }) => Promise<{ reasons: string[]; sourceScopeUnproven?: string; details?: string[] }>;
|
||||
migrateWorkspace: (input: { db: Db; storage: StorageService; companyId: string; workspaceId: string; apply: true;
|
||||
signal: AbortSignal; sourceLockWaitMs: number }) => Promise<{ alreadyMigrated: boolean; reasons: string[] }>;
|
||||
signal: AbortSignal; sourceLockWaitMs: number }) => Promise<{ alreadyMigrated: boolean; reasons: string[]; filesUnavailable?: boolean }>;
|
||||
nativeHarnessBackups: typeof prestageNativeHarnessBackups;
|
||||
nativeControllers: typeof prestageNativeControllers;
|
||||
runEvidencePage: typeof migrateRunEvidencePage;
|
||||
@@ -267,6 +267,7 @@ async function migrate(db: Db, input: { budgetMs: number; now?: () => number },
|
||||
workspaceOwner = tracked;
|
||||
const result = await untilAborted(work, signal);
|
||||
reasons = result.alreadyMigrated ? [] : result.reasons.length ? result.reasons : ["not_migrated"];
|
||||
if (result.filesUnavailable) add(counts, "workspacesFilesUnavailable");
|
||||
}
|
||||
} catch (error) {
|
||||
if (signal.aborted) throw error;
|
||||
|
||||
@@ -2,6 +2,7 @@ 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];
|
||||
@@ -65,6 +66,9 @@ export function matchPreparedRemoteWorkspaceSource<T extends PreparedSourceBindi
|
||||
|
||||
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 };
|
||||
}
|
||||
@@ -84,6 +88,9 @@ export async function cleanupRemoteWorkspaceAllocation(input: {
|
||||
));
|
||||
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) {
|
||||
|
||||
@@ -40,6 +40,8 @@ import { inspectOnlineWorkspaceSource } from "./online-workspace-source.js";
|
||||
import { tryLockNativeWorkspaceFinalization } from "./native-runtime/native-workspace-finalization-ownership.js";
|
||||
import { readMigratedLegacyWorkspaceSource } from "./legacy-workspace-recovery-migration.js";
|
||||
import { nativeSha256 } from "./native-runtime/canonical.js";
|
||||
import { cleanupRemoteWorkspaceAllocation, inspectRemoteWorkspacePersistence } from "./remote-workspace-lifecycle.js";
|
||||
import { WORKSPACE_FILES_UNAVAILABLE_MESSAGE } from "./workspace-files-unavailable.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const git = async (cwd: string, ...args: string[]) => (await execute("git", ["-C", cwd, ...args], { env: { ...process.env,
|
||||
@@ -81,6 +83,99 @@ describe.skipIf(!support.supported)("remote workspace migration", () => {
|
||||
return { companyId, workspaceId, issueId: issue!.id, cwd };
|
||||
}
|
||||
async function workspace(id: string) { return (await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, id)))[0]!; }
|
||||
async function archivedGitWorkspaceWithoutFiles() {
|
||||
const f = await seed(), repository = path.join(root, "origin-repository"); await fs.mkdir(repository);
|
||||
await db.update(executionWorkspaces).set({ status: "archived", closedAt: new Date(), providerType: "git_worktree",
|
||||
strategyType: "git_worktree", repoUrl: pathToFileURL(repository).href, branchName: "task-branch",
|
||||
metadata: { retainedNote: "keep", gitBranchOwnershipVersion: 1 } }).where(eq(executionWorkspaces.id, f.workspaceId));
|
||||
await fs.rm(f.cwd, { recursive: true });
|
||||
return { ...f, repository };
|
||||
}
|
||||
async function expectFilesUnavailable(f: { companyId: string; workspaceId: string; cwd: string }) {
|
||||
const row = await workspace(f.workspaceId);
|
||||
expect(row).toMatchObject({ status: "archived", providerType: "cloud_sandbox", providerRef: null, cwd: `/workspaces/${f.workspaceId}` });
|
||||
expect(row.metadata).toMatchObject({ retainedNote: "keep", workspaceFilesUnavailable: { reason: "files_missing_at_migration", localPath: f.cwd } });
|
||||
expect(readRemoteWorkspaceAuthority(row.metadata)).toMatchObject({ snapshotId: null, location: null, writerRunId: null, dirty: false });
|
||||
expect(await db.select().from(executionWorkspaceSnapshots).where(eq(executionWorkspaceSnapshots.executionWorkspaceId, f.workspaceId))).toHaveLength(0);
|
||||
expect(await db.select().from(activityLog).where(and(eq(activityLog.companyId, f.companyId),
|
||||
eq(activityLog.action, "workspace.files_unavailable_at_migration")))).toEqual([expect.objectContaining({
|
||||
entityType: "execution_workspace", entityId: f.workspaceId, details: expect.objectContaining({ localPath: f.cwd }) })]);
|
||||
expect(await inspectRemoteWorkspacePersistence(db, row)).toMatchObject({ ready: false, reason: WORKSPACE_FILES_UNAVAILABLE_MESSAGE });
|
||||
expect(await cleanupRemoteWorkspaceAllocation({ db, workspace: row, destroyLease: async () => { throw new Error("no allocation"); } }))
|
||||
.toEqual({ cleaned: true, warnings: [] });
|
||||
}
|
||||
it("moves an archived workspace whose files are already gone online without a snapshot", async () => {
|
||||
const f = await archivedGitWorkspaceWithoutFiles();
|
||||
expect((await inventoryRemoteWorkspaceMigration(db, f)).reasons)
|
||||
.toEqual(expect.arrayContaining(["archived_git_source_unavailable", "local_source_unsafe_or_missing"]));
|
||||
await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true }))
|
||||
.rejects.toThrow(/archived_git_source_unavailable.*local_source_unsafe_or_missing|local_source_unsafe_or_missing.*archived_git_source_unavailable/);
|
||||
await fs.rm(f.repository, { recursive: true });
|
||||
expect(await inventoryRemoteWorkspaceMigration(db, f)).toMatchObject({ eligible: true, filesUnavailable: true, reasons: [] });
|
||||
expect(await migrateRemoteWorkspace({ db, storage, ...f, apply: true })).toMatchObject({ applied: true, filesUnavailable: true });
|
||||
await expectFilesUnavailable(f);
|
||||
expect(await migrateRemoteWorkspace({ db, storage, ...f, apply: true })).toMatchObject({ applied: true, replayed: true });
|
||||
expect(await db.select().from(activityLog).where(eq(activityLog.action, "workspace.files_unavailable_at_migration"))).toHaveLength(1);
|
||||
});
|
||||
it("moves an archived workspace whose files are already gone during offline migration", async () => {
|
||||
vi.stubEnv("PAPERCLIP_EPHEMERAL_MIGRATION", "true");
|
||||
const f = await seed();
|
||||
await db.update(executionWorkspaces).set({ status: "archived", closedAt: new Date() }).where(eq(executionWorkspaces.id, f.workspaceId));
|
||||
await fs.rm(f.cwd, { recursive: true });
|
||||
expect(await migrateWorkspaceTrees(db, { storage, signal: new AbortController().signal, phase: () => {} })).toBe(1);
|
||||
await expectFilesUnavailable(f);
|
||||
});
|
||||
it("moves an archived project task workspace whose repository cache is gone too", async () => {
|
||||
vi.stubEnv("PAPERCLIP_HOME", await fs.realpath(root));
|
||||
const f = await seed(), [project] = await db.insert(projects).values({ companyId: f.companyId, name: "Gone project" }).returning();
|
||||
const managed = resolveManagedProjectWorkspaceDir({ companyId: f.companyId, projectId: project!.id, repoName: "repo" });
|
||||
const cwd = path.join(managed, ".paperclip", "worktrees", "task-branch");
|
||||
await db.update(executionWorkspaces).set({ status: "archived", closedAt: new Date(), providerType: "git_worktree", strategyType: "git_worktree",
|
||||
projectId: project!.id, repoUrl: "https://example.test/acme/repo.git", branchName: "task-branch", cwd, providerRef: cwd,
|
||||
metadata: { retainedNote: "keep", gitBranchOwnershipVersion: 1, createdByRuntime: true } }).where(eq(executionWorkspaces.id, f.workspaceId));
|
||||
await fs.rm(f.cwd, { recursive: true });
|
||||
expect(await inventoryRemoteWorkspaceMigration(db, f)).toMatchObject({ eligible: true, filesUnavailable: true, reasons: [] });
|
||||
expect(await migrateRemoteWorkspace({ db, storage, ...f, apply: true })).toMatchObject({ applied: true, filesUnavailable: true });
|
||||
await expectFilesUnavailable({ ...f, cwd });
|
||||
});
|
||||
it("keeps an archived workspace blocked while its repository at a plain local path still exists", async () => {
|
||||
const f = await archivedGitWorkspaceWithoutFiles();
|
||||
await db.update(executionWorkspaces).set({ repoUrl: f.repository }).where(eq(executionWorkspaces.id, f.workspaceId));
|
||||
const inventory = await inventoryRemoteWorkspaceMigration(db, f);
|
||||
expect(inventory).toMatchObject({ eligible: false });
|
||||
expect(inventory).not.toHaveProperty("filesUnavailable");
|
||||
await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).rejects.toThrow("local_source_unsafe_or_missing");
|
||||
expect(readRemoteWorkspaceAuthority((await workspace(f.workspaceId)).metadata)).toBeNull();
|
||||
await fs.rm(f.repository, { recursive: true });
|
||||
expect(await inventoryRemoteWorkspaceMigration(db, f)).toMatchObject({ eligible: true, filesUnavailable: true, reasons: [] });
|
||||
});
|
||||
it("keeps an archived workspace blocked when it still has a saved file reference", async () => {
|
||||
const f = await archivedGitWorkspaceWithoutFiles(); await fs.rm(f.repository, { recursive: true });
|
||||
for (const metadata of [{ gitCacheRestoration: { schema: "paperclip.git-cache-restoration.v2", broken: true } },
|
||||
{ isolatedTaskDirectoryRetention: { schema: "unknown" } }]) {
|
||||
await db.update(executionWorkspaces).set({ metadata: { retainedNote: "keep", gitBranchOwnershipVersion: 1, ...metadata } })
|
||||
.where(eq(executionWorkspaces.id, f.workspaceId));
|
||||
const inventory = await inventoryRemoteWorkspaceMigration(db, f);
|
||||
expect(inventory).toMatchObject({ eligible: false });
|
||||
expect(inventory).not.toHaveProperty("filesUnavailable");
|
||||
expect(inventory.reasons).toContain("local_source_unsafe_or_missing");
|
||||
await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).rejects.toThrow("local_source_unsafe_or_missing");
|
||||
}
|
||||
expect(readRemoteWorkspaceAuthority((await workspace(f.workspaceId)).metadata)).toBeNull();
|
||||
});
|
||||
it("keeps workspaces blocked when their files may still exist", async () => {
|
||||
const f = await seed(), elsewhere = path.join(root, "elsewhere");
|
||||
await db.update(executionWorkspaces).set({ status: "archived", closedAt: new Date() }).where(eq(executionWorkspaces.id, f.workspaceId));
|
||||
await fs.rename(f.cwd, elsewhere); await fs.symlink(elsewhere, f.cwd);
|
||||
expect(await inventoryRemoteWorkspaceMigration(db, f)).toMatchObject({ eligible: false, reasons: ["local_source_unsafe_or_missing"] });
|
||||
await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).rejects.toThrow("local_source_unsafe_or_missing");
|
||||
await fs.rm(f.cwd);
|
||||
await db.update(executionWorkspaces).set({ status: "idle", closedAt: null }).where(eq(executionWorkspaces.id, f.workspaceId));
|
||||
expect(await inventoryRemoteWorkspaceMigration(db, f)).toMatchObject({ eligible: false, reasons: ["local_source_unsafe_or_missing"] });
|
||||
expect(readRemoteWorkspaceAuthority((await workspace(f.workspaceId)).metadata)).toBeNull();
|
||||
expect(await db.select().from(activityLog).where(eq(activityLog.action, "workspace.files_unavailable_at_migration"))).toHaveLength(0);
|
||||
expect(await fs.readFile(path.join(elsewhere, "saved.txt"), "utf8")).toBe("original saved work\n");
|
||||
});
|
||||
it("keeps provider-owned Runner task paths out of offline workspace migration", async () => {
|
||||
vi.stubEnv("PAPERCLIP_EPHEMERAL_MIGRATION", "true");
|
||||
const companyId = randomUUID(), agentId = randomUUID(), environmentId = randomUUID();
|
||||
|
||||
@@ -6,7 +6,7 @@ import path from "node:path";
|
||||
import { and, eq, inArray, ne, or, sql } from "drizzle-orm";
|
||||
import {
|
||||
companies, environmentLeases, executionWorkspaceRepositories, executionWorkspaceRuntimeLeases, executionWorkspaceSnapshots, executionWorkspaces,
|
||||
heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, projects, workspaceOperations, workspaceRuntimeServices, type Db,
|
||||
heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, projects, projectWorkspaces, workspaceOperations, workspaceRuntimeServices, type Db,
|
||||
} from "@paperclipai/db";
|
||||
import { readRemoteWorkspaceAuthority, remoteWorkspaceSourceSchema, type RemoteWorkspaceAuthority, type RemoteWorkspaceSource } from "@paperclipai/shared";
|
||||
import { offlineMigrationExecutionWhere } from "./offline-migration-execution.js";
|
||||
@@ -29,7 +29,11 @@ import { explainOnlineWorkspaceSource, inspectOnlineWorkspaceSource, requiresOnl
|
||||
import { withWorkspaceSourceLocks, withIndependentWorkspaceSourceLocks, IsolatedRepositorySourceBusy } from "./workspace-source-lock.js";
|
||||
import { inspectOnlineLegacyWorkspaceRecoverySource, inspectOnlineLegacyWorkspaceRecoveryHold, isTaskDispositionRecovery, lockOnlineLegacyWorkspaceRecoverySources, ONLINE_LEGACY_WORKSPACE_PRESERVATION, type OnlineLegacyWorkspaceRecoveryHold } from "./online-legacy-workspace-recovery.js";
|
||||
import { inspectNativeWorkspaceMigration, nativeWorkspaceMigrationMarker } from "./native-runtime/native-workspace-migration.js";
|
||||
import { readGitCacheExpiration, GIT_CACHE_EXPIRATION_REASON } from "./git-workspace-restoration.js";
|
||||
import { readGitCacheExpiration, GIT_CACHE_EXPIRATION_REASON, GIT_CACHE_RESTORATION_KEY, managedSourcePaths } from "./git-workspace-restoration.js";
|
||||
import { TASK_DIRECTORY_RETENTION_KEY } from "./isolated-task-directory-snapshot.js";
|
||||
import { recordedIsolatedRemoteSource } from "./isolated-remote-workspace-source.js";
|
||||
import { localRepositoryPath } from "./local-repository-path.js";
|
||||
import { workspaceFilesUnavailableRecord, WORKSPACE_FILES_UNAVAILABLE_KEY } from "./workspace-files-unavailable.js";
|
||||
|
||||
const SCHEMA = "paperclip.remote-workspace-migration.v1";
|
||||
const SUPERSESSION = "paperclip.remote-workspace-migration-supersession.v1";
|
||||
@@ -115,6 +119,37 @@ function recoveryState(recovery: { kind: string; cause: string; evidence: Record
|
||||
return workspaceExportCauses.includes(recovery.cause) ? `${recovery.kind}_export_cause` : `${recovery.kind}_file_evidence`;
|
||||
}
|
||||
|
||||
const FILES_GONE_REASONS = new Set(["archived_git_source_unavailable", "local_source_unsafe_or_missing"]);
|
||||
|
||||
async function pathAbsent(candidate: string) {
|
||||
if (!path.isAbsolute(candidate)) return false;
|
||||
return !await fs.lstat(candidate).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code === "ENOENT") return null;
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
|
||||
const SAVED_FILE_REFERENCE_KEYS = [GIT_CACHE_RESTORATION_KEY, TASK_DIRECTORY_RETENTION_KEY];
|
||||
|
||||
async function workspaceFilesProvenGone(db: ReadDb, workspace: Workspace) {
|
||||
if (SAVED_FILE_REFERENCE_KEYS.some(key => workspace.metadata?.[key] != null)) return false;
|
||||
const candidates = [workspace.cwd, workspace.providerRef].filter((value): value is string => typeof value === "string");
|
||||
if (workspace.repoUrl) {
|
||||
try {
|
||||
const isolated = recordedIsolatedRemoteSource(workspace);
|
||||
if (isolated) candidates.push(isolated);
|
||||
const local = localRepositoryPath(workspace.repoUrl);
|
||||
if (local) candidates.push(local);
|
||||
} catch { return false; }
|
||||
candidates.push(...managedSourcePaths(workspace));
|
||||
const [projectWorkspace] = workspace.projectWorkspaceId ? await db.select({ cwd: projectWorkspaces.cwd }).from(projectWorkspaces)
|
||||
.where(and(eq(projectWorkspaces.companyId, workspace.companyId), eq(projectWorkspaces.id, workspace.projectWorkspaceId))) : [];
|
||||
if (projectWorkspace?.cwd) candidates.push(projectWorkspace.cwd);
|
||||
}
|
||||
for (const candidate of new Set(candidates)) if (!await pathAbsent(candidate)) return false;
|
||||
return candidates.length > 0;
|
||||
}
|
||||
|
||||
async function inspect(db: ReadDb, input: { companyId: string; workspaceId: string; operationId?: string; writersStopped?: boolean; onlineSource?: OnlineWorkspaceSource; onlineSourceUnproven?: boolean }, cohort?: WorkspaceMigrationCohort) {
|
||||
const [workspace] = await db.select().from(executionWorkspaces).where(and(eq(executionWorkspaces.companyId, input.companyId), eq(executionWorkspaces.id, input.workspaceId)));
|
||||
if (!workspace) throw new Error("remote_workspace_migration_workspace_missing");
|
||||
@@ -126,7 +161,7 @@ async function inspect(db: ReadDb, input: { companyId: string; workspaceId: stri
|
||||
reasons.push(reason);
|
||||
details.push(`${reason}:${/^[a-z_]{1,60}$/.test(state) ? state : "unrecognized"}`);
|
||||
};
|
||||
if (authority) return { workspace, reasons, details, settledFinalizationRunIds: [] as string[], authority, marker, source: authority.source, issueBinding: null, retainedDirectory: null, archivedGitSource: null, legacyRecoverySources: [] as LegacyWorkspaceRecoverySource[], finalizedRecoveryHolds: [] as FinalizedWorkspaceRecoveryHold[], onlineRecoveryHolds: [] as OnlineRecoveryHold[], archivedRepositoryIntents: [] as RepositoryRequest[] };
|
||||
if (authority) return { workspace, reasons, details, filesGone: false, settledFinalizationRunIds: [] as string[], authority, marker, source: authority.source, issueBinding: null, retainedDirectory: null, archivedGitSource: null, legacyRecoverySources: [] as LegacyWorkspaceRecoverySource[], finalizedRecoveryHolds: [] as FinalizedWorkspaceRecoveryHold[], onlineRecoveryHolds: [] as OnlineRecoveryHold[], archivedRepositoryIntents: [] as RepositoryRequest[] };
|
||||
if (input.writersStopped) reasons.push(...await offlineWorkspaceMigrationBlockers(db));
|
||||
if (input.onlineSourceUnproven) reasons.push("online_workspace_source_scope_unproven");
|
||||
if (input.onlineSource) {
|
||||
@@ -147,6 +182,7 @@ async function inspect(db: ReadDb, input: { companyId: string; workspaceId: stri
|
||||
const cwd = workspace.cwd ?? workspace.providerRef;
|
||||
let retainedDirectory = null as ReturnType<typeof readTaskDirectoryRetention>;
|
||||
let archivedGitSource: ArchivedGitMigrationSource | null = null;
|
||||
let filesGone = false;
|
||||
if (!cwd || !path.isAbsolute(cwd)) reasons.push("local_source_missing");
|
||||
else {
|
||||
const entry = await fs.lstat(cwd).catch((error: NodeJS.ErrnoException) => {
|
||||
@@ -165,10 +201,15 @@ async function inspect(db: ReadDb, input: { companyId: string; workspaceId: stri
|
||||
}
|
||||
if (!entry && !retainedDirectory && (workspace.status === "archived" || input.writersStopped)) {
|
||||
try { archivedGitSource = await inspectArchivedGitMigrationSource(db, workspace, { allowActiveRetainedBranch: input.writersStopped, operationId: allowedOperation }); }
|
||||
catch (error) { reasons.push(error instanceof Error && error.message === "remote_workspace_migration_restore_point_expired"
|
||||
? "restore_point_expired" : "archived_git_source_unavailable"); }
|
||||
catch (error) {
|
||||
reasons.push(error instanceof Error && error.message === "remote_workspace_migration_restore_point_expired"
|
||||
? "restore_point_expired" : "archived_git_source_unavailable");
|
||||
}
|
||||
}
|
||||
if (!retainedDirectory && !archivedGitSource && (!entry?.isDirectory() || entry.isSymbolicLink())) reasons.push("local_source_unsafe_or_missing");
|
||||
filesGone = !entry && !retainedDirectory && !archivedGitSource && workspace.status === "archived"
|
||||
&& !reasons.includes("restore_point_expired") && !reasons.includes("restore_point_invalid")
|
||||
&& await workspaceFilesProvenGone(db, workspace);
|
||||
if (entry?.isDirectory() && !entry.isSymbolicLink()) reasons.push(...await workspaceMigrationLayoutBlockers(db, workspace, input.writersStopped, input.onlineSource));
|
||||
}
|
||||
const [issue] = workspace.sourceIssueId ? await db.select().from(issues).where(and(eq(issues.companyId, workspace.companyId), eq(issues.id, workspace.sourceIssueId))) : [];
|
||||
@@ -361,7 +402,7 @@ async function inspect(db: ReadDb, input: { companyId: string; workspaceId: stri
|
||||
const materialized = repositories.filter(repository => repository.state === "ready");
|
||||
if (materialized.length) source.repositories = materialized.map(repository => ({ id: repository.id, relativePath: repository.relativePath,
|
||||
repoUrl: repository.repoUrl, ref: repository.requestedRef, ...(repository.pinnedCommit ? { pinnedCommit: repository.pinnedCommit } : {}) }));
|
||||
return { workspace, reasons: [...new Set(reasons)], details: [...new Set(details)].sort(), settledFinalizationRunIds: settledFinalizationRunIds.sort(), authority, marker, source, issueBinding: issue?.executionWorkspaceId ?? null, retainedDirectory, archivedGitSource, legacyRecoverySources, finalizedRecoveryHolds, onlineRecoveryHolds, archivedRepositoryIntents };
|
||||
return { workspace, reasons: [...new Set(reasons)].filter(reason => !filesGone || !FILES_GONE_REASONS.has(reason)), details: [...new Set(details)].filter(entry => !filesGone || !FILES_GONE_REASONS.has(entry.slice(0, entry.indexOf(":")))).sort(), filesGone, settledFinalizationRunIds: settledFinalizationRunIds.sort(), authority, marker, source, issueBinding: issue?.executionWorkspaceId ?? null, retainedDirectory, archivedGitSource, legacyRecoverySources, finalizedRecoveryHolds, onlineRecoveryHolds, archivedRepositoryIntents };
|
||||
}
|
||||
|
||||
export async function inventoryRemoteWorkspaceMigration(db: Db, input: { companyId: string; workspaceId: string; writersStopped?: boolean }) {
|
||||
@@ -374,7 +415,7 @@ export async function inventoryRemoteWorkspaceMigration(db: Db, input: { company
|
||||
return { companyId: input.companyId, workspaceId: input.workspaceId, eligible: result.reasons.length === 0,
|
||||
...(onlineSourceUnproven && explained && "unproven" in explained ? { sourceScopeUnproven: explained.unproven } : {}),
|
||||
...(result.details.length ? { details: result.details } : {}),
|
||||
alreadyMigrated: Boolean(result.authority), reasons: result.reasons, localPath: result.workspace.cwd ?? result.workspace.providerRef,
|
||||
alreadyMigrated: Boolean(result.authority), ...(result.filesGone ? { filesUnavailable: true } : {}), reasons: result.reasons, localPath: result.workspace.cwd ?? result.workspace.providerRef,
|
||||
source: result.source, operationId: typeof result.marker.operationId === "string" ? result.marker.operationId : null,
|
||||
snapshotId: result.authority?.snapshotId ?? null };
|
||||
}
|
||||
@@ -408,6 +449,22 @@ function recoverySourcesResumeIdentity(value: unknown): unknown {
|
||||
});
|
||||
}
|
||||
|
||||
async function recordMissingWorkspaceFiles(tx: MigrationTransaction, workspace: Workspace, source: RemoteWorkspaceSource) {
|
||||
const at = new Date(), localPath = (workspace.cwd ?? workspace.providerRef)!;
|
||||
const authority: RemoteWorkspaceAuthority = { schema: "paperclip.remote-workspace.v1", epoch: 1, snapshotId: null,
|
||||
source: remoteWorkspaceSourceSchema.parse(source), location: null, writerRunId: null, dirty: false };
|
||||
const metadata: Record<string, unknown> = { ...workspace.metadata, remoteWorkspace: authority,
|
||||
[WORKSPACE_FILES_UNAVAILABLE_KEY]: workspaceFilesUnavailableRecord(localPath, at) };
|
||||
delete metadata.remoteWorkspaceMigration;
|
||||
const [saved] = await tx.update(executionWorkspaces).set({ providerType: "cloud_sandbox", providerRef: null, cwd: `/workspaces/${workspace.id}`,
|
||||
metadata, updatedAt: at }).where(and(eq(executionWorkspaces.companyId, workspace.companyId), eq(executionWorkspaces.id, workspace.id))).returning();
|
||||
if (!saved) throw new Error("remote_workspace_migration_source_changed");
|
||||
const { publication } = await persistActivity(tx as unknown as Db, { companyId: workspace.companyId, actorType: "system", actorId: "workspace-migration",
|
||||
action: "workspace.files_unavailable_at_migration", entityType: "execution_workspace", entityId: workspace.id,
|
||||
details: { reason: "files_missing_at_migration", localPath, status: workspace.status } });
|
||||
return { workspace: saved, authority, source: authority.source, filesUnavailablePublication: publication };
|
||||
}
|
||||
|
||||
async function reserveMigration(input: MigrationInput, onlineSource?: OnlineWorkspaceSource, cohort?: WorkspaceMigrationCohort,
|
||||
expectedSourceFingerprint?: string) {
|
||||
return input.db.transaction(async tx => {
|
||||
@@ -419,9 +476,17 @@ async function reserveMigration(input: MigrationInput, onlineSource?: OnlineWork
|
||||
if (!workspace) throw new Error("remote_workspace_migration_workspace_missing");
|
||||
if (workspace.sourceIssueId !== selected.sourceIssueId) throw new Error("remote_workspace_migration_source_changed");
|
||||
const current = await inspect(tx as unknown as Db, { ...input, onlineSource }, cohort);
|
||||
if (current.authority) return { workspace, authority: current.authority, operation: null, source: current.source, sourceFingerprint: "", issueBinding: current.issueBinding, retainedDirectory: null, archivedGitSource: null, legacyRecoverySources: [] as LegacyWorkspaceRecoverySource[], finalizedRecoveryHolds: [] as FinalizedWorkspaceRecoveryHold[], onlineRecoveryHolds: [] as OnlineRecoveryHold[], archivedRepositoryIntents: [] as RepositoryRequest[], settledFinalizationRunIds: [] as string[] };
|
||||
if (current.authority) return { workspace, authority: current.authority, filesUnavailablePublication: undefined, operation: null, source: current.source, sourceFingerprint: "", issueBinding: current.issueBinding, retainedDirectory: null, archivedGitSource: null, legacyRecoverySources: [] as LegacyWorkspaceRecoverySource[], finalizedRecoveryHolds: [] as FinalizedWorkspaceRecoveryHold[], onlineRecoveryHolds: [] as OnlineRecoveryHold[], archivedRepositoryIntents: [] as RepositoryRequest[], settledFinalizationRunIds: [] as string[] };
|
||||
if (current.reasons.length) throw new Error(`remote_workspace_migration_blocked:${current.reasons.join(",")}`);
|
||||
const nativeSessionContinuity = await inspectNativeWorkspaceMigration(tx as unknown as Db, workspace);
|
||||
if (current.filesGone) {
|
||||
if (cohort || current.marker.schema === SCHEMA || nativeSessionContinuity || current.legacyRecoverySources.length
|
||||
|| current.finalizedRecoveryHolds.length || current.onlineRecoveryHolds.length || current.archivedRepositoryIntents.length)
|
||||
throw new Error("remote_workspace_migration_blocked:local_source_unsafe_or_missing");
|
||||
return { ...await recordMissingWorkspaceFiles(tx, workspace, current.source), operation: null, sourceFingerprint: "",
|
||||
issueBinding: current.issueBinding, retainedDirectory: null, archivedGitSource: null, legacyRecoverySources: [] as LegacyWorkspaceRecoverySource[],
|
||||
finalizedRecoveryHolds: [] as FinalizedWorkspaceRecoveryHold[], onlineRecoveryHolds: [] as OnlineRecoveryHold[], archivedRepositoryIntents: [] as RepositoryRequest[], settledFinalizationRunIds: [] as string[] };
|
||||
}
|
||||
const source = remoteWorkspaceSourceSchema.parse(input.source ?? current.source);
|
||||
const sourceFingerprint = fingerprint(workspace);
|
||||
if (cohort && sourceFingerprint !== expectedSourceFingerprint) throw new Error("workspace_cohort_source_changed");
|
||||
@@ -446,7 +511,7 @@ async function reserveMigration(input: MigrationInput, onlineSource?: OnlineWork
|
||||
if (canonical(operation.metadata?.onlineRecoveryHolds ?? []) !== canonical(current.onlineRecoveryHolds)) throw new Error("remote_workspace_migration_source_changed");
|
||||
if (canonical(operation.metadata?.archivedRepositoryIntents ?? []) !== canonical(repositoryIntentBindings(current.archivedRepositoryIntents)))
|
||||
throw new Error("remote_workspace_migration_source_changed");
|
||||
return { workspace, authority: null, operation, source, sourceFingerprint, issueBinding, retainedDirectory: current.retainedDirectory, archivedGitSource: current.archivedGitSource, legacyRecoverySources: current.legacyRecoverySources, finalizedRecoveryHolds: current.finalizedRecoveryHolds, onlineRecoveryHolds: current.onlineRecoveryHolds, archivedRepositoryIntents: current.archivedRepositoryIntents, settledFinalizationRunIds: current.settledFinalizationRunIds };
|
||||
return { workspace, authority: null, filesUnavailablePublication: undefined, operation, source, sourceFingerprint, issueBinding, retainedDirectory: current.retainedDirectory, archivedGitSource: current.archivedGitSource, legacyRecoverySources: current.legacyRecoverySources, finalizedRecoveryHolds: current.finalizedRecoveryHolds, onlineRecoveryHolds: current.onlineRecoveryHolds, archivedRepositoryIntents: current.archivedRepositoryIntents, settledFinalizationRunIds: current.settledFinalizationRunIds };
|
||||
}
|
||||
let migrationSupersession;
|
||||
if (workspace.metadata?.remoteWorkspaceMigrationSupersession != null) {
|
||||
@@ -474,7 +539,7 @@ async function reserveMigration(input: MigrationInput, onlineSource?: OnlineWork
|
||||
await tx.update(executionWorkspaces).set({ metadata: { ...workspace.metadata, remoteWorkspaceMigration: {
|
||||
schema: SCHEMA, operationId: operation!.id, state: "running", sourceFingerprint, source,
|
||||
} }, updatedAt: new Date() }).where(eq(executionWorkspaces.id, workspace.id));
|
||||
return { workspace, authority: null, operation: operation!, source, sourceFingerprint, issueBinding: current.issueBinding, retainedDirectory: current.retainedDirectory, archivedGitSource: current.archivedGitSource, legacyRecoverySources: current.legacyRecoverySources, finalizedRecoveryHolds: current.finalizedRecoveryHolds, onlineRecoveryHolds: current.onlineRecoveryHolds, archivedRepositoryIntents: current.archivedRepositoryIntents, settledFinalizationRunIds: current.settledFinalizationRunIds };
|
||||
return { workspace, authority: null, filesUnavailablePublication: undefined, operation: operation!, source, sourceFingerprint, issueBinding: current.issueBinding, retainedDirectory: current.retainedDirectory, archivedGitSource: current.archivedGitSource, legacyRecoverySources: current.legacyRecoverySources, finalizedRecoveryHolds: current.finalizedRecoveryHolds, onlineRecoveryHolds: current.onlineRecoveryHolds, archivedRepositoryIntents: current.archivedRepositoryIntents, settledFinalizationRunIds: current.settledFinalizationRunIds };
|
||||
});
|
||||
}
|
||||
type ReservedMigration = Awaited<ReturnType<typeof reserveMigration>>;
|
||||
@@ -760,6 +825,10 @@ export async function migrateRemoteWorkspace(input: MigrationInput) {
|
||||
let committedPublication: Parameters<typeof publishActivity>[0] | undefined;
|
||||
const migrate = async (lock: MigrationTransaction) => {
|
||||
const reserved = await reserveMigration(input, onlineSource);
|
||||
if (reserved.filesUnavailablePublication) {
|
||||
publishActivity(reserved.filesUnavailablePublication);
|
||||
return { ...await inventoryRemoteWorkspaceMigration(input.db, input), applied: true, replayed: false, filesUnavailable: true };
|
||||
}
|
||||
if (reserved.authority) return { ...await inventoryRemoteWorkspaceMigration(input.db, input), applied: true, replayed: true };
|
||||
await lockMigrationRecovery(lock, [{ input, onlineSource, reserved }]);
|
||||
const childVerifier = createMigrationChildVerifier(input, onlineSource, lock);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
export const WORKSPACE_FILES_UNAVAILABLE_KEY = "workspaceFilesUnavailable";
|
||||
export const WORKSPACE_FILES_UNAVAILABLE_SCHEMA = "paperclip.workspace-files-unavailable.v1";
|
||||
export const WORKSPACE_FILES_UNAVAILABLE_MESSAGE =
|
||||
"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.";
|
||||
|
||||
export type WorkspaceFilesUnavailable = {
|
||||
schema: typeof WORKSPACE_FILES_UNAVAILABLE_SCHEMA;
|
||||
reason: "files_missing_at_migration";
|
||||
recordedAt: string;
|
||||
localPath: string;
|
||||
};
|
||||
|
||||
export function workspaceFilesUnavailableRecord(localPath: string, at: Date): WorkspaceFilesUnavailable {
|
||||
return { schema: WORKSPACE_FILES_UNAVAILABLE_SCHEMA, reason: "files_missing_at_migration", recordedAt: at.toISOString(), localPath };
|
||||
}
|
||||
|
||||
export function readWorkspaceFilesUnavailable(metadata: Record<string, unknown> | null | undefined): WorkspaceFilesUnavailable | null {
|
||||
const value = metadata?.[WORKSPACE_FILES_UNAVAILABLE_KEY];
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
||||
const record = value as Record<string, unknown>;
|
||||
return record.schema === WORKSPACE_FILES_UNAVAILABLE_SCHEMA && record.reason === "files_missing_at_migration"
|
||||
&& typeof record.recordedAt === "string" && typeof record.localPath === "string" ? record as WorkspaceFilesUnavailable : null;
|
||||
}
|
||||
Reference in new issue
Block a user