Skip to content

The agent that grows with you

fix(kanban): drop --force from worktree remove so git re-verifies dirtiness (TOCTOU)

Teknium77ed972f487f
diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.py
index be5fbc85072..ba2ad6a6d87 100644
--- a/hermes_cli/kanban_db.py
+++ b/hermes_cli/kanban_db.py
@@ -5985,8 +5985,12 @@ def _cleanup_worktree_workspace(
task_id, wp,
)
return
+ # No --force: the dirty/unpushed checks above run before removal, so
+ # git's own dirty guard re-verifies at removal time. If the tree
+ # became dirty between our check and the removal (TOCTOU), removal
+ # fails safe and the worktree is preserved.
result = subprocess.run(
- ["git", "-C", str(repo_root), "worktree", "remove", "--force", str(wp)],
+ ["git", "-C", str(repo_root), "worktree", "remove", str(wp)],
capture_output=True,
text=True, encoding='utf-8', errors='replace',
timeout=60,
diff --git a/tests/hermes_cli/test_kanban_worktree_teardown.py b/tests/hermes_cli/test_kanban_worktree_teardown.py
index e51f1ea0fdf..0fc95939121 100644
--- a/tests/hermes_cli/test_kanban_worktree_teardown.py
+++ b/tests/hermes_cli/test_kanban_worktree_teardown.py
@@ -128,6 +128,28 @@ def test_non_git_dir_preserved(tmp_path: Path) -> None:
assert plain.is_dir()
+def test_tree_dirtied_between_check_and_removal_preserved(
+ repo: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """TOCTOU: a tree that becomes dirty after the pre-check is NOT removed.
+
+ Simulates the race by making the pre-check see a clean tree while the
+ tree is actually dirty when ``git worktree remove`` runs. Without
+ ``--force``, git's own dirty guard re-verifies at removal time and the
+ removal fails safe.
+ """
+ import cli
+
+ wt = _make_worktree(repo, "t_gggg7777")
+ (wt / "late-wip.txt").write_text("dirtied after the check\n", encoding="utf-8")
+ # Pre-check lies (as if the file appeared just after it ran) — real git
+ # must still refuse the removal.
+ monkeypatch.setattr(cli, "_worktree_is_dirty", lambda _p: False)
+ kb._cleanup_worktree_workspace("t_gggg7777", str(wt))
+ assert wt.is_dir()
+ assert (wt / "late-wip.txt").exists()
+
+
# ---------------------------------------------------------------------------
# Lifecycle integration: complete / archive / deferred parents
# ---------------------------------------------------------------------------