Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(agents): wire Hermes as a sixth agent target (#1460)

Raghav Chamadiya845dea05fd60
diff --git a/README.md b/README.md
index d7e23e9d1..c3a50585d 100644
--- a/README.md
+++ b/README.md
@@ -368,7 +368,7 @@ Set Up This Repository**. Guide: **[docs/agent/VSCODE.md →](docs/agent/VSCODE.
## Supported agents
-**Five agents wired end to end · two at the Full tier · every other MCP host one
+**Six agents wired end to end · two at the Full tier · every other MCP host one
paste away.**
<p>
@@ -381,6 +381,7 @@ paste away.**
<img src="https://img.shields.io/badge/VS_Code-007ACC?style=flat-square&logo=visualstudiocode&logoColor=white" alt="VS Code" />
<img src="https://img.shields.io/badge/Cursor-000000?style=flat-square&logo=cursor&logoColor=white" alt="Cursor" />
<img src="https://img.shields.io/badge/OpenCode-000000?style=flat-square&logo=opencode&logoColor=white" alt="OpenCode" />
+ <img src="https://img.shields.io/badge/Hermes-000000?style=flat-square&logoColor=white" alt="Hermes" />
</p>
**Full** is every surface repowise has: MCP tools, skills, slash commands, a managed
diff --git a/docs/agent/CODEX.md b/docs/agent/CODEX.md
index f8a5fd07d..fe897f037 100644
--- a/docs/agent/CODEX.md
+++ b/docs/agent/CODEX.md
@@ -128,7 +128,7 @@ Note this is the mirror image of Claude Code, where the commands come from the p
`repowise init --codex` generates a managed `AGENTS.md` by default. `repowise update` refreshes it when `editor_files.agents_md` is enabled, or when `--agents` is passed. The Repowise section is bounded by managed markers and user content outside the markers is preserved.
-`AGENTS.md` is a host-neutral convention rather than a Codex-only file: [OpenCode](OPENCODE.md) reads the same path and manages the same section. Both writing it is safe, because the section is idempotent. Removing one of the two agents while the other is still wired leaves the section in place and reports that it did, so the agent still using it does not silently lose its instructions.
+`AGENTS.md` is a host-neutral convention rather than a Codex-only file: [OpenCode](OPENCODE.md) and [Hermes](HERMES.md) read the same path and manage the same section. All of them writing it is safe, because the section is idempotent. Removing one agent while another is still wired leaves the section in place and reports that it did, so the agent still using it does not silently lose its instructions.
Controls:
diff --git a/docs/agent/HERMES.md b/docs/agent/HERMES.md
new file mode 100644
index 000000000..9d8ae6788
--- /dev/null
+++ b/docs/agent/HERMES.md
@@ -0,0 +1,104 @@
+# Hermes Integration
+
+[Hermes](https://hermes-agent.nousresearch.com) is an MCP host, so it can read a
+repowise index directly. This page covers wiring it up and the two host details
+that decide whether it works.
+
+## Setup
+
+```bash
+repowise agents add --target=hermes # this repo and this machine
+repowise agents add --target=hermes --scope=user # the MCP server only
+repowise agents add --target=hermes --scope=project # the AGENTS.md section only
+```
+
+Hermes is at the **Good** tier: it gets the MCP tools and the config to reach
+them, but no hook-level interception and no transcript mining. See the
+[support matrix](INTEGRATIONS.md) for what that means in full.
+
+Remove it with `repowise agents remove --target=hermes`, and check it with
+`repowise agents` or `repowise doctor`.
+
+## What each scope writes
+
+Hermes reads exactly one config file per machine, and there is no project-level
+equivalent. So the two scopes write different things:
+
+| Scope | File | What it does |
+|---|---|---|
+| `user` | `config.yaml` in the Hermes home | Registers the MCP server under `mcp_servers.repowise`. Serves every repo. |
+| `project` | `AGENTS.md` at the repo root | The managed instructions section, which Hermes loads per repo. |
+
+The Hermes home is `$HERMES_HOME` when that is set, otherwise
+`%LOCALAPPDATA%\hermes` on Windows and `~/.hermes` everywhere else. **Windows
+does not use `~/.hermes`**, and an entry written there is not broken so much as
+invisible, which is the harder problem to notice.
+
+Because the registration is per machine rather than per repo, the entry passes no
+repo path and lets the server resolve whichever repo Hermes was launched in. It
+pins the absolute path of the repowise install that wrote it, so a later install
+earlier on `PATH` cannot quietly take over.
+
+## `platform_toolsets.cli` is deliberately left alone
+
+This is the part most likely to look like a missing feature, so it is worth
+stating plainly.
+
+Hermes decides which MCP servers a platform sees with one rule: **if that
+platform's toolset list already names one or more MCP servers, the list is an
+allowlist and only those servers are exposed. Otherwise every enabled MCP server
+is exposed.** A config with no `platform_toolsets` at all, or with a plain
+`cli: [hermes-cli]`, takes the permissive branch.
+
+So on an ordinary config repowise is reachable the moment it is in
+`mcp_servers`, and adding `repowise` to that list would flip the config onto the
+allowlist branch with exactly one entry, silently cutting off every other MCP
+server the user had. Writing the key would not be redundant, it would be a
+regression.
+
+Repowise therefore adds itself to `platform_toolsets.cli` **only when that list
+is already an allowlist**, which is the one case where leaving it out would get
+repowise filtered back out. If the list contains the `no_mcp` sentinel, repowise
+writes the server entry, changes nothing else, and tells you the entry will stay
+inert until you remove the sentinel.
+
+## Editing YAML without eating your config
+
+`config.yaml` is commonly seeded from Hermes's heavily annotated example, so
+repowise edits it in place rather than parsing and rewriting it. Comments, key
+order, formatting, and any anchors or merge keys outside the one entry repowise
+owns are returned untouched, and the file's existing line endings are preserved.
+
+Every edit is checked before it lands: repowise re-parses what it is about to
+write and compares it against the config it intended. If the two differ for any
+reason, whether an unusual layout, a flow-style mapping or a duplicate key,
+nothing is written and the file is left exactly as it was. If the file cannot be parsed at
+all, repowise says so and prints the entry for you to paste:
+
+```bash
+repowise agents print-config hermes
+```
+
+Re-running `repowise agents add` reports `unchanged` rather than rewriting, and
+`repowise agents remove` returns the file to what it was before.
+
+## `AGENTS.md` is shared with Codex and OpenCode
+
+All three agents read the same file and manage the same marker-delimited section
+of it. All of them writing it is safe, because the section is idempotent.
+Removing one of them while another is still wired leaves the section in place and
+says so, rather than silently taking the instructions away from an agent that is
+still configured.
+
+Hermes loads exactly one project context file, preferring `.hermes.md` or
+`HERMES.md` over `AGENTS.md`. Repowise deliberately writes `AGENTS.md` and not
+the host-named file: creating a `HERMES.md` in a repo that already has an
+`AGENTS.md` would take precedence over it and suppress the repo's existing
+instructions entirely.
+
+## Official Hermes Docs
+
+- [Hermes Agent](https://hermes-agent.nousresearch.com)
+- [MCP](https://hermes-agent.nousresearch.com/docs/user-guide/features/mcp)
+- [MCP config reference](https://hermes-agent.nousresearch.com/docs/reference/mcp-config-reference)
+- [Configuration](https://hermes-agent.nousresearch.com/docs/user-guide/configuration)
diff --git a/docs/agent/INTEGRATIONS.md b/docs/agent/INTEGRATIONS.md
index 7fcf67be1..17db61e82 100644
--- a/docs/agent/INTEGRATIONS.md
+++ b/docs/agent/INTEGRATIONS.md
@@ -30,12 +30,13 @@ for that agent.
| [VS Code](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) | Good | Yes | No | No | No | No | No |
| [Cursor](https://cursor.com/docs/context/mcp) | Good | Yes | No | No | No | Yes | No |
| [OpenCode](https://opencode.ai/docs/mcp-servers/) | Good | Yes | No | No | No | Yes | No |
+| [Hermes](https://hermes-agent.nousresearch.com/docs/user-guide/features/mcp) | Good | Yes | No | No | No | Yes | No |
-Target ids for `--target=`: `claude-code`, `codex`, `vscode`, `cursor`, `opencode`.
+Target ids for `--target=`: `claude-code`, `codex`, `vscode`, `cursor`, `opencode`, `hermes`.
### What Good tier does not include
-VS Code, Cursor and OpenCode sit at Good, and the honest version of that is worth stating
+VS Code, Cursor, OpenCode and Hermes sit at Good, and the honest version of that is worth stating
plainly. These agents get the MCP tools and the config repowise writes.
They do **not** get hook-level interception: repowise never sees a tool
call before it runs, never rewrites a noisy command, and never annotates
@@ -60,8 +61,9 @@ snippet by hand. The shapes genuinely differ, and not only in their wrapper:
hosts disagree about the top-level key, about whether each entry carries a
`type` field, about whether the invocation is one array or a command plus a
separate argument list, and about the file format itself, so `codex` prints
-TOML where the others print JSON. `claude-code` is the plain `mcpServers` JSON
-most hosts read and is the right default when yours is not listed below.
+TOML and `hermes` prints YAML where the others print JSON. `claude-code` is
+the plain `mcpServers` JSON most hosts read and is the right default when
+yours is not listed below.
Hosts people ask about most, none of which repowise writes config for today:
Cline, Windsurf, Zed, Continue, Gemini CLI, JetBrains AI Assistant, Amp.
diff --git a/docs/agent/OPENCODE.md b/docs/agent/OPENCODE.md
index 13774ca80..d9c515333 100644
--- a/docs/agent/OPENCODE.md
+++ b/docs/agent/OPENCODE.md
@@ -34,9 +34,9 @@ Two things worth knowing:
not rewrite a config it cannot parse as strict JSON. If yours has comments,
`repowise agents add` leaves it alone and tells you to run
`repowise agents print-config opencode` and paste the entry yourself.
-- **`AGENTS.md` is shared with Codex.** Both agents read the same file, and both
- manage the same marker-delimited section of it. Removing one of them leaves the
- section in place while the other is still wired, and says so.
+- **`AGENTS.md` is shared with Codex and Hermes.** All three agents read the same
+ file, and all three manage the same marker-delimited section of it. Removing one
+ of them leaves the section in place while another is still wired, and says so.
Remove it with `repowise agents remove --target=opencode`, and check it with
`repowise agents` or `repowise doctor`.
diff --git a/docs/start/QUICKSTART.md b/docs/start/QUICKSTART.md
index 125a5989d..61865e6db 100644
--- a/docs/start/QUICKSTART.md
+++ b/docs/start/QUICKSTART.md
@@ -156,6 +156,29 @@ parse as strict JSON, so if yours has comments it prints the entry to paste inst
[Agent integrations](../agent/INTEGRATIONS.md).
</details>
+<details><summary><b>Hermes</b></summary>
+
+```bash
+repowise agents add --target=hermes # this repo and this machine
+repowise agents add --target=hermes --scope=user # the MCP server only
+```
+
+Hermes reads one `config.yaml` per machine, so the MCP server is registered there
+and serves every repo: `%LOCALAPPDATA%\hermes\config.yaml` on Windows,
+`~/.hermes/config.yaml` elsewhere, or `$HERMES_HOME/config.yaml` when that is set.
+Project scope writes a managed section in `AGENTS.md`, which Hermes loads per repo.
+
+Repowise edits that config in place rather than rewriting it, so your comments, key
+order and any anchors survive. If it cannot parse the file it leaves it alone and
+prints the entry to paste instead: `repowise agents print-config hermes`.
+
+`platform_toolsets.cli` is deliberately left alone. Hermes exposes every enabled MCP
+server to the CLI by default, and that list only becomes an allowlist once it already
+names one. So repowise adds itself there **only** when the list is already an
+allowlist, and never converts a permissive config into a restrictive one. See
+[Hermes](../agent/HERMES.md).
+</details>
+
<details><summary><b>Cline, Windsurf, and other MCP clients</b></summary>
Print the server entry and paste it into whatever config the host reads:
diff --git a/packages/cli/src/repowise/cli/agent_targets/formats/__init__.py b/packages/cli/src/repowise/cli/agent_targets/formats/__init__.py
index 11fbbd816..92c9f3442 100644
--- a/packages/cli/src/repowise/cli/agent_targets/formats/__init__.py
+++ b/packages/cli/src/repowise/cli/agent_targets/formats/__init__.py
@@ -1,8 +1,14 @@
"""Composable config-format helpers targets build on.
Kept deliberately small and free of per-agent knowledge. The targets differ
-enough — JSON versus TOML versus marker-delimited markdown, and different
-idempotency markers within each — that a shared base class would force an
-awkward shape on all of them; composition lets each take only the mechanics it
-needs.
+enough (JSON versus TOML versus YAML versus marker-delimited markdown, and
+different idempotency markers within each) that a shared base class would
+force an awkward shape on all of them; composition lets each take only the
+mechanics it needs.
+
+The two structured-config writers here, :mod:`toml_merge` and
+:mod:`yaml_merge`, are narrow on purpose and in the same way: each edits the
+source text in place rather than parsing and reserializing, so the user's
+comments, key order and formatting survive everywhere outside the one key
+repowise owns. Neither is a general serializer and neither should become one.
"""
diff --git a/packages/cli/src/repowise/cli/agent_targets/formats/yaml_merge.py b/packages/cli/src/repowise/cli/agent_targets/formats/yaml_merge.py
new file mode 100644
index 000000000..f80bb95a2
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/formats/yaml_merge.py
@@ -0,0 +1,667 @@
+"""A deliberately narrow YAML writer, scoped to one nested key at a time.
+
+The same shape as :mod:`toml_merge` and for the same reason: the edit is
+surgery on the *source text*, not a parse-and-reserialize, so the user's
+comments, key order and formatting survive everywhere outside the one key we
+own. Only the value being written is rendered fresh.
+
+**Why not round-trip the whole document.** ``yaml.safe_load`` followed by
+``yaml.safe_dump`` is four lines and it is wrong here in three separate ways,
+the last of which is not recoverable:
+
+* It deletes every comment in the file. These configs are commonly seeded from
+ a heavily annotated example, and the annotations are most of the file.
+* It reformats everything: quoting style, flow versus block, long scalars
+ folded at a different column. A one-key change becomes a whole-file diff.
+* **It expands anchors and merge keys.** ``safe_load`` resolves ``&defaults``
+ / ``*defaults`` / ``<<:`` into the values they stand for, and ``safe_dump``
+ then writes those values out in full. A config factored with anchors comes
+ back structurally different and much larger, and the factoring is gone for
+ good. Nothing about that failure is visible in a diff of the parsed data,
+ which is what makes it worse than the other two.
+
+**Why not decline the way the JSONC path does.** ``vscode``, ``cursor`` and
+``opencode`` refuse to rewrite their config when it will not parse, because
+comments make it unparseable and there is nothing to be done about that
+without a comment-preserving parser. YAML has no such problem: comments are
+part of the grammar, so a commented file parses cleanly and we can read it
+exactly. Declining here would be refusing work we are able to do correctly.
+
+**Why the surgery is safe despite being line-based.** It is not trusted. The
+caller computes the document it *means* to end up with, from the parsed
+original, and :func:`verify` re-parses the spliced text and compares. A shape
+this module's line matching gets wrong -- a flow mapping, a duplicate top-level
+key, an unusual indent -- lands the edit somewhere that changes the document,
+and the write is refused with the file untouched. So a mis-fired splice fails
+closed. That is a stronger guarantee than enumerating the shapes in advance,
+because the enumeration is the part that would be wrong.
+
+The guarantee is about *meaning*, and it stops there. Comments and blank lines
+do not survive into the parse, so nothing checks them mechanically; they are
+preserved because the edit is confined to one key's own lines, and the tests
+that cover them assert on the text. Inputs that cannot be parsed at all --
+tabs, several documents in one file -- are refused before any of this, by
+:func:`load_mapping`.
+
+Two primitives are enough for every edit a target needs: :func:`set_child` and
+:func:`remove_child`. Adding an item to a nested list is ``set_child`` with the
+new list, so there is no third code path for it.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+from typing import Any
+
+from ..types import FileAction
+from .json_merge import atomic_write_text, json_deep_equal
+
+#: Indent used for a child under a parent whose block is empty, so there is no
+#: sibling to copy. Two spaces is what PyYAML's dumper emits by default, which
+#: is what these hosts write their own configs with.
+DEFAULT_INDENT = 2
+
+
+def detect_newline(text: str) -> str:
+ """The line ending *text* is written with, for writing it back the same way.
+
+ Every function in this module works in ``\\n`` internally, so a caller
+ normalises on the way in and passes this back to :func:`write_if_changed`
+ on the way out. Skipping that step is a whole-file diff rather than a
+ cosmetic one: the platform translation an ordinary config write uses would
+ rewrite every line of a user's LF config to CRLF on Windows, on an edit
+ that touched three lines. The whole point of splicing rather than
+ reserializing is that untouched lines stay untouched, and the line endings
+ are part of that.
+
+ A mixed file resolves to CRLF and is normalised, which is the one case this
+ does not round-trip. Picking the majority style instead would leave the
+ minority lines alone and produce a file that is still mixed, which is not a
+ better answer for anyone.
+ """
+ return "\r\n" if "\r\n" in text else "\n"
+
+
+def load_mapping(text: str) -> dict:
+ """Parse *text* as a YAML mapping.
+
+ Raises ``ValueError`` for anything that is not one, so a caller can catch
+ it beside the other reasons a config is unusable. ``yaml.YAMLError`` is not
+ a ``ValueError``, and letting it through would escape every handler in the
+ targets, which all catch ``(OSError, ValueError)``.
+
+ An empty file is an empty mapping rather than an error: YAML parses it to
+ ``None``, and a config file that exists and says nothing is a perfectly
+ ordinary thing to find.
+ """
+ import yaml
+
+ try:
+ data = yaml.safe_load(text)
+ except yaml.YAMLError as exc:
+ raise ValueError(f"not valid YAML ({exc.__class__.__name__})") from exc
+ if data is None:
+ return {}
+ if not isinstance(data, dict):
+ raise ValueError("top level must be a YAML mapping")
+ return data
+
+
+def render_child(key: str, value: Any, indent: int, *, flow: bool = False) -> list[str]:
+ """Render ``key: value`` as block YAML, indented by *indent* spaces.
+
+ The dumper does the serializing rather than a hand-written encoder. That is
+ the one place this module differs from :mod:`toml_merge`, and deliberately:
+ the narrow TOML encoder had to grow inline tables and floats the moment it
+ met a real config, because rewriting a whole entry means re-rendering
+ everything the user put in it. A server entry here can legally hold a
+ nested ``env`` mapping, an ``args`` list, a ``tools.include`` list and
+ arbitrary scalars, and the dumper already handles all of it correctly.
+
+ ``width`` is set past any real line length on purpose. The default folds
+ long scalars at around 80 columns, and it folds on spaces -- so an absolute
+ repo path containing a space would be wrapped across two lines. It still
+ parses back to the same string, but it is unreadable in a config file and
+ it makes the rendering depend on how long the user's path happens to be.
+
+ *flow* renders ``key: [a, b]`` instead of a block sequence. Callers pass
+ what the key was already written as, so editing one item of a user's inline
+ list gives back an inline list rather than silently restyling the line.
+ Block is the default because it is what the dumper and these hosts emit.
+
+ The flow branch dumps the **value** alone rather than passing
+ ``default_flow_style=True`` for the whole pair. That flag applies to the
+ enclosing mapping too, so the pair comes back as ``{key: [a, b]}`` -- still
+ valid YAML and still the right document, which is why nothing downstream
+ catches it, but the key is then inside a flow mapping where no line-based
+ search will find it again. The next edit appends a second copy instead of
+ replacing it.
+ """
+ import yaml
+
+ pad = " " * indent
+ if flow and isinstance(value, (list, dict)):
+ inline = yaml.safe_dump(
+ value,
+ default_flow_style=True,
+ sort_keys=False,
+ allow_unicode=True,
+ width=1_000_000,
+ ).strip()
+ return [f"{pad}{key}: {inline}"]
+
+ dumped = yaml.safe_dump(
+ {key: value},
+ default_flow_style=False,
+ sort_keys=False,
+ allow_unicode=True,
+ width=1_000_000,
+ )
+ return [pad + line if line else line for line in dumped.rstrip("\n").split("\n")]
+
+
+def _is_top_level_key(line: str) -> bool:
+ """Whether *line* starts a new top-level node, ending the block above it.
+
+ Blank lines and comments do not, because both appear freely inside a block
+ and neither closes it. Everything else at column zero does, including a
+ document separator, which is exactly right: this module must never edit
+ across one.
+ """
+ if not line.strip():
+ return False
+ return not line.startswith((" ", "\t", "#"))
+
+
+def _key_pattern(key: str, indent: str) -> re.Pattern[str]:
+ """Match *key* at *indent*, bare or in either quote.
+
+ Quoting a mapping key is ordinary YAML. Teaching only one of the two
+ searches about it is worse than teaching neither: the child search learned
+ the quoted spellings first, and the parent search left behind then sent a
+ ``"mcp_servers":`` config down the append path, where the second block it
+ added was a duplicate key and the write refused for good.
+ """
+ name = re.escape(key)
+ return re.compile(
+ rf'^{re.escape(indent)}(?:{name}|"{name}"|\'{name}\'):(?=\s|$)'
+ )
+
+
+def _find_top_level(lines: list[str], key: str) -> tuple[int, int] | None:
+ """Line range ``[start, end)`` of top-level *key*, or ``None`` when absent.
+
+ ``start`` is the ``key:`` line itself. Anchored at column zero, so a key of
+ the same name nested inside another mapping, or sitting inside a commented
+ example block, is not mistaken for this one.
+ """
+ pattern = _key_pattern(key, "")
+ for index, line in enumerate(lines):
+ if pattern.match(line):
+ end = index + 1
+ while end < len(lines) and not _is_top_level_key(lines[end]):
+ end += 1
+ return index, end
+ return None
+
+
+def _child_indent(lines: list[str], start: int, end: int) -> int:
+ """Indent the children of the block at *start* are written at."""
+ for index in range(start + 1, end):
+ line = lines[index]
+ if not line.strip() or line.lstrip().startswith("#"):
+ continue
+ return len(line) - len(line.lstrip())
+ return DEFAULT_INDENT
+
+
+def _find_child(lines: list[str], start: int, end: int, child: str, indent: int) -> tuple[int, int] | None:
+ """Line range ``[start, end)`` of *child* inside its parent's block.
+
+ All three spellings of the key are matched, bare and either quote. Quoting a
+ mapping key is ordinary YAML and it is what a user pasting an entry by hand
+ tends to produce, and matching only the bare form was worse than it looks in
+ both directions: the write appended a *second* entry beside the quoted one,
+ leaving a duplicate key that the parser silently resolves to the last, and
+ the removal then found neither and declined for good.
+
+ The replacement is written bare, which changes the quoting of the one key
+ repowise owns and nothing else.
+ """
+ pattern = _key_pattern(child, " " * indent)
+ for index in range(start + 1, end):
+ if pattern.match(lines[index]):
+ return index, _child_end(lines, index, end, indent)
+ return None
+
+
+def _child_end(lines: list[str], child_start: int, end: int, indent: int) -> int:
+ """Where the block belonging to the child at *child_start* stops.
+
+ Two rules beyond "a line indented further belongs to the child":
+
+ * **A ``- `` item at the child's own indent belongs to the child.** That is
+ not an exotic hand-written style, it is what PyYAML emits for a block
+ sequence with ``default_flow_style=False``, so it is the shape these
+ hosts write their own lists in. Reading it as the next sibling truncates
+ the block after its first line, and an edit then lands above items that
+ are still there.
+ * **Trailing blank and comment lines are given back.** A comment sitting
+ between two keys documents the one below it, so swallowing it into the
+ block above would move or delete the user's comment when that block is
+ replaced.
+ """
+ cursor = child_start + 1
+ while cursor < end:
+ line = lines[cursor]
+ if line.strip() and not line.lstrip().startswith("#"):
+ line_indent = len(line) - len(line.lstrip())
+ is_own_list_item = line_indent == indent and line.lstrip().startswith("- ")
+ if line_indent <= indent and not is_own_list_item:
+ break
+ cursor += 1
+ while cursor > child_start + 1 and (
+ not lines[cursor - 1].strip() or lines[cursor - 1].lstrip().startswith("#")
+ ):
+ cursor -= 1
+ return cursor
+
+
+def _trailing_comment(line: str) -> str:
+ """A comment sitting on the key's own line, or ``""``.
+
+ Replacing a child replaces the whole of its first line, and that line can
+ carry a comment describing the value being replaced -- ``cli: [a, b] # an
+ allowlist`` is exactly the shape this module meets. Losing it would be the
+ one place a module built to preserve comments silently ate one.
+
+ **The parser decides where the value ends, not a scanner here.** Three
+ hand-written rules were tried and each was wrong in its own direction: one
+ keyed on quoting copied a fragment of an inline value out into a comment,
+ one searching back from the last bracket deleted any comment that mentioned
+ a brace, and one tracking quotes and bracket depth left to right desynced on
+ an apostrophe in a plain scalar (``note: don't``) and did both. Knowing
+ where a YAML value stops means implementing YAML, so this asks the library
+ that already has: the value node's end mark is the answer, and anything
+ after it on the line is the comment.
+
+ *text* may span several lines, which is what the inline path needs; the
+ value ends on the last of them. Anything that will not compose as a single
+ ``key: value`` pair has no comment this can safely identify, so it reports
+ none.
+ """
+ import yaml
+
+ try:
+ node = yaml.compose(line)
+ except yaml.YAMLError:
+ return ""
+ if not isinstance(node, yaml.MappingNode) or len(node.value) != 1:
+ return ""
+ tail = line[node.value[0][1].end_mark.index :]
+ marker = tail.find("#")
+ return tail[marker:].rstrip() if marker != -1 else ""
+
+
+def _is_flow_value(line: str) -> bool:
+ """Whether the key on *line* already holds an inline ``[...]`` or ``{...}``.
+
+ Editing one item of a user's inline list should give back an inline list.
+ Re-rendering it as a block sequence is a correct document and a gratuitous
+ diff, and on uninstall it would mean the value came back while the
+ formatting did not.
+ """
+ _, separator, rest = line.partition(":")
+ return bool(separator) and rest.lstrip().startswith(("[", "{"))
+
+
+def _split(text: str) -> list[str]:
+ return text.split("\n")
+
+
+def _join(lines: list[str]) -> str:
+ joined = "\n".join(lines)
+ if joined and not joined.endswith("\n"):
+ joined += "\n"
+ return joined
+
+
+def set_child(text: str, parent: str, child: str, value: Any) -> str:
+ """Return *text* with top-level ``parent``'s ``child`` set to *value*.
+
+ Creates the parent block at the end of the file when it is absent, replaces
+ the child in place when it is present, and appends it to the parent's block
+ otherwise. Everything outside the child's own lines is returned untouched.
+ """
+ lines = _split(text)
+ found = _find_top_level(lines, parent)
+
+ if found is None:
+ rendered = [f"{parent}:", *render_child(child, value, DEFAULT_INDENT)]
+ body = text.rstrip("\n")
+ prefix = f"{body}\n\n" if body else ""
+ return prefix + "\n".join(rendered) + "\n"
+
+ start, end = found
+
+ if _is_flow_value(lines[start]):
+ return _set_child_in_flow_parent(lines, start, end, parent, child, value)
+
+ indent = _child_indent(lines, start, end)
+
+ existing = _find_child(lines, start, end, child, indent)
+ if existing is not None:
+ child_start, child_end = existing
+ rendered = render_child(
+ child, value, indent, flow=_is_flow_value(lines[child_start])
+ )
+ comment = _trailing_comment(lines[child_start])
+ if comment:
+ rendered = [f"{rendered[0]} {comment}", *rendered[1:]]
+ return _join(lines[:child_start] + rendered + lines[child_end:])
+
+ rendered = render_child(child, value, indent)
+
+ # Append inside the parent's block, above any blank or comment lines that
+ # trail it, so a comment introducing the next top-level section keeps its
+ # blank line and stays attached to that section rather than to ours.
+ #
+ # Comments count here, not only blanks. The parent's range runs to the next
+ # top-level key, and a heading written above that key sits inside the range,
+ # so stopping at the first blank line inserts our entry *below* the heading:
+ # the user's section title ends up indented inside our block and the section
+ # it introduced loses it. ``_child_end`` walks back over both for the same
+ # reason. The cost when a trailing comment really did belong to the parent
+ # is that our entry lands above it, which loses nothing.
+ # A comment counts only when it is written at the children's own indent or
+ # further left. One indented deeper belongs to the child above it -- a note
+ # under ``github``'s last key, say -- and stepping over that would move it
+ # inside our block, where it reads as documenting our entry instead. The
+ # same rule keeps a ``#`` line that is *content* rather than a comment, a
+ # literal line inside a ``key: |`` block scalar, from being stepped over at
+ # all, which would otherwise truncate the scalar.
+ insert_at = end
+ while insert_at > start + 1:
+ candidate = lines[insert_at - 1]
+ if not candidate.strip():
+ insert_at -= 1
+ continue
+ stripped = candidate.lstrip()
+ if stripped.startswith("#") and len(candidate) - len(stripped) <= indent:
+ insert_at -= 1
+ continue
+ break
+ return _join(lines[:insert_at] + rendered + lines[insert_at:])
+
+
+def _set_child_in_flow_parent(
+ lines: list[str], start: int, end: int, parent: str, child: str, value: Any
+) -> str:
+ """Add a child to a parent whose value is written inline, keeping it inline.
+
+ ``mcp_servers: {}`` is an ordinary way to write a section that exists and
+ holds nothing yet, and ``mcp_servers: {github: {...}}`` is legal too. Neither
+ can be spliced into as a block: the child would be indented under a value
+ that is already closed, producing text that does not parse. Both used to
+ reach :func:`verify`, fail, and surface ``not valid YAML`` about a file that
+ is perfectly valid, with no way forward but hand-editing.
+
+ **Exactly one line is replaced**, not the parent's whole range. The range
+ runs to the next top-level key, so it carries every blank line and comment
+ between the inline value and the next section, and replacing all of it
+ deleted them. That is the same mistake :func:`set_child`'s walk-back exists
+ to avoid, met again on a path that did not inherit the rule, and the parse
+ cannot see it because the document is identical either way.
+
+ The value is re-rendered **inline**, so a parent written as one line stays
+ one line. What that costs is stated in :func:`_flow_span`: the value's own
+ formatting is normalised by the dumper, and a value carrying an anchor is
+ refused rather than re-rendered.
+ """
+ span = _flow_span(lines, start, end, parent)
+ if span is None:
+ return _join(lines)
+ stop, current = span
+ if current is not None and not isinstance(current, dict):
+ # A flow *sequence* is not a mapping we can add a child to.
+ return _join(lines)
+
+ merged = {**(current or {}), child: value}
+ rendered = render_child(parent, merged, 0, flow=True)
+ comment = _trailing_comment("\n".join(lines[start:stop]))
+ if comment:
+ rendered = [f"{rendered[0]} {comment}", *rendered[1:]]
+ return _join(lines[:start] + rendered + lines[stop:])
+
+
+def _flow_span(
+ lines: list[str], start: int, end: int, parent: str
+) -> tuple[int, object] | None:
+ """Where the inline value ends, and what it holds. ``None`` to leave it alone.
+
+ An inline value may wrap across lines, so the shortest slice from *start*
+ that parses is the value: an unbalanced flow collection does not parse, so
+ the first slice that does is the whole of it. Reading only the first line
+ looks equivalent and turned a wrapped value from a working install into a
+ permanent refusal.
+
+ **A value carrying an anchor or an alias is refused.** Adding a child means
+ re-rendering the whole inline value, and the dumper writes anchors back out
+ under generated names, so ``{a: &base {...}, b: *base}`` returns with the
+ name replaced. Every other thing re-rendering normalises here is cosmetic
+ (quote style, the spaces inside the braces) and this one is not: the module
+ header calls losing a factoring the one damage that cannot be undone, so
+ the same rule that keeps this module off a whole-file round trip keeps it
+ off these values.
+ """
+ import yaml
+
+ for stop in range(start + 1, end + 1):
+ text = "\n".join(lines[start:stop])
+ try:
+ parsed = yaml.safe_load(text)
+ except yaml.YAMLError:
+ continue
+ if not isinstance(parsed, dict) or parent not in parsed:
+ return None
+ if _has_anchors(text):
+ return None
+ if stop > start + 1 and "#" in text:
+ # A wrapped value is re-rendered onto one line, so a comment living
+ # *inside* it has nowhere to go. Only the one following the value is
+ # recoverable. Rather than eat the rest, refuse the value: a hash
+ # anywhere in a wrapped inline collection is either a comment worth
+ # keeping or data that says the shape is fussier than this module
+ # should be editing. The single-line case is unaffected, and it is
+ # the common one.
+ return None
+ return stop, parsed.get(parent)
+ return None
+
+
+def _has_anchors(text: str) -> bool:
+ """Whether *text* declares an anchor or uses an alias.
+
+ Asked of the parser rather than by looking for ``&`` and ``*`` in the text,
+ which appear freely inside ordinary scalars: a shell argument like
+ ``sh -c 'ls *'`` would otherwise read as an alias and refuse a config that
+ is fine.
+ """
+ import yaml
+
+ try:
+ for event in yaml.parse(text):
+ if isinstance(event, yaml.events.AliasEvent):
+ return True
+ if getattr(event, "anchor", None):
+ return True
+ except yaml.YAMLError:
+ return True
+ return False
+
+
+#: Returned by :func:`remove_child` when the parent key is gone from the file.
+#: A sentinel rather than ``None``, because ``None`` is a value the key can
+#: legitimately hold: a bare ``parent:`` parses to it. Conflating the two makes
+#: the caller state the wrong document and its own :func:`verify` reject a
+#: removal that was correct.
+ABSENT = object()
+
+
+def remove_child(text: str, parent: str, child: str) -> tuple[str, object]:
+ """Remove top-level ``parent``'s ``child``.
+
+ Returns ``(text, value)``, where *value* is what the parent key holds
+ afterwards, or :data:`ABSENT` when the key is gone. The caller cannot work
+ that out from the text and has to state it to describe the document it
+ means to write, so it is reported rather than left to be guessed.
+
+ **It is reported from what this function did, never by re-reading its own
+ output.** Re-parsing the spliced text to answer the question looks like the
+ same answer and is not: the caller feeds the value straight into the
+ document it hands :func:`verify`, so both sides of that comparison would
+ come from one parse of one string and the check could not fail. It stopped
+ catching a splice that missed, and ``agents remove`` reported ``removed``
+ over a file that still held the entry. Only the caller's own arithmetic is
+ an independent statement of intent, so this reports structure and leaves
+ the value to the caller wherever the caller already knows it.
+
+ Three outcomes, and each is the only safe answer for its case:
+
+ * The block is left with nothing at all, so the parent goes too and an
+ install followed by an uninstall leaves no bare ``parent:`` behind.
+ * **The block still holds the user's comments, which is not empty.**
+ Deleting a parent whose only remaining lines are comments takes those
+ comments with it, and the parse cannot see the difference, so
+ :func:`verify` would wave it through. A user who commented out a parked
+ server inside ``mcp_servers`` would lose the note explaining why. The
+ comments stay, the header stays with them, and the key now holds ``None``.
+ * The value was written inline, in which case the child is taken out of it
+ and the line stays inline. An emptied one comes back as ``parent: {}``,
+ which is exactly what it was before the install.
+
+ A no-op returning the parent untouched when either key is absent.
+ """
+ lines = _split(text)
+ found = _find_top_level(lines, parent)
+ if found is None:
+ return text, ABSENT
+
+ start, end = found
+ if _is_flow_value(lines[start]):
+ return _remove_child_from_flow_parent(lines, start, end, parent, child)
+
+ indent = _child_indent(lines, start, end)
+ existing = _find_child(lines, start, end, child, indent)
+ if existing is None:
+ # Nothing was removed, most often because the key is written in a form
+ # the line match does not recognise, a quoted ``"child":`` for one. The
+ # header is still there, which is what this reports. The caller's own
+ # document says the child is gone while the text still holds it, so
+ # :func:`verify` refuses, which is the honest outcome.
+ return text, None
+
+ child_start, child_end = existing
+ remaining = lines[:child_start] + lines[child_end:]
+
+ # Re-locate the parent in the shortened file rather than reusing the old
+ # offsets: removing the child moved every line after it.
+ refound = _find_top_level(remaining, parent)
+ if refound is None:
+ return _join(remaining), ABSENT
+
+ new_start, new_end = refound
+ body = remaining[new_start + 1 : new_end]
+ if any(line.strip() for line in body):
+ return _join(remaining), None
+ return _join(remaining[:new_start] + remaining[new_end:]), ABSENT
+
+
+def _remove_child_from_flow_parent(
+ lines: list[str], start: int, end: int, parent: str, child: str
+) -> tuple[str, object]:
+ """Take a child out of an inline parent, leaving it inline.
+
+ The mirror of :func:`_set_child_in_flow_parent`, sharing :func:`_flow_span`
+ with it so the two cannot disagree about which lines the value occupies or
+ about which values they will touch. It has to exist for the same reason
+ that one does: teaching the write path about inline parents and leaving
+ this one behind meant ``_find_child`` looked for a ``child:`` line that is
+ not on a line of its own, found nothing, and reported the parent unchanged.
+ Uninstall then failed its own consistency check and left the entry in
+ place, on exactly the configs the write path had just learned to support.
+
+ ``None`` is reported for every path that changes nothing, which says the
+ header is still there and is true. The caller's own document still says the
+ child is gone, so :func:`verify` refuses rather than reporting a removal
+ that did not happen.
+ """
+ span = _flow_span(lines, start, end, parent)
+ if span is None:
+ return _join(lines), None
+ stop, current = span
+ if not isinstance(current, dict) or child not in current:
+ return _join(lines), None
+
+ remaining = {key: item for key, item in current.items() if key != child}
+ rendered = render_child(parent, remaining, 0, flow=True)
+ comment = _trailing_comment("\n".join(lines[start:stop]))
+ if comment:
+ rendered = [f"{rendered[0]} {comment}", *rendered[1:]]
+ return _join(lines[:start] + rendered + lines[stop:]), remaining
+
+
+def verify(merged_text: str, expected: dict) -> None:
+ """Refuse a splice whose result is not the document the caller meant.
+
+ This is what makes line-based surgery safe to ship. The caller builds
+ *expected* from the parsed original, so any shape the matching above did
+ not understand shows up here as a mismatch, and the caller declines with
+ the file untouched instead of writing something it did not intend.
+
+ **What it does not cover, stated plainly so nobody leans on it further than
+ it goes.** The comparison is between *documents*, so it proves the file
+ will mean what the caller intended and nothing more. A splice that dropped
+ only a comment or a blank line produces the same document and passes here.
+ Comment preservation is a property of the surgery being minimal, not
+ something this check enforces, and the tests that cover it assert on the
+ text rather than on the parse.
+
+ Raises ``ValueError`` on a mismatch, so it lands in the same handler as an
+ unreadable file.
+ """
+ actual = load_mapping(merged_text)
+ if not json_deep_equal(actual, expected):
+ raise ValueError(
+ "the merged YAML did not match the intended config, so nothing was written"
+ )
+
+
+def write_if_changed(
+ config_path: Path,
+ merged_text: str,
+ merged_doc: dict,
+ existing_doc: dict | None,
+ *,
+ newline: str | None = None,
+) -> FileAction:
+ """Write *merged_text* only when it would change what the file means.
+
+ Documents rather than bytes, for the reason :func:`toml_merge.write_if_changed`
+ gives: a file that already says the right thing is left exactly as the user
+ has it, including a hand-written flow-style entry that this module would
+ otherwise reformat into block style for no gain. It is also what makes a
+ re-run report :attr:`~..types.FileAction.UNCHANGED` rather than an update it
+ did not make.
+
+ *existing_doc* is ``None`` when the file is new. *newline* should be
+ :func:`detect_newline` of the original text for an existing file, and
+ ``None`` for a new one so it takes the platform's ending the way every
+ other config writer here does.
+ """
+ if existing_doc is not None and json_deep_equal(merged_doc, existing_doc):
+ return FileAction.UNCHANGED
+ action = FileAction.UPDATED if existing_doc is not None else FileAction.CREATED
+ atomic_write_text(config_path, merged_text, newline=newline)
+ return action
diff --git a/packages/cli/src/repowise/cli/agent_targets/registry.py b/packages/cli/src/repowise/cli/agent_targets/registry.py
index 6dc85b869..cd983ebae 100644
--- a/packages/cli/src/repowise/cli/agent_targets/registry.py
+++ b/packages/cli/src/repowise/cli/agent_targets/registry.py
@@ -33,6 +33,7 @@ _TARGET_MODULES: dict[str, str] = {
"vscode": "repowise.cli.agent_targets.targets.vscode:TARGET",
"cursor": "repowise.cli.agent_targets.targets.cursor:TARGET",
"opencode": "repowise.cli.agent_targets.targets.opencode:TARGET",
+ "hermes": "repowise.cli.agent_targets.targets.hermes:TARGET",
}
#: Resolved when :meth:`resolve_target_flag` is asked for ``auto`` and nothing
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py b/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
index fa2ae3bbf..b193077bf 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
@@ -584,15 +584,18 @@ class CodexTarget:
from ..registry import other_managers_of
# ``AGENTS.md`` is a host-neutral convention, not this target's private
- # file: OpenCode reads the same path in the same repo and manages the
- # same marker block. Stripping it while that agent is still wired leaves
- # it configured and silently without its instructions, so the block
- # stays and the caller is told which agent is still reading it.
+ # file: OpenCode and Hermes read the same path in the same repo and
+ # manage the same marker block. Stripping it while any of them is still
+ # wired leaves that agent configured and silently without its
+ # instructions, so the block stays and the caller is told who is still
+ # reading it.
#
- # This guard arrived with OpenCode and belongs here just as much. A
- # shared-ownership fix applied only to the agent added most recently
- # leaves the identical bug in its sibling, which is how this class of
- # defect has kept surviving a review round on this track.
+ # The owner lookup is over the registry rather than a named sibling, so
+ # a fourth agent adopting this file inherits the guard. That matters
+ # more than it sounds: a shared-ownership fix applied only to the agent
+ # added most recently leaves the identical bug in its siblings, which is
+ # how this class of defect has kept surviving a review round on this
+ # track.
owners = other_managers_of(instructions, exclude=ID, scope=scope, repo_path=repo_path)
block_state = inspect(instructions, DISTILL_MARKER_START, DISTILL_MARKER_END).state
if owners and block_state is BlockState.PRESENT:
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/hermes.py b/packages/cli/src/repowise/cli/agent_targets/targets/hermes.py
new file mode 100644
index 000000000..c4965ebe9
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/hermes.py
@@ -0,0 +1,1010 @@
+"""Hermes as an agent target.
+
+Good tier, structurally: it names neither a hook adapter nor a transcript
+adapter, so :func:`derive_tier` cannot place it at Full however many files it
+writes. Hermes exposes no hook protocol repowise can intercept tool calls
+through, and no transcript format to mine.
+
+Every host fact below was read out of Hermes 0.20.0's own source and then
+checked against its shipped documentation, rather than inherited. Where the
+two disagreed the source won, and the disagreements are called out.
+
+**The config file is YAML, one per machine, and the path is platform
+dependent.** ``$HERMES_HOME/config.yaml`` when that variable is set, otherwise
+``%LOCALAPPDATA%\\hermes\\config.yaml`` on Windows and ``~/.hermes/config.yaml``
+everywhere else. The Windows branch is the fact most likely to be dropped for
+looking like an accident: an entry written to ``~/.hermes`` on Windows is not
+broken, it is *invisible*, which is the harder failure to see. Confirmed on
+this machine, which is the strongest form of the check available -- Hermes had
+created ``%LOCALAPPDATA%\\hermes`` with a real config in it, and ``~/.hermes``
+did not exist.
+
+**There is no project-scope config file.** Hermes reads exactly one
+``config.yaml``. So the MCP registration is user scope and nothing else, and
+one registration serves every repo, which is why the entry names no repo path
+and lets the server resolve the repo it was launched in.
+
+**Project scope writes the instructions file, and which file that is matters.**
+Hermes loads exactly one project context file, first match wins, in the order
+``.hermes.md`` / ``HERMES.md``, then ``AGENTS.md``, then ``CLAUDE.md``, then
+``.cursorrules``. The tempting choice is the one named after the host, and it
+is the wrong one: writing ``HERMES.md`` into a repo that already has an
+``AGENTS.md`` would take precedence over it and **suppress the user's existing
+instructions entirely**. So repowise writes the managed block into
+``AGENTS.md``, the file it already manages for two other agents, and a repo
+with no context file at all still gets one.
+
+**The MCP entry carries no ``type`` field.** Hermes distinguishes a local
+subprocess from a remote endpoint by which keys are present: ``command`` and
+``args`` for stdio, ``url`` and ``headers`` for HTTP. See
+:func:`_is_remote_entry` for why the shared ``server_entry`` predicate is not
+used here.
+
+**``platform_toolsets.cli`` is deliberately left alone in the ordinary case,
+and that is the most load-bearing decision in this module.** See
+:func:`_mcp_allowlist`. The short version: Hermes exposes every enabled MCP
+server on every platform by default, and ``platform_toolsets.cli`` only turns
+into an allowlist once it already names an MCP server. Adding ``repowise`` to
+a list that names none would convert a permissive config into an allowlist
+containing only us, silently disabling every other MCP server the user had.
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+from pathlib import Path
+
+from ..formats.server_entry import RemoteServerEntryError
+from ..types import (
+ Capability,
+ DoctorReport,
+ DoctorStatus,
+ FileAction,
+ FileWrite,
+ InstallMethod,
+ Registration,
+ Scope,
+ WriteResult,
+)
+
+ID = "hermes"
+DISPLAY_NAME = "Hermes"
+DOCS_URL = "https://hermes-agent.nousresearch.com/docs/user-guide/features/mcp"
+
+#: Config key gating this agent's managed instruction file. Deliberately the
+#: same id Codex and OpenCode use, because it is the same file: one
+#: ``AGENTS.md`` per repo, so one switch that turns it on and off rather than
+#: three that can disagree.
+PROJECT_FILE_ID = "agents_md"
+
+#: Name of the server entry, and the name Hermes matches in a toolset list.
+SERVER_NAME = "repowise"
+
+#: Top-level key holding MCP servers.
+MCP_KEY = "mcp_servers"
+
+#: Top-level key holding per-platform toolset lists.
+TOOLSETS_KEY = "platform_toolsets"
+
+#: Byte-order mark, spelled as an escape so it cannot be mistaken for stray
+#: whitespace or lost by an editor that strips invisible characters.
+BOM = "\ufeff"
+
+#: The platform key for interactive ``hermes`` sessions.
+CLI_PLATFORM = "cli"
+
+#: Sentinel a user puts in a platform's toolset list to turn every MCP server
+#: off for that platform. Hermes honours it ahead of any allowlist, so a config
+#: carrying it is one repowise must not try to add itself to.
+NO_MCP = "no_mcp"
+
+METHODS = (
+ InstallMethod(
+ id="direct",
+ provides=frozenset({Capability.MCP, Capability.INSTRUCTIONS}),
+ managed_by="repowise",
+ preferred=True,
+ ),
+)
+
+
+def hermes_home() -> Path:
+ """Hermes's data directory, matching the host's own resolution order.
+
+ ``HERMES_HOME`` first, then the platform-native default. The blank check is
+ the part a plain truthiness test misses: an exported-but-empty
+ ``HERMES_HOME`` is ordinary in trimmed CI images and in shell profiles that
+ build the value conditionally, and treating ``""`` as a real prefix would
+ resolve the config to the filesystem root. The value is **stripped** before
+ use for the same reason, and because ``Path(" /home/u/.hermes")`` is a
+ *relative* path -- the config would be written into a directory named
+ ``" "`` inside whatever repo the user happened to be standing in.
+
+ The Windows branch is not a portability nicety, it is where the file
+ actually is. Hermes uses ``%LOCALAPPDATA%\\hermes`` there and has never read
+ ``~/.hermes`` on that platform.
+ """
+ configured = (os.environ.get("HERMES_HOME") or "").strip()
+ if configured:
+ return Path(configured)
+ if sys.platform == "win32":
+ local_appdata = (os.environ.get("LOCALAPPDATA") or "").strip()
+ base = Path(local_appdata) if local_appdata else Path.home() / "AppData" / "Local"
+ return base / "hermes"
+ return Path.home() / ".hermes"
+
+
+def config_path() -> Path:
+ """The one ``config.yaml`` Hermes reads. User scope; there is no other."""
+ return hermes_home() / "config.yaml"
+
+
+def instructions_path(repo_path: Path) -> Path:
+ """``AGENTS.md`` at the repo root. Shared with Codex and OpenCode."""
+ return repo_path / "AGENTS.md"
+
+
+def server_entry() -> dict:
+ """The ``mcp_servers.repowise`` entry, in Hermes's shape.
+
+ Three differences from the JSON hosts, all read off Hermes's schema:
+
+ * No ``type`` key. Hermes has none; ``command`` versus ``url`` is the
+ discriminator.
+ * No ``description``. Hermes's MCP entry documents ``command``, ``args``,
+ ``env``, ``url``, ``headers`` and a fixed set of timeouts and filters; a
+ key outside that set buys nothing.
+ * No ``enabled: true``. It defaults to true when absent, so writing it adds
+ a line that says what the file already means -- and, more usefully, never
+ writing it means ``agents refresh`` can never flip an ``enabled: false``
+ the user set deliberately back on. Parking a server without deleting it
+ is the documented use of that flag.
+
+ This file is per machine and serves every workspace, so the absolute binary
+ of the install that wrote it is pinned -- a PATH shadow cannot hijack it --
+ and **no** repo path is passed, letting the server resolve the repo it was
+ launched in. That bare ``repowise mcp`` form is not novel: it is what
+ ``.mcp.json``, the README and both plugins have always emitted.
+ """
+ from repowise.cli.mcp_config import resolve_repowise_command
+
+ return {
+ "command": resolve_repowise_command(),
+ "args": ["mcp", "--transport", "stdio"],
+ }
+
+
+def _is_remote_entry(entry: dict) -> bool:
+ """Whether a stored entry names a transport repowise did not write.
+
+ Not :func:`..formats.server_entry.is_remote_entry`, and the difference is
+ not cosmetic. That helper is built around a declared ``type`` field, which
+ every JSON host has and Hermes does not, and its fallback limb reads
+ ``"url" in entry and "command" not in entry``. Hermes's own loader is
+ stricter than that fallback: given an entry carrying **both**, it logs a
+ warning and uses the HTTP transport. So an entry with a ``url`` beside a
+ ``command`` is remote as far as this host is concerned, and merging our
+ command into it would leave a registration that looks repointed and still
+ never launches us.
+
+ Reusing a helper that answers a nearby but different question is how this
+ codebase has produced its most expensive bugs, so the rule is spelled out
+ here where the host's behaviour can be checked against it. The shared
+ *exception* is still the right one to raise: the caller's handling is
+ identical.
+ """
+ return "url" in entry
+
+
+def _parse_enabled_flag(value: object) -> bool:
+ """Whether a server's ``enabled`` value reads as on, mirroring the host.
+
+ Hermes treats a missing flag, and any value it does not recognise, as
+ enabled; only ``false`` / ``0`` / ``no`` / ``off`` and a falsey number turn
+ a server off. This is mirrored rather than approximated because it decides
+ whether a toolset list counts as an MCP allowlist, and guessing it wrong in
+ the permissive direction is what would make repowise write the key it must
+ not write.
+ """
+ if value is None:
+ return True
+ if isinstance(value, bool):
+ return value
+ if isinstance(value, int):
+ return value != 0
+ if isinstance(value, str):
+ lowered = value.strip().lower()
+ if lowered in {"true", "1", "yes", "on"}:
+ return True
+ if lowered in {"false", "0", "no", "off"}:
+ return False
+ return True
+
+
+def _enabled_server_names(doc: dict) -> set[str]:
+ """Names of MCP servers this config has switched on."""
+ servers = doc.get(MCP_KEY)
+ if not isinstance(servers, dict):
+ return set()
+ return {
+ str(name)
+ for name, entry in servers.items()
+ if isinstance(entry, dict) and _parse_enabled_flag(entry.get("enabled"))
+ }
+
+
+def _mcp_allowlist(doc: dict) -> list | None:
+ """``platform_toolsets.cli`` when it is already acting as an MCP allowlist.
+
+ **Why this is a condition rather than an unconditional second write.**
+ Hermes resolves a platform's toolsets and then, separately, decides which
+ MCP servers that platform sees. The rule it applies is: if the platform's
+ toolset list names one or more MCP servers, that list is an allowlist and
+ only the named servers are exposed; otherwise **every** enabled MCP server
+ is exposed. A missing ``platform_toolsets`` key means the platform's
+ built-in default applies, which names no MCP server, so it takes the
+ permissive branch too.
+
+ Two consequences, and they point in opposite directions:
+
+ * On an ordinary config -- no ``platform_toolsets`` at all, or a plain
+ ``cli: [hermes-cli]`` -- repowise is already exposed the moment it is in
+ ``mcp_servers``. Adding ``repowise`` to that list would flip the config
+ onto the allowlist branch with exactly one entry, and **every other MCP
+ server the user had would stop being exposed to the CLI**. Writing the
+ key would not merely be redundant, it would be a regression we caused.
+ * On a config whose list already names an MCP server, the allowlist branch
+ is already active, and a repowise absent from that list is filtered out.
+ There the entry is required, and omitting it is the silent failure.
+
+ So the list is touched only when it is already an allowlist, which is what
+ this function returns. ``no_mcp`` is honoured ahead of everything: it turns
+ MCP off for the platform outright, and a user who wrote it does not want us
+ adding ourselves back.
+
+ Membership is tested against the servers this document actually enables, so
+ a list naming only a server the user has since disabled does not read as an
+ allowlist.
+
+ **That test is close to the host's and not identical to it, deliberately.**
+ Hermes also counts MCP servers contributed in memory by an enabled plugin,
+ which are not in ``config.yaml`` at all and cannot be known without loading
+ Hermes. So a toolset list whose only MCP name comes from a plugin reads as
+ an allowlist to the host and as an ordinary list here, and repowise leaves
+ itself out of a list that is filtering on it. The cost of being wrong that
+ way is that repowise does not appear and the user adds one line; the cost of
+ guessing the other way is silently disabling servers they do have. Between a
+ miss the user can see and a regression they cannot, this takes the miss.
+ """
+ toolsets = doc.get(TOOLSETS_KEY)
+ if not isinstance(toolsets, dict):
+ return None
+ listed = toolsets.get(CLI_PLATFORM)
+ # A non-list value is not a configuration Hermes reads: it falls back to
+ # the platform default, which is the permissive branch.
+ if not isinstance(listed, list):
+ return None
+ names = {str(item) for item in listed}
+ if NO_MCP in names:
+ return None
+ if not (names & _enabled_server_names(doc)):
+ return None
+ return listed
+
+
+def _merge_entry(stored: object, generated: dict) -> dict:
+ """Overlay *generated* onto whatever the user already had.
+
+ Generated keys win so a moved install takes effect, and every other key the
+ user added survives -- an ``env`` block carrying provider keys, a ``tools``
+ include/exclude filter, a raised ``timeout``, and ``enabled: false`` on a
+ server they parked on purpose.
+ """
+ if not isinstance(stored, dict):
+ return dict(generated)
+ merged = dict(stored)
+ merged.update(generated)
+ return merged
+
+
+def _plan_write(existing_text: str | None) -> tuple[str, dict, dict | None]:
+ """Compute the whole file this install would write, in one pass.
+
+ Returns ``(merged_text, merged_doc, existing_doc)``. Both edits this target
+ makes land in the same file, so they are two transforms of one string and
+ then one atomic write -- there is no ordering to get wrong and no state in
+ which one landed and the other did not. That is worth stating because the
+ two-key shape invites a two-write implementation, and a two-write
+ implementation would have to answer what a half-installed Hermes means.
+ This one does not have to, because the state cannot occur.
+
+ Raises ``ValueError`` when the file cannot be parsed, when the stored entry
+ is remote, or when the splice did not produce the intended document.
+ """
+ from ..formats import yaml_merge
+
+ generated = server_entry()
+
+ if existing_text is None:
+ existing_doc = None
+ base_doc: dict = {}
+ text = ""
+ else:
+ existing_doc = yaml_merge.load_mapping(existing_text)
+ base_doc = existing_doc
+ text = existing_text
+
+ servers = base_doc.get(MCP_KEY)
+ stored = servers.get(SERVER_NAME) if isinstance(servers, dict) else None
+ if isinstance(stored, dict) and _is_remote_entry(stored):
+ raise RemoteServerEntryError(
+ f"{MCP_KEY}.{SERVER_NAME} names a remote server"
+ )
+
+ entry = _merge_entry(stored, generated)
+
+ # Build the document we intend, from the parsed original, and hand it to
+ # ``verify`` after the splice. Anything the line matching misreads shows up
+ # as a mismatch there rather than as a damaged config.
+ intended = _deep_copy(base_doc)
+ # ``setdefault`` is the obvious call here and it is wrong: it does not
+ # replace a key that is present and null. A section header with nothing
+ # under it yet is ordinary YAML and an ordinary thing to find in a config
+ #
+ # mcp_servers:
+ # # servers go here
+ #
+ # and it parses to ``None``, not to ``{}``. Treating that as a bad shape
+ # made install decline permanently, with a note calling the user's valid
+ # file invalid, and doctor then handed back the command that had just
+ # refused. Hermes itself coerces the same key to an empty mapping before
+ # reading it.
+ section = intended.get(MCP_KEY)
+ if section is None:
+ section = {}
+ if not isinstance(section, dict):
+ raise ValueError(f"'{MCP_KEY}' must be a YAML mapping")
+ intended[MCP_KEY] = section
+ intended[MCP_KEY][SERVER_NAME] = entry
+
+ merged_text = yaml_merge.set_child(text, MCP_KEY, SERVER_NAME, entry)
+
+ allowlist = _mcp_allowlist(intended)
+ if allowlist is not None and SERVER_NAME not in {str(item) for item in allowlist}:
+ updated = [*allowlist, SERVER_NAME]
+ intended[TOOLSETS_KEY][CLI_PLATFORM] = updated
+ merged_text = yaml_merge.set_child(merged_text, TOOLSETS_KEY, CLI_PLATFORM, updated)
+
+ yaml_merge.verify(merged_text, intended)
+ return merged_text, intended, existing_doc
+
+
+def _deep_copy(doc: dict) -> dict:
+ """A copy deep enough that editing the intent cannot touch the original.
+
+ ``copy.deepcopy`` would do, and this exists to keep the comparison in
+ ``write_if_changed`` honest without importing it: the existing document is
+ compared against the intended one, so the two must not share the nested
+ containers being edited.
+ """
+ import copy
+
+ return copy.deepcopy(doc)
+
+
+def write_mcp_config() -> FileWrite:
+ """Merge the repowise server into ``config.yaml``.
+
+ Raises ``ValueError`` when the file cannot be read or the merge cannot be
+ made safely, so the caller can leave it alone and say so.
+ """
+ from ..formats import yaml_merge
+
+ path = config_path()
+ raw = _read_text(path)
+ bom, newline, existing_text = _prepare(raw)
+ merged_text, merged_doc, existing_doc = _plan_write(existing_text)
+
+ if raw is None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ return FileWrite(
+ path=path,
+ action=yaml_merge.write_if_changed(
+ path, bom + merged_text, merged_doc, existing_doc, newline=newline
+ ),
+ )
+
+
+def _prepare(raw: str | None) -> tuple[str, str | None, str | None]:
+ """Split a file's text into what to put back and what to work on.
+
+ Returns ``(bom, newline, text)``. The text is stripped of a byte-order mark
+ and normalised to ``\\n``, which is the only shape the splice understands;
+ the other two are what the write needs to put the file back the way it was.
+
+ **The byte-order mark is the reason this is a function.** Every line match
+ in the splice is anchored at column zero, so a mark sitting in front of the
+ first key hides that key from the search: the edit appends a second copy of
+ a section that was already there, the duplicate makes the merged text parse
+ to something else, and install declines forever on a file both PyYAML and
+ Hermes read without complaint. Notepad on Windows is the ordinary way to get
+ one, and this target is Windows-facing. It is carried across rather than
+ dropped: reading with ``utf-8-sig`` would be shorter and would silently
+ rewrite the file without its mark, which is a change to someone else's file
+ that nothing asked for.
+
+ One helper rather than the same three lines twice, because the install and
+ the removal both do this and the failure when they drift is invisible. The
+ write path keeping the mark while the removal dropped it would break the
+ round trip on exactly the files this exists for.
+ """
+ from ..formats import yaml_merge
+
+ if raw is None:
+ return "", None, None
+ bom = BOM if raw.startswith(BOM) else ""
+ body = raw[len(bom) :]
+ return bom, yaml_merge.detect_newline(body), body.replace("\r\n", "\n")
+
+
+def _read_text(path: Path) -> str | None:
+ """The file's text, or ``None`` when it is not there.
+
+ Read with ``newline=""`` so the line endings survive into
+ :func:`..formats.yaml_merge.detect_newline`. ``read_text`` translates them
+ away in memory, which would make every file look like LF and leave the
+ write to guess -- and the guess is the platform's, which rewrites a user's
+ whole config on Windows for a three-line edit.
+ """
+ if not path.exists():
+ return None
+ with path.open(encoding="utf-8", newline="") as handle:
+ return handle.read()
+
+
+def write_instructions(repo_path: Path) -> FileWrite:
+ """Upsert the managed block into ``AGENTS.md``.
+
+ The body comes from :mod:`..instructions`, which is the one home for it.
+ This is a document the user owns and may already have written in, so there
+ is no ``new_file_prefix`` and no ``delete_if_only``: an ``AGENTS.md``
+ repowise created still belongs to the repo afterwards, and the two other
+ agents managing this same file do not delete it either.
+ """
+ from ..formats import marker_block
+ from ..instructions import DISTILL_MARKER_END, DISTILL_MARKER_START, DISTILL_SECTION
+
+ path = instructions_path(repo_path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ action = marker_block.upsert(
+ path,
+ f"\n{DISTILL_SECTION}\n",
+ DISTILL_MARKER_START,
+ DISTILL_MARKER_END,
+ )
+ return FileWrite(path=path, action=action)
+
+
+def _remove_server_entry() -> tuple[Path, FileAction]:
+ """Drop ``mcp_servers.repowise`` and any allowlist entry naming it.
+
+ Both edits again land in one file and one write.
+
+ **The file itself is only deleted when it is unambiguously ours**, which
+ takes two tests, and the first one is the one that is easy to get wrong.
+
+ The **text** left after the removal has to be blank, not the document. An
+ empty document is not an empty file: a ``config.yaml`` holding nothing but
+ the user's comments parses to ``{}``, and so does one holding a commented
+ out server with a note about why it is parked. Deleting either of those on
+ the strength of the parse destroys a file the user wrote, reports it as
+ ``removed``, and says nothing. Comments do not survive into the parse, so no
+ amount of comparing documents can see the difference.
+
+ The directory has to hold nothing else, as a second test rather than the
+ only one. ``config.yaml`` is the host's own file: Hermes creates it during
+ setup and rewrites it on every ``hermes config set``. But a Hermes that has
+ ever loaded its config also seeds ``SOUL.md`` and ten subdirectories beside
+ it, so a config that is alone in its directory did not come from Hermes.
+ Together the two mean the file is empty, we filled it, and nothing else has
+ ever used the directory.
+ """
+ from ..formats import yaml_merge
+
+ path = config_path()
+ try:
+ raw = _read_text(path)
+ except (OSError, ValueError):
+ return path, FileAction.KEPT
+ if raw is None:
+ return path, FileAction.NOT_FOUND
+ bom, newline, existing_text = _prepare(raw)
+ try:
+ existing_doc = yaml_merge.load_mapping(existing_text or "")
+ except (OSError, ValueError):
+ # Same reason install declines: rewriting a file we could not read
+ # destroys whatever we failed to read.
+ return path, FileAction.KEPT
+
+ servers = existing_doc.get(MCP_KEY)
+ if not isinstance(servers, dict) or SERVER_NAME not in servers:
+ return path, FileAction.NOT_FOUND
+
+ merged_text, section = yaml_merge.remove_child(existing_text, MCP_KEY, SERVER_NAME)
+
+ intended = _deep_copy(existing_doc)
+ del intended[MCP_KEY][SERVER_NAME]
+ if not intended[MCP_KEY]:
+ # What an emptied section leaves behind depends on how it was written:
+ # the header stays when the user's comments are still inside it and
+ # parses to ``None``, an inline one comes back as ``{}``, and otherwise
+ # the key goes. Follow what the helper reports instead of assuming, or
+ # the check below refuses a removal that was correct.
+ if section is yaml_merge.ABSENT:
+ del intended[MCP_KEY]
+ else:
+ intended[MCP_KEY] = section
+
+ merged_text = _prune_allowlist(merged_text, intended)
+
+ try:
+ yaml_merge.verify(merged_text, intended)
+ except ValueError:
+ # A splice that did not produce the intended document must not be
+ # written, and on the destructive verb that is worth reporting as
+ # "left alone" rather than as a removal that did not happen.
+ return path, FileAction.KEPT
+
+ merged_text = bom + merged_text
+ if not merged_text.strip() and _is_sole_occupant(path):
+ try:
+ path.unlink()
+ except OSError:
+ # Never report REMOVED over a file that still holds our entry. A
+ # read-only bit is enough to cause this, and swallowing it turns a
+ # loud failure into a silent false success on the destructive verb.
+ yaml_merge.write_if_changed(
+ path, merged_text, intended, existing_doc, newline=newline
+ )
+ return path, FileAction.REMOVED
+
+ yaml_merge.write_if_changed(path, merged_text, intended, existing_doc, newline=newline)
+ return path, FileAction.REMOVED
+
+
+def _prune_allowlist(text: str, intended: dict) -> str:
+ """Take ``repowise`` back out of ``platform_toolsets.cli``, mutating *intended*.
+
+ Only when it is there, which is only when install put it there. If that
+ leaves the list empty the ``cli`` key goes as well, restoring Hermes's
+ built-in default rather than leaving behind a list that resolves to no
+ toolsets at all -- which the host warns about, and which would be a worse
+ state than the one before repowise was ever installed. That case cannot
+ arise from anything install writes, since install only ever appends to a
+ list that already named another server, but a hand-edited config can reach
+ it and the destructive verb is the wrong place to be surprised.
+ """
+ from ..formats import yaml_merge
+
+ toolsets = intended.get(TOOLSETS_KEY)
+ if not isinstance(toolsets, dict):
+ return text
+ listed = toolsets.get(CLI_PLATFORM)
+ if not isinstance(listed, list) or SERVER_NAME not in listed:
+ return text
+
+ remaining = [item for item in listed if item != SERVER_NAME]
+ if remaining:
+ toolsets[CLI_PLATFORM] = remaining
+ return yaml_merge.set_child(text, TOOLSETS_KEY, CLI_PLATFORM, remaining)
+
+ del toolsets[CLI_PLATFORM]
+ pruned, section = yaml_merge.remove_child(text, TOOLSETS_KEY, CLI_PLATFORM)
+ if not toolsets:
+ # Same contract as the servers section above.
+ if section is yaml_merge.ABSENT:
+ del intended[TOOLSETS_KEY]
+ else:
+ intended[TOOLSETS_KEY] = section
+ return pruned
+
+
+def _is_sole_occupant(path: Path) -> bool:
+ """Whether *path* is the only thing in its directory."""
+ try:
+ return [entry.name for entry in path.parent.iterdir()] == [path.name]
+ except OSError:
+ return False
+
+
+def _prune_home() -> None:
+ """Remove the Hermes home directory when a user-scope uninstall emptied it.
+
+ Only via ``rmdir``, which refuses a directory holding anything, and only
+ after something was actually removed. So a real Hermes home survives
+ untouched. It matters because ``install`` creates this directory and
+ :meth:`HermesTarget.is_present` reads it as evidence the user has Hermes:
+ without the prune, an ``agents add`` followed by an ``agents remove`` would
+ leave our own residue behind as the reason Hermes stays pre-ticked in every
+ later checklist, on a machine that never had it.
+
+ The symlink guard is the other half and it is not theoretical. ``rmdir``
+ refuses a non-empty *directory*, and a Windows junction is not one: it is a
+ reparse point, so ``rmdir`` unlinks it however full its target is. The
+ target survives and the link does not.
+ """
+ import contextlib
+
+ candidate = hermes_home()
+ if candidate.is_symlink():
+ return
+ with contextlib.suppress(OSError):
+ candidate.rmdir()
+
+
+def _remove_instructions(scope: Scope, repo_path: Path) -> tuple[Path, FileAction, list[str]]:
+ """Strip the managed block from ``AGENTS.md``, unless another agent needs it.
+
+ ``AGENTS.md`` is a host-neutral convention rather than this target's private
+ file: Codex and OpenCode read the same path in the same repo and manage the
+ same marker block, and all three descriptors are right to claim it. Install
+ is unaffected, because the block is marker-delimited and idempotent, so
+ whichever agent writes last reports ``unchanged``. Uninstall is where the
+ sharing bites, and the guard is the shared one rather than a third copy of
+ the reasoning.
+
+ Returns the owners that caused a ``KEPT``, empty when something else did.
+ The caller needs that distinction rather than re-deriving it: ``KEPT`` also
+ means "the markers are malformed" and "the file could not be read", and a
+ note blaming shared ownership for one of those sends the user to remove an
+ agent that will not help.
+ """
+ from ..formats import marker_block
+ from ..formats.marker_block import BlockState
+ from ..instructions import DISTILL_MARKER_END, DISTILL_MARKER_START
+ from ..registry import other_managers_of
+
+ path = instructions_path(repo_path)
+
+ state = marker_block.inspect(path, DISTILL_MARKER_START, DISTILL_MARKER_END).state
+ if state is BlockState.PRESENT:
+ owners = other_managers_of(path, exclude=ID, scope=scope, repo_path=repo_path)
+ if owners:
+ return path, FileAction.KEPT, owners
+
+ if marker_block.remove(path, DISTILL_MARKER_START, DISTILL_MARKER_END):
+ return path, FileAction.REMOVED, []
+
+ # ``remove`` returns False for several distinct reasons and they do not
+ # mean the same thing to a reader. "There was nothing of ours here" is
+ # not-found; "there is a file we deliberately did not touch" is kept.
+ if state in (BlockState.ABSENT_FILE, BlockState.ABSENT):
+ return path, FileAction.NOT_FOUND, []
+ return path, FileAction.KEPT, []
+
+
+def _reads_repowise() -> bool:
+ """Whether the user config registers the repowise MCP server."""
+ path = config_path()
+ if not path.exists():
+ return False
+ try:
+ doc = _load_config()
+ except (OSError, ValueError):
+ # ``UnicodeDecodeError`` is a ``ValueError`` and not an ``OSError``, and
+ # a file we cannot decode tells us nothing either way.
+ return False
+ servers = doc.get(MCP_KEY)
+ return isinstance(servers, dict) and SERVER_NAME in servers
+
+
+def _load_config() -> dict:
+ from ..formats import yaml_merge
+
+ raw = _read_text(config_path())
+ return yaml_merge.load_mapping("" if raw is None else raw)
+
+
+def _has_managed_block(repo_path: Path) -> bool:
+ from ..formats import marker_block
+ from ..formats.marker_block import BlockState
+ from ..instructions import DISTILL_MARKER_END, DISTILL_MARKER_START
+
+ state = marker_block.inspect(
+ instructions_path(repo_path), DISTILL_MARKER_START, DISTILL_MARKER_END
+ ).state
+ return state is BlockState.PRESENT
+
+
+def detect(repo_path: Path | None = None) -> list[Registration]:
+ """Every place Hermes is currently wired to repowise. Never raises.
+
+ The user-scope registration is the MCP entry, which is the only thing that
+ makes repowise reachable at all.
+
+ **The project-scope registration is deliberately conditional on the user
+ one**, and the reason is not bookkeeping. The repo half of this target is a
+ managed block in ``AGENTS.md``, a file two other agents also write. Reading
+ that block on its own as "Hermes is wired here" would report Hermes as an
+ owner of ``AGENTS.md`` on a machine that has never had Hermes -- and
+ ``registry.other_managers_of`` asks exactly that question before letting
+ ``agents remove --target=codex`` strip the block, so removing Codex would
+ start refusing on behalf of an agent that does not exist. Requiring the
+ global MCP entry as well makes the claim true in both directions: Hermes
+ can reach repowise, and this repo tells it to. That is also what lets
+ ``agents refresh`` rewrite the repo block, since refresh skips a scope it
+ was told is unwired.
+
+ **There is no text-probe fallback for a config this cannot parse**, and the
+ difference from ``opencode.py`` is the point rather than an omission. That
+ target probes the raw text of a config it failed to parse, because its host
+ accepts comments in JSON and a file ``json.loads`` rejects is usually a
+ working config; answering "not wired" for one would strip a live agent's
+ instructions. YAML has no such gap. Comments are part of the grammar and
+ parse fine, and Hermes reads this file with the same UTF-8 strictness, so a
+ ``config.yaml`` repowise cannot parse is one Hermes cannot parse either.
+ There is no working agent behind it to protect.
+ """
+ found: list[Registration] = []
+ if not _reads_repowise():
+ return found
+
+ config = config_path()
+ found.append(Registration(method="direct", scope=Scope.USER, config_path=config))
+
+ if repo_path is not None:
+ try:
+ has_block = _has_managed_block(repo_path)
+ except (OSError, ValueError):
+ has_block = False
+ if has_block:
+ found.append(
+ Registration(
+ method="direct",
+ scope=Scope.PROJECT,
+ config_path=instructions_path(repo_path),
+ detail="managed instructions block",
+ )
+ )
+ return found
+
+
+class HermesTarget:
+ """Descriptor for Hermes. See the module docstring."""
+
+ id = ID
+ display_name = DISPLAY_NAME
+ docs_url = DOCS_URL
+ hook_adapter = None
+ session_adapter = None
+ methods = METHODS
+ project_file_id = PROJECT_FILE_ID
+
+ def supports_scope(self, scope: Scope) -> bool:
+ """Both, and each writes a different file.
+
+ User scope is the MCP registration in the one ``config.yaml`` Hermes
+ reads; there is no project config file to put it in. Project scope is
+ the managed ``AGENTS.md`` block, which Hermes loads per repo. Neither
+ scope is a subset of the other, so both are real.
+ """
+ return True
+
+ def is_present(self, repo_path: Path | None = None) -> bool:
+ """The ``hermes`` binary on PATH, or a Hermes home directory.
+
+ No repo-local limb. Hermes keeps nothing repo-local of its own -- the
+ only repo file in play is ``AGENTS.md``, which is a host-neutral
+ convention two other agents also write, so reading it as evidence the
+ user has Hermes would pre-tick this agent for anyone using Codex.
+ """
+ import shutil
+
+ if shutil.which("hermes") is not None:
+ return True
+ return hermes_home().is_dir()
+
+ def detect(self, repo_path: Path | None = None) -> list[Registration]:
+ return detect(repo_path)
+
+ def install(
+ self,
+ scope: Scope,
+ options: object = None,
+ *,
+ repo_path: Path | None = None,
+ ) -> WriteResult:
+ result = WriteResult()
+ if scope is Scope.PROJECT and repo_path is None:
+ raise ValueError("project-scope install needs a repo_path")
+
+ if scope is Scope.USER:
+ self._install_user(result)
+ else:
+ self._install_project(result, repo_path)
+ return result
+
+ def _install_user(self, result: WriteResult) -> None:
+ # The write is guarded, and the guard is not theoretical. Nothing wraps
+ # ``install`` -- ``agents add``, ``agents refresh`` and
+ # ``doctor --repair`` all call it bare -- so anything escaping here
+ # aborts the run after other agents' configs have already been written
+ # and prints a traceback in place of the summary naming them.
+ #
+ # ``OSError`` sits alongside ``ValueError`` because the read, the parent
+ # ``mkdir`` and the command resolution all live inside the guarded call.
+ # ``UnicodeDecodeError`` is a ``ValueError``, not an ``OSError``, and is
+ # the ordinary way a cp1252 config on Windows reaches this.
+ path = config_path()
+ try:
+ written = write_mcp_config()
+ result.record(written.path, written.action)
+ except RemoteServerEntryError:
+ result.record(path, FileAction.KEPT)
+ result.note(
+ f'{path} left unchanged: its "{SERVER_NAME}" entry names a remote '
+ "server, and Hermes prefers a URL over a command even when both are "
+ "present, so merging ours in would leave an entry that never launches. "
+ "Run 'repowise agents remove --target=hermes' first if you want the "
+ "local server instead."
+ )
+ return
+ except (ValueError, OSError) as exc:
+ result.record(path, FileAction.KEPT)
+ # The reason is carried rather than asserted: this guard is wide
+ # enough to catch things that are not a bad config file at all, and
+ # a note that flatly said "not valid YAML" would send the user to
+ # inspect a file that is fine.
+ result.note(
+ f"{path} left unchanged ({exc}). Run "
+ f"'repowise agents print-config hermes' and paste the entry under "
+ f'"{MCP_KEY}".'
+ )
+ return
+
+ self._note_toolset_state(result)
+
+ def _note_toolset_state(self, result: WriteResult) -> None:
+ """Say so when the config filters repowise back out after a good write.
+
+ Both cases are silent otherwise, and both look exactly like a working
+ install right up to the point where the tools do not appear.
+ """
+ try:
+ doc = _load_config()
+ except (OSError, ValueError):
+ return
+ toolsets = doc.get(TOOLSETS_KEY)
+ if not isinstance(toolsets, dict):
+ return
+ listed = toolsets.get(CLI_PLATFORM)
+ if not isinstance(listed, list):
+ return
+ if NO_MCP in {str(item) for item in listed}:
+ result.note(
+ f"{config_path()} sets '{TOOLSETS_KEY}.{CLI_PLATFORM}' to include "
+ f"'{NO_MCP}', which turns every MCP server off for the Hermes CLI. "
+ "The repowise entry was written and will stay inert until that is "
+ "removed."
+ )
+
+ def _install_project(self, result: WriteResult, repo_path: Path) -> None:
+ try:
+ written = write_instructions(repo_path)
+ result.record(written.path, written.action)
+ if written.action is FileAction.KEPT:
+ # The helper refuses an orphaned or duplicated marker pair
+ # rather than guessing at a repair that could swallow the
+ # user's own text, so name the file to unpick instead of
+ # reporting a write that did not happen.
+ result.note(
+ f"{instructions_path(repo_path)} left unchanged: its Repowise "
+ "markers are unpaired or duplicated, or the file could not be "
+ "read. Fix it by hand and re-run."
+ )
+ except (OSError, ValueError) as exc:
+ result.record(instructions_path(repo_path), FileAction.KEPT)
+ result.note(f"AGENTS.md could not be written ({exc}).")
+
+ def uninstall(self, scope: Scope, *, repo_path: Path | None = None) -> WriteResult:
+ """Remove whatever install writes at this scope, and nothing else."""
+ result = WriteResult()
+ if scope is Scope.PROJECT and repo_path is None:
+ raise ValueError("project-scope uninstall needs a repo_path")
+
+ if scope is Scope.USER:
+ path, action = _remove_server_entry()
+ result.record(path, action)
+ if action is FileAction.REMOVED:
+ _prune_home()
+ return result
+
+ assert repo_path is not None # narrowed by the guard above
+ instructions, action, owners = _remove_instructions(scope, repo_path)
+ result.record(instructions, action)
+ if owners:
+ result.note(
+ f"{instructions} kept: {' and '.join(owners)} still reads the same "
+ "managed block. Remove that agent too if you want the block gone."
+ )
+ return result
+
+ def print_config(self, scope: Scope, *, repo_path: Path | None = None) -> str:
+ """The entry to paste, in the shape Hermes reads.
+
+ Only the ``mcp_servers`` block. ``platform_toolsets`` is deliberately
+ not printed: on the configs where repowise declines to write it, adding
+ it by hand does the same damage described in :func:`_mcp_allowlist`, and
+ a snippet a user is invited to paste has no way to carry the condition.
+ The one case where the entry is needed is the one where the user
+ already maintains that list and knows what it is for.
+ """
+ from ..formats import yaml_merge
+
+ return "\n".join(
+ [f"{MCP_KEY}:", *yaml_merge.render_child(SERVER_NAME, server_entry(), 2)]
+ )
+
+ def describe_paths(self, scope: Scope, *, repo_path: Path | None = None) -> list[str]:
+ if scope is Scope.USER:
+ return [str(config_path())]
+ return [str(instructions_path(repo_path or Path.cwd()))]
+
+ def doctor(self) -> DoctorReport:
+ """User-scope health, which is the only half a bare call can see.
+
+ ``doctor()`` takes no repo path, so the repo's ``AGENTS.md`` is out of
+ reach and reporting on its behalf would be a claim nothing checked.
+
+ An unreadable config **is** reported as ``BROKEN`` here, which is where
+ this differs from OpenCode. That target declines to call an unparseable
+ file damaged because its host accepts comments in JSON, so the common
+ cause of a parse failure is a perfectly legal file. YAML has no such
+ excuse: comments are part of the grammar and parse fine, so a
+ ``config.yaml`` that will not parse is genuinely damaged, and Hermes
+ cannot read it either.
+ """
+ path = config_path()
+ if _reads_repowise():
+ return DoctorReport(target_id=ID, status=DoctorStatus.OK)
+
+ if path.exists() and not _parses(path):
+ return DoctorReport(
+ target_id=ID,
+ status=DoctorStatus.BROKEN,
+ issues=(
+ f"{path} could not be read as YAML, so Hermes cannot read it "
+ "either. Fix or remove it and re-run.",
+ ),
+ # Refresh skips a target it cannot detect, and install declines
+ # for the same reason this check failed, so ``--repair`` has
+ # nothing to offer here.
+ repairable=False,
+ fix_command="repowise agents add --target=hermes",
+ )
+
+ return DoctorReport(
+ target_id=ID,
+ status=DoctorStatus.NOT_INSTALLED,
+ issues=(
+ "Hermes is not wired at user scope; the managed AGENTS.md block is "
+ "repo-local, so run this from a repo to check that half.",
+ ),
+ fix_command="repowise agents add --target=hermes",
+ )
+
+
+def _parses(path: Path) -> bool:
+ """Whether *path* can be read as a YAML mapping at all."""
+ from ..formats import yaml_merge
+
+ try:
+ raw = _read_text(path)
+ yaml_merge.load_mapping("" if raw is None else raw)
+ except (OSError, ValueError):
+ return False
+ return True
+
+
+TARGET = HermesTarget()
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py b/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py
index 130578800..5bae41e98 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py
@@ -398,19 +398,22 @@ def _remove_instructions(
**The shared-file case, and it is the whole reason this function is not two
lines.** ``AGENTS.md`` is a host-neutral convention, not this target's
private config: Codex has managed the same path in the same repo since long
- before OpenCode was wired, and both descriptors are right to claim it.
+ before OpenCode was wired, Hermes reads it too, and every one of those
+ descriptors is right to claim it.
Install is unaffected -- the block is marker-delimited and idempotent, so
- whichever agent writes second reports ``unchanged``. Uninstall is where the
- sharing bites. Removing OpenCode from a repo that still has Codex wired
- would strip the block out from under Codex, which stays configured, stops
- getting its instructions, and says nothing about it. So the file is left
- alone while another wired agent is still reading it, and the note names
+ whichever agent writes last reports ``unchanged``. Uninstall is where the
+ sharing bites. Removing OpenCode from a repo that still has another of them
+ wired would strip the block out from under an agent that stays configured,
+ stops getting its instructions, and says nothing about it. So the file is
+ left alone while another wired agent is still reading it, and the note names
which one, because a silent ``kept`` is the state that reads as a bug.
- The same guard is in ``codex.py``. It has to be: a fix that only runs on the
- agent added most recently leaves the identical bug sitting in its sibling,
- which is exactly how it went unnoticed for four phases.
+ The same guard is in ``codex.py`` and ``hermes.py``, and all three ask the
+ registry rather than naming each other, so the next agent to adopt this file
+ gets it for free. A fix that only runs on the agent added most recently
+ leaves the identical bug sitting in its siblings, which is exactly how it
+ went unnoticed for four phases.
Returns the owners that caused a ``KEPT``, empty when something else did.
The caller needs that distinction rather than re-deriving it: ``KEPT`` also
diff --git a/scripts/gen_agent_matrix.py b/scripts/gen_agent_matrix.py
index cb8b62067..ccbaf0b25 100644
--- a/scripts/gen_agent_matrix.py
+++ b/scripts/gen_agent_matrix.py
@@ -353,8 +353,9 @@ def render() -> str:
"hosts disagree about the top-level key, about whether each entry carries a",
"`type` field, about whether the invocation is one array or a command plus a",
"separate argument list, and about the file format itself, so `codex` prints",
- "TOML where the others print JSON. `claude-code` is the plain `mcpServers` JSON",
- "most hosts read and is the right default when yours is not listed below.",
+ "TOML and `hermes` prints YAML where the others print JSON. `claude-code` is",
+ "the plain `mcpServers` JSON most hosts read and is the right default when",
+ "yours is not listed below.",
"Hosts people ask about most, none of which repowise writes config for today:",
"",
", ".join(PASTE_CONFIG_HOSTS) + ".",
diff --git a/tests/unit/cli/conftest.py b/tests/unit/cli/conftest.py
index 10601808b..14e212254 100644
--- a/tests/unit/cli/conftest.py
+++ b/tests/unit/cli/conftest.py
@@ -17,6 +17,19 @@ machine that exports one, an unset ``XDG_CONFIG_HOME`` is the difference
between a test writing to a temp directory and a test writing to the
developer's real ``opencode.jsonc``. A test that wants the variable set sets it
itself.
+
+``HERMES_HOME`` and ``LOCALAPPDATA`` are the same hole, one variable further
+along. The Hermes target reads ``HERMES_HOME`` first and then, on Windows only,
+``%LOCALAPPDATA%\\hermes``, never ``~/.hermes`` there, so redirecting home
+covers neither. ``LOCALAPPDATA`` is *redirected* rather than cleared, because
+unlike the other two it is a variable Windows itself always sets and other code
+legitimately reads; pointing it inside the sandbox keeps it meaningful while
+still making it impossible for a test to reach the developer's real
+``config.yaml``.
+
+Every entry here is an absolute-path variable that outranks ``~``. Any new
+target that resolves its config through one belongs in this list, and the check
+is not "does redirecting home cover it", because it does not.
"""
from __future__ import annotations
@@ -32,5 +45,7 @@ def _isolated_home(tmp_path_factory, monkeypatch):
monkeypatch.setenv("HOME", str(fake_home))
monkeypatch.setenv("USERPROFILE", str(fake_home))
monkeypatch.delenv("XDG_CONFIG_HOME", raising=False)
+ monkeypatch.delenv("HERMES_HOME", raising=False)
+ monkeypatch.setenv("LOCALAPPDATA", str(fake_home / "AppData" / "Local"))
monkeypatch.setattr(Path, "home", lambda: fake_home)
return fake_home
diff --git a/tests/unit/cli/test_agent_targets.py b/tests/unit/cli/test_agent_targets.py
index 3b2953882..f4d84d8b7 100644
--- a/tests/unit/cli/test_agent_targets.py
+++ b/tests/unit/cli/test_agent_targets.py
@@ -47,7 +47,7 @@ def test_registry_exposes_the_shipped_targets() -> None:
Order is load-bearing: it is the order agents appear in prompts, in
``--target=all`` and in listings, and new ids append rather than sort in.
"""
- assert ALL_IDS == ["claude-code", "codex", "vscode", "cursor", "opencode"]
+ assert ALL_IDS == ["claude-code", "codex", "vscode", "cursor", "opencode", "hermes"]
@pytest.mark.parametrize("target_id", ALL_IDS)
@@ -125,6 +125,7 @@ def test_tiers_are_derived_from_the_adapters_a_target_names() -> None:
assert tier_of("vscode") is Tier.GOOD
assert tier_of("cursor") is Tier.GOOD
assert tier_of("opencode") is Tier.GOOD
+ assert tier_of("hermes") is Tier.GOOD
def test_a_target_cannot_reach_full_without_a_session_adapter() -> None:
@@ -1935,3 +1936,1201 @@ def test_marker_block_names_the_malformed_states(tmp_path: Path) -> None:
doc.write_text("<!--S-->dangling\n", encoding="utf-8")
assert marker_block.inspect(doc, "<!--S-->", "<!--E-->").state.value == "orphaned"
+
+
+# ---------------------------------------------------------------------------
+# Hermes
+#
+# The first target whose config is YAML, and the first whose two config keys
+# invite a second write that would be actively harmful. Both properties get
+# their own tests, because neither is visible in a fresh-install golden.
+# ---------------------------------------------------------------------------
+
+
+def hermes_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ home = tmp_path / "hermes-home"
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ return home
+
+
+def _hermes():
+ from repowise.cli.agent_targets.targets import hermes
+
+ return hermes
+
+
+def _seed(home: Path, body: str) -> Path:
+ home.mkdir(parents=True, exist_ok=True)
+ config = home / "config.yaml"
+ config.write_bytes(body.encode("utf-8"))
+ return config
+
+
+def test_hermes_home_follows_the_hosts_own_resolution(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """HERMES_HOME wins, then the platform default, and Windows is not ``~/.hermes``.
+
+ The Windows branch is the one worth pinning. An entry written to
+ ``~/.hermes`` on Windows is not broken, it is invisible, and nothing about
+ the install would report a problem.
+ """
+ hermes = _hermes()
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "explicit"))
+ assert hermes.hermes_home() == tmp_path / "explicit"
+
+ # Blank and whitespace-only are not a prefix: joining them resolves to the
+ # filesystem root, or to a relative path named " ".
+ monkeypatch.setenv("HERMES_HOME", " ")
+ monkeypatch.setattr(hermes.sys, "platform", "linux")
+ assert hermes.hermes_home() == Path.home() / ".hermes"
+
+ monkeypatch.delenv("HERMES_HOME", raising=False)
+ monkeypatch.setattr(hermes.sys, "platform", "win32")
+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "AppData" / "Local"))
+ assert hermes.hermes_home() == tmp_path / "AppData" / "Local" / "hermes"
+ assert hermes.hermes_home() != Path.home() / ".hermes"
+
+
+def test_hermes_writes_the_server_entry_and_is_idempotent(hermes_home: Path) -> None:
+ import yaml
+
+ hermes = _hermes()
+ target = get_target("hermes")
+
+ first = target.install(Scope.USER)
+ assert [written.action for written in first.files] == [FileAction.CREATED]
+
+ config = hermes.config_path()
+ doc = yaml.safe_load(config.read_text(encoding="utf-8"))
+ entry = doc["mcp_servers"]["repowise"]
+ # No repo path: one per-machine registration serves every repo, and the
+ # server resolves the repo it was launched in.
+ assert entry["args"] == ["mcp", "--transport", "stdio"]
+ # Keys Hermes does not document must not be invented, and ``enabled``
+ # defaults to true so writing it only creates something to overwrite.
+ assert set(entry) == {"command", "args"}
+
+ second = target.install(Scope.USER)
+ assert [written.action for written in second.files] == [FileAction.UNCHANGED]
+
+
+def test_hermes_does_not_turn_a_permissive_config_into_an_allowlist(
+ hermes_home: Path,
+) -> None:
+ """The single most consequential thing this target does not do.
+
+ Hermes exposes every enabled MCP server to a platform unless that
+ platform's toolset list already names one, at which point the list becomes
+ an allowlist. Adding ``repowise`` to a list that names none would flip the
+ config onto the allowlist branch with exactly one entry and cut off every
+ other MCP server the user had.
+ """
+ import yaml
+
+ config = _seed(
+ hermes_home,
+ "mcp_servers:\n"
+ " github:\n"
+ " command: npx\n"
+ "\n"
+ "platform_toolsets:\n"
+ " cli: [hermes-cli]\n",
+ )
+ get_target("hermes").install(Scope.USER)
+
+ doc = yaml.safe_load(config.read_text(encoding="utf-8"))
+ assert doc["platform_toolsets"]["cli"] == ["hermes-cli"]
+ assert "repowise" in doc["mcp_servers"]
+ assert "github" in doc["mcp_servers"]
+
+
+def test_hermes_joins_a_list_that_is_already_an_mcp_allowlist(hermes_home: Path) -> None:
+ """The mirror case, where omitting the entry is the silent failure.
+
+ The list already names an MCP server, so Hermes is filtering on it, and a
+ repowise absent from it would be registered and never reach the CLI.
+ """
+ import yaml
+
+ config = _seed(
+ hermes_home,
+ "mcp_servers:\n"
+ " github:\n"
+ " command: npx\n"
+ "\n"
+ "platform_toolsets:\n"
+ " cli:\n"
+ " - hermes-cli\n"
+ " - github\n",
+ )
+ get_target("hermes").install(Scope.USER)
+
+ doc = yaml.safe_load(config.read_text(encoding="utf-8"))
+ assert doc["platform_toolsets"]["cli"] == ["hermes-cli", "github", "repowise"]
+
+
+def test_hermes_ignores_an_allowlist_naming_only_a_disabled_server(
+ hermes_home: Path,
+) -> None:
+ """Membership is tested against *enabled* servers, exactly as the host tests it.
+
+ A list naming a server the user has since switched off is not an allowlist
+ to Hermes, so joining it would create the restriction the test above exists
+ to prevent.
+ """
+ import yaml
+
+ config = _seed(
+ hermes_home,
+ "mcp_servers:\n"
+ " github:\n"
+ " command: npx\n"
+ " enabled: false\n"
+ "\n"
+ "platform_toolsets:\n"
+ " cli: [hermes-cli, github]\n",
+ )
+ get_target("hermes").install(Scope.USER)
+
+ doc = yaml.safe_load(config.read_text(encoding="utf-8"))
+ assert doc["platform_toolsets"]["cli"] == ["hermes-cli", "github"]
+
+
+def test_hermes_reports_the_no_mcp_sentinel_rather_than_writing_past_it(
+ hermes_home: Path,
+) -> None:
+ """``no_mcp`` turns every MCP server off for the platform.
+
+ The entry is still written, because the sentinel is a per-platform switch
+ the user can flip back, but a silent success here looks exactly like a
+ working install right up to the point where no tools appear.
+ """
+ import yaml
+
+ config = _seed(
+ hermes_home,
+ "mcp_servers:\n"
+ " github:\n"
+ " command: npx\n"
+ "\n"
+ "platform_toolsets:\n"
+ " cli: [hermes-cli, no_mcp]\n",
+ )
+ result = get_target("hermes").install(Scope.USER)
+
+ assert any("no_mcp" in note for note in result.notes)
+ doc = yaml.safe_load(config.read_text(encoding="utf-8"))
+ assert doc["platform_toolsets"]["cli"] == ["hermes-cli", "no_mcp"]
+
+
+def test_hermes_preserves_comments_anchors_and_line_endings(hermes_home: Path) -> None:
+ """The reason this target splices rather than reserializing.
+
+ A ``safe_load``/``safe_dump`` round-trip loses all three: the comments
+ outright, and the anchors by expanding them into the values they stand for,
+ which is a change no diff of the parsed data would show.
+ """
+ original = (
+ "# my hermes config\r\n"
+ "defaults: &d\r\n"
+ " timeout: 30\r\n"
+ "model:\r\n"
+ " <<: *d\r\n"
+ " name: gpt-5 # the good one\r\n"
+ )
+ config = _seed(hermes_home, original)
+ get_target("hermes").install(Scope.USER)
+
+ text = config.read_bytes().decode("utf-8")
+ assert "# my hermes config" in text
+ assert "&d" in text
+ assert "<<: *d" in text
+ assert "# the good one" in text
+ assert "\r\n" in text
+ assert "\n" not in text.replace("\r\n", "")
+
+
+def test_hermes_does_not_convert_an_lf_config_to_crlf(hermes_home: Path) -> None:
+ """The discriminating half of line-ending preservation, and it only shows on Windows.
+
+ A CRLF fixture cannot prove this here: the platform translation an ordinary
+ config write uses *also* emits CRLF on Windows, so that test stays green
+ against a writer that ignores the file entirely. An LF file is the case
+ where the two answers differ, and turning every line of a user's config
+ over on a three-line edit is a whole-file diff rather than a cosmetic one.
+ """
+ config = _seed(hermes_home, "# my hermes config\nmodel:\n name: gpt-5\n")
+ get_target("hermes").install(Scope.USER)
+
+ assert b"\r\n" not in config.read_bytes()
+
+
+def test_hermes_round_trips_a_seeded_config_byte_for_byte(hermes_home: Path) -> None:
+ original = (
+ "# my hermes config\n"
+ "model:\n"
+ " name: gpt-5 # the good one\n"
+ "\n"
+ "platform_toolsets:\n"
+ " cli: [hermes-cli]\n"
+ )
+ config = _seed(hermes_home, original)
+ target = get_target("hermes")
+
+ target.install(Scope.USER)
+ assert config.read_bytes() != original.encode("utf-8")
+
+ target.uninstall(Scope.USER)
+ assert config.read_bytes() == original.encode("utf-8")
+
+
+def test_hermes_declines_a_config_it_cannot_splice_safely(hermes_home: Path) -> None:
+ """A repeated top-level key is a shape the line matching cannot get right.
+
+ The search finds the first ``mcp_servers:`` while the parser keeps the
+ last, so an edit lands in a block the document does not use. It is caught
+ by re-parsing the spliced text and comparing it against the document the
+ target meant to write, which is what makes line-based surgery safe to ship:
+ a mis-fired splice becomes a decline, never a corrupted file.
+ """
+ original = (
+ "mcp_servers:\n"
+ " github:\n"
+ " command: gh\n"
+ "mcp_servers:\n"
+ " other:\n"
+ " command: npx\n"
+ )
+ config = _seed(hermes_home, original)
+
+ result = get_target("hermes").install(Scope.USER)
+
+ assert [written.action for written in result.files] == [FileAction.KEPT]
+ assert config.read_bytes() == original.encode("utf-8")
+ assert any("print-config hermes" in note for note in result.notes)
+
+
+def test_hermes_declines_unparseable_and_undecodable_configs(hermes_home: Path) -> None:
+ """``UnicodeDecodeError`` is a ``ValueError``, not an ``OSError``.
+
+ Nothing wraps ``install``, so an escape here aborts the whole run after
+ other agents' configs have been written.
+ """
+ hermes = _hermes()
+ target = get_target("hermes")
+
+ broken = _seed(hermes_home, "model: [unclosed\n")
+ result = target.install(Scope.USER)
+ assert [written.action for written in result.files] == [FileAction.KEPT]
+ assert broken.read_bytes() == b"model: [unclosed\n"
+ assert target.doctor().status.value == "broken"
+
+ (hermes_home / "config.yaml").write_bytes(b"model:\n name: caf\xe9\n")
+ result = target.install(Scope.USER)
+ assert [written.action for written in result.files] == [FileAction.KEPT]
+ assert (hermes_home / "config.yaml").read_bytes() == b"model:\n name: caf\xe9\n"
+ # detect is contracted never to raise, whatever the file holds.
+ assert hermes.detect() == []
+
+
+def test_hermes_leaves_a_remote_entry_alone(hermes_home: Path) -> None:
+ """Hermes prefers a ``url`` over a ``command`` even when both are present.
+
+ So merging our command into an entry that has a url would leave a
+ registration that reads as repointed and still never launches us. The
+ shared ``is_remote_entry`` helper keys on a declared ``type`` field, which
+ this host does not have, and its fallback limb would call this entry local.
+ """
+ original = (
+ "mcp_servers:\n"
+ " repowise:\n"
+ ' url: "https://example.invalid/mcp"\n'
+ " command: repowise\n"
+ )
+ config = _seed(hermes_home, original)
+
+ result = get_target("hermes").install(Scope.USER)
+
+ assert [written.action for written in result.files] == [FileAction.KEPT]
+ assert config.read_bytes() == original.encode("utf-8")
+ assert any("remote server" in note for note in result.notes)
+
+
+def test_hermes_keeps_the_keys_a_user_added_to_our_entry(hermes_home: Path) -> None:
+ """Generated keys win so a moved install takes effect; everything else survives.
+
+ ``enabled: false`` is the one most worth keeping: parking a server without
+ deleting it is the documented use of that flag, and re-enabling it on every
+ ``agents refresh`` would undo a deliberate choice.
+ """
+ import yaml
+
+ config = _seed(
+ hermes_home,
+ "mcp_servers:\n"
+ " repowise:\n"
+ " command: /old/path/repowise\n"
+ " args: [mcp]\n"
+ " env:\n"
+ " MY_KEY: secret\n"
+ " timeout: 300\n"
+ " enabled: false\n",
+ )
+ get_target("hermes").install(Scope.USER)
+
+ entry = yaml.safe_load(config.read_text(encoding="utf-8"))["mcp_servers"]["repowise"]
+ assert entry["command"] != "/old/path/repowise"
+ assert entry["args"] == ["mcp", "--transport", "stdio"]
+ assert entry["env"] == {"MY_KEY": "secret"}
+ assert entry["timeout"] == 300
+ assert entry["enabled"] is False
+
+
+def test_hermes_uninstall_keeps_a_config_file_it_did_not_create(hermes_home: Path) -> None:
+ """``config.yaml`` is the host's own file, so an empty one is not proof it is ours.
+
+ The unambiguous signal is the directory: Hermes seeds ``SOUL.md`` and ten
+ subdirectories into its home on every config load, so a lone ``config.yaml``
+ cannot have come from it, and anything else beside it means the file stays.
+ """
+ hermes = _hermes()
+ config = _seed(hermes_home, "")
+ (hermes_home / "SOUL.md").write_text("you are helpful\n", encoding="utf-8")
+
+ target = get_target("hermes")
+ target.install(Scope.USER)
+ target.uninstall(Scope.USER)
+
+ assert config.exists()
+ assert hermes.hermes_home().exists()
+ assert config.read_text(encoding="utf-8").strip() == ""
+
+
+def test_hermes_uninstall_removes_a_home_it_created(hermes_home: Path) -> None:
+ """Otherwise our own residue keeps the agent pre-ticked forever.
+
+ ``is_present`` reads this directory as evidence the user has Hermes, so an
+ ``agents add`` followed by an ``agents remove`` would leave the machine
+ looking like a Hermes machine when it never was.
+ """
+ hermes = _hermes()
+ target = get_target("hermes")
+
+ assert not hermes.hermes_home().exists()
+ target.install(Scope.USER)
+ assert hermes.config_path().exists()
+
+ target.uninstall(Scope.USER)
+ assert not hermes.config_path().exists()
+ assert not hermes.hermes_home().exists()
+
+
+def test_hermes_project_scope_manages_the_agents_md_block(
+ hermes_home: Path, tmp_path: Path
+) -> None:
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ (repo / "AGENTS.md").write_bytes(b"# House rules\n\nBe nice.\n")
+ target = get_target("hermes")
+
+ first = target.install(Scope.PROJECT, repo_path=repo)
+ assert [written.action for written in first.files] == [FileAction.UPDATED]
+ second = target.install(Scope.PROJECT, repo_path=repo)
+ assert [written.action for written in second.files] == [FileAction.UNCHANGED]
+
+ target.uninstall(Scope.PROJECT, repo_path=repo)
+ assert (repo / "AGENTS.md").read_bytes() == b"# House rules\n\nBe nice.\n"
+
+
+def test_hermes_does_not_write_the_file_the_host_prefers(
+ hermes_home: Path, tmp_path: Path
+) -> None:
+ """Hermes loads one project context file, and ``HERMES.md`` outranks ``AGENTS.md``.
+
+ Writing the host-named file into a repo that already has an ``AGENTS.md``
+ would take precedence over it and suppress the repo's real instructions.
+ """
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ get_target("hermes").install(Scope.PROJECT, repo_path=repo)
+
+ assert (repo / "AGENTS.md").exists()
+ assert not (repo / "HERMES.md").exists()
+ assert not (repo / ".hermes.md").exists()
+
+
+def test_hermes_project_registration_requires_the_global_one(
+ hermes_home: Path, tmp_path: Path
+) -> None:
+ """A managed block on its own must not report Hermes as wired.
+
+ ``AGENTS.md`` is written by two other agents, so reading the block alone as
+ "Hermes is wired here" would report Hermes as an owner of that file on a
+ machine that has never had Hermes, and ``other_managers_of`` asks exactly
+ that before letting ``agents remove --target=codex`` strip the block.
+ """
+ hermes = _hermes()
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ target = get_target("hermes")
+
+ target.install(Scope.PROJECT, repo_path=repo)
+ assert hermes.detect(repo) == []
+
+ target.install(Scope.USER)
+ assert [registration.scope for registration in hermes.detect(repo)] == [
+ Scope.USER,
+ Scope.PROJECT,
+ ]
+
+
+def test_hermes_and_codex_do_not_strip_the_shared_block_from_each_other(
+ hermes_home: Path, tmp_path: Path
+) -> None:
+ """Three targets now manage ``AGENTS.md``, and the guard is over the registry.
+
+ Driven through both targets rather than by calling the helper by hand, so
+ deleting either side's guard fails this.
+ """
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ hermes_target = get_target("hermes")
+ codex_target = get_target("codex")
+
+ codex_target.install(Scope.PROJECT, repo_path=repo)
+ hermes_target.install(Scope.USER)
+ hermes_target.install(Scope.PROJECT, repo_path=repo)
+
+ removed_codex = codex_target.uninstall(Scope.PROJECT, repo_path=repo)
+ assert FileAction.KEPT in [written.action for written in removed_codex.files]
+ assert any("Hermes" in note for note in removed_codex.notes)
+
+ removed_hermes = hermes_target.uninstall(Scope.PROJECT, repo_path=repo)
+ assert FileAction.KEPT in [written.action for written in removed_hermes.files]
+ assert any("Codex" in note for note in removed_hermes.notes)
+
+ # The block is still there, which is the whole point.
+ assert "REPOWISE_DISTILL:START" in (repo / "AGENTS.md").read_text(encoding="utf-8")
+
+
+def test_hermes_batch_removal_does_not_deadlock_on_the_shared_block(
+ hermes_home: Path, tmp_path: Path
+) -> None:
+ """Removing both at once must not have each keep the file for the other."""
+ from repowise.cli.agent_targets.registry import removing
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ hermes_target = get_target("hermes")
+ codex_target = get_target("codex")
+
+ codex_target.install(Scope.PROJECT, repo_path=repo)
+ hermes_target.install(Scope.USER)
+ hermes_target.install(Scope.PROJECT, repo_path=repo)
+
+ with removing(["codex", "hermes"]):
+ codex_target.uninstall(Scope.PROJECT, repo_path=repo)
+ hermes_target.uninstall(Scope.PROJECT, repo_path=repo)
+
+ assert not (repo / "AGENTS.md").exists()
+
+
+def test_hermes_print_config_parses_as_the_shape_the_host_reads(hermes_home: Path) -> None:
+ """It also must not touch the filesystem, and must not print the toolset key.
+
+ Printing ``platform_toolsets`` would invite the user to paste the exact
+ change this target declines to make, and a snippet cannot carry the
+ condition under which it is correct.
+ """
+ import yaml
+
+ snippet = get_target("hermes").print_config(Scope.USER)
+ assert not hermes_home.exists()
+
+ doc = yaml.safe_load(snippet)
+ assert set(doc) == {"mcp_servers"}
+ assert doc["mcp_servers"]["repowise"]["args"] == ["mcp", "--transport", "stdio"]
+
+
+def test_hermes_describe_paths_names_what_each_scope_writes(
+ hermes_home: Path, tmp_path: Path
+) -> None:
+ target = get_target("hermes")
+ repo = tmp_path / "repo"
+
+ assert target.describe_paths(Scope.USER) == [str(hermes_home / "config.yaml")]
+ assert target.describe_paths(Scope.PROJECT, repo_path=repo) == [str(repo / "AGENTS.md")]
+
+
+def test_hermes_doctor_distinguishes_absent_from_damaged(hermes_home: Path) -> None:
+ target = get_target("hermes")
+ assert target.doctor().status.value == "not-installed"
+
+ config = _seed(hermes_home, "model: [unclosed\n")
+ report = target.doctor()
+ assert report.status.value == "broken"
+ # Refresh skips what it cannot detect and install declines for the same
+ # reason this failed, so --repair has nothing to offer.
+ assert report.repairable is False
+
+ # Install declines against a file it cannot read, so the row stays broken
+ # rather than flipping to ok on a write that did not happen.
+ target.install(Scope.USER)
+ assert target.doctor().status.value == "broken"
+
+ config.unlink()
+ target.install(Scope.USER)
+ assert target.doctor().status.value == "ok"
+
+
+def test_hermes_uninstall_keeps_a_config_holding_only_the_users_comments(
+ hermes_home: Path,
+) -> None:
+ """An empty document is not an empty file, and the parse cannot tell them apart.
+
+ A ``config.yaml`` that is nothing but the user's comments parses to ``{}``,
+ and so does one whose only server is commented out with a note about why it
+ is parked. Deleting either on the strength of the parse destroys a file the
+ user wrote, reports it as ``removed``, and says nothing. This is the
+ sole-occupant case too, so the directory test alone does not save it.
+ """
+ target = get_target("hermes")
+
+ # Comments at top level only. After the removal the document really is
+ # empty, so this is the case that isolates the text test: nothing else
+ # stops the delete.
+ bare = "# my hermes config, managed by chezmoi\n# model:\n# name: gpt-5\n"
+ config = _seed(hermes_home, bare)
+ assert [entry.name for entry in hermes_home.iterdir()] == ["config.yaml"]
+
+ target.install(Scope.USER)
+ target.uninstall(Scope.USER)
+
+ assert config.exists()
+ assert config.read_bytes() == bare.encode("utf-8")
+ assert hermes_home.exists()
+
+ # Comments inside the section we own. Here the section header survives with
+ # them, so the document is not empty either, and both guards have to hold
+ # for the round trip to be exact.
+ parked = (
+ "mcp_servers:\n"
+ " # github parked 2026-08-01, re-enable after the token rotates\n"
+ " # github:\n"
+ " # command: gh\n"
+ )
+ config.write_bytes(parked.encode("utf-8"))
+ target.install(Scope.USER)
+ target.uninstall(Scope.USER)
+
+ assert config.exists()
+ assert config.read_bytes() == parked.encode("utf-8")
+
+
+def test_hermes_installs_into_a_section_header_with_nothing_under_it(
+ hermes_home: Path,
+) -> None:
+ """``mcp_servers:`` with only a comment under it parses to ``None``, not ``{}``.
+
+ ``setdefault`` is the obvious way to reach that key and it does not replace
+ a present-but-null one, so this declined permanently with a note calling a
+ valid file invalid, and doctor then handed back the command that had just
+ refused. Hermes coerces the same key before reading it.
+ """
+ import yaml
+
+ config = _seed(hermes_home, "model: gpt\nmcp_servers:\n # servers go here\n")
+ result = get_target("hermes").install(Scope.USER)
+
+ assert [written.action for written in result.files] == [FileAction.UPDATED]
+ assert result.notes == []
+ doc = yaml.safe_load(config.read_text(encoding="utf-8"))
+ assert "repowise" in doc["mcp_servers"]
+ assert "# servers go here" in config.read_text(encoding="utf-8")
+
+
+def test_hermes_installs_into_a_flow_style_section(hermes_home: Path) -> None:
+ """``mcp_servers: {}`` is legal and used to be an unfixable decline.
+
+ The whole cycle, because keeping the inline style on write and not teaching
+ removal about it left uninstall reporting ``kept`` and doing nothing.
+ """
+ import yaml
+
+ original = "model: gpt\nmcp_servers: {}\n"
+ config = _seed(hermes_home, original)
+ target = get_target("hermes")
+
+ result = target.install(Scope.USER)
+ assert [written.action for written in result.files] == [FileAction.UPDATED]
+ doc = yaml.safe_load(config.read_text(encoding="utf-8"))
+ assert "repowise" in doc["mcp_servers"]
+ assert doc["model"] == "gpt"
+
+ assert [written.action for written in target.install(Scope.USER).files] == [
+ FileAction.UNCHANGED
+ ]
+
+ removed = target.uninstall(Scope.USER)
+ assert [written.action for written in removed.files] == [FileAction.REMOVED]
+ assert config.read_bytes() == original.encode("utf-8")
+
+
+def test_hermes_survives_a_byte_order_mark(hermes_home: Path) -> None:
+ """A BOM hides the first key from a search anchored at column zero.
+
+ The edit then appends a second copy of a section that was already there,
+ the duplicate makes the merged text parse to something else, and install
+ declines forever on a file both PyYAML and Hermes read fine. The mark is
+ carried across rather than dropped, so the round trip is byte exact.
+ """
+ import yaml
+
+ original = "mcp_servers:\n github:\n command: gh\n"
+ config = _seed(hermes_home, original)
+ target = get_target("hermes")
+
+ result = target.install(Scope.USER)
+ assert [written.action for written in result.files] == [FileAction.UPDATED]
+
+ text = config.read_bytes().decode("utf-8")
+ assert text.startswith("")
+ doc = yaml.safe_load(text)
+ assert set(doc["mcp_servers"]) == {"github", "repowise"}
+
+ target.uninstall(Scope.USER)
+ assert config.read_bytes() == original.encode("utf-8")
+
+
+def test_hermes_round_trips_an_allowlist_config_through_the_cli_path(
+ hermes_home: Path,
+) -> None:
+ """The allowlist branch, exercised through install and uninstall.
+
+ The other round-trip test seeds ``cli: [hermes-cli]``, which does not name
+ an MCP server and so never reaches the toolset write at all. Without this
+ one, the inline-list rendering is covered only by calling the helper by
+ hand, and the failure it guards against shows up on uninstall.
+ """
+ original = (
+ "mcp_servers:\n"
+ " othersrv: # a server I already had\n"
+ " command: npx\n"
+ "\n"
+ "platform_toolsets:\n"
+ " cli: [hermes-cli, othersrv]\n"
+ )
+ config = _seed(hermes_home, original)
+ target = get_target("hermes")
+
+ target.install(Scope.USER)
+ text = config.read_text(encoding="utf-8")
+ assert " cli: [hermes-cli, othersrv, repowise]\n" in text
+ assert "# a server I already had" in text
+
+ assert [written.action for written in target.install(Scope.USER).files] == [
+ FileAction.UNCHANGED
+ ]
+
+ target.uninstall(Scope.USER)
+ assert config.read_bytes() == original.encode("utf-8")
+
+
+# ---------------------------------------------------------------------------
+# yaml_merge
+# ---------------------------------------------------------------------------
+
+
+def test_yaml_merge_treats_a_same_indent_block_list_as_part_of_its_key() -> None:
+ """The dumper writes block sequences at the parent key's own indent.
+
+ Reading the first ``- `` line as the next sibling truncates the block after
+ one line, and the edit then lands above items that are still there.
+ """
+ from repowise.cli.agent_targets.formats import yaml_merge
+
+ text = "platform_toolsets:\n cli:\n - hermes-cli\n - github\nother: 1\n"
+ merged = yaml_merge.set_child(text, "platform_toolsets", "cli", ["hermes-cli", "x"])
+
+ assert yaml_merge.load_mapping(merged) == {
+ "platform_toolsets": {"cli": ["hermes-cli", "x"]},
+ "other": 1,
+ }
+ assert "github" not in merged
+
+
+def test_yaml_merge_verify_refuses_a_splice_that_missed() -> None:
+ """The guard that makes line surgery safe: intent is checked, not assumed."""
+ from repowise.cli.agent_targets.formats import yaml_merge
+
+ yaml_merge.verify("a: 1\n", {"a": 1})
+ with pytest.raises(ValueError):
+ yaml_merge.verify("a: 1\n", {"a": 2})
+
+
+def test_yaml_merge_rejects_what_is_not_a_mapping() -> None:
+ """A ``yaml.YAMLError`` is not a ``ValueError``, so it would escape every handler."""
+ from repowise.cli.agent_targets.formats import yaml_merge
+
+ assert yaml_merge.load_mapping("") == {}
+ with pytest.raises(ValueError):
+ yaml_merge.load_mapping("- a\n- b\n")
+ with pytest.raises(ValueError):
+ yaml_merge.load_mapping("a: [unclosed\n")
+
+
+def test_yaml_merge_detects_the_newline_to_write_back_with() -> None:
+ from repowise.cli.agent_targets.formats import yaml_merge
+
+ assert yaml_merge.detect_newline("a: 1\nb: 2\n") == "\n"
+ assert yaml_merge.detect_newline("a: 1\r\nb: 2\r\n") == "\r\n"
+
+
+def test_yaml_merge_removes_the_parent_once_it_is_empty() -> None:
+ """A bare ``parent:`` parses as ``None``, which is a different document."""
+ from repowise.cli.agent_targets.formats import yaml_merge
+
+ text = "mcp_servers:\n repowise:\n command: x\nmodel: gpt\n"
+ merged, section = yaml_merge.remove_child(text, "mcp_servers", "repowise")
+
+ assert section is yaml_merge.ABSENT
+ assert yaml_merge.load_mapping(merged) == {"model": "gpt"}
+ assert "mcp_servers" not in merged
+
+
+def test_yaml_merge_keeps_a_section_that_still_holds_the_users_comments() -> None:
+ """Comments are content, and the parse cannot see them.
+
+ A section left holding only comments must survive, which means the header
+ survives with it and the key parses to ``None`` rather than going away. The
+ caller is told which happened because it cannot work it out from the text,
+ and ``verify`` cannot catch getting it wrong: deleting the comments leaves
+ the same document.
+ """
+ from repowise.cli.agent_targets.formats import yaml_merge
+
+ text = (
+ "mcp_servers:\n"
+ " # github parked 2026-08-01, re-enable after the token rotates\n"
+ " # github:\n"
+ " # command: gh\n"
+ " repowise:\n"
+ " command: x\n"
+ )
+ merged, section = yaml_merge.remove_child(text, "mcp_servers", "repowise")
+
+ # The header stays with the comments, so the key holds ``None`` rather than
+ # being gone. ``ABSENT`` is a sentinel precisely so those two stay distinct.
+ assert section is None
+ assert section is not yaml_merge.ABSENT
+ assert "token rotates" in merged
+ assert "# command: gh" in merged
+ assert yaml_merge.load_mapping(merged) == {"mcp_servers": None}
+
+
+def test_yaml_merge_can_add_a_child_to_a_flow_mapping_parent() -> None:
+ """``mcp_servers: {}`` is an ordinary way to write an empty section.
+
+ A block child cannot be spliced under a value that is already closed, so
+ this used to produce unparseable text, get refused by ``verify``, and
+ surface "not valid YAML" about a file that is entirely valid, with no way
+ forward for the user.
+ """
+ from repowise.cli.agent_targets.formats import yaml_merge
+
+ empty = yaml_merge.set_child(
+ "model: gpt\nmcp_servers: {}\n", "mcp_servers", "repowise", {"command": "x"}
+ )
+ assert yaml_merge.load_mapping(empty) == {
+ "model": "gpt",
+ "mcp_servers": {"repowise": {"command": "x"}},
+ }
+
+ populated = yaml_merge.set_child(
+ "mcp_servers: {github: {command: gh}}\n",
+ "mcp_servers",
+ "repowise",
+ {"command": "x"},
+ )
+ assert yaml_merge.load_mapping(populated) == {
+ "mcp_servers": {"github": {"command": "gh"}, "repowise": {"command": "x"}}
+ }
+
+
+def test_yaml_merge_flow_parent_edits_only_its_own_line() -> None:
+ """The parent's range runs to the next top-level key, so replacing it is wrong.
+
+ Everything between the inline value and the next section is blank lines and
+ the user's comments, and splicing over the whole range deleted them. Same
+ mistake the block path's walk-back exists to avoid, on a path that did not
+ inherit the rule, and invisible to ``verify`` because the document is
+ identical either way.
+ """
+ from repowise.cli.agent_targets.formats import yaml_merge
+
+ merged = yaml_merge.set_child(
+ "mcp_servers: {}\n\n# ---- model settings, do not remove ----\nmodel: a\n",
+ "mcp_servers",
+ "repowise",
+ {"command": "x"},
+ )
+
+ assert "# ---- model settings, do not remove ----" in merged
+ assert yaml_merge.load_mapping(merged) == {
+ "mcp_servers": {"repowise": {"command": "x"}},
+ "model": "a",
+ }
+
+
+def test_yaml_merge_does_not_read_a_hash_inside_an_inline_value_as_a_comment() -> None:
+ """``#`` inside a plain scalar is data, and a nearby helper cannot tell.
+
+ The scalar-line helper guards only against quoting, so given
+ ``{a: {args: [-c, foo#bar]}}`` it returned ``#bar]}}`` and wrote that
+ fragment of the user's own config into their file as a comment on the
+ section header. The document is unchanged, so nothing downstream noticed.
+ """
+ from repowise.cli.agent_targets.formats import yaml_merge
+
+ merged = yaml_merge.set_child(
+ "mcp_servers: {a: {command: sh, args: [-c, foo#bar]}}\n",
+ "mcp_servers",
+ "repowise",
+ {"command": "x"},
+ )
+
+ # Exactly one hash survives, the one that is part of the user's argument.
+ # A second means a fragment of their value was copied out into a comment.
+ assert merged.count("#") == 1
+ assert "#bar]}}" not in merged.replace("foo#bar", "")
+ assert yaml_merge.load_mapping(merged) == {
+ "mcp_servers": {
+ "a": {"command": "sh", "args": ["-c", "foo#bar"]},
+ "repowise": {"command": "x"},
+ }
+ }
+
+ # A real trailing comment survives, including one that mentions a bracket.
+ # Searching backwards from the last bracket looks like the same answer and
+ # reads the brace in "e.g. {a: b}" as the end of the value, throwing the
+ # comment away, so both limbs are here.
+ for comment in ("# my servers", "# e.g. {name: {command: x}}", "# note with ] bracket"):
+ kept = yaml_merge.set_child(
+ f"mcp_servers: {{}} {comment}\n",
+ "mcp_servers",
+ "repowise",
+ {"command": "x"},
+ )
+ assert comment in kept
+
+
+def test_yaml_merge_finds_the_comment_boundary_the_way_the_parser_does() -> None:
+ """Three hand-written rules were tried and each was wrong its own way.
+
+ An apostrophe in a plain scalar is the case that defeats a quote tracker:
+ ``note: don't`` leaves it stuck open, every bracket after it is miscounted,
+ and the next hash in the data is returned as a comment. Which way it then
+ goes is a coin toss, so both are pinned here: a fragment of the value must
+ never be copied out into a comment, and a real comment must never be lost.
+ """
+ from repowise.cli.agent_targets.formats import yaml_merge
+
+ def merged(line: str) -> str:
+ return yaml_merge.set_child(
+ line + "\n", "mcp_servers", "repowise", {"command": "R"}
+ )
+
+ # No comment here at all: the hash lives inside a quoted scalar.
+ fragment = merged("mcp_servers: {a: don't, b: 'x}y # z'}")
+ assert "#" not in fragment.replace("# z", "")
+ assert yaml_merge.load_mapping(fragment)["mcp_servers"]["b"] == "x}y # z"
+
+ # A real comment survives an apostrophe, and an escaped quote, before it.
+ for line in (
+ "mcp_servers: {a: {command: gh, args: [don't]}} # keep me",
+ 'mcp_servers: {a: {command: "a\\"b"}} # keep me',
+ ):
+ assert "# keep me" in merged(line)
+
+
+def test_yaml_merge_refuses_a_wrapped_value_holding_a_comment() -> None:
+ """A wrapped value is re-rendered onto one line, so a comment inside it has
+ nowhere to go. Only the one following the value is recoverable, so rather
+ than eat the rest the value is left alone. The uncommented wrapped case is
+ the common one and still works.
+ """
+ from repowise.cli.agent_targets.formats import yaml_merge
+
+ commented = (
+ "mcp_servers: {github: {command: gh}, # first server\n"
+ " other: {command: o}}\n"
+ "model: a\n"
+ )
+ assert (
+ yaml_merge.set_child(commented, "mcp_servers", "repowise", {"command": "R"})
+ == commented
+ )
+
+
+def test_yaml_merge_matches_a_quoted_key_at_both_levels() -> None:
+ """Teaching one of the two searches about quoting was worse than neither.
+
+ The child search learned it first, and the parent search left behind sent a
+ quoted section down the append path, where the block it added was a
+ duplicate key and the write then refused for good.
+ """
+ from repowise.cli.agent_targets.formats import yaml_merge
+
+ for spelling in ('"mcp_servers"', "'mcp_servers'"):
+ merged = yaml_merge.set_child(
+ f"{spelling}:\n github:\n command: gh\n",
+ "mcp_servers",
+ "repowise",
+ {"command": "R"},
+ )
+ assert merged.count("mcp_servers") == 1
+ assert sorted(yaml_merge.load_mapping(merged)["mcp_servers"]) == [
+ "github",
+ "repowise",
+ ]
+
+
+def test_yaml_merge_handles_an_inline_value_that_wraps_across_lines() -> None:
+ """The shortest slice that parses is the value.
+
+ An unbalanced flow collection does not parse, so the first slice that does
+ is the whole of it. Reading only the first line looks equivalent and turns
+ a wrapped value from a working install into a permanent refusal.
+ """
+ from repowise.cli.agent_targets.formats import yaml_merge
+
+ merged = yaml_merge.set_child(
+ "mcp_servers: {github: {command: gh},\n other: {command: o}}\nmodel: a\n",
+ "mcp_servers",
+ "repowise",
+ {"command": "x"},
+ )
+
+ assert yaml_merge.load_mapping(merged) == {
+ "mcp_servers": {
+ "github": {"command": "gh"},
+ "other": {"command": "o"},
+ "repowise": {"command": "x"},
+ },
+ "model": "a",
+ }
+
+
+def test_yaml_merge_refuses_an_inline_value_carrying_an_anchor() -> None:
+ """Adding a child re-renders the whole inline value, and anchors do not survive.
+
+ The dumper writes them back under generated names, so a factoring the user
+ wrote is replaced by ``&id001``. Everything else re-rendering normalises is
+ cosmetic; this one is the damage the module refuses to do to a whole file,
+ so it refuses it here too.
+ """
+ from repowise.cli.agent_targets.formats import yaml_merge
+
+ original = "mcp_servers: {a: &base {command: gh}, b: *base}\n"
+ assert (
+ yaml_merge.set_child(original, "mcp_servers", "repowise", {"command": "x"})
+ == original
+ )
+
+ # A star inside an ordinary scalar is not an alias and must not be refused.
+ shell = "mcp_servers: {a: {command: sh, args: [-c, 'ls *']}}\n"
+ merged = yaml_merge.set_child(shell, "mcp_servers", "repowise", {"command": "x"})
+ assert "repowise" in yaml_merge.load_mapping(merged)["mcp_servers"]
+
+
+def test_hermes_uninstall_declines_when_the_splice_missed(hermes_home: Path) -> None:
+ """A removal that changed nothing must never report ``removed``.
+
+ ``remove_child`` reports what it did, and reporting it by re-parsing its own
+ output looks like the same answer: the caller feeds that value straight into
+ the document it hands ``verify``, so both sides came from one parse of one
+ string and the check could not fail. It then reported ``removed`` over a
+ file that still held the entry, leaving repowise registered.
+
+ The shape here is a repeated top-level key. The parser keeps the last, so
+ the entry is genuinely registered, while the line search finds the first and
+ edits a block the document does not use.
+ """
+ original = (
+ "mcp_servers:\n"
+ " other:\n"
+ " command: y\n"
+ "mcp_servers:\n"
+ " repowise:\n"
+ " command: x\n"
+ )
+ config = _seed(hermes_home, original)
+
+ result = get_target("hermes").uninstall(Scope.USER)
+
+ assert [written.action for written in result.files] == [FileAction.KEPT]
+ assert config.read_bytes() == original.encode("utf-8")
+
+
+def test_hermes_updates_a_quoted_key_in_place(hermes_home: Path) -> None:
+ """Quoting a mapping key is ordinary YAML, and matching only the bare form
+ was wrong in both directions: the write appended a second entry beside the
+ quoted one, leaving a duplicate key the parser silently resolves to the
+ last, and the removal then found neither and declined for good.
+ """
+ import yaml
+
+ config = _seed(
+ hermes_home,
+ 'mcp_servers:\n "repowise":\n command: old\n env:\n K: v\nmodel: a\n',
+ )
+ target = get_target("hermes")
+
+ target.install(Scope.USER)
+ text = config.read_text(encoding="utf-8")
+ assert text.count("repowise:") == 1
+ entry = yaml.safe_load(text)["mcp_servers"]["repowise"]
+ assert entry["command"] != "old"
+ assert entry["env"] == {"K": "v"}
+
+ assert [written.action for written in target.install(Scope.USER).files] == [
+ FileAction.UNCHANGED
+ ]
+ assert [written.action for written in target.uninstall(Scope.USER).files] == [
+ FileAction.REMOVED
+ ]
+ assert "repowise" not in config.read_text(encoding="utf-8")
+
+
+def test_yaml_merge_removes_a_child_from_an_inline_parent() -> None:
+ """The mirror of the inline write, and it has to exist for the same reason.
+
+ Teaching the write path about inline parents and leaving removal behind
+ meant the child search looked for a line that is not on a line of its own,
+ found nothing, reported the parent unchanged, and uninstall then failed its
+ own consistency check and left the entry in place. An emptied inline parent
+ comes back as ``{}``, which is what it was before the install.
+ """
+ from repowise.cli.agent_targets.formats import yaml_merge
+
+ text, section = yaml_merge.remove_child(
+ "mcp_servers: {github: {command: gh}, repowise: {command: x}}\n",
+ "mcp_servers",
+ "repowise",
+ )
+ assert text == "mcp_servers: {github: {command: gh}}\n"
+ assert section == {"github": {"command": "gh"}}
+
+ emptied, section = yaml_merge.remove_child(
+ "mcp_servers: {repowise: {command: x}}\n", "mcp_servers", "repowise"
+ )
+ assert emptied == "mcp_servers: {}\n"
+ assert section == {}
+
+
+def test_yaml_merge_leaves_a_deeper_comment_with_the_child_it_documents() -> None:
+ """A comment indented past the children belongs to the one above it.
+
+ Stepping over it moves the user's note inside our block, where it reads as
+ documenting our entry. The same indent rule keeps a ``#`` line that is
+ *content* rather than a comment, a literal inside a ``key: |`` block
+ scalar, from being stepped over at all, which truncated the scalar.
+ """
+ from repowise.cli.agent_targets.formats import yaml_merge
+
+ kept = yaml_merge.set_child(
+ "mcp_servers:\n github:\n command: gh\n # note about github\nmodel: a\n",
+ "mcp_servers",
+ "repowise",
+ {"command": "x"},
+ )
+ lines = kept.splitlines()
+ assert lines.index(" # note about github") < lines.index(" repowise:")
+
+ scalar = yaml_merge.set_child(
+ "mcp_servers:\n desc: |\n # literal text\nmodel: a\n",
+ "mcp_servers",
+ "repowise",
+ {"command": "x"},
+ )
+ assert yaml_merge.load_mapping(scalar)["mcp_servers"]["desc"] == "# literal text\n"
+
+
+def test_yaml_merge_appends_above_a_comment_introducing_the_next_section() -> None:
+ """The parent's range runs to the next top-level key, heading included.
+
+ Stopping at the first blank line puts our entry below the user's section
+ heading, which indents their title into our block and leaves the section it
+ introduced without it. The document is unchanged either way, so ``verify``
+ is structurally blind to this one.
+ """
+ from repowise.cli.agent_targets.formats import yaml_merge
+
+ merged = yaml_merge.set_child(
+ "mcp_servers:\n foo:\n command: x\n\n# ---- model settings ----\nmodel: a\n",
+ "mcp_servers",
+ "repowise",
+ {"command": "y"},
+ )
+
+ lines = merged.splitlines()
+ assert lines.index(" repowise:") < lines.index("# ---- model settings ----")
+ assert lines.index("# ---- model settings ----") == lines.index("model: a") - 1
+
+
+def test_yaml_merge_keeps_a_comment_on_the_line_it_replaces() -> None:
+ """Replacing a child replaces its whole first line, comment included.
+
+ Recovering it is conservative: a ``#`` inside a quoted scalar is not a
+ comment, and moving a fragment of the user's data into one is a worse
+ outcome than losing a comment in a rare shape.
+ """
+ from repowise.cli.agent_targets.formats import yaml_merge
+
+ kept = yaml_merge.set_child(
+ "platform_toolsets:\n cli: [hermes-cli] # deliberately an allowlist\n",
+ "platform_toolsets",
+ "cli",
+ ["hermes-cli", "repowise"],
+ )
+ assert "# deliberately an allowlist" in kept
+ assert yaml_merge.load_mapping(kept) == {
+ "platform_toolsets": {"cli": ["hermes-cli", "repowise"]}
+ }
+
+ quoted = yaml_merge.set_child(
+ 'platform_toolsets:\n cli: ["a#b"]\n', "platform_toolsets", "cli", ["x"]
+ )
+ assert "#" not in quoted
+ assert yaml_merge.load_mapping(quoted) == {"platform_toolsets": {"cli": ["x"]}}
+
+
+def test_yaml_merge_keeps_an_inline_list_inline_and_still_findable() -> None:
+ """Editing one item of a user's inline list gives back an inline list.
+
+ The second assertion is the one that matters, and it is the defect this
+ pins: rendering the *pair* in flow style produces ``{cli: [a, b]}``, which
+ is valid YAML and the right document, so nothing downstream complains --
+ but the key is then inside a flow mapping where the line-based search
+ cannot find it, and the next edit appends a second copy rather than
+ replacing it. Uninstall is where that surfaces, as a removal that silently
+ does nothing.
+ """
+ from repowise.cli.agent_targets.formats import yaml_merge
+
+ text = "platform_toolsets:\n cli: [hermes-cli, othersrv]\n"
+ added = yaml_merge.set_child(
+ text, "platform_toolsets", "cli", ["hermes-cli", "othersrv", "repowise"]
+ )
+ assert " cli: [hermes-cli, othersrv, repowise]\n" in added
+ assert "{cli:" not in added
+
+ # The round trip has to land back on the exact bytes, which only holds if
+ # the edited line is still reachable.
+ restored = yaml_merge.set_child(
+ added, "platform_toolsets", "cli", ["hermes-cli", "othersrv"]
+ )
+ assert restored == text
diff --git a/tests/unit/cli/test_agents_cmd.py b/tests/unit/cli/test_agents_cmd.py
index 1bdd5700c..88715d8cb 100644
--- a/tests/unit/cli/test_agents_cmd.py
+++ b/tests/unit/cli/test_agents_cmd.py
@@ -76,6 +76,7 @@ def test_bare_agents_lists_every_registered_target_as_json(repo: Path) -> None:
"vscode",
"cursor",
"opencode",
+ "hermes",
]
for row in payload["agents"]:
# The keys the table renders, so a dropped one is a broken table.
@@ -355,6 +356,7 @@ def test_doctor_reports_one_row_per_agent_from_its_own_descriptor(repo: Path) ->
"Agent: vscode",
"Agent: cursor",
"Agent: opencode",
+ "Agent: hermes",
]
# Nothing is wired on a clean machine, and an agent you do not use is not a
# problem with your setup.