Skip to content

Commit bebbf52

Browse files
MilosMosovskyclaudecodex
committed
Hold back worktrees something is using, release 0.10.0
Safe to delete was decided from git alone, so a merged worktree with a live Claude Code or Claude Desktop session, a shell or a dev server in it, or one inside a live session's scratchpad, could be removed from under it. - New In use verdict: a process whose working folder is inside the worktree (matched by file identity, so case, symlinks and lsof's escaped names cannot hide it), or a live Claude Code session owning the scratchpad. The reason names it and what the verdict would be. - A check that cannot look holds every worktree back instead of calling them free; removal checks again after re-reading HEAD and after keeping a copy, then compares the files and the real index with that copy once more. - agentyard remove PATH: the re-checked removal from the command line; the dashboard's copyable commands use it instead of git worktree remove. - An MCP server older than what is installed warns and refuses to remove until it is reconnected. - Also: untracked files hidden by status.showUntrackedFiles=no, clean filters other than LFS, and a git-prunable entry whose folder is still there no longer pass as safe. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-Authored-By: GPT-6.1 Sol (Codex) <noreply@openai.com>
1 parent 8a72377 commit bebbf52

18 files changed

Lines changed: 2105 additions & 130 deletions

‎.gitignore‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,5 @@ dist/
44
/agentyard
55
# CocoIndex Code (ccc)
66
/.cocoindex_code/
7+
/.gocache/
8+
/.gotmp/

‎CHANGELOG.md‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,43 @@ All notable changes are documented here. The format follows
66

77
## [Unreleased]
88

9+
## [0.10.0] - 2026-10-12
10+
11+
### Added
12+
13+
- **In use.** A worktree that would be Safe to delete is In use while a process has its working
14+
folder inside it (a shell, a dev server, Codex, Claude Desktop) or while it sits in a live Claude
15+
Code session's scratchpad. The reason names the process or session and says what the verdict is
16+
otherwise. Worktrees with other verdicts show an in-use chip. Folders are compared by identity on
17+
disk, so case, symlinks and `lsof`'s escaped names cannot hide a process.
18+
- `agentyard remove [-dry-run] PATH...`: the re-checked removal from the command line.
19+
- The MCP server warns in every tool result, and refuses `remove_worktrees`, when it is older than
20+
what is installed: its executable changed, the `agentyard` on PATH leads elsewhere, or the agent
21+
runs another version. Reconnect it after an upgrade.
22+
23+
### Changed
24+
25+
- The dashboard's copyable commands are `agentyard remove <path>`, which re-checks when it runs,
26+
instead of `git worktree remove`; every Safe to delete worktree now has one.
27+
- Reclaimability is a field of the verdict table rather than its first two positions.
28+
- Snapshots carry the agent's version.
29+
30+
### Fixed
31+
32+
- A worktree in use by a live session or process was shown as Safe to delete and could be removed.
33+
- A failed check is never read as "nothing uses it": the scan holds every worktree back as In use,
34+
with the reason, and removal refuses. Removal checks again after re-reading HEAD and after keeping
35+
a copy, then compares the files with that copy once more, and drops the copy when it refuses.
36+
- A worktree git calls prunable while its folder is still there is Keep, not Prunable.
37+
- Untracked files are seen even when `status.showUntrackedFiles` is `no`, by the scan and by git's
38+
own check during removal.
39+
- A worktree with a tracked file that goes through a clean filter (other than Git LFS's) is Keep: the
40+
filter decides what git sees, so bytes it drops are on disk only.
41+
- A change staged after a removal kept its copy, and before git ran, refuses the removal.
42+
- Live sessions are read from the installed agent's Claude Code folder as well as this process's, so
43+
an MCP server or a copied command started elsewhere sees the same scratchpads.
44+
- A Prunable worktree whose folder came back before the removal ran is refused instead of removed.
45+
946
## [0.9.0] - 2026-10-11
1047

1148
### Added
@@ -282,7 +319,8 @@ First public release.
282319
- Single zero-dependency Go binary (around 20 MB RAM); Homebrew cask, release archives for macOS and
283320
Linux, and `scripts/install.sh`.
284321

285-
[Unreleased]: https://github.com/MilosMosovsky/agentyard/compare/v0.9.0...HEAD
322+
[Unreleased]: https://github.com/MilosMosovsky/agentyard/compare/v0.10.0...HEAD
323+
[0.10.0]: https://github.com/MilosMosovsky/agentyard/compare/v0.9.0...v0.10.0
286324
[0.9.0]: https://github.com/MilosMosovsky/agentyard/compare/v0.8.0...v0.9.0
287325
[0.8.0]: https://github.com/MilosMosovsky/agentyard/compare/v0.7.0...v0.8.0
288326
[0.7.0]: https://github.com/MilosMosovsky/agentyard/compare/v0.6.0...v0.7.0

‎README.md‎

Lines changed: 43 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,26 @@ fetches it, looks up each branch's pull request, and gives every worktree one ve
7070
|---|---|
7171
| **Safe to delete** | PR merged (or HEAD already in the default branch), and nothing local is missing from the remote: the worktree is clean, or every uncommitted file and local commit is already in the default branch by content. The only verdict that is safe to delete. |
7272
| **Prunable** | The folder is gone; only git's registration is left, and every commit it had is on a branch, tag or remote. |
73+
| **In use** | Otherwise Safe to delete, but a process or live Claude Code session is using it. Wait until that use ends. |
7374
| **Not merged** | Nothing local is missing from the remote, but it was never merged into the default branch (closed PR, no PR, or its changes live on another branch). Needs a human decision. |
7475
| **Open PR** | The branch has a PR in review. |
75-
| **Keep** | Work that no remote has: uncommitted files or local commits whose content is on no remote branch, another checkout inside its ignored folders, a submodule holding work its origin lacks (changes, untracked files, a stash, worktrees of its own, or commits on no branch of its origin), or files git status cannot see (assume-unchanged, skip-worktree). |
76+
| **Keep** | Work that no remote has: uncommitted files or local commits whose content is on no remote branch, another checkout inside its ignored folders, a submodule holding work its origin lacks (changes, untracked files, a stash, worktrees of its own, or commits on no branch of its origin), or files git status cannot see (assume-unchanged, skip-worktree, or a clean filter other than Git LFS's). |
77+
78+
In use is checked on every scan. A process whose working folder is the worktree, or any folder
79+
inside it, uses that worktree. Folders are compared by what they are on disk, not by how their path
80+
is spelled, so a symlink, `/tmp` against `/private/tmp`, a different letter case on a
81+
case-insensitive disk or a name `lsof` prints escaped all still match; a process at the repository
82+
root does not use the worktrees nested under it. Only agentyard's own work is ignored: agentyard
83+
itself and the git, `lsof`, `ps` and `du` commands it runs, plus git's file-watching daemon. A shell
84+
or an agent is a user even when an agentyard started it. Live Claude Code sessions
85+
(`~/.claude/sessions`, or `-claude-dir`) name the session, and a worktree inside a live session's
86+
scratchpad is in use even with no process in it; a session file counts as live while its process
87+
runs, checked against its start time so a reused pid does not count. Worktrees with any other verdict
88+
keep it and show an in-use chip. When the check itself fails (`lsof` cannot run, the sessions folder
89+
cannot be read), no worktree is Safe to delete: each is In use, with the reason, until a scan can
90+
check again. What it cannot see: another user's processes, and a program that works on files in a
91+
worktree without its working folder being there (an editor opened from elsewhere, say). The verdict
92+
is what the last scan saw; a removal checks again when it runs.
7693

7794
Keep is decided by content, not by commit hash. Commits often reach GitHub another way (rebased,
7895
squash-merged, ported to another branch) and uncommitted files are often identical to what was pushed
@@ -92,10 +109,10 @@ throwaway object directory, so a scan never writes to the repository.
92109

93110
An interactive treemap shows measured disk usage by worktree or repository. Select a tile for its verdict and path, or jump to its row. Search, verdict, and repository filters update the chart, totals, and list together. Choose several values in the Filter menu; remove any selection individually.
94111

95-
Totals are grouped by repository and by folder, with ready-to-copy `git worktree remove` commands for
96-
the safe-to-delete rows. A row with uncommitted files, or a detached HEAD holding commits nothing else
97-
has, gets no command: a copied command would skip the checks below, so it goes only through the
98-
dashboard's Remove or `remove_worktrees`. Rows and repositories are sorted by last activity: the newest of the last
112+
Totals are grouped by repository and by folder, with ready-to-copy `agentyard remove <path>` commands
113+
for the safe-to-delete rows. The command runs the same re-checked removal as the dashboard's Remove
114+
and `remove_worktrees` (see below), so one copied an hour ago still refuses a worktree that has come
115+
into use or gained work since; `agentyard remove -dry-run <path>` only reports. Rows and repositories are sorted by last activity: the newest of the last
99116
commit, the worktree's index and any uncommitted file. Sizes are `du` logical sizes, refreshed every
100117
30 minutes; APFS clones and package-manager hardlinks mean the space you actually free can be smaller.
101118

@@ -437,6 +454,7 @@ to that name. The Sessions tab stays on this Mac unless you also pass `--session
437454
```console
438455
$ agentyard status # loaded? pid, root, network, URL, version, last scan, log path
439456
$ agentyard open # open the dashboard in your browser
457+
$ agentyard remove PATH # remove a Safe to delete worktree, re-checked first (-dry-run to only report)
440458
$ agentyard uninstall # stop it and remove the LaunchAgent
441459
```
442460

@@ -479,6 +497,12 @@ anything.
479497
| `remove_worktrees` | Removes the given worktrees if they are still reclaimable; `dry_run` reports what would go. |
480498
| `sync_worktrees` | Asks the background agent to rescan now, refresh PRs and their local validation, and waits for it, up to a few minutes. |
481499

500+
An MCP server keeps running the code it started with, so after `brew upgrade` the AI may be talking
501+
to an old version. When its executable changed on disk, the `agentyard` on your PATH now leads
502+
elsewhere, or the background agent reports another version, every tool result carries a `warning`,
503+
and `remove_worktrees` refuses (dry runs too): older code may lack checks the installed version has.
504+
Reconnect it (`/mcp` in Claude Code) or start a new session.
505+
482506
Start a PR session with `merge_train`, then use `get_pr` to read each candidate. Both tools are
483507
read-only. They read `/api/prs.json`, falling back to the saved `prs.json` snapshot, and report the
484508
source and age. `agentyard mcp -demo` includes every merge train lane and synthetic PR details.
@@ -491,7 +515,16 @@ The same rules hold for the dashboard's `POST /api/remove`, which runs the same
491515
removing anything, agentyard re-scans each affected repository (fetch, `git status`, unpushed
492516
commits, PR lookup) with the same verdict logic as the dashboard. A worktree that has gained an
493517
uncommitted file or a local commit since the last scan is refused.
494-
- **Only Safe to delete and Prunable.** Keep, Open PR and Not merged are always refused, with the
518+
- **In use is re-checked just before removal.** The fresh scan checks processes and live sessions
519+
again, then once more after re-reading HEAD and a last time after any copy is kept. Only then are
520+
the files looked at for the last time (compared with the copy, the real index included, or
521+
required to be clean), so a write or a `git add` by a process that started during the check is
522+
seen. A worktree that came into use meanwhile
523+
is refused, and a copy already kept for it is dropped. A check that fails refuses too. This narrows
524+
the window in which someone starts working in a folder being removed; nothing on a Mac can close it.
525+
A Prunable worktree is pruned only while its folder is still gone: one that is back is refused,
526+
and one git calls prunable while its folder is still there is Keep.
527+
- **Only Safe to delete and Prunable.** In use, Keep, Open PR and Not merged are always refused, with the
495528
reason. A path must exactly match a worktree git lists right now; the main working tree never does.
496529
A worktree whose ignored folders hold another checkout or worktree anywhere (`.worktrees/`, or deep
497530
under `node_modules/`) is Keep, because removing it would delete that one too. So is one with a
@@ -506,8 +539,8 @@ The same rules hold for the dashboard's `POST /api/remove`, which runs the same
506539
origin vouches (a submodule without one has nothing that does), and the removal's fresh scan fetches it first (branches only, after reading the
507540
local refs), so a branch deleted since, or pushed only to another remote, cannot. The same goes for a gone worktree, whose registration still holds its
508541
submodule repositories. Their ignored files are listed as the worktree's own. A clean one does not
509-
keep it: git refuses such a worktree without `--force`, so it gets no copyable command, and the
510-
checked removal looks once more just before forcing it (the worktree still clean, no file git status
542+
keep it: git refuses such a worktree without `--force`, so only the checked removal takes it, and it
543+
looks once more just before forcing it (the worktree still clean, no file git status
511544
cannot see, its submodules unchanged, no new ignored file, even inside an ignored folder).
512545
Paths must be given exactly as listed; one with `..`, `//` or a trailing `/` is refused.
513546
- **What you confirmed is what goes.** A dry run returns a plan for each worktree. Passed back (the
@@ -592,7 +625,7 @@ manager.
592625
| `-mdns NAME` | off | publish as `http://<name>.local` over mDNS (ignored on loopback) |
593626
| `-interval D` | `5m` | rescan interval for worktrees, PRs and sessions |
594627
| `-size-ttl D` | `30m` | how long a measured worktree size is reused |
595-
| `-claude-dir DIR` | `~/.claude` | Claude Code config folder (holds `projects/`) |
628+
| `-claude-dir DIR` | `~/.claude` | Claude Code config folder (holds `projects/` and live `sessions/`) |
596629
| `-codex-dir DIR` | `~/.codex` | Codex home folder (holds `sessions/`) |
597630
| `-sessions-lan` | off | serve the Sessions tab to other devices too |
598631
| `-once` | | scan once, print the worktree JSON to stdout and exit |
@@ -602,6 +635,7 @@ manager.
602635
| Flag | Default | |
603636
|---|---|---|
604637
| `-listen ADDR` | the installed agent's, else `127.0.0.1:4777` | where to reach the background agent |
638+
| `-claude-dir DIR` | `~/.claude` | live Claude Code sessions for removal checks; honors `CLAUDE_CONFIG_DIR` |
605639
| `-demo` | off | serve the demo's synthetic worktrees; nothing is read or removed |
606640

607641
`agentyard demo` takes `-listen` (default `127.0.0.1:4777`; if that port is busy and you did not pass

‎cli.go‎

Lines changed: 74 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414
"net/http"
1515
"os"
1616
"os/exec"
17+
"path/filepath"
1718
"runtime"
1819
"runtime/debug"
1920
"strconv"
@@ -40,7 +41,7 @@ func appVersion() string {
4041
return "dev"
4142
}
4243

43-
const usage = `agentyard — the yard where your coding agents work.
44+
const cliUsage = `agentyard — the yard where your coding agents work.
4445
Every git worktree, open PR and Claude Code / Codex session on one calm page.
4546
4647
Usage:
@@ -54,6 +55,7 @@ Commands:
5455
uninstall stop the background agent and remove it
5556
serve run the dashboard in the foreground
5657
mcp let your AI query and clean up worktrees (MCP over stdio)
58+
remove remove worktrees that are safe to delete, re-checked first
5759
version print the version
5860
help show this help
5961
@@ -65,7 +67,7 @@ func main() {
6567
var err error
6668
switch cmd {
6769
case "help":
68-
fmt.Print(usage)
70+
fmt.Print(cliUsage)
6971
case "version":
7072
fmt.Println("agentyard", appVersion())
7173
case "serve":
@@ -82,8 +84,10 @@ func main() {
8284
err = runOpen(args)
8385
case "mcp":
8486
err = runMCP(args)
87+
case "remove":
88+
err = runRemove(args)
8589
default:
86-
fmt.Fprintf(os.Stderr, "agentyard: unknown command %q\n\n%s", cmd, usage)
90+
fmt.Fprintf(os.Stderr, "agentyard: unknown command %q\n\n%s", cmd, cliUsage)
8791
os.Exit(2)
8892
}
8993
switch {
@@ -312,3 +316,70 @@ func printRows(w io.Writer, rows [][2]string) {
312316
fmt.Fprintf(w, " %-*s %s\n", width, r[0], r[1])
313317
}
314318
}
319+
320+
// ---------------------------------------------------------------- remove
321+
322+
// runRemove is the dashboard's copyable command: the same re-checked removal
323+
// as its Remove button and remove_worktrees, run in this process, so a
324+
// command copied earlier still refuses a worktree that is in use or has new
325+
// work by the time it runs.
326+
func runRemove(args []string) error {
327+
fs := newFlags("remove", "remove [-dry-run] [-listen ADDR] [-claude-dir DIR] PATH...")
328+
dry := fs.Bool("dry-run", false, "re-check and report what would go; change nothing")
329+
listen := fs.String("listen", "", "the background agent's address (default: the installed agent's, else "+defaultListen+")")
330+
claudeDir := fs.String("claude-dir", "", "Claude Code config folder with live sessions/ (default: the installed agent's, else "+tilde(*flagClaudeDir)+")")
331+
if err := fs.Parse(args); err != nil {
332+
if errors.Is(err, flag.ErrHelp) {
333+
return err
334+
}
335+
return errUsage
336+
}
337+
q := removeRequest{Paths: fs.Args(), DryRun: *dry}
338+
if len(q.Paths) == 0 {
339+
fs.Usage()
340+
return errUsage
341+
}
342+
// Relative to here, but never cleaned: through a symlink, "link/../wt"
343+
// is not "wt", and removeWorktrees refuses a path that is not canonical.
344+
if wd, err := os.Getwd(); err == nil {
345+
for i, p := range q.Paths {
346+
if !filepath.IsAbs(p) {
347+
q.Paths[i] = strings.TrimSuffix(wd, string(filepath.Separator)) + string(filepath.Separator) + p
348+
}
349+
}
350+
}
351+
if err := q.check(); err != nil {
352+
return err
353+
}
354+
if *listen == "" {
355+
cfg, _ := agentConfig()
356+
*listen = cfg.Listen
357+
}
358+
if *claudeDir != "" {
359+
*flagClaudeDir = *claudeDir // the installed agent's is checked too: claudeDirs
360+
}
361+
src := agentSource(*listen)
362+
snap, _, err := src.snapshot()
363+
if err != nil {
364+
return err
365+
}
366+
rep := removeWorktrees(snap, q, removeIn, src.poke)
367+
for _, w := range rep.Warnings {
368+
fmt.Fprintln(os.Stderr, "warning:", w)
369+
}
370+
for _, it := range rep.Results {
371+
fmt.Printf("%s %s\n %s\n", it.Outcome, tilde(it.Path), it.Reason)
372+
if it.Backup != "" {
373+
fmt.Printf(" a copy of its files is kept at %s\n", it.Backup)
374+
}
375+
}
376+
verb := "freed"
377+
if rep.DryRun {
378+
verb = "would free"
379+
}
380+
fmt.Printf("%d removed, %d pruned, %d would go, %d refused; %s %s\n", rep.Removed, rep.Pruned, rep.WouldRemove, rep.Refused, verb, rep.Freed)
381+
if rep.nothingDone() {
382+
return errors.New("nothing was removed")
383+
}
384+
return nil
385+
}

‎cli_test.go‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package main
22

33
import (
4+
"errors"
5+
"path/filepath"
46
"reflect"
57
"strings"
68
"testing"
@@ -130,3 +132,46 @@ func TestAppVersion(t *testing.T) {
130132
t.Error("empty version")
131133
}
132134
}
135+
136+
// agentyard remove is the copyable command: it re-checks, so a worktree that
137+
// came into use after the dashboard printed the command is refused.
138+
func TestCLIRemove(t *testing.T) {
139+
base, repo := gitRepo(t)
140+
busy, free := filepath.Join(base, "wt", "busy"), filepath.Join(base, "wt", "free")
141+
gitT(t, repo, "worktree", "add", "-q", "-b", "busy", busy)
142+
gitT(t, repo, "worktree", "add", "-q", "-b", "free", free)
143+
s := &scanner{sizes: &sizeCache{m: map[string]sizeEntry{}}, repos: []string{repo}, cycle: 1}
144+
s.scan() // saved to the cache, which remove reads when no agent answers
145+
sleep := startSleep(t, busy)
146+
err := runRemove([]string{"-listen", "127.0.0.1:1", busy, free})
147+
if err != nil {
148+
t.Fatal(err)
149+
}
150+
if !exists(busy) || exists(free) {
151+
t.Fatalf("busy kept=%v, free removed=%v", exists(busy), !exists(free))
152+
}
153+
sleep.Process.Kill()
154+
sleep.Wait()
155+
if err := runRemove([]string{"-listen", "127.0.0.1:1", "-dry-run", busy}); err != nil || !exists(busy) {
156+
t.Fatalf("dry run: %v", err)
157+
}
158+
if err := runRemove([]string{"-listen", "127.0.0.1:1"}); !errors.Is(err, errUsage) {
159+
t.Fatalf("no paths: %v", err)
160+
}
161+
}
162+
163+
// Paths are taken as typed: relative to here, never cleaned.
164+
func TestCLIRemovePaths(t *testing.T) {
165+
base, repo := gitRepo(t)
166+
wt := filepath.Join(base, "wt", "rel")
167+
gitT(t, repo, "worktree", "add", "-q", "-b", "rel", wt)
168+
s := &scanner{sizes: &sizeCache{m: map[string]sizeEntry{}}, repos: []string{repo}, cycle: 1}
169+
s.scan()
170+
t.Chdir(filepath.Join(base, "wt"))
171+
if err := runRemove([]string{"-listen", "127.0.0.1:1", "-dry-run", "x/../rel"}); err == nil {
172+
t.Fatal("a path with .. was accepted")
173+
}
174+
if err := runRemove([]string{"-listen", "127.0.0.1:1", "rel"}); err != nil || exists(wt) {
175+
t.Fatalf("relative path: %v, still there=%v", err, exists(wt))
176+
}
177+
}

0 commit comments

Comments
 (0)