workspace.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. """Workspace and project-root resolution for LSP.
  2. 1. **Workspace gate** — LSP only runs when the cwd (or the edited file) sits inside a git
  3. worktree, so gateway users on user-home cwd's never spawn daemons.
  4. 2. **Workspace trust** — whether a server may load code the project itself ships.
  5. 3. **nearest_root** — the per-server project-root walk: up from a start path looking for marker
  6. files (``pyproject.toml``, ``Cargo.toml``, ...), optionally bailing if an exclude marker
  7. shows up first.
  8. """
  9. from __future__ import annotations
  10. import logging
  11. import os
  12. from pathlib import Path
  13. from typing import AbstractSet, Iterable, Iterator, Optional, Set, Tuple
  14. logger = logging.getLogger("agent.lsp.workspace")
  15. # Cache: start dir → (worktree_root, is_git) so repeated calls don't re-stat. Cleared on shutdown; capped
  16. # because every distinct file dir a long gateway session touches lands here (#62950).
  17. _workspace_cache: dict = {}
  18. _WORKSPACE_CACHE_CAP = 512
  19. # Walk cap: the deepest reasonable monorepo is well under 64 levels; bounds a
  20. # pathological cwd or symlink cycle even though parent-equality normally stops us.
  21. _MAX_WALK = 64
  22. def normalize_path(path: str) -> str:
  23. """Expand ``~``, make absolute, collapse ``.``/``..``. Symlinks are deliberately NOT resolved —
  24. some servers (rust-analyzer's Cargo workspace identity) care, and we want the path the user typed."""
  25. return os.path.abspath(os.path.expanduser(path))
  26. def _start_dir(start: str) -> Optional[Path]:
  27. """Normalized start directory (a file's parent), or ``None`` on pathological input."""
  28. try:
  29. start_path = Path(normalize_path(start))
  30. if start_path.is_file():
  31. start_path = start_path.parent
  32. except (OSError, RuntimeError, ValueError):
  33. # Symlink loop, encoding error, etc. — bail rather than crash the lint hook.
  34. return None
  35. return start_path
  36. def _walk_up(start: Path) -> Iterator[Path]:
  37. """Yield ``start`` and its ancestors up to the filesystem root, bounded by ``_MAX_WALK``."""
  38. cur = start
  39. for _ in range(_MAX_WALK):
  40. yield cur
  41. parent = cur.parent
  42. if parent == cur:
  43. return
  44. cur = parent
  45. def find_git_worktree(start: str) -> Optional[str]:
  46. """Return the nearest ancestor dir containing ``.git`` (file or dir — worktrees count), else ``None``."""
  47. start_path = _start_dir(start)
  48. if start_path is None:
  49. return None
  50. cached = _workspace_cache.get(str(start_path))
  51. if cached is not None:
  52. return cached[0]
  53. resolved = None
  54. for cur in _walk_up(start_path):
  55. try:
  56. if (cur / ".git").exists():
  57. resolved = str(cur)
  58. break
  59. except OSError:
  60. break # permission error on a parent dir — bail out cleanly
  61. _workspace_cache[str(start_path)] = (resolved, resolved is not None)
  62. if len(_workspace_cache) > _WORKSPACE_CACHE_CAP:
  63. _workspace_cache.clear() # a stat cache: resetting is a few re-stats, and one atomic op is thread-safe
  64. return resolved
  65. def is_inside_workspace(path: str, workspace_root: str) -> bool:
  66. """True iff ``path`` is inside (or equal to) ``workspace_root``. Symlinks are not resolved: a
  67. symlink pointing outside still counts as outside, matching servers that reject didOpen for
  68. unrelated files."""
  69. p = normalize_path(path)
  70. root = normalize_path(workspace_root)
  71. if p == root:
  72. return True
  73. # commonpath handles case-insensitive filesystems on macOS/Windows.
  74. try:
  75. return os.path.commonpath([p, root]) == root
  76. except ValueError:
  77. return False # different drives on Windows
  78. def nearest_root(
  79. start: str,
  80. markers: Iterable[str],
  81. *,
  82. excludes: Optional[Iterable[str]] = None,
  83. ceiling: Optional[str] = None,
  84. ) -> Optional[str]:
  85. """Walk up from ``start`` for the directory containing the first matched marker.
  86. Returns ``None`` past ``ceiling`` (or the filesystem root), or when an exclude marker is found
  87. first — the server is gated off for that file (e.g. typescript skips deno projects when
  88. ``deno.json`` precedes ``package.json``). Marker names are exact filenames — no globs.
  89. """
  90. start_path = _start_dir(start)
  91. if start_path is None:
  92. return None
  93. ceiling_path = Path(normalize_path(ceiling)) if ceiling else None
  94. markers_list = list(markers)
  95. excludes_list = list(excludes) if excludes else []
  96. def present(cur: Path, names: list) -> bool:
  97. for name in names:
  98. try:
  99. if (cur / name).exists():
  100. return True
  101. except OSError:
  102. continue
  103. return False
  104. for cur in _walk_up(start_path):
  105. # Excludes are checked before markers at each level.
  106. if present(cur, excludes_list):
  107. return None
  108. # A directory holding __init__.py is a Python package, never a project root (hermes_cli/setup.py
  109. # matched the python marker list and gave every package dir its own pyright).
  110. if not present(cur, ["__init__.py"]) and present(cur, markers_list):
  111. return str(cur)
  112. if ceiling_path is not None and cur == ceiling_path:
  113. return None
  114. return None
  115. def resolve_workspace_for_file(file_path: str, *, cwd: Optional[str] = None) -> tuple[Optional[str], bool]:
  116. """Return ``(workspace_root, gated_in)`` for a file. The cwd's worktree wins when the file is
  117. inside it; otherwise the file's own worktree is the fallback anchor (monorepos / unrelated
  118. checkouts). ``(None, False)`` when neither is in a git worktree."""
  119. try:
  120. cwd_anchor = cwd or os.getcwd()
  121. except OSError:
  122. # The process cwd was removed underneath us (a scratch workspace cleaned up at
  123. # card completion); getcwd keeps raising even after the path is recreated, so
  124. # there is simply no cwd anchor — fall through to the file's own worktree.
  125. cwd_anchor = None
  126. cwd_root = find_git_worktree(cwd_anchor) if cwd_anchor else None
  127. if cwd_root is not None and is_inside_workspace(file_path, cwd_root):
  128. return cwd_root, True
  129. file_root = find_git_worktree(file_path)
  130. if file_root is not None:
  131. return file_root, True
  132. return None, False
  133. def operator_workspace_roots() -> set[str]:
  134. """Git worktrees the operator pointed Hermes at: the launch dir and the surface-set workspace
  135. (``resolve_agent_cwd``: the Desktop/TUI session cwd, ``hermes -w``'s worktree, a gateway's
  136. ``terminal.cwd``). The agent's ``cd`` moves neither (it only moves the terminal's cwd). A repo at
  137. or above ``$HOME`` never counts: a dotfiles repo would trust every directory below it."""
  138. from agent.runtime_cwd import resolve_agent_cwd
  139. from gateway.session_context import get_session_env
  140. from tools.terminal_scope import TerminalPolicyUnavailable
  141. from utils import is_truthy_value
  142. # Work the model can schedule has no operator anchor: a kanban worker is launched in (with
  143. # TERMINAL_CWD =) the task's workspace and a cron run's session cwd is the job's workdir, and the
  144. # kanban_create / cronjob tools let the model pick both.
  145. if os.environ.get("HERMES_KANBAN_TASK"):
  146. return set()
  147. anchors = [os.getcwd]
  148. if not is_truthy_value(get_session_env("HERMES_CRON_SESSION", "")):
  149. anchors.append(resolve_agent_cwd)
  150. home = normalize_path("~")
  151. roots: set[str] = set()
  152. for anchor in anchors:
  153. try:
  154. root = find_git_worktree(str(anchor()))
  155. except (OSError, TerminalPolicyUnavailable): # a deleted cwd; a profile whose terminal policy failed
  156. continue
  157. if root is not None and not is_inside_workspace(home, root):
  158. roots.add(root)
  159. return roots
  160. def is_trusted_workspace(root: str, trusted_roots: Iterable[str], operator_roots: AbstractSet[str]) -> bool:
  161. """True iff a language server may load code the project at ``root`` ships (its own interpreter,
  162. TypeScript SDK, config files, build scripts): ``root`` is inside an ``lsp.trusted_workspaces``
  163. entry, or belongs to one of the ``operator_workspace_roots`` worktrees. A nested clone inside
  164. such a worktree has its own ``.git`` and is not trusted: the agent may have fetched it."""
  165. if any(is_inside_workspace(root, t) for t in trusted_roots):
  166. return True
  167. return find_git_worktree(root) in operator_roots
  168. def clear_cache() -> None:
  169. """Clear the workspace-resolution cache (on service shutdown, so re-init doesn't see stale results)."""
  170. _workspace_cache.clear()
  171. __all__ = [
  172. "clear_cache",
  173. "find_git_worktree",
  174. "is_inside_workspace",
  175. "is_trusted_workspace",
  176. "nearest_root",
  177. "normalize_path",
  178. "operator_workspace_roots",
  179. "resolve_workspace_for_file",
  180. ]