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(cli): add a repowise agents command group (#1448)

Raghav Chamadiyad65f89afe1cf
diff --git a/packages/cli/src/repowise/cli/agent_targets/formats/json_merge.py b/packages/cli/src/repowise/cli/agent_targets/formats/json_merge.py
index 160968524..994ffc7f4 100644
--- a/packages/cli/src/repowise/cli/agent_targets/formats/json_merge.py
+++ b/packages/cli/src/repowise/cli/agent_targets/formats/json_merge.py
@@ -31,6 +31,8 @@ from typing import Any
import click
+from ..types import FileAction
+
def load_json_object(config_path: Path) -> dict:
"""Read a JSON object, refusing to silently replace bad content.
@@ -71,15 +73,45 @@ def load_json_object_or_value_error(config_path: Path, label: str) -> dict:
return existing
+def is_damaged(config_path: Path) -> bool:
+ """True when *config_path* is present but is not readable JSON.
+
+ The distinction a health check lives on. A config that is absent and a
+ config that is there and unparseable both make every "is repowise wired
+ up" probe answer no, and telling the user "not installed" when the truth is
+ "your settings file has a trailing comma in it" sends them to run an
+ install that will refuse for the same reason.
+
+ False for a file that is absent or that cannot be opened at all: neither is
+ damage we can claim to have seen.
+ """
+ if not config_path.exists():
+ return False
+ try:
+ json.loads(config_path.read_text(encoding="utf-8"))
+ except json.JSONDecodeError:
+ return True
+ except OSError:
+ return False
+ return False
+
+
def json_deep_equal(left: Any, right: Any) -> bool:
"""Deep equality that ignores mapping key order.
Python's ``==`` on dicts already ignores key order, so this exists for the
case ``==`` gets wrong for our purpose: it is the check that decides whether
a write is needed at all, and it has to walk nested structures without being
- fooled by a list/dict type coincidence. Used to return
- :attr:`~..types.FileAction.UNCHANGED` instead of rewriting a file whose
- bytes would not move.
+ fooled by a numeric-tower or bool/int coincidence.
+
+ Its caller is the **TOML** path, not the JSON one, which is worth saying
+ plainly. JSON configs are rendered from a dict every time, so comparing the
+ rendered text answers "would this write move the file" exactly. The TOML
+ merge rewrites the source text and re-appends the table it owns, so the text
+ legitimately differs on a re-run while the *document* is identical —
+ comparing documents is the only way to see that the write is a no-op. It
+ lives here rather than in ``toml_merge`` because the structure it walks is
+ the JSON data model, which is what ``tomllib`` hands back.
"""
# Strict on type, including across the numeric tower. The contract is "the
# bytes would not move", and ``json.dumps`` renders 1 and 1.0 differently,
@@ -103,20 +135,6 @@ def dumps_config(data: dict) -> str:
return json.dumps(data, indent=2) + "\n"
-def backup_unparseable(config_path: Path) -> Path | None:
- """Copy an unparseable file to ``<path>.backup`` before it is overwritten.
-
- Only for paths where the caller intends to overwrite regardless. Where the
- caller can decline instead, declining is better and this is not used.
- """
- backup = config_path.with_suffix(config_path.suffix + ".backup")
- try:
- backup.write_bytes(config_path.read_bytes())
- return backup
- except OSError:
- return None
-
-
def atomic_write_text(path: Path, content: str, *, newline: str | None = None) -> None:
"""Write *content* atomically, preserving what a plain write would preserve.
@@ -158,9 +176,39 @@ def atomic_write_text(path: Path, content: str, *, newline: str | None = None) -
os.chmod(target, mode)
-def write_json_config(path: Path, data: dict) -> None:
- """Atomically write *data* in the repo's standard JSON config shape."""
- atomic_write_text(path, dumps_config(data))
+def write_json_config(path: Path, data: dict) -> FileAction:
+ """Atomically write *data*, skipping the write when it would change nothing.
+
+ Returns without writing when the file already holds exactly the bytes this
+ call would produce, so a re-run reports
+ :attr:`~..types.FileAction.UNCHANGED` instead of an update it did not make.
+
+ The comparison is against the *translated* rendering, not the raw one.
+ :func:`atomic_write_text` passes ``newline=None`` here, so on Windows this
+ writer emits ``\\r\\n`` where :func:`dumps_config` produced ``\\n``.
+ Comparing the untranslated text would call every Windows re-run an update;
+ normalising the file's line endings instead would go wrong the other way —
+ a CRLF file on POSIX would compare equal and be left alone, where the
+ unconditional write used to normalise it. Same trap as the marker block's,
+ and the same answer: compare the bytes that would actually land.
+
+ Byte-exact, so this is a narrower promise than "the data is already right":
+ a file someone reindented, or whose top-level keys sit in another order,
+ holds the same data and is still rewritten. That matches what the
+ unconditional write did before and is the conservative direction — the
+ action stays truthful either way, and the alternative is deciding that a
+ file we would rewrite is "unchanged".
+ """
+ rendered = dumps_config(data)
+ action = FileAction.CREATED
+ if path.exists():
+ action = FileAction.UPDATED
+ on_disk = rendered.replace("\n", os.linesep) if os.linesep != "\n" else rendered
+ with contextlib.suppress(OSError):
+ if path.read_bytes() == on_disk.encode("utf-8"):
+ return FileAction.UNCHANGED
+ atomic_write_text(path, rendered)
+ return action
def merge_server_entries(servers: dict, new_entry: dict) -> dict:
diff --git a/packages/cli/src/repowise/cli/agent_targets/formats/marker_block.py b/packages/cli/src/repowise/cli/agent_targets/formats/marker_block.py
index 82d5b96e9..b2affdbea 100644
--- a/packages/cli/src/repowise/cli/agent_targets/formats/marker_block.py
+++ b/packages/cli/src/repowise/cli/agent_targets/formats/marker_block.py
@@ -12,10 +12,11 @@ and frequently committed, so letting them take the platform translation would
mean the same command produces a different file on Windows than on macOS and
the diff churns on every cross-platform edit.
-Also reports the two malformed states worth naming rather than silently
-repairing, because both mean a user edited inside the block and one of them
-loses data if you guess: an orphan marker (a start with no end, or the reverse)
-and a duplicated block.
+Both malformed states — an orphan marker, and a duplicated block — are named
+rather than guessed at, and both are refused rather than repaired. They mean a
+user edited across one of our markers, and no repair for either is safe. See
+:func:`upsert` for why, including why collapsing a duplicate is not the easy
+win it looks like.
"""
from __future__ import annotations
@@ -25,6 +26,7 @@ from dataclasses import dataclass
from enum import StrEnum
from pathlib import Path
+from ..types import FileAction
from .json_merge import atomic_write_text
@@ -49,10 +51,6 @@ class BlockInspection:
#: Body between the markers for the first block found, markers excluded.
body: str | None = None
- @property
- def is_healthy(self) -> bool:
- return self.state in (BlockState.PRESENT, BlockState.ABSENT, BlockState.ABSENT_FILE)
-
def inspect(path: Path, start: str, end: str) -> BlockInspection:
"""Report what *path* holds for the ``start``/``end`` marker pair."""
@@ -85,12 +83,13 @@ def upsert(
end: str,
*,
new_file_prefix: str = "",
-) -> bool:
- """Ensure *path* carries exactly ``start + body + end``.
+) -> FileAction:
+ """Ensure *path* carries exactly one well-formed ``start + body + end``.
- Replaces an existing block in place, or appends one after existing content.
- Returns True when the file changed, so a caller can report ``unchanged``
- for a re-run rather than claiming an update it did not make.
+ Replaces an existing block in place, appends one after existing content, or
+ collapses a duplicated pair down to the first. Returns the action it took,
+ so a caller can report ``unchanged`` for a re-run rather than claiming an
+ update it did not make.
*new_file_prefix* is written above the block when the file did not exist —
a header telling the reader this file is theirs and only the marked section
@@ -103,27 +102,43 @@ def upsert(
contain either, and the failure mode is a corrupted managed block or a
``bad escape`` crash at install time.
- **Known gap, carried over deliberately.** Against a malformed pair this does
- the wrong thing quietly: an orphaned start marker matches ``start in
- existing`` but not the regex, so nothing is written and it reports
- ``False`` — "unchanged" while the block is in fact absent — and a duplicated
- block is rewritten in both places rather than collapsed. :func:`inspect`
- exists to name both states and this function does not yet consult it. The
- hand-rolled writer this replaced had the identical blind spot, so preserving
- it keeps the rewrite behaviour-neutral; it should be closed before Phase 5
- adds targets that inherit this helper.
+ **A malformed marker pair returns** :attr:`~..types.FileAction.KEPT` **and
+ writes nothing.** Both malformed states mean a user edited across one of our
+ markers, and for both, every available repair can destroy text:
+
+ * An **orphan** — a start with no end. Appending a fresh block leaves the
+ stray start above it, so the next run's non-greedy ``start.*?end`` spans
+ from the orphan to *our* end marker and swallows whatever the user wrote
+ in between.
+ * A **duplicate**. It is tempting to collapse to the first copy on the
+ grounds that every copy is ours, and that is exactly the assumption that
+ does not hold: :func:`inspect` counts marker occurrences, so a file
+ containing one real block *plus a sentence that quotes both markers*
+ reads as duplicated. Collapsing deletes the sentence. Rewriting each
+ match in place — what the hand-rolled writer this replaced did — mangles
+ it instead. Neither is a repair.
+
+ So both are refused, and the caller surfaces it as something to unpick by
+ hand. What this fixes relative to that hand-rolled writer is the *silence*:
+ an orphan used to report "unchanged" while the block was in fact absent.
"""
wrapped = f"{start}{body}{end}"
- if not path.exists():
- atomic_write_text(path, f"{new_file_prefix}\n{wrapped}\n" if new_file_prefix else wrapped + "\n", newline="\n")
- return True
+ inspection = inspect(path, start, end)
+
+ if inspection.state in (BlockState.ORPHANED, BlockState.DUPLICATED):
+ return FileAction.KEPT
+
+ if inspection.state is BlockState.ABSENT_FILE:
+ opening = f"{new_file_prefix}\n{wrapped}\n" if new_file_prefix else f"{wrapped}\n"
+ atomic_write_text(path, opening, newline="\n")
+ return FileAction.CREATED
existing = path.read_text(encoding="utf-8")
- if start in existing:
- pattern = re.escape(start) + r".*?" + re.escape(end)
- content = re.sub(pattern, lambda _m: wrapped, existing, flags=re.DOTALL)
- else:
+ if inspection.state is BlockState.ABSENT:
content = existing.rstrip() + "\n\n" + wrapped + "\n"
+ else:
+ pattern = re.escape(start) + r".*?" + re.escape(end)
+ content = re.sub(pattern, lambda _m: wrapped, existing, count=1, flags=re.DOTALL)
# Compare *bytes*, not the decoded text. ``read_text`` collapses CRLF to LF
# in memory, so a CRLF file whose block is already current compares equal to
@@ -131,9 +146,9 @@ def upsert(
# leave the file CRLF, where an unconditional write normalised it. That is a
# whole-file diff on any Windows checkout with ``core.autocrlf=true``.
if content.encode("utf-8") == path.read_bytes():
- return False
+ return FileAction.UNCHANGED
atomic_write_text(path, content, newline="\n")
- return True
+ return FileAction.UPDATED
def remove(path: Path, start: str, end: str, *, delete_if_only: str | None = None) -> bool:
@@ -144,16 +159,24 @@ def remove(path: Path, start: str, end: str, *, delete_if_only: str | None = Non
deleted, so install then uninstall round-trips back to "no file" rather
than leaving a stub nobody asked for.
+ Refuses a malformed pair for exactly the reasons :func:`upsert` does, and
+ it has to: this strips *every* ``start.*?end`` span, so against one real
+ block plus a sentence quoting both markers it deletes the middle of the
+ sentence. That is the same file shape ``upsert`` refuses, so guarding only
+ the write half would have left ``hook rewrite uninstall`` and
+ ``agents remove`` eating the user's words.
+
Returns True when something was removed.
"""
- if not path.exists():
+ inspection = inspect(path, start, end)
+ if inspection.state in (BlockState.ORPHANED, BlockState.DUPLICATED):
+ return False
+ if inspection.state in (BlockState.ABSENT_FILE, BlockState.ABSENT):
return False
try:
existing = path.read_text(encoding="utf-8")
except OSError:
return False
- if start not in existing:
- return False
pattern = r"\n*" + re.escape(start) + r".*?" + re.escape(end) + r"\n?"
remaining = re.sub(pattern, "", existing, flags=re.DOTALL)
diff --git a/packages/cli/src/repowise/cli/agent_targets/formats/observe.py b/packages/cli/src/repowise/cli/agent_targets/formats/observe.py
new file mode 100644
index 000000000..b355bd7d2
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/formats/observe.py
@@ -0,0 +1,37 @@
+"""Deriving a file action by watching a writer you do not own.
+
+The other helpers here decide *whether* to write and report what they did. This
+one is for the writes that go through ``editor_integrations`` instead —
+``install_claude_code_hooks``, ``install_codex_rewrite_hook`` and friends, which
+carry years of settings-shape migrations and hand back a path rather than an
+action.
+
+Threading an action out through all of that would mean reopening code whose
+whole value is that it already handles the legacy shapes. Reading the file
+either side of the call answers the same question from outside, and it composes:
+three writers touching one settings file fold into a single honest entry rather
+than three rows for one path.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from ..types import FileAction
+
+
+def read_bytes(path: Path) -> bytes | None:
+ """The file's current bytes, or None when it is not there or unreadable."""
+ try:
+ return path.read_bytes()
+ except OSError:
+ return None
+
+
+def observed_action(before: bytes | None, after: bytes | None) -> FileAction:
+ """What happened to a file, from its bytes either side of a write."""
+ if after is None:
+ return FileAction.NOT_FOUND if before is None else FileAction.REMOVED
+ if before is None:
+ return FileAction.CREATED
+ return FileAction.UNCHANGED if before == after else FileAction.UPDATED
diff --git a/packages/cli/src/repowise/cli/agent_targets/formats/toml_merge.py b/packages/cli/src/repowise/cli/agent_targets/formats/toml_merge.py
index c6b2d76eb..efbaca917 100644
--- a/packages/cli/src/repowise/cli/agent_targets/formats/toml_merge.py
+++ b/packages/cli/src/repowise/cli/agent_targets/formats/toml_merge.py
@@ -15,12 +15,11 @@ re-parsed before it is written: a user who spelled the same key differently
would produce a duplicate-key file. Re-parsing turns each of those into a clean
abort with the original file untouched.
-Known wart, preserved deliberately for now: upserting a table strips it from
-wherever it sat and re-appends it at the end, so two upserts in sequence swap
-the two tables' order and leave a blank line at the top on the second run. It is
-cosmetic, it settles after one run, and the baseline test records it by name.
-Fixing it belongs with the deep-equal-before-write pass, not here, so that the
-byte-level oracle has one thing to compare against at a time.
+Upserting a table strips it from wherever it sat and re-appends it at the end,
+so two upserts in sequence swap the two tables' order and the second run
+produces different bytes for an identical document. :func:`write_if_changed` is
+what stops that from reaching disk: it compares parsed documents rather than
+text, so a re-run that would only reshuffle writes nothing at all.
"""
from __future__ import annotations
@@ -32,14 +31,27 @@ from pathlib import Path
import click
+from ..types import FileAction
+from .json_merge import json_deep_equal
+
def toml_value(value: object) -> str:
- """Encode a scalar or string list as TOML.
+ """Encode a scalar, list or inline table as TOML.
Strings go through ``json.dumps``, whose escaping for basic strings is
- TOML-compatible. Anything outside the handful of types our tables hold
- raises, because a silent wrong encoding in a config file is far more
- expensive to diagnose than a crash here.
+ TOML-compatible. Anything outside the types handled here raises, because a
+ silent wrong encoding in a config file is far more expensive to diagnose
+ than a crash.
+
+ Dicts render as **inline tables**, which is what makes preserving a user's
+ keys possible at all: the one key a Codex MCP server entry is most likely
+ to carry beyond ours is ``env``, and ``env`` is a table. Writing a whole
+ generated table means re-rendering everything already in it, so a type this
+ cannot encode is not a hypothetical — it is the standard case. Nested
+ inline tables are legal TOML and the recursion produces them.
+
+ Floats are handled for the same reason: they cost one line, and a timeout
+ someone wrote as ``1.5`` is not an exotic thing to find in a config file.
"""
if isinstance(value, bool):
return "true" if value else "false"
@@ -47,6 +59,11 @@ def toml_value(value: object) -> str:
return json.dumps(value)
if isinstance(value, int):
return str(value)
+ if isinstance(value, float):
+ return repr(value)
+ if isinstance(value, dict) and all(isinstance(key, str) for key in value):
+ rendered = ", ".join(f"{key} = {toml_value(item)}" for key, item in value.items())
+ return f"{{ {rendered} }}" if rendered else "{}"
if isinstance(value, list) and all(isinstance(item, str) for item in value):
return f"[{', '.join(json.dumps(item) for item in value)}]"
raise TypeError(f"Unsupported TOML value: {value!r}")
@@ -59,10 +76,17 @@ def table_block(table_name: str, values: dict[str, object]) -> str:
return "\n".join(lines)
-def ensure_valid_toml(merged_text: str, config_path: Path) -> None:
- """Abort before writing if the regex merge produced invalid TOML."""
+def ensure_valid_toml(merged_text: str, config_path: Path) -> dict:
+ """Abort before writing if the regex merge produced invalid TOML.
+
+ Returns the parsed result, because every caller wants it: the parse has to
+ happen anyway to validate, and the document it produces is what
+ :func:`write_if_changed` compares against to decide whether the write is a
+ no-op. Parsing twice to keep the return type ``None`` would be paying for
+ the same work to throw it away.
+ """
try:
- tomllib.loads(merged_text)
+ return tomllib.loads(merged_text)
except tomllib.TOMLDecodeError as exc:
raise click.ClickException(
f"Cannot update {config_path}: merging the repowise entry would produce "
@@ -106,3 +130,35 @@ def replace_table(existing_text: str, table_name: str, block: str) -> str:
)
merged_text = table_re.sub("", existing_text).rstrip()
return f"{merged_text}\n\n{block}\n" if merged_text else f"{block}\n"
+
+
+def write_if_changed(
+ config_path: Path,
+ merged_text: str,
+ merged_doc: dict,
+ existing_doc: dict | None,
+) -> FileAction:
+ """Write *merged_text* only when it would change what the file means.
+
+ The comparison is between **documents**, not text, and that is the whole
+ point. :func:`replace_table` strips the table it owns and re-appends it at
+ the end, so upserting two tables in sequence swaps their order and the
+ second run produces different bytes for an identical document. Comparing
+ text would call that an update, write it, and swap them back — which is
+ exactly the drift ``.codex/config.toml`` accumulated on every second
+ ``init`` before this check existed.
+
+ *existing_doc* is ``None`` when the file is new.
+
+ One consequence worth naming: because the check is on meaning rather than
+ bytes, a file that already says the right thing is left exactly as the user
+ has it — including its line endings, which the old unconditional rewrite
+ would have normalised. Leaving a user's config untouched is the better
+ default, and nothing downstream reads this file's newlines.
+ """
+ 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
+ config_path.parent.mkdir(parents=True, exist_ok=True)
+ config_path.write_text(merged_text, encoding="utf-8")
+ 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 c8f22e37f..7c7d685c7 100644
--- a/packages/cli/src/repowise/cli/agent_targets/registry.py
+++ b/packages/cli/src/repowise/cli/agent_targets/registry.py
@@ -20,7 +20,7 @@ from __future__ import annotations
import importlib
from pathlib import Path
-from .types import AgentTarget, Registration, Scope, Tier, derive_tier
+from .types import AgentTarget, InstallMethod, Registration, Tier, derive_tier
#: Every known target, by id. Values are ``module:attribute`` so registration
#: costs no import.
@@ -80,6 +80,104 @@ def detect_all(repo_path: Path | None = None) -> dict[str, list[Registration]]:
return found
+def describe_agents(repo_path: Path | None = None) -> list[dict]:
+ """One row per registered target: what it is, and where it is wired.
+
+ The projection both consumers read — ``repowise agents``' JSON payload and
+ table, and ``init``'s checklist. Built here, next to the descriptors, so
+ there is one answer to "what do we know about this agent" rather than one
+ per caller that drift into disagreeing about which are pre-ticked.
+
+ Every probe is best-effort: a descriptor whose detection or presence check
+ raises is reported as absent rather than taking the listing down.
+ """
+ rows: list[dict] = []
+ for target in all_targets():
+ try:
+ registrations = list(target.detect(repo_path))
+ except Exception:
+ registrations = []
+ try:
+ present = bool(target.is_present(repo_path))
+ except Exception:
+ present = False
+ #: None here means "already provided by a host-managed install", which
+ #: is the stand-down the method axis exists for — not "cannot install".
+ method = select_install_method(target, registrations)
+ rows.append(
+ {
+ "id": target.id,
+ "display_name": target.display_name,
+ "tier": tier_of(target.id).value,
+ "docs_url": target.docs_url,
+ "project_file_id": target.project_file_id,
+ "present": present,
+ "method": method.id if method is not None else None,
+ "registrations": [r.as_dict() for r in registrations],
+ }
+ )
+ return rows
+
+
+def default_selection(rows: list[dict]) -> set[str]:
+ """Which agents to pre-tick, given :func:`describe_agents` rows.
+
+ Wired agents, installed agents, and :data:`_AUTO_FALLBACK` — always, not as
+ a last resort.
+
+ That "always" is the whole point and it is easy to get wrong: unioning in
+ ``resolve_target_flag("auto")`` instead *looks* equivalent and is a no-op,
+ because ``auto`` resolves to the detected targets and only reaches the
+ fallback when detection is empty — which is exactly the case the union was
+ already handling. A repo with a committed ``.codex/config.toml`` on a
+ machine with no ``~/.claude`` still produced a non-empty selection with
+ Claude Code missing from it.
+
+ Why it matters that the fallback is unconditional: leaving an agent
+ unticked is not neutral. For the agent that owns the instruction file the
+ setup path persists the opt-out into ``.repowise/config.yaml``, so one
+ Enter turns off a file that used to default to on and ``update`` never
+ generates it again. **Detection decides what to offer; it must not silently
+ withdraw a default.**
+ """
+ chosen = {row["id"] for row in rows if row["registrations"] or row["present"]}
+ return chosen | {_AUTO_FALLBACK}
+
+
+def select_install_method(
+ target: AgentTarget,
+ registrations: list[Registration],
+) -> InstallMethod | None:
+ """The method to install *target* through, or None to stand down.
+
+ This is where the method axis pays for itself. Claude Code is reachable two
+ ways — its host plugin, and repowise writing the config directly — and both
+ register the same MCP server and the same augment hooks. The host merges
+ them without complaint, so the user gets no error, just two process spawns
+ per matched tool call and a duplicate set of tool schemas resident in every
+ session. Measured on a live machine: three repowise MCP servers at once,
+ ~36 tool schemas for one product.
+
+ So: when *registrations* show a host-managed method already in place, return
+ None. There is nothing for us to write, and writing anyway is how the
+ duplicate happens. Otherwise return the method marked ``preferred`` among
+ the ones repowise can actually write, falling back to the first of those.
+
+ Deliberately not applied by ``init``: standing down there would change what
+ a plugin user's ``init`` does today, and this decision is about cost rather
+ than correctness. ``agents add`` and ``agents refresh`` own it.
+ """
+ detected = {r.method for r in registrations}
+ writable = [m for m in target.methods if m.managed_by != "host"]
+ for method in target.methods:
+ if method.managed_by == "host" and method.id in detected:
+ return None
+ for method in writable:
+ if method.preferred:
+ return method
+ return writable[0] if writable else None
+
+
def resolve_target_flag(value: str, repo_path: Path | None = None) -> list[AgentTarget]:
"""Resolve a ``--target=`` value to targets.
@@ -122,8 +220,3 @@ def resolve_target_flag(value: str, repo_path: Path | None = None) -> list[Agent
f"Known: {known}, plus 'auto' / 'all' / 'none'."
)
return resolved
-
-
-def targets_for_scope(scope: Scope) -> list[AgentTarget]:
- """Every target that has a config home at *scope*."""
- return [target for target in all_targets() if target.supports_scope(scope)]
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py b/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py
index 1093c9363..ac41def33 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py
@@ -34,6 +34,7 @@ from ..types import (
DoctorReport,
DoctorStatus,
FileAction,
+ FileWrite,
InstallMethod,
Registration,
Scope,
@@ -108,7 +109,7 @@ def plugin_manifest_path() -> Path:
# ---------------------------------------------------------------------------
-def write_project_mcp_config(repo_path: Path) -> Path:
+def write_project_mcp_config(repo_path: Path) -> FileWrite:
"""Merge the repowise server into the repo-root ``.mcp.json``.
Repo-shared and frequently committed, so it keeps the bare ``repowise``
@@ -135,8 +136,7 @@ def write_project_mcp_config(repo_path: Path) -> Path:
else:
merged = {"mcpServers": new_entry}
- write_json_config(config_path, merged)
- return config_path
+ return FileWrite(path=config_path, action=write_json_config(config_path, merged))
# ---------------------------------------------------------------------------
@@ -236,6 +236,19 @@ class ClaudeCodeTarget:
def supports_scope(self, scope: Scope) -> bool:
return True
+ def is_present(self, repo_path: Path | None = None) -> bool:
+ """``~/.claude`` exists, or Claude Desktop's config directory does.
+
+ Claude Code creates ``~/.claude`` on first run and never removes it, so
+ its presence is the cheapest honest signal. Claude Desktop is checked
+ separately because it is a different product with the same brand and a
+ user can have either.
+ """
+ if (Path.home() / ".claude").is_dir():
+ return True
+ desktop = desktop_config_path()
+ return desktop is not None and desktop.parent.is_dir()
+
def detect(self, repo_path: Path | None = None) -> list[Registration]:
return detect(repo_path)
@@ -263,22 +276,33 @@ class ClaudeCodeTarget:
if scope is Scope.PROJECT:
if repo_path is None:
raise ValueError("project-scope install needs a repo_path")
- result.record(write_project_mcp_config(repo_path), FileAction.UPDATED)
+ written = write_project_mcp_config(repo_path)
+ result.record(written.path, written.action)
return result
if repo_path is None:
raise ValueError("user-scope registration needs a repo_path to point at")
- desktop = register_with_claude_desktop(repo_path)
- if desktop:
- result.record(desktop, FileAction.UPDATED)
- code = register_with_claude_code(repo_path)
- if code:
- result.record(code, FileAction.UPDATED)
- hooks = install_claude_code_hooks()
- if hooks:
- result.record(hooks, FileAction.UPDATED)
+ from ..formats.observe import observed_action, read_bytes
+
+ settings = settings_path()
+ desktop_path = desktop_config_path()
+ settings_before = read_bytes(settings)
+ desktop_before = read_bytes(desktop_path) if desktop_path is not None else None
+
+ register_with_claude_desktop(repo_path)
+ register_with_claude_code(repo_path)
+ install_claude_code_hooks()
enable_tool_search_in_claude_code()
+
+ # One entry per file, not one per call: three of the four calls above
+ # write settings.json, and reporting it three times says nothing a
+ # reader can act on.
+ result.record(settings, observed_action(settings_before, read_bytes(settings)))
+ if desktop_path is not None:
+ after = read_bytes(desktop_path)
+ if not (desktop_before is None and after is None):
+ result.record(desktop_path, observed_action(desktop_before, after))
return result
def uninstall(self, scope: Scope, *, repo_path: Path | None = None) -> WriteResult:
@@ -334,6 +358,27 @@ class ClaudeCodeTarget:
claude_code_rewrite_hook_matcher,
)
+ from ..formats.json_merge import is_damaged
+
+ # Checked before detection, because detection cannot tell an absent
+ # registration from one inside a file it could not parse — and
+ # reporting "not installed" for a settings file with a trailing comma
+ # sends the user to run an install that refuses for the same reason.
+ settings = settings_path()
+ if is_damaged(settings):
+ return DoctorReport(
+ target_id=ID,
+ status=DoctorStatus.BROKEN,
+ issues=(
+ f"{settings} is not valid JSON, so Claude Code ignores all of it. "
+ "Fix or remove it, then re-register.",
+ ),
+ # `add`, not `refresh`. A file this damaged makes detection
+ # find nothing, and refresh only touches what it detects — so
+ # it would skip this target entirely and report success.
+ fix_command="repowise agents add --target=claude-code",
+ )
+
registrations = detect()
if not registrations:
return DoctorReport(
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 e441fd3bc..911451677 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
@@ -31,6 +31,7 @@ from ..types import (
DoctorReport,
DoctorStatus,
FileAction,
+ FileWrite,
InstallMethod,
Registration,
Scope,
@@ -135,41 +136,63 @@ def hooks_config() -> dict[str, object]:
# ---------------------------------------------------------------------------
-def write_server_config(repo_path: Path) -> Path:
+def write_server_config(repo_path: Path) -> FileWrite:
"""Merge the repowise server table into project-local ``.codex/config.toml``."""
+ import click
+
from ..formats.toml_merge import (
ensure_valid_toml,
load_toml_document,
replace_table,
require_table,
table_block,
+ write_if_changed,
)
config_path = project_config_path(repo_path)
- block = table_block("mcp_servers.repowise", server_table(repo_path))
if config_path.exists():
existing_text = config_path.read_text(encoding="utf-8")
- doc = load_toml_document(config_path, existing_text)
+ doc: dict | None = load_toml_document(config_path, existing_text)
else:
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(f"{block}\n", encoding="utf-8")
- return config_path
+ existing_text = ""
+ doc = None
# Both levels are checked before the regex runs: a scalar where a table
# belongs means the merge would produce a duplicate key, and refusing is
# the only answer that leaves the user's file intact.
- servers = require_table(doc, "mcp_servers", config_path, "mcp_servers")
- if servers is not None:
- require_table(servers, "repowise", config_path, "mcp_servers.repowise")
-
+ stored: dict[str, object] = {}
+ if doc is not None:
+ servers = require_table(doc, "mcp_servers", config_path, "mcp_servers")
+ if servers is not None:
+ stored = dict(require_table(servers, "repowise", config_path, "mcp_servers.repowise") or {})
+
+ # Generated keys overwrite stored ones so a moved repo repoints, but any
+ # key the user added to the table survives. ``replace_table`` rewrites the
+ # whole table, so without this every extra key is dropped on every write —
+ # the same failure the JSON path fixed for ``env`` blocks in issue #307,
+ # which this path never had a guard for.
+ #
+ # Preserving a key means re-rendering it, so a value the narrow serializer
+ # cannot encode has to stop the write rather than escape as a bare
+ # TypeError. This function is on init's path with no try around it, so the
+ # difference is a ClickException naming the file against a traceback
+ # mid-run.
+ merged = {**stored, **server_table(repo_path)}
+ try:
+ block = table_block("mcp_servers.repowise", merged)
+ except TypeError as exc:
+ raise click.ClickException(
+ f"Cannot update {config_path}: [mcp_servers.repowise] holds a value repowise "
+ f"cannot rewrite ({exc}). Remove that key and retry; no changes were written."
+ ) from exc
merged_text = replace_table(existing_text, "mcp_servers.repowise", block)
- ensure_valid_toml(merged_text, config_path)
- config_path.write_text(merged_text, encoding="utf-8")
- return config_path
+ merged_doc = ensure_valid_toml(merged_text, config_path)
+ action = write_if_changed(config_path, merged_text, merged_doc, doc)
+ return FileWrite(path=config_path, action=action)
-def enable_hooks_feature(repo_path: Path) -> Path:
+def enable_hooks_feature(repo_path: Path) -> FileWrite:
"""Switch on ``features.hooks``, without which the hooks file is inert."""
from ..formats.toml_merge import (
ensure_valid_toml,
@@ -177,31 +200,35 @@ def enable_hooks_feature(repo_path: Path) -> Path:
replace_table,
require_table,
table_block,
+ write_if_changed,
)
config_path = project_config_path(repo_path)
if config_path.exists():
existing_text = config_path.read_text(encoding="utf-8")
- doc = load_toml_document(config_path, existing_text)
+ doc: dict | None = load_toml_document(config_path, existing_text)
else:
- config_path.parent.mkdir(parents=True, exist_ok=True)
existing_text = ""
- doc = {}
+ doc = None
- features = dict(require_table(doc, "features", config_path, "features") or {})
+ features = dict(require_table(doc or {}, "features", config_path, "features") or {})
features["hooks"] = True
merged_text = replace_table(existing_text, "features", table_block("features", features))
- ensure_valid_toml(merged_text, config_path)
- config_path.write_text(merged_text, encoding="utf-8")
- return config_path
+ merged_doc = ensure_valid_toml(merged_text, config_path)
+ action = write_if_changed(config_path, merged_text, merged_doc, doc)
+ return FileWrite(path=config_path, action=action)
-def write_hooks_config(repo_path: Path) -> Path:
+def write_hooks_config(repo_path: Path) -> tuple[FileWrite, FileWrite]:
"""Merge repowise hooks into ``.codex/hooks.json`` and enable the feature.
Additive per matcher group: a matcher that already carries one of our hooks
is left alone, so a user who narrowed or annotated an entry keeps it.
+
+ Returns both writes — the hooks file *and* ``config.toml``'s feature flag —
+ because they are genuinely two files and reporting only the first would hide
+ a run whose sole effect was switching the feature back on.
"""
import click
@@ -234,9 +261,22 @@ def write_hooks_config(repo_path: Path) -> Path:
if not _has_augment_hook_for_matcher(event_hooks, entry.get("matcher")):
event_hooks.append(entry)
- write_json_config(hooks_path, existing)
- enable_hooks_feature(repo_path)
- return hooks_path
+ action = write_json_config(hooks_path, existing)
+ return FileWrite(path=hooks_path, action=action), enable_hooks_feature(repo_path)
+
+
+def _combined(first: FileAction, second: FileAction) -> FileAction:
+ """One action describing two writes to the same file.
+
+ ``config.toml`` is written twice per install — the server table, then the
+ feature flag — and the file's entry in the result has to answer "did this
+ file move", not "did the last of the two writes move it".
+ """
+ if FileAction.CREATED in (first, second):
+ return FileAction.CREATED
+ if FileAction.UPDATED in (first, second):
+ return FileAction.UPDATED
+ return first
def _is_augment_hook(hook: dict) -> bool:
@@ -296,6 +336,20 @@ class CodexTarget:
def supports_scope(self, scope: Scope) -> bool:
return True
+ def is_present(self, repo_path: Path | None = None) -> bool:
+ """``codex`` on PATH, or a ``~/.codex`` the CLI left behind.
+
+ Deliberately *not* ``is_codex_cli_installed() and is_codex_logged_in()``,
+ which is what init's Codex prompt used to gate on. Those shell out twice
+ with a 5s and a 10s timeout, which is not a probe you run on every
+ listing. Login state is still checked, but where it can act on the
+ answer: the setup path warns when it writes config for a CLI that is
+ installed and signed out.
+ """
+ import shutil
+
+ return shutil.which("codex") is not None or (Path.home() / ".codex").is_dir()
+
def detect(self, repo_path: Path | None = None) -> list[Registration]:
return detect(repo_path)
@@ -308,19 +362,33 @@ class CodexTarget:
) -> WriteResult:
from repowise.cli.editor_integrations.codex_config import install_codex_rewrite_hook
+ from ..formats.observe import observed_action, read_bytes
+
result = WriteResult()
if scope is Scope.PROJECT:
if repo_path is None:
raise ValueError("project-scope install needs a repo_path")
- result.record(write_server_config(repo_path), FileAction.UPDATED)
- result.record(write_hooks_config(repo_path), FileAction.UPDATED)
+ # Server table first, then the hooks file (which flips the feature
+ # flag in the same config.toml). The order is the one init has
+ # always used and it is what the file's table order records.
+ server = write_server_config(repo_path)
+ hooks, feature = write_hooks_config(repo_path)
+ result.record(server.path, _combined(server.action, feature.action))
+ result.record(hooks.path, hooks.action)
return result
- hooks = install_codex_rewrite_hook()
- result.record(
- hooks or user_hooks_path(),
- FileAction.UPDATED if hooks else FileAction.NOT_FOUND,
- )
+ # Observed rather than assumed, for the same reason Claude Code's is:
+ # ``install_codex_rewrite_hook`` returns a path, not an action. Hard-
+ # coding UPDATED here made every re-run and every ``agents refresh``
+ # report a change, which also made the "nothing moved" branch of
+ # ``doctor --repair`` unreachable for any codex-wired repo.
+ hooks_path = user_hooks_path()
+ before = read_bytes(hooks_path)
+ installed = install_codex_rewrite_hook()
+ if not installed:
+ result.record(hooks_path, FileAction.NOT_FOUND)
+ return result
+ result.record(hooks_path, observed_action(before, read_bytes(hooks_path)))
return result
def uninstall(self, scope: Scope, *, repo_path: Path | None = None) -> WriteResult:
@@ -380,6 +448,17 @@ class CodexTarget:
codex_supports_rewrite,
)
+ from ..formats.json_merge import is_damaged
+
+ hooks = user_hooks_path()
+ if is_damaged(hooks):
+ return DoctorReport(
+ target_id=ID,
+ status=DoctorStatus.BROKEN,
+ issues=(f"{hooks} is not valid JSON, so Codex loads none of its hooks.",),
+ fix_command="repowise hook rewrite install",
+ )
+
matcher = codex_rewrite_hook_matcher()
if matcher is None:
return DoctorReport(
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py b/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py
index 3e09e6ec8..ed7ca5871 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py
@@ -28,6 +28,7 @@ from ..types import (
DoctorReport,
DoctorStatus,
FileAction,
+ FileWrite,
InstallMethod,
Registration,
Scope,
@@ -75,7 +76,7 @@ def server_entry(repo_path: Path) -> dict:
return {"type": "stdio", **entry}
-def write_mcp_config(repo_path: Path) -> Path:
+def write_mcp_config(repo_path: Path) -> FileWrite:
"""Merge the repowise server into ``.vscode/mcp.json``.
Raises ``ValueError`` when the existing file is not strict JSON or is not
@@ -103,11 +104,10 @@ def write_mcp_config(repo_path: Path) -> Path:
config_path.parent.mkdir(parents=True, exist_ok=True)
merged = {"servers": new_entry}
- write_json_config(config_path, merged)
- return config_path
+ return FileWrite(path=config_path, action=write_json_config(config_path, merged))
-def write_extensions_config(repo_path: Path) -> Path:
+def write_extensions_config(repo_path: Path) -> FileWrite:
"""Recommend the repowise extension, preserving existing entries."""
from ..formats.json_merge import load_json_object_or_value_error, write_json_config
@@ -127,8 +127,47 @@ def write_extensions_config(repo_path: Path) -> Path:
config_path.parent.mkdir(parents=True, exist_ok=True)
merged = {"recommendations": [EXTENSION_ID]}
- write_json_config(config_path, merged)
- return config_path
+ return FileWrite(path=config_path, action=write_json_config(config_path, merged))
+
+
+def _remove_server_entry(config_path: Path) -> tuple[Path, FileAction]:
+ """Drop ``servers.repowise``, preserving sibling servers."""
+ from ..formats.json_merge import load_json_object_or_value_error, write_json_config
+
+ if not config_path.exists():
+ return config_path, FileAction.NOT_FOUND
+ try:
+ existing = load_json_object_or_value_error(config_path, "mcp.json")
+ except ValueError:
+ # Same reason install declines: it is far more likely to be JSONC than
+ # damaged, and rewriting it would silently delete the user's comments.
+ return config_path, FileAction.KEPT
+
+ servers = existing.get("servers")
+ if not isinstance(servers, dict) or "repowise" not in servers:
+ return config_path, FileAction.NOT_FOUND
+ servers.pop("repowise")
+ write_json_config(config_path, existing)
+ return config_path, FileAction.REMOVED
+
+
+def _remove_extension_recommendation(config_path: Path) -> tuple[Path, FileAction]:
+ """Drop our id from ``recommendations``, preserving everyone else's."""
+ from ..formats.json_merge import load_json_object_or_value_error, write_json_config
+
+ if not config_path.exists():
+ return config_path, FileAction.NOT_FOUND
+ try:
+ existing = load_json_object_or_value_error(config_path, "extensions.json")
+ except ValueError:
+ return config_path, FileAction.KEPT
+
+ recommendations = existing.get("recommendations")
+ if not isinstance(recommendations, list) or EXTENSION_ID not in recommendations:
+ return config_path, FileAction.NOT_FOUND
+ existing["recommendations"] = [r for r in recommendations if r != EXTENSION_ID]
+ write_json_config(config_path, existing)
+ return config_path, FileAction.REMOVED
def detect(repo_path: Path | None = None) -> list[Registration]:
@@ -169,6 +208,23 @@ class VSCodeTarget:
"""Project scope only — there is no user-level file repowise writes."""
return scope is Scope.PROJECT
+ def is_present(self, repo_path: Path | None = None) -> bool:
+ """``code`` on PATH, a user data directory, or a ``.vscode/`` in the repo.
+
+ The repo-local check earns its place: a workspace with ``.vscode/`` in
+ it is worth configuring even from a machine where the ``code`` shim was
+ never installed, because the file is committed and read by whoever
+ opens the repo next.
+ """
+ import shutil
+
+ if repo_path is not None and (repo_path / ".vscode").is_dir():
+ return True
+ if shutil.which("code") is not None:
+ return True
+ home = Path.home()
+ return any((home / candidate).is_dir() for candidate in (".vscode", ".vscode-server"))
+
def detect(self, repo_path: Path | None = None) -> list[Registration]:
return detect(repo_path)
@@ -186,7 +242,8 @@ class VSCodeTarget:
raise ValueError("project-scope install needs a repo_path")
try:
- result.record(write_mcp_config(repo_path), FileAction.UPDATED)
+ written = write_mcp_config(repo_path)
+ result.record(written.path, written.action)
except ValueError:
result.record(mcp_config_path(repo_path), FileAction.KEPT)
result.note(
@@ -194,7 +251,8 @@ class VSCodeTarget:
'comments). Add a "repowise" server under "servers" manually.'
)
try:
- result.record(write_extensions_config(repo_path), FileAction.UPDATED)
+ written = write_extensions_config(repo_path)
+ result.record(written.path, written.action)
except ValueError:
result.record(extensions_config_path(repo_path), FileAction.KEPT)
result.note(
@@ -204,33 +262,19 @@ class VSCodeTarget:
return result
def uninstall(self, scope: Scope, *, repo_path: Path | None = None) -> WriteResult:
- """Remove the repowise server entry, preserving sibling servers."""
- from ..formats.json_merge import (
- load_json_object_or_value_error,
- write_json_config,
- )
+ """Remove the server entry and the extension recommendation.
+ Both files, because :meth:`install` writes both and
+ :meth:`describe_paths` names both. Leaving the recommendation behind
+ meant ``agents remove --target=vscode`` still had the editor prompting
+ every contributor to install an extension for an integration that was
+ just removed — and said nothing about the file it had skipped.
+ """
result = WriteResult()
if scope is not Scope.PROJECT or repo_path is None:
return result
-
- config_path = mcp_config_path(repo_path)
- if not config_path.exists():
- result.record(config_path, FileAction.NOT_FOUND)
- return result
- try:
- existing = load_json_object_or_value_error(config_path, "mcp.json")
- except ValueError:
- result.record(config_path, FileAction.KEPT)
- return result
-
- servers = existing.get("servers")
- if not isinstance(servers, dict) or "repowise" not in servers:
- result.record(config_path, FileAction.NOT_FOUND)
- return result
- servers.pop("repowise")
- write_json_config(config_path, existing)
- result.record(config_path, FileAction.REMOVED)
+ result.record(*_remove_server_entry(mcp_config_path(repo_path)))
+ result.record(*_remove_extension_recommendation(extensions_config_path(repo_path)))
return result
def print_config(self, scope: Scope, *, repo_path: Path | None = None) -> str:
diff --git a/packages/cli/src/repowise/cli/agent_targets/types.py b/packages/cli/src/repowise/cli/agent_targets/types.py
index 7f0a03363..5336e0d1c 100644
--- a/packages/cli/src/repowise/cli/agent_targets/types.py
+++ b/packages/cli/src/repowise/cli/agent_targets/types.py
@@ -157,6 +157,15 @@ class Registration:
version: str | None = None
detail: str | None = None
+ def as_dict(self) -> dict:
+ return {
+ "method": self.method,
+ "scope": self.scope.value,
+ "config_path": str(self.config_path),
+ "version": self.version,
+ "detail": self.detail,
+ }
+
@dataclass(frozen=True)
class FileWrite:
@@ -186,10 +195,6 @@ class WriteResult:
def note(self, message: str) -> None:
self.notes.append(message)
- def extend(self, other: WriteResult) -> None:
- self.files.extend(other.files)
- self.notes.extend(other.notes)
-
@property
def changed(self) -> bool:
"""True when anything actually moved on disk."""
@@ -272,6 +277,28 @@ class AgentTarget(Protocol):
"""Whether this target has a config home at *scope*."""
...
+ def is_present(self, repo_path: Path | None = None) -> bool:
+ """Whether this agent looks installed on this machine.
+
+ Distinct from :meth:`detect`, and the distinction is the whole reason
+ this exists: ``detect`` answers "is repowise wired into this agent",
+ which is ``False`` for every agent on a first-time user's machine.
+ "Which agents should we offer to wire up" needs the other question, and
+ it has to be answered by the descriptor — asking it anywhere else
+ rebuilds the per-host ``if agent == "codex"`` chain the seam exists to
+ delete.
+
+ Cheap by contract: a directory probe or a PATH lookup, never a
+ subprocess. This runs on every listing and in the middle of ``init``,
+ and an agent that has to be *launched* to find out it is installed is
+ an agent we report as absent.
+
+ Best-effort in both directions. A false positive costs an unchecked box
+ the user unchecks; a false negative costs a checked box they check.
+ Neither is worth a slow probe.
+ """
+ ...
+
def detect(self, repo_path: Path | None = None) -> list[Registration]:
"""Every place this target is currently wired.
@@ -332,25 +359,23 @@ class AgentTarget(Protocol):
class InstallLifecycle(Protocol):
"""The ``init`` / ``update`` half of an integration's contract.
- Four methods, and they are a subset of :class:`AgentTarget`:
+ Three methods, and they are a subset of :class:`AgentTarget`:
``write_project_files`` is a project-scope install, ``register_client`` is a
- user-scope one, ``refresh_project_files`` is an install that declines to
- create what is not already there, and ``configure_options`` is the prompting
- that decides which of those run.
+ user-scope one, and ``refresh_project_files`` is an install that declines to
+ create what is not already there.
It lives here rather than in ``editor_setup`` so there is exactly one home
for integration protocols. It is still spelled separately from
- :class:`AgentTarget` because the two are driven by different callers today:
+ :class:`AgentTarget` because the two are driven by different callers:
``init`` and ``update`` drive this one and own the console object and the
- prompting, while ``AgentTarget`` is driven by detection and repair paths
- that must never prompt. Phase 2 collapses them, when ``repowise agents``
- takes over the call sites and the prompting moves behind a resolved
- interactivity decision rather than a per-integration ``click.confirm``.
- """
+ per-file progress lines, while ``AgentTarget`` is driven by detection and
+ repair paths that must never print into someone else's layout.
- def configure_options(self, console_obj: object, options: object) -> object:
- """Let the integration prompt or adjust setup options before writing."""
- ...
+ It had a fourth method, ``configure_options``, where each integration
+ prompted for itself. That is gone: the prompting is now one registry-built
+ checklist rather than one hand-written question per agent, which is what
+ stops a fourth agent from meaning a fourth prompt in a fourth module.
+ """
def write_project_files(
self, console_obj: object, repo_path: Path, options: object
diff --git a/packages/cli/src/repowise/cli/commands/agents_cmd.py b/packages/cli/src/repowise/cli/commands/agents_cmd.py
new file mode 100644
index 000000000..37aa85b67
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/agents_cmd.py
@@ -0,0 +1,499 @@
+"""``repowise agents`` — wire repowise into the agents on this machine.
+
+A noun group, following ``repowise hook``, rather than a top-level verb that
+would compete with ``init`` for meaning. ``init`` is still the front door and
+still sets agents up as part of a first run; this group is for the cases that
+come after it — adding an agent you installed later, removing one, refreshing
+a config after an upgrade, or printing a snippet for a host repowise does not
+write files for at all.
+
+Two contracts worth reading before editing:
+
+**``--format json`` is on every subcommand, including the ones that write.**
+``doctor`` made json incompatible with ``--repair``, which is right for a
+diagnostic and wrong here: the whole point of a wiring command is that an agent
+can run it and read back what changed. ``WriteResult``'s action enum is already
+that payload, so there is nothing to invent.
+
+**One payload, two renderers.** Every subcommand builds a dict and then either
+prints a table *from that dict* or emits it. Never a second projection assembled
+for the table alone. A trimmed projection has two silent failure modes — a key
+dropped, and a key kept that nothing prints — and only the first is visible to a
+test that checks the projection by itself.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+from typing import Any
+
+import click
+
+from repowise.cli.agent_targets.registry import default_selection, describe_agents
+from repowise.cli.helpers import console, resolve_command_target
+from repowise.cli.output import emit_json, format_option, notice_console
+
+#: ``--target`` accepts these alongside a comma-separated list of ids.
+_TARGET_KEYWORDS = "auto, all, none"
+
+
+# ---------------------------------------------------------------------------
+# Shared resolution
+# ---------------------------------------------------------------------------
+
+
+def _repo_path(path: str | None, fmt: str) -> Path:
+ """The repo these subcommands act on.
+
+ Single-repo only, deliberately. ``agents add --workspace`` would have to
+ decide whether a user-scope MCP registration means the workspace root or
+ each member repo, and there is exactly one global ``repowise`` entry to
+ point somewhere. Workspace support is worth having when someone asks for it
+ with a concrete answer to that question.
+ """
+ target = resolve_command_target(path=path, workspace_flag=False, no_workspace_flag=True)
+ target.notice(notice_console(fmt), command="agents")
+ assert target.repo_path is not None
+ return target.repo_path
+
+
+def _scopes_for(target: Any, scope: str) -> list[Any]:
+ """Which scopes to act on for *target*, honouring what it supports."""
+ from repowise.cli.agent_targets.types import Scope
+
+ wanted = [Scope.PROJECT, Scope.USER] if scope == "both" else [Scope(scope)]
+ return [s for s in wanted if target.supports_scope(s)]
+
+
+def _resolve_targets(target_flag: str, repo_path: Path) -> list[Any]:
+ from repowise.cli.agent_targets.registry import resolve_target_flag
+
+ try:
+ return resolve_target_flag(target_flag, repo_path)
+ except ValueError as exc:
+ raise click.UsageError(str(exc)) from exc
+
+
+def _can_prompt(target_flag: str | None, yes: bool) -> bool:
+ """The interactive gate: a TTY **and** no ``--target``, never a TTY alone.
+
+ An explicit ``--target`` is already an answer to the question the prompt
+ asks, so asking again is at best noise and at worst a block. And an agent
+ driving this under a pty reports a TTY it cannot answer from, which is why
+ ``isatty`` is the last condition rather than the only one — the prompt
+ itself treats EOF as "not interactive" and falls through to the defaults.
+ """
+ if target_flag is not None or yes:
+ return False
+ try:
+ return sys.stdin.isatty()
+ except Exception:
+ return False
+
+
+# ---------------------------------------------------------------------------
+# Payload construction — the single source both renderers read
+# ---------------------------------------------------------------------------
+
+
+def _write_payload(
+ action: str,
+ repo_path: Path,
+ targets: list[Any],
+ scope: str,
+ *,
+ remove: bool,
+ refresh_only: bool = False,
+) -> dict:
+ """Run the installs (or uninstalls) and return the record of what happened.
+
+ Built here, at the site that holds the ``WriteResult``, rather than
+ re-derived by a renderer.
+
+ ``skips`` records every scope that was deliberately left alone and why —
+ per scope, not per agent, because all three reasons are scope-shaped:
+
+ * A **host-managed install already present**. The duplicate this prevents is
+ the *user-scope* one: the plugin registers an MCP server and hooks for the
+ whole machine. It says nothing about the repo-shared ``.mcp.json``, which
+ is a committed file other contributors' checkouts read and which the
+ plugin does not write. Standing down for the whole target suppressed that
+ file too, so a plugin user's ``agents add`` wrote nothing at all.
+ * ``REPOWISE_SKIP_EDITOR_SETUP``, which is about the global config only.
+ * ``refresh``, which must not create a registration that did not exist. A
+ target wired project-scope only must not have its user-scope config
+ written, or ``doctor --repair`` buys a global config write with a local
+ detection.
+ """
+ from repowise.cli.agent_targets.registry import select_install_method
+ from repowise.cli.agent_targets.types import Scope
+ from repowise.cli.editor_setup import is_editor_setup_disabled
+
+ user_scope_disabled = is_editor_setup_disabled()
+
+ agents: list[dict] = []
+ for target in targets:
+ registrations = list(target.detect(repo_path))
+ wired_scopes = {r.scope for r in registrations}
+ # Which scopes a host already covers, read off the registrations rather
+ # than assumed to be the user one. Claude Code's detection genuinely
+ # models a project-scoped plugin, and hard-coding USER put the skip on
+ # the wrong scope in both directions for that machine: a duplicate
+ # write where the plugin does cover, and a skip with a false reason
+ # where it does not.
+ host_scopes = {
+ r.scope
+ for r in registrations
+ for method in target.methods
+ if method.id == r.method and method.managed_by == "host"
+ }
+ method = None if remove else select_install_method(target, [])
+
+ entry: dict = {
+ "id": target.id,
+ "display_name": target.display_name,
+ "method": method.id if method is not None else None,
+ "skips": {},
+ "writes": {},
+ }
+
+ for target_scope in _scopes_for(target, scope):
+ reason = None
+ if target_scope is Scope.USER and user_scope_disabled:
+ reason = "REPOWISE_SKIP_EDITOR_SETUP is set"
+ elif not remove and target_scope in host_scopes:
+ reason = "a host-managed install already covers this scope"
+ elif refresh_only and target_scope not in wired_scopes:
+ reason = "nothing wired here, and refresh adds nothing"
+ if reason is not None:
+ entry["skips"][target_scope.value] = reason
+ continue
+
+ if remove:
+ result = target.uninstall(target_scope, repo_path=repo_path)
+ else:
+ result = target.install(target_scope, repo_path=repo_path)
+ if host_scopes and result.changed:
+ # Writing a scope the host does not cover is right — the
+ # repo file is for other contributors' checkouts — but this
+ # machine now loads repowise from both, so say so instead of
+ # quietly handing them the duplicate the skip above avoids.
+ result.note(
+ f"{target.display_name} also has a host-managed install, so this "
+ "machine will load repowise from both. The file is written for "
+ "contributors who do not have the plugin."
+ )
+ entry["writes"][target_scope.value] = result.as_dict()
+ agents.append(entry)
+
+ changed = any(
+ f["action"] in ("created", "updated", "removed")
+ for agent in agents
+ for write in agent["writes"].values()
+ for f in write["files"]
+ )
+ return {
+ "action": action,
+ "repo": str(repo_path),
+ "scope": scope,
+ "changed": changed,
+ "agents": agents,
+ }
+
+
+# ---------------------------------------------------------------------------
+# Renderers
+# ---------------------------------------------------------------------------
+
+
+def _render_list(payload: dict) -> None:
+ from rich.table import Table
+
+ table = Table(title="Agent integrations")
+ table.add_column("Agent", style="cyan")
+ table.add_column("Tier")
+ table.add_column("Status")
+ table.add_column("Wired")
+
+ for row in payload["agents"]:
+ registrations = row["registrations"]
+ if registrations:
+ status = "[green]configured[/green]"
+ if len(registrations) > 1:
+ status = f"[yellow]configured x{len(registrations)}[/yellow]"
+ elif row["present"]:
+ status = "[dim]installed, not configured[/dim]"
+ else:
+ status = "[dim]not detected[/dim]"
+ wired = ", ".join(f"{r['method']}/{r['scope']}" for r in registrations) or "-"
+ table.add_row(row["id"], row["tier"], status, wired)
+
+ console.print(table)
+ if any(len(row["registrations"]) > 1 for row in payload["agents"]):
+ console.print(
+ "[dim]An agent wired more than once loads repowise more than once. "
+ "See [bold]repowise doctor[/bold].[/dim]"
+ )
+ console.print("[dim]Add or remove with [bold]repowise agents add --target=<id>[/bold].[/dim]")
+
+
+def _render_writes(payload: dict) -> None:
+ from rich.table import Table
+
+ verb = "Removed" if payload["action"] == "remove" else "Wired"
+ table = Table(title=f"{verb} agent integrations")
+ table.add_column("Agent", style="cyan")
+ table.add_column("Scope")
+ table.add_column("Action")
+ table.add_column("File")
+
+ for agent in payload["agents"]:
+ for scope, write in agent["writes"].items():
+ for entry in write["files"]:
+ table.add_row(agent["id"], scope, entry["action"], entry["path"])
+ # Every skip gets its own row. Folding them into one "skipped" line
+ # per agent hid the reason whenever a second scope had written
+ # something, which is the common case rather than the edge one.
+ for scope, reason in agent["skips"].items():
+ table.add_row(agent["id"], scope, "[dim]skipped[/dim]", f"[dim]{reason}[/dim]")
+ if not agent["writes"] and not agent["skips"]:
+ table.add_row(agent["id"], "-", "[dim]nothing to do[/dim]", "no config at this scope")
+
+ console.print(table)
+ for agent in payload["agents"]:
+ for write in agent["writes"].values():
+ for note in write["notes"]:
+ console.print(f" [yellow]{note}[/yellow]")
+ if not payload["changed"]:
+ console.print("[dim]Everything was already up to date.[/dim]")
+
+
+# ---------------------------------------------------------------------------
+# Commands
+# ---------------------------------------------------------------------------
+
+
[email protected]("agents", invoke_without_command=True)
+@format_option(help="Output format. json reports what changed, including for writes.")
+def agents_group(ctx: click.Context, fmt: str) -> None:
+ """List and manage the agent integrations repowise can wire up.
+
+ With no subcommand, lists every known agent for the current repo: its
+ support tier, whether it looks installed, and every place it is currently
+ wired to repowise.
+
+ The group takes no path argument, unlike its subcommands. A group with an
+ optional positional cannot tell a repo path from a subcommand name — Click
+ binds ``repowise agents add`` with ``add`` as the path and then reports no
+ such command. The listing runs against the current directory; every
+ subcommand takes an explicit path.
+ """
+ if ctx.invoked_subcommand is not None:
+ return
+
+ repo_path = _repo_path(None, fmt)
+ payload = {"repo": str(repo_path), "agents": describe_agents(repo_path)}
+ if fmt == "json":
+ emit_json(payload)
+ return
+ _render_list(payload)
+
+
+@agents_group.command("add")
[email protected]("path", required=False, default=None)
+ "--target",
+ "target_flag",
+ default=None,
+ help=f"Comma-separated agent ids, or one of: {_TARGET_KEYWORDS}. Prompts when omitted.",
+)
+ "--scope",
+ type=click.Choice(["project", "user", "both"]),
+ default="both",
+ help="Where to write: repo-local config, per-machine config, or both.",
+)
[email protected]("--yes", "-y", is_flag=True, default=False, help="Never prompt.")
+@format_option(help="Output format. json reports every file and what happened to it.")
+def agents_add(
+ path: str | None,
+ target_flag: str | None,
+ scope: str,
+ yes: bool,
+ fmt: str,
+) -> None:
+ """Wire one or more agents up to this repo.
+
+ ``--target=auto`` picks everything already detected. With no ``--target``
+ on a terminal you get a checklist with the installed agents pre-ticked.
+ """
+ repo_path = _repo_path(path, fmt)
+ targets = _select_targets_for_add(repo_path, target_flag, yes, fmt)
+ payload = _write_payload("add", repo_path, targets, scope, remove=False)
+ if fmt == "json":
+ emit_json(payload)
+ return
+ _render_writes(payload)
+
+
+def _select_targets_for_add(
+ repo_path: Path,
+ target_flag: str | None,
+ yes: bool,
+ fmt: str,
+) -> list[Any]:
+ """Resolve ``--target``, or ask, or fall back to what is detected."""
+ from repowise.cli.agent_targets.registry import get_target
+
+ if target_flag is not None:
+ return _resolve_targets(target_flag, repo_path)
+
+ rows = describe_agents(repo_path)
+ chosen = default_selection(rows)
+
+ if _can_prompt(target_flag, yes) and fmt != "json":
+ answered = _prompt_for_agents(rows, chosen)
+ if answered is not None:
+ chosen = answered
+
+ return [t for t in (get_target(agent_id) for agent_id in chosen) if t is not None]
+
+
+def _prompt_for_agents(rows: list[dict], chosen: set[str]) -> set[str] | None:
+ from repowise.cli.ui.agent_selection import AgentChoice, interactive_agent_select
+
+ return interactive_agent_select(
+ console,
+ [
+ AgentChoice(
+ id=row["id"],
+ display_name=row["display_name"],
+ detail=(
+ "already wired"
+ if row["registrations"]
+ else ("installed" if row["present"] else "not detected")
+ ),
+ enabled=row["id"] in chosen,
+ )
+ for row in rows
+ ],
+ )
+
+
+@agents_group.command("remove")
[email protected]("path", required=False, default=None)
+ "--target",
+ "target_flag",
+ required=True,
+ help=f"Comma-separated agent ids, or one of: {_TARGET_KEYWORDS}.",
+)
+ "--scope",
+ type=click.Choice(["project", "user", "both"]),
+ default="both",
+ help="Where to remove from.",
+)
+@format_option(help="Output format. json reports every file and what happened to it.")
+def agents_remove(path: str | None, target_flag: str, scope: str, fmt: str) -> None:
+ """Remove repowise from one or more agents.
+
+ ``--target`` is required rather than defaulted: "remove what you detect" is
+ a plausible reading of ``auto`` and a bad default for a destructive verb.
+ """
+ repo_path = _repo_path(path, fmt)
+ targets = _resolve_targets(target_flag, repo_path)
+ payload = _write_payload("remove", repo_path, targets, scope, remove=True)
+ if fmt == "json":
+ emit_json(payload)
+ return
+ _render_writes(payload)
+
+
+@agents_group.command("refresh")
[email protected]("path", required=False, default=None)
+ "--scope",
+ type=click.Choice(["project", "user", "both"]),
+ default="both",
+ help="Which scope to refresh.",
+)
+@format_option(help="Output format. json reports every file and what happened to it.")
+def agents_refresh(path: str | None, scope: str, fmt: str) -> None:
+ """Rewrite the configs of agents that are already wired up.
+
+ Never adds an agent. This is what to run after upgrading repowise, or after
+ moving the repo: it repoints what exists and leaves everything else alone,
+ which is what makes it safe for ``doctor --repair`` to call.
+ """
+ repo_path = _repo_path(path, fmt)
+ payload = refresh_wired_agents(repo_path, scope=scope)
+ if fmt == "json":
+ emit_json(payload)
+ return
+ if not payload["agents"]:
+ console.print("[dim]No agent is wired up yet. Run [bold]repowise agents add[/bold].[/dim]")
+ return
+ _render_writes(payload)
+
+
+def refresh_wired_agents(repo_path: Path, *, scope: str = "both") -> dict:
+ """Rewrite every already-wired agent's config. The body of ``agents refresh``.
+
+ Public because ``doctor --repair`` routes here rather than reimplementing
+ it or shelling out to the CLI. Adds nothing, and means it at the *scope*
+ level: a target wired only in the repo does not get its per-machine config
+ written as a side effect of being refreshed.
+ """
+ from repowise.cli.agent_targets.registry import get_target
+
+ wired = [
+ target
+ for row in describe_agents(repo_path)
+ if row["registrations"] and (target := get_target(row["id"])) is not None
+ ]
+ return _write_payload("refresh", repo_path, wired, scope, remove=False, refresh_only=True)
+
+
+@agents_group.command("print-config")
[email protected]("target_id")
[email protected]("path", required=False, default=None)
+ "--scope",
+ type=click.Choice(["project", "user"]),
+ default="project",
+ help="Which scope's snippet to print.",
+)
+@format_option(help="Output format. table prints the bare snippet, ready to paste.")
+def agents_print_config(target_id: str, path: str | None, scope: str, fmt: str) -> None:
+ """Print the config snippet for an agent, writing nothing.
+
+ This is the whole of the paste-config tier: an agent nobody has asked us to
+ support properly is still served by a snippet and a docs line, at no
+ maintenance cost.
+ """
+ from repowise.cli.agent_targets.registry import get_target, list_target_ids
+ from repowise.cli.agent_targets.types import Scope
+
+ target = get_target(target_id)
+ if target is None:
+ raise click.UsageError(
+ f"Unknown agent id: {target_id}. Known: {', '.join(list_target_ids())}."
+ )
+
+ repo_path = _repo_path(path, fmt)
+ snippet = target.print_config(Scope(scope), repo_path=repo_path)
+ payload = {
+ "target": target.id,
+ "scope": scope,
+ "repo": str(repo_path),
+ "config": snippet,
+ "docs_url": target.docs_url,
+ }
+ if fmt == "json":
+ emit_json(payload)
+ return
+ # Bare, so it pipes into a file or a clipboard without a table around it.
+ click.echo(payload["config"])
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
index 6c721bd34..cf492753e 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
@@ -484,6 +484,10 @@ def _run_repo_checks(
registration_check, registration_wedged = _claude_registration_check()
checks.append(registration_check)
+ # 13. Per-agent health, reported by each agent's own descriptor
+ agent_checks, agents_need_refresh = _agent_target_checks()
+ checks.extend(agent_checks)
+
all_ok = all(c.ok for c in checks)
if fmt != "table":
@@ -679,9 +683,25 @@ def _run_repo_checks(
repaired_count = run_async(_repair())
console.print(f"[bold green]Repaired {repaired_count} entries.[/bold green]")
- elif repair and not has_mismatches and not registration_wedged:
+ elif repair and not has_mismatches and not registration_wedged and not agents_need_refresh:
console.print("[green]Nothing to repair.[/green]")
+ if repair and agents_need_refresh:
+ from repowise.cli.commands.agents_cmd import refresh_wired_agents
+
+ console.print("\n[bold]Refreshing agent integrations...[/bold]")
+ payload = refresh_wired_agents(repo_path)
+ for agent in payload["agents"]:
+ for scope, write in agent["writes"].items():
+ for entry in write["files"]:
+ console.print(f" {agent['id']} [{scope}]: {entry['action']} {entry['path']}")
+ if not payload["changed"]:
+ console.print(
+ "[yellow]Nothing moved. A hook whose matcher is stale needs "
+ "[bold]repowise hook rewrite install[/bold]; a damaged config file "
+ "has to be fixed or removed by hand.[/yellow]"
+ )
+
if repair and registration_wedged:
from repowise.cli.editor_integrations.claude_config import register_with_claude_code
@@ -699,6 +719,61 @@ def _run_repo_checks(
return all_ok, checks
+def _agent_target_checks() -> tuple[list[DoctorCheck], bool]:
+ """One row per agent, reported by that agent's own descriptor.
+
+ Nothing here knows what any particular agent's health means: each
+ ``AgentTarget`` answers for itself, so a fourth agent gets a doctor row by
+ being registered rather than by someone adding a branch to this function.
+
+ Only ``broken`` fails the run, and the line is drawn there on purpose.
+ ``not-installed`` is not a failure — an agent you do not use is not a
+ problem with your setup — and neither is ``stale``, which is advisory in
+ the same way the "Distill rewrite hook" row above it already is. A stale
+ matcher is common, opt-in surfaces go stale routinely, and making it fail
+ would turn ``repowise doctor`` non-zero in CI for a condition nobody asked
+ the tool to guarantee. ``broken`` means a config file is damaged, which is
+ a real fault in the setup being checked.
+
+ Advisory does not mean quiet. The stale row is the reason this function
+ exists: a hook whose matcher names a tool the host has since renamed is
+ installed, parses, and will never fire, which is indistinguishable from
+ working unless something says so out loud. It is also the agreed mitigation
+ for gating the self-heal migrations on ``REPOWISE_SKIP_EDITOR_SETUP`` —
+ someone who exports that permanently never gets the migration, so the
+ staleness has to be visible somewhere. It is printed, and it drives
+ ``--repair``; it just does not change the exit code.
+
+ Returns ``(checks, needs_refresh)``; ``needs_refresh`` drives ``--repair``.
+ """
+ from repowise.cli.agent_targets.registry import all_targets
+
+ checks: list[DoctorCheck] = []
+ needs_refresh = False
+ try:
+ targets = all_targets()
+ except Exception as exc: # pragma: no cover - a broken registry is a crash elsewhere
+ return [_check("Agent integrations", True, f"Could not check: {exc}")], False
+
+ for target in targets:
+ name = f"Agent: {target.id}"
+ try:
+ report = target.doctor()
+ except Exception as exc:
+ checks.append(_check(name, True, f"Could not check: {exc}"))
+ continue
+ if report.status.value in ("ok", "not-installed"):
+ detail = report.issues[0] if report.issues else "wired up"
+ checks.append(_check(name, True, detail))
+ continue
+ needs_refresh = True
+ detail = "; ".join(report.issues)
+ if report.fix_command:
+ detail += f" (run: {report.fix_command})"
+ checks.append(_check(name, report.status.value != "broken", detail))
+ return checks, needs_refresh
+
+
def _claude_registration_check() -> tuple[DoctorCheck, bool]:
"""Detect a wedged Claude Code MCP registration (stale paths).
diff --git a/packages/cli/src/repowise/cli/commands/hook_cmd.py b/packages/cli/src/repowise/cli/commands/hook_cmd.py
index 36084ad9a..525f0ae9d 100644
--- a/packages/cli/src/repowise/cli/commands/hook_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/hook_cmd.py
@@ -324,7 +324,11 @@ def _install_codex_surfaces(target) -> None:
if agents_path:
console.print(f" [green]✓[/green] AGENTS.md distill section ({agents_path})")
else:
- console.print(f" [yellow]AGENTS.md distill section failed ({repo_path})[/yellow]")
+ console.print(
+ f" [yellow]AGENTS.md distill section not written ({repo_path}); "
+ "check its REPOWISE_DISTILL markers — one unpaired, or more than "
+ "one pair, and repowise will not guess at the repair[/yellow]"
+ )
@rewrite_group.command("uninstall")
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
index dd4a1a84e..c393d14b1 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
@@ -27,6 +27,7 @@ from repowise.cli.editor_integrations.defaults import (
from repowise.cli.editor_setup import (
register_editor_clients,
resolve_editor_setup_options,
+ select_agents_interactively,
write_editor_project_files,
)
from repowise.cli.helpers import (
@@ -1043,7 +1044,6 @@ def init_command(
wiki_style = resolve_style(wiki_style).name
editor_options = resolve_editor_setup_options(
- console,
disabled_project_files=get_default_disabled_project_files(
no_claude_md=no_claude_md,
),
@@ -1053,11 +1053,13 @@ def init_command(
integration_overrides=get_default_integration_overrides(
codex_setup=codex_setup,
),
- # Prompt for CLAUDE.md / AGENTS.md / Codex setup whenever the user is
- # engaging interactively — either generating docs or customizing an
- # index-only run (the latter previously got no say).
- prompt_for_project_files=is_interactive and (generate_docs or customize),
)
+ # Ask which agents to wire up whenever the user is engaging interactively —
+ # either generating docs or customizing an index-only run (the latter
+ # previously got no say). One checklist, pre-ticked from detection, in
+ # place of the three sequential yes/no prompts each integration used to own.
+ if is_interactive and (generate_docs or customize):
+ editor_options = select_agents_interactively(console, repo_path, editor_options)
# Merge exclude_patterns from config.yaml and --exclude/-x flags
config = load_config(repo_path)
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
index 0b9db8648..b000d61e0 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
@@ -731,8 +731,11 @@ def _workspace_init(
# never has to guess why the web UI is missing pages for some repos.
# Maps alias -> (generated_count, skip_reason | None)
docs_outcomes: dict[str, tuple[int, str | None]] = {}
+ # No agent checklist in workspace mode: the question is per repo and this
+ # path indexes many, so asking once would apply one answer everywhere and
+ # asking per repo would be a prompt per repo. Workspace init takes the
+ # defaults and the flags; `repowise agents add` covers the rest.
editor_options = resolve_editor_setup_options(
- console,
disabled_project_files=get_default_disabled_project_files(
no_claude_md=no_claude_md,
),
diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude.py b/packages/cli/src/repowise/cli/editor_integrations/claude.py
index d043c8f60..c21242571 100644
--- a/packages/cli/src/repowise/cli/editor_integrations/claude.py
+++ b/packages/cli/src/repowise/cli/editor_integrations/claude.py
@@ -5,8 +5,6 @@ from __future__ import annotations
from pathlib import Path
from typing import Any
-import click
-
from repowise.cli.agent_targets.targets import claude_code as claude_target
from repowise.cli.editor_setup import EditorSetupOptions
from repowise.cli.helpers import get_db_url_for_repo, load_config, run_async
@@ -24,20 +22,6 @@ class ClaudeCodeSetup:
#: Read from the descriptor rather than restated, so the id has one home.
project_file_id = claude_target.PROJECT_FILE_ID
- def configure_options(
- self,
- console_obj: Any,
- options: EditorSetupOptions,
- ) -> EditorSetupOptions:
- if (
- not options.prompt_for_project_files
- or self.project_file_id in options.disabled_project_files
- ):
- return options
- if _prompt_claude_md_enabled(console_obj):
- return options
- return options.with_disabled_project_file(self.project_file_id)
-
def write_project_files(
self,
console_obj: Any,
@@ -129,21 +113,6 @@ def _uses_lean_tool_surface(repo_path: Path) -> bool:
return False
-def _prompt_claude_md_enabled(console_obj: Any) -> bool:
- """Ask whether the Claude project instruction file should be generated."""
-
- # The inline ``Name:`` form its four sibling prompts use. A brand-coloured
- # section header, borrowed from advanced config, oversold a single yes/no.
- console_obj.print()
- console_obj.print(
- "[bold]Claude Code:[/bold] Write a project instruction file describing this codebase?"
- )
- return click.confirm(
- " Generate .claude/CLAUDE.md?",
- default=True,
- )
-
-
def _claude_md_enabled(repo_path: Path) -> bool:
cfg = load_config(repo_path)
return bool(cfg.get("editor_files", {}).get("claude_md", True))
diff --git a/packages/cli/src/repowise/cli/editor_integrations/codex.py b/packages/cli/src/repowise/cli/editor_integrations/codex.py
index c6c499287..7d33fe3bb 100644
--- a/packages/cli/src/repowise/cli/editor_integrations/codex.py
+++ b/packages/cli/src/repowise/cli/editor_integrations/codex.py
@@ -5,8 +5,6 @@ from __future__ import annotations
from pathlib import Path
from typing import Any
-import click
-
from repowise.cli.agent_targets.targets import codex as codex_target
from repowise.cli.editor_setup import EditorSetupOptions
@@ -22,38 +20,6 @@ class CodexSetup:
integration_id = codex_target.ID
project_file_id = codex_target.PROJECT_FILE_ID
- def configure_options(
- self,
- console_obj: Any,
- options: EditorSetupOptions,
- ) -> EditorSetupOptions:
- if self.integration_id in options.integration_overrides:
- return options
- if not options.prompt_for_project_files:
- return options
-
- from repowise.cli.mcp_config import is_codex_cli_installed, is_codex_logged_in
-
- if not (is_codex_cli_installed() and is_codex_logged_in()):
- return options
-
- console_obj.print()
- console_obj.print("[bold]Codex:[/bold] Generate project-local .codex config and hooks?")
- # Its two neighbours default to yes; say why this one does not, rather
- # than silently inverting Enter-through in the middle of three prompts.
- console_obj.print(
- " [dim]Off by default: only useful if you drive this repo with the Codex CLI.[/dim]"
- )
- enabled = click.confirm(
- " Write .codex/config.toml and .codex/hooks.json?",
- default=False,
- )
- if not enabled:
- console_obj.print(
- " [dim]Skipped. Run 'repowise init --codex' later to set up Codex.[/dim]"
- )
- return options.with_integration_override(self.integration_id, enabled)
-
def write_project_files(
self,
console_obj: Any,
diff --git a/packages/cli/src/repowise/cli/editor_integrations/codex_config.py b/packages/cli/src/repowise/cli/editor_integrations/codex_config.py
index 08c91e8df..f0c9d83f5 100644
--- a/packages/cli/src/repowise/cli/editor_integrations/codex_config.py
+++ b/packages/cli/src/repowise/cli/editor_integrations/codex_config.py
@@ -308,7 +308,12 @@ def install_agents_md_distill_section(repo_path: Path) -> Path | None:
Idempotent: an existing marker block is refreshed in place; a file that
already teaches distillation elsewhere (e.g. a future indexed-template
section) is left untouched; otherwise the block is appended. Returns the
- AGENTS.md path, or None on write failure.
+ AGENTS.md path, or None when nothing was written.
+
+ None covers two cases the caller reports the same way: a write failure, and
+ a file whose markers are unpaired. The marker helper refuses that second one
+ rather than guessing at a repair that could swallow the user's text, so
+ "not written" is the honest answer and the user has to unpick their own edit.
The marker mechanics live in ``agent_targets.formats.marker_block``; what
stays here is the Codex-specific policy — the section text, and the
@@ -316,6 +321,7 @@ def install_agents_md_distill_section(repo_path: Path) -> Path | None:
content rather than about managed blocks in general.
"""
from repowise.cli.agent_targets.formats import marker_block
+ from repowise.cli.agent_targets.types import FileAction
target = _agents_md_path(repo_path)
try:
@@ -323,14 +329,14 @@ def install_agents_md_distill_section(repo_path: Path) -> Path | None:
existing = target.read_text(encoding="utf-8")
if _DISTILL_MARKER_START not in existing and _DISTILL_SECTION_HEADING in existing:
return target # already taught elsewhere in the file
- marker_block.upsert(
+ action = marker_block.upsert(
target,
f"\n{_DISTILL_SECTION}\n",
_DISTILL_MARKER_START,
_DISTILL_MARKER_END,
new_file_prefix=_NEW_FILE_PLACEHOLDER,
)
- return target
+ return None if action is FileAction.KEPT else target
except OSError:
return None
diff --git a/packages/cli/src/repowise/cli/editor_integrations/vscode.py b/packages/cli/src/repowise/cli/editor_integrations/vscode.py
index f41e451fe..5e4a79056 100644
--- a/packages/cli/src/repowise/cli/editor_integrations/vscode.py
+++ b/packages/cli/src/repowise/cli/editor_integrations/vscode.py
@@ -5,8 +5,6 @@ from __future__ import annotations
from pathlib import Path
from typing import Any
-import click
-
from repowise.cli.agent_targets.targets import vscode as vscode_target
from repowise.cli.editor_setup import EditorSetupOptions
@@ -23,20 +21,6 @@ class VSCodeSetup:
integration_id = vscode_target.ID
project_file_id = vscode_target.PROJECT_FILE_ID
- def configure_options(
- self,
- console_obj: Any,
- options: EditorSetupOptions,
- ) -> EditorSetupOptions:
- if (
- not options.prompt_for_project_files
- or self.project_file_id in options.disabled_project_files
- ):
- return options
- if _prompt_vscode_enabled(console_obj):
- return options
- return options.with_disabled_project_file(self.project_file_id)
-
def write_project_files(
self,
console_obj: Any,
@@ -63,19 +47,6 @@ class VSCodeSetup:
_write_vscode_files(console_obj, repo_path)
-def _prompt_vscode_enabled(console_obj: Any) -> bool:
- """Ask whether the VS Code workspace config should be written."""
-
- console_obj.print()
- console_obj.print(
- "[bold]VS Code:[/bold] Configure the workspace MCP server and recommend the extension?"
- )
- return click.confirm(
- " Write .vscode/mcp.json and .vscode/extensions.json?",
- default=True,
- )
-
-
def _write_vscode_files(console_obj: Any, repo_path: Path) -> None:
"""Write or merge the managed .vscode files, skipping any JSONC file safely."""
diff --git a/packages/cli/src/repowise/cli/editor_setup.py b/packages/cli/src/repowise/cli/editor_setup.py
index d8c8efa4f..78a0a327c 100644
--- a/packages/cli/src/repowise/cli/editor_setup.py
+++ b/packages/cli/src/repowise/cli/editor_setup.py
@@ -137,7 +137,6 @@ class EditorSetupOptions:
"""Options shared across editor setup integrations."""
disabled_project_files: frozenset[str] = field(default_factory=frozenset)
- prompt_for_project_files: bool = False
project_file_overrides: dict[str, bool] = field(default_factory=dict)
integration_overrides: dict[str, bool] = field(default_factory=dict)
@@ -146,25 +145,10 @@ class EditorSetupOptions:
return EditorSetupOptions(
disabled_project_files=self.disabled_project_files | {project_file_id},
- prompt_for_project_files=self.prompt_for_project_files,
project_file_overrides=dict(self.project_file_overrides),
integration_overrides=dict(self.integration_overrides),
)
- def with_project_file_override(
- self,
- project_file_id: str,
- enabled: bool,
- ) -> EditorSetupOptions:
- """Return options with one managed project file explicitly enabled or disabled."""
-
- return EditorSetupOptions(
- disabled_project_files=self.disabled_project_files,
- prompt_for_project_files=self.prompt_for_project_files,
- project_file_overrides={**self.project_file_overrides, project_file_id: enabled},
- integration_overrides=dict(self.integration_overrides),
- )
-
def with_integration_override(
self,
integration_id: str,
@@ -174,7 +158,6 @@ class EditorSetupOptions:
return EditorSetupOptions(
disabled_project_files=self.disabled_project_files,
- prompt_for_project_files=self.prompt_for_project_files,
project_file_overrides=dict(self.project_file_overrides),
integration_overrides={**self.integration_overrides, integration_id: enabled},
)
@@ -191,24 +174,88 @@ def _resolve_integrations(
def resolve_editor_setup_options(
- console_obj: Any,
*,
disabled_project_files: Iterable[str] | None = None,
- prompt_for_project_files: bool = False,
project_file_overrides: Mapping[str, bool] | None = None,
integration_overrides: Mapping[str, bool] | None = None,
- integrations: tuple[InstallLifecycle, ...] | None = None,
) -> EditorSetupOptions:
- """Build setup options, allowing integrations to own their prompts."""
+ """Build setup options from the CLI flags.
- options = EditorSetupOptions(
+ Used to also give every integration a chance to prompt, through a
+ ``configure_options`` hook. That is gone: the prompting is now one
+ checklist (:func:`select_agents_interactively`) built from the registry
+ rather than one hand-written question per agent, so the hook had no
+ implementation left that did anything.
+ """
+
+ return EditorSetupOptions(
disabled_project_files=frozenset(disabled_project_files or ()),
- prompt_for_project_files=prompt_for_project_files,
project_file_overrides=dict(project_file_overrides or {}),
integration_overrides=dict(integration_overrides or {}),
)
- for integration in _resolve_integrations(integrations):
- options = integration.configure_options(console_obj, options)
+
+
+def select_agents_interactively(
+ console_obj: Any,
+ repo_path: Path,
+ options: EditorSetupOptions,
+) -> EditorSetupOptions:
+ """Ask once which agents to set up, and fold the answer into *options*.
+
+ Replaces the three sequential yes/no prompts each integration used to own
+ — one per agent, in registry order, each hand-written. Two things were wrong
+ with that shape and only one of them was cosmetic. The cosmetic one: Codex
+ defaulted to *no* while its two neighbours defaulted to yes, so holding
+ Enter through the sequence silently inverted in the middle, and the code
+ apologised for it in a dim line. The structural one: a fourth agent meant a
+ fourth prompt, written by hand, in a fourth module.
+
+ Now the checklist is built from the registry and pre-ticked from detection,
+ so an agent is offered because it is installed rather than because someone
+ remembered to write a question for it.
+
+ The mapping back onto options carries no per-agent knowledge: an unticked
+ agent has its own ``project_file_id`` disabled and its integration id
+ overridden off, both of which the descriptor supplies. A ticked one is
+ overridden on. An id already carrying an explicit override (a CLI flag such
+ as ``--codex``) is shown pre-ticked to match the flag, so accepting the
+ checklist re-applies what the flag already said.
+ """
+ from repowise.cli.agent_targets.registry import default_selection, describe_agents
+ from repowise.cli.ui.agent_selection import AgentChoice, interactive_agent_select
+
+ rows = describe_agents(repo_path)
+ ticked = default_selection(rows)
+ for row in rows:
+ flagged = options.integration_overrides.get(row["id"])
+ if flagged is not None:
+ ticked = (ticked | {row["id"]}) if flagged else (ticked - {row["id"]})
+
+ chosen = interactive_agent_select(
+ console_obj,
+ [
+ AgentChoice(
+ id=row["id"],
+ display_name=row["display_name"],
+ detail=(
+ "already wired"
+ if row["registrations"]
+ else ("installed" if row["present"] else "not detected")
+ ),
+ enabled=row["id"] in ticked,
+ )
+ for row in rows
+ ],
+ )
+ if chosen is None:
+ # stdin claimed a terminal and then returned EOF. Keep the defaults.
+ return options
+
+ for row in rows:
+ enabled = row["id"] in chosen
+ options = options.with_integration_override(row["id"], enabled)
+ if not enabled:
+ options = options.with_disabled_project_file(row["project_file_id"])
return options
diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.py
index 372498468..8c4eb02ff 100644
--- a/packages/cli/src/repowise/cli/main.py
+++ b/packages/cli/src/repowise/cli/main.py
@@ -76,6 +76,7 @@ _OSS_COMMANDS: tuple[tuple[str, str], ...] = (
("corrections", "corrections_cmd:corrections_command"),
("export", "export_cmd:export_command"),
("hook", "hook_cmd:hook_group"),
+ ("agents", "agents_cmd:agents_group"),
("status", "status_cmd:status_command"),
("doctor", "doctor_cmd:doctor_command"),
("watch", "watch_cmd:watch_command"),
diff --git a/packages/cli/src/repowise/cli/mcp_config.py b/packages/cli/src/repowise/cli/mcp_config.py
index a31c0719a..92c2dc040 100644
--- a/packages/cli/src/repowise/cli/mcp_config.py
+++ b/packages/cli/src/repowise/cli/mcp_config.py
@@ -230,28 +230,28 @@ def enable_codex_hooks_feature(repo_path: Path) -> Path:
"""Enable Codex hooks in project-local .codex/config.toml."""
from repowise.cli.agent_targets.targets import codex
- return codex.enable_hooks_feature(repo_path)
+ return codex.enable_hooks_feature(repo_path).path
def save_codex_mcp_config(repo_path: Path) -> Path:
"""Merge the repowise MCP server into project-local .codex/config.toml."""
from repowise.cli.agent_targets.targets import codex
- return codex.write_server_config(repo_path)
+ return codex.write_server_config(repo_path).path
def save_codex_hooks_config(repo_path: Path) -> Path:
"""Merge repowise hooks into project-local .codex/hooks.json."""
from repowise.cli.agent_targets.targets import codex
- return codex.write_hooks_config(repo_path)
+ return codex.write_hooks_config(repo_path)[0].path
def save_root_mcp_config(repo_path: Path) -> Path:
"""Write .mcp.json at repo root for MCP clients that support discovery."""
from repowise.cli.agent_targets.targets import claude_code
- return claude_code.write_project_mcp_config(repo_path)
+ return claude_code.write_project_mcp_config(repo_path).path
def generate_vscode_mcp_server_entry(repo_path: Path) -> dict:
@@ -270,7 +270,7 @@ def save_vscode_mcp_config(repo_path: Path) -> Path:
"""
from repowise.cli.agent_targets.targets import vscode
- return vscode.write_mcp_config(repo_path)
+ return vscode.write_mcp_config(repo_path).path
def save_vscode_extensions_config(repo_path: Path) -> Path:
@@ -281,7 +281,7 @@ def save_vscode_extensions_config(repo_path: Path) -> Path:
"""
from repowise.cli.agent_targets.targets import vscode
- return vscode.write_extensions_config(repo_path)
+ return vscode.write_extensions_config(repo_path).path
#: Re-exported for the Codex hooks writer's own use and for callers that used
diff --git a/packages/cli/src/repowise/cli/ui/agent_selection.py b/packages/cli/src/repowise/cli/ui/agent_selection.py
new file mode 100644
index 000000000..b3cf3d5d6
--- /dev/null
+++ b/packages/cli/src/repowise/cli/ui/agent_selection.py
@@ -0,0 +1,104 @@
+"""The one prompt that asks which agents repowise should wire up.
+
+Replaces three sequential yes/no questions — one per agent, asked in a fixed
+order, each written by hand — with a single checklist whose boxes are ticked
+from detection. The three questions had a wart the checklist removes rather
+than explains: Codex defaulted to *no* while its two neighbours defaulted to
+yes, so Enter-through silently inverted in the middle, and the code had to
+apologise for it in a dim line. A box that is ticked because the agent is
+installed needs no apology.
+
+Shared by ``init`` and ``repowise agents add``, which is what keeps their
+answers to "is this answerable" identical rather than merely similar.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
+from rich.prompt import Prompt
+
+from repowise.cli.ui.brand import BRAND_STYLE
+from repowise.cli.ui.workspace_selection import parse_selection
+
+
+@dataclass(frozen=True)
+class AgentChoice:
+ """One row of the checklist."""
+
+ id: str
+ display_name: str
+ #: Why the box is (or is not) ticked — "wired already", "installed", "".
+ detail: str
+ #: Whether it starts ticked.
+ enabled: bool
+
+
+def interactive_agent_select(
+ console_obj: Any,
+ choices: list[AgentChoice],
+) -> set[str] | None:
+ """Ask which agents to set up. Returns the chosen ids, or None.
+
+ ``None`` means the question could not be asked — stdin reported a terminal
+ and then returned EOF. That happens under Git Bash on Windows with
+ ``< /dev/null``, under some pty wrappers, and under ``docker run -t``
+ without ``-i``; agents drive the CLI through exactly those shapes. The
+ caller treats None as "keep the pre-ticked set" and carries on, rather than
+ dying on a question nobody can hear. Only ``EOFError`` is swallowed: a real
+ Ctrl-C still raises and still stops the run.
+
+ Enter accepts the ticked set. Numbers *toggle*, so unticking the one box
+ the user disagrees with costs one keystroke rather than retyping the rest.
+ """
+ if not choices:
+ return set()
+
+ selected = {choice.id for choice in choices if choice.enabled}
+
+ console_obj.print()
+ # Says "project files" rather than "set up" because that is the honest
+ # scope: it is what the three per-agent prompts it replaced controlled.
+ # The global MCP registration is a separate step and unticking a box here
+ # does not withdraw it, so the question must not imply that it does.
+ console_obj.print(
+ "[bold]Agent integrations:[/bold] write project config and instruction files for?"
+ )
+ for index, choice in enumerate(choices, 1):
+ # ``\[`` escapes the bracket for rich. Unescaped, ``[x]`` is valid
+ # markup and gets eaten as a style tag while ``[ ]`` is not and
+ # survives — so every ticked box rendered blank and every unticked one
+ # rendered as a box, which reads as the exact inverse of the truth.
+ box = r"\[x]" if choice.id in selected else r"\[ ]"
+ detail = f" [dim]{choice.detail}[/dim]" if choice.detail else ""
+ console_obj.print(
+ f" {box} [{BRAND_STYLE}][{index}][/] {choice.display_name}{detail}"
+ )
+ console_obj.print(" [dim]Enter to accept, or numbers to toggle (1,3), 'all', 'none'.[/dim]")
+
+ try:
+ raw = Prompt.ask(" Set up", default="", show_default=False, console=console_obj)
+ except EOFError:
+ return None
+
+ raw = raw.strip().lower()
+ if not raw:
+ return selected
+ if raw == "all":
+ return {choice.id for choice in choices}
+ if raw == "none":
+ return set()
+
+ toggled = parse_selection(raw, len(choices))
+ if toggled is None:
+ # One reprompt would be a loop with no exit for a non-interactive
+ # caller that answered garbage. The ticked set is a safe answer and the
+ # user can rerun `repowise agents add` to change it.
+ console_obj.print(" [dim]Not a selection; keeping the ticked agents.[/dim]")
+ return selected
+
+ for index in toggled:
+ choice_id = choices[index].id
+ selected.symmetric_difference_update({choice_id})
+ return selected
diff --git a/packages/cli/src/repowise/cli/ui/workspace_selection.py b/packages/cli/src/repowise/cli/ui/workspace_selection.py
index ee5d035cc..185799bd7 100644
--- a/packages/cli/src/repowise/cli/ui/workspace_selection.py
+++ b/packages/cli/src/repowise/cli/ui/workspace_selection.py
@@ -79,7 +79,7 @@ def interactive_repo_select(
if raw == "none":
return []
- selected = _parse_selection(raw, len(repos))
+ selected = parse_selection(raw, len(repos))
if selected is not None:
return [repos[i] for i in selected]
@@ -88,11 +88,15 @@ def interactive_repo_select(
)
-def _parse_selection(raw: str, count: int) -> list[int] | None:
+def parse_selection(raw: str, count: int) -> list[int] | None:
"""Parse a comma-separated selection string into zero-based indices.
Supports: ``"1,2,3"``, ``"1-3"``, ``"1,3-5"``, ``"1-3,5"``.
Returns ``None`` on invalid input.
+
+ Shared with the agent multiselect, which uses the same numbers-and-ranges
+ grammar. One parser means one set of accepted spellings across the CLI's
+ list prompts rather than two that drift.
"""
indices: list[int] = []
for part in raw.split(","):
diff --git a/tests/unit/cli/test_agent_target_baseline.py b/tests/unit/cli/test_agent_target_baseline.py
index 1b67d1880..d91344a04 100644
--- a/tests/unit/cli/test_agent_target_baseline.py
+++ b/tests/unit/cli/test_agent_target_baseline.py
@@ -274,28 +274,21 @@ def test_integration_writes_match_baseline(baseline_env) -> None:
), f"{scope}/{rel} changed line-ending discipline"
-#: The one file today's code does not write idempotently. ``.codex/config.toml``
-#: is rebuilt by two regex table-rewrites in sequence — ``save_codex_mcp_config``
-#: strips and re-appends ``[mcp_servers.repowise]``, then
-#: ``enable_codex_hooks_feature`` does the same for ``[features]``. On a clean
-#: repo the tables are written in that order; on the second run each strip moves
-#: its table to the end, they swap back, and the leading newline the swap leaves
-#: behind is never stripped (``rstrip`` only touches the tail). The result gains
-#: exactly one leading ``\n`` on run 2 and is stable from run 3 onward. It stays
-#: valid TOML and parses identically, so this is cosmetic drift, not corruption
-#: — but it is real, it predates this work, and the seam's deep-equal-before-write
-#: is what fixes it. When it does, this test fails loudly and the exception is
-#: removed on purpose rather than by accident.
-_KNOWN_NON_IDEMPOTENT = {("project", ".codex/config.toml")}
-
-
def test_writes_are_idempotent(baseline_env) -> None:
- """Re-running the full write path changes nothing, bar one known file.
-
- Re-running ``init`` is the common case, and the seam's ``WriteResult``
- contract promises an ``unchanged`` action for it. That promise is only
- testable against a known starting point, so pin today's stability here —
- before the rewrite, not after — including the one place it does not hold.
+ """Re-running the full write path changes nothing at all.
+
+ Re-running ``init`` is the common case, and the ``WriteResult`` contract
+ promises an ``unchanged`` action for it.
+
+ This test used to carry one named exception. ``.codex/config.toml`` is
+ rebuilt by two regex table-rewrites in sequence — the server table, then
+ ``[features]`` — and each strip moved its table to the end, so run 2 swapped
+ them back and kept the blank line the swap left, gaining exactly one leading
+ ``\\n``. Valid TOML throughout, so it was cosmetic, but it was real and it
+ predated the seam. ``toml_merge.write_if_changed`` closed it by comparing
+ parsed *documents* rather than text, and the exception was removed here on
+ purpose. It was written to keep passing after the fix rather than to fail,
+ so nothing but this paragraph would have reminded anyone.
"""
home, repo = baseline_env
console = _silent_console()
@@ -306,24 +299,9 @@ def test_writes_are_idempotent(baseline_env) -> None:
first, second, third = _run(), _run(), _run()
- for scope in ("project", "user"):
- for rel in sorted(first[scope]):
- if (scope, rel) in _KNOWN_NON_IDEMPOTENT:
- continue
- assert first[scope][rel] == second[scope][rel], (
- f"{scope}/{rel} is not stable across re-runs"
- )
-
- # Whatever the first run leaves unsettled must settle immediately, so an
- # `init` loop cannot accumulate drift run after run.
+ assert first == second, "a second run changed a file the first run had settled"
assert second == third
- codex = second["project"][".codex/config.toml"]["content"]
- assert codex == "\n" + first["project"][".codex/config.toml"]["content"], (
- "the known .codex/config.toml drift changed shape; re-derive it before "
- "updating _KNOWN_NON_IDEMPOTENT"
- )
-
@pytest.mark.skipif(sys.platform != "win32", reason="separator handling is Windows-specific")
def test_normalization_covers_windows_separator_spellings() -> None:
diff --git a/tests/unit/cli/test_agent_targets.py b/tests/unit/cli/test_agent_targets.py
index 31c2855bb..bbc2bc8d0 100644
--- a/tests/unit/cli/test_agent_targets.py
+++ b/tests/unit/cli/test_agent_targets.py
@@ -9,6 +9,7 @@ it.
from __future__ import annotations
import json
+import os
from pathlib import Path
import pytest
@@ -331,6 +332,166 @@ def test_json_deep_equal_separates_int_from_float() -> None:
assert json.dumps(1) != json.dumps(1.0)
+def test_write_json_config_reports_created_then_unchanged(tmp_path: Path) -> None:
+ """The deep-equal-before-write pass, from the caller's side."""
+ path = tmp_path / "mcp.json"
+
+ assert json_merge.write_json_config(path, {"a": 1}) is FileAction.CREATED
+ assert json_merge.write_json_config(path, {"a": 1}) is FileAction.UNCHANGED
+ assert json_merge.write_json_config(path, {"a": 2}) is FileAction.UPDATED
+
+
+def test_write_json_config_compares_the_bytes_it_would_land(tmp_path: Path) -> None:
+ """Not the raw rendering, and not a normalised read — the translated bytes.
+
+ This writer takes the platform newline translation. Comparing the
+ untranslated text calls every Windows re-run an update; normalising the
+ file's endings instead leaves a CRLF file un-normalised on POSIX. Only the
+ bytes that would actually land answer both.
+ """
+ path = tmp_path / "mcp.json"
+ json_merge.write_json_config(path, {"a": 1})
+ settled = path.read_bytes()
+
+ assert json_merge.write_json_config(path, {"a": 1}) is FileAction.UNCHANGED
+ assert path.read_bytes() == settled
+
+ # A file whose endings do not match this platform's writer is rewritten.
+ path.write_bytes(settled.replace(b"\r\n", b"\n").replace(b"\n", b"\r\n" if os.linesep == "\n" else b"\n"))
+ assert json_merge.write_json_config(path, {"a": 1}) is FileAction.UPDATED
+ assert path.read_bytes() == settled
+
+
+def test_codex_reinstall_reports_unchanged_and_leaves_config_alone(tmp_path: Path) -> None:
+ """The ``.codex/config.toml`` non-idempotency, closed.
+
+ Two table upserts per install, each of which strips its table and re-appends
+ it, so run 2 used to swap them back and keep the blank line the swap left.
+ The document-level comparison means run 2 writes nothing at all.
+ """
+ from repowise.cli.agent_targets.targets import codex as codex_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+
+ first = codex_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+ settled = (repo / ".codex" / "config.toml").read_bytes()
+ assert first.changed
+
+ second = codex_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ assert not second.changed
+ assert {f.action for f in second.files} == {FileAction.UNCHANGED}
+ assert (repo / ".codex" / "config.toml").read_bytes() == settled
+
+
+def test_codex_keeps_user_keys_added_to_its_server_table(tmp_path: Path) -> None:
+ """The TOML twin of the ``env``-block fix (#307) the JSON path already had.
+
+ ``replace_table`` rewrites the whole table, so without a merge every key a
+ user added to ``[mcp_servers.repowise]`` was dropped on every single write.
+ """
+ import tomllib
+
+ from repowise.cli.agent_targets.targets import codex as codex_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ codex_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ config_path = repo / ".codex" / "config.toml"
+ config_path.write_text(
+ config_path.read_text(encoding="utf-8").replace(
+ "startup_timeout_sec = 20", 'startup_timeout_sec = 20\nenv_key = "mine"'
+ ),
+ encoding="utf-8",
+ )
+
+ codex_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ table = tomllib.loads(config_path.read_text(encoding="utf-8"))["mcp_servers"]["repowise"]
+ assert table["env_key"] == "mine"
+ # ...while a generated key still wins, so a moved repo repoints.
+ assert table["cwd"] == str(repo.resolve())
+
+
+def test_codex_preserves_an_env_table_rather_than_choking_on_it(tmp_path: Path) -> None:
+ """``env`` is the key most likely to be there, and it is a table.
+
+ Preserving a user's keys means re-rendering them, so the narrow serializer
+ meets a dict the first time anyone has an env block — the standard case,
+ not an exotic one. It renders as an inline table.
+ """
+ import tomllib
+
+ from repowise.cli.agent_targets.targets import codex as codex_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ codex_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ config_path = repo / ".codex" / "config.toml"
+ config_path.write_text(
+ config_path.read_text(encoding="utf-8").replace(
+ "startup_timeout_sec = 20",
+ 'startup_timeout_sec = 20\nenv = { RUST_LOG = "debug" }\ntimeout = 1.5',
+ ),
+ encoding="utf-8",
+ )
+
+ codex_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ table = tomllib.loads(config_path.read_text(encoding="utf-8"))["mcp_servers"]["repowise"]
+ assert table["env"] == {"RUST_LOG": "debug"}
+ assert table["timeout"] == 1.5
+
+
+def test_codex_refuses_a_value_it_cannot_rewrite_without_a_traceback(tmp_path: Path) -> None:
+ """This runs inside ``init`` with no try around it, so it must not raise raw.
+
+ Every other refusal in this writer is a ClickException naming the file and
+ saying nothing was written; a bare TypeError mid-``init`` is neither.
+ """
+ import click
+
+ from repowise.cli.agent_targets.targets import codex as codex_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ codex_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ config_path = repo / ".codex" / "config.toml"
+ before = config_path.read_text(encoding="utf-8")
+ config_path.write_text(
+ before.replace("startup_timeout_sec = 20", "startup_timeout_sec = 20\nports = [1, 2]"),
+ encoding="utf-8",
+ )
+ poisoned = config_path.read_text(encoding="utf-8")
+
+ with pytest.raises(click.ClickException) as excinfo:
+ codex_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ assert "no changes were written" in str(excinfo.value)
+ assert config_path.read_text(encoding="utf-8") == poisoned
+
+
+def test_marker_block_remove_refuses_what_upsert_refuses(tmp_path: Path) -> None:
+ """Guarding only the write half still lets uninstall eat the sentence.
+
+ ``remove`` strips *every* matched span, so on one real block plus a
+ sentence quoting both markers it deletes the middle of the sentence — the
+ exact file shape ``upsert`` refuses.
+ """
+ doc = tmp_path / "AGENTS.md"
+ original = (
+ "Docs: we manage the text between <!--S--> and <!--E-->.\n\n<!--S-->\nBODY\n<!--E-->\n"
+ )
+ doc.write_text(original, encoding="utf-8", newline="\n")
+
+ assert marker_block.remove(doc, "<!--S-->", "<!--E-->") is False
+ assert doc.read_text(encoding="utf-8") == original
+
+
def test_atomic_write_leaves_no_temp_file_behind(tmp_path: Path) -> None:
target = tmp_path / "nested" / "config.json"
target.parent.mkdir()
@@ -397,8 +558,59 @@ def test_marker_block_round_trips_user_content_byte_for_byte(tmp_path: Path) ->
def test_marker_block_upsert_is_idempotent(tmp_path: Path) -> None:
doc = tmp_path / "AGENTS.md"
- assert marker_block.upsert(doc, "\nbody\n", "<!--S-->", "<!--E-->") is True
- assert marker_block.upsert(doc, "\nbody\n", "<!--S-->", "<!--E-->") is False
+ assert marker_block.upsert(doc, "\nbody\n", "<!--S-->", "<!--E-->") is FileAction.CREATED
+ assert marker_block.upsert(doc, "\nbody\n", "<!--S-->", "<!--E-->") is FileAction.UNCHANGED
+
+
+def test_marker_block_refuses_an_orphaned_marker(tmp_path: Path) -> None:
+ """A start with no end is left strictly alone, and said so.
+
+ Every repair here loses something. Appending a fresh block leaves the stray
+ start above it, so the next run's non-greedy ``start.*?end`` spans from the
+ orphan to *our* end marker and eats whatever the user wrote in between.
+ Before this, upsert reported "unchanged" and wrote nothing — technically
+ safe, but it claimed the block was installed when it was absent.
+ """
+ doc = tmp_path / "AGENTS.md"
+ original = "<!--S-->\nI deleted the end marker\n\nMy own paragraph.\n"
+ doc.write_text(original, encoding="utf-8", newline="\n")
+
+ assert marker_block.upsert(doc, "\nbody\n", "<!--S-->", "<!--E-->") is FileAction.KEPT
+ assert doc.read_text(encoding="utf-8") == original
+
+
+def test_marker_block_refuses_a_duplicated_block(tmp_path: Path) -> None:
+ """Collapsing to the first copy is the trap, not the fix.
+
+ It reads as safe — every copy is ours, so there is nothing of theirs to
+ lose. But ``inspect`` counts marker occurrences, so it cannot tell two
+ blocks from one block plus a sentence quoting both markers, and collapsing
+ deletes the sentence.
+ """
+ doc = tmp_path / "AGENTS.md"
+ original = (
+ "# Notes\n\n<!--S-->managed<!--E-->\n\n"
+ "Repowise owns the text between <!--S--> and <!--E-->, so leave it alone.\n"
+ )
+ doc.write_text(original, encoding="utf-8", newline="\n")
+
+ assert marker_block.upsert(doc, "\nbody\n", "<!--S-->", "<!--E-->") is FileAction.KEPT
+ assert doc.read_text(encoding="utf-8") == original
+
+
+def test_marker_block_never_wedges_itself_on_a_nested_pair(tmp_path: Path) -> None:
+ """A repair that leaves the file worse than it found it is not a repair.
+
+ Rewriting the first match of ``S A S B E text E`` leaves a stray trailing
+ end marker, which reads as orphaned forever after — so the managed block
+ could never be updated again, by any command.
+ """
+ doc = tmp_path / "AGENTS.md"
+ original = "<!--S-->a<!--S-->b<!--E-->keep me<!--E-->\n"
+ doc.write_text(original, encoding="utf-8", newline="\n")
+
+ assert marker_block.upsert(doc, "\nbody\n", "<!--S-->", "<!--E-->") is FileAction.KEPT
+ assert doc.read_text(encoding="utf-8") == original
def test_marker_block_normalizes_a_crlf_file_whose_block_is_current(tmp_path: Path) -> None:
@@ -416,12 +628,12 @@ def test_marker_block_normalizes_a_crlf_file_whose_block_is_current(tmp_path: Pa
doc.write_bytes(lf_content.encode("utf-8"))
assert b"\r\n" in doc.read_bytes()
- changed = marker_block.upsert(doc, body, "<!--S-->", "<!--E-->")
+ action = marker_block.upsert(doc, body, "<!--S-->", "<!--E-->")
- assert changed is True
+ assert action is FileAction.UPDATED
assert b"\r\n" not in doc.read_bytes()
# A second pass has nothing left to do.
- assert marker_block.upsert(doc, body, "<!--S-->", "<!--E-->") is False
+ assert marker_block.upsert(doc, body, "<!--S-->", "<!--E-->") is FileAction.UNCHANGED
def test_marker_block_uses_lf_regardless_of_platform(tmp_path: Path) -> None:
diff --git a/tests/unit/cli/test_agents_cmd.py b/tests/unit/cli/test_agents_cmd.py
new file mode 100644
index 000000000..a6b7b1244
--- /dev/null
+++ b/tests/unit/cli/test_agents_cmd.py
@@ -0,0 +1,468 @@
+"""``repowise agents``, driven end to end through ``CliRunner``.
+
+Every subcommand is exercised in **both** renderings. That is the point of the
+file rather than a nicety: the payload and the table are built from one dict, so
+a key that no renderer prints and a key a renderer needs but the payload dropped
+are both invisible to a test that checks only one side. Running both through the
+real command is what catches them.
+
+The home directory is redirected for every test here. Detection reads
+``~/.claude`` and ``~/.codex``, and a test that skipped the redirect would pass
+or fail depending on whose machine ran it, and worse, the write paths would
+reach the real global config.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli.main import cli
+
+
+def repo(tmp_path_factory, monkeypatch) -> Path:
+ """A git-less repo plus a redirected home, with the machine pinned out."""
+ home = tmp_path_factory.mktemp("agents_home")
+ repo_path = tmp_path_factory.mktemp("agents_repo")
+
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("USERPROFILE", str(home))
+ monkeypatch.setenv("HOMEDRIVE", home.drive or "")
+ monkeypatch.setenv("HOMEPATH", str(home)[len(home.drive) :])
+ monkeypatch.setattr(Path, "home", lambda: home)
+ # A benchmark or CI runner that exported this would silently turn the
+ # user-scope assertions below into no-ops.
+ monkeypatch.delenv("REPOWISE_SKIP_EDITOR_SETUP", raising=False)
+
+ (repo_path / ".repowise").mkdir()
+ # The bare listing takes no path argument (a group with an optional
+ # positional cannot tell one from a subcommand name), so it reads the cwd.
+ monkeypatch.chdir(repo_path)
+ return repo_path
+
+
+def _run(args: list[str]) -> object:
+ result = CliRunner().invoke(cli, args, catch_exceptions=False)
+ assert result.exit_code == 0, result.output
+ return result
+
+
+def _json(args: list[str]) -> dict:
+ result = _run([*args, "--format", "json"])
+ return json.loads(result.output)
+
+
+# ---------------------------------------------------------------------------
+# list (the bare command)
+# ---------------------------------------------------------------------------
+
+
+def test_bare_agents_lists_every_registered_target_as_a_table(repo: Path) -> None:
+ output = _run(["agents"]).output
+ assert "claude-code" in output
+ assert "codex" in output
+ assert "vscode" in output
+
+
+def test_bare_agents_lists_every_registered_target_as_json(repo: Path) -> None:
+ payload = _json(["agents"])
+ assert [row["id"] for row in payload["agents"]] == ["claude-code", "codex", "vscode"]
+ for row in payload["agents"]:
+ # The keys the table renders, so a dropped one is a broken table.
+ assert set(row) >= {"id", "tier", "present", "registrations", "method"}
+ assert payload["agents"][0]["tier"] == "full"
+ assert payload["agents"][2]["tier"] == "good"
+
+
+def test_list_reports_registrations_as_a_list_not_a_boolean(repo: Path) -> None:
+ """'Configured' cannot express 'configured twice', which is the whole point."""
+ _run(["agents", "add", str(repo), "--target", "vscode", "-y"])
+ payload = _json(["agents"])
+ vscode = next(row for row in payload["agents"] if row["id"] == "vscode")
+ assert len(vscode["registrations"]) == 1
+ assert vscode["registrations"][0]["scope"] == "project"
+
+
+# ---------------------------------------------------------------------------
+# add
+# ---------------------------------------------------------------------------
+
+
+def test_add_writes_the_named_target_and_reports_it_as_a_table(repo: Path) -> None:
+ output = _run(["agents", "add", str(repo), "--target", "vscode", "-y"]).output
+ assert "created" in output
+ assert (repo / ".vscode" / "mcp.json").exists()
+
+
+def test_add_reports_every_file_and_action_as_json(repo: Path) -> None:
+ payload = _json(["agents", "add", str(repo), "--target", "vscode", "-y"])
+
+ assert payload["action"] == "add"
+ assert payload["changed"] is True
+ agent = payload["agents"][0]
+ assert agent["method"] == "direct"
+ actions = {f["action"] for f in agent["writes"]["project"]["files"]}
+ assert actions == {"created"}
+
+
+def test_add_is_idempotent_and_says_so(repo: Path) -> None:
+ """A re-run must report unchanged rather than an update it did not make."""
+ _run(["agents", "add", str(repo), "--target", "vscode", "-y"])
+ payload = _json(["agents", "add", str(repo), "--target", "vscode", "-y"])
+
+ assert payload["changed"] is False
+ actions = {f["action"] for f in payload["agents"][0]["writes"]["project"]["files"]}
+ assert actions == {"unchanged"}
+
+
+def test_add_stands_down_when_the_host_plugin_already_provides_it(
+ repo: Path, monkeypatch
+) -> None:
+ """The duplicate-registration fix, from the command's side.
+
+ A machine with the Claude Code plugin installed already has the MCP server
+ and the augment hooks. Writing them again costs a second process spawn per
+ matched tool call and a second copy of every tool schema, for no benefit.
+
+ Scoped to the *user* config, which is the only thing the plugin covers. The
+ repo-shared ``.mcp.json`` is a committed file other contributors' checkouts
+ read and the plugin does not write it, so standing down for the whole
+ target — as this did at first — meant a plugin user's ``agents add`` wrote
+ nothing at all.
+ """
+ from repowise.cli.agent_targets.targets import claude_code as target_mod
+
+ manifest = Path.home() / ".claude" / "plugins" / "installed_plugins.json"
+ manifest.parent.mkdir(parents=True)
+ manifest.write_text(
+ json.dumps(
+ {
+ "version": 2,
+ "plugins": {target_mod.PLUGIN_KEY: [{"scope": "user", "version": "0.41.0"}]},
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ payload = _json(["agents", "add", str(repo), "--target", "claude-code", "-y"])
+
+ agent = payload["agents"][0]
+ assert "host-managed" in agent["skips"]["user"]
+ assert "user" not in agent["writes"]
+ assert not (Path.home() / ".claude" / "settings.json").exists()
+ # ...but the committed repo file is still written, with a note, because
+ # this machine now does load repowise from both.
+ project = agent["writes"]["project"]
+ assert project["files"][0]["action"] == "created"
+ assert (repo / ".mcp.json").exists()
+ assert any("load repowise from both" in note for note in project["notes"])
+
+
+def test_the_stand_down_follows_the_scope_the_host_actually_covers(
+ repo: Path, monkeypatch
+) -> None:
+ """Hard-coding it to user scope is wrong in both directions.
+
+ Claude Code's detection genuinely models a project-scoped plugin. Against
+ one, a constant put the duplicate write on the scope the plugin covers and
+ the skip — with a false reason — on the scope it does not.
+ """
+ from repowise.cli.agent_targets.targets import claude_code as target_mod
+
+ manifest = Path.home() / ".claude" / "plugins" / "installed_plugins.json"
+ manifest.parent.mkdir(parents=True)
+ manifest.write_text(
+ json.dumps(
+ {
+ "version": 2,
+ "plugins": {target_mod.PLUGIN_KEY: [{"scope": "project", "version": "0.41.0"}]},
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ payload = _json(["agents", "add", str(repo), "--target", "claude-code", "-y"])
+
+ agent = payload["agents"][0]
+ assert "host-managed" in agent["skips"]["project"]
+ assert not (repo / ".mcp.json").exists()
+ # The user scope is not covered by a project-scoped plugin, so it is wired.
+ assert "user" in agent["writes"]
+
+
+def test_add_honours_the_skip_env_var_for_user_scope(repo: Path, monkeypatch) -> None:
+ """The flag means what it says: never touch the developer's global config."""
+ monkeypatch.setenv("REPOWISE_SKIP_EDITOR_SETUP", "1")
+
+ payload = _json(["agents", "add", str(repo), "--target", "claude-code", "-y"])
+
+ agent = payload["agents"][0]
+ assert "user" not in agent["writes"]
+ assert "project" in agent["writes"]
+ assert not (Path.home() / ".claude" / "settings.json").exists()
+
+
+def test_add_rejects_an_unknown_target_by_name(repo: Path) -> None:
+ """A typo must not resolve to nothing and report success."""
+ result = CliRunner().invoke(cli, ["agents", "add", str(repo), "--target", "cursr", "-y"])
+ assert result.exit_code != 0
+ assert "cursr" in result.output
+ assert "claude-code" in result.output
+
+
+# ---------------------------------------------------------------------------
+# remove
+# ---------------------------------------------------------------------------
+
+
+def test_remove_takes_the_entry_out_and_reports_it_both_ways(repo: Path) -> None:
+ _run(["agents", "add", str(repo), "--target", "vscode", "-y"])
+
+ payload = _json(["agents", "remove", str(repo), "--target", "vscode"])
+ assert payload["action"] == "remove"
+ assert payload["agents"][0]["writes"]["project"]["files"][0]["action"] == "removed"
+
+ config = json.loads((repo / ".vscode" / "mcp.json").read_text(encoding="utf-8"))
+ assert "repowise" not in config["servers"]
+
+ output = _run(["agents", "remove", str(repo), "--target", "vscode"]).output
+ assert "not-found" in output
+
+
+def test_remove_requires_an_explicit_target(repo: Path) -> None:
+ """'Remove whatever you detect' is a bad default for a destructive verb."""
+ result = CliRunner().invoke(cli, ["agents", "remove", str(repo)])
+ assert result.exit_code != 0
+ assert "--target" in result.output
+
+
+# ---------------------------------------------------------------------------
+# refresh
+# ---------------------------------------------------------------------------
+
+
+def test_refresh_rewrites_what_is_wired_and_adds_nothing(repo: Path) -> None:
+ _run(["agents", "add", str(repo), "--target", "vscode", "-y"])
+
+ payload = _json(["agents", "refresh", str(repo)])
+
+ assert [agent["id"] for agent in payload["agents"]] == ["vscode"]
+ assert not (repo / ".codex").exists()
+
+
+def test_refresh_repoints_a_stale_entry(repo: Path) -> None:
+ """The reason refresh exists: a config that exists but points elsewhere."""
+ _run(["agents", "add", str(repo), "--target", "vscode", "-y"])
+ config_path = repo / ".vscode" / "mcp.json"
+ config = json.loads(config_path.read_text(encoding="utf-8"))
+ config["servers"]["repowise"]["args"] = ["mcp", "/gone", "--transport", "stdio"]
+ config_path.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
+
+ payload = _json(["agents", "refresh", str(repo)])
+
+ assert payload["changed"] is True
+ refreshed = json.loads(config_path.read_text(encoding="utf-8"))
+ assert "/gone" not in refreshed["servers"]["repowise"]["args"]
+
+
+def test_refresh_does_not_create_a_scope_that_was_not_wired(repo: Path) -> None:
+ """"Adds nothing" has to mean it per scope, not per agent.
+
+ Codex wired project-only must not have its per-machine hooks file written
+ as a side effect of a refresh — otherwise ``doctor --repair`` buys a global
+ config write with a repo-local detection.
+ """
+ _run(["agents", "add", str(repo), "--target", "codex", "--scope", "project", "-y"])
+ user_hooks = Path.home() / ".codex" / "hooks.json"
+ assert not user_hooks.exists()
+
+ payload = _json(["agents", "refresh", str(repo)])
+
+ agent = next(a for a in payload["agents"] if a["id"] == "codex")
+ assert "user" not in agent["writes"]
+ assert "refresh adds nothing" in agent["skips"]["user"]
+ assert not user_hooks.exists()
+
+
+def test_remove_takes_the_extension_recommendation_with_it(repo: Path) -> None:
+ """install writes both .vscode files, so remove has to account for both."""
+ _run(["agents", "add", str(repo), "--target", "vscode", "-y"])
+ extensions = repo / ".vscode" / "extensions.json"
+ assert "repowise-dev.repowise" in extensions.read_text(encoding="utf-8")
+
+ payload = _json(["agents", "remove", str(repo), "--target", "vscode"])
+
+ written = {f["path"]: f["action"] for f in payload["agents"][0]["writes"]["project"]["files"]}
+ assert written[str(extensions)] == "removed"
+ assert json.loads(extensions.read_text(encoding="utf-8"))["recommendations"] == []
+
+
+def test_refresh_on_a_clean_repo_says_nothing_is_wired(repo: Path) -> None:
+ output = _run(["agents", "refresh", str(repo)]).output
+ assert "No agent is wired up yet" in output
+ assert _json(["agents", "refresh", str(repo)])["agents"] == []
+
+
+# ---------------------------------------------------------------------------
+# print-config
+# ---------------------------------------------------------------------------
+
+
+def test_print_config_emits_a_bare_snippet_and_writes_nothing(repo: Path) -> None:
+ output = _run(["agents", "print-config", "vscode", str(repo)]).output
+ assert json.loads(output)["servers"]["repowise"]["type"] == "stdio"
+ assert not (repo / ".vscode").exists()
+
+
+def test_print_config_json_wraps_the_snippet_with_its_context(repo: Path) -> None:
+ payload = _json(["agents", "print-config", "codex", str(repo)])
+ assert payload["target"] == "codex"
+ assert payload["scope"] == "project"
+ assert "[mcp_servers.repowise]" in payload["config"]
+ assert not (repo / ".codex").exists()
+
+
+def test_print_config_names_the_known_ids_for_an_unknown_one(repo: Path) -> None:
+ result = CliRunner().invoke(cli, ["agents", "print-config", "zed", str(repo)])
+ assert result.exit_code != 0
+ assert "vscode" in result.output
+
+
+# ---------------------------------------------------------------------------
+# doctor integration
+# ---------------------------------------------------------------------------
+
+
+def test_doctor_reports_one_row_per_agent_from_its_own_descriptor(repo: Path) -> None:
+ """Nothing in doctor knows what any particular agent's health means."""
+ from repowise.cli.commands.doctor_cmd.repo_checks import _agent_target_checks
+
+ checks, needs_refresh = _agent_target_checks()
+
+ assert [c.name for c in checks] == [
+ "Agent: claude-code",
+ "Agent: codex",
+ "Agent: vscode",
+ ]
+ # Nothing is wired on a clean machine, and an agent you do not use is not a
+ # problem with your setup.
+ assert all(c.ok for c in checks)
+ assert needs_refresh is False
+
+
+def test_doctor_surfaces_a_stale_hook_matcher_rather_than_calling_it_ok(
+ repo: Path, monkeypatch
+) -> None:
+ """The agreed mitigation for gating the self-heal on the skip env var.
+
+ A hook whose matcher names a tool the host has since renamed is installed,
+ parses, and will never fire. Someone who exports REPOWISE_SKIP_EDITOR_SETUP
+ permanently never gets the migration that would fix it, so this row is the
+ only place the staleness becomes visible.
+
+ Visible, but advisory: it is printed and it drives ``--repair``, and it does
+ not fail the run. Opt-in surfaces go stale routinely, and failing on it
+ would turn ``repowise doctor`` non-zero in CI for a condition nobody asked
+ the tool to guarantee. Only ``broken`` fails.
+ """
+ from repowise.cli.commands.doctor_cmd.repo_checks import _agent_target_checks
+ from repowise.cli.editor_integrations import codex_config
+
+ monkeypatch.setattr(codex_config, "codex_rewrite_hook_matcher", lambda: "local_shell")
+
+ checks, needs_refresh = _agent_target_checks()
+
+ codex = next(c for c in checks if c.name == "Agent: codex")
+ assert "will never fire" in codex.detail
+ assert "run:" in codex.detail
+ assert needs_refresh is True
+ assert codex.ok is True
+
+
+def test_doctor_fails_the_run_only_for_a_damaged_config(repo: Path) -> None:
+ """The other side of that line: broken is a real fault, so it fails."""
+ from repowise.cli.commands.doctor_cmd.repo_checks import _agent_target_checks
+
+ settings = Path.home() / ".claude" / "settings.json"
+ settings.parent.mkdir(parents=True)
+ settings.write_text('{"mcpServers": {,}', encoding="utf-8")
+
+ checks, needs_refresh = _agent_target_checks()
+
+ claude = next(c for c in checks if c.name == "Agent: claude-code")
+ assert claude.ok is False
+ assert needs_refresh is True
+
+
+def test_doctor_calls_a_damaged_config_broken_not_missing(repo: Path) -> None:
+ """'Not installed' would send the user to run an install that refuses too."""
+ from repowise.cli.agent_targets.targets import claude_code as target_mod
+
+ settings = Path.home() / ".claude" / "settings.json"
+ settings.parent.mkdir(parents=True)
+ settings.write_text('{"mcpServers": {,}', encoding="utf-8")
+
+ report = target_mod.TARGET.doctor()
+
+ assert report.status.value == "broken"
+ assert "not valid JSON" in report.issues[0]
+ assert report.fix_command
+
+
+def test_doctor_repair_routes_to_the_same_refresh_the_command_runs(repo: Path) -> None:
+ """One implementation, so a repair cannot drift from `agents refresh`."""
+ from repowise.cli.commands.agents_cmd import refresh_wired_agents
+
+ _run(["agents", "add", str(repo), "--target", "vscode", "-y"])
+ config_path = repo / ".vscode" / "mcp.json"
+ config = json.loads(config_path.read_text(encoding="utf-8"))
+ config["servers"]["repowise"]["args"] = ["mcp", "/gone", "--transport", "stdio"]
+ config_path.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
+
+ payload = refresh_wired_agents(repo)
+
+ assert payload["changed"] is True
+ assert "/gone" not in config_path.read_text(encoding="utf-8")
+
+
+# ---------------------------------------------------------------------------
+# The interactive gate
+# ---------------------------------------------------------------------------
+
+
+def test_the_gate_is_a_tty_and_no_target_never_a_tty_alone(monkeypatch) -> None:
+ """An explicit ``--target`` already answers the question the prompt asks."""
+ from repowise.cli.commands import agents_cmd
+
+ monkeypatch.setattr(agents_cmd.sys.stdin, "isatty", lambda: True, raising=False)
+
+ assert agents_cmd._can_prompt(None, yes=False)
+ assert not agents_cmd._can_prompt("vscode", yes=False)
+ assert not agents_cmd._can_prompt(None, yes=True)
+
+
+def test_a_tty_that_cannot_answer_falls_through_to_the_defaults(repo: Path, monkeypatch) -> None:
+ """isatty lies: Git Bash on Windows, pty wrappers, ``docker run -t``.
+
+ The prompt returning None must leave the pre-ticked set intact rather than
+ take the run down with an EOFError.
+ """
+ from repowise.cli.commands import agents_cmd
+ from repowise.cli.ui import agent_selection
+
+ monkeypatch.setattr(agents_cmd.sys.stdin, "isatty", lambda: True, raising=False)
+
+ def _eof(*_args, **_kwargs):
+ raise EOFError
+
+ monkeypatch.setattr(agent_selection.Prompt, "ask", _eof)
+ (repo / ".vscode").mkdir() # makes VS Code "present", so it starts ticked
+
+ result = CliRunner().invoke(cli, ["agents", "add", str(repo)], catch_exceptions=False)
+
+ assert result.exit_code == 0
+ assert (repo / ".vscode" / "mcp.json").exists()
diff --git a/tests/unit/cli/test_claude_md_prompt.py b/tests/unit/cli/test_claude_md_prompt.py
index e97687ebb..855ff62b4 100644
--- a/tests/unit/cli/test_claude_md_prompt.py
+++ b/tests/unit/cli/test_claude_md_prompt.py
@@ -2,9 +2,14 @@
The CLAUDE.md opt-out prompt used to live inside ``interactive_advanced_config``
and was therefore skipped entirely in full mode, and the answer was not always
-threaded back to the writer in every code path. These tests pin the current
-behaviour: the Claude editor integration owns that prompt and feeds the
-resulting project-file option into the writer.
+threaded back to the writer in every code path. These tests pin the property
+that fixed it, which survives the prompt itself moving twice: whatever the user
+answers reaches the writer, and the writer persists the opt-out.
+
+The answer now comes from the one agent checklist rather than from a yes/no the
+Claude integration owned. The checklist's own behaviour is tested in
+``test_editor_setup``; what is tested here is the second half — that unticking
+Claude Code still ends in no CLAUDE.md and a persisted opt-out.
"""
from __future__ import annotations
@@ -13,48 +18,37 @@ from io import StringIO
from pathlib import Path
from unittest.mock import patch
-from click.testing import CliRunner
from rich.console import Console
from repowise.cli.editor_integrations import claude as claude_integration
-from repowise.cli.editor_setup import EditorSetupOptions
def _silent_console() -> Console:
return Console(file=StringIO(), force_terminal=False)
-def test_prompt_disables_claude_md_when_user_says_no() -> None:
- runner = CliRunner()
- with runner.isolation(input="n\n"):
- options = claude_integration.ClaudeCodeSetup().configure_options(
- _silent_console(),
- EditorSetupOptions(prompt_for_project_files=True),
- )
-
- assert "claude_md" in options.disabled_project_files
+def test_unticking_claude_code_reaches_the_writer(monkeypatch, tmp_path: Path) -> None:
+ """The whole path: checklist answer -> options -> the writer's opt-out."""
+ from repowise.cli.editor_setup import select_agents_interactively
+ from repowise.cli.ui import agent_selection
+ (tmp_path / ".repowise").mkdir()
+ monkeypatch.setattr(agent_selection, "interactive_agent_select", lambda *_a: set())
-def test_prompt_keeps_claude_md_when_user_says_yes() -> None:
- runner = CliRunner()
- with runner.isolation(input="y\n"):
- options = claude_integration.ClaudeCodeSetup().configure_options(
- _silent_console(),
- EditorSetupOptions(prompt_for_project_files=True),
- )
+ options = select_agents_interactively(_silent_console(), tmp_path, _empty_options())
+ claude_integration.ClaudeCodeSetup().write_project_files(
+ _silent_console(), tmp_path, options
+ )
- assert "claude_md" not in options.disabled_project_files
+ assert not (tmp_path / ".claude").exists()
+ cfg = (tmp_path / ".repowise" / "config.yaml").read_text(encoding="utf-8")
+ assert "claude_md: false" in cfg
-def test_prompt_keeps_claude_md_on_default_enter() -> None:
- runner = CliRunner()
- with runner.isolation(input="\n"):
- options = claude_integration.ClaudeCodeSetup().configure_options(
- _silent_console(),
- EditorSetupOptions(prompt_for_project_files=True),
- )
+def _empty_options():
+ from repowise.cli.editor_setup import EditorSetupOptions
- assert "claude_md" not in options.disabled_project_files
+ return EditorSetupOptions()
def test_maybe_generate_skips_write_when_user_opted_out(tmp_path: Path) -> None:
diff --git a/tests/unit/cli/test_editor_setup.py b/tests/unit/cli/test_editor_setup.py
index 1af4bd64e..4dbe79224 100644
--- a/tests/unit/cli/test_editor_setup.py
+++ b/tests/unit/cli/test_editor_setup.py
@@ -47,9 +47,6 @@ def test_register_editor_clients_skipped_when_env_set(monkeypatch) -> None:
registered: list[Path] = []
class FakeIntegration:
- def configure_options(self, c: Any, o: Any) -> Any:
- return o
-
def write_project_files(self, c: Any, p: Path, o: Any) -> None:
pass
@@ -82,9 +79,6 @@ def test_register_editor_clients_skipped_by_flag(monkeypatch) -> None:
registered: list[Path] = []
class FakeIntegration:
- def configure_options(self, c: Any, o: Any) -> Any:
- return o
-
def write_project_files(self, c: Any, p: Path, o: Any) -> None:
pass
@@ -386,34 +380,115 @@ def test_detect_editor_setup_outcome_skip_env_reports_disconnected(
assert outcome.claude_code_connected is False
-def test_resolve_editor_setup_options_delegates_to_integrations() -> None:
- calls: list[tuple[str, frozenset[str], bool]] = []
-
- class FakeIntegration:
- def configure_options(
- self,
- console_obj: object,
- options: EditorSetupOptions,
- ) -> EditorSetupOptions:
- calls.append(
- (
- "configure",
- options.disabled_project_files,
- options.prompt_for_project_files,
- )
- )
- return options.with_disabled_project_file("fake_instructions")
+def test_resolve_editor_setup_options_carries_the_cli_flags_through() -> None:
+ """Just the flags now.
+ This used to give every integration a ``configure_options`` hook to prompt
+ from. The prompting is one registry-built checklist
+ (:func:`select_agents_interactively`), so the hook had no implementation
+ left that did anything and all three were deleted with it.
+ """
options = resolve_editor_setup_options(
- _silent_console(),
disabled_project_files={"cli_disabled"},
- prompt_for_project_files=True,
- integrations=(FakeIntegration(),), # type: ignore[arg-type]
+ project_file_overrides={"agents_md": False},
+ integration_overrides={"codex": True},
)
- assert calls == [("configure", frozenset({"cli_disabled"}), True)]
- assert options.disabled_project_files == frozenset({"cli_disabled", "fake_instructions"})
- assert options.prompt_for_project_files is True
+ assert options.disabled_project_files == frozenset({"cli_disabled"})
+ assert options.project_file_overrides == {"agents_md": False}
+ assert options.integration_overrides == {"codex": True}
+
+
+# ---------------------------------------------------------------------------
+# The agent checklist that replaced the three per-integration prompts
+# ---------------------------------------------------------------------------
+
+
+def _select(monkeypatch, tmp_path: Path, answer, **kwargs):
+ """Run the checklist with *answer* standing in for the user's reply."""
+ from repowise.cli.editor_setup import select_agents_interactively
+ from repowise.cli.ui import agent_selection
+
+ seen: list[list] = []
+
+ def _fake(console_obj, choices):
+ seen.append(choices)
+ return answer(choices) if callable(answer) else answer
+
+ monkeypatch.setattr(agent_selection, "interactive_agent_select", _fake)
+ options = select_agents_interactively(
+ _silent_console(), tmp_path, EditorSetupOptions(**kwargs)
+ )
+ return options, seen[0]
+
+
+def test_checklist_unticking_an_agent_disables_its_project_file(monkeypatch, tmp_path) -> None:
+ """What the three deleted yes/no prompts each did, now in one place."""
+ options, _ = _select(monkeypatch, tmp_path, {"codex"})
+
+ assert "claude_md" in options.disabled_project_files
+ assert "vscode_mcp" in options.disabled_project_files
+ assert "agents_md" not in options.disabled_project_files
+ assert options.integration_overrides["codex"] is True
+
+
+def test_checklist_ticking_everything_disables_nothing(monkeypatch, tmp_path) -> None:
+ options, _ = _select(
+ monkeypatch, tmp_path, lambda choices: {choice.id for choice in choices}
+ )
+
+ assert options.disabled_project_files == frozenset()
+ assert options.integration_overrides == {"claude-code": True, "codex": True, "vscode": True}
+
+
+def test_checklist_pre_ticks_an_agent_an_explicit_flag_asked_for(monkeypatch, tmp_path) -> None:
+ """``--codex`` is already an answer, so the box it controls starts ticked.
+
+ Otherwise accepting the checklist would silently undo the flag the user
+ passed on the same command line.
+ """
+ _, choices = _select(
+ monkeypatch, tmp_path, set(), integration_overrides={"codex": True}
+ )
+
+ codex = next(choice for choice in choices if choice.id == "codex")
+ assert codex.enabled is True
+
+
+def test_checklist_never_silently_withdraws_the_instruction_file_default(
+ monkeypatch, tmp_path
+) -> None:
+ """Leaving a box unticked is not neutral, so detection must not do it alone.
+
+ On a machine with Codex but no ``~/.claude``, detection returned a
+ non-empty selection, so the auto fallback never fired and Claude Code
+ arrived unticked. One Enter then persisted ``claude_md: false`` into
+ ``.repowise/config.yaml``, so ``update`` never generated it either — where
+ the prompt this replaced defaulted to yes.
+
+ The first fix for this unioned in ``resolve_target_flag("auto")``, which
+ *looks* equivalent and is a no-op: ``auto`` resolves to the detected
+ targets and only reaches the fallback when detection is empty — the case
+ the union already covered. So the moment anything else was wired, Claude
+ Code went missing again. Hence the wired row below.
+ """
+ from repowise.cli.agent_targets.registry import default_selection
+
+ rows = [
+ {"id": "claude-code", "registrations": [], "present": False},
+ {"id": "codex", "registrations": [{"method": "direct"}], "present": True},
+ {"id": "vscode", "registrations": [], "present": True},
+ ]
+
+ assert default_selection(rows) == {"claude-code", "codex", "vscode"}
+
+
+def test_checklist_that_cannot_be_answered_leaves_the_options_alone(monkeypatch, tmp_path) -> None:
+ """isatty lies. A prompt returning None must not disable everything."""
+ options, _ = _select(monkeypatch, tmp_path, None)
+
+ assert options.disabled_project_files == frozenset()
+ assert options.integration_overrides == {}
def test_default_disabled_project_files_maps_legacy_no_claude_flag() -> None:
@@ -472,7 +547,7 @@ def test_write_editor_project_files_uses_pre_resolved_options(
calls: list[tuple[str, Path, EditorSetupOptions]] = []
options = EditorSetupOptions(
disabled_project_files=frozenset({"resolved"}),
- prompt_for_project_files=True,
+ integration_overrides={"codex": True},
)
def fake_save_mcp_config(repo_path: Path) -> Path:
diff --git a/tests/unit/cli/test_lazy_commands.py b/tests/unit/cli/test_lazy_commands.py
index 8793394a8..4a6c0dc7a 100644
--- a/tests/unit/cli/test_lazy_commands.py
+++ b/tests/unit/cli/test_lazy_commands.py
@@ -33,7 +33,7 @@ from repowise.core.registry import CLIRegistry, LazyCommand
#: command is meant to require editing it.
_EXPECTED_NAMES = frozenset(
{
- "ask", "augment", "context", "corrections", "costs", "coverage",
+ "agents", "ask", "augment", "context", "corrections", "costs", "coverage",
"dead-code", "decision", "delete", "distill", "doctor", "expand",
"export", "generate", "generate-claude-md", "health", "hook",
"impacted-tests", "init", "login", "logout", "mcp", "reindex", "restyle",
diff --git a/tests/unit/cli/test_vscode_setup.py b/tests/unit/cli/test_vscode_setup.py
index 456e16573..61cfd8e01 100644
--- a/tests/unit/cli/test_vscode_setup.py
+++ b/tests/unit/cli/test_vscode_setup.py
@@ -236,28 +236,16 @@ def test_vscode_included_in_default_integrations() -> None:
assert any(isinstance(i, VSCodeSetup) for i in integrations)
-def test_vscode_configure_options_disables_when_declined(monkeypatch) -> None:
- monkeypatch.setattr("click.confirm", lambda *a, **k: False)
- options = VSCodeSetup().configure_options(
- _silent_console(),
- EditorSetupOptions(prompt_for_project_files=True),
- )
- assert "vscode_mcp" in options.disabled_project_files
-
+def test_vscode_setup_writes_nothing_when_its_project_file_is_disabled(tmp_path: Path) -> None:
+ """Unticking VS Code in the agent checklist reaches the writer as this.
-def test_vscode_configure_options_keeps_enabled_when_accepted(monkeypatch) -> None:
- monkeypatch.setattr("click.confirm", lambda *a, **k: True)
- options = VSCodeSetup().configure_options(
+ The integration used to own a ``configure_options`` prompt that set the
+ flag itself; the checklist sets it now, and this is the half that has to
+ keep working. See ``test_editor_setup`` for the checklist's own tests.
+ """
+ VSCodeSetup().write_project_files(
_silent_console(),
- EditorSetupOptions(prompt_for_project_files=True),
+ tmp_path,
+ EditorSetupOptions(disabled_project_files=frozenset({"vscode_mcp"})),
)
- assert "vscode_mcp" not in options.disabled_project_files
-
-
-def test_vscode_configure_options_no_prompt_when_not_requested(monkeypatch) -> None:
- def _fail(*_a, **_k):
- raise AssertionError("must not prompt")
-
- monkeypatch.setattr("click.confirm", _fail)
- options = VSCodeSetup().configure_options(_silent_console(), EditorSetupOptions())
- assert "vscode_mcp" not in options.disabled_project_files
+ assert not (tmp_path / ".vscode").exists()