From a87bd7fc0ceb89b829f99ba7d46748731d697fa2 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Wed, 18 Nov 2026 10:10:45 +0700 Subject: [PATCH] Preserve commits when archiving workspaces (#10009) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(workspaces): preserve commits when archiving worktrees A removed worktree can be the only reference to its HEAD. Keep that commit before deletion and record the checkout so detached workspaces restore at the same commit. Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com> * fix(workspaces): restore saved checkouts through one git path Keep existing archive and deletion behavior when Git cannot read a worktree HEAD, and record every readable checkout for a common restore path. * fix(workspaces): preserve git HEAD identity through restore Record Git’s full HEAD ref or commit so restore can pass branch and detached checkouts to Git without guessing from a short name. * fix(workspaces): scope saved HEAD to each archive An archive with no readable checkout must not retain the HEAD saved by an earlier archive. * test(workspaces): verify detached checkout after restore Update the browser journey for detached restore and allow the daemon restart test enough time on Windows runners. --------- Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com> (cherry picked from commit 59d6018dacc1a0d0737f9227d85c9e6b28f0cc8b) --- .../app/e2e/browser/worktree-restore.spec.ts | 17 +- packages/app/src/i18n/resources/ar.ts | 3 +- packages/app/src/i18n/resources/en.ts | 3 +- packages/app/src/i18n/resources/es.ts | 3 +- packages/app/src/i18n/resources/fr.ts | 3 +- packages/app/src/i18n/resources/ja.ts | 3 +- packages/app/src/i18n/resources/ko.ts | 3 +- packages/app/src/i18n/resources/pt-BR.ts | 3 +- packages/app/src/i18n/resources/ru.ts | 2 +- packages/app/src/i18n/resources/zh-CN.ts | 3 +- .../hub/execution-session.websocket.test.ts | 2 +- .../resolve-worktree-creation-intent.ts | 2 +- .../workspace-recovery-service.test.ts | 184 +++++++++++++++++- .../workspace-recovery-service.ts | 43 +++- .../src/server/workspace-archive-service.ts | 11 +- .../server/workspace-archive-undo.e2e.test.ts | 34 ++++ .../server/src/server/workspace-registry.ts | 3 + .../server/src/utils/worktree.posix.test.ts | 26 +++ packages/server/src/utils/worktree.test.ts | 24 +++ packages/server/src/utils/worktree.ts | 75 ++++++- 20 files changed, 396 insertions(+), 51 deletions(-) diff --git a/packages/app/e2e/browser/worktree-restore.spec.ts b/packages/app/e2e/browser/worktree-restore.spec.ts index 5849415984..069a9725e6 100644 --- a/packages/app/e2e/browser/worktree-restore.spec.ts +++ b/packages/app/e2e/browser/worktree-restore.spec.ts @@ -361,6 +361,10 @@ test.describe("Worktree restore", () => { cwd: backingWorktree.workspaceDirectory, stdio: "pipe", }); + const originalHead = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: backingWorktree.workspaceDirectory, + encoding: "utf8", + }).trim(); const created = await worktreeClient.createWorkspace({ source: { kind: "directory", path: backingWorktree.workspaceDirectory }, title: "Sample workspace", @@ -389,10 +393,7 @@ test.describe("Worktree restore", () => { await page.getByTestId(`agent-row-${getServerId()}-${agent.id}`).click(); await expect(page.getByText("Workspace archived", { exact: true })).toBeVisible(); await expect( - page.getByText( - "Restore Sample workspace to return to its agents. A new branch will start from the saved base or the repository default.", - { exact: true }, - ), + page.getByText("Restore Sample workspace to return to its agents.", { exact: true }), ).toBeVisible(); await captureBranchlessRestoreStep(page, "01-restore-workspace.png"); @@ -409,17 +410,13 @@ test.describe("Worktree restore", () => { cwd: backingWorktree.workspaceDirectory, encoding: "utf8", }).trim(); - const defaultHead = execFileSync("git", ["rev-parse", "main"], { - cwd: tempRepo.path, - encoding: "utf8", - }).trim(); - expect(restoredHead).toBe(defaultHead); + expect(restoredHead).toBe(originalHead); expect( execFileSync("git", ["branch", "--show-current"], { cwd: backingWorktree.workspaceDirectory, encoding: "utf8", }).trim(), - ).toMatch(/^restored\//); + ).toBe(""); }); test("restore failure stays visible and permits a successful retry", async ({ page }) => { diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index e79e901253..593d50d922 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -484,8 +484,7 @@ export const ar: TranslationResources = { archivedTitle: "مساحة العمل مؤرشفة", restoreDescription: "استعد {{workspaceName}} للعودة إلى وكلائها. ستستخدم شجرة العمل الفرع {{branch}}.", - restoreWithoutBranchDescription: - "استعد {{workspaceName}} للعودة إلى وكلائها. سيبدأ فرع جديد من الفرع الأساسي المحفوظ أو الفرع الافتراضي للمستودع.", + restoreWithoutBranchDescription: "استعد {{workspaceName}} للعودة إلى وكلائها.", unarchiveDescription: "{{workspaceName}} مؤرشفة. ألغِ أرشفتها لفتحها مجددًا.", restoreAction: "استعادة", unarchiveAction: "إلغاء الأرشفة", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index a59de6a6a1..02e875a75f 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -483,8 +483,7 @@ export const en = { archivedTitle: "Workspace archived", restoreDescription: "Restore {{workspaceName}} to return to its agents. Its worktree will use branch {{branch}}.", - restoreWithoutBranchDescription: - "Restore {{workspaceName}} to return to its agents. A new branch will start from the saved base or the repository default.", + restoreWithoutBranchDescription: "Restore {{workspaceName}} to return to its agents.", unarchiveDescription: "{{workspaceName}} is archived. Unarchive it to open it again.", restoreAction: "Restore", unarchiveAction: "Unarchive", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index e8a942c775..fa510cc8eb 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -489,8 +489,7 @@ export const es: TranslationResources = { archivedTitle: "Espacio de trabajo archivado", restoreDescription: "Restaura {{workspaceName}} para volver a sus agentes. Su worktree usará la rama {{branch}}.", - restoreWithoutBranchDescription: - "Restaura {{workspaceName}} para volver a sus agentes. Se creará una rama nueva desde la base guardada o la rama predeterminada del repositorio.", + restoreWithoutBranchDescription: "Restaura {{workspaceName}} para volver a sus agentes.", unarchiveDescription: "{{workspaceName}} está archivado. Desarchívalo para volver a abrirlo.", restoreAction: "Restaurar", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 8f7eba11ac..18536c5e96 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -489,8 +489,7 @@ export const fr: TranslationResources = { archivedTitle: "Espace de travail archivé", restoreDescription: "Restaurez {{workspaceName}} pour retrouver ses agents. Son worktree utilisera la branche {{branch}}.", - restoreWithoutBranchDescription: - "Restaurez {{workspaceName}} pour retrouver ses agents. Une nouvelle branche partira de la base enregistrée ou de la branche par défaut du dépôt.", + restoreWithoutBranchDescription: "Restaurez {{workspaceName}} pour retrouver ses agents.", unarchiveDescription: "{{workspaceName}} est archivé. Désarchivez-le pour le rouvrir.", restoreAction: "Restaurer", unarchiveAction: "Désarchiver", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 5cd17d7300..6d177c808f 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -489,8 +489,7 @@ export const ja: TranslationResources = { archivedTitle: "ワークスペースはアーカイブ済みです", restoreDescription: "{{workspaceName}} を復元してエージェントに戻ります。worktree ではブランチ {{branch}} を使用します。", - restoreWithoutBranchDescription: - "{{workspaceName}} を復元してエージェントに戻ります。保存されたベース、またはリポジトリのデフォルトブランチから新しいブランチを作成します。", + restoreWithoutBranchDescription: "{{workspaceName}} を復元してエージェントに戻ります。", unarchiveDescription: "{{workspaceName}} はアーカイブされています。再度開くにはアーカイブを解除してください。", restoreAction: "復元", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index 29fe850ac1..6a629c3fa4 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -485,8 +485,7 @@ export const ko: TranslationResources = { archivedTitle: "워크스페이스가 보관되었습니다", restoreDescription: "{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 워크트리는 {{branch}} 브랜치를 사용합니다.", - restoreWithoutBranchDescription: - "{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 저장된 기반 브랜치 또는 저장소 기본 브랜치에서 새 브랜치를 만듭니다.", + restoreWithoutBranchDescription: "{{workspaceName}}를 복원하여 에이전트로 돌아갑니다.", unarchiveDescription: "{{workspaceName}}가 보관되었습니다. 다시 열려면 보관을 취소하세요.", restoreAction: "복원", unarchiveAction: "보관 취소", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index 405de1fe44..23ec297c45 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -488,8 +488,7 @@ export const ptBR: TranslationResources = { archivedTitle: "Workspace arquivado", restoreDescription: "Restaure {{workspaceName}} para voltar aos seus agentes. A worktree usará a branch {{branch}}.", - restoreWithoutBranchDescription: - "Restaure {{workspaceName}} para voltar aos seus agentes. Uma nova branch partirá da base salva ou da branch padrão do repositório.", + restoreWithoutBranchDescription: "Restaure {{workspaceName}} para voltar aos seus agentes.", unarchiveDescription: "{{workspaceName}} está arquivado. Desarquive-o para abri-lo novamente.", restoreAction: "Restaurar", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index bfe65aa2b6..729c04d88e 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -489,7 +489,7 @@ export const ru: TranslationResources = { restoreDescription: "Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Worktree будет использовать ветку {{branch}}.", restoreWithoutBranchDescription: - "Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Новая ветка будет создана от сохранённой базовой или ветки репозитория по умолчанию.", + "Восстановите «{{workspaceName}}», чтобы вернуться к его агентам.", unarchiveDescription: "Рабочее пространство «{{workspaceName}}» находится в архиве. Разархивируйте его, чтобы снова открыть.", restoreAction: "Восстановить", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index c2d2500240..b47edf1e6c 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -484,8 +484,7 @@ export const zhCN: TranslationResources = { archivedTitle: "Workspace 已归档", restoreDescription: "恢复 {{workspaceName}} 以返回其中的代理。worktree 将使用分支 {{branch}}。", - restoreWithoutBranchDescription: - "恢复 {{workspaceName}} 以返回其中的代理。新分支将从保存的基准分支或仓库默认分支创建。", + restoreWithoutBranchDescription: "恢复 {{workspaceName}} 以返回其中的代理。", unarchiveDescription: "{{workspaceName}} 已归档。取消归档以重新打开。", restoreAction: "恢复", unarchiveAction: "取消归档", diff --git a/packages/server/src/server/hub/execution-session.websocket.test.ts b/packages/server/src/server/hub/execution-session.websocket.test.ts index 7cc2db0480..f9f9227f40 100644 --- a/packages/server/src/server/hub/execution-session.websocket.test.ts +++ b/packages/server/src/server/hub/execution-session.websocket.test.ts @@ -554,7 +554,7 @@ test("Hub resolves persisted execution ownership after daemon restart", async () expect(workspaceId).toEqual(expect.any(String)); expect(await hub.archivedWorkspaceAt(workspaceId!)).toEqual(expect.any(String)); expect(await hub.worktreeState(worktreeCwd)).toEqual({ exists: false, listed: false }); -}, 20_000); +}, 60_000); test("Hub treats missing and foreign executions as already controlled without exposing ownership", async () => { const hub = await launchRelationship(); 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/workspace-recovery-service.test.ts b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts index 5526166d05..16a59dcd62 100644 --- a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts +++ b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts @@ -335,11 +335,15 @@ async function createBaseRecoveryFixture(baseBranch: string | null) { await registry.update(record.workspaceId, (value) => ({ ...value, archivedAt: null })); }, }); - async function archiveAndRemove() { - await archivePersistedWorkspaceRecord({ - workspaceId: workspace.workspaceId, - workspaceRegistry: registry, - }); + async function archiveAndRemove(legacy = false) { + if (legacy) { + await registry.archive(workspace.workspaceId, new Date().toISOString()); + } else { + await archivePersistedWorkspaceRecord({ + workspaceId: workspace.workspaceId, + workspaceRegistry: registry, + }); + } await deletePaseoWorktree({ cwd: repoDir, worktreePath: workspace.cwd, paseoHome }); expect(existsSync(workspace.cwd)).toBe(false); } @@ -357,6 +361,134 @@ test("preserves ordinary checkout behavior when no separate base was recorded", ).toMatchObject({ currentBranch: "feature", baseRef: "feature" }); }); +test("records the full HEAD ref of an archived checkout", async () => { + const fixture = await createBaseRecoveryFixture(null); + await fixture.archiveAndRemove(); + expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({ + branch: "feature", + head: "refs/heads/feature", + }); +}); + +test("archives a workspace whose worktree Git administration is missing", async () => { + const fixture = await createBaseRecoveryFixture(null); + const gitDir = execFileSync("git", ["rev-parse", "--absolute-git-dir"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(); + rmSync(gitDir, { recursive: true, force: true }); + await archivePersistedWorkspaceRecord({ + workspaceId: fixture.workspace.workspaceId, + workspaceRegistry: fixture.registry, + }); + expect((await fixture.registry.get(fixture.workspace.workspaceId))?.archivedAt).toBeTruthy(); +}); + +test("restores a branch that shares its name with a tag", async () => { + const fixture = await createBaseRecoveryFixture("main"); + execFileSync("git", ["tag", "feature"], { cwd: fixture.repoDir }); + await fixture.archiveAndRemove(); + expect((await fixture.registry.get(fixture.workspace.workspaceId))?.head).toBe( + "refs/heads/feature", + ); + expect(await fixture.service.inspect(fixture.workspace.workspaceId)).toMatchObject({ + branch: "feature", + }); + await fixture.service.restore(fixture.workspace.workspaceId); + expect( + execFileSync("git", ["symbolic-ref", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe("refs/heads/feature"); +}); + +test("restores detached HEAD even when the stored branch is stale", async () => { + const fixture = await createBaseRecoveryFixture("main"); + execFileSync("git", ["switch", "--detach"], { cwd: fixture.workspace.cwd }); + const commit = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(); + await fixture.archiveAndRemove(); + expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({ + branch: "feature", + head: commit, + }); + expect(await fixture.service.inspect(fixture.workspace.workspaceId)).toMatchObject({ + branch: null, + }); + await fixture.service.restore(fixture.workspace.workspaceId); + expect( + execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe("HEAD"); + expect( + execFileSync("git", ["rev-parse", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe(commit); +}); + +test.each(["manual", "reconciliation"] as const)( + "a later %s archive without a readable HEAD restores the latest recorded branch", + async (route) => { + const fixture = await createBaseRecoveryFixture("main"); + await fixture.archiveAndRemove(); + await fixture.service.restore(fixture.workspace.workspaceId); + execFileSync("git", ["switch", "-c", "feature-b"], { cwd: fixture.workspace.cwd }); + writeFileSync(join(fixture.workspace.cwd, "newer.txt"), "newer\n"); + execFileSync("git", ["add", "newer.txt"], { cwd: fixture.workspace.cwd }); + execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "newer"], { + cwd: fixture.workspace.cwd, + }); + const commit = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(); + // Placement reconciliation records the branch observed while the workspace is active. + await fixture.registry.update(fixture.workspace.workspaceId, (workspace) => ({ + ...workspace, + branch: "feature-b", + })); + execFileSync("git", ["worktree", "remove", "--force", fixture.workspace.cwd], { + cwd: fixture.repoDir, + }); + if (route === "manual") { + await archivePersistedWorkspaceRecord({ + workspaceId: fixture.workspace.workspaceId, + workspaceRegistry: fixture.registry, + }); + } else { + await fixture.registry.archive(fixture.workspace.workspaceId, new Date().toISOString()); + } + + expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({ + branch: "feature-b", + head: undefined, + }); + expect(await fixture.service.inspect(fixture.workspace.workspaceId)).toMatchObject({ + branch: "feature-b", + }); + await fixture.service.restore(fixture.workspace.workspaceId); + expect( + execFileSync("git", ["symbolic-ref", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe("refs/heads/feature-b"); + expect( + execFileSync("git", ["rev-parse", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe(commit); + }, +); + test("restores a branchless workspace from its recorded base so work can continue", async () => { const fixture = await createBaseRecoveryFixture("refs/heads/release"); execFileSync("git", ["switch", "-c", "release"], { cwd: fixture.repoDir, stdio: "pipe" }); @@ -368,7 +500,7 @@ test("restores a branchless workspace from its recorded base so work can continu ...workspace, branch: null, })); - await fixture.archiveAndRemove(); + await fixture.archiveAndRemove(true); await expect(fixture.service.inspect(fixture.workspace.workspaceId)).resolves.toMatchObject({ kind: "recoverable", @@ -402,7 +534,7 @@ test("restores a branchless workspace from the repository default when its base ...workspace, branch: null, })); - await fixture.archiveAndRemove(); + await fixture.archiveAndRemove(true); await expect(fixture.service.restore(fixture.workspace.workspaceId)).resolves.toEqual({ workspaceId: fixture.workspace.workspaceId, @@ -418,6 +550,44 @@ test("restores a branchless workspace from the repository default when its base ); }); +test("restores the archived detached checkout at its recorded commit", async () => { + const fixture = await createBaseRecoveryFixture("refs/heads/main"); + execFileSync("git", ["switch", "--detach"], { cwd: fixture.workspace.cwd }); + writeFileSync(join(fixture.workspace.cwd, "detached.txt"), "detached\n"); + execFileSync("git", ["add", "detached.txt"], { cwd: fixture.workspace.cwd }); + execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "detached"], { + cwd: fixture.workspace.cwd, + }); + const commit = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(); + await fixture.archiveAndRemove(); + expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({ + branch: "feature", + head: commit, + }); + execFileSync("git", ["reflog", "expire", "--expire=now", "--all"], { cwd: fixture.repoDir }); + execFileSync("git", ["gc", "--prune=now"], { cwd: fixture.repoDir }); + await fixture.service.restore(fixture.workspace.workspaceId); + expect(await readPaseoWorktreeMetadata(fixture.workspace.cwd)).toMatchObject({ + baseRefName: "main", + baseRef: "refs/heads/main", + }); + expect( + execFileSync("git", ["rev-parse", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe(commit); + expect( + execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe("HEAD"); +}); + test("restores the branch HEAD with a base name when the exact base is missing", async () => { const fixture = await createBaseRecoveryFixture("refs/remotes/upstream/main"); const headBeforeArchive = execFileSync("git", ["rev-parse", "HEAD"], { 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..38c95cb421 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 @@ -151,13 +151,27 @@ 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), - }; + let source: WorktreeSource; + const checkout = parseWorkspaceHead(workspace); + if (checkout.kind === "branch") { + source = { + kind: "restore", + branchName: checkout.branch, + baseRef: workspace.baseBranch, + }; + } else if (checkout.kind === "commit") { + source = { + kind: "restore-commit", + commit: checkout.commit, + baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch), + }; + } else { + source = { + kind: "restore-from-base", + branchName: `restored/${randomUUID().slice(0, 8)}`, + baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch), + }; + } try { await runGitCommand(["worktree", "prune"], { cwd: sourceRepoRoot, timeout: 30_000 }); @@ -251,16 +265,29 @@ async function resolveRecoveryBase(repoRoot: string, recordedBase: string | null return defaultBranch; } +function parseWorkspaceHead( + workspace: PersistedWorkspaceRecord, +): { kind: "branch"; branch: string } | { kind: "commit"; commit: string } | { kind: "missing" } { + if (workspace.head) { + const prefix = "refs/heads/"; + return workspace.head.startsWith(prefix) + ? { kind: "branch", branch: workspace.head.slice(prefix.length) } + : { kind: "commit", commit: workspace.head }; + } + return workspace.branch ? { kind: "branch", branch: workspace.branch } : { kind: "missing" }; +} + function createRecoveryPlan( input: | { action: "unarchive"; workspace: PersistedWorkspaceRecord } | { action: "restore"; workspace: PersistedWorkspaceRecord; sourceRepoRoot: string }, ): RecoveryPlan { + const checkout = parseWorkspaceHead(input.workspace); const state = { kind: "recoverable" as const, workspaceId: input.workspace.workspaceId, workspaceName: resolveWorkspaceDisplayName(input.workspace), - branch: input.workspace.branch, + branch: checkout.kind === "branch" ? checkout.branch : null, }; if (input.action === "restore") { return { diff --git a/packages/server/src/server/workspace-archive-service.ts b/packages/server/src/server/workspace-archive-service.ts index 7a71b4682b..5f6fb473e7 100644 --- a/packages/server/src/server/workspace-archive-service.ts +++ b/packages/server/src/server/workspace-archive-service.ts @@ -8,6 +8,7 @@ import type { WorkspaceGitService } from "./workspace-git-service.js"; import type { ForgeService } from "../services/forge-service.js"; import { deletePaseoWorktree, + readWorktreeHeadReference, isPaseoOwnedWorktreeCwd, runWorktreeTeardownCommands, WorktreeTeardownError, @@ -707,7 +708,15 @@ export async function archivePersistedWorkspaceRecord(input: { } const archivedAt = input.archivedAt ?? new Date().toISOString(); - await input.workspaceRegistry.archive(input.workspaceId, archivedAt, input.context); + let head: string | null = null; + if (existingWorkspace.kind === "worktree") { + const cwd = existingWorkspace.worktreeRoot ?? existingWorkspace.cwd; + head = await readWorktreeHeadReference(cwd); + } + await input.workspaceRegistry.archive(input.workspaceId, archivedAt, { + ...input.context, + ...(head ? { head } : {}), + }); return existingWorkspace; } 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..f68dbc5dd1 100644 --- a/packages/server/src/server/workspace-archive-undo.e2e.test.ts +++ b/packages/server/src/server/workspace-archive-undo.e2e.test.ts @@ -151,6 +151,40 @@ test.skipIf(process.platform === "win32")( 60000, ); +test.skipIf(process.platform === "win32").each([ + ["branch", "restore"], + ["branch", "undo"], + ["detached", "restore"], + ["detached", "undo"], +] as const)( + "%s checkout survives archive and %s", + async (checkout, action) => { + const repo = createRepoWithGatedTeardown(); + repo.releaseTeardown(); + const { workspaceId, directory } = await createWorktreeWorkspaceWithAgent( + repo.repoDir, + `keep-${checkout}-${action}`, + ); + if (checkout === "detached") git(directory, ["switch", "--detach"]); + writeFileSync(path.join(directory, "change.txt"), `${checkout}\n`); + git(directory, ["add", "change.txt"]); + git(directory, ["-c", "commit.gpgsign=false", "commit", "-m", "workspace commit"]); + const readHead = (args: string[]) => + execFileSync("git", args, { cwd: directory, encoding: "utf8" }).trim(); + const commit = readHead(["rev-parse", "HEAD"]); + const branch = readHead(["rev-parse", "--abbrev-ref", "HEAD"]); + expect((await ctx.client.archiveWorkspace(workspaceId)).error).toBeNull(); + expect(existsSync(directory)).toBe(false); + git(repo.repoDir, ["reflog", "expire", "--expire=now", "--all"]); + git(repo.repoDir, ["gc", "--prune=now"]); + if (action === "undo") await ctx.client.undoWorkspaceArchive(workspaceId); + else await ctx.client.restoreWorkspace(workspaceId); + expect(readHead(["rev-parse", "HEAD"])).toBe(commit); + expect(readHead(["rev-parse", "--abbrev-ref", "HEAD"])).toBe(branch); + }, + 60000, +); + test.skipIf(process.platform === "win32")( "archive, undo, archive leaves the workspace archived", async () => { diff --git a/packages/server/src/server/workspace-registry.ts b/packages/server/src/server/workspace-registry.ts index fd376cc14c..04265da0c2 100644 --- a/packages/server/src/server/workspace-registry.ts +++ b/packages/server/src/server/workspace-registry.ts @@ -72,6 +72,7 @@ const PersistedWorkspaceRecordSchema = z.object({ .nullable() .optional() .transform((value) => value ?? null), + head: z.string().optional(), // Exact checkout/worktree root backing cwd. This differs from cwd when the // selected project is a subdirectory inside a repository. Persist it so // archive and recovery do not need the directory to still exist in order to @@ -126,6 +127,7 @@ export interface WorkspaceMutationContext { export interface WorkspaceArchiveContext { autoArchivedChangeRequestUrl?: string; + head?: string; } export interface ProjectMutation { @@ -586,6 +588,7 @@ export class FileBackedWorkspaceRegistry ...existing, updatedAt: archivedAt, archivedAt, + head: context?.head, ...(context?.autoArchivedChangeRequestUrl ? { autoArchivedChangeRequestUrl: context.autoArchivedChangeRequestUrl } : {}), diff --git a/packages/server/src/utils/worktree.posix.test.ts b/packages/server/src/utils/worktree.posix.test.ts index 35d59cce3f..5ee2ec5b1a 100644 --- a/packages/server/src/utils/worktree.posix.test.ts +++ b/packages/server/src/utils/worktree.posix.test.ts @@ -1406,6 +1406,32 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { rmSync(tempDir, { recursive: true, force: true }); }); + it("keeps an otherwise unreachable detached commit after deleting the worktree", async () => { + const result = await createWorktreePrimitive({ + cwd: repoDir, + worktreeSlug: "keep-commit", + source: { kind: "branch-off", baseBranch: "main", branchName: "feature/keep-commit" }, + paseoHome, + }); + execFileSync("git", ["checkout", "--detach"], { cwd: result.worktreePath }); + writeFileSync(join(result.worktreePath, "file.txt"), "detached change\n"); + execFileSync("git", ["add", "file.txt"], { cwd: result.worktreePath }); + execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "detached"], { + cwd: result.worktreePath, + }); + const commit = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: result.worktreePath, + encoding: "utf8", + }).trim(); + + await deletePaseoWorktree({ cwd: repoDir, worktreePath: result.worktreePath, paseoHome }); + execFileSync("git", ["reflog", "expire", "--expire=now", "--all"], { cwd: repoDir }); + execFileSync("git", ["gc", "--prune=now"], { cwd: repoDir }); + expect( + execFileSync("git", ["cat-file", "-t", commit], { cwd: repoDir, encoding: "utf8" }).trim(), + ).toBe("commit"); + }); + it("places, owns, lists, and deletes a worktree outside the legacy root", async () => { // Sibling layout: /wt- diff --git a/packages/server/src/utils/worktree.test.ts b/packages/server/src/utils/worktree.test.ts index f549b461f8..39f2af09c0 100644 --- a/packages/server/src/utils/worktree.test.ts +++ b/packages/server/src/utils/worktree.test.ts @@ -3,6 +3,7 @@ import { createWorktree as createWorktreePrimitive, deriveWorktreeProjectHash, deletePaseoWorktree, + readWorktreeHead, isPaseoOwnedWorktreeCwd, mapWorkspaceCwdToWorktree, runWorktreeTeardownCommands, @@ -302,6 +303,29 @@ describe("paseo worktree manager", () => { expect(existsSync(created.worktreePath)).toBe(false); }); + it("does not read a parent repository's HEAD when the worktree has no .git", async () => { + const directory = join(repoDir, "missing-worktree"); + mkdirSync(directory); + await expect(readWorktreeHead(directory)).resolves.toBeNull(); + }); + + it("keeps a worktree when writing its retention ref fails", async () => { + const created = await createLegacyWorktreeForTest({ + branchName: "ref-write-failure", + cwd: repoDir, + baseBranch: "main", + worktreeSlug: "ref-write-failure", + paseoHome, + }); + mkdirSync(join(repoDir, ".git", "refs", "paseo"), { recursive: true }); + writeFileSync(join(repoDir, ".git", "refs", "paseo", "kept-commits"), "blocked\n"); + + await expect( + deletePaseoWorktree({ cwd: repoDir, worktreePath: created.worktreePath, paseoHome }), + ).rejects.toThrow(); + expect(existsSync(created.worktreePath)).toBe(true); + }); + it("deletes a worktree when Git reports its source through native and long path spellings", async () => { const created = await createLegacyWorktreeForTest({ branchName: "identity-delete", diff --git a/packages/server/src/utils/worktree.ts b/packages/server/src/utils/worktree.ts index 2fc8bc05db..92e70c9e87 100644 --- a/packages/server/src/utils/worktree.ts +++ b/packages/server/src/utils/worktree.ts @@ -188,6 +188,7 @@ export type WorktreeSource = | { kind: "branch-off"; baseBranch: string; branchName: string } | { kind: "checkout-branch"; branchName: string } | { kind: "restore"; branchName: string; baseRef: string | null } + | { kind: "restore-commit"; commit: string; baseRef: string } | { kind: "restore-from-base"; baseRef: string; branchName: string } | { kind: "checkout-change-request"; @@ -1153,6 +1154,32 @@ async function assertWorktreeBelongsToRepo(cwd: string, worktreePath: string): P } } +export async function readWorktreeHead(worktreePath: string): Promise { + if (!(await pathExists(join(worktreePath, ".git")))) return null; + try { + const { stdout } = await runGitCommand(["rev-parse", "--verify", "HEAD^{commit}"], { + cwd: worktreePath, + }); + return stdout.trim(); + } catch { + return null; + } +} + +export async function readWorktreeHeadReference(worktreePath: string): Promise { + if (!(await pathExists(join(worktreePath, ".git")))) return null; + try { + const result = await runGitCommand(["symbolic-ref", "--quiet", "HEAD"], { + cwd: worktreePath, + acceptExitCodes: [0, 1], + }); + if (result.exitCode === 0) return result.stdout.trim(); + return readWorktreeHead(worktreePath); + } catch { + return null; + } +} + export async function deletePaseoWorktree({ cwd, worktreePath, @@ -1208,6 +1235,12 @@ export async function deletePaseoWorktree({ teardownCwd, }); } + const commit = await readWorktreeHead(resolvedWorktree); + if (commit) { + await runGitCommand(["update-ref", `refs/paseo/kept-commits/${commit}`, commit], { + cwd: resolvedWorktree, + }); + } } if (cwd) { @@ -1361,14 +1394,22 @@ export async function resolveDefaultWorktreePath( /** * Create a git worktree with proper naming conventions */ -export const createWorktree = async ({ +export function createWorktree( + options: CreateWorktreeOptions & { source: Exclude }, +): Promise; +export function createWorktree( + options: CreateWorktreeOptions, +): Promise & { branchName: string | null }>; +export async function createWorktree({ cwd, source, worktreeSlug, paseoHome, worktreesRoot, worktreePath: explicitWorktreePath, -}: CreateWorktreeOptions): Promise => { +}: CreateWorktreeOptions): Promise< + Omit & { branchName: string | null } +> { const branchesBefore = source.kind === "checkout-branch" || source.kind === "checkout-change-request" || @@ -1394,14 +1435,14 @@ export const createWorktree = async ({ }); worktreePath = await normalizePathForOwnership(worktreePath); - if (sourcePlan.pushRemote) { + if (sourcePlan.pushRemote && sourcePlan.branchName) { await configureWorktreePushRemote({ cwd, branchName: sourcePlan.branchName, remote: sourcePlan.pushRemote, }); } - if (sourcePlan.trackingRemote) { + if (sourcePlan.trackingRemote && sourcePlan.branchName) { await configureWorktreeTrackingRemote({ cwd, branchName: sourcePlan.branchName, @@ -1434,7 +1475,7 @@ export const createWorktree = async ({ } throw error; } -}; +} interface ResolveWorktreeSourcePlanOptions { cwd: string; @@ -1443,7 +1484,7 @@ interface ResolveWorktreeSourcePlanOptions { } interface WorktreeSourcePlan { - branchName: string; + branchName: string | null; // Display name and exact ref are two different facts. The name cannot round-trip to a // commit — "main" resolves local-first even when the worktree was cut from a fork's // upstream — so comparisons and actions read the ref and the UI reads the name. @@ -1492,6 +1533,26 @@ async function resolveRestoredWorktreeSourcePlan( }; } +async function resolveRestoredCommitSourcePlan( + cwd: string, + source: Extract, +): Promise { + let exactBase: string | undefined; + if (isQualifiedRef(source.baseRef)) { + try { + exactBase = await resolveBaseBranchForWorktree(cwd, source.baseRef); + } catch { + // Restore the saved commit even when its comparison ref no longer exists. + } + } + return { + branchName: null, + metadataBaseRefName: normalizeRequiredBaseBranch(source.baseRef), + ...(exactBase ? { metadataBaseRef: exactBase } : {}), + addArguments: ["--detach", source.commit], + }; +} + async function resolveRestoredWorktreeFromBasePlan( cwd: string, source: Extract, @@ -1544,6 +1605,8 @@ async function resolveWorktreeSourcePlan({ return resolveBranchOffWorktreeSourcePlan(cwd, source, desiredSlug); case "restore": return resolveRestoredWorktreeSourcePlan(cwd, source); + case "restore-commit": + return resolveRestoredCommitSourcePlan(cwd, source); case "restore-from-base": return resolveRestoredWorktreeFromBasePlan(cwd, source); case "checkout-branch": {