fix(plugins): pass untrusted on create, clean up rejected worktrees, and sync docs

This commit is contained in:
Mohamed Boudra
2026-11-20 08:30:52 +01:00
parent 524116e111
commit c1d10b4e75
11 changed files with 180 additions and 51 deletions
+2 -2
View File
@@ -478,8 +478,8 @@ worktree commands. Paseo snapshots existing worktree paths before calling `creat
cannot adopt a pre-existing directory as Paseo-owned, verifies Git worktree postconditions, records
`worktreeManagerPluginId` in `paseo/worktree.json` and on the workspace record,
and skips first-agent branch auto-rename. Removal saves `refs/paseo/kept-commits/<sha>` before
calling the owning plugin's `remove`, and both `remove` and `restore` carry `untrusted` for fork
change requests and fall back to built-in Git when the plugin declines or is disabled. See the
calling the owning plugin's `remove`, and `create`, `remove`, and `restore` carry `untrusted` for fork
change requests; `remove` and `restore` fall back to built-in Git when the plugin declines or is disabled. See the
[worktree managers reference](../public-docs/plugins/reference.md#worktree-managers) and
`plugin-examples/worktrunk`.
+4 -1
View File
@@ -608,11 +608,14 @@ describe("worktree manager SDK boundary", () => {
export default function contribute(server: PluginServerContext) {
const manager: WorktreeManagerRegistration = {
async create(request: PluginWorktreeCreateInput, { paseo, signal }) {
const untrusted: boolean = request.untrusted;
// @ts-expect-error untrusted is read-only
request.untrusted = true;
if (request.kind === "branch-off") {
const start: string = request.startPoint ?? request.baseRef;
// @ts-expect-error startPoint is read-only
request.startPoint = "other";
if (!start) return;
if (!start || untrusted) return;
}
if (signal.aborted) return;
void paseo;
+4 -1
View File
@@ -4,7 +4,10 @@ import type { PluginHookContext, PluginWorktreeCreateRequest } from "./lifecycle
export type PluginWorktreeContext = PluginHookContext;
/** Resolved creation request handed to a worktree manager after `worktree.create.before`. */
export type PluginWorktreeCreateInput = PluginWorktreeCreateRequest;
export type PluginWorktreeCreateInput = PluginWorktreeCreateRequest & {
/** True when the worktree comes from an untrusted source such as a fork change request; skip repository-defined hooks. */
readonly untrusted: boolean;
};
/** Return `{ type: "created", path }` to claim creation, or `undefined` to decline. */
export interface PluginWorktreeCreateResult {
@@ -10,6 +10,7 @@ import type { PersistedWorkspaceRecord } from "./workspace-registry.js";
import type { WorkspaceProvisioningService } from "./session/workspace-provisioning/workspace-provisioning-service.js";
import {
createWorktreeCore,
isUntrustedWorktreeCreationIntent,
type CreateWorktreeCoreDeps,
type CreateWorktreeCoreInput,
} from "./worktree-core.js";
@@ -158,9 +159,7 @@ async function createPaseoWorktreeWithPriority(
worktreeManagers: deps.worktreeManagers,
worktreeManagerPluginId: createdWorktree.worktree.worktreeManagerPluginId ?? null,
removeReason: "rollback",
untrusted:
createdWorktree.intent.kind === "checkout-change-request" &&
Boolean(createdWorktree.intent.headRepository),
untrusted: isUntrustedWorktreeCreationIntent(createdWorktree.intent),
},
error,
);
@@ -485,7 +485,21 @@ export default function contribute(server) {
});
return { type: "created", path: target };
}
return { type: "created", path: "relative/path" };
if (request.branch === "throw-after-create") {
if (request.untrusted !== false) {
throw new Error("expected untrusted=false on branch-off create");
}
const target = path.join(${JSON.stringify(root)}, "orphan-wt");
execFileSync("git", ["worktree", "add", "-b", request.branch, target, "main"], {
cwd: request.repoRoot,
stdio: "pipe",
});
throw new Error("timed out before returning path");
}
if (request.branch === "relative") {
return { type: "created", path: "relative/path" };
}
return;
},
});
}
@@ -504,6 +518,7 @@ export default function contribute(server) {
["plain-dir", "did not create a Git worktree"],
["other-repo", "outside the repository"],
["detached", "detached HEAD"],
["throw-after-create", "timed out before returning path"],
["relative", "relative path"],
];
for (const [branchName, expectedError] of cases) {
@@ -520,6 +535,10 @@ export default function contribute(server) {
// The newly created detached worktree failed adoption and must be rolled back cleanly.
await expect(stat(path.join(root, "detached-wt"))).rejects.toMatchObject({ code: "ENOENT" });
expect(git(repository, ["worktree", "list", "--porcelain"])).not.toContain("detached-wt");
// The worktree and new branch left behind when create threw before returning must be cleaned up.
await expect(stat(path.join(root, "orphan-wt"))).rejects.toMatchObject({ code: "ENOENT" });
expect(git(repository, ["worktree", "list", "--porcelain"])).not.toContain("orphan-wt");
expect(git(repository, ["branch", "--list", "throw-after-create"])).toBe("");
} finally {
await client.close();
await daemon.close();
@@ -7,9 +7,11 @@ import { runGitCommand } from "../../../utils/run-git-command.js";
import {
adoptPluginWorktree,
cleanupFailedPluginWorktree,
cleanupOrphanedPluginWorktreeOnReject,
createWorktree,
isPaseoOwnedWorktreeCwd,
listGitWorktreePaths,
localBranchExists,
mapWorkspaceCwdToWorktree,
rollbackCreatedPaseoWorktree,
type WorktreeSource,
@@ -277,16 +279,35 @@ export function createWorkspaceRecoveryService(deps: {
const untrusted = Boolean(workspace.untrustedSource);
if (managerPluginId && hasRecordedWorktreePath && deps.worktreeManagers) {
const existingWorktreePaths = await listGitWorktreePaths(sourceRepoRoot);
const managed = await deps.worktreeManagers.restoreWorktree(
{
repoRoot: sourceRepoRoot,
path: previousWorktreePath,
target: restoreTargetFromWorktreeSource(source),
baseRef: workspace.baseBranch,
untrusted,
},
{ preferredPluginId: managerPluginId },
);
const restoreBranch = source.kind === "restore-commit" ? null : source.branchName;
const branchExistedBefore =
source.kind === "restore-from-base"
? await localBranchExists(sourceRepoRoot, source.branchName)
: true;
let managed: { pluginId: string; path: string } | null;
try {
managed = await deps.worktreeManagers.restoreWorktree(
{
repoRoot: sourceRepoRoot,
path: previousWorktreePath,
target: restoreTargetFromWorktreeSource(source),
baseRef: workspace.baseBranch,
untrusted,
},
{ preferredPluginId: managerPluginId },
);
} catch (error) {
await cleanupOrphanedPluginWorktreeOnReject({
cwd: sourceRepoRoot,
existingWorktreePaths,
expectedPath: previousWorktreePath,
expectedBranch: restoreBranch,
branchExistedBefore,
paseoHome: deps.paseoHome,
worktreesBaseRoot: deps.worktreesRoot,
}).catch(() => {});
throw error;
}
if (managed) {
try {
const validatedPath = await validateWorktreePath({
+29 -3
View File
@@ -1,4 +1,7 @@
import type { PluginWorktreeCreateRequest } from "@getpaseo/plugin/server";
import type {
PluginWorktreeCreateInput,
PluginWorktreeCreateRequest,
} from "@getpaseo/plugin/server";
import type { PluginLifecycle } from "./plugins/lifecycle/index.js";
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
import { createNameId } from "mnemonic-id";
@@ -7,9 +10,11 @@ import type { ForgeService } from "../services/forge-service.js";
import {
adoptPluginWorktree,
cleanupFailedPluginWorktree,
cleanupOrphanedPluginWorktreeOnReject,
createWorktree,
fetchFirstAvailableRef,
listGitWorktreePaths,
localBranchExists,
resolveDefaultWorktreePath,
slugify,
validateBranchSlug,
@@ -186,6 +191,10 @@ async function createWorktreeCoreWithPriority(
};
}
export function isUntrustedWorktreeCreationIntent(intent: WorktreeCreationIntent): boolean {
return intent.kind === "checkout-change-request" && Boolean(intent.headRepository);
}
async function tryCreateWithWorktreeManager(options: {
repoRoot: string;
transformed: PluginWorktreeCreateRequest;
@@ -196,9 +205,26 @@ async function tryCreateWithWorktreeManager(options: {
const { repoRoot, transformed, intent, input, deps } = options;
if (!deps.worktreeManagers) return null;
const existingWorktreePaths = await listGitWorktreePaths(repoRoot);
const managed = await deps.worktreeManagers.createWorktree(transformed);
const untrusted = isUntrustedWorktreeCreationIntent(intent);
const branchExistedBefore =
intent.kind === "branch-off" ? await localBranchExists(repoRoot, transformed.branch) : true;
const createRequest: PluginWorktreeCreateInput = { ...transformed, untrusted };
let managed: { pluginId: string; path: string } | null;
try {
managed = await deps.worktreeManagers.createWorktree(createRequest);
} catch (error) {
await cleanupOrphanedPluginWorktreeOnReject({
cwd: repoRoot,
existingWorktreePaths,
expectedPath: transformed.path,
expectedBranch: transformed.branch,
branchExistedBefore,
paseoHome: input.paseoHome,
worktreesBaseRoot: input.worktreesRoot,
}).catch(() => {});
throw error;
}
if (!managed) return null;
const untrusted = intent.kind === "checkout-change-request" && Boolean(intent.headRepository);
try {
const validatedPath = await validateWorktreePath({
candidate: managed.path,
+59 -1
View File
@@ -1671,6 +1671,64 @@ export interface AdoptPluginWorktreeOptions {
existingWorktreePaths?: ReadonlySet<string>;
}
/**
* Roll back a newly created worktree when a worktree manager's `create` or
* `restore` call rejects (timeout, abort, crash, or thrown error) without
* returning a path. Only removes worktrees absent from `existingWorktreePaths`
* whose path matches `expectedPath` or whose checked-out branch matches
* `expectedBranch`, so concurrent worktree creations are never touched.
*/
export async function cleanupOrphanedPluginWorktreeOnReject(options: {
cwd: string;
existingWorktreePaths: ReadonlySet<string>;
expectedPath?: string;
expectedBranch?: string | null;
branchExistedBefore?: boolean;
paseoHome?: string;
worktreesBaseRoot?: string;
}): Promise<void> {
const {
cwd,
existingWorktreePaths,
expectedPath,
expectedBranch,
branchExistedBefore = true,
paseoHome,
worktreesBaseRoot,
} = options;
const normalizedExpectedPath = expectedPath
? await normalizePathForOwnership(expectedPath)
: null;
const { stdout } = await runGitCommand(["worktree", "list", "--porcelain"], {
cwd,
envOverlay: READ_ONLY_GIT_ENV,
}).catch(() => ({ stdout: "" }));
let removedWorktree = false;
for (const entry of parseWorktreeList(stdout)) {
const entryPath = await normalizePathForOwnership(entry.path);
if (existingWorktreePaths.has(entryPath)) continue;
const matchesPath = normalizedExpectedPath !== null && entryPath === normalizedExpectedPath;
const matchesBranch = Boolean(expectedBranch && entry.branchName === expectedBranch);
if (!matchesPath && !matchesBranch) continue;
await deletePaseoWorktree({
cwd,
worktreePath: entryPath,
teardownCwds: [],
paseoHome,
worktreesBaseRoot,
registryProven: true,
}).catch(() => {});
removedWorktree = true;
}
if (
expectedBranch &&
!branchExistedBefore &&
(removedWorktree || (await localBranchExists(cwd, expectedBranch)))
) {
await runGitCommand(["branch", "-D", expectedBranch], { cwd }).catch(() => {});
}
}
/**
* Roll back a newly created worktree that failed adoption or path verification.
* Only touches a directory that was absent from `existingWorktreePaths` and
@@ -2431,7 +2489,7 @@ async function uniqueRemoteTrackingBranch(cwd: string, branchName: string): Prom
return candidates.length === 1 ? candidates[0] : null;
}
async function localBranchExists(cwd: string, branchName: string): Promise<boolean> {
export async function localBranchExists(cwd: string, branchName: string): Promise<boolean> {
try {
await runGitCommand(["show-ref", "--verify", "--quiet", `refs/heads/${branchName}`], {
cwd,
+1 -5
View File
@@ -92,10 +92,6 @@ function parseSwitchOutput(stdout: string): SwitchJsonOutput {
return parsed;
}
function isUntrustedCreate(request: PluginWorktreeCreateInput): boolean {
return request.kind === "checkout-change-request" && Boolean(request.headRepository);
}
function hookFlags(untrusted: boolean): string[] {
// Never approve repository-defined hooks on untrusted checkouts such as fork PRs.
return untrusted ? ["--no-hooks"] : ["--yes"];
@@ -107,7 +103,7 @@ export function buildCreateArgs(request: PluginWorktreeCreateInput): string[] |
request.repoRoot,
"switch",
"--no-cd",
...hookFlags(isUntrustedCreate(request)),
...hookFlags(request.untrusted),
"--format=json",
];
switch (request.kind) {
+19 -16
View File
@@ -717,7 +717,7 @@ export default function contribute(server: PluginServerContext) {
"--base",
request.startPoint ?? request.baseRef,
"--no-cd",
"--yes",
request.untrusted ? "--no-hooks" : "--yes",
"--format=json",
],
{ signal },
@@ -725,16 +725,17 @@ export default function contribute(server: PluginServerContext) {
const { path } = JSON.parse(stdout) as { path: string };
return { type: "created", path };
},
async remove({ path, force }, { signal }) {
async remove({ repoRoot, path, force, untrusted }, { signal }) {
const skipHooks = untrusted || repoRoot === null;
await execCommand(
"wt",
[
"-C",
path,
repoRoot ?? path,
"remove",
"--foreground",
"--no-delete-branch",
"--yes",
skipHooks ? "--no-hooks" : "--yes",
...(force ? ["--force"] : []),
path,
],
@@ -742,7 +743,7 @@ export default function contribute(server: PluginServerContext) {
);
return { type: "removed" };
},
async restore({ repoRoot, path, target }, { signal }) {
async restore({ repoRoot, path, target, untrusted }, { signal }) {
if (target.type !== "branch") return;
const { stdout } = await execCommand(
"wt",
@@ -754,7 +755,7 @@ export default function contribute(server: PluginServerContext) {
"--path",
path,
"--no-cd",
"--yes",
untrusted ? "--no-hooks" : "--yes",
"--format=json",
],
{ signal },
@@ -768,19 +769,21 @@ export default function contribute(server: PluginServerContext) {
- **Create** runs after all `worktree.create.before` hooks and before `worktree.create.after`, with a
120-second timeout. Return `{ type: "created", path }` to claim creation, or `undefined` to decline
so the next manager or Paseo's built-in Git checkout runs. Paseo verifies that `path` is a safe,
newly created Git worktree of the same repository on a named branch, then records the checked-out
`HEAD` branch (managers may normalize or uniquely name the branch, and should create a new branch
for `branch-off`), writes comparison-base metadata, and seeds `paseo.json`. If adoption or a later
creation step fails after a new worktree was created in the repository, Paseo rolls it back; if
`create` throws before returning, the plugin is responsible for cleaning up any partial worktree it
created. First-agent branch auto-rename is skipped for manager-created worktrees.
so the next manager or Paseo's built-in Git checkout runs. When `request.untrusted` is `true` (for
example, a fork change request), skip repository-defined hooks. Paseo verifies that `path` is a
safe, newly created Git worktree of the same repository on a named branch, then records the
checked-out `HEAD` branch (managers may normalize or uniquely name the branch, and should create a
new branch for `branch-off`), writes comparison-base metadata, and seeds `paseo.json`. If
adoption, a later creation step, or `create` itself fails (including timeout or abort) after a new
worktree was created at the requested path or branch, Paseo rolls it back; managers should still
clean up any custom-named partial worktree when throwing or when `signal` aborts. First-agent
branch auto-rename is skipped for manager-created worktrees.
- **Remove** is optional and runs on workspace archive and creation rollback, after Paseo runs
`paseo.json` teardown and saves `refs/paseo/kept-commits/<sha>` for restore. Return
`{ type: "removed" }` after removing the directory, or `undefined` to fall back to Git. When
`untrusted` is `true` (for example, a fork change request), skip repository-defined hooks. Paseo
routes removal to the plugin that created the worktree, falling back to Git when that plugin is
disabled or uninstalled.
`untrusted` is `true` (for example, a fork change request) or `repoRoot` is `null`, skip
repository-defined hooks and run against `repoRoot` when available. Paseo routes removal to the
plugin that created the worktree, falling back to Git when that plugin is disabled or uninstalled.
- **Restore** is optional and runs when unarchiving a workspace whose worktree directory was deleted.
It receives the recorded `path` that the recreated worktree must occupy, `target` (`branch`,
`commit`, or `from-base`), and `untrusted`. Return `{ type: "restored", path }` or `undefined` to
+9 -8
View File
@@ -564,7 +564,7 @@ export default function contribute(server: PluginServerContext) {
"--base",
request.startPoint ?? request.baseRef,
"--no-cd",
"--yes",
request.untrusted ? "--no-hooks" : "--yes",
"--format=json",
],
{ signal },
@@ -572,16 +572,17 @@ export default function contribute(server: PluginServerContext) {
const { path } = JSON.parse(stdout) as { path: string };
return { type: "created", path };
},
async remove({ path, force }, { signal }) {
async remove({ repoRoot, path, force, untrusted }, { signal }) {
const skipHooks = untrusted || repoRoot === null;
await execCommand(
"wt",
[
"-C",
path,
repoRoot ?? path,
"remove",
"--foreground",
"--no-delete-branch",
"--yes",
skipHooks ? "--no-hooks" : "--yes",
...(force ? ["--force"] : []),
path,
],
@@ -589,7 +590,7 @@ export default function contribute(server: PluginServerContext) {
);
return { type: "removed" };
},
async restore({ repoRoot, path, target }, { signal }) {
async restore({ repoRoot, path, target, untrusted }, { signal }) {
if (target.type !== "branch") return;
const { stdout } = await execCommand(
"wt",
@@ -601,7 +602,7 @@ export default function contribute(server: PluginServerContext) {
"--path",
path,
"--no-cd",
"--yes",
untrusted ? "--no-hooks" : "--yes",
"--format=json",
],
{ signal },
@@ -613,8 +614,8 @@ export default function contribute(server: PluginServerContext) {
}
```
- **Create**:在所有 `worktree.create.before` 钩子之后、`worktree.create.after` 之前运行,超时为 120 秒。返回 `{ type: "created", path }` 表示接管创建,返回 `undefined` 表示放弃并交由下一个管理器或 Paseo 内置 Git 检出处理。Paseo 会验证 `path` 是同一仓库下新建且安全的命名分支 Git worktree,并记录实际检出的 `HEAD` 分支(管理器可自行规范或生成唯一分支名,但在 `branch-off` 时应创建新分支),随后写入基准元数据并生成 `paseo.json`。若在仓库内新建 worktree 后采纳或后续创建步骤失败,Paseo 会执行回滚;若 `create` 在返回前抛出错误,则由插件清理其部分创建的 worktree。由管理器创建的 worktree 会跳过首个 Agent 的分支自动重命名。
- **Remove**:可选。在工作区归档和创建回滚时运行,位于 Paseo 执行 `paseo.json` 清理并保存 `refs/paseo/kept-commits/<sha>` 之后。删除目录后返回 `{ type: "removed" }`,或返回 `undefined` 回退到 Git。当 `untrusted` 为 `true`(例如来自 fork 变更请求)时,请跳过仓库内定义的钩子。Paseo 会将移除路由到创建该 worktree 的插件;若该插件已停用或移除,则回退到内置 Git。
- **Create**:在所有 `worktree.create.before` 钩子之后、`worktree.create.after` 之前运行,超时为 120 秒。返回 `{ type: "created", path }` 表示接管创建,返回 `undefined` 表示放弃并交由下一个管理器或 Paseo 内置 Git 检出处理。当 `request.untrusted` 为 `true`(例如来自 fork 变更请求)时,请跳过仓库内定义的钩子。Paseo 会验证 `path` 是同一仓库下新建且安全的命名分支 Git worktree,并记录实际检出的 `HEAD` 分支(管理器可自行规范或生成唯一分支名,但在 `branch-off` 时应创建新分支),随后写入基准元数据并生成 `paseo.json`。若在请求路径或分支上新建 worktree 后采纳、后续创建步骤或 `create` 本身失败(包括超时或中止),Paseo 会执行回滚;管理器在抛出错误或 `signal` 中止时仍应清理自定义命名的部分 worktree。由管理器创建的 worktree 会跳过首个 Agent 的分支自动重命名。
- **Remove**:可选。在工作区归档和创建回滚时运行,位于 Paseo 执行 `paseo.json` 清理并保存 `refs/paseo/kept-commits/<sha>` 之后。删除目录后返回 `{ type: "removed" }`,或返回 `undefined` 回退到 Git。当 `untrusted` 为 `true`(例如来自 fork 变更请求)或 `repoRoot` 为 `null` 时,请跳过仓库内定义的钩子,并在可用时从 `repoRoot` 运行。Paseo 会将移除路由到创建该 worktree 的插件;若该插件已停用或移除,则回退到内置 Git。
- **Restore**:可选。在取消归档且 worktree 目录已被删除时运行,接收必须恢复到的原路径 `path`、目标 `target`(`branch`、`commit` 或 `from-base`)以及 `untrusted`。返回 `{ type: "restored", path }`,或返回 `undefined` 回退到 Git。当 `restore` 回退到 Git 时,Paseo 会清除该工作区的管理器归属,后续归档也会使用 Git。
完整插件见 [worktrunk 示例](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktrunk)。