mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
Skip worktree teardown commands for unapproved cross-repository checkouts (#10694)
* fix(server): skip teardown commands when archiving unapproved checkouts `archiveByScope` previously treated `assertWorkspaceAutomationAllowed` as optional and did not skip `runWorktreeTeardownCommands` when `untrustedBacking` was already true or when archiving an unrecorded worktree directory. Four callers (`CreateAgentLifecycleDispatch`, `archiveIfSafe`, `paseo-tools` `archive_workspace`, and `handlePaseoWorktreeArchiveRequest`) also omitted `assertWorkspaceAutomationAllowed`, letting `paseo.json` teardown commands run during failed agent creation cleanup, first-turn auto-archive, auto-archive on merge, MCP workspace archive, and worktree archive RPCs. Make `assertWorkspaceAutomationAllowed` and `isCheckoutUntrusted` required on `ArchiveDependencies`, skip teardown whenever the backing checkout is untrusted, any workspace on the checkout is blocked, or no active workspace record exists, and wire the guard through all archive callers. * fix(server): scope archive teardown check to active checkout workspaces `isCheckoutUntrusted` scans all workspace records by path, including previously archived records, so gating teardown on it suppressed `paseo.json` teardown for a fresh approved worktree that reused a previously archived unapproved slug path. Keep teardown approval scoped to the active workspaces sharing the backing checkout at archive start (the records being archived plus active siblings), drop the null-workspace fallback target for unrecorded worktree-scope archives so they never run teardown or flip `untrustedBacking`, and verify caller wiring reaches `assertWorkspaceAutomationAllowed` directly. * fix(server): inherit untrustedSource when unarchiving onto an active unapproved checkout Unarchiving a previously approved workspace onto an existing directory that currently holds an active unapproved checkout left the restored workspace without `untrustedSource`. If the unapproved sibling was archived first, the directory remained on disk and archiving the restored workspace could run teardown commands. Inherit `untrustedSource` from active workspaces sharing the checkout root in `ensureWorkspaceRecordUnarchived`, while ignoring already-archived historical records so restoring an approved checkout onto a reused path stays approved. * fix(server): bind automation approval state to checkout worktree metadata Keeping `untrustedSource` only on workspace records meant a retained unapproved worktree directory could lose its teardown block if its last unapproved workspace was archived and an older approved workspace was unarchived onto that path, while scanning archived records by path blocked fresh worktrees that reused a deleted slug. Persist `untrustedSource` on the checkout itself in `paseo/worktree.json` when creating or restoring an unapproved worktree, clear it in `clearWorkspaceAutomationBlock` when setup is approved, and read it in both `workspace-archive-service` and `workspace-provisioning-service`. Deleting the worktree removes its metadata automatically, so fresh worktrees reusing the path start clean while retained checkouts keep their block across workspace archives and restores. * fix(server): backfill worktree metadata when archiving retained unapproved checkouts Unapproved checkouts created before `paseo/worktree.json` stored `untrustedSource` carry their block only in the workspace record. If archive keeps the directory on disk (such as a retained sibling or nested worktree), backfilling `untrustedSource` into `paseo/worktree.json` before removal ensures the retained checkout keeps its block even after its unapproved workspace record is archived. * fix(server): never propagate archived untrustedSource onto fresh checkouts Both archive metadata backfill and directory workspace creation previously consulted already-archived records matching a path, allowing an old archived unapproved record to copy `untrustedSource` onto a fresh approved worktree that reused the same slug path. Ignore `untrustedSource` on already-archived records during archive target resolution and metadata backfill (only backfill when active workspaces are being archived), and share one `resolveCheckoutUntrustedSource` rule across `createWorkspaceForDirectory` and `ensureWorkspaceRecordUnarchived` that checks `paseo/worktree.json` first and falls back only to active workspaces. * fix(server): align unarchived workspace approval state with the live checkout Unarchiving an old unapproved workspace onto a path already owned by an active approved checkout kept the old record's stale `untrustedSource`, causing a later re-archive of that workspace to backfill the block onto the fresh checkout's metadata. Align `ensureWorkspaceRecordUnarchived` symmetrically with the live checkout: adopt `untrustedSource` from `paseo/worktree.json` or active workspaces on the checkout when present, and drop stale `untrustedSource` when live active workspaces own an approved checkout at that path. * fix(server): preserve block when opening a pre-upgrade retained checkout Opening a pre-upgrade retained checkout directory whose last unapproved workspace was already archived before this change has no active workspace on the path and no `untrustedSource` in `paseo/worktree.json`. In `resolveCheckoutUntrustedSource`, prefer `paseo/worktree.json`, then active workspaces on the checkout when any exist (so a fresh approved worktree at a reused path stays approved), and only when zero active workspaces exist on the directory fall back to the most recently archived record for that path. * fix(server): share one checkout approval lookup across open and unarchive * fix(server): resolve checkout approval state only from metadata and active workspaces * fix(server): keep archive read-only on worktree approval metadata * fix(server): serialize setup approval with archive checkout lock and backfill retained metadata * fix(server): fail setup approval before clearing records when worktree metadata write fails
This commit is contained in:
@@ -1,7 +1,29 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import pino from "pino";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
|
||||
import type { AgentManagerEvent, AgentSubscriber } from "./agent-manager.js";
|
||||
import { registerAgentAutoArchive } from "./create-agent-lifecycle-dispatch.js";
|
||||
import type { ForgeService } from "../../services/forge-service.js";
|
||||
import { createWorktree } from "../../utils/worktree.js";
|
||||
import { WorkspaceAutomationBlockedError } from "../workspace-automation-gate.js";
|
||||
import type { WorkspaceGitService } from "../workspace-git-service.js";
|
||||
import type { PersistedWorkspaceRecord } from "../workspace-registry.js";
|
||||
import type { AgentManager, AgentManagerEvent, AgentSubscriber } from "./agent-manager.js";
|
||||
import type { AgentStorage } from "./agent-storage.js";
|
||||
import {
|
||||
CreateAgentLifecycleDispatch,
|
||||
registerAgentAutoArchive,
|
||||
} from "./create-agent-lifecycle-dispatch.js";
|
||||
|
||||
const cleanupPaths: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const target of cleanupPaths.splice(0)) {
|
||||
rmSync(target, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
class AgentLifecycleEvents {
|
||||
private readonly listeners = new Set<AgentSubscriber>();
|
||||
@@ -25,6 +47,109 @@ class AgentLifecycleEvents {
|
||||
}
|
||||
}
|
||||
|
||||
async function createUntrustedWorktreeFixture(slug: string, markerName: string) {
|
||||
const tempDir = mkdtempSync(path.join(tmpdir(), "lifecycle-dispatch-"));
|
||||
cleanupPaths.push(tempDir);
|
||||
const repoDir = path.join(tempDir, "repo");
|
||||
const paseoHome = path.join(tempDir, ".paseo");
|
||||
mkdirSync(repoDir, { recursive: true });
|
||||
execFileSync("git", ["init", "-b", "main"], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["config", "user.email", "test@getpaseo.local"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
execFileSync("git", ["config", "user.name", "Paseo Test"], { cwd: repoDir, stdio: "pipe" });
|
||||
writeFileSync(
|
||||
path.join(repoDir, "paseo.json"),
|
||||
JSON.stringify({
|
||||
worktree: {
|
||||
teardown: [
|
||||
`node -e "require('fs').writeFileSync(process.env.PASEO_SOURCE_CHECKOUT_PATH + '/${markerName}', 'ran')"`,
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
execFileSync("git", ["add", "."], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "init"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const worktree = await createWorktree({
|
||||
cwd: repoDir,
|
||||
worktreeSlug: slug,
|
||||
source: { kind: "branch-off", baseBranch: "main", branchName: slug },
|
||||
paseoHome,
|
||||
});
|
||||
const workspace: PersistedWorkspaceRecord = {
|
||||
workspaceId: `ws-${slug}`,
|
||||
projectId: "proj-1",
|
||||
cwd: worktree.worktreePath,
|
||||
kind: "worktree",
|
||||
worktreeRoot: worktree.worktreePath,
|
||||
isPaseoOwnedWorktree: true,
|
||||
mainRepoRoot: repoDir,
|
||||
createdAt: "2026-11-24T00:00:00.000Z",
|
||||
updatedAt: "2026-11-24T00:00:00.000Z",
|
||||
};
|
||||
const blockedSource = {
|
||||
kind: "change_request" as const,
|
||||
forge: "github",
|
||||
number: 99,
|
||||
headRepository: "contributor/paseo",
|
||||
};
|
||||
const assertWorkspaceAutomationAllowed = vi.fn(async (id: string) => {
|
||||
if (id === workspace.workspaceId) {
|
||||
throw new WorkspaceAutomationBlockedError(blockedSource);
|
||||
}
|
||||
});
|
||||
const activeWorkspaces = [workspace];
|
||||
const archived = new Set<string>();
|
||||
const events = new AgentLifecycleEvents();
|
||||
const agentManager = {
|
||||
subscribe: (cb: AgentSubscriber) => events.subscribe(cb),
|
||||
listAgents: () => [],
|
||||
getAgent: () => null,
|
||||
archiveAgent: vi.fn(async () => ({ archivedAt: new Date().toISOString() })),
|
||||
archiveSnapshot: vi.fn(async () => ({})),
|
||||
} as unknown as AgentManager;
|
||||
const dispatch = new CreateAgentLifecycleDispatch({
|
||||
paseoHome,
|
||||
getWorkspace: async (id) => (id === workspace.workspaceId ? workspace : null),
|
||||
assertWorkspaceAutomationAllowed,
|
||||
isCheckoutUntrusted: async () => false,
|
||||
agentManager,
|
||||
agentStorage: { listByWorkspace: async () => [] } as unknown as AgentStorage,
|
||||
github: { invalidate: () => {} } as unknown as ForgeService,
|
||||
workspaceGitService: {
|
||||
getSnapshot: vi.fn(async () => null),
|
||||
invalidateWorktrees: () => {},
|
||||
} as unknown as WorkspaceGitService,
|
||||
createPaseoWorktreeWorkflow: vi.fn(),
|
||||
archiveAgentForClose: vi.fn(async () => undefined),
|
||||
findWorkspaceIdForCwd: async () => workspace.workspaceId,
|
||||
listActiveWorkspaces: async () => activeWorkspaces.filter((w) => !archived.has(w.workspaceId)),
|
||||
archiveWorkspaceRecord: async (id) => {
|
||||
archived.add(id);
|
||||
},
|
||||
emit: vi.fn(),
|
||||
emitAgentRemove: vi.fn(async () => undefined),
|
||||
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(async () => undefined),
|
||||
markWorkspaceArchiving: vi.fn(),
|
||||
clearWorkspaceArchiving: vi.fn(),
|
||||
killTerminalsForWorkspace: vi.fn(async () => undefined),
|
||||
logger: pino({ level: "silent" }),
|
||||
});
|
||||
|
||||
return {
|
||||
dispatch,
|
||||
events,
|
||||
marker: path.join(repoDir, markerName),
|
||||
createdWorktree: { worktree, workspace },
|
||||
archived,
|
||||
assertWorkspaceAutomationAllowed,
|
||||
};
|
||||
}
|
||||
|
||||
test("auto-archive self-releases once and later cancellation waits harmlessly", async () => {
|
||||
const agentId = "4a7e2521-286d-4ad5-af35-e091c55302e3";
|
||||
const agents = new AgentLifecycleEvents();
|
||||
@@ -45,3 +170,41 @@ test("auto-archive self-releases once and later cancellation waits harmlessly",
|
||||
expect(archiveCount).toBe(1);
|
||||
expect(agents.listenerCount()).toBe(0);
|
||||
});
|
||||
|
||||
test("failed create cleanup skips teardown commands for an unapproved cross-repository checkout", async () => {
|
||||
const { dispatch, marker, createdWorktree, archived, assertWorkspaceAutomationAllowed } =
|
||||
await createUntrustedWorktreeFixture("failed-create-untrusted", "failed-create-teardown.log");
|
||||
|
||||
await dispatch.cleanupCreatedWorktreeAfterFailedAgentCreate({
|
||||
createdWorktree,
|
||||
createdAgentId: null,
|
||||
});
|
||||
|
||||
expect(assertWorkspaceAutomationAllowed).toHaveBeenCalledWith(
|
||||
createdWorktree.workspace.workspaceId,
|
||||
);
|
||||
expect(archived.has(createdWorktree.workspace.workspaceId)).toBe(true);
|
||||
expect(existsSync(createdWorktree.worktree.worktreePath)).toBe(false);
|
||||
expect(existsSync(marker)).toBe(false);
|
||||
});
|
||||
|
||||
test("first-turn auto-archive skips teardown commands for an unapproved cross-repository checkout", async () => {
|
||||
const { dispatch, events, marker, createdWorktree, archived, assertWorkspaceAutomationAllowed } =
|
||||
await createUntrustedWorktreeFixture("auto-archive-untrusted", "auto-archive-teardown.log");
|
||||
const agentId = "agent-auto-archive-untrusted";
|
||||
|
||||
const registration = dispatch.registerAutoArchiveIfRequested({
|
||||
autoArchive: true,
|
||||
agentId,
|
||||
createdWorktree,
|
||||
});
|
||||
events.completeTurn(agentId);
|
||||
await registration.cancel();
|
||||
|
||||
expect(assertWorkspaceAutomationAllowed).toHaveBeenCalledWith(
|
||||
createdWorktree.workspace.workspaceId,
|
||||
);
|
||||
expect(archived.has(createdWorktree.workspace.workspaceId)).toBe(true);
|
||||
expect(existsSync(createdWorktree.worktree.worktreePath)).toBe(false);
|
||||
expect(existsSync(marker)).toBe(false);
|
||||
});
|
||||
|
||||
@@ -29,7 +29,8 @@ interface CreateAgentLifecycleDispatchDependencies {
|
||||
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
|
||||
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
|
||||
getWorkspace?: ArchiveDependencies["getWorkspace"];
|
||||
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
|
||||
assertWorkspaceAutomationAllowed: ArchiveDependencies["assertWorkspaceAutomationAllowed"];
|
||||
isCheckoutUntrusted: ArchiveDependencies["isCheckoutUntrusted"];
|
||||
agentManager: AgentManager;
|
||||
agentStorage: AgentStorage;
|
||||
github: ForgeService;
|
||||
@@ -201,6 +202,7 @@ export class CreateAgentLifecycleDispatch {
|
||||
agentStorage: this.dependencies.agentStorage,
|
||||
findWorkspaceIdForCwd: this.dependencies.findWorkspaceIdForCwd,
|
||||
getWorkspace: this.dependencies.getWorkspace,
|
||||
assertWorkspaceAutomationAllowed: this.dependencies.assertWorkspaceAutomationAllowed,
|
||||
isCheckoutUntrusted: this.dependencies.isCheckoutUntrusted,
|
||||
listActiveWorkspaces: this.dependencies.listActiveWorkspaces,
|
||||
archiveWorkspaceRecord: this.dependencies.archiveWorkspaceRecord,
|
||||
|
||||
@@ -2527,6 +2527,8 @@ describe("create_agent MCP tool", () => {
|
||||
emitWorkspaceUpdatesForWorkspaceIds,
|
||||
markWorkspaceArchiving,
|
||||
clearWorkspaceArchiving,
|
||||
assertWorkspaceAutomationAllowed: async () => {},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
github: createGitHubServiceStub(),
|
||||
logger,
|
||||
});
|
||||
@@ -2643,6 +2645,8 @@ describe("create_agent MCP tool", () => {
|
||||
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(async () => undefined),
|
||||
markWorkspaceArchiving: vi.fn(),
|
||||
clearWorkspaceArchiving: vi.fn(),
|
||||
assertWorkspaceAutomationAllowed: async () => {},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
github: createGitHubServiceStub(),
|
||||
logger,
|
||||
});
|
||||
@@ -2675,6 +2679,117 @@ describe("create_agent MCP tool", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("skips teardown commands when archiving a worktree with blocked repository automation", async () => {
|
||||
const { agentManager, agentStorage } = createTestDeps();
|
||||
const tempDir = realpathSync.native(
|
||||
await mkdtemp(join(tmpdir(), "paseo-mcp-archive-worktree-blocked-")),
|
||||
);
|
||||
const repoDir = join(tempDir, "repo");
|
||||
const paseoHome = join(tempDir, ".paseo");
|
||||
const markerName = "mcp-blocked-teardown.log";
|
||||
const markerPath = join(repoDir, markerName);
|
||||
|
||||
try {
|
||||
execFileSync("git", ["init", repoDir], { stdio: "pipe" });
|
||||
execFileSync("git", ["config", "user.email", "test@example.com"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
execFileSync("git", ["config", "user.name", "Test"], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["config", "commit.gpgsign", "false"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
await writeFile(
|
||||
join(repoDir, "paseo.json"),
|
||||
JSON.stringify({
|
||||
worktree: {
|
||||
teardown: [
|
||||
`node -e "require('fs').writeFileSync(process.env.PASEO_SOURCE_CHECKOUT_PATH + '/${markerName}', 'ran')"`,
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
execFileSync("git", ["add", "paseo.json"], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["commit", "-m", "init"], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["branch", "-M", "main"], { cwd: repoDir, stdio: "pipe" });
|
||||
|
||||
const workspaceGitService = {
|
||||
getSnapshot: vi.fn(async () => null),
|
||||
listWorktrees: vi.fn(async () => []),
|
||||
resolveRepoRoot: vi.fn(async () => repoDir),
|
||||
invalidateWorktrees: vi.fn(),
|
||||
};
|
||||
const archivedWorkspaceIds: string[] = [];
|
||||
const activeWorkspaces: Array<{
|
||||
workspaceId: string;
|
||||
cwd: string;
|
||||
kind: "worktree" | "local_checkout" | "directory";
|
||||
}> = [];
|
||||
const listActiveWorkspaces = vi.fn(async () => activeWorkspaces);
|
||||
const archiveWorkspaceRecord = createArchiveWorkspaceRecordMutator(
|
||||
activeWorkspaces,
|
||||
archivedWorkspaceIds,
|
||||
);
|
||||
const { WorkspaceAutomationBlockedError } = await import("../workspace-automation-gate.js");
|
||||
const server = await createAgentMcpServer({
|
||||
agentManager,
|
||||
agentStorage,
|
||||
providerSnapshotManager: createOpenCodeManager().manager,
|
||||
paseoHome,
|
||||
createPaseoWorktree: createPaseoWorktreeForMcpTest({ paseoHome, broadcasts: [] }),
|
||||
workspaceGitService: workspaceGitService as unknown as Pick<
|
||||
WorkspaceGitService,
|
||||
"getSnapshot" | "listWorktrees" | "resolveRepoRoot" | "invalidateWorktrees"
|
||||
>,
|
||||
findWorkspaceIdForCwd: vi.fn(async () => "ws-mcp-blocked"),
|
||||
listActiveWorkspaces,
|
||||
archiveWorkspaceRecord,
|
||||
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(async () => undefined),
|
||||
markWorkspaceArchiving: vi.fn(),
|
||||
clearWorkspaceArchiving: vi.fn(),
|
||||
assertWorkspaceAutomationAllowed: async () => {
|
||||
throw new WorkspaceAutomationBlockedError({
|
||||
kind: "change_request",
|
||||
forge: "github",
|
||||
number: 77,
|
||||
headRepository: "contributor/repo",
|
||||
});
|
||||
},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
github: createGitHubServiceStub(),
|
||||
logger,
|
||||
});
|
||||
const createTool = registeredTool(server, "create_workspace");
|
||||
const archiveTool = registeredTool(server, "archive_workspace");
|
||||
const created = await createTool.handler({
|
||||
isolation: "worktree",
|
||||
path: repoDir,
|
||||
worktreeSlug: "archive-blocked-worktree",
|
||||
baseBranch: "main",
|
||||
});
|
||||
const worktreePath = z.string().parse(created.structuredContent.cwd);
|
||||
activeWorkspaces.push({
|
||||
workspaceId: "ws-mcp-blocked",
|
||||
cwd: worktreePath,
|
||||
kind: "worktree",
|
||||
});
|
||||
|
||||
const archived = await archiveTool.handler({
|
||||
workspaceId: "ws-mcp-blocked",
|
||||
});
|
||||
|
||||
expect(archived.structuredContent).toMatchObject({
|
||||
workspaceId: "ws-mcp-blocked",
|
||||
removedDirectory: true,
|
||||
});
|
||||
await expect(access(worktreePath)).rejects.toThrow();
|
||||
await expect(access(markerPath)).rejects.toThrow();
|
||||
} finally {
|
||||
await removeTempDir(tempDir);
|
||||
}
|
||||
});
|
||||
|
||||
it("does not expose worktree path or slug operations", async () => {
|
||||
const { agentManager, agentStorage } = createTestDeps();
|
||||
const tempDir = realpathSync.native(
|
||||
|
||||
@@ -145,6 +145,7 @@ export interface PaseoToolHostDependencies {
|
||||
findWorkspaceIdForCwd?: ArchiveDependencies["findWorkspaceIdForCwd"];
|
||||
worktreeManagers?: ArchiveDependencies["worktreeManagers"];
|
||||
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
|
||||
assertWorkspaceAutomationAllowed?: ArchiveDependencies["assertWorkspaceAutomationAllowed"];
|
||||
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
|
||||
listActiveWorkspaces?: ArchiveDependencies["listActiveWorkspaces"];
|
||||
archiveWorkspaceRecord?: ArchiveDependencies["archiveWorkspaceRecord"];
|
||||
@@ -3427,11 +3428,18 @@ function archiveWorktreeDependencies(
|
||||
if (!options.clearWorkspaceArchiving) {
|
||||
throw new Error("Workspace archiving clearer is required to archive worktrees");
|
||||
}
|
||||
if (!options.assertWorkspaceAutomationAllowed) {
|
||||
throw new Error("Workspace automation gate is required to archive worktrees");
|
||||
}
|
||||
if (!options.isCheckoutUntrusted) {
|
||||
throw new Error("Checkout trust lookup is required to archive worktrees");
|
||||
}
|
||||
return {
|
||||
paseoHome: options.paseoHome,
|
||||
paseoWorktreesBaseRoot: options.worktreesRoot,
|
||||
worktreeManagers: options.worktreeManagers,
|
||||
workspaceArchiveOperations: options.workspaceArchiveOperations,
|
||||
assertWorkspaceAutomationAllowed: options.assertWorkspaceAutomationAllowed,
|
||||
isCheckoutUntrusted: options.isCheckoutUntrusted,
|
||||
github: options.github,
|
||||
workspaceGitService: options.workspaceGitService,
|
||||
|
||||
@@ -111,6 +111,8 @@ function createHarness(overrides?: {
|
||||
markWorkspaceArchiving: vi.fn(),
|
||||
clearWorkspaceArchiving: vi.fn(),
|
||||
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(),
|
||||
assertWorkspaceAutomationAllowed: vi.fn(async () => undefined),
|
||||
isCheckoutUntrusted: vi.fn(async () => false),
|
||||
};
|
||||
const archiveByScope = vi.fn(
|
||||
overrides?.archiveByScope ??
|
||||
@@ -328,6 +330,8 @@ function createRealOutcomeHarness(input: {
|
||||
},
|
||||
markWorkspaceArchiving: () => {},
|
||||
clearWorkspaceArchiving: () => {},
|
||||
assertWorkspaceAutomationAllowed: async () => {},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(),
|
||||
};
|
||||
|
||||
@@ -628,4 +632,68 @@ describe("archiveIfSafe", () => {
|
||||
expect(archivedWorkspaceIds.has(workspace.workspaceId)).toBe(false);
|
||||
expect(existsSync(worktree.worktreePath)).toBe(true);
|
||||
});
|
||||
|
||||
test("real outcome: skips teardown commands for an unapproved cross-repository checkout", async () => {
|
||||
const { tempDir, repoDir } = createGitRepo();
|
||||
const markerName = "auto-archive-merge-teardown.log";
|
||||
const marker = path.join(repoDir, markerName);
|
||||
const fs = await import("node:fs");
|
||||
fs.writeFileSync(
|
||||
path.join(repoDir, "paseo.json"),
|
||||
JSON.stringify({
|
||||
worktree: {
|
||||
teardown: [
|
||||
`node -e "require('fs').writeFileSync(process.env.PASEO_SOURCE_CHECKOUT_PATH + '/${markerName}', 'ran')"`,
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
execFileSync("git", ["add", "."], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "teardown"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const paseoHome = path.join(tempDir, ".paseo");
|
||||
const worktree = await createPaseoOwnedWorktree(repoDir, paseoHome, "merged-untrusted");
|
||||
const workspaceId = "ws-merged-untrusted";
|
||||
const archivedWorkspaceIds = new Set<string>();
|
||||
const harness = createRealOutcomeHarness({
|
||||
paseoHome,
|
||||
repoDir,
|
||||
worktreePath: worktree.worktreePath,
|
||||
activeWorkspaces: [
|
||||
{
|
||||
workspaceId,
|
||||
cwd: worktree.worktreePath,
|
||||
kind: "worktree",
|
||||
worktreeRoot: worktree.worktreePath,
|
||||
isPaseoOwnedWorktree: true,
|
||||
mainRepoRoot: repoDir,
|
||||
},
|
||||
],
|
||||
archivedWorkspaceIds,
|
||||
});
|
||||
const { WorkspaceAutomationBlockedError } = await import("../workspace-automation-gate.js");
|
||||
const assertWorkspaceAutomationAllowed = vi.fn(async () => {
|
||||
throw new WorkspaceAutomationBlockedError({
|
||||
kind: "change_request",
|
||||
forge: "github",
|
||||
number: 123,
|
||||
headRepository: "contributor/repo",
|
||||
});
|
||||
});
|
||||
harness.options.assertWorkspaceAutomationAllowed = assertWorkspaceAutomationAllowed;
|
||||
|
||||
await archiveIfSafe({
|
||||
workspaceId,
|
||||
snapshot: { ...createSnapshot(), cwd: worktree.worktreePath },
|
||||
options: harness.options,
|
||||
log: harness.log,
|
||||
});
|
||||
|
||||
expect(assertWorkspaceAutomationAllowed).toHaveBeenCalledWith(workspaceId);
|
||||
expect(archivedWorkspaceIds.has(workspaceId)).toBe(true);
|
||||
expect(existsSync(worktree.worktreePath)).toBe(false);
|
||||
expect(existsSync(marker)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25,7 +25,8 @@ export interface AutoArchiveArchiveOptions {
|
||||
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
|
||||
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
|
||||
getWorkspace?: ArchiveDependencies["getWorkspace"];
|
||||
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
|
||||
assertWorkspaceAutomationAllowed: ArchiveDependencies["assertWorkspaceAutomationAllowed"];
|
||||
isCheckoutUntrusted: ArchiveDependencies["isCheckoutUntrusted"];
|
||||
daemonConfigStore: DaemonConfigStore;
|
||||
workspaceGitService: WorkspaceGitServiceImpl;
|
||||
github: ForgeService;
|
||||
@@ -113,6 +114,7 @@ export async function archiveIfSafe(input: {
|
||||
agentStorage: options.agentStorage,
|
||||
findWorkspaceIdForCwd: options.findWorkspaceIdForCwd,
|
||||
getWorkspace: options.getWorkspace,
|
||||
assertWorkspaceAutomationAllowed: options.assertWorkspaceAutomationAllowed,
|
||||
isCheckoutUntrusted: options.isCheckoutUntrusted,
|
||||
listActiveWorkspaces: options.listActiveWorkspaces,
|
||||
archiveWorkspaceRecord: (workspaceIdToArchive, archivedAt) =>
|
||||
|
||||
@@ -1246,6 +1246,8 @@ export async function createPaseoDaemon(
|
||||
logger,
|
||||
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
|
||||
getWorkspace: (workspaceId) => workspaceRegistry.get(workspaceId),
|
||||
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
|
||||
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
|
||||
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
|
||||
listActiveWorkspaces: listActiveWorkspacesExternal,
|
||||
getAutoArchivedChangeRequestUrl: async (workspaceId) =>
|
||||
@@ -1358,6 +1360,8 @@ export async function createPaseoDaemon(
|
||||
worktreeManagers: pluginRuntime,
|
||||
workspaceArchiveOperations,
|
||||
getWorkspace: (workspaceId) => workspaceRegistry.get(workspaceId),
|
||||
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
|
||||
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
|
||||
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
|
||||
agentManager,
|
||||
agentStorage,
|
||||
@@ -1611,6 +1615,8 @@ export async function createPaseoDaemon(
|
||||
workspaceGitService,
|
||||
worktreeManagers: pluginRuntime,
|
||||
workspaceArchiveOperations,
|
||||
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
|
||||
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
|
||||
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
|
||||
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
|
||||
listActiveWorkspaces: listActiveWorkspacesExternal,
|
||||
|
||||
@@ -171,6 +171,8 @@ function createScheduleService(options: TestScheduleServiceOptions): ScheduleSer
|
||||
markWorkspaceArchiving: () => {},
|
||||
clearWorkspaceArchiving: () => {},
|
||||
killTerminalsForWorkspace: async () => {},
|
||||
assertWorkspaceAutomationAllowed: async () => {},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
sessionLogger: options.logger,
|
||||
},
|
||||
{
|
||||
@@ -276,6 +278,8 @@ async function createRegistryBackedScheduleWorkspaceDeps(rootDir: string): Promi
|
||||
markWorkspaceArchiving: () => {},
|
||||
clearWorkspaceArchiving: () => {},
|
||||
killTerminalsForWorkspace: async () => {},
|
||||
assertWorkspaceAutomationAllowed: async () => {},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
sessionLogger: logger,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1301,6 +1301,8 @@ export class Session {
|
||||
worktreeManagers: this.pluginRuntime,
|
||||
workspaceArchiveOperations: this.workspaceArchiveOperations,
|
||||
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
|
||||
assertWorkspaceAutomationAllowed: (workspaceId) =>
|
||||
assertWorkspaceAutomationAllowedForWorkspace(this.workspaceRegistry, workspaceId),
|
||||
isCheckoutUntrusted: (checkoutPath) =>
|
||||
isCheckoutUntrusted(this.workspaceRegistry, checkoutPath),
|
||||
agentManager: this.agentManager,
|
||||
@@ -5850,6 +5852,8 @@ export class Session {
|
||||
clearWorkspaceArchiving: (workspaceIds) => this.clearWorkspaceArchiving(workspaceIds),
|
||||
killTerminalsForWorkspace: (workspaceId) =>
|
||||
this.terminalController.killTerminalsForWorkspace(workspaceId),
|
||||
assertWorkspaceAutomationAllowed: (workspaceId) =>
|
||||
assertWorkspaceAutomationAllowedForWorkspace(this.workspaceRegistry, workspaceId),
|
||||
isCheckoutUntrusted: (checkoutPath) =>
|
||||
isCheckoutUntrusted(this.workspaceRegistry, checkoutPath),
|
||||
sessionLogger: this.sessionLogger,
|
||||
@@ -6557,16 +6561,19 @@ export class Session {
|
||||
};
|
||||
}
|
||||
|
||||
private async withWorkspaceCheckout<T>(workspaceId: string, run: () => Promise<T>): Promise<T> {
|
||||
private async withWorkspaceCheckout<T>(
|
||||
workspaceId: string,
|
||||
run: (checkoutPath: string | null) => Promise<T>,
|
||||
): Promise<T> {
|
||||
const workspace = await this.workspaceRegistry.get(workspaceId);
|
||||
if (!workspace) {
|
||||
return run();
|
||||
return run(null);
|
||||
}
|
||||
const checkoutPath = await resolveWorkspaceBackingPath(workspace, {
|
||||
paseoHome: this.paseoHome,
|
||||
paseoWorktreesBaseRoot: this.worktreesRoot,
|
||||
});
|
||||
return this.workspaceArchiveOperations.withCheckout(checkoutPath, run);
|
||||
return this.workspaceArchiveOperations.withCheckout(checkoutPath, () => run(checkoutPath));
|
||||
}
|
||||
|
||||
private async withCheckoutForDirectory<T>(cwd: string, run: () => Promise<T>): Promise<T> {
|
||||
@@ -8209,7 +8216,15 @@ export class Session {
|
||||
{
|
||||
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
|
||||
clearAutomationBlock: (workspaceId) =>
|
||||
clearWorkspaceAutomationBlock(this.workspaceRegistry, workspaceId),
|
||||
this.withWorkspaceCheckout(workspaceId, async (checkoutPath) => {
|
||||
const current = await this.workspaceRegistry.get(workspaceId);
|
||||
if (!current || current.archivedAt) {
|
||||
throw new Error(`Workspace not found: ${workspaceId}`);
|
||||
}
|
||||
return clearWorkspaceAutomationBlock(this.workspaceRegistry, workspaceId, {
|
||||
checkoutPath,
|
||||
});
|
||||
}),
|
||||
startWorkspaceSetup: (workspaceId, operation) =>
|
||||
this.workspaceSetupRuntime.start(workspaceId, operation),
|
||||
paseoHome: this.paseoHome,
|
||||
|
||||
+148
-1
@@ -1,8 +1,9 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { mkdirSync, mkdtempSync, rmSync, statSync, symlinkSync } from "node:fs";
|
||||
|
||||
import { afterEach, beforeEach, expect, test } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||
|
||||
import { getCheckoutStatus } from "../../../utils/checkout-git.js";
|
||||
import {
|
||||
@@ -1168,3 +1169,149 @@ test("a failed workspace unarchive write keeps agents archived and permits retry
|
||||
expect((await registry.get(workspace.workspaceId))?.archivedAt).toBeNull();
|
||||
expect(agentArchived).toBe(false);
|
||||
});
|
||||
|
||||
describe("checkout approval state on open and unarchive", () => {
|
||||
const sampleUntrustedSource = (number: number) => ({
|
||||
kind: "change_request" as const,
|
||||
forge: "github",
|
||||
number,
|
||||
headRepository: "contributor/repo",
|
||||
});
|
||||
|
||||
function createCheckoutDirs(name: string) {
|
||||
const sourceCwd = path.join(tmpDir, `repo-${name}`);
|
||||
const worktreePath = path.join(tmpDir, `worktree-${name}`);
|
||||
mkdirSync(sourceCwd, { recursive: true });
|
||||
mkdirSync(worktreePath, { recursive: true });
|
||||
gitRoots.add(sourceCwd);
|
||||
gitRoots.add(worktreePath);
|
||||
return { sourceCwd, worktreePath };
|
||||
}
|
||||
|
||||
function addWorktreeRecord(
|
||||
dirs: { sourceCwd: string; worktreePath: string },
|
||||
branch: string,
|
||||
untrustedSource?: ReturnType<typeof sampleUntrustedSource>,
|
||||
) {
|
||||
return provisioning.createWorkspaceForWorktree({
|
||||
sourceCwd: dirs.sourceCwd,
|
||||
repoRoot: dirs.sourceCwd,
|
||||
cwd: dirs.worktreePath,
|
||||
worktreeRoot: dirs.worktreePath,
|
||||
branch,
|
||||
baseBranch: "main",
|
||||
title: null,
|
||||
...(untrustedSource ? { untrustedSource } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
test("unarchiving an approved workspace onto an active unapproved checkout inherits untrustedSource", async () => {
|
||||
const dirs = createCheckoutDirs("unarchive-inherit");
|
||||
const original = await addWorktreeRecord(dirs, "feature/approved");
|
||||
await workspaceRegistry.archive(original.workspaceId, ARCHIVED_AT);
|
||||
const archivedOriginal = (await workspaceRegistry.get(original.workspaceId))!;
|
||||
|
||||
const untrustedSource = sampleUntrustedSource(55);
|
||||
await addWorktreeRecord(dirs, "contributor/pr-55", untrustedSource);
|
||||
|
||||
const restored = await provisioning.ensureWorkspaceRecordUnarchived(archivedOriginal);
|
||||
|
||||
expect(restored.archivedAt).toBeNull();
|
||||
expect(restored.untrustedSource).toEqual(untrustedSource);
|
||||
expect((await workspaceRegistry.get(original.workspaceId))?.untrustedSource).toEqual(
|
||||
untrustedSource,
|
||||
);
|
||||
});
|
||||
|
||||
test("unarchiving an approved workspace ignores archived unapproved records on the same path", async () => {
|
||||
const dirs = createCheckoutDirs("unarchive-historical");
|
||||
const oldUntrusted = await addWorktreeRecord(
|
||||
dirs,
|
||||
"contributor/pr-56",
|
||||
sampleUntrustedSource(56),
|
||||
);
|
||||
await workspaceRegistry.archive(oldUntrusted.workspaceId, "2026-04-01T00:00:00.000Z");
|
||||
|
||||
const approved = await addWorktreeRecord(dirs, "feature/fresh");
|
||||
await workspaceRegistry.archive(approved.workspaceId, "2026-04-02T00:00:00.000Z");
|
||||
|
||||
const restored = await provisioning.ensureWorkspaceRecordUnarchived(
|
||||
(await workspaceRegistry.get(approved.workspaceId))!,
|
||||
);
|
||||
|
||||
expect(restored.archivedAt).toBeNull();
|
||||
expect(restored.untrustedSource).toBeUndefined();
|
||||
});
|
||||
|
||||
test("unarchiving an approved workspace onto a retained unapproved checkout inherits untrustedSource from checkout metadata", async () => {
|
||||
const sourceCwd = path.join(tmpDir, "repo-retained-metadata");
|
||||
mkdirSync(sourceCwd, { recursive: true });
|
||||
execFileSync("git", ["init", "-b", "main"], { cwd: sourceCwd, stdio: "pipe" });
|
||||
execFileSync("git", ["config", "user.email", "test@getpaseo.local"], {
|
||||
cwd: sourceCwd,
|
||||
stdio: "pipe",
|
||||
});
|
||||
execFileSync("git", ["config", "user.name", "Paseo Test"], { cwd: sourceCwd, stdio: "pipe" });
|
||||
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "--allow-empty", "-m", "init"], {
|
||||
cwd: sourceCwd,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const worktreePath = path.join(tmpDir, "worktree-retained-metadata");
|
||||
execFileSync("git", ["worktree", "add", "-b", "retained-pr", worktreePath, "main"], {
|
||||
cwd: sourceCwd,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const untrustedSource = sampleUntrustedSource(57);
|
||||
await writePaseoWorktreeMetadata(worktreePath, {
|
||||
baseRefName: "main",
|
||||
untrustedSource,
|
||||
});
|
||||
gitRoots.add(sourceCwd);
|
||||
gitRoots.add(worktreePath);
|
||||
|
||||
const approved = await addWorktreeRecord({ sourceCwd, worktreePath }, "feature/approved");
|
||||
await workspaceRegistry.archive(approved.workspaceId, ARCHIVED_AT);
|
||||
|
||||
const restored = await provisioning.ensureWorkspaceRecordUnarchived(
|
||||
(await workspaceRegistry.get(approved.workspaceId))!,
|
||||
);
|
||||
|
||||
expect(restored.archivedAt).toBeNull();
|
||||
expect(restored.untrustedSource).toEqual(untrustedSource);
|
||||
});
|
||||
|
||||
test("creating a directory workspace ignores archived unapproved records on the same path", async () => {
|
||||
const dirs = createCheckoutDirs("dir-reused-path");
|
||||
const oldUntrusted = await addWorktreeRecord(
|
||||
dirs,
|
||||
"contributor/pr-58",
|
||||
sampleUntrustedSource(58),
|
||||
);
|
||||
await workspaceRegistry.archive(oldUntrusted.workspaceId, ARCHIVED_AT);
|
||||
|
||||
const opened = await provisioning.createWorkspaceForDirectory(dirs.worktreePath);
|
||||
|
||||
expect(opened.untrustedSource).toBeUndefined();
|
||||
});
|
||||
|
||||
test("unarchiving an old unapproved workspace onto a live approved checkout drops its stale untrustedSource", async () => {
|
||||
const dirs = createCheckoutDirs("unarchive-stale-block");
|
||||
const oldUntrusted = await addWorktreeRecord(
|
||||
dirs,
|
||||
"contributor/pr-59",
|
||||
sampleUntrustedSource(59),
|
||||
);
|
||||
await workspaceRegistry.archive(oldUntrusted.workspaceId, ARCHIVED_AT);
|
||||
const archivedOldUntrusted = (await workspaceRegistry.get(oldUntrusted.workspaceId))!;
|
||||
|
||||
await addWorktreeRecord(dirs, "feature/fresh-approved");
|
||||
|
||||
const unarchived = await provisioning.ensureWorkspaceRecordUnarchived(archivedOldUntrusted);
|
||||
|
||||
expect(unarchived.archivedAt).toBeNull();
|
||||
expect(unarchived.untrustedSource).toBeUndefined();
|
||||
expect(
|
||||
(await workspaceRegistry.get(oldUntrusted.workspaceId))?.untrustedSource,
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
+48
-7
@@ -275,12 +275,10 @@ export function createWorkspaceProvisioningService(deps: {
|
||||
? await readPaseoWorktreeMetadata(checkout.worktreeRoot ?? normalizedCwd)
|
||||
: null;
|
||||
const checkoutRoot = checkout.worktreeRoot ?? normalizedCwd;
|
||||
const matchesCheckout = createRealpathAwarePathMatcher(checkoutRoot);
|
||||
const inheritedUntrustedSource = (await workspaceRegistry.listAll()).find(
|
||||
(candidate) =>
|
||||
Boolean(candidate.untrustedSource) &&
|
||||
matchesCheckout(candidate.worktreeRoot ?? candidate.cwd),
|
||||
)?.untrustedSource;
|
||||
const { untrustedSource: inheritedUntrustedSource } = await resolveCheckoutUntrustedSource(
|
||||
checkoutRoot,
|
||||
baseMetadata?.untrustedSource,
|
||||
);
|
||||
const timestamp = new Date().toISOString();
|
||||
const workspace = createPersistedWorkspaceRecord({
|
||||
workspaceId: context?.workspaceId ?? generateWorkspaceId(),
|
||||
@@ -429,6 +427,49 @@ export function createWorkspaceProvisioningService(deps: {
|
||||
).workspaceId;
|
||||
}
|
||||
|
||||
async function resolveCheckoutUntrustedSource(
|
||||
checkoutRoot: string,
|
||||
knownMetadataUntrustedSource?: UntrustedWorkspaceSource,
|
||||
): Promise<{ hasEvidence: boolean; untrustedSource: UntrustedWorkspaceSource | undefined }> {
|
||||
const metadataUntrustedSource =
|
||||
knownMetadataUntrustedSource ??
|
||||
(await readPaseoWorktreeMetadata(checkoutRoot).catch(() => null))?.untrustedSource;
|
||||
if (metadataUntrustedSource) {
|
||||
return { hasEvidence: true, untrustedSource: metadataUntrustedSource };
|
||||
}
|
||||
const matchesCheckout = createRealpathAwarePathMatcher(checkoutRoot);
|
||||
const active = (await workspaceRegistry.listActive()).filter((candidate) =>
|
||||
matchesCheckout(candidate.worktreeRoot ?? candidate.cwd),
|
||||
);
|
||||
if (active.length === 0) {
|
||||
return { hasEvidence: false, untrustedSource: undefined };
|
||||
}
|
||||
return {
|
||||
hasEvidence: true,
|
||||
untrustedSource: active.find((candidate) => Boolean(candidate.untrustedSource))
|
||||
?.untrustedSource,
|
||||
};
|
||||
}
|
||||
|
||||
async function syncUnarchivedCheckoutUntrustedSource(
|
||||
workspace: PersistedWorkspaceRecord,
|
||||
): Promise<PersistedWorkspaceRecord> {
|
||||
const resolved = await resolveCheckoutUntrustedSource(workspace.worktreeRoot ?? workspace.cwd);
|
||||
if (!resolved.hasEvidence) {
|
||||
return workspace;
|
||||
}
|
||||
if (resolved.untrustedSource) {
|
||||
return workspace.untrustedSource
|
||||
? workspace
|
||||
: { ...workspace, untrustedSource: resolved.untrustedSource };
|
||||
}
|
||||
if (!workspace.untrustedSource) {
|
||||
return workspace;
|
||||
}
|
||||
const { untrustedSource: _stale, ...approved } = workspace;
|
||||
return approved;
|
||||
}
|
||||
|
||||
async function resolveRestoredAutoArchiveChangeRequestUrl(
|
||||
workspace: PersistedWorkspaceRecord,
|
||||
): Promise<string | null> {
|
||||
@@ -466,7 +507,7 @@ export function createWorkspaceProvisioningService(deps: {
|
||||
updatedAt: timestamp,
|
||||
});
|
||||
next = {
|
||||
...(placementUpdate?.workspace ?? workspace),
|
||||
...(await syncUnarchivedCheckoutUntrustedSource(placementUpdate?.workspace ?? workspace)),
|
||||
archivedAt: null,
|
||||
autoArchivedChangeRequestUrl,
|
||||
updatedAt: timestamp,
|
||||
|
||||
+133
@@ -23,12 +23,14 @@ import {
|
||||
} from "../../../utils/worktree-metadata.js";
|
||||
import { createWorktree, deletePaseoWorktree } from "../../../utils/worktree.js";
|
||||
import {
|
||||
FileBackedProjectRegistry,
|
||||
FileBackedWorkspaceRegistry,
|
||||
createPersistedProjectRecord,
|
||||
createPersistedWorkspaceRecord,
|
||||
type PersistedProjectRecord,
|
||||
type PersistedWorkspaceRecord,
|
||||
} from "../../workspace-registry.js";
|
||||
import { createWorkspaceProvisioningService } from "../workspace-provisioning/workspace-provisioning-service.js";
|
||||
import { createWorkspaceRecoveryService } from "./workspace-recovery-service.js";
|
||||
|
||||
const NOW = "2026-07-11T10:12:30.752Z";
|
||||
@@ -719,3 +721,134 @@ test("restores a user-created worktree at its recorded path outside Paseo's root
|
||||
).toBe("external-feature");
|
||||
expect(unarchived).toEqual([workspace.workspaceId]);
|
||||
});
|
||||
|
||||
describe("recovery approval ownership for shared archived history", () => {
|
||||
async function setupSlugReuseHistory(options: { keepLatestCheckoutOnDisk: boolean }) {
|
||||
const { tempDir, repoDir } = createGitRepository();
|
||||
const paseoHome = join(tempDir, "paseo-home");
|
||||
const workspaceRegistry = new FileBackedWorkspaceRegistry(
|
||||
join(paseoHome, "workspaces.json"),
|
||||
pino({ level: "silent" }),
|
||||
);
|
||||
const projectRegistry = new FileBackedProjectRegistry(
|
||||
join(paseoHome, "projects.json"),
|
||||
pino({ level: "silent" }),
|
||||
);
|
||||
const provisioning = createWorkspaceProvisioningService({
|
||||
unarchiveWorkspaceAgents: async () => {},
|
||||
workspaceRegistry,
|
||||
projectRegistry,
|
||||
workspaceGitService: {
|
||||
getCheckout: async (cwd) => getCheckoutStatus(cwd),
|
||||
getSnapshot: async () => ({
|
||||
checkout: null,
|
||||
forge: { pullRequest: null, checkedAt: null, error: null },
|
||||
}),
|
||||
},
|
||||
isDirectory: async (target) => existsSync(target) && statSync(target).isDirectory(),
|
||||
logger: pino({ level: "silent" }),
|
||||
});
|
||||
|
||||
const firstWorktree = await createWorktree({
|
||||
cwd: repoDir,
|
||||
worktreeSlug: "shared-slug",
|
||||
source: { kind: "branch-off", branchName: "feature/older-approved", baseBranch: "main" },
|
||||
paseoHome,
|
||||
});
|
||||
const olderApproved = await provisioning.createWorkspaceForWorktree({
|
||||
sourceCwd: repoDir,
|
||||
repoRoot: repoDir,
|
||||
cwd: firstWorktree.worktreePath,
|
||||
worktreeRoot: firstWorktree.worktreePath,
|
||||
branch: firstWorktree.branchName,
|
||||
baseBranch: firstWorktree.baseRef,
|
||||
title: null,
|
||||
isPaseoOwnedWorktree: true,
|
||||
});
|
||||
await workspaceRegistry.archive(olderApproved.workspaceId, "2026-04-01T00:00:00.000Z");
|
||||
await deletePaseoWorktree({
|
||||
cwd: repoDir,
|
||||
worktreePath: firstWorktree.worktreePath,
|
||||
paseoHome,
|
||||
});
|
||||
|
||||
const untrustedSource = {
|
||||
kind: "change_request" as const,
|
||||
forge: "github",
|
||||
number: 72,
|
||||
headRepository: "contributor/repo",
|
||||
};
|
||||
const secondWorktree = await createWorktree({
|
||||
cwd: repoDir,
|
||||
worktreeSlug: "shared-slug",
|
||||
source: { kind: "branch-off", branchName: "contributor/pr-72", baseBranch: "main" },
|
||||
paseoHome,
|
||||
});
|
||||
await writePaseoWorktreeMetadata(secondWorktree.worktreePath, {
|
||||
baseRefName: "main",
|
||||
untrustedSource,
|
||||
});
|
||||
const laterUntrusted = await provisioning.createWorkspaceForWorktree({
|
||||
sourceCwd: repoDir,
|
||||
repoRoot: repoDir,
|
||||
cwd: secondWorktree.worktreePath,
|
||||
worktreeRoot: secondWorktree.worktreePath,
|
||||
branch: secondWorktree.branchName,
|
||||
baseBranch: secondWorktree.baseRef,
|
||||
title: null,
|
||||
isPaseoOwnedWorktree: true,
|
||||
untrustedSource,
|
||||
});
|
||||
await workspaceRegistry.archive(laterUntrusted.workspaceId, "2026-04-02T00:00:00.000Z");
|
||||
if (!options.keepLatestCheckoutOnDisk) {
|
||||
await deletePaseoWorktree({
|
||||
cwd: repoDir,
|
||||
worktreePath: secondWorktree.worktreePath,
|
||||
paseoHome,
|
||||
});
|
||||
}
|
||||
|
||||
const recovery = createWorkspaceRecoveryService({
|
||||
paseoHome,
|
||||
getWorkspace: (id) => workspaceRegistry.get(id),
|
||||
getProject: (id) => projectRegistry.get(id),
|
||||
isDirectory: async (target) => existsSync(target) && statSync(target).isDirectory(),
|
||||
unarchiveWorkspace: async (workspace) => {
|
||||
await provisioning.ensureWorkspaceRecordUnarchived(workspace);
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
olderApproved,
|
||||
untrustedSource,
|
||||
worktreePath: firstWorktree.worktreePath,
|
||||
workspaceRegistry,
|
||||
recovery,
|
||||
};
|
||||
}
|
||||
|
||||
test("restoring a deleted approved workspace after slug reuse keeps the recreated worktree approved", async () => {
|
||||
const { olderApproved, worktreePath, workspaceRegistry, recovery } =
|
||||
await setupSlugReuseHistory({ keepLatestCheckoutOnDisk: false });
|
||||
|
||||
const result = await recovery.restore(olderApproved.workspaceId);
|
||||
|
||||
expect(result).toEqual({ workspaceId: olderApproved.workspaceId, action: "restore" });
|
||||
const restored = await workspaceRegistry.get(olderApproved.workspaceId);
|
||||
expect(restored?.archivedAt).toBeNull();
|
||||
expect(restored?.untrustedSource).toBeUndefined();
|
||||
expect((await readPaseoWorktreeMetadata(worktreePath))?.untrustedSource).toBeUndefined();
|
||||
});
|
||||
|
||||
test("unarchiving onto a retained unapproved checkout inherits untrustedSource from worktree metadata", async () => {
|
||||
const { olderApproved, untrustedSource, workspaceRegistry, recovery } =
|
||||
await setupSlugReuseHistory({ keepLatestCheckoutOnDisk: true });
|
||||
|
||||
const result = await recovery.restore(olderApproved.workspaceId);
|
||||
|
||||
expect(result).toEqual({ workspaceId: olderApproved.workspaceId, action: "unarchive" });
|
||||
const restored = await workspaceRegistry.get(olderApproved.workspaceId);
|
||||
expect(restored?.archivedAt).toBeNull();
|
||||
expect(restored?.untrustedSource).toEqual(untrustedSource);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,6 +5,7 @@ import { resolveRepositoryDefaultBranch } from "../../../utils/checkout-git.js";
|
||||
import { runWithRepositoryRoot } from "../../../utils/git-repository-discovery.js";
|
||||
import { createRealpathAwarePathMatcher } from "../../../utils/path.js";
|
||||
import { runGitCommand } from "../../../utils/run-git-command.js";
|
||||
import { setPaseoWorktreeUntrustedSource } from "../../../utils/worktree-metadata.js";
|
||||
import {
|
||||
createWorktree,
|
||||
isPaseoOwnedWorktreeCwd,
|
||||
@@ -280,6 +281,9 @@ export function createWorkspaceRecoveryService(deps: {
|
||||
error,
|
||||
);
|
||||
}
|
||||
if (workspace.untrustedSource) {
|
||||
await setPaseoWorktreeUntrustedSource(recreatedWorktreePath, workspace.untrustedSource);
|
||||
}
|
||||
return { worktreePath: recreatedWorktreePath, pluginId: restoredByPluginId };
|
||||
}
|
||||
|
||||
|
||||
@@ -7,12 +7,17 @@ import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
import type { ForgeService } from "../services/forge-service.js";
|
||||
import { createRealpathAwarePathMatcher } from "../utils/path.js";
|
||||
import { getPaseoWorktreeMetadataPath } from "../utils/worktree-metadata.js";
|
||||
import {
|
||||
getPaseoWorktreeMetadataPath,
|
||||
readPaseoWorktreeMetadata,
|
||||
setPaseoWorktreeUntrustedSource,
|
||||
} from "../utils/worktree-metadata.js";
|
||||
import { archiveCommand } from "./worktree/commands.js";
|
||||
import { createWorktree, listPaseoWorktrees, type WorktreeConfig } from "../utils/worktree.js";
|
||||
import type { ManagedAgent } from "./agent/agent-manager.js";
|
||||
import type { AgentStorage, StoredAgentRecord } from "./agent/agent-storage.js";
|
||||
import type { WorkspaceGitService } from "./workspace-git-service.js";
|
||||
import { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
|
||||
import {
|
||||
archiveByScope,
|
||||
unarchiveWorkspaceAgents,
|
||||
@@ -22,7 +27,16 @@ import {
|
||||
resolveWorkspaceIdAtPath,
|
||||
WorkspaceArchiveCanceledError,
|
||||
} from "./workspace-archive-service.js";
|
||||
import { WorkspaceAutomationBlockedError } from "./workspace-automation-gate.js";
|
||||
import {
|
||||
assertWorkspaceAutomationAllowedForWorkspace,
|
||||
clearWorkspaceAutomationBlock,
|
||||
isCheckoutUntrusted,
|
||||
WorkspaceAutomationBlockedError,
|
||||
} from "./workspace-automation-gate.js";
|
||||
import {
|
||||
createPersistedWorkspaceRecord,
|
||||
FileBackedWorkspaceRegistry,
|
||||
} from "./workspace-registry.js";
|
||||
|
||||
const cleanupPaths: string[] = [];
|
||||
|
||||
@@ -175,6 +189,8 @@ function createArchiveDeps(input: ArchiveDepsInput): ArchiveTestDependencies {
|
||||
markWorkspaceArchiving: vi.fn(),
|
||||
clearWorkspaceArchiving: vi.fn(),
|
||||
killTerminalsForWorkspace: vi.fn(async () => {}),
|
||||
assertWorkspaceAutomationAllowed: async () => {},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
sessionLogger: createLogger(),
|
||||
activeWorkspaces: active,
|
||||
archivedAgentIds,
|
||||
@@ -480,6 +496,394 @@ describe("archiveByScope", () => {
|
||||
expect(existsSync(marker)).toBe(false);
|
||||
});
|
||||
|
||||
describe("teardown approval gating", () => {
|
||||
const sampleBlockedSource = (number = 42) => ({
|
||||
kind: "change_request" as const,
|
||||
forge: "github",
|
||||
number,
|
||||
headRepository: "contributor/paseo",
|
||||
});
|
||||
|
||||
async function createTeardownWorktree(slug: string, options?: { nestedRelative?: string }) {
|
||||
const { tempDir, repoDir } = createGitRepo();
|
||||
const markerName = `${slug}-teardown.log`;
|
||||
const marker = path.join(repoDir, markerName);
|
||||
const configDir = options?.nestedRelative
|
||||
? path.join(repoDir, options.nestedRelative)
|
||||
: repoDir;
|
||||
mkdirSync(configDir, { recursive: true });
|
||||
writeFileSync(
|
||||
path.join(configDir, "paseo.json"),
|
||||
JSON.stringify({
|
||||
worktree: {
|
||||
teardown: [
|
||||
`node -e "require('fs').writeFileSync(process.env.PASEO_SOURCE_CHECKOUT_PATH + '/${markerName}', 'ran')"`,
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
execFileSync("git", ["add", "."], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", `teardown ${slug}`], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const paseoHome = path.join(tempDir, ".paseo");
|
||||
const worktree = await createPaseoOwnedWorktree(repoDir, paseoHome, slug);
|
||||
return { repoDir, paseoHome, worktreePath: worktree.worktreePath, marker };
|
||||
}
|
||||
|
||||
function makeWorktreeWorkspace(
|
||||
workspaceId: string,
|
||||
fixture: { repoDir: string; worktreePath: string },
|
||||
overrides: Partial<ActiveWorkspaceRef> = {},
|
||||
): ActiveWorkspaceRef {
|
||||
return {
|
||||
workspaceId,
|
||||
cwd: fixture.worktreePath,
|
||||
kind: "worktree",
|
||||
worktreeRoot: fixture.worktreePath,
|
||||
isPaseoOwnedWorktree: true,
|
||||
mainRepoRoot: fixture.repoDir,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
test("workspace scope skips teardown when the workspace record carries untrustedSource", async () => {
|
||||
const fixture = await createTeardownWorktree("untrusted-record");
|
||||
const workspaceId = "ws-untrusted-record";
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome: fixture.paseoHome,
|
||||
activeWorkspaces: [
|
||||
makeWorktreeWorkspace(workspaceId, fixture, { untrustedSource: sampleBlockedSource() }),
|
||||
],
|
||||
});
|
||||
|
||||
const result = await archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId },
|
||||
requestId: "req-untrusted-record",
|
||||
});
|
||||
|
||||
expect(result.archivedWorkspaceIds).toEqual([workspaceId]);
|
||||
expect(result.removedDirectory).toBe(true);
|
||||
expect(existsSync(fixture.worktreePath)).toBe(false);
|
||||
expect(existsSync(fixture.marker)).toBe(false);
|
||||
});
|
||||
|
||||
test("workspace scope runs teardown for a fresh worktree reusing the path of an archived unapproved checkout", async () => {
|
||||
const fixture = await createTeardownWorktree("reused-slug");
|
||||
const workspaceId = "ws-fresh-reused-slug";
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome: fixture.paseoHome,
|
||||
activeWorkspaces: [makeWorktreeWorkspace(workspaceId, fixture)],
|
||||
});
|
||||
// Simulates an earlier archived unapproved workspace that previously used the same path.
|
||||
deps.isCheckoutUntrusted = async () => true;
|
||||
|
||||
const result = await archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId },
|
||||
requestId: "req-fresh-reused-slug",
|
||||
});
|
||||
|
||||
expect(result.archivedWorkspaceIds).toEqual([workspaceId]);
|
||||
expect(result.removedDirectory).toBe(true);
|
||||
expect(existsSync(fixture.worktreePath)).toBe(false);
|
||||
expect(readFileSync(fixture.marker, "utf8")).toBe("ran");
|
||||
});
|
||||
|
||||
test("retrying archive on an already-archived unapproved workspace does not mark a fresh worktree at the same path", async () => {
|
||||
const fixture = await createTeardownWorktree("reused-after-retry");
|
||||
const oldArchivedId = "ws-old-archived-unapproved";
|
||||
const freshWorkspaceId = "ws-fresh-approved";
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome: fixture.paseoHome,
|
||||
activeWorkspaces: [makeWorktreeWorkspace(freshWorkspaceId, fixture)],
|
||||
});
|
||||
deps.getWorkspace = async (workspaceId) =>
|
||||
workspaceId === oldArchivedId
|
||||
? {
|
||||
...makeWorktreeWorkspace(oldArchivedId, fixture, {
|
||||
untrustedSource: sampleBlockedSource(),
|
||||
}),
|
||||
projectId: "proj-1",
|
||||
archivedAt: "2026-11-24T00:00:00.000Z",
|
||||
createdAt: "2026-11-24T00:00:00.000Z",
|
||||
updatedAt: "2026-11-24T00:00:00.000Z",
|
||||
}
|
||||
: null;
|
||||
deps.isCheckoutUntrusted = async () => true;
|
||||
|
||||
const retry = await archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId: oldArchivedId },
|
||||
requestId: "req-retry-archived",
|
||||
});
|
||||
expect(retry.archivedWorkspaceIds).toEqual([]);
|
||||
expect(retry.removedDirectory).toBe(false);
|
||||
expect(
|
||||
(await readPaseoWorktreeMetadata(fixture.worktreePath))?.untrustedSource,
|
||||
).toBeUndefined();
|
||||
|
||||
const fresh = await archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId: freshWorkspaceId },
|
||||
requestId: "req-archive-fresh",
|
||||
});
|
||||
expect(fresh.archivedWorkspaceIds).toEqual([freshWorkspaceId]);
|
||||
expect(fresh.removedDirectory).toBe(true);
|
||||
expect(existsSync(fixture.worktreePath)).toBe(false);
|
||||
expect(readFileSync(fixture.marker, "utf8")).toBe("ran");
|
||||
});
|
||||
|
||||
test("workspace scope skips teardown when retained checkout metadata carries untrustedSource", async () => {
|
||||
const fixture = await createTeardownWorktree("retained-metadata");
|
||||
await setPaseoWorktreeUntrustedSource(fixture.worktreePath, sampleBlockedSource(88));
|
||||
const workspaceId = "ws-reopened-on-retained";
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome: fixture.paseoHome,
|
||||
activeWorkspaces: [makeWorktreeWorkspace(workspaceId, fixture)],
|
||||
});
|
||||
|
||||
const result = await archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId },
|
||||
requestId: "req-retained-metadata",
|
||||
});
|
||||
|
||||
expect(result.archivedWorkspaceIds).toEqual([workspaceId]);
|
||||
expect(result.removedDirectory).toBe(true);
|
||||
expect(existsSync(fixture.worktreePath)).toBe(false);
|
||||
expect(existsSync(fixture.marker)).toBe(false);
|
||||
});
|
||||
|
||||
test("workspace scope backfills checkout metadata when archiving a pre-upgrade unapproved worktree whose directory stays on disk", async () => {
|
||||
const fixture = await createTeardownWorktree("pre-upgrade-retained");
|
||||
expect(
|
||||
(await readPaseoWorktreeMetadata(fixture.worktreePath))?.untrustedSource,
|
||||
).toBeUndefined();
|
||||
const untrustedSource = sampleBlockedSource(91);
|
||||
const blockedWorkspaceId = "ws-pre-upgrade-blocked";
|
||||
const keptSiblingId = "ws-pre-upgrade-sibling";
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome: fixture.paseoHome,
|
||||
activeWorkspaces: [
|
||||
makeWorktreeWorkspace(blockedWorkspaceId, fixture, { untrustedSource }),
|
||||
makeWorktreeWorkspace(keptSiblingId, fixture),
|
||||
],
|
||||
});
|
||||
|
||||
const first = await archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId: blockedWorkspaceId },
|
||||
requestId: "req-pre-upgrade-first",
|
||||
});
|
||||
expect(first.removedDirectory).toBe(false);
|
||||
expect(existsSync(fixture.marker)).toBe(false);
|
||||
expect((await readPaseoWorktreeMetadata(fixture.worktreePath))?.untrustedSource).toEqual(
|
||||
untrustedSource,
|
||||
);
|
||||
|
||||
const second = await archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId: keptSiblingId },
|
||||
requestId: "req-pre-upgrade-second",
|
||||
});
|
||||
expect(second.removedDirectory).toBe(true);
|
||||
expect(existsSync(fixture.worktreePath)).toBe(false);
|
||||
expect(existsSync(fixture.marker)).toBe(false);
|
||||
});
|
||||
|
||||
test.each(["approval-first", "archive-first"] as const)(
|
||||
"serializing archive and setup approval through withCheckout preserves completed approval (%s)",
|
||||
async (order) => {
|
||||
const fixture = await createTeardownWorktree(`serialized-${order}`);
|
||||
const untrustedSource = sampleBlockedSource(92);
|
||||
const registry = new FileBackedWorkspaceRegistry(
|
||||
path.join(fixture.paseoHome, "workspaces.json"),
|
||||
createLogger(),
|
||||
);
|
||||
const operations = new WorkspaceArchiveOperations();
|
||||
const now = "2026-11-24T00:00:00.000Z";
|
||||
const ws1 = createPersistedWorkspaceRecord({
|
||||
workspaceId: "ws-archive-target",
|
||||
projectId: "proj-1",
|
||||
displayName: "ws-archive-target",
|
||||
cwd: fixture.worktreePath,
|
||||
kind: "worktree",
|
||||
worktreeRoot: fixture.worktreePath,
|
||||
isPaseoOwnedWorktree: true,
|
||||
mainRepoRoot: fixture.repoDir,
|
||||
untrustedSource,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
const ws2 = createPersistedWorkspaceRecord({
|
||||
workspaceId: "ws-approve-sibling",
|
||||
projectId: "proj-1",
|
||||
displayName: "ws-approve-sibling",
|
||||
cwd: fixture.worktreePath,
|
||||
kind: "worktree",
|
||||
worktreeRoot: fixture.worktreePath,
|
||||
isPaseoOwnedWorktree: true,
|
||||
mainRepoRoot: fixture.repoDir,
|
||||
untrustedSource,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
await registry.upsert(ws1);
|
||||
await registry.upsert(ws2);
|
||||
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome: fixture.paseoHome,
|
||||
activeWorkspaces: [],
|
||||
});
|
||||
deps.workspaceArchiveOperations = operations;
|
||||
deps.getWorkspace = (id) => registry.get(id);
|
||||
deps.listActiveWorkspaces = () => registry.listActive();
|
||||
deps.archiveWorkspaceRecord = async (id, archivedAt) => {
|
||||
await registry.archive(id, archivedAt);
|
||||
};
|
||||
deps.assertWorkspaceAutomationAllowed = (id) =>
|
||||
assertWorkspaceAutomationAllowedForWorkspace(registry, id);
|
||||
deps.isCheckoutUntrusted = (checkoutPath) => isCheckoutUntrusted(registry, checkoutPath);
|
||||
|
||||
async function clearInsideCheckoutLock() {
|
||||
return clearWorkspaceAutomationBlock(registry, ws2.workspaceId, {
|
||||
checkoutPath: fixture.worktreePath,
|
||||
});
|
||||
}
|
||||
|
||||
if (order === "approval-first") {
|
||||
const [cleared, archived] = await Promise.all([
|
||||
operations.withCheckout(fixture.worktreePath, clearInsideCheckoutLock),
|
||||
archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId: ws1.workspaceId },
|
||||
requestId: `req-${order}-ws1`,
|
||||
}),
|
||||
]);
|
||||
expect(cleared).toBe(true);
|
||||
expect(archived.removedDirectory).toBe(false);
|
||||
} else {
|
||||
// Pause archive mid-flight (after resolving targets, before backfill) while Run setup
|
||||
// queues on the same checkout lock, ensuring approval runs after backfill and wins.
|
||||
let enteredStop!: () => void;
|
||||
let releaseStop!: () => void;
|
||||
const stopEntered = new Promise<void>((resolve) => {
|
||||
enteredStop = resolve;
|
||||
});
|
||||
const stopGate = new Promise<void>((resolve) => {
|
||||
releaseStop = resolve;
|
||||
});
|
||||
deps.stopWorkspaceSetup = async () => {
|
||||
enteredStop();
|
||||
await stopGate;
|
||||
};
|
||||
const archivePromise = archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId: ws1.workspaceId },
|
||||
requestId: `req-${order}-ws1`,
|
||||
});
|
||||
await stopEntered;
|
||||
const approvalPromise = operations.withCheckout(
|
||||
fixture.worktreePath,
|
||||
clearInsideCheckoutLock,
|
||||
);
|
||||
releaseStop();
|
||||
const [archived, cleared] = await Promise.all([archivePromise, approvalPromise]);
|
||||
expect(archived.removedDirectory).toBe(false);
|
||||
expect(cleared).toBe(true);
|
||||
deps.stopWorkspaceSetup = undefined;
|
||||
}
|
||||
|
||||
expect(
|
||||
(await readPaseoWorktreeMetadata(fixture.worktreePath))?.untrustedSource,
|
||||
).toBeUndefined();
|
||||
expect((await registry.get(ws2.workspaceId))?.untrustedSource).toBeUndefined();
|
||||
|
||||
const finalArchive = await archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId: ws2.workspaceId },
|
||||
requestId: `req-${order}-ws2`,
|
||||
});
|
||||
expect(finalArchive.removedDirectory).toBe(true);
|
||||
expect(readFileSync(fixture.marker, "utf8")).toBe("ran");
|
||||
},
|
||||
);
|
||||
|
||||
test("workspace scope skips teardown when an active sibling on the same checkout is blocked", async () => {
|
||||
const nestedRelative = path.join("packages", "app");
|
||||
const fixture = await createTeardownWorktree("shared-blocked-sibling", { nestedRelative });
|
||||
const blockedRootId = "ws-shared-blocked-root";
|
||||
const nestedWorkspaceId = "ws-shared-nested";
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome: fixture.paseoHome,
|
||||
activeWorkspaces: [
|
||||
makeWorktreeWorkspace(blockedRootId, fixture),
|
||||
makeWorktreeWorkspace(nestedWorkspaceId, fixture, {
|
||||
cwd: path.join(fixture.worktreePath, nestedRelative),
|
||||
}),
|
||||
],
|
||||
});
|
||||
deps.assertWorkspaceAutomationAllowed = async (workspaceId) => {
|
||||
if (workspaceId === blockedRootId) {
|
||||
throw new WorkspaceAutomationBlockedError(sampleBlockedSource());
|
||||
}
|
||||
};
|
||||
|
||||
const result = await archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId: nestedWorkspaceId },
|
||||
requestId: "req-shared-blocked-sibling",
|
||||
});
|
||||
|
||||
expect(result.archivedWorkspaceIds).toEqual([nestedWorkspaceId]);
|
||||
expect(result.removedDirectory).toBe(false);
|
||||
expect(existsSync(fixture.worktreePath)).toBe(true);
|
||||
expect(existsSync(fixture.marker)).toBe(false);
|
||||
});
|
||||
|
||||
test("worktree scope skips teardown when archiving an unrecorded worktree directory", async () => {
|
||||
const fixture = await createTeardownWorktree("unrecorded-worktree");
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome: fixture.paseoHome,
|
||||
activeWorkspaces: [],
|
||||
});
|
||||
|
||||
const result = await archiveByScope(deps, {
|
||||
scope: { kind: "worktree", targetPath: fixture.worktreePath },
|
||||
requestId: "req-unrecorded-worktree",
|
||||
});
|
||||
|
||||
expect(result.removedDirectory).toBe(true);
|
||||
expect(existsSync(fixture.worktreePath)).toBe(false);
|
||||
expect(existsSync(fixture.marker)).toBe(false);
|
||||
});
|
||||
|
||||
test("worktree scope skips teardown for nested siblings when any workspace on the checkout is blocked", async () => {
|
||||
const nestedRelative = path.join("packages", "app");
|
||||
const fixture = await createTeardownWorktree("blocked-sibling", { nestedRelative });
|
||||
const rootWorkspaceId = "ws-blocked-root";
|
||||
const nestedWorkspaceId = "ws-nested-sibling";
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome: fixture.paseoHome,
|
||||
activeWorkspaces: [
|
||||
makeWorktreeWorkspace(rootWorkspaceId, fixture),
|
||||
makeWorktreeWorkspace(nestedWorkspaceId, fixture, {
|
||||
cwd: path.join(fixture.worktreePath, nestedRelative),
|
||||
}),
|
||||
],
|
||||
});
|
||||
deps.assertWorkspaceAutomationAllowed = async (workspaceId) => {
|
||||
if (workspaceId === rootWorkspaceId) {
|
||||
throw new WorkspaceAutomationBlockedError(sampleBlockedSource());
|
||||
}
|
||||
};
|
||||
|
||||
const result = await archiveByScope(deps, {
|
||||
scope: { kind: "worktree", targetPath: fixture.worktreePath },
|
||||
requestId: "req-blocked-sibling",
|
||||
});
|
||||
|
||||
expect(result.archivedWorkspaceIds).toEqual(
|
||||
expect.arrayContaining([rootWorkspaceId, nestedWorkspaceId]),
|
||||
);
|
||||
expect(result.removedDirectory).toBe(true);
|
||||
expect(existsSync(fixture.worktreePath)).toBe(false);
|
||||
expect(existsSync(fixture.marker)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
test("workspace scope keeps a worktree for an active workspace in a subdirectory", async () => {
|
||||
const { tempDir, repoDir } = createGitRepo();
|
||||
const paseoHome = path.join(tempDir, ".paseo");
|
||||
|
||||
@@ -21,7 +21,14 @@ import type {
|
||||
} from "./workspace-registry.js";
|
||||
import { createRealpathAwarePathMatcher, isRealpathInsideRoot } from "../utils/path.js";
|
||||
import { runWithGitCommandPriority } from "../utils/run-git-command.js";
|
||||
import { WorkspaceAutomationBlockedError } from "./workspace-automation-gate.js";
|
||||
import {
|
||||
readPaseoWorktreeMetadata,
|
||||
setPaseoWorktreeUntrustedSource,
|
||||
} from "../utils/worktree-metadata.js";
|
||||
import {
|
||||
WorkspaceAutomationBlockedError,
|
||||
type UntrustedWorkspaceSource,
|
||||
} from "./workspace-automation-gate.js";
|
||||
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
|
||||
import type { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
|
||||
|
||||
@@ -59,8 +66,8 @@ export interface ArchiveDependencies {
|
||||
clearWorkspaceArchiving: (workspaceIds: Iterable<string>) => void;
|
||||
killTerminalsForWorkspace: (workspaceId: string) => Promise<void>;
|
||||
stopWorkspaceSetup?: (workspaceId: string) => Promise<void>;
|
||||
assertWorkspaceAutomationAllowed?: (workspaceId: string) => Promise<void>;
|
||||
isCheckoutUntrusted?: (checkoutPath: string) => Promise<boolean>;
|
||||
assertWorkspaceAutomationAllowed: (workspaceId: string) => Promise<void>;
|
||||
isCheckoutUntrusted: (checkoutPath: string) => Promise<boolean>;
|
||||
sessionLogger?: Logger;
|
||||
}
|
||||
|
||||
@@ -128,12 +135,17 @@ interface BackingDirectory {
|
||||
mainRepoRoot: string | null;
|
||||
paseoWorktreesRoot: string | null;
|
||||
worktreeManagerPluginId: string | null;
|
||||
untrusted: boolean;
|
||||
untrustedSource: UntrustedWorkspaceSource | null;
|
||||
}
|
||||
|
||||
interface ArchiveTarget {
|
||||
backing: BackingDirectory | null;
|
||||
teardownTargets: Array<{ workspaceId: string | null; cwd: string }>;
|
||||
teardownTargets: Array<{ workspaceId: string; cwd: string }>;
|
||||
// Active workspaces sharing the resolved backing checkout when archive starts
|
||||
// (including the records being archived and any active siblings). Keeps
|
||||
// teardown approval scoped to the live checkout rather than historical
|
||||
// archived records that previously occupied the same path.
|
||||
checkoutWorkspaceIds: string[];
|
||||
setupWorkspaceIds: string[];
|
||||
workspaceIds: string[];
|
||||
}
|
||||
@@ -275,6 +287,33 @@ async function resolveArchiveCheckoutPath(
|
||||
return (await resolveBackingDirectory(scope.targetPath, dependencies)).path;
|
||||
}
|
||||
|
||||
async function listActiveWorkspacesOnBacking(
|
||||
activeWorkspaces: ActiveWorkspaceRef[],
|
||||
backingPath: string,
|
||||
dependencies: Pick<ArchiveDependencies, "paseoHome" | "paseoWorktreesBaseRoot">,
|
||||
): Promise<ActiveWorkspaceRef[]> {
|
||||
const matchesBackingDirectory = createRealpathAwarePathMatcher(backingPath);
|
||||
return (
|
||||
await Promise.all(
|
||||
activeWorkspaces.map(async (workspace) => {
|
||||
const backingDirectory = await resolveWorkspaceBackingDirectory(workspace, dependencies);
|
||||
return matchesBackingDirectory(backingDirectory.path) ? workspace : null;
|
||||
}),
|
||||
)
|
||||
).filter((workspace): workspace is ActiveWorkspaceRef => workspace !== null);
|
||||
}
|
||||
|
||||
function firstUntrustedSource(
|
||||
primary: UntrustedWorkspaceSource | null,
|
||||
workspaces: ActiveWorkspaceRef[],
|
||||
): UntrustedWorkspaceSource | null {
|
||||
return (
|
||||
primary ??
|
||||
workspaces.find((workspace) => Boolean(workspace.untrustedSource))?.untrustedSource ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
async function resolveArchiveTarget(
|
||||
dependencies: ArchiveDependencies,
|
||||
scope: ArchiveScope,
|
||||
@@ -291,12 +330,37 @@ async function resolveArchiveTarget(
|
||||
{ workspaceId },
|
||||
"Workspace not found for archive-by-scope; skipping",
|
||||
);
|
||||
return { backing: null, teardownTargets: [], setupWorkspaceIds: [], workspaceIds: [] };
|
||||
return {
|
||||
backing: null,
|
||||
teardownTargets: [],
|
||||
checkoutWorkspaceIds: [],
|
||||
setupWorkspaceIds: [],
|
||||
workspaceIds: [],
|
||||
};
|
||||
}
|
||||
const isArchived = "archivedAt" in record && Boolean(record.archivedAt);
|
||||
const backing = await resolveWorkspaceBackingDirectory(record, dependencies);
|
||||
const activeOnCheckout = await listActiveWorkspacesOnBacking(
|
||||
activeWorkspaces,
|
||||
backing.path,
|
||||
dependencies,
|
||||
);
|
||||
const checkoutWorkspaceIds = Array.from(
|
||||
new Set([
|
||||
...(isArchived ? [] : [workspaceId]),
|
||||
...activeOnCheckout.map((workspace) => workspace.workspaceId),
|
||||
]),
|
||||
);
|
||||
return {
|
||||
backing: await resolveWorkspaceBackingDirectory(record, dependencies),
|
||||
backing: {
|
||||
...backing,
|
||||
untrustedSource: firstUntrustedSource(
|
||||
isArchived ? null : backing.untrustedSource,
|
||||
activeOnCheckout,
|
||||
),
|
||||
},
|
||||
teardownTargets: isArchived ? [] : [{ workspaceId, cwd: record.cwd }],
|
||||
checkoutWorkspaceIds,
|
||||
setupWorkspaceIds: [workspaceId],
|
||||
workspaceIds: isArchived ? [] : [workspaceId],
|
||||
};
|
||||
@@ -304,14 +368,11 @@ async function resolveArchiveTarget(
|
||||
|
||||
const backing = await resolveBackingDirectory(scope.targetPath, dependencies);
|
||||
const matchesBackingDirectory = createRealpathAwarePathMatcher(backing.path);
|
||||
const targetWorkspaces = (
|
||||
await Promise.all(
|
||||
activeWorkspaces.map(async (workspace) => {
|
||||
const backingDirectory = await resolveWorkspaceBackingDirectory(workspace, dependencies);
|
||||
return matchesBackingDirectory(backingDirectory.path) ? workspace : null;
|
||||
}),
|
||||
)
|
||||
).filter((workspace): workspace is ActiveWorkspaceRef => workspace !== null);
|
||||
const targetWorkspaces = await listActiveWorkspacesOnBacking(
|
||||
activeWorkspaces,
|
||||
backing.path,
|
||||
dependencies,
|
||||
);
|
||||
const recordedId = await dependencies.findWorkspaceIdForCwd(backing.path);
|
||||
const recorded = recordedId ? await dependencies.getWorkspace?.(recordedId) : null;
|
||||
const record =
|
||||
@@ -320,15 +381,19 @@ async function resolveArchiveTarget(
|
||||
? recorded
|
||||
: null) ??
|
||||
targetWorkspaces[0];
|
||||
const resolvedBacking = record
|
||||
? await resolveWorkspaceBackingDirectory(record, dependencies)
|
||||
: backing;
|
||||
return {
|
||||
backing: record ? await resolveWorkspaceBackingDirectory(record, dependencies) : backing,
|
||||
teardownTargets:
|
||||
targetWorkspaces.length > 0
|
||||
? targetWorkspaces.map((workspace) => ({
|
||||
workspaceId: workspace.workspaceId,
|
||||
cwd: workspace.cwd,
|
||||
}))
|
||||
: [{ workspaceId: null, cwd: scope.targetPath }],
|
||||
backing: {
|
||||
...resolvedBacking,
|
||||
untrustedSource: firstUntrustedSource(null, targetWorkspaces),
|
||||
},
|
||||
teardownTargets: targetWorkspaces.map((workspace) => ({
|
||||
workspaceId: workspace.workspaceId,
|
||||
cwd: workspace.cwd,
|
||||
})),
|
||||
checkoutWorkspaceIds: targetWorkspaces.map((workspace) => workspace.workspaceId),
|
||||
setupWorkspaceIds: targetWorkspaces.map((workspace) => workspace.workspaceId),
|
||||
workspaceIds: targetWorkspaces.map((workspace) => workspace.workspaceId),
|
||||
};
|
||||
@@ -360,7 +425,7 @@ async function resolveWorkspaceBackingDirectory(
|
||||
dependencies: Pick<ArchiveDependencies, "paseoHome" | "paseoWorktreesBaseRoot">,
|
||||
): Promise<BackingDirectory> {
|
||||
const worktreeManagerPluginId = workspace.worktreeManagerPluginId ?? null;
|
||||
const untrusted = Boolean(workspace.untrustedSource);
|
||||
const untrustedSource = workspace.untrustedSource ?? null;
|
||||
if (workspace.isPaseoOwnedWorktree === false) {
|
||||
return {
|
||||
path: resolve(workspace.worktreeRoot ?? workspace.cwd),
|
||||
@@ -370,7 +435,7 @@ async function resolveWorkspaceBackingDirectory(
|
||||
mainRepoRoot: workspace.mainRepoRoot ?? null,
|
||||
paseoWorktreesRoot: null,
|
||||
worktreeManagerPluginId,
|
||||
untrusted,
|
||||
untrustedSource,
|
||||
};
|
||||
}
|
||||
if (workspace.isPaseoOwnedWorktree && workspace.worktreeRoot && workspace.mainRepoRoot) {
|
||||
@@ -382,7 +447,7 @@ async function resolveWorkspaceBackingDirectory(
|
||||
mainRepoRoot: workspace.mainRepoRoot,
|
||||
paseoWorktreesRoot: null,
|
||||
worktreeManagerPluginId,
|
||||
untrusted,
|
||||
untrustedSource,
|
||||
};
|
||||
}
|
||||
if (workspace.kind !== "worktree") {
|
||||
@@ -394,7 +459,7 @@ async function resolveWorkspaceBackingDirectory(
|
||||
mainRepoRoot: workspace.mainRepoRoot ?? null,
|
||||
paseoWorktreesRoot: null,
|
||||
worktreeManagerPluginId,
|
||||
untrusted,
|
||||
untrustedSource,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -408,7 +473,7 @@ async function resolveWorkspaceBackingDirectory(
|
||||
...backing,
|
||||
mainRepoRoot: workspace.mainRepoRoot ?? backing.mainRepoRoot,
|
||||
worktreeManagerPluginId: worktreeManagerPluginId ?? backing.worktreeManagerPluginId,
|
||||
untrusted: untrusted || backing.untrusted,
|
||||
untrustedSource: untrustedSource ?? backing.untrustedSource,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -429,7 +494,7 @@ async function resolveBackingDirectory(
|
||||
mainRepoRoot: ownership.repoRoot ?? null,
|
||||
paseoWorktreesRoot: ownership.worktreeRoot ?? null,
|
||||
worktreeManagerPluginId: null,
|
||||
untrusted: false,
|
||||
untrustedSource: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -509,22 +574,20 @@ async function maybeRemoveDirectory(
|
||||
}
|
||||
|
||||
const archivedWorkspaceIdSet = new Set(archivedWorkspaceIds);
|
||||
const teardownTargets = target.teardownTargets.filter(
|
||||
(teardownTarget) =>
|
||||
teardownTarget.workspaceId === null || archivedWorkspaceIdSet.has(teardownTarget.workspaceId),
|
||||
const teardownTargets = target.teardownTargets.filter((teardownTarget) =>
|
||||
archivedWorkspaceIdSet.has(teardownTarget.workspaceId),
|
||||
);
|
||||
|
||||
const teardownPlan = await resolveCheckoutTeardownPlan(
|
||||
dependencies,
|
||||
backing,
|
||||
teardownTargets,
|
||||
target.checkoutWorkspaceIds,
|
||||
);
|
||||
let untrustedBacking =
|
||||
backing.untrusted || Boolean(await dependencies.isCheckoutUntrusted?.(backing.path));
|
||||
teardownPlan.untrustedBacking || Boolean(await dependencies.isCheckoutUntrusted(backing.path));
|
||||
try {
|
||||
const allowedTeardownTargets = await filterAllowedTeardownTargets(
|
||||
dependencies,
|
||||
teardownTargets,
|
||||
);
|
||||
if (allowedTeardownTargets.length < teardownTargets.length) {
|
||||
untrustedBacking = true;
|
||||
}
|
||||
for (const teardownTarget of uniqueTeardownTargets(allowedTeardownTargets)) {
|
||||
for (const teardownTarget of uniqueTeardownTargets(teardownPlan.allowedTargets)) {
|
||||
request.checkpoint();
|
||||
await runWorktreeTeardownCommands({
|
||||
worktreePath: backing.path,
|
||||
@@ -584,25 +647,66 @@ async function maybeRemoveDirectory(
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveCheckoutTeardownPlan(
|
||||
dependencies: ArchiveDependencies,
|
||||
backing: BackingDirectory,
|
||||
teardownTargets: Array<{ workspaceId: string; cwd: string }>,
|
||||
checkoutWorkspaceIds: string[],
|
||||
): Promise<{
|
||||
allowedTargets: Array<{ workspaceId: string; cwd: string }>;
|
||||
untrustedBacking: boolean;
|
||||
}> {
|
||||
const metadataUntrustedSource =
|
||||
(await readPaseoWorktreeMetadata(backing.path).catch(() => null))?.untrustedSource ?? null;
|
||||
const checkoutUntrusted = Boolean(backing.untrustedSource || metadataUntrustedSource);
|
||||
const teardownGate = checkoutUntrusted
|
||||
? { allowed: [] as Array<{ workspaceId: string; cwd: string }>, blockedSource: null }
|
||||
: await filterAllowedTeardownTargets(dependencies, teardownTargets, checkoutWorkspaceIds);
|
||||
const untrustedSourceToPersist =
|
||||
teardownTargets.length === 0 || metadataUntrustedSource
|
||||
? null
|
||||
: (backing.untrustedSource ?? teardownGate.blockedSource);
|
||||
if (untrustedSourceToPersist) {
|
||||
// Runs inside workspaceArchiveOperations.withCheckout alongside Run setup approval,
|
||||
// so retained pre-upgrade checkouts keep their block without racing approval clears.
|
||||
await setPaseoWorktreeUntrustedSource(backing.path, untrustedSourceToPersist).catch(
|
||||
() => false,
|
||||
);
|
||||
}
|
||||
return {
|
||||
allowedTargets: teardownGate.allowed,
|
||||
untrustedBacking: checkoutUntrusted || teardownGate.allowed.length < teardownTargets.length,
|
||||
};
|
||||
}
|
||||
|
||||
async function filterAllowedTeardownTargets(
|
||||
dependencies: ArchiveDependencies,
|
||||
targets: Array<{ workspaceId: string | null; cwd: string }>,
|
||||
): Promise<Array<{ workspaceId: string | null; cwd: string }>> {
|
||||
const allowed: Array<{ workspaceId: string | null; cwd: string }> = [];
|
||||
const blockedCwds: string[] = [];
|
||||
for (const target of targets) {
|
||||
targets: Array<{ workspaceId: string; cwd: string }>,
|
||||
checkoutWorkspaceIds: string[],
|
||||
): Promise<{
|
||||
allowed: Array<{ workspaceId: string; cwd: string }>;
|
||||
blockedSource: UntrustedWorkspaceSource | null;
|
||||
}> {
|
||||
if (targets.length === 0) {
|
||||
return { allowed: [], blockedSource: null };
|
||||
}
|
||||
if (typeof dependencies.assertWorkspaceAutomationAllowed !== "function") {
|
||||
return { allowed: [], blockedSource: null };
|
||||
}
|
||||
const workspaceIdsToCheck = Array.from(
|
||||
new Set([...targets.map((target) => target.workspaceId), ...checkoutWorkspaceIds]),
|
||||
);
|
||||
for (const workspaceId of workspaceIdsToCheck) {
|
||||
try {
|
||||
if (target.workspaceId)
|
||||
await dependencies.assertWorkspaceAutomationAllowed?.(target.workspaceId);
|
||||
allowed.push(target);
|
||||
await dependencies.assertWorkspaceAutomationAllowed(workspaceId);
|
||||
} catch (error) {
|
||||
if (!(error instanceof WorkspaceAutomationBlockedError)) throw error;
|
||||
blockedCwds.push(target.cwd);
|
||||
// Every workspace in checkoutWorkspaceIds shares the same backing checkout;
|
||||
// if any active workspace on it is blocked, skip teardown for the checkout.
|
||||
return { allowed: [], blockedSource: error.source };
|
||||
}
|
||||
}
|
||||
return allowed.filter(
|
||||
(target) => !blockedCwds.some((cwd) => createRealpathAwarePathMatcher(cwd)(target.cwd)),
|
||||
);
|
||||
return { allowed: targets, blockedSource: null };
|
||||
}
|
||||
|
||||
function uniqueTeardownTargets<T extends { cwd: string }>(targets: T[]): T[] {
|
||||
|
||||
@@ -1,9 +1,28 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { chmodSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
getPaseoWorktreeMetadataPath,
|
||||
readPaseoWorktreeMetadata,
|
||||
writePaseoWorktreeMetadata,
|
||||
} from "../utils/worktree-metadata.js";
|
||||
import {
|
||||
WorkspaceAutomationBlockedError,
|
||||
assertWorkspaceAutomationAllowed,
|
||||
clearWorkspaceAutomationBlock,
|
||||
formatWorkspaceAutomationBlockedMessage,
|
||||
} from "./workspace-automation-gate.js";
|
||||
import type { PersistedWorkspaceRecord } from "./workspace-registry.js";
|
||||
|
||||
const cleanupPaths: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const target of cleanupPaths.splice(0)) {
|
||||
rmSync(target, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("workspace automation gate", () => {
|
||||
it("refuses executable repository automation for a cross-repository change request", () => {
|
||||
@@ -43,4 +62,96 @@ describe("workspace automation gate", () => {
|
||||
}),
|
||||
).toBe(`Scripts are blocked for ${noun} #42 from contributor/paseo. Run setup to allow them.`);
|
||||
});
|
||||
|
||||
async function createUntrustedWorktreeFixture(number: number) {
|
||||
const tempDir = mkdtempSync(path.join(tmpdir(), `automation-gate-${number}-`));
|
||||
cleanupPaths.push(tempDir);
|
||||
const repoDir = path.join(tempDir, "repo");
|
||||
const worktreeDir = path.join(tempDir, "wt");
|
||||
mkdirSync(repoDir, { recursive: true });
|
||||
execFileSync("git", ["init", "-b", "main"], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["config", "user.email", "test@getpaseo.local"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
execFileSync("git", ["config", "user.name", "Paseo Test"], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "--allow-empty", "-m", "init"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
execFileSync("git", ["worktree", "add", "-b", `pr-${number}`, worktreeDir, "main"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const source = {
|
||||
kind: "change_request" as const,
|
||||
forge: "github",
|
||||
number,
|
||||
headRepository: "contributor/paseo",
|
||||
};
|
||||
await writePaseoWorktreeMetadata(worktreeDir, { baseRefName: "main", untrustedSource: source });
|
||||
const records = new Map<string, PersistedWorkspaceRecord>([
|
||||
[
|
||||
"ws-1",
|
||||
{
|
||||
workspaceId: "ws-1",
|
||||
projectId: "proj-1",
|
||||
cwd: worktreeDir,
|
||||
kind: "worktree",
|
||||
worktreeRoot: worktreeDir,
|
||||
isPaseoOwnedWorktree: true,
|
||||
mainRepoRoot: repoDir,
|
||||
untrustedSource: source,
|
||||
createdAt: "2026-11-24T00:00:00.000Z",
|
||||
updatedAt: "2026-11-24T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
]);
|
||||
const registry = {
|
||||
listAll: async () => Array.from(records.values()),
|
||||
update: async (
|
||||
id: string,
|
||||
updater: (record: PersistedWorkspaceRecord) => PersistedWorkspaceRecord,
|
||||
) => {
|
||||
const current = records.get(id);
|
||||
if (!current) return null;
|
||||
const next = updater(current);
|
||||
records.set(id, next);
|
||||
return next;
|
||||
},
|
||||
};
|
||||
return { worktreeDir, source, records, registry };
|
||||
}
|
||||
|
||||
it("clears untrustedSource from both workspace records and worktree metadata", async () => {
|
||||
const { worktreeDir, records, registry } = await createUntrustedWorktreeFixture(42);
|
||||
|
||||
const cleared = await clearWorkspaceAutomationBlock(registry, "ws-1");
|
||||
|
||||
expect(cleared).toBe(true);
|
||||
expect(records.get("ws-1")?.untrustedSource).toBeUndefined();
|
||||
expect((await readPaseoWorktreeMetadata(worktreeDir))?.untrustedSource).toBeUndefined();
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
|
||||
"fails without clearing workspace records when worktree metadata cannot be written",
|
||||
async () => {
|
||||
const { worktreeDir, source, records, registry } = await createUntrustedWorktreeFixture(43);
|
||||
const metadataDir = path.dirname(await getPaseoWorktreeMetadataPath(worktreeDir));
|
||||
|
||||
chmodSync(metadataDir, 0o555);
|
||||
try {
|
||||
await expect(clearWorkspaceAutomationBlock(registry, "ws-1")).rejects.toThrow();
|
||||
expect(records.get("ws-1")?.untrustedSource).toEqual(source);
|
||||
expect((await readPaseoWorktreeMetadata(worktreeDir))?.untrustedSource).toEqual(source);
|
||||
} finally {
|
||||
chmodSync(metadataDir, 0o755);
|
||||
}
|
||||
|
||||
const retried = await clearWorkspaceAutomationBlock(registry, "ws-1");
|
||||
expect(retried).toBe(true);
|
||||
expect(records.get("ws-1")?.untrustedSource).toBeUndefined();
|
||||
expect((await readPaseoWorktreeMetadata(worktreeDir))?.untrustedSource).toBeUndefined();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createRealpathAwarePathMatcher } from "../utils/path.js";
|
||||
import { setPaseoWorktreeUntrustedSource } from "../utils/worktree-metadata.js";
|
||||
import type { WorkspaceRegistry } from "./workspace-registry.js";
|
||||
|
||||
export interface UntrustedWorkspaceSource {
|
||||
@@ -51,23 +52,26 @@ export async function isCheckoutUntrusted(
|
||||
export async function clearWorkspaceAutomationBlock(
|
||||
registry: Pick<WorkspaceRegistry, "update" | "listAll">,
|
||||
workspaceId: string,
|
||||
options?: { checkoutPath?: string | null },
|
||||
): Promise<boolean> {
|
||||
let cleared = false;
|
||||
const allWorkspaces = await registry.listAll();
|
||||
const target = allWorkspaces.find((record) => record.workspaceId === workspaceId);
|
||||
if (!target) throw new Error(`Workspace not found: ${workspaceId}`);
|
||||
const checkoutPath = options?.checkoutPath ?? target.worktreeRoot ?? target.cwd;
|
||||
// Clear checkout metadata before mutating workspace records so a failed metadata
|
||||
// write surfaces an error and leaves workspace records intact to retry approval.
|
||||
let cleared = await setPaseoWorktreeUntrustedSource(checkoutPath, null);
|
||||
const timestamp = new Date().toISOString();
|
||||
const workspace = await registry.update(workspaceId, (record) => {
|
||||
if (!record.untrustedSource) return record;
|
||||
cleared = true;
|
||||
const { untrustedSource: _removed, ...trusted } = record;
|
||||
return { ...trusted, updatedAt: timestamp };
|
||||
});
|
||||
if (!workspace) throw new Error(`Workspace not found: ${workspaceId}`);
|
||||
const checkoutPath = workspace.worktreeRoot ?? workspace.cwd;
|
||||
const matchesCheckout = createRealpathAwarePathMatcher(checkoutPath);
|
||||
const siblings = await registry.listAll();
|
||||
for (const sibling of siblings) {
|
||||
if (sibling.workspaceId === workspaceId || !sibling.untrustedSource) continue;
|
||||
if (!matchesCheckout(sibling.worktreeRoot ?? sibling.cwd)) continue;
|
||||
await registry.update(sibling.workspaceId, (record) => {
|
||||
for (const candidate of allWorkspaces) {
|
||||
if (!candidate.untrustedSource) continue;
|
||||
if (
|
||||
candidate.workspaceId !== workspaceId &&
|
||||
!matchesCheckout(candidate.worktreeRoot ?? candidate.cwd)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
await registry.update(candidate.workspaceId, (record) => {
|
||||
if (!record.untrustedSource) return record;
|
||||
cleared = true;
|
||||
const { untrustedSource: _removed, ...trusted } = record;
|
||||
|
||||
@@ -29,6 +29,7 @@ import type { ChangeRequestCheckoutSource, FirstAgentContext } from "@getpaseo/p
|
||||
import type { WorkspaceGitService } from "./workspace-git-service.js";
|
||||
import { runWithRepositoryRoot } from "../utils/git-repository-discovery.js";
|
||||
import { runGitCommand, runWithGitCommandPriority } from "../utils/run-git-command.js";
|
||||
import { setPaseoWorktreeUntrustedSource } from "../utils/worktree-metadata.js";
|
||||
|
||||
import type { UntrustedWorkspaceSource } from "./workspace-automation-gate.js";
|
||||
|
||||
@@ -185,18 +186,9 @@ async function createWorktreeAtRepositoryRoot(
|
||||
input,
|
||||
deps,
|
||||
});
|
||||
if (managedWorktree) {
|
||||
return {
|
||||
worktree: managedWorktree,
|
||||
intent,
|
||||
untrustedSource,
|
||||
repoRoot,
|
||||
created: true,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
worktree: await createWorktree({
|
||||
const createdWorktree =
|
||||
managedWorktree ??
|
||||
(await createWorktree({
|
||||
cwd: repoRoot,
|
||||
worktreeSlug: normalizedSlug,
|
||||
worktreePath: transformed.path,
|
||||
@@ -204,7 +196,12 @@ async function createWorktreeAtRepositoryRoot(
|
||||
preparedBranchOff,
|
||||
paseoHome: input.paseoHome,
|
||||
worktreesRoot: input.worktreesRoot,
|
||||
}),
|
||||
}));
|
||||
if (untrustedSource) {
|
||||
await setPaseoWorktreeUntrustedSource(createdWorktree.worktreePath, untrustedSource);
|
||||
}
|
||||
return {
|
||||
worktree: createdWorktree,
|
||||
intent,
|
||||
untrustedSource,
|
||||
repoRoot,
|
||||
|
||||
@@ -1756,6 +1756,8 @@ describe("handlePaseoWorktreeArchiveRequest worktree scope", () => {
|
||||
markWorkspaceArchiving: vi.fn(),
|
||||
clearWorkspaceArchiving: vi.fn(),
|
||||
killTerminalsForWorkspace: vi.fn(async () => {}),
|
||||
assertWorkspaceAutomationAllowed: async () => {},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
sessionLogger: createLogger(),
|
||||
},
|
||||
{
|
||||
@@ -1832,6 +1834,8 @@ describe("handlePaseoWorktreeArchiveRequest worktree scope", () => {
|
||||
markWorkspaceArchiving: vi.fn(),
|
||||
clearWorkspaceArchiving: vi.fn(),
|
||||
killTerminalsForWorkspace: vi.fn(async () => {}),
|
||||
assertWorkspaceAutomationAllowed: async () => {},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
sessionLogger: createLogger(),
|
||||
},
|
||||
{
|
||||
@@ -1909,6 +1913,8 @@ describe("handlePaseoWorktreeArchiveRequest worktree scope", () => {
|
||||
markWorkspaceArchiving: vi.fn(),
|
||||
clearWorkspaceArchiving: vi.fn(),
|
||||
killTerminalsForWorkspace: vi.fn(async () => {}),
|
||||
assertWorkspaceAutomationAllowed: async () => {},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
sessionLogger: createLogger(),
|
||||
},
|
||||
{
|
||||
@@ -1982,6 +1988,8 @@ describe("handlePaseoWorktreeArchiveRequest worktree scope", () => {
|
||||
markWorkspaceArchiving: vi.fn(),
|
||||
clearWorkspaceArchiving: vi.fn(),
|
||||
killTerminalsForWorkspace: vi.fn(async () => {}),
|
||||
assertWorkspaceAutomationAllowed: async () => {},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
sessionLogger: createLogger(),
|
||||
};
|
||||
|
||||
|
||||
@@ -14,6 +14,13 @@ const ChangeRequestLookupTargetSchema = z.object({
|
||||
localBranchName: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
const UntrustedWorktreeSourceSchema = z.object({
|
||||
kind: z.literal("change_request"),
|
||||
forge: z.string().min(1),
|
||||
number: z.number().int().positive(),
|
||||
headRepository: z.string().min(1),
|
||||
});
|
||||
|
||||
// baseRefName is the display name; baseRef is the checkout's current exact base
|
||||
// ("refs/remotes/upstream/main"). baseRef is optional because worktrees written before it
|
||||
// existed only have the name — there are no migrations, so readers fall back.
|
||||
@@ -23,6 +30,7 @@ const PaseoWorktreeMetadataV1Schema = z.object({
|
||||
baseRef: z.string().min(1).optional(),
|
||||
changeRequestLookupTarget: ChangeRequestLookupTargetSchema.optional(),
|
||||
worktreeManagerPluginId: z.string().min(1).optional(),
|
||||
untrustedSource: UntrustedWorktreeSourceSchema.optional(),
|
||||
});
|
||||
|
||||
const PaseoWorktreeMetadataV2Schema = z.object({
|
||||
@@ -31,6 +39,7 @@ const PaseoWorktreeMetadataV2Schema = z.object({
|
||||
baseRef: z.string().min(1).optional(),
|
||||
changeRequestLookupTarget: ChangeRequestLookupTargetSchema.optional(),
|
||||
worktreeManagerPluginId: z.string().min(1).optional(),
|
||||
untrustedSource: UntrustedWorktreeSourceSchema.optional(),
|
||||
firstAgentBranchAutoName: z
|
||||
.discriminatedUnion("status", [
|
||||
z.object({
|
||||
@@ -58,6 +67,7 @@ const PaseoWorktreeMetadataSchema = z.union([
|
||||
|
||||
export type PaseoWorktreeMetadata = z.infer<typeof PaseoWorktreeMetadataSchema>;
|
||||
export type PaseoWorktreeChangeRequestHint = z.infer<typeof ChangeRequestLookupTargetSchema>;
|
||||
export type PaseoWorktreeUntrustedSource = z.infer<typeof UntrustedWorktreeSourceSchema>;
|
||||
|
||||
export function createPaseoWorktreeChangeRequestHint(
|
||||
input: PaseoWorktreeChangeRequestHint,
|
||||
@@ -230,6 +240,7 @@ export async function writePaseoWorktreeMetadata(
|
||||
baseRef?: string;
|
||||
changeRequestLookupTarget?: PaseoWorktreeChangeRequestHint;
|
||||
worktreeManagerPluginId?: string;
|
||||
untrustedSource?: PaseoWorktreeUntrustedSource;
|
||||
},
|
||||
): Promise<void> {
|
||||
return mutateMetadata(worktreeRoot, async (root) => {
|
||||
@@ -250,11 +261,41 @@ export async function writePaseoWorktreeMetadata(
|
||||
...(options.worktreeManagerPluginId
|
||||
? { worktreeManagerPluginId: options.worktreeManagerPluginId }
|
||||
: {}),
|
||||
...(options.untrustedSource ? { untrustedSource: options.untrustedSource } : {}),
|
||||
};
|
||||
await writePaseoWorktreeMetadataFile(root, metadata);
|
||||
});
|
||||
}
|
||||
|
||||
export async function setPaseoWorktreeUntrustedSource(
|
||||
worktreeRoot: string,
|
||||
untrustedSource: PaseoWorktreeUntrustedSource | null,
|
||||
): Promise<boolean> {
|
||||
return mutateMetadata(worktreeRoot, async (root) => {
|
||||
let current: PaseoWorktreeMetadata | null;
|
||||
try {
|
||||
current = await readMetadataFile(root);
|
||||
} catch (error) {
|
||||
const cause = (error as { cause?: NodeJS.ErrnoException }).cause;
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT" || cause?.code === "ENOENT") {
|
||||
return false;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (!current) {
|
||||
return false;
|
||||
}
|
||||
const hadUntrustedSource = Boolean(current.untrustedSource);
|
||||
if (!untrustedSource && !hadUntrustedSource) {
|
||||
return false;
|
||||
}
|
||||
const { untrustedSource: _previous, ...rest } = current;
|
||||
const next: PaseoWorktreeMetadata = untrustedSource ? { ...rest, untrustedSource } : rest;
|
||||
await writePaseoWorktreeMetadataFile(root, next);
|
||||
return untrustedSource ? true : hadUntrustedSource;
|
||||
});
|
||||
}
|
||||
|
||||
export async function setPaseoWorktreeBaseRef(input: {
|
||||
worktreeRoot: string;
|
||||
baseRef: string;
|
||||
|
||||
Reference in New Issue
Block a user