diff --git a/docs/agent-lifecycle.md b/docs/agent-lifecycle.md index d5eeed4d5c..9af207402e 100644 --- a/docs/agent-lifecycle.md +++ b/docs/agent-lifecycle.md @@ -276,7 +276,13 @@ sent right behind its archive still cancels it. An aborted archive stops at its next checkpoint and reports `canceled`; the undo unarchives only the agents that archive itself archived. Deleting the worktree directory is the point of no -return: an undo after it recreates the worktree through workspace recovery. The client shows or +return: an undo after it recreates the worktree through workspace recovery. Recovery checks out +the workspace's branch, which stays in the repository. A worktree on a detached HEAD has no +branch to come back to, so before deleting its directory the archive records HEAD as +`refs/paseo/archived/`. The ref keeps git's cleanup from deleting commits only that +HEAD held, and recovery creates a new `restored/…` branch at it, then deletes the ref. Recovery +reads the ref before the record's `branch`, which can still name the branch HEAD left. The ref +lives as long as the workspace stays archived. The client shows or hides the row by the latest local intent, so a late remove or upsert from a superseded request does not flip it back. Tabs and layout are purged only once the undo window closes with the archive committed. diff --git a/packages/app/e2e/browser/workspace-archive-undo.spec.ts b/packages/app/e2e/browser/workspace-archive-undo.spec.ts index 68cc16166e..b48bc252ed 100644 --- a/packages/app/e2e/browser/workspace-archive-undo.spec.ts +++ b/packages/app/e2e/browser/workspace-archive-undo.spec.ts @@ -1,3 +1,6 @@ +import { execFileSync } from "node:child_process"; +import { writeFileSync } from "node:fs"; +import path from "node:path"; import type { Page } from "@playwright/test"; import { expect, test } from "../support/fixtures"; import { gotoAppShell } from "../support/helpers/app"; @@ -238,6 +241,38 @@ test.describe("Workspace archive undo", () => { await expectHostWorkspaceSettledActive(client, worktree.workspaceId); }); + test("Undo brings back a worktree archived on a detached HEAD with its commit", async ({ + page, + }) => { + const worktree = await seedWorktree(page, "archive-undo-detached"); + const git = (args: string[]) => + execFileSync("git", args, { cwd: worktree.workspaceDirectory, encoding: "utf8" }).trim(); + git(["checkout", "--detach"]); + writeFileSync(path.join(worktree.workspaceDirectory, "detached.txt"), "detached work\n"); + git(["add", "detached.txt"]); + git([ + "-c", + "user.name=Paseo Test", + "-c", + "user.email=test@getpaseo.local", + "-c", + "commit.gpgsign=false", + "commit", + "-m", + "detached work", + ]); + const detachedCommit = git(["rev-parse", "HEAD"]); + + await archiveFromRowButton(page, worktree.workspaceId); + await undoButton(page).hover(); + await expectDirectoryPresence(worktree.workspaceDirectory, false); + await undoButton(page).click(); + + await expect(workspaceRow(page, worktree.workspaceId)).toBeVisible({ timeout: 30_000 }); + await expectHostWorkspaceSettledActive(client, worktree.workspaceId); + expect(git(["rev-parse", "HEAD"])).toBe(detachedCommit); + }); + test("hovering Undo keeps the toast open past its deadline, and its close ends the undo", async ({ page, }) => { diff --git a/packages/server/src/server/resolve-worktree-creation-intent.ts b/packages/server/src/server/resolve-worktree-creation-intent.ts index 5eddc0ef7b..34d587da03 100644 --- a/packages/server/src/server/resolve-worktree-creation-intent.ts +++ b/packages/server/src/server/resolve-worktree-creation-intent.ts @@ -3,7 +3,7 @@ import type { WorktreeSource } from "../utils/worktree.js"; export type WorktreeCreationIntent = Exclude< WorktreeSource, - { kind: "restore" | "restore-from-base" } + { kind: "restore" | "restore-from-base" | "restore-commit" } >; export interface ResolveWorktreeCreationIntentInput { diff --git a/packages/server/src/server/session/workspace-recovery/archived-commit.ts b/packages/server/src/server/session/workspace-recovery/archived-commit.ts new file mode 100644 index 0000000000..f0858caadd --- /dev/null +++ b/packages/server/src/server/session/workspace-recovery/archived-commit.ts @@ -0,0 +1,68 @@ +import { stat } from "node:fs/promises"; + +import { runGitCommand } from "../../../utils/run-git-command.js"; + +// A worktree on a detached HEAD holds commits that no branch may hold. Removing its folder at +// archive leaves those commits unreachable, and git's cleanup deletes them. Before the folder goes, +// archive records HEAD under a ref of its own, which keeps the commit alive and tells recovery +// where the worktree was. A worktree on a branch needs nothing: the branch stays in the +// repository and recovery checks it out again. +// +// Refs outside refs/heads, refs/tags and refs/remotes are shared by every worktree of a +// repository and hidden from branch lists, pushes and fetches. + +async function isDirectory(path: string): Promise { + return stat(path).then( + (stats) => stats.isDirectory(), + () => false, + ); +} + +function archivedCommitRef(workspaceId: string): string { + return `refs/paseo/archived/${workspaceId}`; +} + +/** + * Records a detached HEAD's commit for each workspace before archive removes the worktree, and + * clears what an earlier archive kept when HEAD is now on a branch. + */ +export async function keepArchivedCommit(input: { + worktreePath: string; + workspaceIds: readonly string[]; +}): Promise { + // A folder that is already gone has no HEAD left to lose. + if (input.workspaceIds.length === 0 || !(await isDirectory(input.worktreePath))) return; + const symbolicHead = await runGitCommand(["symbolic-ref", "-q", "HEAD"], { + cwd: input.worktreePath, + acceptExitCodes: [0, 1], + }); + const onBranch = symbolicHead.exitCode === 0; + for (const workspaceId of input.workspaceIds) { + const ref = archivedCommitRef(workspaceId); + await runGitCommand(onBranch ? ["update-ref", "-d", ref] : ["update-ref", ref, "HEAD"], { + cwd: input.worktreePath, + }); + } +} + +/** The commit archive kept for this workspace, or null when its HEAD was on a branch. */ +export async function readArchivedCommit(input: { + repoRoot: string; + workspaceId: string; +}): Promise { + const { stdout, exitCode } = await runGitCommand( + ["rev-parse", "--verify", "--quiet", `${archivedCommitRef(input.workspaceId)}^{commit}`], + { cwd: input.repoRoot, acceptExitCodes: [0, 1] }, + ); + return exitCode === 0 ? stdout.trim() : null; +} + +/** Stops keeping the commit once a restored worktree holds it on a new branch. */ +export async function releaseArchivedCommit(input: { + repoRoot: string; + workspaceId: string; +}): Promise { + await runGitCommand(["update-ref", "-d", archivedCommitRef(input.workspaceId)], { + cwd: input.repoRoot, + }); +} diff --git a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts index a683a07744..46a617af3c 100644 --- a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts +++ b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts @@ -17,6 +17,7 @@ import { type PersistedProjectRecord, type PersistedWorkspaceRecord, } from "../../workspace-registry.js"; +import { readArchivedCommit, releaseArchivedCommit } from "./archived-commit.js"; export type WorkspaceRecoveryAction = "unarchive" | "restore"; @@ -142,6 +143,10 @@ export function createWorkspaceRecoveryService(deps: { if (resolved.kind === "restore") { await recreateArchivedWorktree(resolved.workspace, resolved.sourceRepoRoot); + await releaseArchivedCommit({ + repoRoot: resolved.sourceRepoRoot, + workspaceId: resolved.workspace.workspaceId, + }); } await deps.unarchiveWorkspace(resolved.workspace); return { workspaceId, action: resolved.kind }; @@ -151,13 +156,7 @@ export function createWorkspaceRecoveryService(deps: { workspace: PersistedWorkspaceRecord, sourceRepoRoot: string, ): Promise { - const source: WorktreeSource = workspace.branch - ? { kind: "restore", branchName: workspace.branch, baseRef: workspace.baseBranch } - : { - kind: "restore-from-base", - branchName: `restored/${randomUUID().slice(0, 8)}`, - baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch), - }; + const source = await resolveRecoverySource(workspace, sourceRepoRoot); try { await runGitCommand(["worktree", "prune"], { cwd: sourceRepoRoot, timeout: 30_000 }); @@ -231,6 +230,38 @@ export function createWorkspaceRecoveryService(deps: { return { inspect, restore }; } +// A commit archive kept wins over the recorded branch: the record's branch is the last one +// observed, and HEAD may have left it before the archive. +async function resolveRecoverySource( + workspace: PersistedWorkspaceRecord, + sourceRepoRoot: string, +): Promise { + const archivedCommit = await readArchivedCommit({ + repoRoot: sourceRepoRoot, + workspaceId: workspace.workspaceId, + }); + if (archivedCommit) { + return { + kind: "restore-commit", + commit: archivedCommit, + branchName: restoredBranchName(), + baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch), + }; + } + if (workspace.branch) { + return { kind: "restore", branchName: workspace.branch, baseRef: workspace.baseBranch }; + } + return { + kind: "restore-from-base", + branchName: restoredBranchName(), + baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch), + }; +} + +function restoredBranchName(): string { + return `restored/${randomUUID().slice(0, 8)}`; +} + async function resolveRecoveryBase(repoRoot: string, recordedBase: string | null): Promise { if (recordedBase) { try { diff --git a/packages/server/src/server/workspace-archive-service.ts b/packages/server/src/server/workspace-archive-service.ts index 7a71b4682b..377df6c146 100644 --- a/packages/server/src/server/workspace-archive-service.ts +++ b/packages/server/src/server/workspace-archive-service.ts @@ -21,6 +21,7 @@ import type { import { createRealpathAwarePathMatcher } from "../utils/path.js"; import { runWithGitCommandPriority } from "../utils/run-git-command.js"; import { WorkspaceAutomationBlockedError } from "./workspace-automation-gate.js"; +import { keepArchivedCommit } from "./session/workspace-recovery/archived-commit.js"; export type ActiveWorkspaceRef = Pick< PersistedWorkspaceRecord, @@ -491,6 +492,17 @@ async function maybeRemoveDirectory( // Last chance to keep the directory. Teardown commands already ran, so a cancel here restores // a workspace whose teardown hooks fired; that beats deleting what the user asked to keep. request.checkpoint(); + try { + await keepArchivedCommit({ worktreePath: backing.path, workspaceIds: archivedWorkspaceIds }); + } catch (error) { + // Without the kept commit, removing the folder could delete commits that only its HEAD holds. + const reason = "could not keep the commit its HEAD is on"; + dependencies.sessionLogger?.warn( + { err: error, targetPath: backing.path, requestId: request.requestId }, + `Worktree directory left in place during archive: ${reason}`, + ); + return { removedDirectory: false, directoryLeftBehind: { path: backing.path, reason } }; + } try { await deletePaseoWorktree({ cwd: backing.mainRepoRoot, diff --git a/packages/server/src/server/workspace-archive-undo.e2e.test.ts b/packages/server/src/server/workspace-archive-undo.e2e.test.ts index a509cb2b6a..3baf47518c 100644 --- a/packages/server/src/server/workspace-archive-undo.e2e.test.ts +++ b/packages/server/src/server/workspace-archive-undo.e2e.test.ts @@ -35,6 +35,10 @@ function git(repoDir: string, args: string[]): void { execFileSync("git", args, { cwd: repoDir, stdio: "pipe" }); } +function gitOutput(cwd: string, args: string[]): string { + return execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); +} + /** A repo whose worktree teardown parks until released. */ function createRepoWithGatedTeardown(): GatedRepo { const tempRoot = mkdtempSync(path.join(tmpdir(), "workspace-archive-undo-")); @@ -151,6 +155,40 @@ test.skipIf(process.platform === "win32")( 60000, ); +test.skipIf(process.platform === "win32").each(["undo", "restore"] as const)( + "%s brings back a worktree archived on a detached HEAD with the commits no ref held", + async (route) => { + const repo = createRepoWithGatedTeardown(); + repo.releaseTeardown(); + const { workspaceId, directory } = await createWorktreeWorkspaceWithAgent( + repo.repoDir, + `detached-${route}`, + ); + git(directory, ["checkout", "--detach"]); + writeFileSync(path.join(directory, "detached.txt"), "detached work\n"); + git(directory, ["add", "detached.txt"]); + git(directory, ["-c", "commit.gpgsign=false", "commit", "-m", "detached work"]); + const detachedCommit = gitOutput(directory, ["rev-parse", "HEAD"]); + + const archived = await ctx.client.archiveWorkspace(workspaceId); + expect(archived.error).toBeNull(); + expect(existsSync(directory)).toBe(false); + git(repo.repoDir, ["reflog", "expire", "--expire-unreachable=now", "--all"]); + git(repo.repoDir, ["gc", "--prune=now", "--quiet"]); + + if (route === "undo") await ctx.client.undoWorkspaceArchive(workspaceId); + else await ctx.client.restoreWorkspace(workspaceId); + + expect({ + workspaceActive: await isWorkspaceActive(workspaceId), + head: gitOutput(directory, ["rev-parse", "HEAD"]), + onBranch: gitOutput(directory, ["branch", "--show-current"]).length > 0, + keptRefs: gitOutput(repo.repoDir, ["for-each-ref", "refs/paseo"]), + }).toEqual({ workspaceActive: true, head: detachedCommit, onBranch: true, keptRefs: "" }); + }, + 60000, +); + test.skipIf(process.platform === "win32")( "archive, undo, archive leaves the workspace archived", async () => { diff --git a/packages/server/src/utils/worktree.ts b/packages/server/src/utils/worktree.ts index 2fc8bc05db..2758c0cc83 100644 --- a/packages/server/src/utils/worktree.ts +++ b/packages/server/src/utils/worktree.ts @@ -189,6 +189,8 @@ export type WorktreeSource = | { kind: "checkout-branch"; branchName: string } | { kind: "restore"; branchName: string; baseRef: string | null } | { kind: "restore-from-base"; baseRef: string; branchName: string } + // A new branch at a commit archive kept, compared against baseRef. + | { kind: "restore-commit"; commit: string; baseRef: string; branchName: string } | { kind: "checkout-change-request"; forge: string; @@ -1492,18 +1494,19 @@ async function resolveRestoredWorktreeSourcePlan( }; } -async function resolveRestoredWorktreeFromBasePlan( +async function resolveRestoredNewBranchPlan( cwd: string, - source: Extract, + source: Extract, ): Promise { await validateGitBranchName(cwd, source.branchName); const baseRef = await resolveBaseBranchForWorktree(cwd, source.baseRef); const branchName = await resolveUniqueLocalBranchName(cwd, source.branchName); + const startPoint = source.kind === "restore-commit" ? source.commit : baseRef; return { branchName, metadataBaseRefName: normalizeRequiredBaseBranch(source.baseRef), metadataBaseRef: baseRef, - addArguments: ["-b", branchName, "--no-track", baseRef], + addArguments: ["-b", branchName, "--no-track", startPoint], }; } @@ -1545,7 +1548,8 @@ async function resolveWorktreeSourcePlan({ case "restore": return resolveRestoredWorktreeSourcePlan(cwd, source); case "restore-from-base": - return resolveRestoredWorktreeFromBasePlan(cwd, source); + case "restore-commit": + return resolveRestoredNewBranchPlan(cwd, source); case "checkout-branch": { await validateGitBranchName(cwd, source.branchName); await ensureLocalBranch(cwd, source.branchName);