Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

workspace gc frees unused trees when the user asks

justrach356fcdac4ea9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3fb04efe..a629e1a3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,7 +12,7 @@ current is part of cutting a release.
## v0.0.302.4
-- Task workspace housekeeping: `graff worktree update` merges the remote base; `gc` drops dead session trees and clean trees whose GitHub PR is MERGED (dirty trees stay). Desktop: Update from main, disk use on the projects card.
+- Task workspace housekeeping: `graff worktree update` merges the remote base; `gc` drops dead session trees and clean trees whose GitHub PR is MERGED (dirty trees stay). Desktop: Update from main, disk use on the projects card. `/workspace gc` and `workspace action=gc` free space when the user asks; they do not run because a turn finished.
## v0.0.302.3
diff --git a/apps/native/app/api/worktree/route.ts b/apps/native/app/api/worktree/route.ts
index 28585c43..3d7abab2 100644
--- a/apps/native/app/api/worktree/route.ts
+++ b/apps/native/app/api/worktree/route.ts
@@ -73,6 +73,11 @@ export async function POST(req: Request) {
const kb = Number((result.stdout.trim().split(/\s+/)[0] ?? "").replace(/[^0-9]/g, ""));
return Response.json({ ok: true, name: name ?? null, bytes: Number.isFinite(kb) ? kb * 1024 : 0 });
}
+ if (action === "gc") {
+ const result = await run(bin, ["worktree", "gc"], repo, 60_000);
+ if (result.code !== 0) return Response.json({ error: result.stderr.trim() || result.stdout.trim() || "gc failed" }, { status: 502 });
+ return Response.json({ ok: true, output: result.stdout.trim() });
+ }
if (action === "run") {
const name = slug();
if (!name) return Response.json({ error: "not a task workspace" }, { status: 400 });
diff --git a/apps/native/components/site/HarnessChrome.tsx b/apps/native/components/site/HarnessChrome.tsx
index d82de8d2..4c375d6e 100644
--- a/apps/native/components/site/HarnessChrome.tsx
+++ b/apps/native/components/site/HarnessChrome.tsx
@@ -7,7 +7,7 @@ import { IconSidebarLeftOpen } from "@/lib/icons";
import type { PointerEvent, MouseEvent, ReactNode } from "react";
import type { Chat } from "./harness-types";
import reviewStyles from "./ChangesPane.module.css";
-import { archiveTaskWorkspace, createTaskWorkspace, landTaskWorkspace, runTaskWorkspace, updateTaskWorkspace } from "./harness-task-workspace";
+import { archiveTaskWorkspace, createTaskWorkspace, gcTaskWorkspaces, landTaskWorkspace, runTaskWorkspace, updateTaskWorkspace } from "./harness-task-workspace";
type Props = {
navigationToggle?: ReactNode; sidebarVisible?: boolean;
@@ -61,6 +61,7 @@ export default function HarnessChrome({navigationToggle, sidebarVisible = false,
<button type="button" aria-label="Update task workspace from main" onClick={() => void updateTaskWorkspace(chatCwd).catch(err => window.alert(String(err.message || err)))}>Update from main</button>
<button type="button" aria-label="Land task workspace" onClick={() => void landTaskWorkspace(chatCwd).catch(err => window.alert(String(err.message || err)))}>Land</button>
<button type="button" aria-label="Archive task workspace" onClick={() => void archiveTaskWorkspace(chatCwd).catch(err => window.alert(String(err.message || err)))}>Archive</button>
+ <button type="button" aria-label="Clear unused task trees" onClick={() => void gcTaskWorkspaces(chatCwd).catch(err => window.alert(String(err.message || err)))}>Clear unused trees</button>
<button type="button" aria-label="Toggle terminal" aria-pressed={terminalVisible} onClick={toggleTerminal}>Terminal <span className="ml-auto text-ink-3">⌘J</span></button>
<button type="button" aria-label="Browser" aria-pressed={browserOpen} onClick={onBrowser}>Browser{pinCount > 0 ? ` (${pinCount})` : ""}</button>
<button type="button" aria-label="Files" aria-pressed={filesOpen && !changesOpen} onClick={onFiles}>Files</button>
diff --git a/apps/native/components/site/harness-task-workspace.ts b/apps/native/components/site/harness-task-workspace.ts
index 42b0a46d..92f9bb4f 100644
--- a/apps/native/components/site/harness-task-workspace.ts
+++ b/apps/native/components/site/harness-task-workspace.ts
@@ -33,6 +33,12 @@ export async function archiveTaskWorkspace(root?: string): Promise<void> {
if (body.root) window.dispatchEvent(new CustomEvent("graff-open-workspace", { detail: { cwd: body.root } }));
}
+export async function gcTaskWorkspaces(root?: string): Promise<void> {
+ if (!window.confirm("Clear unused task trees? Dead session checkouts and clean trees whose PR is merged go away. Dirty trees stay.")) return;
+ const body = await post("gc", root);
+ window.alert(body.output || "gc finished");
+}
+
export async function updateTaskWorkspace(root?: string): Promise<void> {
const body = await post("update", root);
if (body.output) window.alert(body.output);
diff --git a/assets/skills/workspace.md b/assets/skills/workspace.md
index 11d23e25..ab40e3a0 100644
--- a/assets/skills/workspace.md
+++ b/assets/skills/workspace.md
@@ -31,9 +31,10 @@ A new independent task is `workspace action=create`.
`include` in `.graff/workspace.toml`, else `.env*`) from the main checkout,
then runs `scripts.setup` from `.graff/workspace.toml`.
`graff worktree run <name>` is the run script. The user lands or archives;
- do not spawn a child to delete a tree. `graff worktree land <name>` squash-lands
- onto the base branch and removes the checkout. `archive` removes a clean
- duplicate only. Desktop Tools: New task workspace, Run, Land, Archive.
+ do not spawn a child to delete a tree. When the user asks to free disk or
+ clear unused trees, `workspace action=gc` (or `/workspace gc`). That drops
+ dead session trees and clean trees whose GitHub PR is MERGED. Dirty trees
+ stay. Do not gc because a turn finished.
4. If the match is ambiguous, name more of the path. Do not guess.
Do not paste every worktree path into the next user turn. The list result is
diff --git a/src/command_catalog.zig b/src/command_catalog.zig
index 15435de4..246693fe 100644
--- a/src/command_catalog.zig
+++ b/src/command_catalog.zig
@@ -83,7 +83,7 @@ pub const commands = [_]Item{
.{ .name = "/save", .usage = "/save [name]", .desc = "write the conversation to <name>.session.json (default: current)" },
.{ .name = "/resume", .usage = "/resume [source] [--branch destination]", .desc = "restore a saved conversation, optionally cloning it into an independent branch" },
.{ .name = "/sessions", .desc = "list saved sessions here and under ~/.graff/sessions" },
- .{ .name = "/workspace", .usage = "/workspace [list|use <name>]", .desc = "list git worktrees or switch this session into one (file tools follow)" },
+ .{ .name = "/workspace", .usage = "/workspace [list|use <name>|create <name>|gc]", .desc = "list git worktrees, switch, create a task workspace, or gc unused trees (free space)" },
.{ .name = "/experiment", .usage = "/experiment [N|off|status]", .desc = "pre-mint N child worktrees (1-16) and seat the next spawns in them; off clears the pool" },
.{ .name = "/todo", .desc = "show the current task list" },
.{ .name = "/jobs", .usage = "/jobs [keep|unkeep|stop|restart <id>]", .desc = "list background jobs (age, port, idle stop); keep pins a server, restart reruns one" },
diff --git a/src/workspace_switch.zig b/src/workspace_switch.zig
index e3517e00..3737adb9 100644
--- a/src/workspace_switch.zig
+++ b/src/workspace_switch.zig
@@ -30,9 +30,9 @@ const ExecResult = tools_mod.ExecResult;
const task_workspace = @import("task_workspace.zig");
pub const tool_name = "workspace";
-pub const tool_desc = "List this repo's git worktrees, switch into one, or create a task workspace (fresh branch + worktree). action=list (default), use, or create. path is a worktree path, its last folder, or a unique name fragment. create needs name and optional base. File tools and bash follow the new cwd. Root session only — a subagent stays in its assigned tree. Do not bash-cd to switch.";
+pub const tool_desc = "List this repo's git worktrees, switch into one, create a task workspace, or gc unused trees when the user asks to free space. action=list (default), use, create, or gc. gc drops dead session trees and clean trees whose GitHub PR is MERGED; dirty trees stay. Root session only. Do not bash-cd to switch. Do not gc because a turn finished.";
pub const tool_schema =
- \\{"type": "object", "properties": {"action": {"type": "string", "enum": ["list", "use", "create"], "description": "list (default): the repo's git worktrees. use: chdir this session into one. create: mint a fresh branch and worktree from the remote base, then enter it."}, "path": {"type": "string", "description": "worktree path, last folder, or unique fragment (required for use)"}, "name": {"type": "string", "description": "task workspace name (required for create)"}, "base": {"type": "string", "description": "base branch or commit for create (default origin/main after fetch)"}}}
+ \\{"type": "object", "properties": {"action": {"type": "string", "enum": ["list", "use", "create", "gc"], "description": "list (default): the repo's git worktrees. use: chdir this session into one. create: mint a fresh branch and worktree from the remote base, then enter it. gc: free disk — dead session trees and clean merged-PR trees. Only when the user asked to clear space."}, "path": {"type": "string", "description": "worktree path, last folder, or unique fragment (required for use)"}, "name": {"type": "string", "description": "task workspace name (required for create)"}, "base": {"type": "string", "description": "base branch or commit for create (default origin/main after fetch)"}}}
;
pub const Entry = struct {
@@ -248,8 +248,16 @@ fn run(gpa: Allocator, io: Io, arena: Allocator, from_sub: bool, action: []const
if (std.mem.eql(u8, action, "create")) {
return createAndEnter(gpa, io, arena, path, base);
}
+ if (std.mem.eql(u8, action, "gc")) {
+ const n = @import("worktree_reap.zig").orphans(gpa, io, arena, ".");
+ const m = @import("worktree_reap.zig").mergedPulls(gpa, io, arena, ".");
+ return .{
+ .text = tryText(arena, "cleared {d} idle session tree(s) and {d} merged-PR tree(s). Dirty and unique-commit trees stayed.", .{ n, m }),
+ .is_error = false,
+ };
+ }
if (!std.mem.eql(u8, action, "use")) return .{
- .text = "workspace action must be list, use, or create",
+ .text = "workspace action must be list, use, create, or gc",
.is_error = true,
};
if (path.len == 0) return .{
@@ -329,6 +337,8 @@ pub fn slashCommand(root: *Agent, arena: Allocator, line: []const u8, out: *Io.W
action = "create";
} else if (std.mem.eql(u8, rest, "list") or std.mem.eql(u8, rest, "ls")) {
action = "list";
+ } else if (std.mem.eql(u8, rest, "gc") or std.mem.eql(u8, rest, "clean") or std.mem.eql(u8, rest, "clear")) {
+ action = "gc";
} else {
action = "use";
path = rest;
@@ -487,6 +497,7 @@ test "run: subagent is refused; bad action and empty use name the fix" {
try std.testing.expect(std.mem.indexOf(u8, sub.text, "root-session only") != null);
const bad = run(gpa, io, a, false, "send", "", "");
try std.testing.expect(bad.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, bad.text, "gc") != null);
const empty = run(gpa, io, a, false, "use", "", "");
try std.testing.expect(empty.is_error);
try std.testing.expect(std.mem.indexOf(u8, empty.text, "action=list") != null);