coding_context.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. """Coding-context awareness: the single place that decides "are we coding?".
  2. In a code workspace on an interactive surface Hermes adopts a **coding posture**: a
  3. frozen :class:`RuntimeMode` built from a :class:`ContextProfile` (pure data). The
  4. system prompt reads ``system_prompt_parts()``; the toolset collapses ONLY under opt-in
  5. ``focus`` (never strips a user-enabled toolset). ``agent.coding_context``: ``auto``
  6. (default, prompt-only) / ``focus`` / ``on`` / ``off``. Resolved once, immutable; the
  7. workspace snapshot is probed once per session and replayed through
  8. ``system_prompt_parts(workspace_block=...)`` on every later build (cache safety).
  9. """
  10. from __future__ import annotations
  11. import json
  12. import logging
  13. import os
  14. import re
  15. import tempfile
  16. from dataclasses import dataclass
  17. from pathlib import Path
  18. from typing import Any, Optional
  19. from hermes_cli._subprocess_compat import bounded_git_probe
  20. logger = logging.getLogger("hermes.coding_context")
  21. CODING_TOOLSET = "coding"
  22. # Surfaces where ``auto`` may adopt the posture; messaging platforms are deliberately absent.
  23. INTERACTIVE_CODING_PLATFORMS = {"cli", "tui", "acp", "desktop", ""}
  24. # Project-root signals (cheap filename checks) marking a code workspace even without git.
  25. _PROJECT_MARKERS = (
  26. "pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "package.json", "tsconfig.json", "deno.json",
  27. "Cargo.toml", "go.mod", "pom.xml", "build.gradle", "build.gradle.kts", "Gemfile", "composer.json", "mix.exs",
  28. "pubspec.yaml", "CMakeLists.txt", "Makefile", "Dockerfile", "AGENTS.md", "CLAUDE.md", ".cursorrules",
  29. )
  30. # Agent-instruction files surfaced separately from manifests in the snapshot.
  31. _CONTEXT_FILES = ("AGENTS.md", "CLAUDE.md", ".cursorrules")
  32. # Extensions that make a manifest-less git repo a *code* workspace (a `git init` notes folder is not).
  33. _CODE_EXTENSIONS = frozenset({
  34. ".py", ".pyi", ".ipynb", ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".go", ".rs", ".java", ".kt", ".kts",
  35. ".scala", ".rb", ".php", ".c", ".h", ".cc", ".cpp", ".hpp", ".cs", ".swift", ".m", ".mm", ".dart", ".ex", ".exs",
  36. ".lua", ".sh", ".bash", ".zsh", ".sql", ".vue", ".svelte", ".r", ".jl", ".hs", ".clj", ".erl", ".pl",
  37. })
  38. _CODE_SCAN_SKIP_DIRS = frozenset({
  39. ".git", "node_modules", "venv", ".venv", "__pycache__", "dist", "build", "target", ".next", ".turbo", "vendor",
  40. })
  41. # Bounded sweep: a code workspace reveals itself in the first handful of entries.
  42. _CODE_SCAN_MAX_ENTRIES = 500
  43. # Lockfile → package manager, checked in priority order.
  44. _PY_LOCKFILES = (("uv.lock", "uv"), ("poetry.lock", "poetry"), ("Pipfile.lock", "pipenv"))
  45. _JS_LOCKFILES = (
  46. ("pnpm-lock.yaml", "pnpm"), ("bun.lockb", "bun"), ("bun.lock", "bun"), ("yarn.lock", "yarn"), ("package-lock.json", "npm"),
  47. )
  48. # package.json scripts / Makefile targets worth surfacing as verify commands.
  49. _VERIFY_TARGETS = ("test", "tests", "lint", "typecheck", "check", "build", "fmt", "format")
  50. _MAX_VERIFY_COMMANDS = 8
  51. _MAX_FACT_FILE_BYTES = 256 * 1024
  52. _GIT_TIMEOUT = 2.5
  53. # Per-model edit-format steering toward the `patch` mode each family was trained on (unknown
  54. # families get nothing). GPT/Codex get V4A for ALL edits incl. single-file: codex-rs ships
  55. # apply_patch as its ONLY editor. Anthropic and most open-weight coders were RL'd on str_replace
  56. # editors. Substrings match the model id; aligned with TOOL_USE_ENFORCEMENT_MODELS.
  57. _EDIT_FORMAT_GUIDANCE: dict[str, tuple[tuple[str, ...], str]] = {
  58. "patch": (
  59. ("gpt", "codex"),
  60. "- Edit format: author new files with `write_file`; for edits to "
  61. "existing code use `patch` with `mode='patch'` (V4A diff) — including "
  62. "single-file edits. It's the edit format you handle most reliably.",
  63. ),
  64. "replace": (
  65. ("claude", "sonnet", "opus", "haiku",
  66. "gemini", "gemma", "deepseek", "qwen", "kimi", "glm", "grok",
  67. "hermes", "llama", "mistral", "devstral", "minimax"),
  68. "- Edit format: author new files with `write_file`; for edits to "
  69. "existing code prefer `patch` in `mode='replace'` — match a unique "
  70. "snippet and swap it. Reach for `mode='patch'` (V4A) only when an edit "
  71. "genuinely spans several files at once.",
  72. ),
  73. }
  74. # Operating brief. Tool names referenced here are in the coding toolset and _HERMES_CORE_TOOLS.
  75. CODING_AGENT_GUIDANCE = (
  76. "You are a coding agent pairing with the user inside their codebase. "
  77. "Operate like a careful senior engineer.\n"
  78. "\n"
  79. "Gather context first:\n"
  80. "- Read the relevant files with `read_file` and locate code with "
  81. "`search_files` before changing anything. Trace a symbol to its definition "
  82. "and usages rather than guessing its shape.\n"
  83. "- Batch independent lookups: when several reads/searches don't depend on "
  84. "each other, issue them together in one turn instead of one at a time.\n"
  85. "- Never invent files, symbols, APIs, or imports. If you haven't seen it in "
  86. "the repo, go look. Don't assume a library is available — check the project "
  87. "manifest (pyproject.toml / package.json / Cargo.toml / go.mod) and how "
  88. "neighbouring files import it.\n"
  89. "\n"
  90. "Make changes through the tools, not the chat:\n"
  91. "- Edit with `patch`/`write_file`. Do NOT print code blocks to the user as "
  92. "a substitute for editing — apply the change, then summarise it. Only show "
  93. "code when the user explicitly asks to see it.\n"
  94. "- Match the project's existing style and conventions; AGENTS.md / "
  95. "CLAUDE.md / .cursorrules already in context win over your defaults. Touch "
  96. "only what the task needs — no drive-by refactors, renames, or reformatting "
  97. "— and add any imports/dependencies your code requires.\n"
  98. "- If an edit fails to apply, re-read the file to get the current exact "
  99. "contents before retrying — don't repeat a stale patch. If the same region "
  100. "fails twice, rewrite the enclosing function or file with `write_file` "
  101. "instead of attempting a third patch.\n"
  102. "\n"
  103. "Verify, and know when to stop:\n"
  104. "- Use `terminal` for git, builds, tests, and inspection. Run the relevant "
  105. "tests/linter/build and confirm they pass before claiming the work is done.\n"
  106. "- Terminal state persists across calls: current directory and exported "
  107. "environment variables carry forward. Activate a virtualenv or export setup "
  108. "vars once, then reuse that state instead of re-sourcing it before every "
  109. "test command.\n"
  110. "- Fix root causes, not symptoms: when you find a bug, check sibling call "
  111. "paths for the same flaw and fix the class, not just the reported site.\n"
  112. "- When fixing linter/type errors on a file, stop after about three "
  113. "attempts on the same file and ask the user rather than looping.\n"
  114. "- Track multi-step work with `todo_list`. Reference code as `path:line` instead "
  115. "of pasting whole files.\n"
  116. "\n"
  117. "Respect the user's repo: don't commit, push, or rewrite history unless "
  118. "asked, and never read, print, or commit secrets — leave `.env` and "
  119. "credential files alone unless the user explicitly asks. The Workspace "
  120. "block below is a snapshot from session start — re-run `git status`/"
  121. "`git branch` before relying on it. Be concise: lead with the change or "
  122. "answer, not a preamble."
  123. )
  124. _TODO_SENTENCE = (
  125. "- Track multi-step work with `todo_list`. Reference code as "
  126. "`path:line` instead of pasting whole files."
  127. )
  128. _NO_TODO_SENTENCE = "- Reference code as `path:line` instead of pasting whole files."
  129. # Clearly non-coding skill categories (deny-list; coding-adjacent and custom ones keep full entries).
  130. _NON_CODING_SKILL_CATEGORIES = (
  131. "apple", "communication", "cooking", "creative", "email", "finance", "gaming", "gifs", "health", "media",
  132. "music", "note-taking", "productivity", "shopping", "smart-home", "social-media", "travel", "yuanbao",
  133. )
  134. _MODE_ALIASES = {
  135. **dict.fromkeys(("focus", "strict", "lean"), "focus"),
  136. **dict.fromkeys(("on", "true", "yes", "1", "always"), "on"),
  137. **dict.fromkeys(("off", "false", "no", "0", "never"), "off"),
  138. }
  139. @dataclass(frozen=True)
  140. class ContextProfile:
  141. """A named operating posture (pure data). ``toolset``: collapse target under ``focus``
  142. (``None`` keeps the platform default). ``compact_skill_categories``: DEMOTED to
  143. names-only under ``focus`` — deny-list, never hidden, so recall keeps working."""
  144. name: str
  145. toolset: Optional[str] = None
  146. guidance: str = ""
  147. model_hint: Optional[str] = None
  148. compact_skill_categories: tuple[str, ...] = ()
  149. GENERAL_PROFILE = ContextProfile(name="general")
  150. CODING_PROFILE = ContextProfile(
  151. name="coding", toolset=CODING_TOOLSET, guidance=CODING_AGENT_GUIDANCE, model_hint="coding",
  152. compact_skill_categories=_NON_CODING_SKILL_CATEGORIES,
  153. )
  154. # ── Detection helpers ───────────────────────────────────────────────────────
  155. def _model_family(model: Optional[str]) -> Optional[str]:
  156. """Edit-format family key for a model id, or ``None`` (neutral wording applies)."""
  157. lowered = (model or "").lower()
  158. for family, (needles, _line) in _EDIT_FORMAT_GUIDANCE.items():
  159. if lowered and any(n in lowered for n in needles):
  160. return family
  161. return None
  162. def _agent_config_value(config: Optional[dict[str, Any]], key: str, default: Any, *, readonly: bool) -> Any:
  163. """``config["agent"][key]``, loading config when none was passed."""
  164. if config is None:
  165. try:
  166. from hermes_cli.config import load_config, load_config_readonly
  167. config = load_config_readonly() if readonly else load_config()
  168. except Exception:
  169. config = {}
  170. return ((config or {}).get("agent", {}) or {}).get(key, default)
  171. def _coding_mode(config: Optional[dict[str, Any]]) -> str:
  172. """Normalized ``agent.coding_context`` mode (auto/focus/on/off)."""
  173. raw = _agent_config_value(config, "coding_context", "auto", readonly=True)
  174. return _MODE_ALIASES.get(str(raw).strip().lower(), "auto")
  175. def _resolve_cwd(cwd: Optional[str | Path]) -> Path:
  176. if cwd:
  177. return Path(cwd).expanduser()
  178. try:
  179. from agent.runtime_cwd import resolve_agent_cwd
  180. return resolve_agent_cwd()
  181. except Exception:
  182. return Path(os.getcwd())
  183. def _git_root(cwd: Path) -> Optional[Path]:
  184. current = cwd.resolve()
  185. return next((p for p in (current, *current.parents) if (p / ".git").exists()), None)
  186. def _home() -> Optional[Path]:
  187. try:
  188. return Path.home().resolve()
  189. except (OSError, RuntimeError):
  190. return None
  191. def _marker_root(cwd: Path) -> Optional[Path]:
  192. """Nearest ancestor (≤6 levels) that looks like a project root, or ``None``. ``$HOME``
  193. and the shared temp root are skipped: a Makefile/AGENTS.md in the home dir is global
  194. config, and a stray manifest in /tmp must not flip every session under it."""
  195. current = cwd.resolve()
  196. try:
  197. temp_root = Path(tempfile.gettempdir()).resolve()
  198. except Exception:
  199. temp_root = None
  200. skip = (_home(), temp_root)
  201. for parent in (current, *current.parents)[:7]:
  202. if parent not in skip and any((parent / marker).exists() for marker in _PROJECT_MARKERS):
  203. return parent
  204. return None
  205. def _has_code_files(root: Path) -> bool:
  206. """Bounded check for source files in the root and its immediate subdirs."""
  207. seen = 0
  208. stack = [(root, True)]
  209. while stack:
  210. directory, is_root = stack.pop()
  211. try:
  212. entries = os.scandir(directory)
  213. except OSError:
  214. continue
  215. with entries:
  216. for entry in entries:
  217. seen += 1
  218. if seen > _CODE_SCAN_MAX_ENTRIES:
  219. return False
  220. try:
  221. if entry.is_file():
  222. if os.path.splitext(entry.name)[1].lower() in _CODE_EXTENSIONS:
  223. return True
  224. elif is_root and entry.is_dir() and entry.name not in _CODE_SCAN_SKIP_DIRS and not entry.name.startswith("."):
  225. stack.append((Path(entry.path), False))
  226. except OSError:
  227. continue
  228. return False
  229. def _detect_profile(mode: str, platform: str, cwd: Path) -> ContextProfile:
  230. """``auto``/``focus``: coding when the surface is interactive AND the cwd is a code
  231. workspace (project root, or a git repo that actually holds code; a repo rooted at
  232. ``$HOME`` is NOT a signal). ``on``/``off`` force. Not memoized: one gateway serves many cwds."""
  233. if mode == "off":
  234. return GENERAL_PROFILE
  235. if mode == "on":
  236. return CODING_PROFILE
  237. if platform and platform.strip().lower() not in INTERACTIVE_CODING_PLATFORMS:
  238. return GENERAL_PROFILE
  239. if _marker_root(cwd) is not None:
  240. return CODING_PROFILE
  241. git_root = _git_root(cwd)
  242. if git_root is not None and git_root != _home() and _has_code_files(git_root):
  243. return CODING_PROFILE
  244. return GENERAL_PROFILE
  245. def _enabled_mcp_servers(config: Optional[dict[str, Any]]) -> list[str]:
  246. """Names of MCP servers the user has enabled — kept in the coding posture. The profile default's
  247. resolver, so plugin-provided servers stay too; *config* None reads the user's config."""
  248. try:
  249. from hermes_cli.config import read_raw_config
  250. from hermes_cli.tools_config import enabled_mcp_server_names
  251. return sorted(enabled_mcp_server_names(read_raw_config() if config is None else config))
  252. except Exception:
  253. logger.debug("Could not list enabled MCP servers for the coding posture", exc_info=True)
  254. return []
  255. def _posture_toolsets(config: Optional[dict[str, Any]]) -> list[str]:
  256. """The coding posture's toolset list; callers own the ``focus`` check."""
  257. return [CODING_TOOLSET, *_enabled_mcp_servers(config)]
  258. def focus_toolsets(config: Optional[dict[str, Any]]) -> Optional[list[str]]:
  259. """The coding posture's toolsets when ``agent.coding_context`` is ``focus``, else None, for a
  260. session whose workspace decision is already made (no cwd probe)."""
  261. return _posture_toolsets(config) if _coding_mode(config) == "focus" else None
  262. # ── RuntimeMode (the seam) ──────────────────────────────────────────────────
  263. @dataclass(frozen=True)
  264. class RuntimeMode:
  265. """The resolved operating posture for a session; immutable, built once via
  266. :func:`resolve_runtime_mode` and never re-resolved mid-session (prompt cache).
  267. ``config_mode``: normalized ``agent.coding_context`` (toolset collapse gated on
  268. ``focus``); ``model``: steers edit-format guidance only; ``instructions``:
  269. ``agent.coding_instructions``."""
  270. profile: ContextProfile
  271. surface: str
  272. cwd: Path
  273. config_mode: str = "auto"
  274. model: Optional[str] = None
  275. instructions: str = ""
  276. @property
  277. def kind(self) -> str:
  278. return self.profile.name
  279. @property
  280. def is_coding(self) -> bool:
  281. return self.profile.name == CODING_PROFILE.name
  282. def toolset_selection(self, config: Optional[dict[str, Any]] = None) -> Optional[list[str]]:
  283. """Toolset list (only under ``focus``), or ``None`` to keep the platform default. Callers
  284. apply it only when the user hasn't pinned a selection (``--toolsets``, ``HERMES_TUI_TOOLSETS``).
  285. *config* None lists MCP servers from the user's config."""
  286. if self.config_mode != "focus" or self.profile.toolset is None:
  287. return None
  288. return _posture_toolsets(config) # the focus decision is this mode's own config_mode
  289. def system_prompt_parts(self, valid_tool_names=None, workspace_block: Optional[str] = None) -> tuple[list[str], list[str], list[str]]:
  290. """Return (prefix, workspace, trailing) posture blocks in the historical flat order —
  291. brief, snapshot, operator instructions — so prompt assembly can put a cache boundary
  292. before the snapshot without changing persisted bytes. The brief carries the model-family
  293. edit-format nudge (one cached string); ``valid_tool_names`` drops the ``todo_list``
  294. sentence when that tool isn't loaded; operator instructions ride their own block so
  295. the brief stays byte-stable. ``workspace_block`` replays a snapshot the caller already
  296. pinned at session start (``""`` = no workspace) instead of re-running the git probe;
  297. ``None`` probes."""
  298. if not self.is_coding:
  299. return [], [], []
  300. prefix: list[str] = []
  301. if self.profile.guidance:
  302. brief = self.profile.guidance
  303. if valid_tool_names is not None and "todo_list" not in valid_tool_names:
  304. brief = brief.replace(_TODO_SENTENCE, _NO_TODO_SENTENCE)
  305. family = _model_family(self.model)
  306. if family is not None:
  307. brief = f"{brief}\n{_EDIT_FORMAT_GUIDANCE[family][1]}"
  308. prefix.append(brief)
  309. workspace = build_coding_workspace_block(self.cwd) if workspace_block is None else workspace_block
  310. trailing = [f"Operator instructions (from config):\n{self.instructions}"] if self.instructions else []
  311. return prefix, [workspace] if workspace else [], trailing
  312. def system_blocks(self) -> list[str]:
  313. """Posture blocks as one flat list in historical order."""
  314. prefix, workspace, trailing = self.system_prompt_parts()
  315. return [*prefix, *workspace, *trailing]
  316. def compact_skill_categories(self) -> frozenset[str]:
  317. """Skill categories to demote to names-only in the skill index. Gated on ``focus``
  318. like the toolset collapse (index changes under ``auto`` proved too surprising).
  319. Demoted, never hidden: pruning caused silent capability loss."""
  320. if not self.is_coding or self.config_mode != "focus":
  321. return frozenset()
  322. return frozenset(self.profile.compact_skill_categories)
  323. def resolve_runtime_mode(
  324. *, platform: Optional[str] = None, cwd: Optional[str | Path] = None, config: Optional[dict[str, Any]] = None,
  325. model: Optional[str] = None,
  326. ) -> RuntimeMode:
  327. """Resolve the operating posture once (a handful of ``stat`` calls) — the single entry
  328. point every domain should call; the result is safe to hold for the session. ``model``
  329. only steers edit-format guidance; ``agent.coding_instructions`` (str or list) becomes
  330. the trailing block so a user can pin workflow rules without editing the shipped brief."""
  331. resolved_cwd = _resolve_cwd(cwd)
  332. mode = _coding_mode(config)
  333. raw = _agent_config_value(config, "coding_instructions", "", readonly=False)
  334. items = raw if isinstance(raw, (list, tuple)) else [raw or ""]
  335. instructions = "\n".join(str(item).strip() for item in items if str(item).strip())
  336. return RuntimeMode(
  337. profile=_detect_profile(mode, (platform or "").strip().lower(), resolved_cwd),
  338. surface=platform or "",
  339. cwd=resolved_cwd,
  340. config_mode=mode,
  341. model=model,
  342. instructions=instructions,
  343. )
  344. # ── Functional API (thin wrappers over RuntimeMode) ──────────────────────────
  345. def is_coding_context(*, platform: Optional[str] = None, cwd: Optional[str | Path] = None, config: Optional[dict[str, Any]] = None) -> bool:
  346. """Whether Hermes should operate in its coding posture right now."""
  347. return resolve_runtime_mode(platform=platform, cwd=cwd, config=config).is_coding
  348. def in_focus_workspace(*, platform: Optional[str] = None, cwd: Optional[str | Path] = None, config: Optional[dict[str, Any]] = None) -> bool:
  349. """Whether *cwd* selects the coding posture's toolsets (``focus`` and a code workspace), without
  350. building them; ``focus_toolsets`` builds them once the decision is made."""
  351. return _coding_mode(config) == "focus" and is_coding_context(platform=platform, cwd=cwd, config=config)
  352. def coding_selection(*, platform: Optional[str] = None, cwd: Optional[str | Path] = None, config: Optional[dict[str, Any]] = None) -> Optional[list[str]]:
  353. """Toolset selection for the coding posture (``None`` unless ``focus`` and active)."""
  354. if _coding_mode(config) != "focus": # only focus swaps toolsets: skip the workspace probe
  355. return None
  356. return resolve_runtime_mode(platform=platform, cwd=cwd, config=config).toolset_selection(config)
  357. def coding_system_prompt_parts(
  358. *, platform: Optional[str] = None, cwd: Optional[str | Path] = None, config: Optional[dict[str, Any]] = None,
  359. model: Optional[str] = None, valid_tool_names=None, workspace_block: Optional[str] = None,
  360. ) -> tuple[list[str], list[str], list[str]]:
  361. """Return coding prefix, workspace snapshot, and trailing guidance. ``workspace_block``
  362. replays the caller's pinned session-start snapshot instead of probing git again."""
  363. mode = resolve_runtime_mode(platform=platform, cwd=cwd, config=config, model=model)
  364. return mode.system_prompt_parts(valid_tool_names=valid_tool_names, workspace_block=workspace_block)
  365. def coding_compact_skill_categories(*, platform: Optional[str] = None, cwd: Optional[str | Path] = None, config: Optional[dict[str, Any]] = None) -> frozenset[str]:
  366. """Skill categories the active posture demotes to names-only (empty outside ``focus``)."""
  367. return resolve_runtime_mode(platform=platform, cwd=cwd, config=config).compact_skill_categories()
  368. # ── git/workspace probe ─────────────────────────────────────────────────────
  369. def _git(cwd: Path, *args: str) -> str:
  370. """``git -C <cwd> <args>`` → stripped stdout, or ``""`` on any failure. bounded_git_probe
  371. bounds post-kill cleanup on Windows — plain ``subprocess.run(timeout=...)`` deadlocked
  372. when a killed git left a suspended descendant holding the pipe handles.
  373. See #66037.
  374. """
  375. return bounded_git_probe(["git", "-C", str(cwd), *args], timeout=_GIT_TIMEOUT)
  376. def _parse_status(porcelain: str) -> tuple[dict[str, str], dict[str, int]]:
  377. """Parse ``git status --porcelain=2 --branch`` into branch + counts."""
  378. branch: dict[str, str] = {}
  379. counts = {"staged": 0, "modified": 0, "untracked": 0, "conflicts": 0}
  380. for line in porcelain.splitlines():
  381. if line.startswith(("# branch.head", "# branch.upstream")):
  382. parts = line.split(maxsplit=2)
  383. branch[parts[1].removeprefix("branch.")] = parts[-1]
  384. elif line.startswith("# branch.ab"):
  385. parts = line.split()
  386. branch["ahead"], branch["behind"] = parts[2].lstrip("+"), parts[3].lstrip("-")
  387. elif line.startswith(("1 ", "2 ")):
  388. xy = line.split(maxsplit=2)[1]
  389. counts["staged"] += xy[0] != "."
  390. counts["modified"] += xy[1] != "."
  391. elif line.startswith(("u ", "? ")):
  392. counts["conflicts" if line[0] == "u" else "untracked"] += 1
  393. return branch, counts
  394. def _read_small(path: Path) -> str:
  395. """Read a small text file, or ``""`` — never raises, never reads huge files."""
  396. try:
  397. if not path.is_file() or path.stat().st_size > _MAX_FACT_FILE_BYTES:
  398. return ""
  399. return path.read_text(encoding="utf-8-sig", errors="replace")
  400. except OSError:
  401. return ""
  402. @dataclass(frozen=True)
  403. class ProjectFacts:
  404. """Structured project facts — exposed so non-prompt consumers (desktop verify UI) don't re-detect."""
  405. manifests: list[str]
  406. package_managers: list[str]
  407. verify_commands: list[str]
  408. context_files: list[str]
  409. def detect_project_facts(root: Path) -> ProjectFacts:
  410. """Detect manifests, package manager(s), verify commands, context files (single source of truth)."""
  411. verify: list[str] = []
  412. if (root / "scripts" / "run_tests.sh").is_file():
  413. verify.append("scripts/run_tests.sh")
  414. if (root / "package.json").is_file():
  415. try:
  416. scripts = json.loads(_read_small(root / "package.json") or "{}").get("scripts") or {}
  417. except (json.JSONDecodeError, AttributeError):
  418. scripts = {}
  419. js_pm = next((pm for lock, pm in _JS_LOCKFILES if (root / lock).is_file()), "npm")
  420. verify.extend(f"{js_pm} run {name}" for name in _VERIFY_TARGETS if name in scripts)
  421. if (root / "pytest.ini").is_file() or "[tool.pytest" in _read_small(root / "pyproject.toml"):
  422. verify.append("pytest")
  423. makefile = _read_small(root / "Makefile")
  424. verify.extend(
  425. f"make {name}" for name in _VERIFY_TARGETS
  426. if makefile and re.search(rf"^{re.escape(name)}\s*:", makefile, re.MULTILINE)
  427. )
  428. return ProjectFacts(
  429. manifests=[m for m in _PROJECT_MARKERS if m not in _CONTEXT_FILES and (root / m).is_file()],
  430. package_managers=list(dict.fromkeys(
  431. pm for lock, pm in (*_PY_LOCKFILES, *_JS_LOCKFILES) if (root / lock).is_file()
  432. )),
  433. verify_commands=list(dict.fromkeys(verify))[:_MAX_VERIFY_COMMANDS],
  434. context_files=[c for c in _CONTEXT_FILES if (root / c).is_file()],
  435. )
  436. def _workspace_roots(cwd: Optional[str | Path]) -> tuple[Optional[Path], Optional[Path]]:
  437. """(git_root, workspace_root) for *cwd*; workspace root is git root else marker root."""
  438. resolved = _resolve_cwd(cwd)
  439. git_root = _git_root(resolved)
  440. return git_root, git_root or _marker_root(resolved)
  441. def project_facts_for(cwd: Optional[str | Path] = None) -> Optional[dict[str, Any]]:
  442. """Structured project facts for ``cwd`` (desktop verify UI) — ``None`` outside a workspace."""
  443. _, root = _workspace_roots(cwd)
  444. if root is None:
  445. return None
  446. f = detect_project_facts(root)
  447. return {
  448. "root": str(root),
  449. "manifests": f.manifests,
  450. "packageManagers": f.package_managers,
  451. "verifyCommands": f.verify_commands,
  452. "contextFiles": f.context_files,
  453. }
  454. WORKSPACE_BLOCK_HEADER = "Workspace (snapshot at session start — re-check with `git` before acting on it):"
  455. def build_coding_workspace_block(cwd: Optional[str | Path] = None) -> str:
  456. """Workspace snapshot for the system prompt (empty outside a workspace): git state when
  457. in a repo, plus project facts — so marker-only (non-git) projects still get one."""
  458. git_root, root = _workspace_roots(cwd)
  459. if root is None:
  460. return ""
  461. lines = [
  462. WORKSPACE_BLOCK_HEADER,
  463. f"- Root: {root}",
  464. ]
  465. if git_root is not None:
  466. # ``status`` hashes re-timestamped files through the repo-named clean filter; skip it when
  467. # the filter overrides cannot be discovered rather than run it half-hardened.
  468. from hermes_cli._subprocess_compat import noninteractive_repo_git_env
  469. status_env = noninteractive_repo_git_env(root)
  470. status = "" if status_env is None else bounded_git_probe(
  471. ["git", "-C", str(root), "status", "--porcelain=2", "--branch"], timeout=_GIT_TIMEOUT, env=status_env)
  472. branch, counts = _parse_status(status)
  473. head = branch.get("head", "")
  474. if head == "(detached)":
  475. lines.append("- Branch: (detached HEAD)")
  476. elif head:
  477. ahead, behind = branch.get("ahead", "0"), branch.get("behind", "0")
  478. upstream = f" \u2192 {branch['upstream']}" if branch.get("upstream") else ""
  479. ab = f" (ahead {ahead}, behind {behind})" if upstream and (ahead, behind) != ("0", "0") else ""
  480. lines.append(f"- Branch: {head}{upstream}{ab}")
  481. # Linked worktree: say so (branches/stashes are shared state) but do NOT expose
  482. # the primary tree path — a second absolute path makes the model run commands
  483. # in the wrong directory. Derived from the session's own cwd, so every surface
  484. # opened in a worktree (``hermes -w``, Ink, Desktop, ACP) gets the same guidance.
  485. git_dir, common_dir = _git(root, "rev-parse", "--git-dir"), _git(root, "rev-parse", "--git-common-dir")
  486. if git_dir and common_dir and Path(git_dir).resolve() != Path(common_dir).resolve():
  487. on_branch = f" on branch {head}" if head and head != "(detached)" else ""
  488. lines.append(
  489. f"- Worktree: linked, isolated{on_branch} (git state shared with primary tree). Changes here do"
  490. " not affect the main working tree or other agents; commit and push your changes, and open a"
  491. " PR if appropriate.")
  492. dirty = [f"{n} {label}" for label, n in counts.items() if n]
  493. lines.append(f"- Status: {', '.join(dirty) if dirty else 'clean'}")
  494. recent = _git(root, "log", "-3", "--pretty=%h %s")
  495. if recent:
  496. lines.extend(["- Recent commits:", *(f" {c}" for c in recent.splitlines())])
  497. f = detect_project_facts(root)
  498. if f.manifests:
  499. managers = f" ({'/'.join(f.package_managers)})" if f.package_managers else ""
  500. lines.append(f"- Project: {', '.join(f.manifests[:6])}{managers}")
  501. if f.verify_commands:
  502. lines.append(f"- Verify: {'; '.join(f.verify_commands)}")
  503. if f.context_files:
  504. lines.append(f"- Context files: {', '.join(f.context_files)}")
  505. return "\n".join(lines)