Skip to content

The agent that grows with you

fix(kanban): reap worktree workspaces at task completion and archive

Aleksei Razsadin00c184170b73
diff --git a/hermes_cli/kanban.py b/hermes_cli/kanban.py
index 85cc4b1f80f..0671c133590 100644
--- a/hermes_cli/kanban.py
+++ b/hermes_cli/kanban.py
@@ -3217,9 +3217,20 @@ def _cmd_gc(args: argparse.Namespace) -> int:
removed_ws = 0
with kb.connect_closing() as conn:
rows = conn.execute(
- "SELECT id, workspace_kind, workspace_path FROM tasks WHERE status = 'archived'"
+ "SELECT id, workspace_kind, workspace_path, branch_name FROM tasks "
+ "WHERE status = 'archived'"
).fetchall()
for row in rows:
+ if row["workspace_kind"] == "worktree":
+ # Backstop for worktrees that escaped the completion/archive hook
+ # (e.g. tasks archived before that hook existed). Same safety
+ # predicate: only clean, fully-pushed worktrees are removed.
+ wt_path = row["workspace_path"]
+ if wt_path and Path(wt_path).is_dir():
+ kb._cleanup_worktree_workspace(row["id"], wt_path, row["branch_name"])
+ if not Path(wt_path).is_dir():
+ removed_ws += 1
+ continue
if row["workspace_kind"] != "scratch":
continue
path = Path(row["workspace_path"] or (scratch_root / row["id"]))
diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.py
index ce29dbe7e20..ddb37526311 100644
--- a/hermes_cli/kanban_db.py
+++ b/hermes_cli/kanban_db.py
@@ -5880,19 +5880,20 @@ def _cleanup_workspace(conn: sqlite3.Connection, task_id: str) -> None:
Called from :func:`complete_task` after the DB transaction commits.
Best-effort — any error is swallowed so cleanup never blocks task completion.
- Only ``scratch`` workspaces are removed; ``worktree`` and ``dir`` workspaces
- are intentionally preserved.
+ ``scratch`` workspaces are removed; ``worktree`` workspaces are removed only
+ when provably free of work (clean tree, every commit reachable from a
+ remote-tracking ref); ``dir`` workspaces are intentionally preserved.
"""
try:
row = conn.execute(
- "SELECT workspace_kind, workspace_path FROM tasks WHERE id = ?",
+ "SELECT workspace_kind, workspace_path, branch_name FROM tasks WHERE id = ?",
(task_id,),
).fetchone()
if not row:
return
kind: Optional[str] = row["workspace_kind"]
path: Optional[str] = row["workspace_path"]
- if kind != "scratch" or not path:
+ if kind not in ("scratch", "worktree") or not path:
# This task's own workspace isn't a removable scratch dir, but its
# completion may still unblock a deferred parent scratch cleanup
# (e.g. a 'dir' child whose scratch parent was waiting on it). #33774
@@ -5900,7 +5901,7 @@ def _cleanup_workspace(conn: sqlite3.Connection, task_id: str) -> None:
return
# Check if this task has children that still need the workspace.
# If any child is not yet done/archived, defer cleanup so the
- # child can read handoff artifacts from the scratch dir (#33774).
+ # child can read handoff artifacts from the workspace (#33774).
_active_children = conn.execute(
"SELECT 1 FROM task_links l "
"JOIN tasks t ON t.id = l.child_id "
@@ -5910,11 +5911,16 @@ def _cleanup_workspace(conn: sqlite3.Connection, task_id: str) -> None:
).fetchone()
if _active_children:
_log.debug(
- "Deferring scratch workspace cleanup for task %s: "
+ "Deferring %s workspace cleanup for task %s: "
"active children still need workspace at %s",
- task_id, path,
+ kind, task_id, path,
)
return
+ if kind == "worktree":
+ _cleanup_worktree_workspace(task_id, path, row["branch_name"])
+ _cleanup_worker_tmux(conn, task_id)
+ _try_cleanup_parent_workspaces(conn, task_id)
+ return
import shutil
wp = Path(path)
if wp.is_dir():
@@ -5944,6 +5950,65 @@ def _cleanup_workspace(conn: sqlite3.Connection, task_id: str) -> None:
pass # best-effort — never block completion
+def _cleanup_worktree_workspace(
+ task_id: str, path: str, branch_name: Optional[str] = None
+) -> None:
+ """Remove a finished task's linked git worktree when it holds no work.
+
+ Mirrors the safety judgment of the CLI startup pruner
+ (``cli._prune_stale_worktrees``): removal requires a clean working tree
+ AND every commit reachable from a remote-tracking ref. Any doubt — dirty
+ files, unpushed commits, unresolvable repo, failing git — preserves the
+ worktree. The task's auto-generated ``wt/<task-id>`` branch is deleted
+ with it; custom branches are kept. Best-effort like the scratch path.
+ """
+ try:
+ from cli import _worktree_has_unpushed_commits, _worktree_is_dirty
+ except Exception:
+ return # CLI safety predicates unavailable — preserve
+ try:
+ wp = Path(path).expanduser()
+ if not wp.is_dir():
+ return
+ common = _git_common_dir(wp)
+ if common is None or common.name != ".git":
+ return # not a linked worktree of a normal repo — never guess
+ repo_root = common.parent
+ if wp.resolve(strict=False) == repo_root.resolve(strict=False):
+ return # never remove the main checkout
+ if _worktree_is_dirty(str(wp)) or _worktree_has_unpushed_commits(str(wp)):
+ _log.info(
+ "Preserving worktree for task %s: dirty or unpushed work at %s",
+ task_id, wp,
+ )
+ return
+ result = subprocess.run(
+ ["git", "-C", str(repo_root), "worktree", "remove", "--force", str(wp)],
+ capture_output=True,
+ text=True, encoding='utf-8', errors='replace',
+ timeout=60,
+ check=False,
+ )
+ if result.returncode != 0:
+ _log.warning(
+ "git worktree remove failed for task %s at %s: %s",
+ task_id, wp, (result.stderr or result.stdout or "").strip(),
+ )
+ return
+ _log.debug("Removed worktree workspace: %s", wp)
+ branch = (branch_name or "").strip() or f"wt/{task_id}"
+ if branch.startswith("wt/"):
+ subprocess.run(
+ ["git", "-C", str(repo_root), "branch", "-D", branch],
+ capture_output=True,
+ text=True, encoding='utf-8', errors='replace',
+ timeout=30,
+ check=False,
+ )
+ except Exception:
+ pass # best-effort — never block completion
+
+
def _try_cleanup_parent_workspaces(conn: sqlite3.Connection, task_id: str) -> None:
"""Clean up parent scratch workspaces now that *task_id* completed.
@@ -5959,10 +6024,14 @@ def _try_cleanup_parent_workspaces(conn: sqlite3.Connection, task_id: str) -> No
).fetchall()
for (parent_id,) in parents:
row = conn.execute(
- "SELECT workspace_kind, workspace_path FROM tasks WHERE id = ?",
+ "SELECT workspace_kind, workspace_path, branch_name FROM tasks WHERE id = ?",
(parent_id,),
).fetchone()
- if not row or row["workspace_kind"] != "scratch" or not row["workspace_path"]:
+ if (
+ not row
+ or row["workspace_kind"] not in ("scratch", "worktree")
+ or not row["workspace_path"]
+ ):
continue
# Check if ALL children of this parent are terminal
active = conn.execute(
@@ -5975,6 +6044,11 @@ def _try_cleanup_parent_workspaces(conn: sqlite3.Connection, task_id: str) -> No
if active:
continue # still has active children
# All children done — safe to clean up parent workspace
+ if row["workspace_kind"] == "worktree":
+ _cleanup_worktree_workspace(
+ parent_id, row["workspace_path"], row["branch_name"]
+ )
+ continue
import shutil
wp = Path(row["workspace_path"])
if wp.is_dir() and _is_managed_scratch_path(wp):
@@ -7452,6 +7526,9 @@ def archive_task(conn: sqlite3.Connection, task_id: str) -> bool:
# Promote newly-unblocked dependents immediately instead of waiting
# for a later dispatcher tick.
recompute_ready(conn)
+ # Reap the workspace on archive too — tasks archived without ever
+ # completing previously kept their scratch dir / worktree forever.
+ _cleanup_workspace(conn, task_id)
return True
diff --git a/tests/hermes_cli/test_kanban_worktree_teardown.py b/tests/hermes_cli/test_kanban_worktree_teardown.py
new file mode 100644
index 00000000000..e51f1ea0fdf
--- /dev/null
+++ b/tests/hermes_cli/test_kanban_worktree_teardown.py
@@ -0,0 +1,198 @@
+"""Tests for worktree workspace teardown at task completion/archive.
+
+Covers the ownership gap where kanban ``worktree`` workspaces were never
+reaped by anything: ``_cleanup_workspace`` preserved them by design, the CLI
+startup pruner explicitly skips ``t_*`` worktrees ("dispatcher-driven
+lifecycle"), and ``kanban gc`` only swept scratch. A completed or archived
+task's linked worktree is now removed when — and only when — it provably
+holds no work: clean working tree and every commit reachable from a
+remote-tracking ref. Any doubt preserves the worktree.
+"""
+
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from hermes_cli import kanban_db as kb
+
+
+def _git(*args: str, cwd: str | None = None) -> str:
+ result = subprocess.run(
+ ["git", *args],
+ cwd=cwd,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=60,
+ )
+ assert result.returncode == 0, f"git {' '.join(args)} failed: {result.stderr}"
+ return result.stdout
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+def kanban_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ kb.init_db()
+ return home
+
+
+def repo(tmp_path: Path) -> Path:
+ """A project repo with a remote whose history is fully pushed."""
+ origin = tmp_path / "origin.git"
+ _git("init", "--bare", str(origin))
+ project = tmp_path / "project"
+ _git("clone", str(origin), str(project))
+ _git("-C", str(project), "config", "user.email", "[email protected]")
+ _git("-C", str(project), "config", "user.name", "t")
+ (project / "README.md").write_text("hello\n", encoding="utf-8")
+ _git("-C", str(project), "add", "README.md")
+ _git("-C", str(project), "commit", "-m", "init")
+ _git("-C", str(project), "push", "origin", "HEAD")
+ return project
+
+
+def _make_worktree(repo: Path, task_id: str, branch: str | None = None) -> Path:
+ target = repo / ".worktrees" / task_id
+ kb._ensure_git_worktree(repo, target, branch or f"wt/{task_id}")
+ return target
+
+
+def _branch_exists(repo: Path, branch: str) -> bool:
+ out = _git("-C", str(repo), "branch", "--list", branch)
+ return bool(out.strip())
+
+
+# ---------------------------------------------------------------------------
+# _cleanup_worktree_workspace unit behavior
+# ---------------------------------------------------------------------------
+
+
+def test_clean_pushed_worktree_removed(repo: Path) -> None:
+ wt = _make_worktree(repo, "t_aaaa1111")
+ kb._cleanup_worktree_workspace("t_aaaa1111", str(wt))
+ assert not wt.exists()
+ # auto-generated task branch goes with it
+ assert not _branch_exists(repo, "wt/t_aaaa1111")
+ # main checkout untouched
+ assert (repo / "README.md").exists()
+
+
+def test_dirty_worktree_preserved(repo: Path) -> None:
+ wt = _make_worktree(repo, "t_bbbb2222")
+ (wt / "wip.txt").write_text("uncommitted\n", encoding="utf-8")
+ kb._cleanup_worktree_workspace("t_bbbb2222", str(wt))
+ assert wt.is_dir()
+ assert (wt / "wip.txt").exists()
+
+
+def test_unpushed_commits_preserved(repo: Path) -> None:
+ wt = _make_worktree(repo, "t_cccc3333")
+ (wt / "work.txt").write_text("committed but not pushed\n", encoding="utf-8")
+ _git("-C", str(wt), "add", "work.txt")
+ _git("-C", str(wt), "commit", "-m", "local work")
+ kb._cleanup_worktree_workspace("t_cccc3333", str(wt))
+ assert wt.is_dir()
+
+
+def test_custom_branch_survives_worktree_removal(repo: Path) -> None:
+ wt = _make_worktree(repo, "t_dddd4444", branch="feature/custom")
+ kb._cleanup_worktree_workspace("t_dddd4444", str(wt), "feature/custom")
+ assert not wt.exists()
+ # only auto-generated wt/* branches are deleted
+ assert _branch_exists(repo, "feature/custom")
+
+
+def test_main_checkout_never_removed(repo: Path) -> None:
+ kb._cleanup_worktree_workspace("t_eeee5555", str(repo))
+ assert repo.is_dir()
+ assert (repo / "README.md").exists()
+
+
+def test_non_git_dir_preserved(tmp_path: Path) -> None:
+ plain = tmp_path / "not-a-worktree"
+ plain.mkdir()
+ kb._cleanup_worktree_workspace("t_ffff6666", str(plain))
+ assert plain.is_dir()
+
+
+# ---------------------------------------------------------------------------
+# Lifecycle integration: complete / archive / deferred parents
+# ---------------------------------------------------------------------------
+
+
+def _worktree_task(conn, repo: Path, title: str = "wt-task") -> tuple[str, Path]:
+ tid = kb.create_task(conn, title=title, assignee="worker")
+ wt = _make_worktree(repo, tid)
+ with kb.write_txn(conn):
+ conn.execute(
+ "UPDATE tasks SET workspace_kind='worktree', workspace_path=?, "
+ "branch_name=? WHERE id=?",
+ (str(wt), f"wt/{tid}", tid),
+ )
+ return tid, wt
+
+
+def test_complete_task_reaps_clean_worktree(kanban_home: Path, repo: Path) -> None:
+ with kb.connect_closing() as conn:
+ tid, wt = _worktree_task(conn, repo)
+ with kb.write_txn(conn):
+ conn.execute("UPDATE tasks SET status='ready' WHERE id=?", (tid,))
+ assert kb.claim_task(conn, tid, claimer="worker") is not None
+ assert kb.complete_task(conn, tid, summary="done")
+ assert not wt.exists()
+ assert not _branch_exists(repo, f"wt/{tid}")
+
+
+def test_complete_task_preserves_dirty_worktree(kanban_home: Path, repo: Path) -> None:
+ with kb.connect_closing() as conn:
+ tid, wt = _worktree_task(conn, repo)
+ (wt / "wip.txt").write_text("unsaved\n", encoding="utf-8")
+ with kb.write_txn(conn):
+ conn.execute("UPDATE tasks SET status='ready' WHERE id=?", (tid,))
+ assert kb.claim_task(conn, tid, claimer="worker") is not None
+ assert kb.complete_task(conn, tid, summary="done")
+ assert wt.is_dir()
+ assert (wt / "wip.txt").exists()
+
+
+def test_archive_task_reaps_clean_worktree(kanban_home: Path, repo: Path) -> None:
+ with kb.connect_closing() as conn:
+ tid, wt = _worktree_task(conn, repo)
+ assert kb.archive_task(conn, tid)
+ assert not wt.exists()
+
+
+def test_parent_worktree_deferred_until_children_done(
+ kanban_home: Path, repo: Path
+) -> None:
+ with kb.connect_closing() as conn:
+ parent, parent_wt = _worktree_task(conn, repo, title="parent")
+ child = kb.create_task(conn, title="child", assignee="worker")
+ kb.link_tasks(conn, parent, child)
+
+ with kb.write_txn(conn):
+ conn.execute("UPDATE tasks SET status='ready' WHERE id=?", (parent,))
+ assert kb.claim_task(conn, parent, claimer="worker") is not None
+ assert kb.complete_task(conn, parent, summary="parent done")
+ # child still active -> parent worktree must survive for handoff
+ assert parent_wt.is_dir()
+
+ with kb.write_txn(conn):
+ conn.execute("UPDATE tasks SET status='ready' WHERE id=?", (child,))
+ assert kb.claim_task(conn, child, claimer="worker") is not None
+ assert kb.complete_task(conn, child, summary="child done")
+ # last child terminal -> deferred parent worktree reaped
+ assert not parent_wt.exists()