Skip to content

The agent that grows with you

fix(kanban): remove worktree when the process cwd is already gone

teknium1cf5287b040d6
diff --git a/hermes_cli/kanban_db_workspace.py b/hermes_cli/kanban_db_workspace.py
index 3bb5b543faa..ff19b76b911 100644
--- a/hermes_cli/kanban_db_workspace.py
+++ b/hermes_cli/kanban_db_workspace.py
@@ -207,10 +207,20 @@ def _cleanup_worktree_workspace(
worktree_path = wp.resolve(strict=False)
try:
cwd = Path.cwd().resolve(strict=False)
- if cwd == worktree_path or cwd.is_relative_to(worktree_path):
- os.chdir(repo_root)
except OSError:
- return # Cannot leave the worktree safely — preserve it.
+ # cwd was already deleted (a scratch-kind child's own workspace is
+ # rmtree'd before this deferred parent cleanup runs, #33774). A
+ # dead cwd cannot hold the worktree open, so leaving it is safe.
+ cwd = None
+ if cwd is None or cwd == worktree_path or cwd.is_relative_to(worktree_path):
+ try:
+ os.chdir(repo_root)
+ except OSError as exc:
+ _kb._log.warning(
+ "Preserving worktree for task %s: cannot leave %s for %s: %s",
+ task_id, cwd or "<deleted cwd>", repo_root, exc,
+ )
+ return
# No --force: git's own dirty guard re-verifies at removal time, so if
# the tree became dirty since our check (TOCTOU) removal fails safe.
result = _git(repo_root, "worktree", "remove", str(wp), timeout=60)
diff --git a/tests/hermes_cli/test_kanban_worktree_teardown.py b/tests/hermes_cli/test_kanban_worktree_teardown.py
index 464b40f54c1..84ff2c55ea2 100644
--- a/tests/hermes_cli/test_kanban_worktree_teardown.py
+++ b/tests/hermes_cli/test_kanban_worktree_teardown.py
@@ -114,6 +114,23 @@ def test_cleanup_leaves_a_worktree_cwd_before_removal(
assert not wt.exists()
+def test_cleanup_proceeds_when_cwd_was_deleted(
+ repo: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Deferred parent cleanup (#33774) runs after the child's scratch cwd was
+ rmtree'd; a dead cwd must not preserve a clean, pushed worktree."""
+ wt = _make_worktree(repo, "t_deadcwd113073")
+ scratch = tmp_path / "scratch"
+ scratch.mkdir()
+ monkeypatch.chdir(scratch)
+ scratch.rmdir()
+
+ kbw._cleanup_worktree_workspace("t_deadcwd113073", str(wt))
+
+ assert not wt.exists()
+ assert not _branch_exists(repo, "wt/t_deadcwd113073")
+
+
def test_cleanup_retries_worktree_removal_once(
repo: Path, monkeypatch: pytest.MonkeyPatch
) -> None: