Skip to content

Commit aa7f290

Browse files
committed
fix(worktrees): keep setup and cleanup failures readable
1 parent 07cf670 commit aa7f290

8 files changed

Lines changed: 395 additions & 60 deletions

File tree

‎docs/concepts/managed-worktrees.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ OPENCLAW_WORKTREE_PATH=<managed worktree>
4343

4444
A nonzero exit aborts creation and removes the new worktree and branch. This is a repository-local contract; there is no OpenClaw config key for it.
4545

46+
Setup failures report the exit code or termination signal, or an actual timeout after 120 seconds, with a bounded excerpt of recent output rather than the full setup log. If setup times out, inspect `.openclaw/worktree-setup.sh` and its dependencies for slow downloads, unavailable services, or commands waiting for interactive input.
47+
4648
## Session worktrees
4749

4850
Start an isolated chat from a Git-backed folder with a worktree session: on the Control UI's New session page, use the **Place** picker to choose a Gateway source folder, then select **Worktree** (with an optional base branch and worktree name). Choosing a paired device or cloud profile forces this managed-worktree path from the selected Gateway source; remote placement never browses or binds a node working directory. When the name is omitted, OpenClaw derives it from the explicit session label or the concise title generated from the first message, then falls back to a crustacean-themed name. The choice appears only after the Gateway confirms that the selected folder is a Git checkout; ordinary folders can run directly only on the Gateway and show no Git isolation control. iOS exposes the same choice from Chat actions, and Android exposes it beside New Chat, when the active agent workspace is Git-backed.
Lines changed: 256 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,256 @@
1+
import { execFile } from "node:child_process";
2+
import fs from "node:fs/promises";
3+
import os from "node:os";
4+
import path from "node:path";
5+
import { promisify } from "node:util";
6+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
7+
import * as commandExec from "../../process/exec.js";
8+
import type { SpawnResult } from "../../process/exec.js";
9+
import { closeOpenClawStateDatabaseForTest } from "../../state/openclaw-state-db.js";
10+
import { ManagedWorktreeService } from "./service.js";
11+
import { initializeManagedWorktreeTestRepository } from "./service.test-support.js";
12+
13+
const execFileAsync = promisify(execFile);
14+
const realRunCommand = commandExec.runCommandWithTimeout;
15+
const emptyFailure: SpawnResult = {
16+
stdout: "",
17+
stderr: "",
18+
code: 73,
19+
signal: null,
20+
killed: false,
21+
termination: "exit",
22+
};
23+
24+
async function failureMessage(operation: Promise<unknown>): Promise<string> {
25+
try {
26+
await operation;
27+
} catch (error) {
28+
if (error instanceof Error) {
29+
return error.message;
30+
}
31+
throw error;
32+
}
33+
throw new Error("expected worktree operation to fail");
34+
}
35+
36+
async function git(cwd: string, ...args: string[]): Promise<string> {
37+
const { stdout } = await execFileAsync("git", ["-C", cwd, ...args]);
38+
return stdout.trim();
39+
}
40+
41+
const terminationCases: Array<{
42+
name: string;
43+
result: Partial<SpawnResult>;
44+
expected: RegExp[];
45+
}> = [
46+
{
47+
name: "exit without output",
48+
result: { code: 23 },
49+
expected: [/(?:exit|code|status)[^\n]*23/i],
50+
},
51+
{
52+
name: "exit with output",
53+
result: { code: 23, stderr: "fatal: dependency unavailable" },
54+
expected: [/fatal: dependency unavailable/, /(?:exit|code|status)[^\n]*23/i],
55+
},
56+
{
57+
name: "timeout with output",
58+
result: {
59+
code: 124,
60+
termination: "timeout",
61+
signal: "SIGTERM",
62+
killed: true,
63+
stderr: "waiting for dependency",
64+
},
65+
expected: [/waiting for dependency/, /timed?\s*out|timeout/i, /SIGTERM/],
66+
},
67+
{
68+
name: "timeout without output",
69+
result: {
70+
code: 124,
71+
termination: "timeout",
72+
signal: "SIGKILL",
73+
killed: true,
74+
},
75+
expected: [/timed?\s*out|timeout/i, /SIGKILL/],
76+
},
77+
{
78+
name: "signal without output",
79+
result: { code: null, termination: "signal", signal: "SIGTERM" },
80+
expected: [/SIGTERM/],
81+
},
82+
];
83+
84+
describe("ManagedWorktreeService failure diagnostics", () => {
85+
let root: string;
86+
let repo: string;
87+
let service: ManagedWorktreeService;
88+
89+
beforeEach(async () => {
90+
root = await fs.mkdtemp(path.join(await fs.realpath(os.tmpdir()), "openclaw-worktree-errors-"));
91+
repo = await initializeManagedWorktreeTestRepository(root);
92+
service = new ManagedWorktreeService({
93+
env: { ...process.env, OPENCLAW_STATE_DIR: path.join(root, "state") },
94+
});
95+
});
96+
97+
afterEach(async () => {
98+
vi.restoreAllMocks();
99+
closeOpenClawStateDatabaseForTest();
100+
await fs.rm(root, { recursive: true, force: true });
101+
});
102+
103+
async function writeFailingSetup(): Promise<string> {
104+
const script = path.join(repo, ".openclaw", "worktree-setup.sh");
105+
await fs.mkdir(path.dirname(script));
106+
await fs.writeFile(script, "#!/bin/sh\nprintf 'fatal: setup failed\\n' >&2\nexit 9\n", {
107+
mode: 0o755,
108+
});
109+
return script;
110+
}
111+
112+
it.each(terminationCases)("reports setup $name and removes its allocation", async (entry) => {
113+
const script = await writeFailingSetup();
114+
vi.spyOn(commandExec, "runCommandWithTimeout").mockImplementation(async (argv, options) => {
115+
if (argv[0] === script) {
116+
return { ...emptyFailure, ...entry.result };
117+
}
118+
return await realRunCommand(argv, options);
119+
});
120+
121+
const message = await failureMessage(
122+
service.create({ repoRoot: repo, name: "terminated-setup", baseRef: "HEAD" }),
123+
);
124+
125+
expect(await git(repo, "worktree", "list", "--porcelain")).not.toContain("terminated-setup");
126+
expect(await git(repo, "branch", "--list", "openclaw/terminated-setup")).toBe("");
127+
expect(service.listRegistryRecords()).toEqual([]);
128+
expect(message).toContain("worktree setup failed");
129+
for (const pattern of entry.expected) {
130+
expect.soft(message).toMatch(pattern);
131+
}
132+
expect(message.length).toBeLessThanOrEqual(2_300);
133+
});
134+
135+
it.each([
136+
{ phase: "create", failedOperation: "remove" },
137+
{ phase: "create", failedOperation: "branch" },
138+
{ phase: "create", failedOperation: "both" },
139+
{ phase: "restore", failedOperation: "remove" },
140+
{ phase: "restore", failedOperation: "branch" },
141+
{ phase: "restore", failedOperation: "both" },
142+
] as const)(
143+
"reports the failed $failedOperation operation during $phase cleanup",
144+
async ({ phase, failedOperation }) => {
145+
const removeFails = failedOperation !== "branch";
146+
const branchFails = failedOperation !== "remove";
147+
const name = "cleanup-failure";
148+
const branch = `openclaw/${name}`;
149+
let record;
150+
if (phase === "restore") {
151+
record = await service.create({ repoRoot: repo, name, baseRef: "HEAD" });
152+
await service.remove({ id: record.id, reason: "test" });
153+
} else {
154+
await writeFailingSetup();
155+
}
156+
const registryBefore = service.listRegistryRecords();
157+
const fatal = "fatal: branch deletion denied";
158+
let cleanupPath: string | undefined;
159+
vi.spyOn(commandExec, "runCommandWithTimeout").mockImplementation(async (argv, options) => {
160+
const args = argv[0] === "git" ? argv.slice(3) : [];
161+
if (phase === "restore" && args[0] === "reset") {
162+
return { ...emptyFailure, code: 45, stderr: "fatal: restore index failed" };
163+
}
164+
if (args[0] === "worktree" && args[1] === "remove") {
165+
cleanupPath = args.at(-1);
166+
const removed = await realRunCommand(argv, options);
167+
expect(removed.code).toBe(0);
168+
// A child can fail after applying its filesystem effects. Later branch
169+
// deletion output must not mask this removal failure.
170+
return removeFails ? emptyFailure : { ...removed, stdout: "worktree removal complete" };
171+
}
172+
if (args[0] === "branch" && args[1] === "-D" && branchFails) {
173+
return {
174+
...emptyFailure,
175+
stderr: `${"Deleting branch\r".repeat(200)}\n${"x".repeat(8_000)}${fatal}`,
176+
};
177+
}
178+
return await realRunCommand(argv, options);
179+
});
180+
181+
const message = await failureMessage(
182+
record
183+
? service.restore({ id: record.id })
184+
: service.create({ repoRoot: repo, name, baseRef: "HEAD" }),
185+
);
186+
187+
expect(cleanupPath).toBeDefined();
188+
await expect(fs.stat(cleanupPath!)).rejects.toMatchObject({ code: "ENOENT" });
189+
expect(service.listRegistryRecords()).toEqual(registryBefore);
190+
expect(await git(repo, "branch", "--list", branch)).toBe(branchFails ? branch : "");
191+
if (record) {
192+
expect(await git(repo, "show-ref", "--verify", registryBefore[0]!.snapshotRef!)).not.toBe(
193+
"",
194+
);
195+
}
196+
expect(message).toContain(
197+
phase === "restore" ? "fatal: restore index failed" : "fatal: setup failed",
198+
);
199+
const label =
200+
phase === "restore" ? "restore cleanup failed:" : "failed to clean up worktree creation:";
201+
expect(message).toContain(label);
202+
const cleanupMessage = message.slice(message.indexOf(label) + label.length);
203+
expect.soft(cleanupMessage).toContain(removeFails ? "git worktree remove" : "git branch -D");
204+
expect.soft(/(?:exit|code|status)[^\n]*73/i.test(cleanupMessage)).toBe(true);
205+
expect.soft(cleanupMessage).not.toContain("worktree removal complete");
206+
expect.soft(cleanupMessage).not.toContain("Deleted branch");
207+
if (!removeFails) {
208+
expect.soft(cleanupMessage.includes(fatal)).toBe(true);
209+
} else {
210+
expect.soft(cleanupMessage).not.toContain(fatal);
211+
}
212+
expect.soft(cleanupMessage.length).toBeLessThanOrEqual(2_300);
213+
},
214+
);
215+
216+
it.each([
217+
{ name: "long evidence inside the existing window", oldEvidenceVisible: true },
218+
{ name: "evidence outside the existing newline window", oldEvidenceVisible: false },
219+
])("preserves retry authority for $name", async ({ oldEvidenceVisible }) => {
220+
await git(path.join(root, "remote.git"), "symbolic-ref", "HEAD", "refs/heads/main");
221+
await git(repo, "remote", "set-head", "origin", "-a");
222+
const name = "retry-evidence";
223+
const branch = `openclaw/${name}`;
224+
let allocatedPath: string | undefined;
225+
let firstAdd = true;
226+
vi.spyOn(commandExec, "runCommandWithTimeout").mockImplementation(async (argv, options) => {
227+
const result = await realRunCommand(argv, options);
228+
const args = argv[0] === "git" ? argv.slice(3) : [];
229+
if (firstAdd && args[0] === "worktree" && args[1] === "add") {
230+
firstAdd = false;
231+
allocatedPath = args.at(-2);
232+
expect(result.code).toBe(0);
233+
const separator = oldEvidenceVisible ? "\r" : "\n";
234+
return {
235+
...result,
236+
code: 1,
237+
stderr: `Preparing worktree (new branch '${branch}')${separator}${`progress ${"x".repeat(200)}${separator}`.repeat(20)}fatal: checkout failed`,
238+
};
239+
}
240+
return result;
241+
});
242+
243+
if (oldEvidenceVisible) {
244+
const created = await service.create({ repoRoot: repo, name });
245+
expect(created.baseRef).toBe("HEAD");
246+
expect(await git(created.path, "branch", "--show-current")).toBe(branch);
247+
expect(service.listRegistryRecords()).toEqual([created]);
248+
} else {
249+
await expect(service.create({ repoRoot: repo, name })).rejects.toThrow("checkout failed");
250+
expect(service.listRegistryRecords()).toEqual([]);
251+
}
252+
expect(allocatedPath).toBeDefined();
253+
expect(await git(repo, "worktree", "list", "--porcelain")).toContain(allocatedPath);
254+
expect(await git(allocatedPath!, "branch", "--show-current")).toBe(branch);
255+
});
256+
});

‎src/agents/worktrees/service.test.ts‎

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -530,15 +530,34 @@ describe("ManagedWorktreeService", () => {
530530
await expect(fs.access(setupMarker)).rejects.toMatchObject({ code: "ENOENT" });
531531
});
532532

533-
it("removes the worktree and branch when setup fails", async () => {
533+
it("bounds failed setup diagnostics without losing the fatal detail or cleanup", async () => {
534534
await fs.mkdir(path.join(repo, ".openclaw"));
535535
const script = path.join(repo, ".openclaw", "worktree-setup.sh");
536-
await fs.writeFile(script, "#!/bin/sh\necho setup-broke >&2\nexit 9\n", { mode: 0o755 });
537-
await expect(
538-
service.create({ repoRoot: repo, name: "broken-setup", baseRef: "HEAD" }),
539-
).rejects.toThrow("setup-broke");
536+
const fatal = "fatal: setup dependency could not be resolved";
537+
const progress = Array.from(
538+
{ length: 2_000 },
539+
(_, index) => `Receiving objects: ${index}/2000\r`,
540+
).join("");
541+
await fs.writeFile(
542+
script,
543+
`#!/bin/sh\nprintf '%s\\n' "$OPENCLAW_WORKTREE_PATH" > "$OPENCLAW_SOURCE_TREE_PATH/setup-path.txt"\nprintf '%s' '${progress}\n${"x".repeat(65_536)}${fatal}\n' >&2\nexit 23\n`,
544+
{ mode: 0o755 },
545+
);
546+
const failure: unknown = await service
547+
.create({ repoRoot: repo, name: "broken-setup", baseRef: "HEAD" })
548+
.catch((error: unknown) => error);
549+
expect(failure).toBeInstanceOf(Error);
550+
if (!(failure instanceof Error)) {
551+
throw new Error("expected setup failure");
552+
}
553+
const worktreePath = (await fs.readFile(path.join(repo, "setup-path.txt"), "utf8")).trim();
554+
await expect(fs.stat(worktreePath)).rejects.toMatchObject({ code: "ENOENT" });
540555
expect(await git(repo, "worktree", "list", "--porcelain")).not.toContain("broken-setup");
541556
expect(await git(repo, "branch", "--list", "openclaw/broken-setup")).toBe("");
557+
expect(service.listRegistryRecords()).toEqual([]);
558+
expect.soft(failure.message).toContain(fatal);
559+
expect.soft(failure.message.length).toBeLessThanOrEqual(2_300);
560+
expect.soft(/(?:exit|code|status)[^\n]*23/i.test(failure.message)).toBe(true);
542561
});
543562

544563
it("restores tracked, untracked, and provisioned ignored files from the snapshot", async () => {

‎src/agents/worktrees/service.ts‎

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
77
import { resolveStateDir } from "../../config/paths.js";
88
import { isMissingPathError, formatErrorMessage } from "../../infra/errors.js";
99
import { createSubsystemLogger } from "../../logging/subsystem.js";
10+
import { createCommandError } from "../../process/command-error.js";
1011
import { runCommandWithTimeout } from "../../process/exec.js";
1112
import { withOpenClawStateLease } from "../../state/openclaw-state-lease.js";
1213
import { createCrustaceanSlug } from "../session-slug.js";
@@ -135,10 +136,6 @@ export function resolveWorktreeCleanupLimits(): WorktreeCleanupLimits {
135136
return {};
136137
}
137138

138-
function resultMessage(result: GitResult): string {
139-
return (result.stderr || result.stdout).trim().split("\n").slice(-12).join("\n");
140-
}
141-
142139
function validateName(name: string): string {
143140
if (!NAME_PATTERN.test(name)) {
144141
throw new Error("worktree name must match [a-z0-9][a-z0-9-]{0,63}");
@@ -275,9 +272,11 @@ async function cleanupFailedCreate(repoRoot: string, worktreePath: string, branc
275272
const deletedBranch = await runGit(repoRoot, ["branch", "-D", branch]);
276273
await runGit(repoRoot, ["worktree", "prune"]);
277274
if (removed.code !== 0 || deletedBranch.code !== 0) {
278-
throw new Error(
279-
`failed to clean up worktree creation: ${resultMessage(removed) || resultMessage(deletedBranch)}`,
280-
);
275+
const failure =
276+
removed.code !== 0
277+
? commandError("git worktree remove", removed)
278+
: commandError("git branch -D", deletedBranch);
279+
throw new Error(`failed to clean up worktree creation: ${failure.message}`);
281280
}
282281
}
283282

@@ -316,7 +315,9 @@ async function canResetFailedWorktreeAdd(
316315
branch: string,
317316
failure: GitResult,
318317
): Promise<boolean> {
319-
const message = resultMessage(failure);
318+
// Keep retry evidence unchanged: diagnostic rendering/truncation must never
319+
// grant cleanup or retry authority.
320+
const message = (failure.stderr || failure.stdout).trim().split("\n").slice(-12).join("\n");
320321
const createdBranch = message.includes(`Preparing worktree (new branch '${branch}')`);
321322
if (message.includes("unable to checkout working tree") || createdBranch) {
322323
return true;
@@ -342,18 +343,17 @@ async function runSetupScript(repoRoot: string, worktreePath: string): Promise<v
342343
if (!stat?.isFile() || (stat.mode & 0o111) === 0) {
343344
return;
344345
}
346+
const timeoutMs = 120_000;
345347
const result = await runCommandWithTimeout([setupScript], {
346-
timeoutMs: 120_000,
348+
timeoutMs,
347349
cwd: worktreePath,
348350
env: {
349351
OPENCLAW_SOURCE_TREE_PATH: repoRoot,
350352
OPENCLAW_WORKTREE_PATH: worktreePath,
351353
},
352354
});
353355
if (result.code !== 0) {
354-
throw new Error(
355-
`worktree setup failed${resultMessage(result) ? `:\n${resultMessage(result)}` : ""}`,
356-
);
356+
throw createCommandError("worktree setup", result, { timeoutMs });
357357
}
358358
}
359359

@@ -1092,10 +1092,13 @@ export class ManagedWorktreeService {
10921092
? await runGit(record.repoRoot, ["branch", "-D", record.branch])
10931093
: undefined;
10941094
if (removed.code !== 0 || (branchDeleted && branchDeleted.code !== 0)) {
1095-
throw new Error(
1096-
`${String(error)}\nrestore cleanup failed: ${resultMessage(removed) || (branchDeleted ? resultMessage(branchDeleted) : "")}`,
1097-
{ cause: error },
1098-
);
1095+
const failure =
1096+
branchDeleted && removed.code === 0
1097+
? commandError("git branch -D", branchDeleted)
1098+
: commandError("git worktree remove", removed);
1099+
throw new Error(`${String(error)}\nrestore cleanup failed: ${failure.message}`, {
1100+
cause: error,
1101+
});
10991102
}
11001103
throw error;
11011104
}

0 commit comments

Comments
 (0)