diff --git a/server/src/services/local-workspace-dependencies.ts b/server/src/services/local-workspace-dependencies.ts index e145204c0e3..a787f6721a9 100644 --- a/server/src/services/local-workspace-dependencies.ts +++ b/server/src/services/local-workspace-dependencies.ts @@ -1,4 +1,4 @@ -import { and, eq, isNotNull, notExists, sql } from "drizzle-orm"; +import { and, asc, desc, eq, gt, isNotNull, notExists, sql } from "drizzle-orm"; import { agents, environments, executionWorkspaces, type Db } from "@paperclipai/db"; export function localWorkspaceDependencyWhere(db: Pick) { @@ -25,3 +25,22 @@ export function localWorkspaceDependencyWhere(db: Pick) { notExists(pluginTaskWorkspace), ); } + +export async function listLocalWorkspaceCompanies(db: Pick, input: { after?: string; limit: number }) { + const rows = await db.selectDistinct({ companyId: executionWorkspaces.companyId }).from(executionWorkspaces) + .where(and(localWorkspaceDependencyWhere(db), input.after ? gt(executionWorkspaces.companyId, input.after) : undefined)) + .orderBy(asc(executionWorkspaces.companyId)).limit(input.limit); + return rows.map(row => row.companyId); +} + +export async function listLocalWorkspaces(db: Pick, input: { after?: string; limit: number }) { + const depth = sql`length(${executionWorkspaces.cwd})`; + const cursor = input.after?.match(/^(\d{1,9}):([0-9a-f-]{36})$/); + if (input.after && !cursor) throw new Error("local_workspace_cursor_invalid"); + const rows = await db.select({ companyId: executionWorkspaces.companyId, workspaceId: executionWorkspaces.id, depth }) + .from(executionWorkspaces).where(and(localWorkspaceDependencyWhere(db), cursor + ? sql`(${depth} < ${Number(cursor[1])} or (${depth} = ${Number(cursor[1])} and ${executionWorkspaces.id} > ${cursor[2]}::uuid))` + : undefined)) + .orderBy(desc(depth), asc(executionWorkspaces.id)).limit(input.limit); + return rows.map(row => ({ companyId: row.companyId, workspaceId: row.workspaceId, cursor: `${Number(row.depth)}:${row.workspaceId}` })); +} diff --git a/server/src/services/online-durable-data-migration-postgres.test.ts b/server/src/services/online-durable-data-migration-postgres.test.ts new file mode 100644 index 00000000000..5b22b9dce2d --- /dev/null +++ b/server/src/services/online-durable-data-migration-postgres.test.ts @@ -0,0 +1,136 @@ +import { randomUUID } from "node:crypto"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { eq, sql } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { activityLog, agents, companies, createDb, executionWorkspaceSnapshots, executionWorkspaces, heartbeatRuns, issues, projects, workspaceOperations } from "@paperclipai/db"; +import { readRemoteWorkspaceAuthority } from "@paperclipai/shared"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; +import { resolveManagedProjectWorkspaceDir } from "../home-paths.js"; +import { createLocalDiskStorageProvider } from "../storage/local-disk-provider.js"; +import { createStorageService } from "../storage/service.js"; +import type { StorageService } from "../storage/types.js"; +import { listLocalWorkspaceCompanies, listLocalWorkspaces } from "./local-workspace-dependencies.js"; +import { reconcileOnlineWorkspaceOperations } from "./offline-workspace-operation-reconciliation.js"; +import { inventoryRemoteWorkspaceMigration, migrateRemoteWorkspace } from "./remote-workspace-migration.js"; +import { getWorkspaceSnapshot, loadWorkspaceSnapshotArchive } from "./remote-workspace-snapshot-storage.js"; +import { restoreRemoteWorkspaceArchive } from "./remote-workspace-snapshot-archive.js"; +import { resetOnlineDurableDataMigrationProgressForTests, runOnlineDurableDataMigration } from "./online-durable-data-migration.js"; + +const support = await getEmbeddedPostgresTestSupport(); +describe.skipIf(!support.supported)("online durable-data migration of local workspaces", () => { + let database: Awaited>; + let db: ReturnType, home: string, storage: StorageService; + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("online-durable-workspaces-"); + db = createDb(database.connectionString); + await db.execute(sql`set client_min_messages = warning`); + }, 90_000); + afterAll(async () => { await db?.$client.end({ timeout: 1 }); await database?.cleanup(); }); + beforeEach(async () => { + resetOnlineDurableDataMigrationProgressForTests(); + home = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "pc-online-durable-"))); + vi.stubEnv("PAPERCLIP_HOME", home); + storage = { ...createStorageService(createLocalDiskStorageProvider(path.join(home, "objects"))), provider: "s3" } as StorageService; + }); + afterEach(async () => { + await db.delete(activityLog); + await db.delete(workspaceOperations); + await db.delete(executionWorkspaceSnapshots); + await db.delete(heartbeatRuns); + await db.delete(issues); + await db.delete(agents); + await db.delete(executionWorkspaces); + await db.delete(projects); + await db.delete(companies); + vi.unstubAllEnvs(); + await fs.rm(home, { recursive: true, force: true }); + }); + + async function localWorkspace(companyId: string, text: string) { + const [project] = await db.insert(projects).values({ companyId, name: `Project ${text}` }).returning(); + const cwd = resolveManagedProjectWorkspaceDir({ companyId, projectId: project.id }); + await fs.mkdir(cwd, { recursive: true }); + await fs.writeFile(path.join(cwd, "saved.txt"), text); + const [issue] = await db.insert(issues).values({ companyId, projectId: project.id, title: `Task ${text}` }).returning(); + const [workspace] = await db.insert(executionWorkspaces).values({ companyId, projectId: project.id, sourceIssueId: issue.id, + name: `Workspace ${text}`, mode: "shared_workspace", strategyType: "project_primary", providerType: "local_fs", cwd, providerRef: cwd }).returning(); + await db.update(issues).set({ executionWorkspaceId: workspace.id }).where(eq(issues.id, issue.id)); + return { workspace, issue, cwd }; + } + + const done = async () => ({ results: [], inspected: 0, migrated: 0, busy: 0, after: null, next: null }); + const owners = () => ({ + storage: () => storage, + localSkillStorage: () => storage, + durableAgentFiles: () => true, + agentFiles: done, + skillObjects: done, + skillPackages: () => ({ migrateSnapshots: done, migrateVersions: done }), + skillInstallations: () => ({ installations: done }), + runtimeSkillAssets: done, + workspaceCompanies: listLocalWorkspaceCompanies, + workspaceOperations: reconcileOnlineWorkspaceOperations, + localWorkspaces: listLocalWorkspaces, + inventoryWorkspace: inventoryRemoteWorkspaceMigration, + migrateWorkspace: migrateRemoteWorkspace, + nativeHarnessBackups: async () => undefined, + nativeControllers: async () => undefined, + eligibility: async () => ({ eligible: false, blockers: [] }), + record: async () => undefined, + }) as never; + + it("moves an idle local workspace to shared storage while serving and leaves a workspace with an active run in place", async () => { + const companyId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Online workspaces", issuePrefix: `W${companyId.slice(0, 6)}` }); + const idle = await localWorkspace(companyId, "idle work\n"); + const busy = await localWorkspace(companyId, "busy work\n"); + const [agent] = await db.insert(agents).values({ companyId, name: "Writer" }).returning(); + await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, issueId: busy.issue.id, status: "running", runtimeMode: "legacy" }); + const busyBefore = (await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, busy.workspace.id)))[0]; + + const result = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, owners()); + + expect(result).toMatchObject({ state: "completed", counts: { workspaces: 1 }, deferred: { "workspaces:active_execution": 1 } }); + const [moved] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, idle.workspace.id)); + const authority = readRemoteWorkspaceAuthority(moved.metadata)!; + expect(moved.providerType).toBe("cloud_sandbox"); + expect(authority.snapshotId).toEqual(expect.any(String)); + const reference = await getWorkspaceSnapshot(db, { companyId, workspaceId: idle.workspace.id, snapshotId: authority.snapshotId! }); + const archivePath = path.join(home, "idle.pcws"), restored = path.join(home, "idle-restored"); + await loadWorkspaceSnapshotArchive({ storage, reference: reference!, targetPath: archivePath }); + await restoreRemoteWorkspaceArchive({ archivePath, targetDir: restored, expectedManifestDigest: reference!.manifestDigest }); + expect(await fs.readFile(path.join(restored, "saved.txt"), "utf8")).toBe("idle work\n"); + + expect((await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, busy.workspace.id)))[0]).toEqual(busyBefore); + expect(await fs.readFile(path.join(busy.cwd, "saved.txt"), "utf8")).toBe("busy work\n"); + expect(await db.select().from(workspaceOperations).where(eq(workspaceOperations.executionWorkspaceId, busy.workspace.id))).toEqual([]); + }, 60_000); + + it("pages local workspaces deepest first and pages companies, with no skips or repeats across page boundaries", async () => { + const expected: Array<{ id: string; depth: number }> = []; + const companyIds = [randomUUID(), randomUUID()].sort(); + for (const companyId of companyIds) { + await db.insert(companies).values({ id: companyId, name: "Paging", issuePrefix: `P${companyId.slice(0, 6)}` }); + for (const cwd of ["/a/b", "/a/bb", "/a/bb", "/a/b/c/d", "/a/b/c"]) { + const [row] = await db.insert(executionWorkspaces).values({ companyId, name: cwd, mode: "shared_workspace", + strategyType: "project_primary", providerType: "local_fs", cwd, providerRef: cwd }).returning(); + expected.push({ id: row.id, depth: cwd.length }); + } + } + expected.sort((a, b) => b.depth - a.depth || a.id.localeCompare(b.id)); + const seen: string[] = []; + let after: string | undefined; + for (;;) { + const page = await listLocalWorkspaces(db, { after, limit: 3 }); + seen.push(...page.map(row => row.workspaceId)); + if (page.length < 3) break; + after = page.at(-1)!.cursor; + } + expect(seen).toEqual(expected.map(row => row.id)); + expect(await listLocalWorkspaceCompanies(db, { limit: 1 })).toEqual([companyIds[0]]); + expect(await listLocalWorkspaceCompanies(db, { after: companyIds[0], limit: 1 })).toEqual([companyIds[1]]); + expect(await listLocalWorkspaceCompanies(db, { after: companyIds[1], limit: 1 })).toEqual([]); + }); +}); diff --git a/server/src/services/online-durable-data-migration.test.ts b/server/src/services/online-durable-data-migration.test.ts index 2933c455b82..a157952367c 100644 --- a/server/src/services/online-durable-data-migration.test.ts +++ b/server/src/services/online-durable-data-migration.test.ts @@ -24,6 +24,11 @@ function owners(overrides: Record = {}) { { skillId: "s1", companyId: "c", status: "converted" }, { skillId: "s2", companyId: "c", status: "unchanged" }, { skillId: "s3", companyId: "c", status: "linked_local" }] }) }), runtimeSkillAssets: page("runtimeSkillAssets", { inspected: 1, after: null, results: [{ runId: "r1", status: "preserved" }] }), + workspaceCompanies: page("workspaceCompanies", []), + workspaceOperations: page("workspaceOperations", { reconciled: 0, held: [] }), + localWorkspaces: page("localWorkspaces", []), + inventoryWorkspace: page("inventoryWorkspace", { reasons: [] }), + migrateWorkspace: page("migrateWorkspace", { alreadyMigrated: true, reasons: [] }), nativeHarnessBackups: async (_db: Db, input: { onOutcome?: (outcome: string) => void }) => { calls.push("nativeHarnessBackups"); for (const outcome of ["published", "current", "source_active", "source_active"]) input.onOutcome?.(outcome); @@ -48,7 +53,7 @@ describe("online durable-data migration pass", () => { const fixture = owners(); const result = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners); expect(fixture.calls).toEqual(["agentFiles", "skillObjects", "skillSnapshots", "skillVersions", "skillInstallations", - "runtimeSkillAssets", "nativeHarnessBackups", "nativeControllers"]); + "runtimeSkillAssets", "workspaceCompanies", "localWorkspaces", "nativeHarnessBackups", "nativeControllers"]); expect(result).toEqual({ state: "completed", counts: { agentFiles: 1, skillObjects: 1, skillSnapshots: 1, skillInstallations: 1, runtimeSkillRuns: 1, nativeHarnessBackups: 1, nativeControllers: 1 }, @@ -194,4 +199,124 @@ describe("online durable-data migration pass", () => { expect(await second).toBe(await first); expect(agentFiles).toHaveBeenCalledOnce(); }); + + describe("workspaces", () => { + const workspace = (n: number) => ({ companyId: "c1", workspaceId: `w${n}`, cursor: `20:w${n}` }); + + it("reconciles stale workspace operations per company before migrating workspaces, then runs the native owners", async () => { + const workspaceOperations = vi.fn(async (_db: Db, input: { companyId: string }) => { + fixture.calls.push(`reconcile:${input.companyId}`); + return { reconciled: input.companyId === "c1" ? 2 : 0, held: [{ reason: "finalization_owner_busy" }] }; + }); + const fixture = owners({ + workspaceCompanies: vi.fn(async () => { fixture.calls.push("workspaceCompanies"); return ["c1", "c2"]; }), + workspaceOperations, + localWorkspaces: vi.fn(async () => { fixture.calls.push("localWorkspaces"); return [workspace(1)]; }), + migrateWorkspace: vi.fn(async () => { fixture.calls.push("migrateWorkspace"); return { alreadyMigrated: true, reasons: [] }; }), + }); + const result = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners); + expect(fixture.calls.slice(fixture.calls.indexOf("runtimeSkillAssets"))).toEqual(["runtimeSkillAssets", "workspaceCompanies", + "reconcile:c1", "reconcile:c2", "localWorkspaces", "inventoryWorkspace", "migrateWorkspace", "nativeHarnessBackups", "nativeControllers"]); + expect(workspaceOperations).toHaveBeenCalledWith(db, { companyId: "c1", signal: expect.any(AbortSignal) }); + expect(result.counts).toMatchObject({ workspaceOperations: 2, workspaces: 1 }); + expect(result.deferred).toMatchObject({ "workspace_operations:finalization_owner_busy": 2 }); + }); + + it("migrates an idle workspace through the online owner with a bounded source-lock wait, never the offline mode", async () => { + const migrateWorkspace = vi.fn(async () => ({ alreadyMigrated: true, reasons: [] })); + const fixture = owners({ localWorkspaces: async () => [workspace(1)], migrateWorkspace }); + await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners); + expect(migrateWorkspace).toHaveBeenCalledWith({ db, storage: s3, companyId: "c1", workspaceId: "w1", apply: true, + signal: expect.any(AbortSignal), sourceLockWaitMs: 1_000 }); + expect(migrateWorkspace.mock.calls[0]).not.toEqual([expect.objectContaining({ writersStopped: expect.anything() })]); + }); + + it("defers busy and unsupported workspaces with their owner reasons and does not force them", async () => { + const reasons: Record = { w1: ["active_execution"], w2: ["task_binding_required", "workspace_provider_unsupported"], w3: [] }; + const migrateWorkspace = vi.fn(async () => ({ alreadyMigrated: true, reasons: [] })); + const fixture = owners({ + localWorkspaces: async () => [workspace(1), workspace(2), workspace(3)], + inventoryWorkspace: async (_db: Db, input: { workspaceId: string }) => ({ reasons: reasons[input.workspaceId] }), + migrateWorkspace, + }); + const result = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners); + expect(migrateWorkspace).toHaveBeenCalledOnce(); + expect(migrateWorkspace).toHaveBeenCalledWith(expect.objectContaining({ workspaceId: "w3" })); + expect(result.counts).toMatchObject({ workspaces: 1 }); + expect(result.deferred).toMatchObject({ "workspaces:active_execution": 1, "workspaces:task_binding_required": 1, + "workspaces:workspace_provider_unsupported": 1 }); + }); + + it("defers a workspace that the owner refuses under its locks and continues with the rest of the page", async () => { + const failures: Record = { + w1: new Error("remote_workspace_migration_blocked:active_execution,workspace_runtime_owned"), + w2: new Error("workspace_source_busy"), + w3: new Error("EACCES: permission denied, open '/private/path'"), + }; + const fixture = owners({ + localWorkspaces: async (_db: Db, input: { after?: string }) => input.after ? [] : [workspace(1), workspace(2), workspace(3), workspace(4)], + migrateWorkspace: async (input: { workspaceId: string }) => { + if (failures[input.workspaceId]) throw failures[input.workspaceId]; + return { alreadyMigrated: true, reasons: [] }; + }, + }); + const result = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners); + expect(result.counts).toMatchObject({ workspaces: 1 }); + expect(result.deferred).toMatchObject({ "workspaces:active_execution": 1, "workspaces:workspace_runtime_owned": 1, + "workspaces:workspace_source_busy": 1, "workspaces:owner_failed": 1 }); + expect(JSON.stringify(result)).not.toContain("private"); + }); + + it("pages workspaces with the owner cursor and resumes the same page after the budget ends", async () => { + let clock = 0; + const pages: Array<{ after?: string; limit: number }> = []; + const localWorkspaces = vi.fn(async (_db: Db, input: { after?: string; limit: number }) => { + pages.push(input); + const start = input.after ? Number(input.after.split(":w")[1]) : 0; + return start >= 8 ? [] : Array.from({ length: input.limit }, (_, index) => workspace(start + index + 1)); + }); + const migrateWorkspace = vi.fn(async () => { clock += 10_000; return { alreadyMigrated: true, reasons: [] }; }); + const fixture = owners({ localWorkspaces, migrateWorkspace }); + const run = () => runOnlineDurableDataMigration(db, { budgetMs: 60_000, now: () => clock }, fixture.owners); + expect(await run()).toMatchObject({ state: "budget_exhausted", resumePhase: "workspaces", counts: expect.objectContaining({ workspaces: 8 }) }); + expect(await run()).toMatchObject({ state: "completed" }); + expect(pages).toEqual([{ limit: 4, after: undefined }, { limit: 4, after: "20:w4" }, { limit: 4, after: "20:w8" }]); + expect(fixture.calls.filter(call => call === "agentFiles")).toHaveLength(1); + }); + + it("halves a workspace page that overruns the budget and keeps the workspaces it already moved", async () => { + const limits: number[] = []; + const localWorkspaces = vi.fn(async (_db: Db, input: { limit: number }) => { + limits.push(input.limit); + return Array.from({ length: input.limit }, (_, index) => workspace(index + 1)); + }); + const migrateWorkspace = vi.fn(async (input: { workspaceId: string; signal: AbortSignal }) => { + if (input.workspaceId === "w1") return { alreadyMigrated: true, reasons: [] }; + return new Promise((_resolve, reject) => { + input.signal.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")), { once: true }); + }); + }); + const fixture = owners({ localWorkspaces, migrateWorkspace }); + const first = await runOnlineDurableDataMigration(db, { budgetMs: 20 }, fixture.owners); + expect(first).toMatchObject({ state: "budget_exhausted", resumePhase: "workspaces", counts: expect.objectContaining({ workspaces: 1 }) }); + expect(first.deferred).not.toHaveProperty("workspaces:owner_failed"); + await runOnlineDurableDataMigration(db, { budgetMs: 20 }, fixture.owners); + expect(limits).toEqual([4, 2]); + }); + + it("returns at the budget while the owner waits on a lock, and skips workspaces until that owner settles", async () => { + let release!: () => void; + const held = new Promise(resolve => { release = resolve; }); + const migrateWorkspace = vi.fn(async () => { await held; return { alreadyMigrated: true, reasons: [] }; }); + const fixture = owners({ localWorkspaces: async (_db: Db, input: { after?: string }) => input.after ? [] : [workspace(1)], migrateWorkspace }); + expect(await runOnlineDurableDataMigration(db, { budgetMs: 20 }, fixture.owners)).toMatchObject({ state: "budget_exhausted", resumePhase: "workspaces" }); + const busy = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners); + expect(busy).toMatchObject({ state: "completed", deferred: expect.objectContaining({ "workspaces:owner_busy": 1 }) }); + expect(migrateWorkspace).toHaveBeenCalledOnce(); + release(); + await held; + await new Promise(resolve => setTimeout(resolve, 0)); + expect(await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners)).toMatchObject({ counts: expect.objectContaining({ workspaces: 1 }) }); + }); + }); }); diff --git a/server/src/services/online-durable-data-migration.ts b/server/src/services/online-durable-data-migration.ts index 69bb195d933..635c3c16326 100644 --- a/server/src/services/online-durable-data-migration.ts +++ b/server/src/services/online-durable-data-migration.ts @@ -14,6 +14,9 @@ import { skillInstallationMaintenance } from "./skill-installation-maintenance.j import { migrateRuntimeSkillAssets } from "./native-runtime/runtime-skill-preservation.js"; import { prestageNativeHarnessBackups } from "./native-runtime/native-harness-backup-migration.js"; import { prestageNativeControllers } from "./native-runtime/native-controller-migration.js"; +import { listLocalWorkspaceCompanies, listLocalWorkspaces } from "./local-workspace-dependencies.js"; +import { reconcileOnlineWorkspaceOperations } from "./offline-workspace-operation-reconciliation.js"; +import { inventoryRemoteWorkspaceMigration, migrateRemoteWorkspace } from "./remote-workspace-migration.js"; export type OnlineDurableDataMigrationResult = { state: "completed" | "budget_exhausted" | "unsupported"; @@ -36,6 +39,12 @@ type Owners = { skillPackages: (db: Db, storage: StorageService) => Pick, "migrateSnapshots" | "migrateVersions">; skillInstallations: (db: Db, storage: StorageService) => Pick, "installations">; runtimeSkillAssets: typeof migrateRuntimeSkillAssets; + workspaceCompanies: typeof listLocalWorkspaceCompanies; + workspaceOperations: (db: Db, input: { companyId: string; signal: AbortSignal }) => Promise<{ reconciled: number; held: Array<{ reason: string }> }>; + localWorkspaces: typeof listLocalWorkspaces; + inventoryWorkspace: (db: Db, input: { companyId: string; workspaceId: string }) => Promise<{ reasons: string[] }>; + migrateWorkspace: (input: { db: Db; storage: StorageService; companyId: string; workspaceId: string; apply: true; + signal: AbortSignal; sourceLockWaitMs: number }) => Promise<{ alreadyMigrated: boolean; reasons: string[] }>; nativeHarnessBackups: typeof prestageNativeHarnessBackups; nativeControllers: typeof prestageNativeControllers; eligibility: (db: Db) => Promise<{ eligible: boolean; blockers: string[] }>; @@ -59,6 +68,11 @@ const defaultOwners: Owners = { skillPackages: skillPackageMaintenance, skillInstallations: skillInstallationMaintenance, runtimeSkillAssets: migrateRuntimeSkillAssets, + workspaceCompanies: listLocalWorkspaceCompanies, + workspaceOperations: reconcileOnlineWorkspaceOperations, + localWorkspaces: listLocalWorkspaces, + inventoryWorkspace: inventoryRemoteWorkspaceMigration, + migrateWorkspace: migrateRemoteWorkspace, nativeHarnessBackups: prestageNativeHarnessBackups, nativeControllers: prestageNativeControllers, eligibility: readOnlineEphemeralEnrollmentEligibility, @@ -66,17 +80,39 @@ const defaultOwners: Owners = { }; const PHASES = ["agent_files", "skill_objects", "skill_snapshots", "skill_versions", "skill_installations", - "runtime_skill_assets", "native_harness_backups", "native_controllers"] as const; + "runtime_skill_assets", "workspace_operations", "workspaces", "native_harness_backups", "native_controllers"] as const; type Phase = typeof PHASES[number]; let running: Promise | null = null; +let workspaceOwner: Promise | null = null; type Progress = { phase: number; after?: string; limit?: number; timeouts?: number }; let progress: Progress = { phase: 0 }; const DEFAULT_LIMITS: Partial> = { agent_files: 5, skill_objects: 50, skill_snapshots: 50, skill_versions: 50, - skill_installations: 50, runtime_skill_assets: 50 }; + skill_installations: 50, runtime_skill_assets: 50, workspace_operations: 10, workspaces: 4 }; +const WORKSPACE_SOURCE_LOCK_WAIT_MS = 1_000; +const WORKSPACE_BLOCKED = "remote_workspace_migration_blocked:"; + +function workspaceDeferrals(error: unknown): string[] { + const message = error instanceof Error ? error.message : ""; + if (message.startsWith(WORKSPACE_BLOCKED)) { + const reasons = message.slice(WORKSPACE_BLOCKED.length).split(",").filter(reason => /^[a-z_]{1,80}$/.test(reason)); + if (reasons.length) return reasons; + } + return [/^[a-z_]{1,80}$/.test(message) ? message : "owner_failed"]; +} export function resetOnlineDurableDataMigrationProgressForTests() { progress = { phase: 0 }; + workspaceOwner = null; +} + +function untilAborted(work: Promise, signal: AbortSignal): Promise { + return new Promise((resolve, reject) => { + const abort = () => reject(signal.reason); + if (signal.aborted) return abort(); + signal.addEventListener("abort", abort, { once: true }); + work.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort)); + }); } export function runOnlineDurableDataMigration(db: Db, input: { budgetMs: number; now?: () => number }, owners: Owners = defaultOwners) { @@ -148,6 +184,43 @@ async function migrate(db: Db, input: { budgetMs: number; now?: () => number }, add(counts, "runtimeSkillRuns", result.results.filter(row => row.status === "preserved").length); return result.inspected < limit || !result.after ? null : result.after; } + case "workspace_operations": { + const companies = await owners.workspaceCompanies(db, { after, limit }); + for (const companyId of companies) { + const result = await owners.workspaceOperations(db, { companyId, signal }); + add(counts, "workspaceOperations", result.reconciled); + for (const held of result.held) add(deferred, `workspace_operations:${held.reason}`); + } + return companies.length < limit ? null : companies.at(-1)!; + } + case "workspaces": { + if (workspaceOwner) { + add(deferred, "workspaces:owner_busy"); + return null; + } + const rows = await owners.localWorkspaces(db, { after, limit }); + for (const { companyId, workspaceId } of rows) { + let reasons: string[]; + try { + reasons = (await owners.inventoryWorkspace(db, { companyId, workspaceId })).reasons; + if (!reasons.length) { + const work = owners.migrateWorkspace({ db, storage, companyId, workspaceId, apply: true, signal, + sourceLockWaitMs: WORKSPACE_SOURCE_LOCK_WAIT_MS }); + const tracked: Promise = work.then(() => undefined, () => undefined) + .finally(() => { if (workspaceOwner === tracked) workspaceOwner = null; }); + workspaceOwner = tracked; + const result = await untilAborted(work, signal); + reasons = result.alreadyMigrated ? [] : result.reasons.length ? result.reasons : ["not_migrated"]; + } + } catch (error) { + if (signal.aborted) throw error; + reasons = workspaceDeferrals(error); + } + if (!reasons.length) add(counts, "workspaces"); + for (const reason of reasons) add(deferred, `workspaces:${reason}`); + } + return rows.length < limit ? null : rows.at(-1)!.cursor; + } case "native_harness_backups": { await owners.nativeHarnessBackups(db, { storage, signal, onOutcome: outcome => { if (outcome === "published") add(counts, "nativeHarnessBackups");