Skip to content

The agent that grows with you

fix(lsp): release language servers on every in-process workspace removal; pin the call sites

teknium12ebfec40a338
diff --git a/hermes_cli/kanban_db_workspace.py b/hermes_cli/kanban_db_workspace.py
index 5f3804d5f18..b37e4728787 100644
--- a/hermes_cli/kanban_db_workspace.py
+++ b/hermes_cli/kanban_db_workspace.py
@@ -17,6 +17,8 @@ from typing import Optional
from typing import TYPE_CHECKING
import contextlib
+from hermes_cli.worktree_ops import release_lsp_clients
+
if TYPE_CHECKING:
from hermes_cli.kanban_db import Task
@@ -152,6 +154,7 @@ def _cleanup_workspace(conn: sqlite3.Connection, task_id: str) -> None:
# source tree; without this, completion would rmtree the user's data.
# See #28818.
if _is_managed_scratch_path(wp):
+ release_lsp_clients(str(wp))
shutil.rmtree(wp, ignore_errors=True)
_kb._log.debug("Removed scratch workspace: %s", wp)
else:
@@ -181,7 +184,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, release_lsp_clients
+ from hermes_cli.worktree_ops import _worktree_has_unpushed_commits, _worktree_is_dirty
except Exception:
return # CLI safety predicates unavailable — preserve
try:
@@ -270,6 +273,7 @@ def _try_cleanup_parent_workspaces(conn: sqlite3.Connection, task_id: str) -> No
continue
wp = Path(row["workspace_path"])
if wp.is_dir() and _is_managed_scratch_path(wp):
+ release_lsp_clients(str(wp))
shutil.rmtree(wp, ignore_errors=True)
_kb._log.debug("Deferred cleanup: removed parent %s scratch workspace: %s", parent_id, wp)
except Exception:
diff --git a/tests/agent/lsp/test_workspace_release.py b/tests/agent/lsp/test_workspace_release.py
index 771007e3927..8b3ff02f00a 100644
--- a/tests/agent/lsp/test_workspace_release.py
+++ b/tests/agent/lsp/test_workspace_release.py
@@ -6,11 +6,13 @@ worktree is an unbounded leak (multi-GiB tsserver heaps for trees that no longer
from __future__ import annotations
import shutil
+import subprocess
import sys
from pathlib import Path
import pytest
+import agent.lsp
from agent.lsp.manager import LSPService
from agent.lsp.servers import SERVERS, ServerContext, ServerDef, SpawnSpec
from agent.lsp.workspace import clear_cache
@@ -18,13 +20,25 @@ from agent.lsp.workspace import clear_cache
MOCK_SERVER = str(Path(__file__).parent / "_mock_lsp_server.py")
+def _git(*args: str, cwd: Path) -> str:
+ res = subprocess.run(["git", *args], cwd=str(cwd), capture_output=True, text=True, encoding="utf-8",
+ errors="replace", timeout=60)
+ assert res.returncode == 0, f"git {' '.join(args)} failed: {res.stderr}"
+ return res.stdout.strip()
+
+
+def _seed_project(root: Path) -> Path:
+ """A Python project the mock ``pyright`` will attach to."""
+ (root / "pyproject.toml").write_text("", encoding="utf-8")
+ (root / "x.py").write_text("x = 1\n", encoding="utf-8")
+ return root
+
+
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
+ return _seed_project(repo)
@pytest.fixture
@@ -53,12 +67,88 @@ def _service() -> LSPService:
idle_timeout=600.0)
+def project(tmp_path: Path) -> Path:
+ """A pushed-clean project repo: every worktree-removal path agrees it holds no work."""
+ origin = tmp_path / "origin.git"
+ _git("init", "-q", "--bare", str(origin), cwd=tmp_path)
+ repo = tmp_path / "project"
+ _git("clone", "-q", str(origin), str(repo), cwd=tmp_path)
+ _git("config", "user.email", "[email protected]", cwd=repo)
+ _git("config", "user.name", "t", cwd=repo)
+ _seed_project(repo)
+ _git("add", "-A", cwd=repo)
+ _git("commit", "-q", "-m", "init", cwd=repo)
+ _git("push", "-q", "origin", "HEAD", cwd=repo)
+ return repo
+
+
+def _linked_worktree(project: Path, tmp_path: Path) -> Path:
+ wt = tmp_path / "wt"
+ _git("worktree", "add", "-q", "-b", "wt/t1", str(wt), "HEAD", cwd=project)
+ return wt
+
+
+# Production removal paths; each returns (root that goes away, sibling root that stays, remove()).
+def _kanban_worktree(project, tmp_path, monkeypatch):
+ from hermes_cli import kanban_db_workspace as kbw
+ wt = _linked_worktree(project, tmp_path)
+ return wt, project, lambda: kbw._cleanup_worktree_workspace("t1", str(wt), "wt/t1")
+
+
+def _cli_worktree(project, tmp_path, monkeypatch):
+ import cli
+ wt = _linked_worktree(project, tmp_path)
+ info = {"path": str(wt), "branch": "wt/t1", "repo_root": str(project)}
+ return wt, project, lambda: cli._cleanup_worktree(info)
+
+
+def _subagent_worktree(project, tmp_path, monkeypatch):
+ from tools.subagent_worktree import finalize_subagent_worktree
+ wt = _linked_worktree(project, tmp_path)
+ info = {"path": str(wt), "branch": "wt/t1", "repo_root": str(project),
+ "base_commit": _git("rev-parse", "HEAD", cwd=project)}
+
+ def remove():
+ assert finalize_subagent_worktree(info)["pruned"] is True
+ return wt, project, remove
+
+
+def _kanban_scratch(project, tmp_path, monkeypatch):
+ from hermes_cli import kanban_db as kb
+ from hermes_cli import kanban_db_connect as kbc
+ from hermes_cli import kanban_db_workspace as kbw
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ kb.init_db()
+ with kbc.connect() as conn:
+ tid = kb.create_task(conn, title="scratch")
+ ws = kbw.resolve_workspace(kb.get_task(conn, tid))
+ kbw.set_workspace_path(conn, tid, ws)
+ (ws / ".git").mkdir() # the worker cloned a project into its scratch dir
+ _seed_project(ws)
+
+ def remove():
+ with kbc.connect() as conn:
+ assert kb.complete_task(conn, tid, result="ok")
+ return ws, project, remove
+
+
@pytest.mark.parametrize("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")
[email protected]("entry", [_kanban_worktree, _cli_worktree, _subagent_worktree, _kanban_scratch],
+ ids=lambda f: f.__name__.strip("_"))
+def test_workspace_removal_releases_only_its_language_servers(entry, mock_pyright, project, tmp_path,
+ monkeypatch):
+ """Every in-process workspace-removal path (kanban worktree/scratch cleanup, ``hermes -w`` exit, the
+ delegate_task worktree prune) shuts down (single-root) or detaches (multi-root) exactly the removed
+ root's servers BEFORE the tree goes: the sibling keeps serving diagnostics, the released state is gone
+ everywhere, and a repeat release is a no-op."""
+ gone, kept, remove = entry(project, tmp_path, monkeypatch)
+ gone_s, kept_s = str(gone.resolve()), str(kept.resolve())
svc = _service()
+ monkeypatch.setattr(agent.lsp, "_service", svc) # the process-wide singleton the removal paths reach
try:
svc.snapshot_baseline(str(gone / "x.py"))
assert svc.get_diagnostics_sync(str(gone / "x.py"), delta=False)
@@ -66,18 +156,19 @@ def test_release_workspace_tears_down_only_that_workspace(mock_pyright, tmp_path
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)
+ remove()
- 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)
+ assert not gone.exists(), "the production removal path must have removed the tree"
+ assert all(gone_s not in f for c in svc._clients.values() for f in c.workspace_folders)
+ assert all(not p.startswith(gone_s) 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)]
+ (gone_key,) = [k for k in clients if k[1] == gone_s]
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 client.workspace_folders == [kept_s] and client.is_running
+ assert svc.release_workspace(gone_s) == 0
assert svc.get_diagnostics_sync(str(kept / "x.py"), delta=False)
finally:
svc.shutdown()
diff --git a/tools/subagent_worktree.py b/tools/subagent_worktree.py
index 9b1e4add6a9..b30dc5bbc37 100644
--- a/tools/subagent_worktree.py
+++ b/tools/subagent_worktree.py
@@ -168,6 +168,8 @@ def finalize_subagent_worktree(info: Dict[str, str], *, prune: bool = True) -> D
if prune and payload["commits"] == 0 and not payload["dirty"]:
cwd = info.get("repo_root", "") or path
try:
+ from hermes_cli.worktree_ops import release_lsp_clients
+ release_lsp_clients(path) # the child ran in-process: its language servers are ours
removed = _run_git(["worktree", "remove", "--force", path], cwd=cwd)
if removed.returncode == 0:
_run_git(["branch", "-D", branch], cwd=cwd)