Skip to content

Commit 4f81644

Browse files
authored
feat: configure a global managed worktree storage root (#134872)
* feat: configure a global managed worktree storage root * refactor: remove obsolete managed worktree path lookup * test: refresh session fixture config before runtime publication * docs: clarify bare home directory worktree roots * fix: protect nested worktree roots during orphan cleanup
1 parent 3ae010c commit 4f81644

19 files changed

Lines changed: 365 additions & 72 deletions
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"core": 2407,
2+
"core": 2408,
33
"channel": 3706,
44
"plugin": 4055
55
}
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
b01f06a7a504abf5d5e3f4350d84d32eeb22592866f311d8e10086c9dd175155 config-baseline.json
2-
3e902283780334ddb7b21d7b7c23f4c4dcbb54a7d9ac0ba55f41bfdfe409c243 config-baseline.core.json
3-
c0df39cf6b2e290c114fa5f46e16ac67c55e6d10b39754f41d8dbc55b45eb4c8 config-baseline.channel.json
4-
ac1f364bf8ecb0d34cee215150e29bf350f1d1909778ecdde53cbe5b0fb22014 config-baseline.plugin.json
1+
50d9ff57e46967d5d6718c0fdb702d06963ad0859faf963a1a6f2e1575f21787 config-baseline.json
2+
b7af07d4882584af586794654a39aa5b85bb8fba201365f5f6ed887f84859f6c config-baseline.core.json
3+
5b1580fa405a12d34c5e4038fe75be57b22d85d612a6ead29a69bc2fed425668 config-baseline.channel.json
4+
184f74c8b996c17539a833904cf166faa8a58af38426f680c94f8b61a532f72c config-baseline.plugin.json

‎docs/concepts/managed-worktrees.md‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,39 @@ summary: "Run agent tasks in isolated git checkouts with automatic snapshots and
33
read_when:
44
- You want an isolated branch and checkout for an agent task
55
- You are configuring Workboard cards with worktree workspaces
6+
- You want to store managed worktrees on another disk or in a custom folder
67
- You need to restore or clean up an OpenClaw-managed worktree
78
title: "Managed worktrees"
89
---
910

10-
Managed worktrees give an agent task its own git branch and checkout without placing temporary directories inside the source repository. OpenClaw creates them under its state directory, records them in the shared state database, and snapshots their tracked and non-ignored untracked contents before removal.
11+
Managed worktrees give an agent task its own git branch and checkout without placing temporary directories inside the source repository. OpenClaw records them in the shared state database and snapshots their tracked and non-ignored untracked contents before removal.
12+
13+
## Choose where worktrees are stored
14+
15+
By default, OpenClaw stores managed checkouts under `<openclaw-state-dir>/worktrees`. Set the global `worktreeRoot` option in `openclaw.json` to use another folder or disk:
16+
17+
```json5
18+
{
19+
worktreeRoot: "/mnt/workspaces/openclaw-worktrees",
20+
}
21+
```
22+
23+
Use an absolute path on the Gateway host, `~` for the Gateway user's home directory, or a path beginning with `~/` for a folder inside it. Relative paths are rejected. The Gateway user must be able to create and write to the directory.
24+
25+
This setting applies to all managed worktrees, including session, manual, and Workboard worktrees; there is no per-agent override. It changes checkout storage only. The shared state database, snapshots of provisioned ignored files, allocation limits, and cleanup lifecycle remain associated with the same OpenClaw state directory.
26+
27+
Changing `worktreeRoot` affects new allocations. Existing registered worktrees keep their recorded paths for reuse and cleanup, and removed worktrees restore to their original paths. OpenClaw does not move existing checkouts or snapshots when this setting changes. Keep their original storage available until those worktrees are no longer needed.
28+
29+
Outside the default state-owned worktree directory, cleanup acts only on registered worktrees. It leaves unrelated, unregistered folders in your custom location alone.
30+
31+
See [Configuration reference](/gateway/configuration-reference#worktreeroot) for the option's default and scope.
1132

1233
## Layout and names
1334

1435
Each worktree lives at:
1536

1637
```text
17-
<openclaw-state-dir>/worktrees/<repo-fingerprint>/<name>
38+
<worktreeRoot>/<repo-fingerprint>/<name>
1839
```
1940

2041
The repository fingerprint is the first 16 hexadecimal characters of a SHA-256 hash over the canonical git common directory and origin URL. A supplied name must match `[a-z0-9][a-z0-9-]{0,63}`. Without a name, OpenClaw generates a readable crustacean-themed name such as `brisk-lobster`. Inferred names already occupied by any registered worktree (including the caller's own removed checkout), local branch, or unmanaged path get a numeric suffix such as `brisk-lobster-2`; only a supplied name reuses or restores the caller's existing record.

‎docs/gateway/configuration-reference.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,20 @@ See [Configuration - agents](/gateway/config-agents) for:
5050
- `talk.silenceTimeoutMs`: when unset, Talk keeps the platform default pause window before sending the transcript (`700 ms on macOS and Android, 900 ms on iOS`)
5151
- `talk.realtime.consultRouting`: Gateway relay fallback for finalized realtime Talk transcripts that skip `openclaw_agent_consult`
5252

53+
## `worktreeRoot`
54+
55+
Optional global root directory for [managed worktree](/concepts/managed-worktrees) checkouts. Defaults to `<openclaw-state-dir>/worktrees`.
56+
57+
```json5
58+
{
59+
worktreeRoot: "/mnt/workspaces/openclaw-worktrees",
60+
}
61+
```
62+
63+
Use an absolute Gateway-host path, `~` for the Gateway user's home directory, or `~/` followed by a folder inside it; relative paths are rejected. OpenClaw creates checkouts at `<worktreeRoot>/<repo-fingerprint>/<name>`. This setting applies to all agents and all managed-worktree owners, with no per-agent override. The shared state database and allocation limits remain under the existing state directory.
64+
65+
Changes affect new allocations only. Registered worktrees retain their original paths for reuse, cleanup, and snapshot restore; existing checkouts are not moved automatically. Keep their original storage available while those records are still needed.
66+
5367
## Tools and custom providers
5468

5569
Tool policy, experimental toggles, provider-backed tool config, and custom

‎src/agents/worktrees/git.ts‎

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -158,15 +158,3 @@ export async function worktreePathExists(target: string): Promise<boolean> {
158158
throw error;
159159
}
160160
}
161-
162-
export async function removeEmptyParents(start: string, stop: string): Promise<void> {
163-
let current = start;
164-
while (current.startsWith(`${stop}${path.sep}`)) {
165-
try {
166-
await fs.rmdir(current);
167-
} catch {
168-
return;
169-
}
170-
current = path.dirname(current);
171-
}
172-
}

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

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import {
1010
import {
1111
deleteRegistryWorktree,
1212
getRegistryWorktreeProvisionedChunk,
13-
findRegistryWorktreeByPath,
1413
findLiveRegistryWorktreeByPath,
1514
getRegistryWorktree,
1615
getRegistryWorktreeProvisionedPaths,
@@ -98,7 +97,6 @@ describe("managed worktree registry", () => {
9897
snapshotRef: "refs/openclaw/snapshots/first",
9998
});
10099
expect(findLiveRegistryWorktreeByPath(env, record.path)).toBeUndefined();
101-
expect(findRegistryWorktreeByPath(env, record.path)?.id).toBe("first");
102100
expect(getRegistryWorktreeProvisionedPaths(env, "first")).toEqual([".env.local"]);
103101
expect(getRegistryWorktreeProvisionedState(env, "first")).toEqual([
104102
{ path: ".env.local", mode: 0o600, chunks: 1 },

‎src/agents/worktrees/registry.ts‎

Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -367,21 +367,6 @@ export function findLiveRegistryWorktreeByOwner(
367367
return row ? rowToRecord(row) : undefined;
368368
}
369369

370-
export function findRegistryWorktreeByPath(
371-
env: NodeJS.ProcessEnv,
372-
worktreePath: string,
373-
): ManagedWorktreeRecord | undefined {
374-
const db = dbFor(env);
375-
const query = kyselyFor(db)
376-
.selectFrom("worktrees")
377-
.selectAll()
378-
.where("path", "=", worktreePath)
379-
.orderBy("created_at", "desc")
380-
.limit(1);
381-
const row = executeSqliteQuerySync(db, query).rows[0];
382-
return row ? rowToRecord(row) : undefined;
383-
}
384-
385370
export function insertRegistryWorktree(
386371
env: NodeJS.ProcessEnv,
387372
record: ManagedWorktreeRecord,
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
import fs from "node:fs/promises";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
5+
import { closeOpenClawStateDatabaseForTest } from "../../state/openclaw-state-db.js";
6+
import { ManagedWorktreeService, IDLE_GC_MS } from "./service.js";
7+
import { useManagedWorktreeTestRepository } from "./service.test-support.js";
8+
9+
describe("configured managed worktree root", () => {
10+
const initializeRepository = useManagedWorktreeTestRepository();
11+
let root: string;
12+
let repo: string;
13+
let stateDir: string;
14+
let worktreeRoot: string | undefined;
15+
let now: number;
16+
let service: ManagedWorktreeService;
17+
18+
beforeEach(async () => {
19+
root = await fs.mkdtemp(path.join(await fs.realpath(os.tmpdir()), "openclaw-worktree-root-"));
20+
repo = await initializeRepository(root);
21+
stateDir = path.join(root, "state");
22+
worktreeRoot = undefined;
23+
now = Date.now();
24+
service = new ManagedWorktreeService({
25+
env: { ...process.env, OPENCLAW_STATE_DIR: stateDir },
26+
now: () => now,
27+
getConfig: () => ({ worktreeRoot }),
28+
});
29+
});
30+
31+
afterEach(async () => {
32+
closeOpenClawStateDatabaseForTest();
33+
await fs.rm(root, { recursive: true, force: true });
34+
});
35+
36+
it.each(["manual", "session", "workboard"] as const)(
37+
"allocates %s worktrees under the custom root with the shared registry unchanged",
38+
async (ownerKind) => {
39+
worktreeRoot = path.join(root, "custom");
40+
const record = await service.create({
41+
repoRoot: repo,
42+
name: "task",
43+
baseRef: "HEAD",
44+
ownerKind,
45+
...(ownerKind === "manual" ? {} : { ownerId: "owner" }),
46+
});
47+
48+
expect(record.path).toBe(path.join(worktreeRoot, record.repoFingerprint, record.name));
49+
expect(await fs.readFile(path.join(record.path, "README.md"), "utf8")).toBe("base\n");
50+
expect((await service.list()).map((entry) => entry.id)).toEqual([record.id]);
51+
await expect(fs.stat(path.join(stateDir, "state", "openclaw.sqlite"))).resolves.toBeDefined();
52+
await expect(fs.stat(path.join(worktreeRoot, "state"))).rejects.toMatchObject({
53+
code: "ENOENT",
54+
});
55+
},
56+
);
57+
58+
it("reuses, snapshots, and restores recorded paths when the new root is unavailable", async () => {
59+
const manual = await service.create({ repoRoot: repo, name: "manual", baseRef: "HEAD" });
60+
const owner = {
61+
repoRoot: repo,
62+
baseRef: "HEAD",
63+
ownerKind: "session" as const,
64+
ownerId: "owner",
65+
};
66+
const session = await service.create({ ...owner, name: "session" });
67+
await fs.writeFile(path.join(manual.path, "README.md"), "preserved edit\n");
68+
await fs.writeFile(path.join(manual.path, "untracked.txt"), "preserved untracked\n");
69+
worktreeRoot = path.join(root, "unavailable-root");
70+
await fs.writeFile(worktreeRoot, "a file is not a worktree directory\n");
71+
72+
expect((await service.create({ repoRoot: repo, name: "manual", baseRef: "HEAD" })).id).toBe(
73+
manual.id,
74+
);
75+
expect((await service.create({ ...owner, name: "another-title" })).id).toBe(session.id);
76+
await service.remove({ id: manual.id, reason: "root-change" });
77+
const restoredByName = await service.create({
78+
repoRoot: repo,
79+
name: "manual",
80+
baseRef: "HEAD",
81+
});
82+
expect(restoredByName.id).toBe(manual.id);
83+
expect(restoredByName.path).toBe(manual.path);
84+
await service.remove({ id: manual.id, reason: "root-change-again" });
85+
const restoredById = await service.restore({ id: manual.id });
86+
expect(restoredById.path).toBe(manual.path);
87+
expect(await fs.readFile(path.join(manual.path, "README.md"), "utf8")).toBe("preserved edit\n");
88+
expect(await fs.readFile(path.join(manual.path, "untracked.txt"), "utf8")).toBe(
89+
"preserved untracked\n",
90+
);
91+
});
92+
93+
it("cleans registered work across roots and preserves unregistered custom-root contents", async () => {
94+
const owner = {
95+
repoRoot: repo,
96+
baseRef: "HEAD",
97+
ownerKind: "session" as const,
98+
ownerId: "old-owner",
99+
};
100+
const original = await service.create({ ...owner, name: "same-title" });
101+
await service.remove({ id: original.id, reason: "before-root-change" });
102+
worktreeRoot = path.join(root, "custom");
103+
const successor = await service.create({ ...owner, suggestedName: "same-title" });
104+
expect(successor.name).toBe("same-title-2");
105+
expect(successor.path).toBe(path.join(worktreeRoot, successor.repoFingerprint, successor.name));
106+
const restored = await service.restore({ id: original.id });
107+
const unrelated = path.join(
108+
worktreeRoot,
109+
successor.repoFingerprint,
110+
"unregistered",
111+
"keep.txt",
112+
);
113+
await fs.mkdir(path.dirname(unrelated), { recursive: true });
114+
await fs.writeFile(unrelated, "unrelated data\n");
115+
now = Math.max(restored.lastActiveAt, successor.lastActiveAt) + IDLE_GC_MS + 1;
116+
117+
const result = await service.gc();
118+
expect(result.removed.toSorted()).toEqual([original.id, successor.id].toSorted());
119+
expect(result.orphansDeleted).toBe(0);
120+
expect(await fs.readFile(unrelated, "utf8")).toBe("unrelated data\n");
121+
expect((await service.list()).every((record) => record.snapshotRef && record.removedAt)).toBe(
122+
true,
123+
);
124+
expect((await service.restore({ id: original.id })).path).toBe(original.path);
125+
});
126+
127+
it.skipIf(process.platform === "win32")("canonicalizes a symlinked custom root", async () => {
128+
const destination = path.join(root, "destination");
129+
worktreeRoot = path.join(root, "linked");
130+
await fs.mkdir(destination);
131+
await fs.symlink(destination, worktreeRoot, "dir");
132+
const record = await service.create({ repoRoot: repo, name: "linked", baseRef: "HEAD" });
133+
expect(record.path).toBe(path.join(destination, record.repoFingerprint, record.name));
134+
await service.remove({ id: record.id, reason: "symlink-root" });
135+
expect((await service.restore({ id: record.id })).path).toBe(record.path);
136+
});
137+
138+
it.each(["nested", "deep", "symlink"])(
139+
"preserves %s custom-root contents during GC, including after a root change",
140+
async (kind) => {
141+
const nestedRoot = path.join(
142+
stateDir,
143+
"worktrees",
144+
"custom",
145+
...(kind === "deep" ? ["deeper"] : []),
146+
);
147+
await fs.mkdir(nestedRoot, { recursive: true });
148+
worktreeRoot = nestedRoot;
149+
if (kind === "symlink") {
150+
worktreeRoot = path.join(root, "linked-nested-root");
151+
await fs.symlink(
152+
nestedRoot,
153+
worktreeRoot,
154+
process.platform === "win32" ? "junction" : "dir",
155+
);
156+
}
157+
const unrelated = path.join(nestedRoot, "unregistered", "keep.txt");
158+
await fs.mkdir(path.dirname(unrelated));
159+
await fs.writeFile(unrelated, "unrelated data\n");
160+
expect((await service.gc()).orphansDeleted).toBe(0);
161+
expect(await fs.readFile(unrelated, "utf8")).toBe("unrelated data\n");
162+
163+
const record = await service.create({ repoRoot: repo, name: "nested", baseRef: "HEAD" });
164+
await fs.writeFile(path.join(record.path, "README.md"), "unsnapshotted edit\n");
165+
for (const nextRoot of [worktreeRoot, path.join(root, "next-root")]) {
166+
worktreeRoot = nextRoot;
167+
expect((await service.gc()).orphansDeleted).toBe(0);
168+
expect(await fs.readFile(path.join(record.path, "README.md"), "utf8")).toBe(
169+
"unsnapshotted edit\n",
170+
);
171+
expect(await fs.readFile(unrelated, "utf8")).toBe("unrelated data\n");
172+
expect(
173+
(await service.list()).find((entry) => entry.id === record.id)?.removedAt,
174+
).toBeUndefined();
175+
}
176+
},
177+
);
178+
});

0 commit comments

Comments
 (0)