Skip to content

The agent that grows with you

fix(lsp): release a worktree's language servers on removal; reap deleted roots

teknium1d6f1de3f742c
diff --git a/agent/lsp/__init__.py b/agent/lsp/__init__.py
index 933655b00ff..7468e131ab2 100644
--- a/agent/lsp/__init__.py
+++ b/agent/lsp/__init__.py
@@ -63,6 +63,20 @@ def get_service() -> Optional[LSPService]:
return _active(_service)
+def release_workspace(path: str) -> int:
+ """Shut down the LSP clients serving ``path`` (a worktree about to be removed) in every started
+ service, without shutting down unrelated workspaces. Never creates a service. Returns the count."""
+ with _service_lock:
+ services = [svc for svc in (_service, *_services_by_home.values()) if svc is not None]
+ released = 0
+ for svc in services:
+ try:
+ released += svc.release_workspace(path)
+ except Exception as e: # noqa: BLE001
+ logger.debug("LSP workspace release failed for %s: %s", path, e)
+ return released
+
+
def shutdown_service() -> None:
"""Tear down every LSP service that was started. Idempotent."""
global _service
@@ -86,4 +100,4 @@ def _atexit_shutdown() -> None:
logger.debug("atexit LSP shutdown failed: %s", e)
-__all__ = ["get_service", "shutdown_service", "LSPService"]
+__all__ = ["get_service", "release_workspace", "shutdown_service", "LSPService"]
diff --git a/agent/lsp/client.py b/agent/lsp/client.py
index 08714984021..b88503c4e86 100644
--- a/agent/lsp/client.py
+++ b/agent/lsp/client.py
@@ -283,6 +283,16 @@ class LSPClient:
"workspace/didChangeWorkspaceFolders", {"event": {"added": [_folder(root)], "removed": []}},
)
+ async def remove_workspace_folder(self, root: str) -> None:
+ """Detach ``root`` from a running multi-root server (a removed worktree) so the process keeps
+ serving its sibling roots instead of being torn down with them. Idempotent."""
+ if root not in self.workspace_folders:
+ return
+ self.workspace_folders.remove(root)
+ await self._send_notification(
+ "workspace/didChangeWorkspaceFolders", {"event": {"added": [], "removed": [_folder(root)]}},
+ )
+
async def _initialize(self) -> None:
params = {
"rootUri": file_uri(self.workspace_root), "rootPath": self.workspace_root, "processId": os.getpid(),
diff --git a/agent/lsp/eventlog.py b/agent/lsp/eventlog.py
index 69d0b9f22a0..7b374063cc1 100644
--- a/agent/lsp/eventlog.py
+++ b/agent/lsp/eventlog.py
@@ -116,6 +116,15 @@ def log_reaped(keys: List[Tuple[str, str]], idle_timeout: float) -> None:
_emit("reaper", logging.INFO, f"reaped {len(keys)} idle client(s) after {idle_timeout:.0f}s: {summary}")
+def log_released(keys: List[Tuple[str, str]], reason: str) -> None:
+ """Clients were shut down because their workspace went away (worktree released or root deleted).
+ INFO, one line per event; forgets the ``log_active`` announcement like :func:`log_reaped`."""
+ with _announce_lock:
+ _announced_active.difference_update(keys)
+ summary = ", ".join(f"{sid} ({root})" for sid, root in keys)
+ _emit("reaper", logging.INFO, f"released {len(keys)} client(s) ({reason}): {summary}")
+
+
def reset_announce_caches() -> None:
"""Test-only: clear the dedup caches. Production code never calls this."""
with _announce_lock:
diff --git a/agent/lsp/manager.py b/agent/lsp/manager.py
index fb51c5202ea..36056e14f3d 100644
--- a/agent/lsp/manager.py
+++ b/agent/lsp/manager.py
@@ -482,6 +482,66 @@ class LSPService:
if clients:
eventlog.log_reaped([(c.server_id, c.workspace_root) for c in clients], self._idle_timeout)
await asyncio.gather(*(client.shutdown() for client in clients), return_exceptions=True)
+ # Externally deleted project roots (rm -rf, a worktree removed by another process) never go
+ # idle from the server's point of view — tsserver keeps its multi-GiB heap for a tree that is gone.
+ await self._detach_roots(lambda folder: not os.path.isdir(folder), reason="workspace root deleted")
+
+ def release_workspace(self, workspace_root: str) -> int:
+ """Shut down the clients serving ``workspace_root`` or any root beneath it; returns how many.
+
+ Called by the worktree cleanup paths BEFORE ``git worktree remove`` so a gateway that outlives the
+ session does not keep the language server (and its stdio pipes) alive for a tree that no longer
+ exists. Multi-root servers only drop the folder. Idempotent; best-effort — never blocks removal.
+ """
+ if not self._enabled:
+ return 0
+ root = os.path.abspath(workspace_root)
+ try:
+ return self._loop.run(self._release_async(root), timeout=15.0)
+ except Exception as e: # noqa: BLE001
+ logger.debug("LSP release of %s failed: %s", root, e)
+ return 0
+
+ async def _release_async(self, root: str) -> int:
+ def _under(path: str) -> bool:
+ return path == root or path.startswith(root + os.sep)
+
+ # A spawn in flight would insert its client AFTER we detach; let it land first (same loop, so
+ # once the future resolves the client is in ``_clients`` and the pass below sees it).
+ with self._state_lock:
+ pending = [fut for fut in self._spawning.values() if not fut.done()]
+ self._broken = {key for key in self._broken if not _under(key[1])}
+ for path in [p for p in self._delta_baseline if _under(p)]:
+ del self._delta_baseline[path]
+ if pending:
+ await asyncio.wait(pending, timeout=10.0)
+ released = await self._detach_roots(_under, reason="workspace released")
+ clear_cache()
+ return released
+
+ async def _detach_roots(self, is_gone: Callable[[str], bool], *, reason: str) -> int:
+ """Shared teardown primitive for :meth:`release_workspace` and the reaper.
+
+ Clients whose every workspace folder ``is_gone`` are detached under ``_state_lock`` and shut down;
+ multi-root clients that still serve other folders only drop the gone ones. Returns the number of
+ clients shut down.
+ """
+ with self._state_lock:
+ dead_keys = [key for key, c in self._clients.items() if all(map(is_gone, c.workspace_folders))]
+ clients = [self._clients.pop(key) for key in dead_keys]
+ for key in dead_keys:
+ self._last_used.pop(key, None)
+ trims = [(c, [f for f in c.workspace_folders if is_gone(f)]) for c in self._clients.values()]
+ for client, folders in trims:
+ for folder in folders:
+ try:
+ await client.remove_workspace_folder(folder)
+ except Exception as e: # noqa: BLE001
+ logger.debug("LSP folder removal for %s failed: %s", folder, e)
+ if clients:
+ eventlog.log_released([(c.server_id, c.workspace_root) for c in clients], reason)
+ await asyncio.gather(*(client.shutdown() for client in clients), return_exceptions=True)
+ return len(clients)
async def _shutdown_async(self) -> None:
if (reaper := self._idle_reaper_task) is not None:
diff --git a/cli.py b/cli.py
index 4bf44d4ea72..66ff1ad4b20 100644
--- a/cli.py
+++ b/cli.py
@@ -1041,6 +1041,7 @@ from hermes_cli.worktree_ops import (
_repo_is_shallow,
_setup_worktree,
_worktree_has_unpushed_commits,
+ release_lsp_clients,
)
# ============================================================================= Git Worktree Isolation
@@ -1070,7 +1071,9 @@ def _cleanup_worktree(info: Dict[str, str] = None) -> None:
_active_worktree = None
return
- # Unlock first so `remove` isn't blocked by the lock placed at creation. Fail-soft.
+ # Release the tree's language servers while the path still exists, then unlock so `remove`
+ # isn't blocked by the lock placed at creation. Fail-soft.
+ release_lsp_clients(wt_path)
_git_quiet(["worktree", "unlock", wt_path], repo_root, log="git worktree unlock failed (non-fatal)")
_git_quiet(["worktree", "remove", wt_path, "--force"], repo_root, timeout=15, log="Failed to remove worktree")
_git_quiet(["branch", "-D", branch], repo_root, log=f"Failed to delete branch {branch}")
diff --git a/hermes_cli/kanban_db_workspace.py b/hermes_cli/kanban_db_workspace.py
index ff19b76b911..5f3804d5f18 100644
--- a/hermes_cli/kanban_db_workspace.py
+++ b/hermes_cli/kanban_db_workspace.py
@@ -181,7 +181,7 @@ def _cleanup_worktree_workspace(
it. The auto-generated ``wt/<task-id>`` branch is deleted with it; custom
branches are kept. Best-effort."""
try:
- from hermes_cli.worktree_ops import _worktree_has_unpushed_commits, _worktree_is_dirty
+ from hermes_cli.worktree_ops import _worktree_has_unpushed_commits, _worktree_is_dirty, release_lsp_clients
except Exception:
return # CLI safety predicates unavailable — preserve
try:
@@ -223,6 +223,7 @@ def _cleanup_worktree_workspace(
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.
+ release_lsp_clients(str(worktree_path))
result = _git(repo_root, "worktree", "remove", str(wp), timeout=60)
if result.returncode != 0:
# Windows can retain a directory handle briefly after cwd changes.
diff --git a/hermes_cli/worktree_ops.py b/hermes_cli/worktree_ops.py
index f616118b197..d9216a9e395 100644
--- a/hermes_cli/worktree_ops.py
+++ b/hermes_cli/worktree_ops.py
@@ -79,6 +79,20 @@ def _path_is_within_root(path: Path, root: Path) -> bool:
return False
+def release_lsp_clients(wt_path: str) -> None:
+ """Shut down this process's language servers for ``wt_path`` before ``git worktree remove``.
+
+ A gateway outlives the sessions it runs, so without this the ``(server, root)`` client for the
+ removed tree stays registered (tsserver heaps of several GiB pointed at a deleted worktree).
+ Best-effort: LSP trouble must never block worktree removal.
+ """
+ try:
+ from agent.lsp import release_workspace
+ release_workspace(wt_path)
+ except Exception as e:
+ logger.debug("LSP release for worktree %s failed: %s", wt_path, e)
+
+
def _cleanup_failed_worktree_add(repo_root: str, wt_path: Path, branch_name: str) -> None:
"""Sweep the leftovers of a failed/timed-out ``git worktree add`` (fail-soft).
diff --git a/tests/agent/lsp/test_workspace_release.py b/tests/agent/lsp/test_workspace_release.py
new file mode 100644
index 00000000000..771007e3927
--- /dev/null
+++ b/tests/agent/lsp/test_workspace_release.py
@@ -0,0 +1,103 @@
+"""Workspace-scoped teardown: removed worktrees and deleted roots must not keep language servers alive.
+
+A gateway outlives the coding sessions it runs, so a ``(server, root)`` client that survives its
+worktree is an unbounded leak (multi-GiB tsserver heaps for trees that no longer exist).
+"""
+from __future__ import annotations
+
+import shutil
+import sys
+from pathlib import Path
+
+import pytest
+
+from agent.lsp.manager import LSPService
+from agent.lsp.servers import SERVERS, ServerContext, ServerDef, SpawnSpec
+from agent.lsp.workspace import clear_cache
+
+MOCK_SERVER = str(Path(__file__).parent / "_mock_lsp_server.py")
+
+
+def _make_repo(tmp_path: Path, name: str) -> Path:
+ repo = tmp_path / name
+ repo.mkdir()
+ (repo / ".git").mkdir()
+ (repo / "pyproject.toml").write_text("", encoding="utf-8")
+ (repo / "x.py").write_text("x = 1\n", encoding="utf-8")
+ return repo
+
+
+def mock_pyright(request):
+ """Install the mock as ``pyright``; ``request.param`` selects the multi-root shape."""
+ idx = next(i for i, s in enumerate(SERVERS) if s.server_id == "pyright")
+ original = SERVERS[idx]
+
+ def _spawn(root: str, ctx: ServerContext) -> SpawnSpec:
+ return SpawnSpec(command=[sys.executable, MOCK_SERVER], workspace_root=root, cwd=root,
+ env={"MOCK_LSP_SCRIPT": "errors"}, initialization_options={})
+
+ SERVERS[idx] = ServerDef(
+ server_id="pyright", extensions=original.extensions, resolve_root=lambda fp, ws: ws,
+ build_spawn=_spawn, seed_first_push=False, description="mock pyright",
+ multi_root=getattr(request, "param", False),
+ )
+ clear_cache()
+ yield
+ SERVERS[idx] = original
+ clear_cache()
+
+
+def _service() -> LSPService:
+ return LSPService(enabled=True, wait_mode="document", wait_timeout=3.0, install_strategy="manual",
+ idle_timeout=600.0)
+
+
[email protected]("mock_pyright", [False, True], ids=["single-root", "multi-root"], indirect=True)
+def test_release_workspace_tears_down_only_that_workspace(mock_pyright, tmp_path):
+ """Releasing one root shuts down (single-root) or detaches (multi-root) exactly that root: the
+ sibling keeps serving diagnostics, the released state is gone everywhere, and a repeat is a no-op."""
+ gone, kept = _make_repo(tmp_path, "gone"), _make_repo(tmp_path, "kept")
+ svc = _service()
+ try:
+ svc.snapshot_baseline(str(gone / "x.py"))
+ assert svc.get_diagnostics_sync(str(gone / "x.py"), delta=False)
+ assert svc.get_diagnostics_sync(str(kept / "x.py"), delta=False)
+ clients = dict(svc._clients)
+ procs = {key: c._proc for key, c in clients.items()} # asyncio subprocess handles
+
+ assert svc.release_workspace(str(gone)) == (0 if len(clients) == 1 else 1)
+
+ assert all(str(gone) not in f for c in svc._clients.values() for f in c.workspace_folders)
+ assert all(not p.startswith(str(gone)) for p in svc._delta_baseline)
+ if len(clients) == 2: # single-root: the released process is gone, the sibling's is not
+ (gone_key,) = [k for k in clients if k[1] == str(gone)]
+ assert gone_key not in svc._clients and gone_key not in svc._last_used
+ assert procs[gone_key].returncode is not None, "released server process must have exited"
+ else: # multi-root: one shared process, only the folder was dropped
+ (client,) = svc._clients.values()
+ assert client.workspace_folders == [str(kept)] and client.is_running
+ assert svc.release_workspace(str(gone)) == 0
+ assert svc.get_diagnostics_sync(str(kept / "x.py"), delta=False)
+ finally:
+ svc.shutdown()
+
+
+def test_reaper_shuts_down_client_whose_root_was_deleted(mock_pyright, tmp_path):
+ """A root deleted outside Hermes is reaped on the next sweep even though the client is not idle."""
+ repo = _make_repo(tmp_path, "repo")
+ svc = _service()
+ try:
+ assert svc.get_diagnostics_sync(str(repo / "x.py"), delta=False)
+ (key,) = svc._clients
+ proc = svc._clients[key]._proc
+
+ svc._loop.run(svc._reap_idle_once(), timeout=10.0)
+ assert key in svc._clients, "an existing, recently used root must survive the sweep"
+
+ shutil.rmtree(repo)
+ svc._loop.run(svc._reap_idle_once(), timeout=10.0)
+ assert key not in svc._clients and key not in svc._last_used
+ assert proc.returncode is not None, "reaped server process must have exited"
+ finally:
+ svc.shutdown()