Skip to content

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

Python

Task workspace update, gc, and disk use

justrach47b14c10be35
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7dc7596f..3fb04efe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,10 @@ The release workflow uses a tag's section here as its release notes (a
hand-written `docs/releases/<tag>.md` wins if present), so keeping this file
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.
+
## v0.0.302.3
- Desktop first launch: one MCP install (no overlapping flock / “MCP setup incomplete”), and `graff` on login-shell PATH (zsh/bash login+interactive, Homebrew and `~/bin` shims).
diff --git a/apps/native/app/api/worktree/route.ts b/apps/native/app/api/worktree/route.ts
index 6b442717..28585c43 100644
--- a/apps/native/app/api/worktree/route.ts
+++ b/apps/native/app/api/worktree/route.ts
@@ -59,6 +59,20 @@ export async function POST(req: Request) {
if (result.code !== 0) return Response.json({ error: result.stderr.trim() || result.stdout.trim() || "land failed" }, { status: 502 });
return Response.json({ ok: true, output: result.stdout.trim(), root: repo });
}
+ if (action === "update") {
+ const name = slug();
+ if (!name) return Response.json({ error: "not a task workspace" }, { status: 400 });
+ const result = await run(bin, ["worktree", "update", name], repo, 120_000);
+ if (result.code !== 0) return Response.json({ error: result.stderr.trim() || result.stdout.trim() || "update failed" }, { status: 502 });
+ return Response.json({ ok: true, output: result.stdout.trim() });
+ }
+ if (action === "status") {
+ const name = slug();
+ const checkout = name ? `${repo}/.graff/worktrees/${name}` : resolved.root;
+ const result = await run("du", ["-sk", checkout], repo, 15_000);
+ 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 === "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 c7412f35..d82de8d2 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 } from "./harness-task-workspace";
+import { archiveTaskWorkspace, createTaskWorkspace, landTaskWorkspace, runTaskWorkspace, updateTaskWorkspace } from "./harness-task-workspace";
type Props = {
navigationToggle?: ReactNode; sidebarVisible?: boolean;
@@ -58,6 +58,7 @@ export default function HarnessChrome({navigationToggle, sidebarVisible = false,
{onReviews && <button type="button" aria-label="GitHub reviews" aria-pressed={reviewsOpen} onClick={onReviews}>Reviews</button>}
<button type="button" aria-label="New task workspace" onClick={() => void createTaskWorkspace(chatCwd).catch(err => window.alert(String(err.message || err)))}>New task workspace</button>
<button type="button" aria-label="Run workspace script" onClick={() => void runTaskWorkspace(chatCwd, () => { if (!terminalVisible) toggleTerminal(); }).catch(err => window.alert(String(err.message || err)))}>Run</button>
+ <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="Toggle terminal" aria-pressed={terminalVisible} onClick={toggleTerminal}>Terminal <span className="ml-auto text-ink-3">⌘J</span></button>
diff --git a/apps/native/components/site/ProjectsPane.tsx b/apps/native/components/site/ProjectsPane.tsx
index 2335d306..e1413d30 100644
--- a/apps/native/components/site/ProjectsPane.tsx
+++ b/apps/native/components/site/ProjectsPane.tsx
@@ -1,8 +1,8 @@
"use client";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { IconFolder, IconPlusMedium } from "@/lib/icons";
import { compareWorkspaceActivity, workspaceSourceLabel, type Workspace } from "@/lib/workspaces";
-import { archiveTaskWorkspace, landTaskWorkspace } from "./harness-task-workspace";
+import { archiveTaskWorkspace, landTaskWorkspace, updateTaskWorkspace, workspaceBytes } from "./harness-task-workspace";
function taskSlug(path: string): string | null {
const parts = path.replace(/\\/g, "/").split("/");
@@ -29,10 +29,12 @@ export default function ProjectsPane({ workspaces, current, onOpen, onContinue,
{shown.map(w => <article key={w.path} data-project-path={w.path} className="min-w-0 rounded-[14px] border border-line bg-surface p-4">
<div className="flex items-center gap-2 text-ink"><IconFolder size={19} /><h2 className="min-w-0 flex-1 truncate font-medium">{w.name}</h2>{w.path === current && <span className="text-xs text-accent">Current</span>}</div>
<p className="my-3 break-all font-mono text-xs text-ink-3">{workspaceSourceLabel(w)} · {w.path}{taskSlug(w.path) ? ` · worktree-${taskSlug(w.path)}` : ""}</p>
+ {taskSlug(w.path) && <TaskSize path={w.path} />}
<div className="flex flex-wrap gap-2">
<button type="button" onClick={() => onContinue(w.path)} className="rounded-control bg-hover-2 px-3 py-2 text-sm text-ink">Open</button>
<button type="button" onClick={() => onNewChat(w.path)} className="rounded-control px-3 py-2 text-sm text-ink-2 hover:bg-hover">New chat</button>
{taskSlug(w.path) && <>
+ <button type="button" onClick={() => void updateTaskWorkspace(w.path).catch(err => window.alert(String(err.message || err)))} className="rounded-control px-3 py-2 text-sm text-ink-2 hover:bg-hover">Update from main</button>
<button type="button" onClick={() => void landTaskWorkspace(w.path).catch(err => window.alert(String(err.message || err)))} className="rounded-control px-3 py-2 text-sm text-ink-2 hover:bg-hover">Land</button>
<button type="button" onClick={() => void archiveTaskWorkspace(w.path).catch(err => window.alert(String(err.message || err)))} className="rounded-control px-3 py-2 text-sm text-ink-2 hover:bg-hover">Archive</button>
</>}
@@ -43,3 +45,16 @@ export default function ProjectsPane({ workspaces, current, onOpen, onContinue,
</div>
</section>;
}
+
+function TaskSize({ path }: { path: string }) {
+ const [label, setLabel] = useState("");
+ useEffect(() => {
+ let alive = true;
+ void workspaceBytes(path).then(bytes => {
+ if (!alive || bytes <= 0) return;
+ setLabel(bytes >= 1_048_576 ? `${(bytes / 1_048_576).toFixed(1)} MB on disk` : `${Math.max(1, Math.round(bytes / 1024))} KB on disk`);
+ }).catch(() => {});
+ return () => { alive = false; };
+ }, [path]);
+ return label ? <p className="mb-3 text-xs text-ink-3">{label}</p> : null;
+}
diff --git a/apps/native/components/site/harness-task-workspace.ts b/apps/native/components/site/harness-task-workspace.ts
index a66f85ca..42b0a46d 100644
--- a/apps/native/components/site/harness-task-workspace.ts
+++ b/apps/native/components/site/harness-task-workspace.ts
@@ -4,7 +4,7 @@ async function post(action: string, root: string | undefined, name?: string) {
headers: { "content-type": "application/json" },
body: JSON.stringify({ action, root, name }),
});
- const body = await response.json() as { error?: string; path?: string; command?: string; output?: string; root?: string };
+ const body = await response.json() as { error?: string; path?: string; command?: string; output?: string; root?: string; bytes?: number };
if (!response.ok) throw new Error(body.error || "Worktree request failed");
return body;
}
@@ -33,6 +33,16 @@ 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 updateTaskWorkspace(root?: string): Promise<void> {
+ const body = await post("update", root);
+ if (body.output) window.alert(body.output);
+}
+
+export async function workspaceBytes(root?: string): Promise<number> {
+ const body = await post("status", root);
+ return typeof body.bytes === "number" ? body.bytes : 0;
+}
+
export async function landTaskWorkspace(root?: string): Promise<void> {
if (!window.confirm("Land this workspace onto the base branch as one commit and remove the checkout?")) return;
const body = await post("merge", root);
diff --git a/src/cli.zig b/src/cli.zig
index f68de46a..c38735fc 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -339,6 +339,8 @@ pub const usage_text =
\\ graff worktree archive <name> remove a clean duplicate checkout; dirty or unique-commit trees stay
\\ graff worktree merge <name> squash-land worktree-<name> onto the current branch + clean up
\\ graff worktree land <name> same as merge
+ \\ graff worktree update <name> merge the remote base into that workspace
+ \\ graff worktree gc drop dead session trees and clean merged-PR trees
\\ graff worktree remove <name> discard worktree-<name> (drops its scratch work) + delete the branch
\\ graff worktree prune drop git registrations for worktrees whose dirs were deleted
\\ graff servers background servers graff started (this session's or older): pid, port, age
diff --git a/src/task_workspace.zig b/src/task_workspace.zig
index df05bebb..e87dec2c 100644
--- a/src/task_workspace.zig
+++ b/src/task_workspace.zig
@@ -20,6 +20,7 @@ const workspace_prepare = @import("workspace_prepare.zig");
pub const CreateError = error{ NotAGitRepo, InvalidName, NameCollision, CreateFailed, Unsupported };
pub const ArchiveError = error{ InvalidName, NotFound, ArchiveFailed };
+pub const UpdateError = error{ InvalidName, NotFound, Dirty, MergeFailed };
pub const AutoIsolate = union(enum) {
skip,
@@ -266,6 +267,46 @@ pub fn ensure(gpa: Allocator, io: Io, arena: Allocator, opts: CreateOpts) (Creat
return create(gpa, io, arena, opts);
}
+/// Fetch the remote base and merge it into the task workspace. Dirty trees stay untouched.
+pub fn update(gpa: Allocator, io: Io, arena: Allocator, cwd: []const u8, slug: []const u8) (UpdateError || Allocator.Error)!Workspace {
+ const named = try names(arena, slug);
+ const dest = try joinCwd(arena, cwd, named.path);
+ if (!dirExists(io, dest)) return error.NotFound;
+ const path = try absPath(io, arena, dest);
+ const st = runCapped(gpa, io, &.{ "git", "-C", dest, "status", "--porcelain" }, 1 << 16, 8192, 30_000) catch return error.MergeFailed;
+ defer {
+ gpa.free(st.stdout);
+ gpa.free(st.stderr);
+ }
+ if (!ranOk(st)) return error.MergeFailed;
+ if (std.mem.trim(u8, st.stdout, " \t\r\n").len > 0) return error.Dirty;
+ const remote = resolveCreateBase(gpa, io, arena, cwd, "");
+ const base = if (remote.len > 0) remote else readHead(gpa, io, arena, cwd);
+ if (base.len == 0) return error.MergeFailed;
+ const m = runCapped(gpa, io, &.{ "git", "-C", dest, "merge", "--no-edit", base }, 1 << 16, 1 << 16, 60_000) catch return error.MergeFailed;
+ defer {
+ gpa.free(m.stdout);
+ gpa.free(m.stderr);
+ }
+ if (!ranOk(m)) return error.MergeFailed;
+ return .{
+ .name = named.name,
+ .path = path,
+ .branch = named.branch,
+ .base = readHead(gpa, io, arena, path),
+ };
+}
+
+pub fn updateFailureText(err: anyerror) []const u8 {
+ return switch (err) {
+ error.InvalidName => createFailureText(error.InvalidName),
+ error.NotFound => archiveFailureText(error.NotFound),
+ error.Dirty => "workspace has uncommitted changes — commit or stash them first, then update",
+ error.MergeFailed => "could not merge the remote base into this workspace (conflict or missing origin)",
+ else => "could not update the task workspace",
+ };
+}
+
/// Archive removes a clean tree whose commits exist elsewhere. Dirty or unique-commit trees stay.
pub fn archive(gpa: Allocator, io: Io, arena: Allocator, cwd: []const u8, slug: []const u8) (ArchiveError || Allocator.Error)!ArchiveResult {
const named = try names(arena, slug);
diff --git a/src/task_workspace_tests.zig b/src/task_workspace_tests.zig
index 72788346..3d8596bf 100644
--- a/src/task_workspace_tests.zig
+++ b/src/task_workspace_tests.zig
@@ -239,6 +239,38 @@ test "archive: keeps dirty and unique-commit trees, removes a clean duplicate" {
try std.testing.expectEqual(agent_worktree.KeepReason.removed, dropped.reason);
}
+test "update: merges new main commits into a clean workspace" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
+ const a = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const tmp_root = try tmp.dir.realPathFileAlloc(io, ".", a);
+ defer a.free(tmp_root);
+ const root = try std.fmt.allocPrint(a, "{s}/repo", .{tmp_root});
+ defer a.free(root);
+ try Io.Dir.cwd().createDirPath(io, root);
+ try git(io, a, &.{ "init", "-q", "-b", "main", root });
+ try git(io, a, &.{ "-C", root, "config", "user.email", "t@t" });
+ try git(io, a, &.{ "-C", root, "config", "user.name", "t" });
+ const tracked = try std.fs.path.join(a, &.{ root, "f" });
+ defer a.free(tracked);
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = tracked, .data = "old\n" });
+ try git(io, a, &.{ "-C", root, "add", "f" });
+ try git(io, a, &.{ "-C", root, "commit", "-m", "old" });
+ var arena = std.heap.ArenaAllocator.init(a);
+ defer arena.deinit();
+ const ar = arena.allocator();
+ const wt = try ws.create(a, io, ar, .{ .slug = "behind", .cwd = root });
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = tracked, .data = "new\n" });
+ try git(io, a, &.{ "-C", root, "add", "f" });
+ try git(io, a, &.{ "-C", root, "commit", "-m", "new" });
+ _ = try ws.update(a, io, ar, root, "behind");
+ const got = try Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(ar, &.{ wt.path, "f" }), a, .limited(64));
+ defer a.free(got);
+ try std.testing.expectEqualStrings("new\n", got);
+}
+
fn headAt(io: Io, a: Allocator, arena: Allocator, path: []const u8) ![]const u8 {
const r = try runCapped(a, io, &.{ "git", "-C", path, "rev-parse", "HEAD" }, 4096, 4096, 15_000);
defer {
diff --git a/src/worktree_cmd.zig b/src/worktree_cmd.zig
index c1f6ac55..493ddf16 100644
--- a/src/worktree_cmd.zig
+++ b/src/worktree_cmd.zig
@@ -224,13 +224,34 @@ pub fn worktreeCommand(gpa: Allocator, io: Io, arena: Allocator, args: []const [
return;
}
+ if (std.mem.eql(u8, action, "update")) {
+ if (args.len < 2) {
+ try out.writeAll("usage: graff worktree update <name>\n");
+ return;
+ }
+ const tw = @import("task_workspace.zig");
+ const wt = tw.update(gpa, io, arena, ".", args[1]) catch |err| {
+ try out.print("✗ {s}\n", .{tw.updateFailureText(err)});
+ return;
+ };
+ try out.print("✓ updated {s} from the remote base\n path {s}\n branch {s}\n", .{ wt.name, wt.path, wt.branch });
+ return;
+ }
+
+ 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, ".");
+ try out.print("✓ gc: removed {d} idle session tree(s), {d} merged-PR tree(s)\n", .{ n, m });
+ return;
+ }
+
if (std.mem.eql(u8, action, "prune")) {
// Drops git's registrations for worktrees whose dirs were deleted out of
// band, and with `older-than <days>` the stale DIRECTORIES too (#112).
return worktree_prune.pruneCommand(gpa, io, arena, out, args[1..]);
}
- try out.print("unknown worktree command '{s}' — use: graff worktree list | create <name> [base] | run <name> | archive <name> | merge <name> | remove <name> | prune [older-than <days>]\n", .{action});
+ try out.print("unknown worktree command '{s}' — use: graff worktree list | create <name> [base] | run <name> | update <name> | land <name> | archive <name> | merge <name> | remove <name> | gc | prune [older-than <days>]\n", .{action});
}
test { // split-out module: unreferenced, its tests silently never run
diff --git a/src/worktree_reap.zig b/src/worktree_reap.zig
index 43f552b8..2b7de11b 100644
--- a/src/worktree_reap.zig
+++ b/src/worktree_reap.zig
@@ -55,6 +55,53 @@ pub fn orphans(gpa: Allocator, io: Io, arena: Allocator, cwd: []const u8) usize
return removed;
}
+fn prMerged(gpa: Allocator, io: Io, cwd: []const u8, branch: []const u8) bool {
+ const name = prune.shortBranch(branch);
+ const r = process_runner.runCappedWithOptions(gpa, io, &.{ "gh", "pr", "view", name, "--json", "state", "-q", ".state" }, 4096, 4096, 20_000, .{ .cwd = .{ .path = cwd } }) catch return false;
+ defer {
+ gpa.free(r.stdout);
+ gpa.free(r.stderr);
+ }
+ if (!process_runner.ranOk(r)) return false;
+ return std.mem.eql(u8, std.mem.trim(u8, r.stdout, " \t\r\n"), "MERGED");
+}
+
+fn treeDirty(gpa: Allocator, io: Io, path: []const u8) bool {
+ const st = runCapped(gpa, io, &.{ "git", "-C", path, "status", "--porcelain" }, 1 << 16, 8192, 15_000) catch return true;
+ defer {
+ gpa.free(st.stdout);
+ gpa.free(st.stderr);
+ }
+ if (!process_runner.ranOk(st)) return true;
+ return std.mem.trim(u8, st.stdout, " \t\r\n").len > 0;
+}
+
+/// Named task trees whose GitHub PR is MERGED and whose checkout is clean.
+/// Dirty trees stay. `gh` missing or offline is a no-op.
+pub fn mergedPulls(gpa: Allocator, io: Io, arena: Allocator, cwd: []const u8) usize {
+ const dir = if (cwd.len > 0) cwd else ".";
+ const listed = runCapped(gpa, io, &.{ "git", "-C", dir, "worktree", "list", "--porcelain" }, 1 << 18, 8192, 15_000) catch return 0;
+ defer {
+ gpa.free(listed.stdout);
+ gpa.free(listed.stderr);
+ }
+ const entries = prune.parseEntries(arena, listed.stdout) catch return 0;
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const here_n = Io.Dir.cwd().realPathFile(io, ".", &buf) catch 0;
+ const here = if (here_n > 0) buf[0..here_n] else "";
+ var removed: usize = 0;
+ for (entries) |e| {
+ const name = prune.shortBranch(e.branch);
+ if (!std.mem.startsWith(u8, name, "worktree-")) continue;
+ if (sessionPid(e.branch) != null) continue;
+ if (here.len > 0 and std.mem.eql(u8, e.path, here)) continue;
+ if (treeDirty(gpa, io, e.path)) continue;
+ if (!prMerged(gpa, io, dir, e.branch)) continue;
+ if (prune.removeWorktree(gpa, io, e)) removed += 1;
+ }
+ return removed;
+}
+
test "sessionPid: only auto-isolate session branches" {
try std.testing.expectEqual(@as(?i32, 65043), sessionPid("refs/heads/worktree-session-65043-e9cc718d"));
try std.testing.expectEqual(@as(?i32, 65043), sessionPid("worktree-session-65043-e9cc718d"));