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.
This commit is contained in:
Mohamed Boudra
2026-11-17 16:25:28 +01:00
parent a0c4865630
commit 5eff161fb8
9 changed files with 149 additions and 55 deletions
@@ -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 {
@@ -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<Parameters<ForgeService["createPullRequest"]>[0]> = [];
const service: ForgeService = {
@@ -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 });
@@ -152,13 +152,19 @@ export function createWorkspaceRecoveryService(deps: {
sourceRepoRoot: string,
): Promise<void> {
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 {
@@ -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";
@@ -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;
@@ -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 }
: {}),
@@ -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,
});
+61 -20
View File
@@ -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<string | n
}
}
export async function readWorktreeHeadReference(worktreePath: string): Promise<string | null> {
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<WorktreeSource, { kind: "restore-commit" }> },
): Promise<CreatedWorktree>;
export function createWorktree(
options: CreateWorktreeOptions,
): Promise<Omit<CreatedWorktree, "branchName"> & { branchName: string | null }>;
export async function createWorktree({
cwd,
source,
worktreeSlug,
paseoHome,
worktreesRoot,
worktreePath: explicitWorktreePath,
}: CreateWorktreeOptions): Promise<CreatedWorktree> => {
}: CreateWorktreeOptions): Promise<
Omit<CreatedWorktree, "branchName"> & { 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<WorktreeSource, { kind: "restore" }>,
): Promise<WorktreeSourcePlan> {
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<WorktreeSource, { kind: "restore-commit" }>,
): Promise<WorktreeSourcePlan> {
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": {