Skip to content

The open-source app everyone uses to manage agents at work

feat: reopen a fresh workspace with a warning when its restore point expired (#17269)

Devin Foleyd69631b01b9c
diff --git a/doc/recoverable-disk-cleanup.md b/doc/recoverable-disk-cleanup.md
index e3ea33ac73..cde748386f 100644
--- a/doc/recoverable-disk-cleanup.md
+++ b/doc/recoverable-disk-cleanup.md
@@ -149,8 +149,16 @@ result. The bundle is always imported, so history-only commits are present again
objects in the repository; they are not recreated as branches or reflog entries, and the
restore point keeps them until it expires. A draft commit message left by an aborted
commit still keeps the worktree from expiring, because restore points do not save it. A worktree that already matches is only marked applied, and a worktree that
-diverged is never overwritten: the restore fails closed and can be retried. A missing,
-corrupt or expired restore point also fails closed.
+diverged is never overwritten: the restore fails closed and can be retried. A missing
+or corrupt restore point also fails closed.
+
+When a restore point has expired, through retention or on a nested checkout, reopening
+starts fresh instead: the worktree is recreated on its branch (the branch tip if the
+repository still has it, otherwise a new branch from the base ref), the project's nested
+repositories are cloned fresh before the provision command runs, the saved recipe is
+dropped, and a system comment on the issue warns that unpushed and uncommitted work from
+before the cleanup is no longer available. The same warning is returned with the reopen
+result and recorded on the `execution_workspace.reopened` activity.
Restore points are encrypted saves of the parts of a git worktree that its remote
diff --git a/server/src/__tests__/git-restore-point-expiration.test.ts b/server/src/__tests__/git-restore-point-expiration.test.ts
index b21b4b7574..aea5a1e25d 100644
--- a/server/src/__tests__/git-restore-point-expiration.test.ts
+++ b/server/src/__tests__/git-restore-point-expiration.test.ts
@@ -6,13 +6,15 @@ import { randomUUID } from "node:crypto";
import { pathToFileURL } from "node:url";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { eq, sql } from "drizzle-orm";
-import { agents, companies, createDb, executionWorkspaceRestorePoints, executionWorkspaces, heartbeatRuns, issues } from "@paperclipai/db";
+import { agents, companies, createDb, executionWorkspaceRestorePoints, executionWorkspaces, heartbeatRuns, issueComments, issues } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { materializeIsolatedRemoteWorkspaceSource } from "../services/isolated-remote-workspace-source.js";
import { ensurePersistedExecutionWorkspaceAvailable, realizeExecutionWorkspace } from "../services/workspace-runtime.js";
import { executionWorkspaceService } from "../services/execution-workspaces.js";
import { expireReconstructableGitWorkspace, gitWorkspaceLastActivityAt } from "../services/git-workspace-expiration.js";
import { getStorageService } from "../storage/index.js";
+import { markGitRestorePointExpired } from "../services/git-restore-point-storage.js";
+import { GIT_RESTORE_POINT_EXPIRED_WARNING } from "../services/execution-workspaces.js";
const gitEnv = { ...process.env, GIT_AUTHOR_NAME: "Fixture", GIT_AUTHOR_EMAIL: "[email protected]",
GIT_COMMITTER_NAME: "Fixture", GIT_COMMITTER_EMAIL: "[email protected]", GIT_TERMINAL_PROMPT: "0" };
@@ -226,6 +228,36 @@ describeEmbeddedPostgres("git restore point expiration", () => {
expect(await f.reopen()).toMatchObject({ ok: false, code: "rebuild_failed" });
});
+ it("reopens a workspace whose restore point expired as a fresh workspace with a warning", async () => {
+ const f = await fixture();
+ const unpushed = await makeUnsavedWork(f.cwd);
+ expect(await f.expire()).toMatchObject({ expired: true });
+ const [ledgerRow] = await f.ledger();
+ await markGitRestorePointExpired(db, ledgerRow!);
+ await getStorageService().deleteObject(f.companyId, ledgerRow!.objectKey);
+ const branch = (await f.row()).branchName!;
+ git(f.baseCwd, "worktree", "prune");
+ git(f.baseCwd, "branch", "-D", branch);
+ git(f.baseCwd, "reflog", "expire", "--expire=now", "--all");
+ git(f.baseCwd, "gc", "-q", "--prune=now");
+ expect(() => git(f.baseCwd, "cat-file", "-e", `${unpushed}^{commit}`)).toThrow();
+ expect((await f.row()).metadata?.gitCacheRestoration).toMatchObject({ restorePoint: { expiredAt: expect.any(String) } });
+ await fs.writeFile(f.cwd, "blocks the worktree\n");
+ expect(await f.reopen()).toMatchObject({ ok: false, code: "rebuild_failed" });
+ expect((await f.row()).metadata?.gitCacheRestoration).toMatchObject({ restorePoint: { expiredAt: expect.any(String) } });
+ await fs.rm(f.cwd);
+ const reopened = await f.reopen();
+ expect(reopened).toMatchObject({ ok: true, reopened: true, warning: GIT_RESTORE_POINT_EXPIRED_WARNING });
+ expect(await exists(f.cwd)).toBe(true);
+ expect(git(f.cwd, "rev-parse", "--abbrev-ref", "HEAD")).toBe(branch);
+ expect(git(f.cwd, "rev-parse", "HEAD")).not.toBe(unpushed);
+ expect(git(f.cwd, "status", "--porcelain")).toBe("");
+ await expect(fs.access(path.join(f.cwd, "notes", "todo.md"))).rejects.toMatchObject({ code: "ENOENT" });
+ expect((await f.row()).metadata?.gitCacheRestoration).toBeUndefined();
+ const comments = await db.select().from(issueComments).where(eq(issueComments.issueId, f.issueId));
+ expect(comments.filter(comment => comment.body === GIT_RESTORE_POINT_EXPIRED_WARNING)).toMatchObject([{ authorType: "system" }]);
+ });
+
describe("idle open issues", () => {
async function openIdle(f: Awaited<ReturnType<typeof fixture>>, idleDays: number) {
await db.update(issues).set({ status: "in_progress", completedAt: null, updatedAt: new Date(Date.now() - idleDays * DAY_MS) })
diff --git a/server/src/__tests__/git-workspace-expiration.test.ts b/server/src/__tests__/git-workspace-expiration.test.ts
index 263308de2f..0b527a257c 100644
--- a/server/src/__tests__/git-workspace-expiration.test.ts
+++ b/server/src/__tests__/git-workspace-expiration.test.ts
@@ -8,6 +8,8 @@ import { createRequire } from "node:module";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { eq, sql } from "drizzle-orm";
import { companies, projects, projectWorkspaces, issues, executionWorkspaces, agents, heartbeatRuns, nativeRunFinalizations, workspaceRuntimeServices, executionWorkspaceRestorePoints, createDb } from "@paperclipai/db";
+import { markGitRestorePointExpired } from "../services/git-restore-point-storage.js";
+import { GIT_RESTORE_POINT_EXPIRED_WARNING } from "../services/execution-workspaces.js";
import { getStorageService } from "../storage/index.js";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { resolveManagedProjectWorkspaceDir } from "../home-paths.js";
@@ -229,6 +231,24 @@ describeEmbeddedPostgres("reconstructable Git expiration", () => {
vi.unstubAllEnvs();
});
+ it("reopens with a fresh workspace and a warning when a nested checkout's restore point expired", async () => {
+ vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY", "31".repeat(32));
+ const f = await nestedFixture(false);
+ await unpushedNestedWork(f.nested.cwd);
+ expect(await f.expire({ expireBase: false, restorePoint: restorePoint() })).toMatchObject({ expired: true, restorePoint: true });
+ const [row] = await ledger(f.workspaceId);
+ await markGitRestorePointExpired(db, row!);
+ const recipe = (await f.row()).metadata?.gitCacheRestoration as Record<string, any>;
+ expect(recipe.contents.checkouts[0].restorePoint.expiredAt).toEqual(expect.any(String));
+ await fs.rm(f.nested.cwd, { recursive: true, force: true });
+ expect(await f.reopen()).toMatchObject({ ok: true, reopened: true, warning: GIT_RESTORE_POINT_EXPIRED_WARNING });
+ expect(await exists(f.cwd)).toBe(true);
+ expect(git(f.nested.cwd, "rev-parse", "HEAD")).toBe(f.nestedA);
+ expect(await exists(path.join(f.nested.cwd, "draft.md"))).toBe(false);
+ expect((await f.row()).metadata?.gitCacheRestoration).toBeUndefined();
+ vi.unstubAllEnvs();
+ });
+
it("expires and restores a nested checkout that only has an unpushed commit", async () => {
vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY", "31".repeat(32));
const f = await nestedFixture(false);
diff --git a/server/src/services/execution-workspaces.ts b/server/src/services/execution-workspaces.ts
index 231fd6c51e..6fa7522060 100644
--- a/server/src/services/execution-workspaces.ts
+++ b/server/src/services/execution-workspaces.ts
@@ -7,7 +7,9 @@ import { assertExecutionWorkspaceRecordAccess, assertTaskWorkspaceExecutionAcces
import { verifiedRecordedIsolatedRemoteSource, withIsolatedRepositorySourceLock } from "./isolated-remote-workspace-source.js";
import { expireReconstructableGitWorkspace, gitWorkspaceLastActivityAt, hasPendingGitExpiration } from "./git-workspace-expiration.js";
import type { StorageService } from "../storage/types.js";
-import { readGitCacheRestoration, restoreGitCacheBase, recoverGitCacheExpirationLocks, GitCacheRestorationFailure } from "./git-workspace-restoration.js";
+import { readGitCacheRestoration, restoreGitCacheBase, recoverGitCacheExpirationLocks, GitCacheRestorationFailure, gitRestorePointExpired } from "./git-workspace-restoration.js";
+
+export const GIT_RESTORE_POINT_EXPIRED_WARNING = "The saved state of this workspace expired, so it was reopened as a fresh workspace on its branch. Unpushed and uncommitted work from before it was cleaned up is no longer available.";
import { parseObject } from "../adapters/utils.js";
import { resolveCoreTrustPreset } from "./trust-preset-resolver.js";
import { CONTROLLER_PROVISION_COPY_ONLY, workspaceRequiresCopyOnlyProvisioning } from "./workspace-host-provision.js";
@@ -290,7 +292,7 @@ export type ReopenClosedIsolatedExecutionWorkspaceResult =
// `generation` is the lifecycle generation the reopen published the active row
// at. It owns the reopen-pending flag. A later clear must present this same
// generation, so a stale actor never clears a newer reopen's fence.
- | { ok: true; workspace: ExecutionWorkspace; reopened: true; generation: number }
+ | { ok: true; workspace: ExecutionWorkspace; reopened: true; generation: number; warning?: string }
| { ok: true; workspace: ExecutionWorkspace; reopened: false; generation: number }
| { ok: false; code: "not_reopenable" | "rebuild_failed"; message: string };
@@ -3847,6 +3849,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
let recipe: ReturnType<typeof readGitCacheRestoration>;
try { recipe = readGitCacheRestoration(snapshot); }
catch { return { ok: false, code: "rebuild_failed", message: new GitCacheRestorationFailure().message }; }
+ const freshStart = recipe !== null && isClosedExecutionWorkspaceStatus(snapshot.status) && gitRestorePointExpired(recipe);
const gitAuth = createGitRemoteAuthProvider(db, snapshot.companyId, { issueId: issue.id });
const [
{ ensurePersistedExecutionWorkspaceAvailable },
@@ -3877,7 +3880,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
let resolvedBaseCwd: string | null;
try {
resolvedBaseCwd = recipe && isClosedExecutionWorkspaceStatus(snapshot.status)
- ? await restoreGitCacheBase(snapshot, recipe, gitAuth)
+ ? await restoreGitCacheBase(snapshot, recipe, gitAuth, undefined, { freshStart })
: await verifiedRecordedIsolatedRemoteSource(snapshot) ?? projectWorkspace?.cwd ?? null;
} catch {
return { ok: false, code: "rebuild_failed", message: recipe
@@ -3996,6 +3999,27 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
row.metadata as Record<string, unknown> | null,
);
delete nextMetadata.gitCacheExpiration;
+ const rebuildMetadata = { ...(row.metadata as Record<string, unknown> | null ?? {}) };
+ if (freshStart) {
+ delete rebuildMetadata.gitCacheRestoration;
+ delete rebuildMetadata.gitCacheExpiration;
+ }
+ const freshCheckouts = freshStart && Boolean(row.projectId) && (recipe?.contents?.checkouts.length ?? 0) > 0;
+ const prepareFreshProjectRepositories = async (targetCwd: string) => {
+ const { prepareProjectRepositoryWorkspaces } = await import("./heartbeat/workspaces.js");
+ const repositoryRows = await tx.select().from(projectWorkspaces).where(and(
+ eq(projectWorkspaces.companyId, row.companyId), eq(projectWorkspaces.projectId, row.projectId!),
+ )).orderBy(asc(projectWorkspaces.createdAt), asc(projectWorkspaces.id));
+ await prepareProjectRepositoryWorkspaces({ cwd: targetCwd, anchorRepoUrl: row.repoUrl, workspaces: repositoryRows,
+ resolveGitAuth: gitAuth,
+ prepareLocalSource: async sourceCwd => {
+ const sourceIdentity = await fs.realpath(sourceCwd);
+ return async () => {
+ if (await fs.realpath(sourceCwd) !== sourceIdentity) throw forbidden("Execution workspace copy identity changed during reopen");
+ await assertTaskWorkspaceExecutionAccess(tx, input.authorizationActor, issue.companyId, { issueId: issue.id, workspaceId: row.id });
+ };
+ } });
+ };
const recorder = workspaceOperationService(db).createRecorder({
companyId: row.companyId,
executionWorkspaceId: row.id,
@@ -4069,7 +4093,10 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
},
skipHostProvision: trust.kind === "low_trust_review" || copyOnlyProvisioning,
beforeSourceCopy: verifyCopyIdentity,
- afterSourceCopy: verifyCopyIdentity,
+ afterSourceCopy: freshCheckouts ? async (sourceCwd: string, targetCwd: string) => {
+ await verifyCopyIdentity?.(sourceCwd, targetCwd);
+ await prepareFreshProjectRepositories(targetCwd);
+ } : verifyCopyIdentity,
base: {
baseCwd: resolvedBaseCwd ?? row.cwd ?? "",
source: "task_session",
@@ -4089,7 +4116,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
repoUrl: row.repoUrl,
baseRef: row.baseRef,
branchName: row.branchName,
- metadata: row.metadata as Record<string, unknown> | null,
+ metadata: freshStart ? rebuildMetadata : row.metadata as Record<string, unknown> | null,
config: {
...config,
provisionCommand:
@@ -4173,7 +4200,8 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
// Keep the refresh guard after reopening so normal preparation cannot
// advance the saved checkout to upstream HEAD. Its intact branch may now
// receive newer task commits; the next expiration records a fresh recipe.
- if (recipe) nextMetadata.gitCacheRestoration = { ...nextMetadata.gitCacheRestoration as Record<string, unknown>, restoredAt: now().toISOString() };
+ if (freshStart) delete nextMetadata.gitCacheRestoration;
+ else if (recipe) nextMetadata.gitCacheRestoration = { ...nextMetadata.gitCacheRestoration as Record<string, unknown>, restoredAt: now().toISOString() };
const activeMetadata = setMetadataReopenPendingConsumption(nextMetadata, now());
await measureRunPhase("workspace.notification", () => notifyTerminalWorkspaceWork(tx, `workspace:${row.id}`));
const activeRow = await tx
@@ -4218,9 +4246,15 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
issueId: issue.id,
outcome: "reopened",
generation: nextGeneration,
+ ...(freshStart ? { restorePointExpired: true, warning: GIT_RESTORE_POINT_EXPIRED_WARNING } : {}),
},
});
- return { ok: true, reopened: true, workspace: toExecutionWorkspace(activeRow), generation: nextGeneration };
+ if (freshStart) {
+ const { issueService } = await import("./issues.js");
+ await issueService(db).addComment(issue.id, GIT_RESTORE_POINT_EXPIRED_WARNING, {}, { authorType: "system" }, tx);
+ }
+ return { ok: true, reopened: true, workspace: toExecutionWorkspace(activeRow), generation: nextGeneration,
+ ...(freshStart ? { warning: GIT_RESTORE_POINT_EXPIRED_WARNING } : {}) };
}).catch((error): ReopenClosedIsolatedExecutionWorkspaceResult => {
logger.warn({ error, executionWorkspaceId: snapshot.id }, "Execution workspace reopen failed");
return { ok: false, code: "rebuild_failed", message: recipe ? new GitCacheRestorationFailure().message : "Failed to rebuild the execution workspace" };
diff --git a/server/src/services/git-restore-point-storage.ts b/server/src/services/git-restore-point-storage.ts
index 53596bb54b..a373451506 100644
--- a/server/src/services/git-restore-point-storage.ts
+++ b/server/src/services/git-restore-point-storage.ts
@@ -264,9 +264,27 @@ export async function applyGitRestorePointToWorktree(input: {
}
export async function markGitRestorePointExpired(db: Db, restorePoint: { companyId: string; executionWorkspaceId: string; objectKey: string }) {
- await db.update(executionWorkspaces).set({
- metadata: sql`jsonb_set(${executionWorkspaces.metadata}, '{gitCacheRestoration,restorePoint,expiredAt}', ${JSON.stringify(new Date().toISOString())}::jsonb)`,
- updatedAt: new Date(),
- }).where(and(eq(executionWorkspaces.id, restorePoint.executionWorkspaceId), eq(executionWorkspaces.companyId, restorePoint.companyId),
- sql`${executionWorkspaces.metadata}->'gitCacheRestoration'->'restorePoint'->>'objectKey' = ${restorePoint.objectKey}`));
+ const at = new Date().toISOString();
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ const [row] = await db.select({ metadata: executionWorkspaces.metadata }).from(executionWorkspaces)
+ .where(and(eq(executionWorkspaces.id, restorePoint.executionWorkspaceId), eq(executionWorkspaces.companyId, restorePoint.companyId)));
+ const recipe = row?.metadata?.gitCacheRestoration as Record<string, any> | undefined;
+ if (!recipe) return;
+ const expire = (ref: Record<string, unknown> | undefined) => ref?.objectKey === restorePoint.objectKey ? { ...ref, expiredAt: at } : ref;
+ const next = {
+ ...recipe,
+ ...(recipe.restorePoint ? { restorePoint: expire(recipe.restorePoint) } : {}),
+ ...(recipe.contents ? { contents: { ...recipe.contents, checkouts: (recipe.contents.checkouts ?? []).map((checkout: Record<string, any>) =>
+ checkout.restorePoint ? { ...checkout, restorePoint: expire(checkout.restorePoint) } : checkout) } } : {}),
+ };
+ if (JSON.stringify(next) === JSON.stringify(recipe)) return;
+ const updated = await db.update(executionWorkspaces).set({
+ metadata: sql`jsonb_set(${executionWorkspaces.metadata}, '{gitCacheRestoration}', ${JSON.stringify(next)}::jsonb)`,
+ updatedAt: new Date(),
+ }).where(and(eq(executionWorkspaces.id, restorePoint.executionWorkspaceId), eq(executionWorkspaces.companyId, restorePoint.companyId),
+ sql`${executionWorkspaces.metadata}->'gitCacheRestoration' = ${JSON.stringify(recipe)}::jsonb`))
+ .returning({ id: executionWorkspaces.id });
+ if (updated.length === 1) return;
+ }
+ throw new RestorePointRestoreFailure("restore_point_expiry_conflict");
}
diff --git a/server/src/services/git-workspace-restoration.ts b/server/src/services/git-workspace-restoration.ts
index 0c29ceaf3b..017d71c272 100644
--- a/server/src/services/git-workspace-restoration.ts
+++ b/server/src/services/git-workspace-restoration.ts
@@ -574,8 +574,12 @@ export async function finishGitCacheTrash(workspace: Workspace) {
}
/** Called only after authorization and while holding the source/lifecycle fences. */
+export function gitRestorePointExpired(recipe: GitCacheRestoration) {
+ return Boolean(recipe.restorePoint?.expiredAt) || (recipe.contents?.checkouts ?? []).some(checkout => Boolean(checkout.restorePoint?.expiredAt));
+}
+
export async function restoreGitCacheBase(workspace: Workspace, recipe: GitCacheRestoration, resolveGitAuth: GitRemoteAuthProvider,
- storage?: StorageService) {
+ storage?: StorageService, options: { freshStart?: boolean } = {}) {
if (readGitCacheRestoration(workspace)?.commit !== recipe.commit) throw new GitCacheRestorationFailure();
try {
await finishGitCacheTrash(workspace);
@@ -600,6 +604,7 @@ export async function restoreGitCacheBase(workspace: Workspace, recipe: GitCache
: (await materializeManagedProjectWorkspace(recipe.sourcePath, { repoUrl: recipe.repoUrl, resolveGitAuth })).cwd;
await verifiedGitCacheSource(workspace, recipe.sourcePath);
if (!cwd) throw new GitCacheRestorationFailure();
+ if (options.freshStart) return cwd;
if (recipe.restorePoint) {
await ensureGitRestorePointCommit({ storage: storage ?? getStorageService(), workspace: { companyId: workspace.companyId, id: workspace.id },
ref: recipe.restorePoint, repositoryCwd: cwd });