Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 224ba30fb3 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.
2026-11-17 17:06:27 +01:00
Mohamed Boudra 02d1068aab fix(workspaces): scope saved HEAD to each archive
An archive with no readable checkout must not retain the HEAD saved by an earlier archive.
2026-11-17 16:35:19 +01:00
Mohamed Boudra 5eff161fb8 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.
2026-11-17 16:25:28 +01:00
Mohamed Boudra a0c4865630 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.
2026-11-17 16:03:01 +01:00
Mohamed BoudraandOkan YILDIRIM e5021f89de 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>
2026-11-17 15:49:37 +01:00
20 changed files with 396 additions and 51 deletions
@@ -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 }) => {
+1 -2
View File
@@ -484,8 +484,7 @@ export const ar: TranslationResources = {
archivedTitle: "مساحة العمل مؤرشفة",
restoreDescription:
"استعد {{workspaceName}} للعودة إلى وكلائها. ستستخدم شجرة العمل الفرع {{branch}}.",
restoreWithoutBranchDescription:
"استعد {{workspaceName}} للعودة إلى وكلائها. سيبدأ فرع جديد من الفرع الأساسي المحفوظ أو الفرع الافتراضي للمستودع.",
restoreWithoutBranchDescription: "استعد {{workspaceName}} للعودة إلى وكلائها.",
unarchiveDescription: "{{workspaceName}} مؤرشفة. ألغِ أرشفتها لفتحها مجددًا.",
restoreAction: "استعادة",
unarchiveAction: "إلغاء الأرشفة",
+1 -2
View File
@@ -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",
+1 -2
View File
@@ -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",
+1 -2
View File
@@ -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",
+1 -2
View File
@@ -489,8 +489,7 @@ export const ja: TranslationResources = {
archivedTitle: "ワークスペースはアーカイブ済みです",
restoreDescription:
"{{workspaceName}} を復元してエージェントに戻ります。worktree ではブランチ {{branch}} を使用します。",
restoreWithoutBranchDescription:
"{{workspaceName}} を復元してエージェントに戻ります。保存されたベース、またはリポジトリのデフォルトブランチから新しいブランチを作成します。",
restoreWithoutBranchDescription: "{{workspaceName}} を復元してエージェントに戻ります。",
unarchiveDescription:
"{{workspaceName}} はアーカイブされています。再度開くにはアーカイブを解除してください。",
restoreAction: "復元",
+1 -2
View File
@@ -485,8 +485,7 @@ export const ko: TranslationResources = {
archivedTitle: "워크스페이스가 보관되었습니다",
restoreDescription:
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 워크트리는 {{branch}} 브랜치를 사용합니다.",
restoreWithoutBranchDescription:
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 저장된 기반 브랜치 또는 저장소 기본 브랜치에서 새 브랜치를 만듭니다.",
restoreWithoutBranchDescription: "{{workspaceName}}를 복원하여 에이전트로 돌아갑니다.",
unarchiveDescription: "{{workspaceName}}가 보관되었습니다. 다시 열려면 보관을 취소하세요.",
restoreAction: "복원",
unarchiveAction: "보관 취소",
+1 -2
View File
@@ -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",
+1 -1
View File
@@ -489,7 +489,7 @@ export const ru: TranslationResources = {
restoreDescription:
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Worktree будет использовать ветку {{branch}}.",
restoreWithoutBranchDescription:
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Новая ветка будет создана от сохранённой базовой или ветки репозитория по умолчанию.",
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам.",
unarchiveDescription:
"Рабочее пространство «{{workspaceName}}» находится в архиве. Разархивируйте его, чтобы снова открыть.",
restoreAction: "Восстановить",
+1 -2
View File
@@ -484,8 +484,7 @@ export const zhCN: TranslationResources = {
archivedTitle: "Workspace 已归档",
restoreDescription:
"恢复 {{workspaceName}} 以返回其中的代理。worktree 将使用分支 {{branch}}。",
restoreWithoutBranchDescription:
"恢复 {{workspaceName}} 以返回其中的代理。新分支将从保存的基准分支或仓库默认分支创建。",
restoreWithoutBranchDescription: "恢复 {{workspaceName}} 以返回其中的代理。",
unarchiveDescription: "{{workspaceName}} 已归档。取消归档以重新打开。",
restoreAction: "恢复",
unarchiveAction: "取消归档",
@@ -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();
@@ -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 {
@@ -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"], {
@@ -151,13 +151,27 @@ export function createWorkspaceRecoveryService(deps: {
workspace: PersistedWorkspaceRecord,
sourceRepoRoot: string,
): Promise<void> {
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 {
@@ -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;
}
@@ -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 () => {
@@ -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 }
: {}),
@@ -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: <repo-parent>/wt-<slug>
@@ -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",
+69 -6
View File
@@ -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<string | null> {
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<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,
@@ -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<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" ||
@@ -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<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],
};
}
async function resolveRestoredWorktreeFromBasePlan(
cwd: string,
source: Extract<WorktreeSource, { kind: "restore-from-base" }>,
@@ -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": {