Files
gabrielvidalandClaude Opus 5.5 e9afb461cb feat(cli): ai-agent worktrees — ls / rm / clean the git worktrees under ~/worktrees
ls shows branch, idle days, merged or +N, uncommitted paths and the
conversations that recorded each one; stale = merged, clean, no running
conversation, idle >= --days (3). clean is a dry run until --yes; rm
refuses a dirty / unmerged / running one without --force. Removing also
deletes the merged branch (git branch -d) and stamps removedAt on the
owning conversations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 20:44:33 +01:00

251 lines
9.9 KiB
Python

"""Worktrees — the git worktrees sessions spin up under ``~/worktrees`` (the
homelab's ``scripts/new-worktree.sh``), from a session's side: list them with
what they still hold, remove some, sweep the stale ones. Stdlib only.
A worktree is **stale** — ``clean`` removes it — when nothing would be lost and
nobody is using it:
- its branch is merged: every commit on it is on the repo's main branch (local
``main`` or ``origin/main``), so the worktree adds nothing;
- it has no uncommitted changes (modified or untracked files; gitignored ones
such as the hardlinked ``node_modules`` don't count);
- no conversation that made it is still running;
- it has been idle — no commit, checkout or reset in it — for ``days`` days.
``unmerged_days`` widens that to branches with commits main never got, once
they have been idle that long *and* every conversation that made them has
ended: abandoned experiments. Off unless asked for.
Removing one is ``git worktree remove`` + ``prune`` on the repo that owns it,
then ``git branch -d`` of its branch when it is merged (never a remote branch),
and a ``removedAt`` stamp on every conversation that recorded it, so their
worktree pills show it struck through.
"""
from __future__ import annotations
import os
import shutil
import subprocess
import time
from dataclasses import asdict, dataclass, field
from pathlib import Path
ROOT = Path(os.environ.get("WORKTREES_ROOT") or Path.home() / "worktrees")
# What `clean` waits for after the last commit/checkout before a merged
# worktree counts as stale.
DEFAULT_DAYS = 3.0
# Branches a worktree is "merged" into, local first.
BASES = ("main", "master")
@dataclass
class Worktree:
dir: str # basename — the key conv-meta records
path: str
repo: str | None = None # the main working tree that owns it
branch: str | None = None # None on a detached HEAD
base: str | None = None # the ref it is compared with (main / origin/main)
merged: bool | None = None
ahead: int | None = None # commits main doesn't have
dirty: int | None = None # modified + untracked paths
idle_days: float | None = None
size_mb: float | None = None # without node_modules (hardlinks, ~free)
sessions: list[dict] = field(default_factory=list) # {sessionId, state, title}
broken: str | None = None # why it isn't a usable worktree
@property
def running(self) -> bool:
return any(s.get("state") == "running" for s in self.sessions)
def as_dict(self) -> dict:
return {**asdict(self), "running": self.running}
def _git(cwd: str | Path, *args: str, timeout: float = 20) -> str | None:
try:
r = subprocess.run(["git", "-C", str(cwd), *args], capture_output=True,
text=True, timeout=timeout)
except (OSError, subprocess.TimeoutExpired):
return None
return r.stdout.strip() if r.returncode == 0 else None
def _gitdir(path: Path) -> Path | None:
"""The worktree's admin dir (``<repo>/.git/worktrees/<name>``), from its
``.git`` file."""
try:
line = (path / ".git").read_text().strip()
except OSError:
return None
return Path(line.split(":", 1)[1].strip()) if line.startswith("gitdir:") else None
def _mtime(p: Path) -> float:
try:
return p.stat().st_mtime
except OSError:
return 0.0
def inspect(path: Path, now: float | None = None, size: bool = False) -> Worktree:
"""What one worktree holds. Reads the activity times before running any
git command (``git status`` refreshes the index)."""
now = now or time.time()
w = Worktree(dir=path.name, path=str(path))
gd = _gitdir(path)
if not gd:
w.broken = "not a git worktree (no .git file)"
return w
if not gd.is_dir():
w.broken = f"its git dir is gone ({gd})"
return w
# Last commit / checkout / reset made *in this worktree* (its own reflog),
# or its HEAD commit's time — whichever is later.
last = max(_mtime(gd / "logs" / "HEAD"), _mtime(gd / "HEAD"))
common = _git(path, "rev-parse", "--path-format=absolute", "--git-common-dir")
w.repo = str(Path(common).parent) if common else None
head = _git(path, "rev-parse", "HEAD")
if not head or not w.repo:
w.broken = "git can't read it"
return w
ct = _git(path, "log", "-1", "--format=%ct", "HEAD")
last = max(last, float(ct) if ct else 0.0)
w.idle_days = round(max(0.0, now - last) / 86400, 1) if last else None
br = _git(path, "symbolic-ref", "--short", "-q", "HEAD")
w.branch = br or None
status = _git(path, "status", "--porcelain", "--untracked-files=normal")
w.dirty = len(status.splitlines()) if status is not None else None
# Merged into main if its HEAD is on the local main or the remote one (a
# PR merged on the forge before the local main was pulled).
for base in (*BASES, *(f"origin/{b}" for b in BASES)):
if _git(w.repo, "rev-parse", "--verify", "-q", base) is None:
continue
if w.base is None:
w.base = base
if subprocess.run(["git", "-C", w.repo, "merge-base", "--is-ancestor", head, base],
capture_output=True).returncode == 0:
w.base, w.merged, w.ahead = base, True, 0
break
if w.base and not w.merged:
w.merged = False
n = _git(w.repo, "rev-list", "--count", f"{w.base}..{head}")
w.ahead = int(n) if n and n.isdigit() else None
if size:
try:
r = subprocess.run(["du", "-sk", "--exclude=node_modules", str(path)],
capture_output=True, text=True, timeout=120)
w.size_mb = round(int(r.stdout.split()[0]) / 1024, 1)
except (OSError, ValueError, IndexError, subprocess.TimeoutExpired):
pass
return w
def scan(root: Path | None = None, size: bool = False) -> list[Worktree]:
root = root or ROOT
if not root.is_dir():
return []
now = time.time()
return [inspect(p, now, size) for p in sorted(root.iterdir())
if p.is_dir() and not p.name.startswith(".")]
def owners(meta: dict) -> dict[str, list[str]]:
"""``dir → [session id…]`` of the conversations that recorded each
worktree and haven't stamped it removed (``GET /api/conversation-meta``)."""
out: dict[str, list[str]] = {}
for sid, m in (meta or {}).items():
for e in (m or {}).get("worktrees") or ():
d = (e or {}).get("dir")
if d and not e.get("removedAt"):
out.setdefault(d, []).append(sid)
return out
def verdict(w: Worktree, days: float = DEFAULT_DAYS,
unmerged_days: float | None = None) -> str | None:
"""Why ``clean`` keeps this worktree — None when it is stale."""
if w.broken:
return w.broken
if w.running:
return "its conversation is running"
if w.dirty:
return f"{w.dirty} uncommitted change{'s' if w.dirty != 1 else ''}"
if w.dirty is None or w.merged is None:
return "couldn't tell what it holds"
idle = w.idle_days if w.idle_days is not None else 0.0
if not w.merged:
n = f"{w.ahead} commit{'s' if w.ahead != 1 else ''}" if w.ahead is not None else "commits"
if unmerged_days is None:
return f"{n} not on {w.base}"
if idle < unmerged_days:
return f"{n} not on {w.base}, idle {idle:g}d < {unmerged_days:g}d"
return None
if idle < days:
return f"idle {idle:g}d < {days:g}d"
return None
def unsafe(w: Worktree) -> str | None:
"""What ``rm`` without ``--force`` refuses on: anything that would lose
work or pull a worktree out from under a live run."""
if w.broken:
return w.broken
if w.running:
return "its conversation is running"
if w.dirty:
return f"{w.dirty} uncommitted change{'s' if w.dirty != 1 else ''}"
if w.merged is False:
return f"{w.ahead if w.ahead is not None else 'some'} commit(s) not on {w.base}"
cwd = os.path.realpath(os.getcwd())
if cwd == w.path or cwd.startswith(w.path.rstrip("/") + "/"):
return "this shell is inside it"
return None
def remove(w: Worktree, force: bool = False, keep_branch: bool = False) -> list[str]:
"""Remove one worktree; returns what was done, line by line. Raises
RuntimeError when git refuses."""
done: list[str] = []
if w.broken:
# A leftover directory git no longer knows: only ever under ROOT.
p = Path(w.path).resolve()
if not force or ROOT.resolve() not in p.parents:
raise RuntimeError(f"{w.dir}: {w.broken} (--force deletes the directory)")
shutil.rmtree(p)
return [f"deleted the leftover directory {p}"]
args = ["worktree", "remove", *(["--force"] if force else []), w.path]
r = subprocess.run(["git", "-C", w.repo, *args], capture_output=True, text=True)
if r.returncode != 0:
raise RuntimeError(f"{w.dir}: {(r.stderr or r.stdout).strip()}")
done.append(f"removed {w.path}")
_git(w.repo, "worktree", "prune")
if w.branch and w.merged and not keep_branch:
# `-d`, never `-D`: git re-checks that the branch is merged.
if _git(w.repo, "branch", "-d", w.branch) is not None:
done.append(f"deleted branch {w.branch}")
return done
def fmt_row(w: Worktree, why: str | None) -> str:
if w.broken:
state = "broken"
elif w.merged:
state = "merged"
elif w.merged is False:
state = f"+{w.ahead}" if w.ahead is not None else "unmerged"
else:
state = "?"
bits = [state]
if w.dirty:
bits.append(f"{w.dirty} dirty")
if w.running:
bits.append("running")
elif w.sessions:
bits.append(f"{len(w.sessions)} conv")
if w.size_mb is not None:
bits.append(f"{w.size_mb:g} MB")
idle = f"{w.idle_days:g}d" if w.idle_days is not None else "?"
tail = f"keep: {why}" if why else "stale"
return f"{w.dir:<44} {(w.branch or '-')[:28]:<28} {idle:>6} {', '.join(bits):<22} {tail}"