Skip to content

Commit 8e4eb78

Browse files
authored
fix(worktrees): reclaim archived checkouts and bound disk allocation (#132706)
* fix(worktrees): bound allocation and reclaim archived checkouts * test(worktrees): verify retained state and deterministic archive races * fix(worktrees): align lifecycle guard contracts and cleanup callers * fix(worktrees): budget snapshot deltas without charging unchanged blobs * test(worktrees): release reply dispatchers after archive admission proof * docs: keep managed worktree release note in PR body Managed worktree capacity: default to 30 live checkouts, reserve disk headroom, and reclaim archived checkouts while retaining restorable work and conversation history. Root CHANGELOG.md is owned by the release workflow. * fix(sessions): commit archive state before worktree cleanup
1 parent 2fda157 commit 8e4eb78

34 files changed

Lines changed: 2212 additions & 374 deletions

‎docs/concepts/managed-worktrees.md‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,16 @@ OpenClaw creates branch `openclaw/<name>` at the requested base ref. Without a b
2323

2424
Each `git worktree add` checkout during creation or snapshot restore has a five-minute timeout, including a creation retry from local `HEAD`. Other managed-worktree Git commands keep their two-minute timeout. The separate `.openclaw/worktree-setup.sh` step also keeps its own two-minute timeout.
2525

26+
## Capacity and disk space
27+
28+
OpenClaw allows up to 30 live managed worktrees per state directory. Manual and protected worktrees count toward this limit. Creating or restoring a checkout at the limit reports how to free a slot; it never evicts another session as part of creation. Reusing an existing valid checkout does not require a new slot.
29+
30+
Before allocating a checkout, OpenClaw checks its destination, Git metadata, source checkout, and state volumes. It keeps 10% of each volume free, with a minimum reserve of 4 GiB and a maximum of 16 GiB, plus twice the estimated Git checkout and provisioned-file size. An executable setup script requires additional room equal to the larger of 4 GiB or the current source checkout footprint excluding Git metadata. Space is checked again before provisioning/setup and after setup. An unavailable capacity reading stops allocation with an actionable error.
31+
32+
Creation, restore, and snapshot removal share one allocation lease across repositories and processes using the same state directory. Costs on the same volume are added together. These checks are conservative estimates, not a disk quota: other OpenClaw state directories, shell commands, deployment tools, and arbitrary setup/build output can still consume space. Worktrees created directly through Git are outside the managed count and cleanup lifecycle.
33+
34+
Snapshot removal uses a smaller reserve of 128 MiB plus estimated snapshot writes, so safe cleanup remains possible below the operational reserve. If a snapshot cannot fit, removal preserves the checkout and asks you to free space first.
35+
2636
## Provision ignored files
2737

2838
Add `.worktreeinclude` at the source repository root to copy selected ignored, untracked files into a new worktree. The file uses gitignore-pattern syntax, one pattern per line, with `#` comments:
@@ -59,6 +69,10 @@ OpenClaw exposes these tools only to operator sessions with an actionable Gatewa
5969

6070
The resulting managed worktree is owned by the session, and every agent run in that session uses its checkout. When the workspace is a repository subdirectory, the worktree is anchored at the repository root and the session runs from the matching subdirectory inside it. Session worktree creation uses the method's `operator.write` scope. Repository checkout/ref hooks and filesystem monitors are always disabled. The `.openclaw/worktree-setup.sh` step runs only for an `operator.admin` caller; retries evaluate the current caller's scope rather than retaining the original caller's permission. `.worktreeinclude` provisioning still applies to every caller. Deleting the session attempts to snapshot and remove its managed worktree, including dirty worktrees and branches with unpushed commits. Hourly cleanup also snapshots session worktrees after 7 idle days, treating recent session activity as worktree activity. Removed worktrees remain restorable from their snapshots as described below.
6171

72+
Archiving a session commits its archive state, then snapshots and removes its managed checkout while preserving the conversation and worktree binding. A failed metadata write leaves the checkout untouched. If cleanup cannot finish safely, the session remains archived, its files stay preserved, and the error explains that cleanup is pending. Repeating archive retries cleanup; startup and hourly garbage collection also retry any checkout that remains. Automatic session archival uses the same metadata-first ordering.
73+
74+
Unarchiving, or an authorized human message that reopens the archived session, restores the original branch HEAD plus saved dirty and untracked files before admitting work. A restore failure leaves the session archived. If the original repository or its snapshot is missing, or the 30-day snapshot retention has expired, recover the original repository/snapshot or start a new task; OpenClaw does not substitute an empty checkout for the saved work.
75+
6276
`sessions.create` may include an absolute `cwd` to run directly in another Gateway folder or to choose the source checkout together with `worktree: true`. Connections with `operator.write` may use a Gateway `cwd` contained in any configured agent workspace; realpath containment prevents symlinks from escaping that boundary. Gateway paths outside those workspaces require `operator.admin`. Ordinary worktree chat creation remains `operator.write` and stays anchored to the configured workspace. New Session dispatches a completed worktree session to paired devices or cloud profiles instead of passing a paired-node working directory to creation.
6377

6478
`sessions.create` also accepts `worktreeBaseRef` and `worktreeName` alongside `worktree: true` to pick the base ref and the worktree name (the branch becomes `openclaw/<name>`); both stay at `operator.write`. If `worktreeName` is omitted, the session label or generated first-message title supplies the readable branch name, with a crustacean-themed fallback. For a new session with an initial message or task, creation returns the admitted session and run before worktree preparation finishes. The chat shows the submitted message and naming, checkout, and setup progress; failures remain visible and retryable in the same session. The agent starts only after the finalized worktree is bound. Creation without an initial turn still waits for preparation and returns the worktree in the create result. The bound checkout is persisted on the session row as `worktree: { id, branch, repoRoot }`, so session lists can show its checkout and branch. When session deletion cannot finish that cleanup, `worktreePreserved` identifies the active worktree record that needs attention and reports one bounded reason: owner mismatch, active use or competing cleanup, a foreign Git lock, snapshot failure, or another cleanup failure. These reasons describe cleanup and ownership, not whether the checkout is dirty or has unpushed commits.
@@ -73,6 +87,8 @@ If **New session** reports `git worktree add failed`, read the termination reaso
7387

7488
Before another creation attempt, inspect `git -C <repo-root> worktree list` and `git -C <repo-root> branch --list 'openclaw/*'` for partial state. A failed creation does not guarantee that its checkout and branch were removed. Do not delete a checkout or branch without checking whether it contains work you need.
7589

90+
If a checkout's `.git` link points to missing administrative files, OpenClaw preserves its files and refuses to reuse it. Restore the original repository metadata before using `git worktree repair` from that repository. A different clone with the same remote URL does not recover the missing index or unpushed history; do not replace the link or rebuild the index without verifying the original metadata.
91+
7692
## Snapshots, cleanup, and restore
7793

7894
Removal first creates a synthetic commit containing tracked and non-ignored untracked files, then pins it at `refs/openclaw/snapshots/<id>`. Ignored files never enter the repository object database. OpenClaw stores only the ignored files it actually provisioned in chunked shared-state database rows; the recorded path set remains authoritative even if `.worktreeinclude` later changes or disappears. Restore reads those bytes from the immutable snapshot and reapplies their complete modes. Automatic cleanup preserves a live worktree when a recorded path can no longer be snapshotted safely. If snapshot creation fails, removal stops unless an explicit force delete discards snapshot safety.
@@ -82,7 +98,8 @@ Nested Git repositories and linked worktrees are separate ownership boundaries.
8298
OpenClaw applies these cleanup rules:
8399

84100
- At run end, it removes a worktree only when `git status --porcelain` is empty and `git log HEAD --not --remotes --oneline` finds no unpushed commits. Otherwise it only releases the activity lock.
85-
- Hourly cleanup snapshots and removes unlocked Workboard- and session-owned worktrees idle for more than 7 days, even when dirty. Manual worktrees are never automatically removed.
101+
- Startup and hourly cleanup snapshot and remove unlocked Workboard- and session-owned worktrees idle for more than 7 days, even when dirty. Session worktrees whose owner is archived or absent are eligible immediately. Failed owner lookups preserve the checkout.
102+
- Cleanup also removes the least recently active eligible run-owned worktrees above the default limit of 30. Manual worktrees are never automatically removed, and protected worktrees can keep the total above the limit until they are released or explicitly cleaned up.
86103
- Snapshot records remain restorable for 30 days. Cleanup then deletes the snapshot ref and registry row.
87104
- A live OpenClaw process lock and any foreign or unrecognized git worktree lock protect a worktree from garbage collection.
88105

‎src/agents/worktrees/capacity.ts‎

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
import { statSync, type Dirent } from "node:fs";
2+
import fs from "node:fs/promises";
3+
import path from "node:path";
4+
import { formatDiskSpaceBytes, tryReadDiskSpace } from "../../infra/disk-space.js";
5+
import { isMissingPathError } from "../../infra/errors.js";
6+
import { requireGit } from "./git.js";
7+
8+
const GiB = 1024 ** 3;
9+
export const WORKTREE_SETUP_HEADROOM_BYTES = 4 * GiB;
10+
11+
/** Admission estimates allocations, not a quota on arbitrary repository scripts or other writers. */
12+
export function requireWorktreeDiskSpace(
13+
demands: readonly { path: string; bytes: number }[],
14+
purpose: string,
15+
snapshot = false,
16+
): void {
17+
const volumes = new Map<
18+
number,
19+
{ path: string; available: number; total: number; bytes: number }
20+
>();
21+
for (const demand of demands) {
22+
const space = tryReadDiskSpace(demand.path);
23+
if (!space || space.totalBytes === null) {
24+
throw new Error(
25+
`Cannot determine disk space near ${demand.path}; check the volume and retry ${purpose}.`,
26+
);
27+
}
28+
const device = statSync(space.checkedPath).dev;
29+
const existing = volumes.get(device);
30+
if (existing) {
31+
existing.available = Math.min(existing.available, space.availableBytes);
32+
existing.bytes += demand.bytes;
33+
} else {
34+
volumes.set(device, {
35+
path: space.checkedPath,
36+
available: space.availableBytes,
37+
total: space.totalBytes,
38+
bytes: demand.bytes,
39+
});
40+
}
41+
}
42+
for (const volume of volumes.values()) {
43+
// Cleanup must still be possible below the operational reserve, but never without snapshot room.
44+
const reserve = snapshot
45+
? 128 * 1024 ** 2
46+
: Math.max(4 * GiB, Math.min(volume.total / 10, 16 * GiB));
47+
const required = reserve + volume.bytes;
48+
if (!Number.isSafeInteger(Math.ceil(required)) || volume.available < required) {
49+
throw new Error(
50+
`Insufficient disk space near ${volume.path} for ${purpose}: ${formatDiskSpaceBytes(volume.available)} available; approximately ${formatDiskSpaceBytes(required)} required including safety reserve. Free caches or archive/remove unused worktrees, then retry.`,
51+
);
52+
}
53+
}
54+
}
55+
56+
export async function estimateWorktreeGitBytes(repoRoot: string, ref: string): Promise<number> {
57+
const commit = await requireGit(repoRoot, [
58+
"rev-parse",
59+
"--verify",
60+
"--end-of-options",
61+
`${ref === "-" ? "@{-1}" : ref}^{commit}`,
62+
]);
63+
const sizes = await requireGit(repoRoot, [
64+
"ls-tree",
65+
"-r",
66+
"--format=%(objectsize)",
67+
commit,
68+
"--",
69+
]);
70+
let bytes = 0;
71+
for (const size of sizes.split("\n")) {
72+
if (!size || size === "-") {
73+
continue;
74+
}
75+
const value = Number(size);
76+
if (!Number.isSafeInteger(value) || value < 0) {
77+
throw new Error(
78+
"Cannot estimate worktree checkout size; inspect the repository objects and retry.",
79+
);
80+
}
81+
bytes += Math.max(4096, Math.ceil(value / 4096) * 4096);
82+
}
83+
return bytes;
84+
}
85+
86+
/** Measure without following links; unreadable trees must never be counted as empty. */
87+
export async function directorySizeBytes(root: string, excludeGit = false): Promise<number> {
88+
let entries: Dirent[];
89+
try {
90+
entries = await fs.readdir(root, { withFileTypes: true });
91+
} catch (error) {
92+
if (isMissingPathError(error)) {
93+
return 0;
94+
}
95+
throw error;
96+
}
97+
let total = 0;
98+
for (const entry of entries) {
99+
if (excludeGit && entry.name === ".git") {
100+
continue;
101+
}
102+
const child = path.join(root, entry.name);
103+
if (entry.isDirectory() && !entry.isSymbolicLink()) {
104+
total += await directorySizeBytes(child, excludeGit);
105+
} else {
106+
try {
107+
total += (await fs.lstat(child)).size;
108+
} catch (error) {
109+
if (!isMissingPathError(error)) {
110+
throw error;
111+
}
112+
}
113+
}
114+
}
115+
return total;
116+
}

‎src/agents/worktrees/git.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,12 @@ export function commandError(command: string, result: GitResult): Error {
5555
export async function requireGit(
5656
cwd: string,
5757
args: string[],
58-
options: { env?: NodeJS.ProcessEnv; input?: string | Uint8Array; timeoutMs?: number } = {},
58+
options: {
59+
env?: NodeJS.ProcessEnv;
60+
input?: string | Uint8Array;
61+
timeoutMs?: number;
62+
signal?: AbortSignal;
63+
} = {},
5964
): Promise<string> {
6065
return await requireGitCommand(cwd, args, { ...options, env: gitEnvironment(options.env) });
6166
}

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

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, it } from "vitest";
2-
import { slugifyWorktreeTitle, worktreeNameAllocationFamily } from "./name.js";
2+
import { slugifyWorktreeTitle } from "./name.js";
33

44
describe("slugifyWorktreeTitle", () => {
55
it.each([
@@ -20,13 +20,4 @@ describe("slugifyWorktreeTitle", () => {
2020
it("returns undefined when a title has no ASCII slug characters", () => {
2121
expect(slugifyWorktreeTitle("🦞 日本語")).toBeUndefined();
2222
});
23-
24-
it("joins numeric and dash-truncated names into the same allocation family", () => {
25-
const base = `${"a".repeat(58)}-${"b".repeat(5)}`;
26-
const thousandthCandidate = `${"a".repeat(58)}-1000`;
27-
28-
expect(worktreeNameAllocationFamily(base)).toBe("a".repeat(58));
29-
expect(worktreeNameAllocationFamily(thousandthCandidate)).toBe("a".repeat(58));
30-
expect(worktreeNameAllocationFamily("task-2-3")).toBe("task");
31-
});
3223
});

‎src/agents/worktrees/name.ts‎

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
const WORKTREE_NAME_MAX_LENGTH = 64;
2-
const WORKTREE_ALLOCATION_FAMILY_LENGTH = 59;
32

43
/** Converts a short human-readable title into a valid managed-worktree name. */
54
export function slugifyWorktreeTitle(title: string): string | undefined {
@@ -17,12 +16,3 @@ export function slugifyWorktreeTitle(title: string): string | undefined {
1716
const wordBoundary = truncated.lastIndexOf("-");
1817
return wordBoundary > 0 ? truncated.slice(0, wordBoundary) : truncated;
1918
}
20-
21-
/** Maps names that can converge after a `-1000` suffix into one allocation lane. */
22-
export function worktreeNameAllocationFamily(name: string): string {
23-
let base = name;
24-
while (/-\d+$/.test(base)) {
25-
base = base.replace(/-\d+$/, "");
26-
}
27-
return (base || name).slice(0, WORKTREE_ALLOCATION_FAMILY_LENGTH).replace(/-+$/g, "");
28-
}

0 commit comments

Comments
 (0)