mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-21 07:45:38 +00:00
fix(plugins): preserve worktree setup on retry and refresh branch bases
A failed setup could leave a new branch behind and send the retry through the built-in checkout. Use the manager's reported branch creation status during rollback. Share base preparation so both checkout paths start from the updated remote-tracking ref.
This commit is contained in:
@@ -42,7 +42,7 @@ async function createFakeWorktrunkCli(dir: string, logFile: string): Promise<str
|
||||
scriptPath,
|
||||
`#!/usr/bin/env node
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
|
||||
import { appendFileSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
const rawArgs = process.argv.slice(2);
|
||||
@@ -98,8 +98,8 @@ if (command === "switch") {
|
||||
${JSON.stringify(logFile)},
|
||||
JSON.stringify({ command: "switch", cwd, branch, base, create, explicitPath, target, args }) + "\\n",
|
||||
);
|
||||
process.stdout.write(JSON.stringify({ path: target, branch, action: "created" }) + "\\n");
|
||||
if (branch.endsWith("fail-pre-start")) {
|
||||
process.stdout.write(JSON.stringify({ path: target, branch, action: "created", created_branch: create }) + "\\n");
|
||||
if (branch.endsWith("fail-pre-start") && !existsSync(path.join(cwd, ".setup-fixed"))) {
|
||||
console.error("pre-start hook failed");
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -233,6 +233,15 @@ test("plugin-examples/worktrunk manages create, before-hook chaining, archive wi
|
||||
stat(path.join(path.dirname(repository), "repo.team-fail-pre-start")),
|
||||
).rejects.toMatchObject({ code: "ENOENT" });
|
||||
|
||||
await writeFile(path.join(repository, ".setup-fixed"), "");
|
||||
const retried = await client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repository, worktreeSlug: "fail-pre-start" },
|
||||
});
|
||||
expect(retried.error).toBeNull();
|
||||
const retriedPath = retried.workspace!.workspaceDirectory;
|
||||
expect(git(retriedPath, ["branch", "--show-current"])).toBe("team/fail-pre-start");
|
||||
expect(await readFile(path.join(retriedPath, ".wt-hook-ran"), "utf8")).toBe("pre-start");
|
||||
|
||||
// Archive delegates removal to `wt remove` (run from repoRoot) AFTER Paseo writes refs/paseo/kept-commits/*.
|
||||
const archived = await client.archiveWorkspace(workspaceId);
|
||||
expect(archived.error).toBeNull();
|
||||
@@ -269,7 +278,7 @@ test("plugin-examples/worktrunk manages create, before-hook chaining, archive wi
|
||||
expect.objectContaining({
|
||||
command: "switch",
|
||||
branch: "team/feat-one",
|
||||
base: "release",
|
||||
base: "refs/heads/release",
|
||||
create: true,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
@@ -293,6 +302,11 @@ test("plugin-examples/worktrunk manages create, before-hook chaining, archive wi
|
||||
"--force",
|
||||
]),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
command: "switch",
|
||||
branch: "team/fail-pre-start",
|
||||
create: true,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
command: "remove",
|
||||
cwd: repository,
|
||||
@@ -686,13 +700,29 @@ test("untrusted workspaces pass untrusted=true to worktree manager remove and re
|
||||
);
|
||||
await client.archiveWorkspace(collision.workspace!.id);
|
||||
|
||||
const remote = await createRepo(path.join(root, "remote"));
|
||||
git(repository, ["remote", "add", "origin", remote]);
|
||||
git(repository, ["fetch", "origin", "main"]);
|
||||
const cached = git(repository, ["rev-parse", "refs/remotes/origin/main"]);
|
||||
git(remote, ["commit", "--allow-empty", "-m", "advance remote main"]);
|
||||
const remoteTip = git(remote, ["rev-parse", "HEAD"]);
|
||||
expect(cached).not.toBe(remoteTip);
|
||||
|
||||
const created = await client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repository, branchName: "fork-pr-branch" },
|
||||
source: {
|
||||
kind: "worktree",
|
||||
cwd: repository,
|
||||
action: "branch-off",
|
||||
baseBranch: "refs/remotes/origin/main",
|
||||
branchName: "fork-pr-branch",
|
||||
},
|
||||
});
|
||||
expect(created.error).toBeNull();
|
||||
const workspaceId = created.workspace!.id;
|
||||
const worktreePath = created.workspace!.workspaceDirectory;
|
||||
|
||||
expect(git(worktreePath, ["rev-parse", "HEAD"])).toBe(remoteTip);
|
||||
|
||||
// Mark the persisted workspace record as originating from an untrusted fork PR and reload daemon.
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
|
||||
@@ -10,6 +10,8 @@ import type { ForgeService } from "../services/forge-service.js";
|
||||
import {
|
||||
createWorktree,
|
||||
fetchFirstAvailableRef,
|
||||
prepareWorktreeBranchOff,
|
||||
type PreparedWorktreeBranchOff,
|
||||
resolveDefaultWorktreePath,
|
||||
runPluginWorktreeManagerCheckout,
|
||||
slugify,
|
||||
@@ -158,7 +160,7 @@ async function createWorktreeCoreWithPriority(
|
||||
normalizedSlug = validateWorktreeSlug(transformed.slug);
|
||||
intent = creationIntentFromRequest(transformed, intent);
|
||||
|
||||
const managedWorktree = await tryCreateWithWorktreeManager({
|
||||
const { worktree: managedWorktree, preparedBranchOff } = await tryCreateWithWorktreeManager({
|
||||
repoRoot,
|
||||
transformed,
|
||||
intent,
|
||||
@@ -180,6 +182,7 @@ async function createWorktreeCoreWithPriority(
|
||||
worktreeSlug: normalizedSlug,
|
||||
worktreePath: transformed.path,
|
||||
source: intent,
|
||||
preparedBranchOff,
|
||||
paseoHome: input.paseoHome,
|
||||
worktreesRoot: input.worktreesRoot,
|
||||
}),
|
||||
@@ -199,11 +202,11 @@ async function tryCreateWithWorktreeManager(options: {
|
||||
intent: WorktreeCreationIntent;
|
||||
input: Pick<CreateWorktreeCoreInput, "paseoHome" | "worktreesRoot">;
|
||||
deps: Pick<CreateWorktreeCoreDeps, "worktreeManagers">;
|
||||
}): Promise<CreatedWorktree | null> {
|
||||
}): Promise<{ worktree: CreatedWorktree | null; preparedBranchOff?: PreparedWorktreeBranchOff }> {
|
||||
const { repoRoot, transformed, intent, input, deps } = options;
|
||||
const untrusted = isUntrustedWorktreeCreationIntent(intent);
|
||||
const createRequest: PluginWorktreeCreateInput = { ...transformed, untrusted };
|
||||
return runPluginWorktreeManagerCheckout({
|
||||
let preparedBranchOff: PreparedWorktreeBranchOff | undefined;
|
||||
const worktree = await runPluginWorktreeManagerCheckout({
|
||||
cwd: repoRoot,
|
||||
source: intent,
|
||||
operation: "create",
|
||||
@@ -211,8 +214,16 @@ async function tryCreateWithWorktreeManager(options: {
|
||||
paseoHome: input.paseoHome,
|
||||
worktreesBaseRoot: input.worktreesRoot,
|
||||
worktreeManagers: deps.worktreeManagers,
|
||||
run: () => deps.worktreeManagers!.createWorktree(createRequest),
|
||||
run: async () => {
|
||||
let request: PluginWorktreeCreateInput = { ...transformed, untrusted };
|
||||
if (request.kind === "branch-off" && intent.kind === "branch-off") {
|
||||
preparedBranchOff = await prepareWorktreeBranchOff(repoRoot, intent);
|
||||
request = { ...request, baseRef: preparedBranchOff.baseRef };
|
||||
}
|
||||
return deps.worktreeManagers!.createWorktree(request);
|
||||
},
|
||||
});
|
||||
return { worktree, preparedBranchOff };
|
||||
}
|
||||
|
||||
function describeCreationRequest(
|
||||
|
||||
@@ -231,10 +231,17 @@ export type WorktreeSource =
|
||||
trackOriginHead?: boolean;
|
||||
};
|
||||
|
||||
export interface PreparedWorktreeBranchOff {
|
||||
baseRef: string;
|
||||
checkoutRef: string;
|
||||
branchExists: boolean;
|
||||
}
|
||||
|
||||
export interface CreateWorktreeOptions {
|
||||
cwd: string;
|
||||
worktreeSlug: string;
|
||||
source: WorktreeSource;
|
||||
preparedBranchOff?: PreparedWorktreeBranchOff;
|
||||
paseoHome?: string;
|
||||
worktreesRoot?: string;
|
||||
worktreePath?: string;
|
||||
@@ -1589,6 +1596,7 @@ export function createWorktree(
|
||||
export async function createWorktree({
|
||||
cwd,
|
||||
source,
|
||||
preparedBranchOff,
|
||||
worktreeSlug,
|
||||
paseoHome,
|
||||
worktreesRoot,
|
||||
@@ -1602,7 +1610,12 @@ export async function createWorktree({
|
||||
source.kind === "checkout-github-pr"
|
||||
? await listLocalBranchNames(cwd)
|
||||
: new Set<string>();
|
||||
const sourcePlan = await resolveWorktreeSourcePlan({ cwd, source, desiredSlug: worktreeSlug });
|
||||
const sourcePlan = await resolveWorktreeSourcePlan({
|
||||
cwd,
|
||||
source,
|
||||
desiredSlug: worktreeSlug,
|
||||
preparedBranchOff,
|
||||
});
|
||||
const fetchedBranch = planCreatedLocalBranch(source, sourcePlan);
|
||||
const fetchedTip =
|
||||
fetchedBranch && !branchesBefore.has(fetchedBranch)
|
||||
@@ -2033,6 +2046,7 @@ interface ResolveWorktreeSourcePlanOptions {
|
||||
cwd: string;
|
||||
source: WorktreeSource;
|
||||
desiredSlug: string;
|
||||
preparedBranchOff?: PreparedWorktreeBranchOff;
|
||||
}
|
||||
|
||||
interface WorktreeSourcePlan {
|
||||
@@ -2105,30 +2119,46 @@ async function resolveRestoredWorktreeFromBasePlan(
|
||||
};
|
||||
}
|
||||
|
||||
export async function prepareWorktreeBranchOff(
|
||||
cwd: string,
|
||||
source: Extract<WorktreeSource, { kind: "branch-off" }>,
|
||||
previous?: PreparedWorktreeBranchOff,
|
||||
): Promise<PreparedWorktreeBranchOff> {
|
||||
const baseRef = previous?.baseRef ?? (await resolveBaseBranchForWorktree(cwd, source.baseBranch));
|
||||
const branchExists = await localBranchExists(cwd, source.branchName);
|
||||
const checkoutRef = branchExists ? source.branchName : (source.startPoint ?? baseRef);
|
||||
if (checkoutRef !== previous?.checkoutRef) {
|
||||
await refreshRemoteTrackingBaseRef(cwd, checkoutRef);
|
||||
}
|
||||
return { baseRef, branchExists, checkoutRef };
|
||||
}
|
||||
|
||||
async function resolveBranchOffWorktreeSourcePlan(
|
||||
cwd: string,
|
||||
source: Extract<WorktreeSource, { kind: "branch-off" }>,
|
||||
desiredSlug: string,
|
||||
preparedBranchOff?: PreparedWorktreeBranchOff,
|
||||
): Promise<WorktreeSourcePlan> {
|
||||
const branchName = source.branchName;
|
||||
await validateGitBranchName(cwd, branchName);
|
||||
const resolvedBaseBranch = await resolveBaseBranchForWorktree(cwd, source.baseBranch);
|
||||
const branchExists = await localBranchExists(cwd, branchName);
|
||||
const base = branchExists ? branchName : (source.startPoint ?? resolvedBaseBranch);
|
||||
await refreshRemoteTrackingBaseRef(cwd, base);
|
||||
const { baseRef, branchExists, checkoutRef } = await prepareWorktreeBranchOff(
|
||||
cwd,
|
||||
source,
|
||||
preparedBranchOff,
|
||||
);
|
||||
const candidateBranch = branchExists ? desiredSlug : branchName;
|
||||
const newBranchName = await resolveUniqueLocalBranchName(cwd, candidateBranch);
|
||||
const metadata = await resolveWorktreeMetadata({
|
||||
cwd,
|
||||
source,
|
||||
branchName: newBranchName,
|
||||
resolvedBaseRef: resolvedBaseBranch,
|
||||
resolvedBaseRef: baseRef,
|
||||
});
|
||||
|
||||
return {
|
||||
branchName: newBranchName,
|
||||
...metadata,
|
||||
addArguments: ["-b", newBranchName, "--no-track", base],
|
||||
addArguments: ["-b", newBranchName, "--no-track", checkoutRef],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2136,10 +2166,11 @@ async function resolveWorktreeSourcePlan({
|
||||
cwd,
|
||||
source,
|
||||
desiredSlug,
|
||||
preparedBranchOff,
|
||||
}: ResolveWorktreeSourcePlanOptions): Promise<WorktreeSourcePlan> {
|
||||
switch (source.kind) {
|
||||
case "branch-off":
|
||||
return resolveBranchOffWorktreeSourcePlan(cwd, source, desiredSlug);
|
||||
return resolveBranchOffWorktreeSourcePlan(cwd, source, desiredSlug, preparedBranchOff);
|
||||
case "restore":
|
||||
return resolveRestoredWorktreeSourcePlan(cwd, source);
|
||||
case "restore-commit":
|
||||
|
||||
@@ -15,6 +15,8 @@ export const WAITING_MARKER = "💬";
|
||||
interface SwitchJsonOutput {
|
||||
path: string;
|
||||
action?: string;
|
||||
branch?: string;
|
||||
createdBranch: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -73,10 +75,17 @@ async function runWt(
|
||||
function tryParseSwitchOutput(stdout: string | undefined): SwitchJsonOutput | null {
|
||||
if (!stdout?.trim()) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(stdout) as { path?: unknown; action?: unknown };
|
||||
const parsed = JSON.parse(stdout) as {
|
||||
path?: unknown;
|
||||
action?: unknown;
|
||||
branch?: unknown;
|
||||
created_branch?: unknown;
|
||||
};
|
||||
if (typeof parsed.path !== "string" || parsed.path.length === 0) return null;
|
||||
return {
|
||||
path: parsed.path,
|
||||
createdBranch: parsed.created_branch === true,
|
||||
...(typeof parsed.branch === "string" && parsed.branch ? { branch: parsed.branch } : {}),
|
||||
...(typeof parsed.action === "string" ? { action: parsed.action } : {}),
|
||||
};
|
||||
} catch {
|
||||
@@ -127,23 +136,30 @@ export function buildCreateArgs(request: PluginWorktreeCreateInput): string[] |
|
||||
}
|
||||
|
||||
async function cleanupPartiallyCreatedWorktree(repoRoot: string, error: unknown): Promise<void> {
|
||||
// Worktrunk prints `{ path, action: "created" }` on stdout even when a later hook exits non-zero.
|
||||
// Worktrunk reports the checkout and whether it created the branch even if a hook fails.
|
||||
const stdout =
|
||||
error instanceof Error && error.cause && typeof error.cause === "object"
|
||||
? (error.cause as { stdout?: string }).stdout
|
||||
: undefined;
|
||||
const parsed = tryParseSwitchOutput(stdout);
|
||||
if (parsed?.action !== "created") return;
|
||||
await runWt([
|
||||
"-C",
|
||||
repoRoot,
|
||||
"remove",
|
||||
"--foreground",
|
||||
"--no-delete-branch",
|
||||
"--no-hooks",
|
||||
"--force",
|
||||
parsed.path,
|
||||
]).catch(() => {});
|
||||
try {
|
||||
await runWt([
|
||||
"-C",
|
||||
repoRoot,
|
||||
"remove",
|
||||
"--foreground",
|
||||
"--no-delete-branch",
|
||||
"--no-hooks",
|
||||
"--force",
|
||||
parsed.path,
|
||||
]);
|
||||
if (parsed.createdBranch && parsed.branch) {
|
||||
await execCommand("git", ["branch", "-D", "--", parsed.branch], { cwd: repoRoot });
|
||||
}
|
||||
} catch {
|
||||
// Keep the original setup error.
|
||||
}
|
||||
}
|
||||
|
||||
export async function createWithWorktrunk(
|
||||
|
||||
@@ -769,7 +769,9 @@ 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. When `request.untrusted` is `true` (for
|
||||
so the next manager or Paseo's built-in Git checkout runs. For branch-off, Paseo resolves
|
||||
`baseRef` and refreshes a remote-tracking starting ref before calling the manager, using the
|
||||
cached ref if the fetch fails. 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
|
||||
|
||||
@@ -614,7 +614,7 @@ export default function contribute(server: PluginServerContext) {
|
||||
}
|
||||
```
|
||||
|
||||
- **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`。如果采纳或后续创建步骤失败,Paseo 会根据返回的路径回滚。回调在返回前抛出错误或收到中止信号时,由管理器清理自己创建的 worktree。由管理器创建的 worktree 会跳过首个 Agent 的分支自动重命名。
|
||||
- **Create**:在所有 `worktree.create.before` 钩子之后、`worktree.create.after` 之前运行,超时为 120 秒。返回 `{ type: "created", path }` 表示接管创建,返回 `undefined` 表示放弃并交由下一个管理器或 Paseo 内置 Git 检出处理。创建新分支时,Paseo 会在调用管理器前解析 `baseRef`,并刷新用作起点的远程跟踪引用。如果获取失败,则使用本地缓存的引用。当 `request.untrusted` 为 `true`(例如来自 fork 变更请求)时,请跳过仓库内定义的钩子。Paseo 会验证 `path` 是同一仓库下新建且安全的命名分支 Git worktree,并记录实际检出的 `HEAD` 分支(管理器可自行规范或生成唯一分支名,但在 `branch-off` 时应创建新分支),随后写入基准元数据并生成 `paseo.json`。如果采纳或后续创建步骤失败,Paseo 会根据返回的路径回滚。回调在返回前抛出错误或收到中止信号时,由管理器清理自己创建的 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。Paseo 会验证检出结果是否为指定的分支、分离 HEAD 的提交,或位于指定基准提交的新分支。清理规则与 Create 相同。当 `restore` 回退到 Git 时,Paseo 会清除该工作区的管理器归属,后续归档也会使用 Git。
|
||||
|
||||
|
||||
Reference in New Issue
Block a user