From 5eff161fb83870201a410197b1cd0bb0a26b68d8 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 17 Nov 2026 16:25:28 +0100 Subject: [PATCH] fix(workspaces): preserve git HEAD identity through restore MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Record Git’s full HEAD ref or commit so restore can pass branch and detached checkouts to Git without guessing from a short name. --- .../resolve-worktree-creation-intent.ts | 2 +- .../session/checkout/checkout-session.test.ts | 2 +- .../workspace-recovery-service.test.ts | 61 ++++++++++++-- .../workspace-recovery-service.ts | 27 ++++++- .../server/workspace-archive-service.test.ts | 2 +- .../src/server/workspace-archive-service.ts | 21 ++--- .../server/src/server/workspace-registry.ts | 6 +- .../server/src/utils/worktree.posix.test.ts | 2 +- packages/server/src/utils/worktree.ts | 81 ++++++++++++++----- 9 files changed, 149 insertions(+), 55 deletions(-) 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/checkout/checkout-session.test.ts b/packages/server/src/server/session/checkout/checkout-session.test.ts index 52c8a68a82..61c9328e48 100644 --- a/packages/server/src/server/session/checkout/checkout-session.test.ts +++ b/packages/server/src/server/session/checkout/checkout-session.test.ts @@ -1756,7 +1756,7 @@ it("creates a PR from a restored exact base using the host metadata and a forge cwd: repo, paseoHome, worktreeSlug: "restored-pr", - source: { kind: "restore", ref: created.branchName, baseRef }, + source: { kind: "restore", branchName: created.branchName, baseRef }, }); const requests: Array[0]> = []; const service: ForgeService = { 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 9ba25790f1..e640d118e6 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 @@ -361,16 +361,12 @@ test("preserves ordinary checkout behavior when no separate base was recorded", ).toMatchObject({ currentBranch: "feature", baseRef: "feature" }); }); -test("records the branch and commit of an archived checkout", async () => { +test("records the full HEAD ref of an archived checkout", async () => { const fixture = await createBaseRecoveryFixture(null); - const commit = execFileSync("git", ["rev-parse", "feature"], { - cwd: fixture.repoDir, - encoding: "utf8", - }).trim(); await fixture.archiveAndRemove(); expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({ branch: "feature", - commit, + head: "refs/heads/feature", }); }); @@ -388,6 +384,55 @@ test("archives a workspace whose worktree Git administration is missing", async 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("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" }); @@ -463,8 +508,8 @@ test("restores the archived detached checkout at its recorded commit", async () }).trim(); await fixture.archiveAndRemove(); expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({ - branch: null, - commit, + branch: "feature", + head: commit, }); execFileSync("git", ["reflog", "expire", "--expire=now", "--all"], { cwd: fixture.repoDir }); execFileSync("git", ["gc", "--prune=now"], { cwd: fixture.repoDir }); 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 896615ec4d..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 @@ -152,13 +152,19 @@ export function createWorkspaceRecoveryService(deps: { sourceRepoRoot: string, ): Promise { let source: WorktreeSource; - const ref = workspace.branch ?? workspace.commit; - if (ref) { + const checkout = parseWorkspaceHead(workspace); + if (checkout.kind === "branch") { source = { kind: "restore", - ref, + 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", @@ -259,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.test.ts b/packages/server/src/server/workspace-archive-service.test.ts index e870367bd3..b5d656bf7c 100644 --- a/packages/server/src/server/workspace-archive-service.test.ts +++ b/packages/server/src/server/workspace-archive-service.test.ts @@ -210,7 +210,7 @@ describe("archiveByScope", () => { paseoHome, worktreeSlug: "external", worktreePath: recordedPath, - source: { kind: "restore", ref: "external", baseRef: "main" }, + source: { kind: "restore", branchName: "external", baseRef: "main" }, }); expect(existsSync(await getPaseoWorktreeMetadataPath(restored.worktreePath))).toBe(true); const workspaceId = "external-workspace"; diff --git a/packages/server/src/server/workspace-archive-service.ts b/packages/server/src/server/workspace-archive-service.ts index f0228ac492..5f6fb473e7 100644 --- a/packages/server/src/server/workspace-archive-service.ts +++ b/packages/server/src/server/workspace-archive-service.ts @@ -8,7 +8,7 @@ import type { WorkspaceGitService } from "./workspace-git-service.js"; import type { ForgeService } from "../services/forge-service.js"; import { deletePaseoWorktree, - readWorktreeHead, + readWorktreeHeadReference, isPaseoOwnedWorktreeCwd, runWorktreeTeardownCommands, WorktreeTeardownError, @@ -20,7 +20,7 @@ import type { WorkspaceRegistry, } from "./workspace-registry.js"; import { createRealpathAwarePathMatcher } from "../utils/path.js"; -import { runGitCommand, runWithGitCommandPriority } from "../utils/run-git-command.js"; +import { runWithGitCommandPriority } from "../utils/run-git-command.js"; import { WorkspaceAutomationBlockedError } from "./workspace-automation-gate.js"; export type ActiveWorkspaceRef = Pick< @@ -708,25 +708,14 @@ export async function archivePersistedWorkspaceRecord(input: { } const archivedAt = input.archivedAt ?? new Date().toISOString(); - let checkout: WorkspaceArchiveContext["checkout"]; + let head: string | null = null; if (existingWorkspace.kind === "worktree") { const cwd = existingWorkspace.worktreeRoot ?? existingWorkspace.cwd; - try { - const [commit, branch] = await Promise.all([ - readWorktreeHead(cwd), - runGitCommand(["symbolic-ref", "--quiet", "--short", "HEAD"], { - cwd, - acceptExitCodes: [0, 1], - }), - ]); - if (commit) checkout = { branch: branch.stdout.trim() || null, commit }; - } catch { - // An unavailable checkout retains its previously recorded placement. - } + head = await readWorktreeHeadReference(cwd); } await input.workspaceRegistry.archive(input.workspaceId, archivedAt, { ...input.context, - ...(checkout ? { checkout } : {}), + ...(head ? { head } : {}), }); return existingWorkspace; diff --git a/packages/server/src/server/workspace-registry.ts b/packages/server/src/server/workspace-registry.ts index 946c33f509..4833cb62fc 100644 --- a/packages/server/src/server/workspace-registry.ts +++ b/packages/server/src/server/workspace-registry.ts @@ -72,7 +72,7 @@ const PersistedWorkspaceRecordSchema = z.object({ .nullable() .optional() .transform((value) => value ?? null), - commit: z.string().optional(), + 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 @@ -127,7 +127,7 @@ export interface WorkspaceMutationContext { export interface WorkspaceArchiveContext { autoArchivedChangeRequestUrl?: string; - checkout?: { branch: string | null; commit: string }; + head?: string; } export interface ProjectMutation { @@ -588,7 +588,7 @@ export class FileBackedWorkspaceRegistry ...existing, updatedAt: archivedAt, archivedAt, - ...context?.checkout, + ...(context?.head ? { 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 d7feb05d89..5ee2ec5b1a 100644 --- a/packages/server/src/utils/worktree.posix.test.ts +++ b/packages/server/src/utils/worktree.posix.test.ts @@ -1562,7 +1562,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { const restored = await createWorktreePrimitive({ cwd: repoDir, worktreeSlug: "restorable", - source: { kind: "restore", ref: "feature/restorable", baseRef: "main" }, + source: { kind: "restore", branchName: "feature/restorable", baseRef: "main" }, paseoHome, worktreePath: created.worktreePath, }); diff --git a/packages/server/src/utils/worktree.ts b/packages/server/src/utils/worktree.ts index fc06122476..92e70c9e87 100644 --- a/packages/server/src/utils/worktree.ts +++ b/packages/server/src/utils/worktree.ts @@ -187,7 +187,8 @@ export interface WorktreeCheckoutRef { export type WorktreeSource = | { kind: "branch-off"; baseBranch: string; branchName: string } | { kind: "checkout-branch"; branchName: string } - | { kind: "restore"; ref: string; baseRef: string | null } + | { 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"; @@ -1165,6 +1166,20 @@ export async function readWorktreeHead(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, @@ -1379,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" || @@ -1412,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, @@ -1452,7 +1475,7 @@ export const createWorktree = async ({ } throw error; } -}; +} interface ResolveWorktreeSourcePlanOptions { cwd: string; @@ -1461,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. @@ -1485,14 +1508,10 @@ async function resolveRestoredWorktreeSourcePlan( cwd: string, source: Extract, ): Promise { - await validateGitBranchName(cwd, source.ref); - try { - await runGitCommand(["rev-parse", "--verify", `${source.ref}^{commit}`], { cwd }); - } catch { - await ensureLocalBranch(cwd, source.ref); - } - if (await isBranchCheckedOut(cwd, source.ref)) { - throw new BranchAlreadyCheckedOutError(source.ref); + await validateGitBranchName(cwd, source.branchName); + await ensureLocalBranch(cwd, source.branchName); + if (await isBranchCheckedOut(cwd, source.branchName)) { + throw new BranchAlreadyCheckedOutError(source.branchName); } let exactBase: string | undefined; if (source.baseRef && isQualifiedRef(source.baseRef)) { @@ -1503,14 +1522,34 @@ async function resolveRestoredWorktreeSourcePlan( } } return { - branchName: source.ref, - metadataBaseRefName: normalizeRequiredBaseBranch(source.baseRef ?? source.ref), + branchName: source.branchName, + metadataBaseRefName: normalizeRequiredBaseBranch(source.baseRef ?? source.branchName), ...(exactBase ? { metadataBaseRef: exactBase } : {}), changeRequestLookupTarget: createPaseoWorktreeChangeRequestHint({ - headRef: source.ref, - localBranchName: source.ref, + headRef: source.branchName, + localBranchName: source.branchName, }), - addArguments: [source.ref], + addArguments: [source.branchName], + }; +} + +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], }; } @@ -1566,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": {