From c9ec9863ba78aa355ebcd8b4b13458c758543ded Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:38:31 +0700 Subject: [PATCH] Keep worktrees with uncommitted changes when archiving (#11430) * fix(archive): keep worktrees with uncommitted changes Archive used forced Git removal after workspace teardown, even when a file appeared after a clean status check. Check the worktree after teardown and preserve it unless the caller explicitly requests forced removal. * Remove clean worktrees with initialized submodules --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../internal/archive-selected.ts | 9 +- .../archive-undo/internal/undo-window.tsx | 7 +- .../src/workspace/use-workspace-archive.ts | 74 ++++++++------- .../app/src/workspace/workspace-archive.ts | 25 +++-- .../cli/src/commands/workspace/archive.ts | 20 +++- packages/cli/src/commands/workspace/index.ts | 5 +- packages/cli/src/commands/worktree/archive.ts | 85 ++++++++++------- packages/cli/src/commands/worktree/index.ts | 5 +- packages/cli/tests/14-worktree.test.ts | 1 + packages/client/src/daemon-client-core.ts | 4 + packages/protocol/src/messages.ts | 6 ++ .../src/server/agent/mcp-parity.e2e.test.ts | 32 ++++++- .../src/server/agent/tools/paseo-tools.ts | 12 ++- .../src/server/plugins/lifecycle.e2e.test.ts | 6 +- .../plugins/worktree-manager.e2e.test.ts | 28 +++++- packages/server/src/server/session.ts | 4 + .../workspace-archive-operations.test.ts | 19 ++++ .../server/workspace-archive-operations.ts | 12 ++- ...orkspace-archive-record-scoped.e2e.test.ts | 95 +++++++++++++++++-- .../server/workspace-archive-service.test.ts | 28 ++++-- .../src/server/workspace-archive-service.ts | 18 ++-- .../server/src/server/worktree-session.ts | 3 + .../server/src/server/worktree/commands.ts | 13 ++- packages/server/src/utils/worktree.test.ts | 50 ++++++++++ packages/server/src/utils/worktree.ts | 49 +++++++++- 25 files changed, 483 insertions(+), 127 deletions(-) diff --git a/packages/app/src/sidebar-selection/internal/archive-selected.ts b/packages/app/src/sidebar-selection/internal/archive-selected.ts index ede57574c1..38ece36bad 100644 --- a/packages/app/src/sidebar-selection/internal/archive-selected.ts +++ b/packages/app/src/sidebar-selection/internal/archive-selected.ts @@ -100,12 +100,14 @@ export async function archiveSelectedWorkspaces(input: { } const riskyWorkspaces: WorktreeArchiveConfirmationInput[] = []; + const dirtyWorktrees = new Set(); const worktrees = resolved.filter((item) => item.entry.workspaceKind === "worktree"); if (worktrees.length > 0) { try { const risks = await Promise.all( worktrees.map(async ({ entry, client }) => { const risk = await deps.readWorktreeRisk(client, entry.workspaceDirectory); + if (risk.isDirty) dirtyWorktrees.add(entry); return { workspaceName: entry.name, diffStat: entry.diffStat, @@ -162,6 +164,7 @@ export async function archiveSelectedWorkspaces(input: { return { client, workspace, + force: dirtyWorktrees.has(entry) || undefined, onArchiveCommitted: () => deps.purgeWorkspaceState(workspace), }; }), @@ -175,7 +178,11 @@ export async function archiveSelectedWorkspaces(input: { ...legacy.map(async ({ entry, client }) => { const workspace = { serverId: entry.serverId, workspaceId: entry.workspaceId }; try { - await deps.archiveWithoutUndo({ client, workspace }); + await deps.archiveWithoutUndo({ + client, + workspace, + force: dirtyWorktrees.has(entry) || undefined, + }); deps.purgeWorkspaceState(workspace); } catch (error) { failures.push({ error }); diff --git a/packages/app/src/workspace/archive-undo/internal/undo-window.tsx b/packages/app/src/workspace/archive-undo/internal/undo-window.tsx index 94a5a8f4ad..6428f7f795 100644 --- a/packages/app/src/workspace/archive-undo/internal/undo-window.tsx +++ b/packages/app/src/workspace/archive-undo/internal/undo-window.tsx @@ -6,20 +6,21 @@ import { isWorkspaceListed, undoWorkspaceArchiveOptimistically, type WorkspaceArchiveTarget, + type WorkspaceArchiveClient, } from "@/workspace/workspace-archive"; import { WorkspaceArchivedToast } from "./workspace-archived-toast"; /** How long the archived toast, and with it the chance to undo, stays up. */ export const WORKSPACE_ARCHIVE_UNDO_WINDOW_MS = 6000; -export interface UndoableWorkspaceArchiveClient { - archiveWorkspace: (workspaceId: string) => Promise<{ error: string | null; canceled?: boolean }>; +export interface UndoableWorkspaceArchiveClient extends WorkspaceArchiveClient { undoWorkspaceArchive: (workspaceId: string) => Promise; } export interface UndoableWorkspaceArchiveEntryInput { client: UndoableWorkspaceArchiveClient; workspace: WorkspaceArchiveTarget; + force?: boolean; onArchiveCommitted: () => void; } @@ -229,6 +230,7 @@ export async function archiveWorkspacesWithUndo(input: { export async function archiveWorkspaceWithUndo(input: { client: UndoableWorkspaceArchiveClient; workspace: WorkspaceArchiveTarget; + force?: boolean; toast: ToastApi; onArchiveCommitted: () => void; }): Promise { @@ -237,6 +239,7 @@ export async function archiveWorkspaceWithUndo(input: { { client: input.client, workspace: input.workspace, + force: input.force, onArchiveCommitted: input.onArchiveCommitted, }, ], diff --git a/packages/app/src/workspace/use-workspace-archive.ts b/packages/app/src/workspace/use-workspace-archive.ts index 5a01b1015b..db0a564076 100644 --- a/packages/app/src/workspace/use-workspace-archive.ts +++ b/packages/app/src/workspace/use-workspace-archive.ts @@ -62,44 +62,47 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch const onArchiveStartedRef = useRef(onArchiveStarted); onArchiveStartedRef.current = onArchiveStarted; - const archiveWorkspaceRecord = useCallback(async () => { - const client = getHostRuntimeStore().getClient(serverId); - if (!client) { - toast.error(t("sidebar.workspace.toasts.hostDisconnected")); - return; - } - const workspace = { serverId, workspaceId }; - onSetHiding?.(true); - try { - onArchiveStartedRef.current(workspace); - if (supportsWorkspaceArchiveUndo(serverId)) { - await archiveWorkspaceWithUndo({ - client, - workspace, - toast, - onArchiveCommitted: () => purgeArchivedWorkspaceState(workspace), - }); - } else { - // COMPAT(workspaceArchiveUndo): hosts before v0.15.3 cannot undo; remove after 2027-05-06. - await archiveWorkspaceOptimistically({ client, workspace }); - purgeArchivedWorkspaceState(workspace); + const archiveWorkspaceRecord = useCallback( + async (options?: { force: boolean }) => { + const client = getHostRuntimeStore().getClient(serverId); + if (!client) { + toast.error(t("sidebar.workspace.toasts.hostDisconnected")); + return; } - } catch (error) { - toast.error( - error instanceof Error ? error.message : t("sidebar.workspace.toasts.archiveFailed"), - ); - } finally { - onSetHiding?.(false); - } - }, [onSetHiding, serverId, t, toast, workspaceId]); + const workspace = { serverId, workspaceId }; + onSetHiding?.(true); + try { + onArchiveStartedRef.current(workspace); + if (supportsWorkspaceArchiveUndo(serverId)) { + await archiveWorkspaceWithUndo({ + client, + workspace, + force: options?.force, + toast, + onArchiveCommitted: () => purgeArchivedWorkspaceState(workspace), + }); + } else { + // COMPAT(workspaceArchiveUndo): hosts before v0.15.3 cannot undo; remove after 2027-05-06. + await archiveWorkspaceOptimistically({ client, workspace, force: options?.force }); + purgeArchivedWorkspaceState(workspace); + } + } catch (error) { + toast.error( + error instanceof Error ? error.message : t("sidebar.workspace.toasts.archiveFailed"), + ); + } finally { + onSetHiding?.(false); + } + }, + [onSetHiding, serverId, t, toast, workspaceId], + ); - // The host removes a worktree it archives, uncommitted work included. Ask it what that would - // lose: the sidebar row's git status is empty until the row receives it. - const confirmWorktreeArchive = useCallback(async (): Promise => { + // Ask the host what the archive would lose. The sidebar may not have loaded Git status. + const confirmWorktreeArchive = useCallback(async (): Promise<{ force: boolean } | null> => { const client = getHostRuntimeStore().getClient(serverId); if (!client) { toast.error(t("sidebar.workspace.toasts.hostDisconnected")); - return false; + return null; } const risk = await readWorktreeArchiveRisk(client, workspaceDirectory).catch( (error: unknown) => { @@ -110,12 +113,13 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch }, ); if (!risk) { - return false; + return null; } - return await confirmRiskyWorktreeArchive( + const confirmed = await confirmRiskyWorktreeArchive( { workspaceName: name, diffStat, ...risk }, warningLabels, ); + return confirmed ? { force: risk.isDirty === true } : null; }, [diffStat, name, serverId, t, toast, warningLabels, workspaceDirectory]); const archive = useCallback(() => { diff --git a/packages/app/src/workspace/workspace-archive.ts b/packages/app/src/workspace/workspace-archive.ts index ab3ff94e79..278869d916 100644 --- a/packages/app/src/workspace/workspace-archive.ts +++ b/packages/app/src/workspace/workspace-archive.ts @@ -26,8 +26,8 @@ const pendingArchiveAttempts = new Set(); /** Checks and starts one archive at a time for a workspace. */ export async function runWorkspaceArchiveAttempt(input: { workspace: WorkspaceArchiveTarget; - confirm?: () => Promise; - archive: () => Promise; + confirm?: () => Promise<{ force: boolean } | null>; + archive: (options?: { force: boolean }) => Promise; }): Promise { const { serverId, workspaceId } = input.workspace; const key = JSON.stringify([serverId, workspaceId]); @@ -35,18 +35,23 @@ export async function runWorkspaceArchiveAttempt(input: { pendingArchiveAttempts.add(key); try { - if (input.confirm && !(await input.confirm())) return; + const confirmed = input.confirm ? await input.confirm() : undefined; + if (confirmed === null) return; if (!isWorkspaceListed(input.workspace)) return; // Archive hides the row synchronously. Undo can restore it and start a new // archive while the previous daemon request is still settling. - return input.archive(); + return input.archive(confirmed); } finally { pendingArchiveAttempts.delete(key); } } -interface WorkspaceArchiveClient { - archiveWorkspace: (workspaceId: string) => Promise<{ error: string | null; canceled?: boolean }>; +export interface WorkspaceArchiveClient { + archiveWorkspace: ( + workspaceId: string, + requestId?: string, + options?: { force?: boolean }, + ) => Promise<{ error: string | null; canceled?: boolean }>; } interface WorkspaceArchiveUndoClient { @@ -158,8 +163,11 @@ function invalidateAgentHistory(serverId: string): void { async function archiveWorkspaceOrThrow(input: { client: WorkspaceArchiveClient; workspaceId: string; + force?: boolean; }): Promise { - const payload = await input.client.archiveWorkspace(input.workspaceId); + const payload = input.force + ? await input.client.archiveWorkspace(input.workspaceId, undefined, { force: true }) + : await input.client.archiveWorkspace(input.workspaceId); if (payload.canceled) { return "canceled"; } @@ -176,6 +184,7 @@ async function archiveWorkspaceOrThrow(input: { export function beginOptimisticWorkspaceArchive(input: { client: WorkspaceArchiveClient; workspace: WorkspaceArchiveTarget; + force?: boolean; }): OptimisticWorkspaceArchive { const snapshot = hideWorkspaceOptimistically(input.workspace); const done = (async () => { @@ -183,6 +192,7 @@ export function beginOptimisticWorkspaceArchive(input: { const outcome = await archiveWorkspaceOrThrow({ client: input.client, workspaceId: input.workspace.workspaceId, + force: input.force, }); if (outcome === "canceled") { restoreOptimisticallyHiddenWorkspace({ serverId: input.workspace.serverId, snapshot }); @@ -201,6 +211,7 @@ export function beginOptimisticWorkspaceArchive(input: { export async function archiveWorkspaceOptimistically(input: { client: WorkspaceArchiveClient; workspace: WorkspaceArchiveTarget; + force?: boolean; }): Promise { return beginOptimisticWorkspaceArchive(input).done; } diff --git a/packages/cli/src/commands/workspace/archive.ts b/packages/cli/src/commands/workspace/archive.ts index a9dad90e91..f096e44551 100644 --- a/packages/cli/src/commands/workspace/archive.ts +++ b/packages/cli/src/commands/workspace/archive.ts @@ -6,6 +6,8 @@ interface WorkspaceArchiveResult { workspaceId: string; status: "archived"; archivedAt: string; + removedDirectory?: boolean; + directoryLeftBehind?: { path: string; reason: string }; } const workspaceArchiveSchema: OutputSchema = { @@ -14,12 +16,18 @@ const workspaceArchiveSchema: OutputSchema = { { header: "WORKSPACE ID", field: "workspaceId", width: 20 }, { header: "STATUS", field: "status", width: 10 }, { header: "ARCHIVED AT", field: "archivedAt", width: 26 }, + { header: "RETAINED PATH", field: (item) => item.directoryLeftBehind?.path }, + { header: "REASON", field: (item) => item.directoryLeftBehind?.reason }, ], }; export async function runArchiveCommand( workspaceId: string, - options: { host?: string; daemonTarget: import("../../utils/daemon-target.js").DaemonTarget }, + options: { + host?: string; + force?: boolean; + daemonTarget: import("../../utils/daemon-target.js").DaemonTarget; + }, _command: Command, ): Promise> { const host = getDaemonHost({ target: options.daemonTarget }); @@ -31,7 +39,7 @@ export async function runArchiveCommand( } satisfies CommandError; }); try { - const payload = await client.archiveWorkspace(workspaceId); + const payload = await client.archiveWorkspace(workspaceId, undefined, { force: options.force }); if (payload.error) { throw new Error(payload.error); } @@ -40,7 +48,13 @@ export async function runArchiveCommand( } return { type: "single", - data: { workspaceId, status: "archived", archivedAt: payload.archivedAt }, + data: { + workspaceId, + status: "archived", + archivedAt: payload.archivedAt, + removedDirectory: payload.removedDirectory, + directoryLeftBehind: payload.directoryLeftBehind, + }, schema: workspaceArchiveSchema, }; } catch (error) { diff --git a/packages/cli/src/commands/workspace/index.ts b/packages/cli/src/commands/workspace/index.ts index 7d15ef26f3..493f1e58b8 100644 --- a/packages/cli/src/commands/workspace/index.ts +++ b/packages/cli/src/commands/workspace/index.ts @@ -61,8 +61,9 @@ export function createWorkspaceCommand(): Command { addJsonAndDaemonHostOptions( workspace .command("archive") - .description("Archive a workspace and everything it owns") - .argument("", "Workspace id"), + .description("Archive a workspace and keep any worktree with uncommitted changes") + .argument("", "Workspace id") + .option("--force", "Remove the worktree even if it has uncommitted changes"), ).action(withOutput(runArchiveCommand)); return workspace; diff --git a/packages/cli/src/commands/worktree/archive.ts b/packages/cli/src/commands/worktree/archive.ts index 5d2bc60f33..18d7efa3f3 100644 --- a/packages/cli/src/commands/worktree/archive.ts +++ b/packages/cli/src/commands/worktree/archive.ts @@ -15,6 +15,8 @@ export interface WorktreeArchiveResult { name: string; status: "archived"; removedAgents: string[]; + removedDirectory?: boolean; + directoryLeftBehind?: { path: string; reason: string }; } /** Schema for archive command output */ @@ -23,6 +25,8 @@ export const archiveSchema: OutputSchema = { columns: [ { header: "NAME", field: "name" }, { header: "STATUS", field: "status" }, + { header: "RETAINED PATH", field: (item) => item.directoryLeftBehind?.path }, + { header: "REASON", field: (item) => item.directoryLeftBehind?.reason }, { header: "REMOVED AGENTS", field: (item) => (item.removedAgents.length > 0 ? item.removedAgents.join(", ") : "-"), @@ -33,6 +37,7 @@ export const archiveSchema: OutputSchema = { export interface WorktreeArchiveOptions extends CommandOptions { host?: string; cwd?: string; + force?: boolean; } export type WorktreeArchiveCommandResult = SingleResult; @@ -78,41 +83,13 @@ export async function runArchiveCommandWithDeps( } try { - // Get the list of worktrees first to resolve the name - const listResponse = await client.getPaseoWorktreeList({ cwd }); - - if (listResponse.error) { - const error: CommandError = { - code: "WORKTREE_LIST_FAILED", - message: `Failed to list worktrees: ${listResponse.error.message}`, - }; - throw error; - } - - // Find the worktree by name or branch - const worktree = listResponse.worktrees.find((wt) => { - const name = path.basename(wt.worktreePath); - return name === nameArg || wt.branchName === nameArg; - }); - - if (!worktree) { - const error: CommandError = { - code: "WORKTREE_NOT_FOUND", - message: `Worktree not found: ${nameArg}`, - details: 'Use "paseo worktree ls" to list available worktrees', - }; - throw error; - } - - // Archive the worktree. scope:"worktree" archives every active workspace on - // the directory and then removes the directory (Paseo-owned gated). + const worktreePath = await resolveWorktreePath(client, cwd, nameArg); const response = await client.archivePaseoWorktree({ - worktreePath: worktree.worktreePath, + worktreePath, scope: "worktree", + force: options.force, }); - await client.close(); - if (response.error) { const error: CommandError = { code: "WORKTREE_ARCHIVE_FAILED", @@ -121,7 +98,7 @@ export async function runArchiveCommandWithDeps( throw error; } - const worktreeName = path.basename(worktree.worktreePath) || nameArg; + const worktreeName = basename(worktreePath) || nameArg; return { type: "single", @@ -129,12 +106,12 @@ export async function runArchiveCommandWithDeps( name: worktreeName, status: "archived", removedAgents: response.removedAgents ?? [], + removedDirectory: response.removedDirectory, + directoryLeftBehind: response.directoryLeftBehind, }, schema: archiveSchema, }; } catch (err) { - await client.close().catch(() => {}); - // Re-throw CommandError as-is if (err && typeof err === "object" && "code" in err) { throw err; @@ -146,5 +123,45 @@ export async function runArchiveCommandWithDeps( message: `Failed to archive worktree: ${message}`, }; throw error; + } finally { + await client.close().catch(() => {}); } } + +async function resolveWorktreePath( + client: DaemonClient, + cwd: string, + name: string, +): Promise { + if (path.posix.isAbsolute(name) || path.win32.isAbsolute(name)) return name; + + const listResponse = await client.getPaseoWorktreeList({ cwd }); + + if (listResponse.error) { + const error: CommandError = { + code: "WORKTREE_LIST_FAILED", + message: `Failed to list worktrees: ${listResponse.error.message}`, + }; + throw error; + } + + const worktree = listResponse.worktrees.find( + (entry) => basename(entry.worktreePath) === name || entry.branchName === name, + ); + + if (!worktree) { + const error: CommandError = { + code: "WORKTREE_NOT_FOUND", + message: `Worktree not found: ${name}`, + details: 'Use "paseo worktree ls" to list available worktrees', + }; + throw error; + } + return worktree.worktreePath; +} + +function basename(worktreePath: string): string { + return path.posix.isAbsolute(worktreePath) + ? path.posix.basename(worktreePath) + : path.win32.basename(worktreePath); +} diff --git a/packages/cli/src/commands/worktree/index.ts b/packages/cli/src/commands/worktree/index.ts index 37405e2630..e3ceb4ffd3 100644 --- a/packages/cli/src/commands/worktree/index.ts +++ b/packages/cli/src/commands/worktree/index.ts @@ -33,8 +33,9 @@ export function createWorktreeCommand(): Command { addJsonAndDaemonHostOptions( worktree .command("archive") - .description("Archive a worktree (removes worktree and associated branch)") - .argument("", "Worktree name or branch name") + .description("Archive a worktree, keeping the branch and any uncommitted work by default") + .option("--force", "Remove the directory even if it has uncommitted changes") + .argument("", "Worktree name, branch name, or absolute path") .option("--cwd ", "Repository directory (default: current)"), ).action(withOutput(runArchiveCommand)); diff --git a/packages/cli/tests/14-worktree.test.ts b/packages/cli/tests/14-worktree.test.ts index 9ae293bf11..76e66ff93a 100644 --- a/packages/cli/tests/14-worktree.test.ts +++ b/packages/cli/tests/14-worktree.test.ts @@ -92,6 +92,7 @@ try { assert(result.stdout.includes("--host"), "help should mention --host option"); assert(result.stdout.includes("--cwd"), "help should mention --cwd option"); assert(result.stdout.includes(""), "help should mention required name argument"); + assert(result.stdout.includes("--force"), "help should mention --force option"); console.log("✓ worktree archive --help shows options\n"); } diff --git a/packages/client/src/daemon-client-core.ts b/packages/client/src/daemon-client-core.ts index 292f06a7d1..3b02c2eb98 100644 --- a/packages/client/src/daemon-client-core.ts +++ b/packages/client/src/daemon-client-core.ts @@ -3411,12 +3411,14 @@ export class DaemonClientCore { async archiveWorkspace( workspaceId: string, requestId?: string, + options?: { force?: boolean }, ): Promise { return this.sendCorrelatedSessionRequest({ requestId, message: { type: "archive_workspace_request", workspaceId, + ...(options?.force === true ? { force: true } : {}), }, responseType: "archive_workspace_response", // Archive may wait for a queued checkout operation and then run teardown/manager removal, @@ -5648,6 +5650,7 @@ export class DaemonClientCore { branchName?: string; workspaceId?: string; scope?: "workspace" | "worktree"; + force?: boolean; }, requestId?: string, ): Promise { @@ -5660,6 +5663,7 @@ export class DaemonClientCore { branchName: input.branchName, ...(input.workspaceId !== undefined ? { workspaceId: input.workspaceId } : {}), ...(input.scope !== undefined ? { scope: input.scope } : {}), + ...(input.force ? { force: true } : {}), }, responseType: "paseo_worktree_archive_response", // Archive may wait for a queued checkout operation and then run teardown/manager removal, diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index b816834b30..a26991e89a 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -2957,6 +2957,7 @@ export const PaseoWorktreeArchiveRequestSchema = z.object({ // cwd resolves to the target directory, then removes the directory if it is // Paseo-owned. Omitted/unknown values default to "workspace" for old-client safety. scope: z.enum(["workspace", "worktree"]).optional().default("workspace"), + force: z.boolean().optional(), // COMPAT(worktreeDiskDeletion): added in v0.1.97, ignored as of v0.1.97 // (disk removal derived from scope + last-reference + ownership); field // retained for wire parse-compat, drop when floor >= v0.1.97. @@ -3073,6 +3074,7 @@ export const ProjectGithubCloneRequestSchema = z.object({ export const ArchiveWorkspaceRequestSchema = z.object({ type: z.literal("archive_workspace_request"), workspaceId: z.string(), + force: z.boolean().optional(), requestId: z.string(), }); @@ -5274,6 +5276,8 @@ export const ArchiveWorkspaceResponseMessageSchema = z.object({ workspaceId: z.string(), archivedAt: z.string().nullable(), error: z.string().nullable(), + removedDirectory: z.boolean().optional(), + directoryLeftBehind: z.object({ path: z.string(), reason: z.string() }).optional(), // An undo stopped this archive before it finished; `error` carries the reason. canceled: z.boolean().optional(), }), @@ -6825,6 +6829,8 @@ export const PaseoWorktreeArchiveResponseSchema = z.object({ payload: z.object({ success: z.boolean(), removedAgents: z.array(z.string()).optional(), + removedDirectory: z.boolean().optional(), + directoryLeftBehind: z.object({ path: z.string(), reason: z.string() }).optional(), error: CheckoutErrorSchema.nullable(), requestId: z.string(), }), diff --git a/packages/server/src/server/agent/mcp-parity.e2e.test.ts b/packages/server/src/server/agent/mcp-parity.e2e.test.ts index 2cea0c69bc..47a47bb5f4 100644 --- a/packages/server/src/server/agent/mcp-parity.e2e.test.ts +++ b/packages/server/src/server/agent/mcp-parity.e2e.test.ts @@ -1,7 +1,7 @@ import os from "node:os"; import path from "node:path"; import { execSync } from "node:child_process"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { afterAll, beforeAll, describe, expect, test } from "vitest"; import { experimental_createMCPClient } from "ai"; import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; @@ -1154,6 +1154,36 @@ describe("Suite D: Provider Tools", () => { }); describe("Suite E: Workspace Tools", () => { + test.each([false, true])( + "archive_workspace respects force=%s for untracked files", + async (force) => { + const created = await callToolStructured(topLevelClient, "create_workspace", { + isolation: "worktree", + path: worktreeRepoCwd, + baseBranch: "main", + branchName: `parity-archive-${force}`, + }); + const cwd = str(created.cwd); + const file = path.join(cwd, "untracked.txt"); + await writeFile(file, "keep this file"); + + const result = await callToolStructured(topLevelClient, "archive_workspace", { + workspaceId: str(created.workspaceId), + ...(force ? { force } : {}), + }); + expect(result.removedDirectory).toBe(force); + if (force) { + await expect(readFile(file, "utf8")).rejects.toMatchObject({ code: "ENOENT" }); + } else { + expect(result.directoryLeftBehind).toEqual({ + path: cwd, + reason: "The worktree has uncommitted changes.", + }); + await expect(readFile(file, "utf8")).resolves.toBe("keep this file"); + } + }, + ); + test("background worktree creation, discovery and archive use ordinary workspace ownership", async () => { const created = await callToolStructured(topLevelClient, "create_workspace", { isolation: "worktree", diff --git a/packages/server/src/server/agent/tools/paseo-tools.ts b/packages/server/src/server/agent/tools/paseo-tools.ts index 8a278425f6..fc2aa7e456 100644 --- a/packages/server/src/server/agent/tools/paseo-tools.ts +++ b/packages/server/src/server/agent/tools/paseo-tools.ts @@ -1652,15 +1652,17 @@ function createToolCatalog( "archive_workspace", { title: "Archive workspace", - description: "Archive a workspace and everything it owns.", - inputSchema: { workspaceId: z.string().min(1) }, + description: + "Archive a workspace. Keep worktrees with uncommitted changes unless force is true.", + inputSchema: { workspaceId: z.string().min(1), force: z.boolean().optional() }, outputSchema: { workspaceId: z.string(), archivedAgentIds: z.array(z.string()), removedDirectory: z.boolean(), + directoryLeftBehind: z.object({ path: z.string(), reason: z.string() }).optional(), }, }, - async ({ workspaceId }) => { + async ({ workspaceId, force }) => { if (!options.listActiveWorkspaces) { throw new Error("Active workspace lister is required to archive workspaces"); } @@ -1677,6 +1679,7 @@ function createToolCatalog( }), { requestId: "mcp:archive_workspace", + force, scope: { kind: "workspace", workspaceId: workspace.workspaceId }, }, ); @@ -1686,6 +1689,9 @@ function createToolCatalog( workspaceId, archivedAgentIds: result.archivedAgentIds, removedDirectory: result.removedDirectory, + ...(result.directoryLeftBehind + ? { directoryLeftBehind: result.directoryLeftBehind } + : {}), }), }; }, diff --git a/packages/server/src/server/plugins/lifecycle.e2e.test.ts b/packages/server/src/server/plugins/lifecycle.e2e.test.ts index 606adfccff..7bc322b336 100644 --- a/packages/server/src/server/plugins/lifecycle.e2e.test.ts +++ b/packages/server/src/server/plugins/lifecycle.e2e.test.ts @@ -1500,7 +1500,11 @@ test.each([false, true])( expect((await client.fetchWorkspaces()).entries.map((workspace) => workspace.id)).toContain( created.workspace!.id, ); - await client.archiveWorkspace(created.workspace!.id); + // The hook creates an untracked fixture. This flow needs to restore after disk removal. + const archived = await client.archiveWorkspace(created.workspace!.id, undefined, { + force: true, + }); + expect(archived.removedDirectory).toBe(true); await expect(stat(cwd)).rejects.toMatchObject({ code: "ENOENT" }); const hookRecordsBeforeRestore = await readFile(orderFile, "utf8"); await client.close(); diff --git a/packages/server/src/server/plugins/worktree-manager.e2e.test.ts b/packages/server/src/server/plugins/worktree-manager.e2e.test.ts index 85a6831371..86d1e874e4 100644 --- a/packages/server/src/server/plugins/worktree-manager.e2e.test.ts +++ b/packages/server/src/server/plugins/worktree-manager.e2e.test.ts @@ -268,7 +268,14 @@ export default function contribute(server) { expect(await readFile(path.join(retriedAfterPath, ".wt-hook-ran"), "utf8")).toBe("pre-start"); // Archive delegates removal to `wt remove` (run from repoRoot) AFTER Paseo writes refs/paseo/kept-commits/*. - const archived = await client.archiveWorkspace(workspaceId); + const retained = await client.archiveWorkspace(workspaceId); + expect(retained).toMatchObject({ + error: null, + removedDirectory: false, + directoryLeftBehind: { path: worktreePath }, + }); + expect((await stat(worktreePath)).isDirectory()).toBe(true); + const archived = await client.archiveWorkspace(workspaceId, undefined, { force: true }); expect(archived.error).toBeNull(); await expect(stat(worktreePath)).rejects.toMatchObject({ code: "ENOENT" }); @@ -805,7 +812,14 @@ test("untrusted workspaces pass untrusted=true to worktree manager remove and re client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); await client.connect(); - const archived = await client.archiveWorkspace(workspaceId); + const retained = await client.archiveWorkspace(workspaceId); + expect(retained).toMatchObject({ + error: null, + removedDirectory: false, + directoryLeftBehind: { path: worktreePath }, + }); + expect((await stat(worktreePath)).isDirectory()).toBe(true); + const archived = await client.archiveWorkspace(workspaceId, undefined, { force: true }); expect(archived.error).toBeNull(); await expect(stat(worktreePath)).rejects.toMatchObject({ code: "ENOENT" }); @@ -843,7 +857,7 @@ test("untrusted workspaces pass untrusted=true to worktree manager remove and re expect((await client.archiveWorkspace(workspaceId)).error).toBeNull(); expect((await stat(worktreePath)).isDirectory()).toBe(true); - expect((await client.archiveWorkspace(siblingId)).error).toBeNull(); + expect((await client.archiveWorkspace(siblingId, undefined, { force: true })).error).toBeNull(); await expect(stat(worktreePath)).rejects.toMatchObject({ code: "ENOENT" }); await client.restoreWorkspace(siblingId); @@ -1438,7 +1452,9 @@ test("built-in archive removes the worktree with dependency clones and recursive const checkout = created.workspace!.workspaceDirectory; await addNestedGitContent(checkout, leaf, middle); - const archived = await client.archiveWorkspace(created.workspace!.id); + const archived = await client.archiveWorkspace(created.workspace!.id, undefined, { + force: true, + }); expect(archived.error).toBeNull(); await expect(stat(checkout)).rejects.toMatchObject({ code: "ENOENT" }); expect(git(repository, ["worktree", "list", "--porcelain"])).not.toContain( @@ -1583,7 +1599,9 @@ export default function contribute(server) { const checkout = managed.workspace!.workspaceDirectory; await addNestedGitContent(checkout, otherRepo, middle); - const archivedWithContent = await client.archiveWorkspace(managed.workspace!.id); + const archivedWithContent = await client.archiveWorkspace(managed.workspace!.id, undefined, { + force: true, + }); expect(archivedWithContent.error).toBeNull(); expect(path.normalize((await readFile(removeCallsFile, "utf8")).trim())).toBe( path.normalize(checkout), diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index fe919366ce..33680247d1 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -8785,11 +8785,13 @@ export class Session { }, { scope: { kind: "workspace", workspaceId: existing.workspaceId }, + force: request.force, requestId: request.requestId, signal, }, ); }, + request.force, ); if (outcome.kind === "canceled") { @@ -8815,6 +8817,8 @@ export class Session { workspaceId: request.workspaceId, archivedAt, error: null, + removedDirectory: outcome.result.removedDirectory, + directoryLeftBehind: outcome.result.directoryLeftBehind, }, }); } catch (error) { diff --git a/packages/server/src/server/workspace-archive-operations.test.ts b/packages/server/src/server/workspace-archive-operations.test.ts index b3bc8cb38c..7197005e9b 100644 --- a/packages/server/src/server/workspace-archive-operations.test.ts +++ b/packages/server/src/server/workspace-archive-operations.test.ts @@ -128,6 +128,25 @@ describe("WorkspaceArchiveOperations", () => { expect(runs).toBe(1); }); + test.each([false, true])( + "an in-flight archive with force=%s only accepts matching requests", + async (force) => { + const operations = new WorkspaceArchiveOperations(); + const archive = parkedArchive(["agent-a"]); + const first = operations.archive("ws", archive.run, force); + await archive.started; + + try { + await expect(operations.archive("ws", archive.run, !force)).rejects.toThrow( + "An archive with different force settings is already running.", + ); + } finally { + archive.release(); + await first; + } + }, + ); + test("an archive requested during an undo runs after the undo, and wins", async () => { const operations = new WorkspaceArchiveOperations(); await operations.archive("ws", async () => archived(["agent-a"])); diff --git a/packages/server/src/server/workspace-archive-operations.ts b/packages/server/src/server/workspace-archive-operations.ts index 144d7846db..17a5736e21 100644 --- a/packages/server/src/server/workspace-archive-operations.ts +++ b/packages/server/src/server/workspace-archive-operations.ts @@ -17,7 +17,7 @@ interface PendingArchive { } type LaneEntry = - | { kind: "archiving"; controller: AbortController; done: Promise } + | ({ kind: "archiving"; force: boolean } & PendingArchive) | { kind: "restoring"; pendingArchive: PendingArchive | null; @@ -30,7 +30,7 @@ type LaneEntry = * Daemon-wide coordinator for workspace archive, undo, and restore operations. * * Per-workspace lanes: - * - An archive while one runs joins it. + * - An archive while one runs joins it if both requests use the same removal policy. * - An undo while an archive runs (including when a restore queued behind it) aborts the archive, * waits for it to stop, then restores. * - A restore while an archive runs waits for the archive without aborting it, then restores. @@ -75,10 +75,14 @@ export class WorkspaceArchiveOperations { archive( workspaceId: string, run: (signal: AbortSignal) => Promise, + force = false, ): Promise { const current = this.lanes.get(workspaceId); if (current?.kind === "archiving") { - return current.done; + if (current.force === force) return current.done; + return Promise.reject( + new Error("An archive with different force settings is already running."), + ); } const controller = new AbortController(); const done = (async (): Promise => { @@ -91,7 +95,7 @@ export class WorkspaceArchiveOperations { return { kind: "canceled", archivedAt: error.archivedAt }; } })(); - this.claim(workspaceId, { kind: "archiving", controller, done }); + this.claim(workspaceId, { kind: "archiving", force, controller, done }); return done; } diff --git a/packages/server/src/server/workspace-archive-record-scoped.e2e.test.ts b/packages/server/src/server/workspace-archive-record-scoped.e2e.test.ts index bd243ced8e..dd2b9fd5de 100644 --- a/packages/server/src/server/workspace-archive-record-scoped.e2e.test.ts +++ b/packages/server/src/server/workspace-archive-record-scoped.e2e.test.ts @@ -27,8 +27,7 @@ import { // to a directory on disk. A directory can back multiple workspaces, so archiving // one must never tear down a sibling's agents/terminals, and must never delete a // directory another workspace still references. On-disk worktree removal is -// derived from scope + last-reference + Paseo ownership; there is no caller- -// supplied disk flag. +// gated on scope, the last active reference, ownership, and checkout cleanliness. let ctx: DaemonTestContext; const tempRoots: string[] = []; @@ -398,6 +397,83 @@ test("an archived workspace keeps its base when a later workspace reuses its pat ); }); +test.each([ + { command: "workspace", mode: "default", force: false }, + { command: "workspace", mode: "forced", force: true }, + { command: "worktree", mode: "default", force: false }, + { command: "worktree", mode: "forced", force: true }, +])("$command archive handles a late untracked file in $mode mode", async ({ command, force }) => { + const repoDir = createGitRepo(); + const sibling = await ctx.client.createWorkspace({ + source: { kind: "worktree", cwd: repoDir, baseBranch: "main", worktreeSlug: "control" }, + }); + if (!sibling.workspace) throw new Error(sibling.error ?? "Failed to create control worktree"); + + const created = await ctx.client.createWorkspace({ + source: { kind: "worktree", cwd: repoDir, baseBranch: "main", worktreeSlug: "late-file" }, + }); + const workspace = created.workspace; + if (!workspace) throw new Error(created.error ?? "Failed to create worktree workspace"); + + const cwd = workspace.workspaceDirectory; + const status = () => + execFileSync("git", ["status", "--porcelain", "--untracked-files=all"], { cwd }).toString(); + expect(status()).toBe(""); + const lateFile = path.join(cwd, "late-untracked.txt"); + writeFileSync(lateFile, "disposable fixture\n"); + expect(status()).toBe("?? late-untracked.txt\n"); + + const target = command === "workspace" ? workspace.id : path.basename(cwd); + const archived = JSON.parse( + await runCli([command, "archive", target, "--json", ...(force ? ["--force"] : [])], repoDir), + ); + expect(archived.status).toBe("archived"); + expect(await activeWorkspaceIds()).not.toContain(workspace.id); + expect(await activeWorkspaceIds()).toContain(sibling.workspace.id); + expect(existsSync(sibling.workspace.workspaceDirectory)).toBe(true); + expect(existsSync(lateFile)).toBe(!force); + expect(archived.removedDirectory).toBe(force); + if (!force) { + expect(readFileSync(lateFile, "utf8")).toBe("disposable fixture\n"); + expect(archived.directoryLeftBehind).toEqual({ + path: cwd, + reason: "The worktree has uncommitted changes.", + }); + } +}); + +test("worktree archive by absolute path keeps an orphaned directory until forced", async () => { + const repoDir = createGitRepo(); + const { workspace, error } = await ctx.client.createWorkspace({ + source: { kind: "worktree", cwd: repoDir, baseBranch: "main", worktreeSlug: "orphaned" }, + }); + if (!workspace) throw new Error(error ?? "Failed to create worktree workspace"); + + const cwd = workspace.workspaceDirectory; + const gitDir = execFileSync("git", ["rev-parse", "--absolute-git-dir"], { cwd }) + .toString() + .trim(); + rmSync(gitDir, { recursive: true, force: true }); + + const archive = ["worktree", "archive", cwd, "--json"]; + expect(JSON.parse(await runCli(archive, repoDir))).toMatchObject({ + status: "archived", + removedDirectory: false, + directoryLeftBehind: { + path: cwd, + reason: "Git could not check the worktree for uncommitted changes.", + }, + }); + expect(await activeWorkspaceIds()).not.toContain(workspace.id); + expect(existsSync(cwd)).toBe(true); + + expect(JSON.parse(await runCli([...archive, "--force"], repoDir))).toMatchObject({ + status: "archived", + removedDirectory: true, + }); + expect(existsSync(cwd)).toBe(false); +}); + test.each(["worktree", "workspace"] as const)( "%s archive immediately removes the deleted worktree from a warm CLI listing", async (command) => { @@ -564,12 +640,15 @@ test.skipIf(process.platform === "win32")( const archive = await ctx.client.archiveWorkspace(workspace.id); const retry = await ctx.client.archiveWorkspace(workspace.id); - expect({ archiveError: archive.error, retryError: retry.error }).toEqual({ - archiveError: null, - retryError: null, - }); + for (const response of [archive, retry]) { + expect(response).toMatchObject({ + error: null, + removedDirectory: false, + directoryLeftBehind: { path: workspace.workspaceDirectory }, + }); + } expect((await activeWorkspaceIds()).has(workspace.id)).toBe(false); - expect(existsSync(workspace.workspaceDirectory)).toBe(false); + expect(existsSync(workspace.workspaceDirectory)).toBe(true); } finally { writeFileSync(stopSetupPath, "stop\n"); } @@ -731,7 +810,7 @@ test.skipIf(process.platform === "win32" || process.getuid?.() === 0)( if (existsSync(directory)) chmodSync(directory, originalMode); } - const retry = await ctx.client.archiveWorkspace(workspace.id); + const retry = await ctx.client.archiveWorkspace(workspace.id, undefined, { force: true }); expect(retry.error).toBeNull(); expect(existsSync(directory)).toBe(false); diff --git a/packages/server/src/server/workspace-archive-service.test.ts b/packages/server/src/server/workspace-archive-service.test.ts index 59dbdaa5ce..499e57b7ab 100644 --- a/packages/server/src/server/workspace-archive-service.test.ts +++ b/packages/server/src/server/workspace-archive-service.test.ts @@ -359,7 +359,7 @@ describe("archiveByScope", () => { requestId: "slug-archive", }, ); - expect(result).toEqual({ ok: true, removedAgents: [] }); + expect(result).toMatchObject({ ok: true, removedAgents: [], removedDirectory: true }); expect(existsSync(worktreePath)).toBe(false); }); @@ -1188,9 +1188,13 @@ describe("archiveByScope", () => { expect(deps.emitWorkspaceUpdatesForWorkspaceIds).not.toHaveBeenCalled(); }); - test.each(["intact", "missing"] as const)( - "worktree scope removes an owned directory with zero matching records and %s Git administration", - async (gitAdministration) => { + test.each([ + { gitAdministration: "intact", force: false, removed: true }, + { gitAdministration: "missing", force: false, removed: false }, + { gitAdministration: "missing", force: true, removed: true }, + ])( + "worktree scope with $gitAdministration Git administration and force=$force", + async ({ gitAdministration, force, removed }) => { const { tempDir, repoDir } = createGitRepo(); const paseoHome = path.join(tempDir, ".paseo"); const worktree = await createPaseoOwnedWorktree(repoDir, paseoHome, "zero-records"); @@ -1209,14 +1213,18 @@ describe("archiveByScope", () => { const result = await archiveByScope(dependencies, { scope: { kind: "worktree", targetPath: worktree.worktreePath }, requestId: "req-zero-records", + force, }); - assertArchiveResult(result, { - archivedWorkspaceIds: [], - removedDirectory: true, - }); - expect(existsSync(worktree.worktreePath)).toBe(false); - expect(invalidateWorktrees).toHaveBeenCalledTimes(1); + expect(result).toMatchObject({ archivedWorkspaceIds: [], removedDirectory: removed }); + if (!removed) { + expect(result.directoryLeftBehind).toEqual({ + path: worktree.worktreePath, + reason: "Git could not check the worktree for uncommitted changes.", + }); + } + expect(existsSync(worktree.worktreePath)).toBe(!removed); + expect(invalidateWorktrees).toHaveBeenCalledTimes(Number(removed)); }, ); diff --git a/packages/server/src/server/workspace-archive-service.ts b/packages/server/src/server/workspace-archive-service.ts index bbbbc94185..5080182fe7 100644 --- a/packages/server/src/server/workspace-archive-service.ts +++ b/packages/server/src/server/workspace-archive-service.ts @@ -89,14 +89,13 @@ export interface ArchiveResult { archivedAgentIds: string[]; archivedWorkspaceIds: string[]; removedDirectory: boolean; - // Set when the record archived but its worktree directory was left on - // disk because no ownership proof held for it. The directory is never - // deleted in that case; the path and reason surface here and in the log. + // The path and reason when archive could not safely remove the worktree. directoryLeftBehind?: { path: string; reason: string }; } export interface ArchiveByScopeRequest { scope: ArchiveScope; + force?: boolean; requestId: string; // Aborting cancels the archive at its next checkpoint. Removing the worktree directory is the // point of no return: once it starts the archive completes. @@ -242,7 +241,7 @@ async function archiveByScopeWithPriority( if (target.backing !== null) { const removal = await maybeRemoveDirectory( dependencies, - { requestId: request.requestId, checkpoint }, + { requestId: request.requestId, force: request.force ?? false, checkpoint }, target, archivedWorkspaceIds, ); @@ -550,7 +549,7 @@ async function archiveTargetRecords( async function maybeRemoveDirectory( dependencies: ArchiveDependencies, - request: { requestId: string; checkpoint: () => void }, + request: { requestId: string; force: boolean; checkpoint: () => void }, target: ArchiveTarget, archivedWorkspaceIds: string[], ): Promise<{ @@ -642,6 +641,7 @@ async function maybeRemoveDirectory( worktreeManagers: dependencies.worktreeManagers, worktreeManagerPluginId: backing.worktreeManagerPluginId, removeReason: "archive", + force: request.force, untrusted: untrustedBacking, }); dependencies.workspaceGitService.invalidateWorktrees(); @@ -652,7 +652,13 @@ async function maybeRemoveDirectory( { err: error, targetPath: backing.path, requestId: request.requestId }, "Worktree disk removal failed during archive; workspace already archived", ); - return { removedDirectory: false }; + return { + removedDirectory: false, + directoryLeftBehind: { + path: backing.path, + reason: error instanceof Error ? error.message : String(error), + }, + }; } } diff --git a/packages/server/src/server/worktree-session.ts b/packages/server/src/server/worktree-session.ts index 72b6323fbf..ed01527b94 100644 --- a/packages/server/src/server/worktree-session.ts +++ b/packages/server/src/server/worktree-session.ts @@ -218,6 +218,7 @@ export async function handlePaseoWorktreeArchiveRequest( branchName: msg.branchName, workspaceId: msg.workspaceId, scope: msg.scope, + force: msg.force, }); if (!result.ok) { dependencies.emit({ @@ -240,6 +241,8 @@ export async function handlePaseoWorktreeArchiveRequest( payload: { success: true, removedAgents: result.removedAgents, + removedDirectory: result.removedDirectory, + directoryLeftBehind: result.directoryLeftBehind, error: null, requestId, }, diff --git a/packages/server/src/server/worktree/commands.ts b/packages/server/src/server/worktree/commands.ts index 4382e46633..b94b7c5c23 100644 --- a/packages/server/src/server/worktree/commands.ts +++ b/packages/server/src/server/worktree/commands.ts @@ -5,6 +5,7 @@ import { archiveByScope, resolveWorkspaceIdAtPath, type ArchiveDependencies, + type ArchiveResult, type ArchiveScope, } from "../workspace-archive-service.js"; import type { @@ -104,13 +105,14 @@ export interface ArchiveCommandInput { branchName?: string; workspaceId?: string; scope?: ArchiveScope["kind"]; + force?: boolean; } export type ArchiveCommandResult = - | { + | ({ ok: true; removedAgents: string[]; - } + } & Pick) | { ok: false; code: "NOT_ALLOWED"; @@ -141,12 +143,15 @@ export async function archiveCommand( const result = await archiveByScope(dependencies, { scope: { kind: "worktree", targetPath }, + force: input.force, requestId: input.requestId, }); return { ok: true, removedAgents: result.archivedAgentIds, + removedDirectory: result.removedDirectory, + directoryLeftBehind: result.directoryLeftBehind, }; } @@ -161,17 +166,21 @@ export async function archiveCommand( return { ok: true, removedAgents: [], + removedDirectory: false, }; } const result = await archiveByScope(dependencies, { scope: { kind: "workspace", workspaceId }, + force: input.force, requestId: input.requestId, }); return { ok: true, removedAgents: result.archivedAgentIds, + removedDirectory: result.removedDirectory, + directoryLeftBehind: result.directoryLeftBehind, }; } diff --git a/packages/server/src/utils/worktree.test.ts b/packages/server/src/utils/worktree.test.ts index d225dcef22..9aa10b9ee6 100644 --- a/packages/server/src/utils/worktree.test.ts +++ b/packages/server/src/utils/worktree.test.ts @@ -420,6 +420,56 @@ describe("paseo worktree manager", () => { ]); }); + it.each([false, true])( + "archives a worktree with an initialized submodule (dirty: %s)", + async (dirty) => { + const submoduleRepo = join(tempDir, "submodule-source"); + execFileSync("git", ["clone", "--local", repoDir, submoduleRepo], { + stdio: "pipe", + }); + execFileSync( + "git", + ["-c", "protocol.file.allow=always", "submodule", "add", submoduleRepo, "submodule"], + { + cwd: repoDir, + stdio: "pipe", + }, + ); + execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "Add submodule"], { + cwd: repoDir, + stdio: "pipe", + }); + const { worktreePath } = await createLegacyWorktreeForTest({ + branchName: "with-submodule", + cwd: repoDir, + baseBranch: "main", + worktreeSlug: "with-submodule", + paseoHome, + }); + execFileSync("git", ["-c", "protocol.file.allow=always", "submodule", "update", "--init"], { + cwd: worktreePath, + stdio: "pipe", + }); + + const remove = () => + deletePaseoWorktree({ + cwd: repoDir, + worktreePath, + paseoHome, + force: false, + }); + if (dirty) { + const untracked = join(worktreePath, "submodule", "keep.txt"); + writeFileSync(untracked, "keep"); + await expect(remove()).rejects.toThrow("The worktree has uncommitted changes."); + expect(readFileSync(untracked, "utf8")).toBe("keep"); + } else { + await remove(); + expect(existsSync(worktreePath)).toBe(false); + } + }, + ); + it("deletes a worktree whose .git admin dir has already been removed", async () => { const created = await createLegacyWorktreeForTest({ branchName: "orphan-delete-branch", diff --git a/packages/server/src/utils/worktree.ts b/packages/server/src/utils/worktree.ts index 7a40153dde..9d6f2d5b2a 100644 --- a/packages/server/src/utils/worktree.ts +++ b/packages/server/src/utils/worktree.ts @@ -1489,6 +1489,7 @@ export interface DeletePaseoWorktreeOptions { worktreeManagers?: Pick; worktreeManagerPluginId?: string | null; removeReason?: "archive" | "rollback"; + force?: boolean; untrusted?: boolean; signal?: AbortSignal; } @@ -1554,6 +1555,7 @@ async function deletePaseoWorktreeAtRepositoryRoot({ worktreeManagers, worktreeManagerPluginId, removeReason = "archive", + force = true, untrusted = false, signal, }: DeletePaseoWorktreeOptions): Promise { @@ -1603,6 +1605,7 @@ async function deletePaseoWorktreeAtRepositoryRoot({ worktreeManagers, worktreeManagerPluginId, removeReason, + force, untrusted, signal, }); @@ -1612,6 +1615,8 @@ async function deletePaseoWorktreeAtRepositoryRoot({ } } + if (!force) return removeCleanWorktree(cwd, resolvedWorktree); + if (cwd) { try { await runGitCommand(["worktree", "remove", resolvedWorktree, "--force"], { @@ -1630,6 +1635,44 @@ async function deletePaseoWorktreeAtRepositoryRoot({ await pruneWorktreesBestEffort(cwd); } +async function assertCleanWorktree(worktreePath: string): Promise { + if (!(await pathExists(join(worktreePath, ".git")))) { + throw new Error("Git could not check the worktree for uncommitted changes."); + } + const status = await runGitCommand( + ["status", "--porcelain", "--untracked-files=all", "--ignore-submodules=none"], + { cwd: worktreePath, envOverlay: READ_ONLY_GIT_ENV }, + ).catch(() => { + throw new Error("Git could not check the worktree for uncommitted changes."); + }); + if (status.stdout.length > 0) { + throw new Error("The worktree has uncommitted changes."); + } +} + +async function removeCleanWorktree(cwd: string | null, worktreePath: string): Promise { + if (!(await pathExists(worktreePath))) return; + if (!cwd) throw new Error("The worktree repository could not be located."); + const options = { cwd, timeout: 120_000, envOverlay: { LC_ALL: "C" } }; + try { + await runGitCommand(["worktree", "remove", worktreePath], options); + } catch (error) { + if ( + !(error instanceof Error) || + !error.message.endsWith( + "\nfatal: working trees containing submodules cannot be moved or removed", + ) + ) { + throw error; + } + // Git refuses even a clean initialized submodule. Recheck the contents + // before using Git's submodule removal path, without a recursive fallback. + await assertNoNestedLinkedWorktrees(worktreePath); + await assertCleanWorktree(worktreePath); + await runGitCommand(["worktree", "remove", "--force", worktreePath], options); + } +} + async function assertNoNestedLinkedWorktrees(worktreePath: string): Promise { const pending = [worktreePath]; for (let directory = pending.pop(); directory !== undefined; directory = pending.pop()) { @@ -1684,6 +1727,7 @@ async function prepareAndTryPluginWorktreeRemove(options: { worktreeManagers?: Pick; worktreeManagerPluginId?: string | null; removeReason: "archive" | "rollback"; + force: boolean; untrusted: boolean; signal?: AbortSignal; }): Promise { @@ -1694,6 +1738,7 @@ async function prepareAndTryPluginWorktreeRemove(options: { worktreeManagers, worktreeManagerPluginId, removeReason, + force, untrusted, signal, } = options; @@ -1703,6 +1748,8 @@ async function prepareAndTryPluginWorktreeRemove(options: { teardownCwd, }); } + if (!force) await assertCleanWorktree(resolvedWorktree); + const effectiveManagerPluginId = worktreeManagerPluginId !== undefined ? worktreeManagerPluginId @@ -1729,7 +1776,7 @@ async function prepareAndTryPluginWorktreeRemove(options: { path: resolvedWorktree, branch, reason: removeReason, - force: true, + force, untrusted, }, { preferredPluginId: effectiveManagerPluginId, signal },