Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
refactor(cli): put the three agent integrations behind one target seam (#1446)
Raghav Chamadiya2ddcb39d5a2a
diff --git a/packages/cli/src/repowise/cli/agent_targets/__init__.py b/packages/cli/src/repowise/cli/agent_targets/__init__.pynew file mode 100644index 000000000..3608455e6--- /dev/null+++ b/packages/cli/src/repowise/cli/agent_targets/__init__.py@@ -0,0 +1,42 @@+"""Agent integration targets — one descriptor per agent repowise can wire up.++The seam that makes adding an agent cost a descriptor file and a registry line.+See :mod:`.types` for the shape a descriptor implements and why the tier is+derived rather than declared, and :mod:`.registry` for how they are looked up.++Import discipline: everything here is lazy at module scope. ``agent_targets`` is+reached from ``init`` and ``doctor``, which already pay for click and rich, but+it must never be reached from a hook — ``cli.agent_adapters`` sits on the+PreToolUse hot path and imports stdlib only. The dependency runs one way:+``agent_targets`` may name ``agent_adapters``, never the reverse.+"""++from .types import (+ AgentTarget,+ Capability,+ DoctorReport,+ DoctorStatus,+ FileAction,+ InstallMethod,+ Registration,+ Scope,+ Tier,+ WriteResult,+ capabilities_of,+ derive_tier,+)++__all__ = [+ "AgentTarget",+ "Capability",+ "DoctorReport",+ "DoctorStatus",+ "FileAction",+ "InstallMethod",+ "Registration",+ "Scope",+ "Tier",+ "WriteResult",+ "capabilities_of",+ "derive_tier",+]diff --git a/packages/cli/src/repowise/cli/agent_targets/formats/__init__.py b/packages/cli/src/repowise/cli/agent_targets/formats/__init__.pynew file mode 100644index 000000000..98fa5e32a--- /dev/null+++ b/packages/cli/src/repowise/cli/agent_targets/formats/__init__.py@@ -0,0 +1,8 @@+"""Composable config-format helpers targets build on.++Kept deliberately small and free of per-agent knowledge. The targets differ+enough — JSON versus TOML versus marker-delimited markdown, and different+idempotency markers within each — that a shared base class would force an+awkward shape on all of them; composition lets each take only the mechanics it+needs. codegraph reached the same conclusion for the same reason.+"""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.pynew file mode 100644index 000000000..160968524--- /dev/null+++ b/packages/cli/src/repowise/cli/agent_targets/formats/json_merge.py@@ -0,0 +1,183 @@+"""JSON config mechanics shared by every target that writes JSON.++Mechanics only — atomic writes, order-insensitive comparison, and the two+reader disciplines the existing writers use. Merge *semantics* stay in each+target, because they differ in ways that are not incidental: the Claude and+root configs deep-merge per server so a user's ``env`` block survives+re-registration, while the VS Code files bail rather than touch a file that+might carry comments. Unifying those would change observable behaviour, which+is the one thing this rewrite is not allowed to do.++The two reader disciplines are deliberate and both are kept:++* :func:`load_json_object` raises ``click.ClickException`` with a message that+ names the file and states that nothing was written. This is for config we own+ the write of, where the right answer is to stop and tell the user.+* :func:`load_json_object_or_value_error` raises ``ValueError``. This is for the+ ``.vscode`` files, where the caller catches it and leaves the file alone: VS+ Code accepts comments, so a parse failure is more likely to mean "JSONC" than+ "damaged", and destroying a commented config would be far worse than skipping+ a merge.+"""++from __future__ import annotations++import contextlib+import json+import os+import stat+from pathlib import Path+from typing import Any++import click+++def load_json_object(config_path: Path) -> dict:+ """Read a JSON object, refusing to silently replace bad content.++ Behaviourally identical to the long-standing ``mcp_config.load_existing_config``+ it replaces, down to the message text, because those messages are what+ users have seen and what the tests assert.+ """+ try:+ existing = json.loads(config_path.read_text(encoding="utf-8"))+ except json.JSONDecodeError as exc:+ raise click.ClickException(+ f"Cannot update {config_path}: existing file is not valid JSON. "+ "Fix or remove it and retry; no changes were written."+ ) from exc+ except OSError as exc:+ raise click.ClickException(+ f"Cannot update {config_path}: existing file could not be read. "+ "Fix the file permissions and retry; no changes were written."+ ) from exc+ if not isinstance(existing, dict):+ raise click.ClickException(+ f"Cannot update {config_path}: existing file must contain a JSON object. "+ "Fix or remove it and retry; no changes were written."+ )+ return existing+++def load_json_object_or_value_error(config_path: Path, label: str) -> dict:+ """Read a JSON object, raising ``ValueError`` so the caller can skip.++ ``json.JSONDecodeError`` is itself a ``ValueError``, so a JSONC file and a+ wrong-shaped file reach the caller through one except clause.+ """+ existing = json.loads(config_path.read_text(encoding="utf-8"))+ if not isinstance(existing, dict):+ raise ValueError(f"{label} must contain a JSON object")+ return existing+++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.+ """+ # 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,+ # so treating them as equal would report ``unchanged`` for a write that+ # changes the file. ``True == 1`` in Python makes bool-vs-int the same trap.+ if type(left) is not type(right):+ return False+ if isinstance(left, dict):+ if set(left) != set(right):+ return False+ return all(json_deep_equal(left[key], right[key]) for key in left)+ if isinstance(left, list):+ if len(left) != len(right):+ return False+ return all(json_deep_equal(a, b) for a, b in zip(left, right, strict=True))+ return bool(left == right)+++def dumps_config(data: dict) -> str:+ """Serialize exactly as every existing writer does: indent 2, trailing newline."""+ 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.++ The atomic mechanics are ``core.fsutils.atomic_write_text`` — temp file in+ the destination directory, then rename — rather than a second copy of the+ same eight lines. What this wrapper adds is the two things a temp-file+ rename silently loses that a plain ``write_text`` kept:++ * **Symlinks.** ``os.replace`` replaces the *link*; a plain write follows+ it. Dotfile setups do symlink ``.mcp.json``, so the link is resolved+ first and the write lands on its target.+ * **Permissions.** The temp file's mode is umask-derived, so replacing an+ existing file would quietly reset its bits. The prior mode is restored.++ Parent directories are **not** created. Every caller that needs one already+ creates it at the point where it knows the directory is legitimately+ absent; creating them here turned a missing repo path from a loud+ ``FileNotFoundError`` into a silently-created tree.++ *newline* is passed through rather than defaulted, because the two+ disciplines in this codebase are both deliberate: config files take the+ platform translation (``None``), and the marker-managed markdown files pass+ ``"\\n"`` explicitly so a repo-shared file does not change line endings+ depending on who ran the command. Getting this wrong is a whole-file diff.+ """+ from repowise.core.fsutils import atomic_write_text as _atomic_write_text++ target = Path(os.path.realpath(path)) if path.is_symlink() else path++ mode: int | None = None+ with contextlib.suppress(OSError):+ if target.exists():+ mode = stat.S_IMODE(target.stat().st_mode)++ _atomic_write_text(target, content, newline=newline)++ if mode is not None:+ with contextlib.suppress(OSError):+ 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 merge_server_entries(servers: dict, new_entry: dict) -> dict:+ """Deep-merge *new_entry* server definitions into *servers* in place.++ Generated ``command``/``args``/``description`` overwrite the stored values+ so a path or command change takes effect, but any other key the user added+ to the entry survives — most importantly an ``env`` block carrying BYOK+ provider keys. A shallow ``servers.update()`` would replace the whole entry+ and wipe ``env`` on every re-registration (issue #307).+ """+ for name, entry in new_entry.items():+ current = servers.get(name)+ if isinstance(current, dict) and isinstance(entry, dict):+ merged_entry = dict(current)+ merged_entry.update(entry)+ servers[name] = merged_entry+ else:+ servers[name] = entry+ return serversdiff --git a/packages/cli/src/repowise/cli/agent_targets/formats/marker_block.py b/packages/cli/src/repowise/cli/agent_targets/formats/marker_block.pynew file mode 100644index 000000000..82d5b96e9--- /dev/null+++ b/packages/cli/src/repowise/cli/agent_targets/formats/marker_block.py@@ -0,0 +1,173 @@+"""Marker-delimited managed blocks inside a user-owned markdown file.++The one write shape shared by every instructions file: repowise owns the text+between two markers and nothing else in the file. Install replaces the block in+place, uninstall removes it, and content outside the markers round-trips+byte-for-byte. That last property is the whole point — these files are things+users write in, and a managed section that eats a paragraph once will not be+trusted again.++Line endings are forced to ``\\n`` on every write. These files are repo-shared+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.+"""++from __future__ import annotations++import re+from dataclasses import dataclass+from enum import StrEnum+from pathlib import Path++from .json_merge import atomic_write_text+++class BlockState(StrEnum):+ """What a file currently holds for one marker pair."""++ #: File does not exist.+ ABSENT_FILE = "absent-file"+ #: File exists, no marker of ours in it.+ ABSENT = "absent"+ #: Exactly one well-formed block.+ PRESENT = "present"+ #: More than one complete block — an install ran against a hand-edited file.+ DUPLICATED = "duplicated"+ #: A start without its end, or an end without its start.+ ORPHANED = "orphaned"+++@dataclass(frozen=True)+class BlockInspection:+ state: BlockState+ #: 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."""+ if not path.exists():+ return BlockInspection(BlockState.ABSENT_FILE)+ try:+ content = path.read_text(encoding="utf-8")+ except OSError:+ return BlockInspection(BlockState.ABSENT_FILE)++ starts = content.count(start)+ ends = content.count(end)+ if starts == 0 and ends == 0:+ return BlockInspection(BlockState.ABSENT)+ if starts != ends:+ return BlockInspection(BlockState.ORPHANED)++ match = re.search(re.escape(start) + r"(.*?)" + re.escape(end), content, flags=re.DOTALL)+ if match is None:+ # Both markers present but the end precedes the start.+ return BlockInspection(BlockState.ORPHANED)+ state = BlockState.DUPLICATED if starts > 1 else BlockState.PRESENT+ return BlockInspection(state, body=match.group(1))+++def upsert(+ path: Path,+ body: str,+ start: str,+ end: str,+ *,+ new_file_prefix: str = "",+) -> bool:+ """Ensure *path* carries exactly ``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.++ *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+ is managed. Pair it with ``remove(delete_if_only=...)`` so install and+ uninstall round-trip to "no file".++ The replacement goes through a function rather than a string because+ ``re.sub`` interprets backslashes and ``\\g<name>`` group references in a+ replacement *string*. Instruction bodies are prose that can legitimately+ 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.+ """+ 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++ 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:+ content = existing.rstrip() + "\n\n" + wrapped + "\n"++ # 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+ # the LF content we are about to write — and short-circuiting there would+ # 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+ atomic_write_text(path, content, newline="\n")+ return True+++def remove(path: Path, start: str, end: str, *, delete_if_only: str | None = None) -> bool:+ """Strip the managed block, leaving user content untouched.++ *delete_if_only* is the placeholder an install writes into a file it+ created. When removal leaves nothing but that placeholder, the file is+ deleted, so install then uninstall round-trips back to "no file" rather+ than leaving a stub nobody asked for.++ Returns True when something was removed.+ """+ if not path.exists():+ 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)+ if remaining and not remaining.endswith("\n"):+ # Upsert rstrips before appending; restore the newline that consumed so+ # removal is a true inverse.+ remaining += "\n"++ try:+ leftovers = {""} | ({delete_if_only.strip()} if delete_if_only else set())+ if remaining.strip() in leftovers:+ path.unlink()+ else:+ atomic_write_text(path, remaining, newline="\n")+ except OSError:+ return False+ return Truediff --git a/packages/cli/src/repowise/cli/agent_targets/formats/toml_merge.py b/packages/cli/src/repowise/cli/agent_targets/formats/toml_merge.pynew file mode 100644index 000000000..c6b2d76eb--- /dev/null+++ b/packages/cli/src/repowise/cli/agent_targets/formats/toml_merge.py@@ -0,0 +1,108 @@+"""A deliberately narrow TOML writer, scoped to whole-table upserts.++Absorbed from ``mcp_config``. It is not a general TOML serializer and should+not become one: it handles the value types our tables actually contain, and+raises on anything else rather than guessing at an encoding. codegraph made the+same call for the same reason — 254 lines serving one target beats a dependency+whose failure modes you inherit.++The merge strategy is regex table replacement over the *source text*, not a+parse-and-reserialize. That is what preserves the user's comments, key order and+formatting everywhere outside the one table we own. The cost is that the regex+only recognises the bare ``[table.name]`` spelling, so every merged result is+re-parsed before it is written: a user who spelled the same key differently+(quoted, or inline under a parent) slips past the regex, and appending our block+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.+"""++from __future__ import annotations++import json+import re+import tomllib+from pathlib import Path++import click+++def toml_value(value: object) -> str:+ """Encode a scalar or string list 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.+ """+ if isinstance(value, bool):+ return "true" if value else "false"+ if isinstance(value, str):+ return json.dumps(value)+ if isinstance(value, int):+ return str(value)+ 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}")+++def table_block(table_name: str, values: dict[str, object]) -> str:+ """Render ``[table_name]`` and its key/value lines, without a trailing newline."""+ lines = [f"[{table_name}]"]+ lines.extend(f"{key} = {toml_value(value)}" for key, value in values.items())+ 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."""+ try:+ tomllib.loads(merged_text)+ except tomllib.TOMLDecodeError as exc:+ raise click.ClickException(+ f"Cannot update {config_path}: merging the repowise entry would produce "+ "invalid TOML (an existing entry may use a different key spelling). "+ "No changes were written."+ ) from exc+++def load_toml_document(config_path: Path, existing_text: str) -> dict:+ """Parse *existing_text*, refusing to overwrite a file we cannot read."""+ try:+ return tomllib.loads(existing_text)+ except tomllib.TOMLDecodeError as exc:+ raise click.ClickException(+ f"Cannot update {config_path}: existing file is not valid TOML. "+ "Fix or remove it and retry; no changes were written."+ ) from exc+++def require_table(doc: dict, key: str, config_path: Path, label: str) -> dict | None:+ """Fetch ``doc[key]`` insisting it is a table, or ``None`` when absent."""+ value = doc.get(key)+ if value is None:+ return None+ if not isinstance(value, dict):+ raise click.ClickException(+ f"Cannot update {config_path}: [{label}] must be a TOML table. "+ "Fix or remove it and retry; no changes were written."+ )+ return value+++def replace_table(existing_text: str, table_name: str, block: str) -> str:+ """Strip *table_name* from *existing_text* and re-append *block*.++ Matches the table header at a line start through to the next header or end+ of input, so sibling tables and everything between them survive verbatim.+ """+ table_re = re.compile(+ r"(?ms)^\s*\[" + re.escape(table_name) + r"\]\s*\n.*?(?=^\s*\[|\Z)",+ )+ merged_text = table_re.sub("", existing_text).rstrip()+ return f"{merged_text}\n\n{block}\n" if merged_text else f"{block}\n"diff --git a/packages/cli/src/repowise/cli/agent_targets/registry.py b/packages/cli/src/repowise/cli/agent_targets/registry.pynew file mode 100644index 000000000..c8f22e37f--- /dev/null+++ b/packages/cli/src/repowise/cli/agent_targets/registry.py@@ -0,0 +1,129 @@+"""The registry of every agent target repowise knows.++Adding an agent is a module in :mod:`.targets` plus one line in+:data:`_TARGET_MODULES`. Order here is the order agents appear in prompts, in+``--target=all``, and in listings — keep it stable.++Targets are named by ``module:attribute`` rather than imported at module scope,+mirroring the hook-adapter registry. Registration should cost nothing: a caller+resolving one target must not pay the import of every other, and this module is+reachable from ``init`` and ``doctor`` where startup time is visible.++One deviation from codegraph, deliberate: their ``TargetId`` is a hand-written+string union, so adding a target touches three files instead of two and the+union can drift from the registry. Here the ids *are* the registry keys, so+there is nothing to keep in sync.+"""++from __future__ import annotations++import importlib+from pathlib import Path++from .types import AgentTarget, Registration, Scope, Tier, derive_tier++#: Every known target, by id. Values are ``module:attribute`` so registration+#: costs no import.+_TARGET_MODULES: dict[str, str] = {+ "claude-code": "repowise.cli.agent_targets.targets.claude_code:TARGET",+ "codex": "repowise.cli.agent_targets.targets.codex:TARGET",+ "vscode": "repowise.cli.agent_targets.targets.vscode:TARGET",+}++#: Resolved when :meth:`resolve_target_flag` is asked for ``auto`` and nothing+#: is detected. Least surprise for existing users, who are overwhelmingly here.+_AUTO_FALLBACK = "claude-code"+++def list_target_ids() -> list[str]:+ """Every known target id, in registry order."""+ return list(_TARGET_MODULES)+++def get_target(target_id: str) -> AgentTarget | None:+ """The target for *target_id*, or None when it is not a known id."""+ spec = _TARGET_MODULES.get(target_id)+ if spec is None:+ return None+ module_name, _, attr = spec.partition(":")+ return getattr(importlib.import_module(module_name), attr)+++def all_targets() -> list[AgentTarget]:+ """Every target, in registry order. Imports all of them, so call sparingly."""+ return [target for target in (get_target(tid) for tid in _TARGET_MODULES) if target]+++def tier_of(target_id: str) -> Tier | None:+ """The derived support tier for *target_id*."""+ target = get_target(target_id)+ return derive_tier(target) if target else None+++def detect_all(repo_path: Path | None = None) -> dict[str, list[Registration]]:+ """Run detection for every target, keyed by target id.++ Returns a registration *list* per target, never a bool, so the caller can+ report "wired twice" rather than "wired". Detection is best-effort by+ contract: a target whose probe raises is reported as having no+ registrations rather than taking the whole listing down with it.+ """+ found: dict[str, list[Registration]] = {}+ for target_id in _TARGET_MODULES:+ target = get_target(target_id)+ if target is None:+ continue+ try:+ found[target_id] = list(target.detect(repo_path))+ except Exception:+ found[target_id] = []+ return found+++def resolve_target_flag(value: str, repo_path: Path | None = None) -> list[AgentTarget]:+ """Resolve a ``--target=`` value to targets.++ Accepts ``auto`` (everything detected, falling back to Claude Code when+ nothing is), ``all``, ``none``, or a comma-separated list of ids. An unknown+ id raises with the full list of known ones, because the alternative — a+ typo silently resolving to nothing and the command reporting success — is+ the failure mode that wastes the most of a user's time.+ """+ normalized = (value or "").strip().lower()+ if normalized == "none":+ return []+ if normalized == "all":+ return all_targets()+ if normalized == "auto":+ detected = detect_all(repo_path)+ resolved = [+ target+ for target_id, registrations in detected.items()+ if registrations and (target := get_target(target_id)) is not None+ ]+ if resolved:+ return resolved+ fallback = get_target(_AUTO_FALLBACK)+ return [fallback] if fallback else []++ ids = [part.strip() for part in normalized.split(",") if part.strip()]+ resolved = []+ unknown = []+ for target_id in ids:+ target = get_target(target_id)+ if target is None:+ unknown.append(target_id)+ else:+ resolved.append(target)+ if unknown:+ known = ", ".join(list_target_ids())+ raise ValueError(+ f"Unknown --target id(s): {', '.join(unknown)}. "+ 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/__init__.py b/packages/cli/src/repowise/cli/agent_targets/targets/__init__.pynew file mode 100644index 000000000..be9900f6c--- /dev/null+++ b/packages/cli/src/repowise/cli/agent_targets/targets/__init__.py@@ -0,0 +1,8 @@+"""One module per agent target.++Each exports a module-level ``TARGET`` implementing+:class:`~repowise.cli.agent_targets.types.AgentTarget`, plus the module-level+write functions that target owns. The registry resolves them lazily by+``module:attribute``, so nothing here is imported until a caller asks for that+specific agent.+"""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.pynew file mode 100644index 000000000..1093c9363--- /dev/null+++ b/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py@@ -0,0 +1,374 @@+"""Claude Code (and Claude Desktop) as an agent target.++Reaches Full tier through two different routes, which is why the method axis+exists at all:++* **plugin** — the host owns the artifact. It ships MCP, hooks, skills and+ slash commands together, and repowise cannot rewrite it; only ``/plugin+ update`` can. A version skew here is something to *report*, never to repair+ by writing.+* **direct** — repowise owns the files. ``init`` writes the MCP registration+ and the augment hooks into ``~/.claude/settings.json`` plus a repo-local+ ``.mcp.json``. No skills, no commands.++Both routes register ``mcpServers.repowise`` and the same augment hook+commands, and Claude Code merges them without complaint, so a user on both+paths pays two process spawns per matched tool call and carries duplicate tool+schemas. That is a cost problem rather than a correctness one — the emission+dedup in ``augment_cmd`` means the agent still sees one notice — which is+exactly why :meth:`ClaudeCodeTarget.detect` reports every registration it finds+instead of collapsing them into a boolean.++The hook writing itself is *not* reimplemented here. ``editor_integrations.claude_config``+owns the settings.json hook merge and its legacy-matcher migrations, which+encode several years of shape changes; this module names it and calls it.+"""++from __future__ import annotations++import json+from pathlib import Path++from ..types import (+ Capability,+ DoctorReport,+ DoctorStatus,+ FileAction,+ InstallMethod,+ Registration,+ Scope,+ WriteResult,+)++ID = "claude-code"+DISPLAY_NAME = "Claude Code"+DOCS_URL = "https://docs.claude.com/en/docs/claude-code"++#: Name the plugin registers itself under in the host's plugin manifest.+PLUGIN_KEY = "repowise@repowise"++#: Config key for this agent's managed instruction file, under+#: ``editor_files`` in ``.repowise/config.yaml``. Owned here so the CLI flag+#: mapping can look it up rather than restate it per agent.+PROJECT_FILE_ID = "claude_md"++METHODS = (+ InstallMethod(+ id="plugin",+ provides=frozenset(+ {+ Capability.MCP,+ Capability.HOOKS,+ Capability.SKILLS,+ Capability.COMMANDS,+ }+ ),+ managed_by="host",+ preferred=True,+ ),+ InstallMethod(+ id="direct",+ provides=frozenset({Capability.MCP, Capability.HOOKS, Capability.INSTRUCTIONS}),+ managed_by="repowise",+ ),+)+++# ---------------------------------------------------------------------------+# Paths+# ---------------------------------------------------------------------------+++def settings_path() -> Path:+ """The user-level Claude Code settings file."""+ from repowise.cli.editor_integrations.claude_config import _claude_code_settings_path++ return _claude_code_settings_path()+++def desktop_config_path() -> Path | None:+ """Claude Desktop's config file, or None where the platform has none."""+ from repowise.cli.editor_integrations.claude_config import _claude_desktop_config_path++ return _claude_desktop_config_path()+++def project_mcp_config_path(repo_path: Path) -> Path:+ """The repo-root ``.mcp.json`` MCP clients discover."""+ return repo_path / ".mcp.json"+++def plugin_manifest_path() -> Path:+ """Where the host records which plugins are installed."""+ return Path.home() / ".claude" / "plugins" / "installed_plugins.json"+++# ---------------------------------------------------------------------------+# Writes+# ---------------------------------------------------------------------------+++def write_project_mcp_config(repo_path: Path) -> Path:+ """Merge the repowise server into the repo-root ``.mcp.json``.++ Repo-shared and frequently committed, so it keeps the bare ``repowise``+ command: one contributor's absolute path would break every other checkout.+ Other servers the user configured are preserved.+ """+ from repowise.cli.mcp_config import generate_mcp_config++ from ..formats.json_merge import (+ load_json_object,+ merge_server_entries,+ write_json_config,+ )++ config_path = project_mcp_config_path(repo_path)+ new_entry = generate_mcp_config(repo_path)["mcpServers"]++ if config_path.exists():+ existing = load_json_object(config_path)+ servers = dict(existing.get("mcpServers", {}))+ merge_server_entries(servers, new_entry)+ existing["mcpServers"] = servers+ merged = existing+ else:+ merged = {"mcpServers": new_entry}++ write_json_config(config_path, merged)+ return config_path+++# ---------------------------------------------------------------------------+# Detection+# ---------------------------------------------------------------------------+++def _plugin_installs() -> list[dict]:+ """Records the host holds for the repowise plugin, or an empty list.++ Reads the host's own manifest (``installed_plugins.json``, schema version 2:+ a ``plugins`` map from ``"<plugin>@<marketplace>"`` to a list of installs,+ each carrying ``scope``, ``installPath`` and ``version``). Every failure+ mode degrades to "no plugin": a manifest we cannot read is not evidence of+ absence, but treating it as presence would make us report a registration+ that may not exist.+ """+ manifest = plugin_manifest_path()+ if not manifest.exists():+ return []+ try:+ data = json.loads(manifest.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ return []+ plugins = data.get("plugins")+ if not isinstance(plugins, dict):+ return []+ installs = plugins.get(PLUGIN_KEY)+ if not isinstance(installs, list):+ return []+ return [entry for entry in installs if isinstance(entry, dict)]+++def _has_repowise_server(config_path: Path) -> bool:+ try:+ data = json.loads(config_path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ return False+ servers = data.get("mcpServers")+ return isinstance(servers, dict) and "repowise" in servers+++def detect(repo_path: Path | None = None) -> list[Registration]:+ """Every place Claude Code is currently wired to repowise.++ Deliberately a list. A machine carrying both the plugin and a direct+ ``init`` has two MCP registrations for one product, and the only way to+ tell the user that is to have counted them.+ """+ found: list[Registration] = []++ for entry in _plugin_installs():+ scope = Scope.USER if entry.get("scope") != "project" else Scope.PROJECT+ found.append(+ Registration(+ method="plugin",+ scope=scope,+ config_path=plugin_manifest_path(),+ version=entry.get("version"),+ detail=entry.get("installPath"),+ )+ )++ settings = settings_path()+ if settings.exists() and _has_repowise_server(settings):+ found.append(+ Registration(method="direct", scope=Scope.USER, config_path=settings),+ )++ desktop = desktop_config_path()+ if desktop is not None and desktop.exists() and _has_repowise_server(desktop):+ found.append(+ Registration(method="direct", scope=Scope.USER, config_path=desktop, detail="desktop"),+ )++ if repo_path is not None:+ project = project_mcp_config_path(repo_path)+ if project.exists() and _has_repowise_server(project):+ found.append(+ Registration(method="direct", scope=Scope.PROJECT, config_path=project),+ )++ return found+++class ClaudeCodeTarget:+ """Descriptor for Claude Code. See the module docstring."""++ id = ID+ display_name = DISPLAY_NAME+ docs_url = DOCS_URL+ hook_adapter = "claude-code"+ session_adapter = "claude_code"+ methods = METHODS+ project_file_id = PROJECT_FILE_ID++ def supports_scope(self, scope: Scope) -> bool:+ return True++ def detect(self, repo_path: Path | None = None) -> list[Registration]:+ return detect(repo_path)++ def install(+ self,+ scope: Scope,+ options: object = None,+ *,+ repo_path: Path | None = None,+ ) -> WriteResult:+ """Wire Claude Code up at *scope*.++ The direct method only. The plugin is host-managed by definition, so+ there is nothing here to write for it — when :meth:`detect` finds it,+ the caller is the one that decides whether to skip the direct write.+ """+ from repowise.cli.editor_integrations.claude_config import (+ enable_tool_search_in_claude_code,+ install_claude_code_hooks,+ register_with_claude_code,+ register_with_claude_desktop,+ )++ result = WriteResult()+ 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)+ 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)+ enable_tool_search_in_claude_code()+ return result++ def uninstall(self, scope: Scope, *, repo_path: Path | None = None) -> WriteResult:+ """Remove the distill rewrite hook; leave sibling user hooks intact.++ Scoped narrowly on purpose. Tearing the augment hooks and the MCP+ registration out is not something any command asks for today, and a+ half-written uninstall is worse than none — the surface grows in+ Phase 2 alongside the command that needs it.+ """+ from repowise.cli.editor_integrations.claude_config import (+ uninstall_claude_code_rewrite_hook,+ )++ result = WriteResult()+ settings = settings_path()+ if scope is not Scope.USER:+ result.record(settings, FileAction.KEPT)+ return result+ removed = uninstall_claude_code_rewrite_hook()+ result.record(settings, FileAction.REMOVED if removed else FileAction.NOT_FOUND)+ return result++ def print_config(self, scope: Scope, *, repo_path: Path | None = None) -> str:+ """The MCP snippet to paste. Touches nothing."""+ from repowise.cli.mcp_config import generate_mcp_config++ target = repo_path or Path.cwd()+ return json.dumps(generate_mcp_config(target), indent=2)++ def describe_paths(self, scope: Scope, *, repo_path: Path | None = None) -> list[str]:+ if scope is Scope.PROJECT:+ return [str(project_mcp_config_path(repo_path or Path.cwd()))]+ paths = [str(settings_path())]+ desktop = desktop_config_path()+ if desktop is not None:+ paths.append(str(desktop))+ return paths++ def doctor(self) -> DoctorReport:+ """Health of the Claude Code wiring, with one command to fix it.++ Reports a stale rewrite-hook matcher explicitly. An entry 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. This is also the surface that keeps the+ ``REPOWISE_SKIP_EDITOR_SETUP`` decision honest: someone who exports that+ var permanently never gets hook migrations, so the staleness has to be+ visible somewhere.+ """+ from repowise.cli.agent_adapters.claude_code import SHELL_TOOL_MATCHER+ from repowise.cli.editor_integrations.claude_config import (+ claude_code_rewrite_hook_matcher,+ )++ registrations = detect()+ if not registrations:+ return DoctorReport(+ target_id=ID,+ status=DoctorStatus.NOT_INSTALLED,+ issues=("repowise is not registered with Claude Code.",),+ fix_command="repowise init",+ )++ issues: list[str] = []+ matcher = claude_code_rewrite_hook_matcher()+ if matcher is not None and matcher != SHELL_TOOL_MATCHER:+ issues.append(+ f"The distill rewrite hook matches {matcher!r}, but Claude Code now "+ f"names its shell tools {SHELL_TOOL_MATCHER!r}. The hook is installed "+ "and will never fire."+ )++ duplicates = [r for r in registrations if r.method == "plugin"] and [+ r for r in registrations if r.method == "direct"+ ]+ if duplicates:+ issues.append(+ "repowise is registered twice — once by the plugin and once directly — "+ "so its MCP tool schemas and hooks are loaded twice."+ )++ if not issues:+ return DoctorReport(target_id=ID, status=DoctorStatus.OK)+ return DoctorReport(+ target_id=ID,+ status=DoctorStatus.STALE,+ issues=tuple(issues),+ fix_command="repowise hook rewrite install",+ )+++TARGET = ClaudeCodeTarget()diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py b/packages/cli/src/repowise/cli/agent_targets/targets/codex.pynew file mode 100644index 000000000..e441fd3bc--- /dev/null+++ b/packages/cli/src/repowise/cli/agent_targets/targets/codex.py@@ -0,0 +1,414 @@+"""Codex CLI as an agent target.++Full tier by the derived rule — it names both a hook adapter and a transcript+adapter — but asymmetric with Claude Code in a way worth stating: its plugin+ships skills and no ``commands/`` directory, so Codex users have no slash+commands today. That gap is Phase 3's, and the tier rule does not paper over it+because slash commands are not one of the two surfaces Full is derived from.++Codex is the only target that writes three formats for one install: a TOML+server table, a TOML feature flag that has to be switched on separately or the+hooks are inert, and a JSON hooks file. That combination is the concrete+argument for composition over a base class — no single inherited ``write()``+shape fits it without an override per format.++Two quirks preserved from the existing implementation, both load-bearing:++* The shell-tool matcher is derived from the hook adapter rather than spelled+ here. Codex renamed its shell tool between releases, and a hardcoded name+ produced installs whose matcher selected nothing — silent in exactly the way+ a working hook is.+* Enabling ``features.hooks`` is a second write to the same TOML file. Skipping+ it leaves a hooks.json the host never reads.+"""++from __future__ import annotations++from pathlib import Path++from ..types import (+ Capability,+ DoctorReport,+ DoctorStatus,+ FileAction,+ InstallMethod,+ Registration,+ Scope,+ WriteResult,+)++ID = "codex"+DISPLAY_NAME = "Codex CLI"+DOCS_URL = "https://developers.openai.com/codex/cli"++#: Config key for this agent's managed instruction file (``AGENTS.md``).+PROJECT_FILE_ID = "agents_md"++METHODS = (+ InstallMethod(+ id="plugin",+ provides=frozenset({Capability.SKILLS, Capability.HOOKS}),+ managed_by="host",+ ),+ InstallMethod(+ id="direct",+ provides=frozenset({Capability.MCP, Capability.HOOKS, Capability.INSTRUCTIONS}),+ managed_by="repowise",+ preferred=True,+ ),+)+++# ---------------------------------------------------------------------------+# Paths+# ---------------------------------------------------------------------------+++def project_config_path(repo_path: Path) -> Path:+ return repo_path / ".codex" / "config.toml"+++def project_hooks_path(repo_path: Path) -> Path:+ return repo_path / ".codex" / "hooks.json"+++def user_hooks_path() -> Path:+ from repowise.cli.editor_integrations.codex_config import _codex_hooks_path++ return _codex_hooks_path()+++def instructions_path(repo_path: Path) -> Path:+ return repo_path / "AGENTS.md"+++# ---------------------------------------------------------------------------+# Config generation+# ---------------------------------------------------------------------------+++def server_table(repo_path: Path) -> dict[str, object]:+ """The ``[mcp_servers.repowise]`` table Codex reads.++ Bare ``repowise`` command: this file is repo-local and may be committed, so+ it follows the same rule as ``.mcp.json`` rather than pinning an absolute+ path only valid on the machine that ran ``init``.+ """+ return {+ "command": "repowise",+ "args": ["mcp"],+ "cwd": str(repo_path.resolve()),+ "startup_timeout_sec": 20,+ }+++def hooks_config() -> dict[str, object]:+ """Project-local Codex hooks for context injection and freshness checks."""+ from repowise.cli.agent_adapters.codex import SHELL_TOOL_MATCHER++ context_hook = {+ "type": "command",+ "command": "repowise-augment --client codex",+ "timeout": 30,+ "statusMessage": "Loading repowise context...",+ }+ freshness_hook = {+ "type": "command",+ "command": "repowise-augment --client codex",+ "timeout": 30,+ "statusMessage": "Checking repowise freshness...",+ }+ return {+ "hooks": {+ "SessionStart": [{"matcher": "startup|resume|clear", "hooks": [context_hook]}],+ "UserPromptSubmit": [{"hooks": [context_hook]}],+ "PostToolUse": [+ {"matcher": SHELL_TOOL_MATCHER, "hooks": [freshness_hook]},+ {"matcher": "apply_patch|Edit|Write", "hooks": [freshness_hook]},+ ],+ }+ }+++# ---------------------------------------------------------------------------+# Writes+# ---------------------------------------------------------------------------+++def write_server_config(repo_path: Path) -> Path:+ """Merge the repowise server table into project-local ``.codex/config.toml``."""+ from ..formats.toml_merge import (+ ensure_valid_toml,+ load_toml_document,+ replace_table,+ require_table,+ table_block,+ )++ 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)+ else:+ config_path.parent.mkdir(parents=True, exist_ok=True)+ config_path.write_text(f"{block}\n", encoding="utf-8")+ return config_path++ # 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")++ 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+++def enable_hooks_feature(repo_path: Path) -> Path:+ """Switch on ``features.hooks``, without which the hooks file is inert."""+ from ..formats.toml_merge import (+ ensure_valid_toml,+ load_toml_document,+ replace_table,+ require_table,+ table_block,+ )++ 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)+ else:+ config_path.parent.mkdir(parents=True, exist_ok=True)+ existing_text = ""+ doc = {}++ features = dict(require_table(doc, "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+++def write_hooks_config(repo_path: Path) -> Path:+ """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.+ """+ import click++ from ..formats.json_merge import load_json_object, write_json_config++ hooks_path = project_hooks_path(repo_path)+ new_config = hooks_config()++ if hooks_path.exists():+ existing = load_json_object(hooks_path)+ else:+ hooks_path.parent.mkdir(parents=True, exist_ok=True)+ existing = {}++ hooks = existing.setdefault("hooks", {})+ if not isinstance(hooks, dict):+ raise click.ClickException(+ f"Cannot update {hooks_path}: hooks must contain a JSON object. "+ "Fix or remove it and retry; no changes were written."+ )++ for event, entries in new_config["hooks"].items():+ event_hooks = hooks.setdefault(event, [])+ if not isinstance(event_hooks, list):+ raise click.ClickException(+ f"Cannot update {hooks_path}: hooks.{event} must contain a JSON array. "+ "Fix or remove it and retry; no changes were written."+ )+ for entry in entries:+ 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+++def _is_augment_hook(hook: dict) -> bool:+ cmd = hook.get("command", "")+ return "repowise-augment" in cmd or "repowise augment" in cmd+++def _has_augment_hook_for_matcher(hook_list: list, matcher: object) -> bool:+ for entry in hook_list:+ if entry.get("matcher") != matcher:+ continue+ for hook in entry.get("hooks", []):+ if _is_augment_hook(hook):+ return True+ return False+++# ---------------------------------------------------------------------------+# Detection+# ---------------------------------------------------------------------------+++def detect(repo_path: Path | None = None) -> list[Registration]:+ """Every place Codex is currently wired to repowise."""+ from repowise.cli.editor_integrations.codex_config import codex_rewrite_hook_installed++ found: list[Registration] = []++ if codex_rewrite_hook_installed():+ found.append(+ Registration(method="direct", scope=Scope.USER, config_path=user_hooks_path()),+ )++ if repo_path is not None:+ config_path = project_config_path(repo_path)+ if config_path.exists() and "mcp_servers.repowise" in config_path.read_text(+ encoding="utf-8", errors="ignore"+ ):+ found.append(+ Registration(method="direct", scope=Scope.PROJECT, config_path=config_path),+ )++ return found+++class CodexTarget:+ """Descriptor for the Codex CLI. See the module docstring."""++ id = ID+ display_name = DISPLAY_NAME+ docs_url = DOCS_URL+ hook_adapter = "codex"+ session_adapter = "codex"+ methods = METHODS+ project_file_id = PROJECT_FILE_ID++ def supports_scope(self, scope: Scope) -> bool:+ return True++ def detect(self, repo_path: Path | None = None) -> list[Registration]:+ return detect(repo_path)++ def install(+ self,+ scope: Scope,+ options: object = None,+ *,+ repo_path: Path | None = None,+ ) -> WriteResult:+ from repowise.cli.editor_integrations.codex_config import install_codex_rewrite_hook++ 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)+ return result++ hooks = install_codex_rewrite_hook()+ result.record(+ hooks or user_hooks_path(),+ FileAction.UPDATED if hooks else FileAction.NOT_FOUND,+ )+ return result++ def uninstall(self, scope: Scope, *, repo_path: Path | None = None) -> WriteResult:+ from repowise.cli.editor_integrations.codex_config import (+ remove_agents_md_distill_section,+ uninstall_codex_rewrite_hook,+ )++ result = WriteResult()+ if scope is Scope.USER:+ removed = uninstall_codex_rewrite_hook()+ result.record(+ user_hooks_path(),+ FileAction.REMOVED if removed else FileAction.NOT_FOUND,+ )+ return result++ if repo_path is None:+ raise ValueError("project-scope uninstall needs a repo_path")+ removed = remove_agents_md_distill_section(repo_path)+ result.record(+ instructions_path(repo_path),+ FileAction.REMOVED if removed else FileAction.NOT_FOUND,+ )+ return result++ def print_config(self, scope: Scope, *, repo_path: Path | None = None) -> str:+ from ..formats.toml_merge import table_block++ target = repo_path or Path.cwd()+ return (+ table_block("mcp_servers.repowise", server_table(target))+ + "\n\n"+ + table_block("features", {"hooks": True})+ )++ def describe_paths(self, scope: Scope, *, repo_path: Path | None = None) -> list[str]:+ if scope is Scope.USER:+ return [str(user_hooks_path())]+ repo = repo_path or Path.cwd()+ return [+ str(project_config_path(repo)),+ str(project_hooks_path(repo)),+ str(instructions_path(repo)),+ ]++ def doctor(self) -> DoctorReport:+ """Health of the Codex wiring.++ The stale-matcher case matters more here than anywhere else: Codex is+ the harness that actually renamed its shell tool, and an install written+ before the rename carries a matcher that selects nothing.+ """+ from repowise.cli.agent_adapters.codex import SHELL_TOOL_MATCHER+ from repowise.cli.editor_integrations.codex_config import (+ codex_rewrite_hook_matcher,+ codex_supports_rewrite,+ )++ matcher = codex_rewrite_hook_matcher()+ if matcher is None:+ return DoctorReport(+ target_id=ID,+ status=DoctorStatus.NOT_INSTALLED,+ issues=("The distill rewrite hook is not installed for Codex.",),+ fix_command="repowise hook rewrite install",+ )++ issues: list[str] = []+ if matcher != SHELL_TOOL_MATCHER:+ issues.append(+ f"The rewrite hook matches {matcher!r}, but Codex now names its shell "+ f"tools {SHELL_TOOL_MATCHER!r}. The hook is installed and will never fire."+ )+ if codex_supports_rewrite() is False:+ issues.append(+ "This Codex build predates PreToolUse command rewriting, so the hook "+ "is registered but its rewrite will be rejected at runtime."+ )++ if not issues:+ return DoctorReport(target_id=ID, status=DoctorStatus.OK)+ return DoctorReport(+ target_id=ID,+ status=DoctorStatus.STALE,+ issues=tuple(issues),+ fix_command="repowise hook rewrite install",+ )+++TARGET = CodexTarget()diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py b/packages/cli/src/repowise/cli/agent_targets/targets/vscode.pynew file mode 100644index 000000000..3e09e6ec8--- /dev/null+++ b/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py@@ -0,0 +1,260 @@+"""VS Code as an agent target.++Good tier, and the descriptor makes that structural rather than editorial: it+names neither a hook adapter nor a transcript adapter, so :func:`derive_tier`+cannot place it at Full however many files it writes. VS Code gets the MCP+server and an extension recommendation; it has no hook protocol for repowise to+intercept tool calls through, and no transcript format to mine.++The distinguishing quirk is that both files it writes may legally contain+comments — VS Code accepts JSONC throughout ``.vscode/``. So this target is the+one that *declines* rather than repairs: a file it cannot parse is far more+likely to be a commented config than a damaged one, and rewriting it would+silently delete the user's comments. Both writers raise ``ValueError`` and the+caller reports what to add by hand.++Worth recording for Phase 5: Cursor does **not** read ``.vscode/mcp.json``. It+uses ``.cursor/mcp.json`` and exposes no provider API, so it is a separate+target rather than a flag on this one.+"""++from __future__ import annotations++import json+from pathlib import Path++from ..types import (+ Capability,+ DoctorReport,+ DoctorStatus,+ FileAction,+ InstallMethod,+ Registration,+ Scope,+ WriteResult,+)++ID = "vscode"+DISPLAY_NAME = "VS Code"+DOCS_URL = "https://code.visualstudio.com/docs/copilot/chat/mcp-servers"++EXTENSION_ID = "repowise-dev.repowise"++#: Config key gating this agent's managed project files.+PROJECT_FILE_ID = "vscode_mcp"++METHODS = (+ InstallMethod(+ id="direct",+ provides=frozenset({Capability.MCP}),+ managed_by="repowise",+ preferred=True,+ ),+)+++def mcp_config_path(repo_path: Path) -> Path:+ return repo_path / ".vscode" / "mcp.json"+++def extensions_config_path(repo_path: Path) -> Path:+ return repo_path / ".vscode" / "extensions.json"+++def server_entry(repo_path: Path) -> dict:+ """The ``.vscode/mcp.json`` server entry.++ VS Code keys stdio servers under a top-level ``servers`` map and expects a+ ``type`` field. Command and path convention mirror the repo-shared+ ``.mcp.json`` exactly, so a committed workspace config resolves the same+ server on every contributor's checkout.+ """+ from repowise.cli.mcp_config import generate_mcp_config++ entry = generate_mcp_config(repo_path)["mcpServers"]["repowise"]+ return {"type": "stdio", **entry}+++def write_mcp_config(repo_path: Path) -> Path:+ """Merge the repowise server into ``.vscode/mcp.json``.++ Raises ``ValueError`` when the existing file is not strict JSON or is not+ shaped as expected, so the caller can skip rather than destroy a JSONC file.+ """+ from ..formats.json_merge import (+ load_json_object_or_value_error,+ merge_server_entries,+ write_json_config,+ )++ config_path = mcp_config_path(repo_path)+ new_entry = {"repowise": server_entry(repo_path)}++ if config_path.exists():+ existing = load_json_object_or_value_error(config_path, "mcp.json")+ servers = existing.get("servers", {})+ if not isinstance(servers, dict):+ raise ValueError("mcp.json 'servers' must be a JSON object")+ servers = dict(servers)+ merge_server_entries(servers, new_entry)+ existing["servers"] = servers+ merged = existing+ else:+ config_path.parent.mkdir(parents=True, exist_ok=True)+ merged = {"servers": new_entry}++ write_json_config(config_path, merged)+ return config_path+++def write_extensions_config(repo_path: Path) -> Path:+ """Recommend the repowise extension, preserving existing entries."""+ from ..formats.json_merge import load_json_object_or_value_error, write_json_config++ config_path = extensions_config_path(repo_path)++ if config_path.exists():+ existing = load_json_object_or_value_error(config_path, "extensions.json")+ recommendations = existing.get("recommendations", [])+ if not isinstance(recommendations, list):+ raise ValueError("extensions.json 'recommendations' must be a JSON array")+ recommendations = list(recommendations)+ if EXTENSION_ID not in recommendations:+ recommendations.append(EXTENSION_ID)+ existing["recommendations"] = recommendations+ merged = existing+ else:+ config_path.parent.mkdir(parents=True, exist_ok=True)+ merged = {"recommendations": [EXTENSION_ID]}++ write_json_config(config_path, merged)+ return config_path+++def detect(repo_path: Path | None = None) -> list[Registration]:+ """Whether the workspace MCP config names repowise.++ Project scope only: VS Code reads the workspace file, and repowise writes+ nothing user-level for it.+ """+ if repo_path is None:+ return []+ config_path = mcp_config_path(repo_path)+ if not config_path.exists():+ return []+ try:+ data = json.loads(config_path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ # A JSONC workspace file is unparseable here but may well be wired up.+ # Reporting "not configured" would be a guess, so report nothing.+ return []+ servers = data.get("servers")+ if not isinstance(servers, dict) or "repowise" not in servers:+ return []+ return [Registration(method="direct", scope=Scope.PROJECT, config_path=config_path)]+++class VSCodeTarget:+ """Descriptor for VS Code. See the module docstring."""++ id = ID+ display_name = DISPLAY_NAME+ docs_url = DOCS_URL+ hook_adapter = None+ session_adapter = None+ methods = METHODS+ project_file_id = PROJECT_FILE_ID++ def supports_scope(self, scope: Scope) -> bool:+ """Project scope only — there is no user-level file repowise writes."""+ return scope is Scope.PROJECT++ def detect(self, repo_path: Path | None = None) -> list[Registration]:+ return detect(repo_path)++ def install(+ self,+ scope: Scope,+ options: object = None,+ *,+ repo_path: Path | None = None,+ ) -> WriteResult:+ result = WriteResult()+ if scope is not Scope.PROJECT:+ return result+ if repo_path is None:+ raise ValueError("project-scope install needs a repo_path")++ try:+ result.record(write_mcp_config(repo_path), FileAction.UPDATED)+ except ValueError:+ result.record(mcp_config_path(repo_path), FileAction.KEPT)+ result.note(+ ".vscode/mcp.json left unchanged (not valid JSON; it may contain "+ 'comments). Add a "repowise" server under "servers" manually.'+ )+ try:+ result.record(write_extensions_config(repo_path), FileAction.UPDATED)+ except ValueError:+ result.record(extensions_config_path(repo_path), FileAction.KEPT)+ result.note(+ ".vscode/extensions.json left unchanged (not valid JSON; it may "+ f'contain comments). Add "{EXTENSION_ID}" to "recommendations" manually.'+ )+ 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,+ )++ 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)+ return result++ def print_config(self, scope: Scope, *, repo_path: Path | None = None) -> str:+ return json.dumps({"servers": {"repowise": server_entry(repo_path or Path.cwd())}}, indent=2)++ def describe_paths(self, scope: Scope, *, repo_path: Path | None = None) -> list[str]:+ if scope is not Scope.PROJECT:+ return []+ repo = repo_path or Path.cwd()+ return [str(mcp_config_path(repo)), str(extensions_config_path(repo))]++ def doctor(self) -> DoctorReport:+ """Health is repo-scoped, so a bare call can only report the honest answer.++ Without a repo path there is nothing user-level to inspect. Reporting+ ``OK`` would be a claim we have not checked, so this reports+ not-installed with the command that would wire it.+ """+ return DoctorReport(+ target_id=ID,+ status=DoctorStatus.NOT_INSTALLED,+ issues=("VS Code wiring is workspace-local; run this from a repo to check it.",),+ fix_command="repowise init",+ )+++TARGET = VSCodeTarget()diff --git a/packages/cli/src/repowise/cli/agent_targets/types.py b/packages/cli/src/repowise/cli/agent_targets/types.pynew file mode 100644index 000000000..7f0a03363--- /dev/null+++ b/packages/cli/src/repowise/cli/agent_targets/types.py@@ -0,0 +1,403 @@+"""The descriptor every agent integration implements.++One :class:`AgentTarget` per agent repowise can wire up. The orchestrators+(``init``, ``update``, ``doctor``) drive targets through this Protocol and never+branch on an agent's name, so adding an agent is a descriptor module plus a+registry line rather than an edit to every caller.++Three shapes here are load-bearing and worth reading before implementing a+target:++**The tier is derived, never declared.** :func:`derive_tier` computes it from+what a descriptor actually wires — whether it names a hook adapter, whether it+names a transcript adapter, whether it writes anything at all. A target cannot+claim Full while its session adapter is missing, which is exactly the drift a+declared field would let through and the docs would then repeat.++**:meth:`AgentTarget.detect` returns a list, not a bool.** "Configured: yes" is+the wrong answer when the truth is "configured three times, one of them five+weeks old". Each :class:`Registration` carries the method, scope and config path+that produced it, which is what lets the CLI report duplicate registrations and+lets a repair collapse them.++**Install method is a first-class axis.** An agent reachable both through a host+plugin and through direct wiring declares both, so the direct path can stand+down when :meth:`detect` finds the plugin already present rather than writing a+second registration the host will merge and charge for twice.++A descriptor names the hook and transcript layers by string and never+reimplements them. ``agent_targets`` may reference ``cli.agent_adapters``;+``cli.agent_adapters`` must never import ``agent_targets``, because it sits on+the PreToolUse hot path where module scope is stdlib-only by design.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from enum import StrEnum+from pathlib import Path+from typing import Protocol, runtime_checkable+++class Scope(StrEnum):+ """Where a registration lives.++ ``USER`` is per-machine config outside the repo (``~/.claude/settings.json``,+ ``~/.codex/hooks.json``); ``PROJECT`` is repo-local and may be committed.+ The distinction drives more than paths: a repo-shared file keeps the bare+ ``repowise`` command because one contributor's absolute path would break+ everyone else's checkout, while a per-user file pins the absolute path of+ the install that wrote it so a PATH shadow cannot hijack the server.+ """++ USER = "user"+ PROJECT = "project"+++class FileAction(StrEnum):+ """What an install or uninstall did to one file.++ Taken from codegraph's installer, which reports one of these per file and+ renders a log line from it. ``UNCHANGED`` is the one that earns its keep:+ it means the file was inspected and already held exactly what we would+ write, which is what makes a re-run byte-identical and stops an idempotent+ re-install from printing a misleading "updated".++ (The plan called this a 7-value enum; codegraph ships six, and six is what+ the actions actually are. Its marker-block helper has a seventh internal+ ``appended`` state, but it is folded into ``updated`` before it reaches a+ result, so it is not an action a caller can observe.)+ """++ CREATED = "created"+ UPDATED = "updated"+ UNCHANGED = "unchanged"+ REMOVED = "removed"+ NOT_FOUND = "not-found"+ KEPT = "kept"+++class Capability(StrEnum):+ """A surface a target can wire, and the vocabulary tiers are derived from."""++ #: An MCP server registration the host will launch.+ MCP = "mcp"+ #: Hook entries that let repowise intercept or annotate tool calls.+ HOOKS = "hooks"+ #: Skill/prompt content the host loads from disk.+ SKILLS = "skills"+ #: Slash commands the host exposes to the user.+ COMMANDS = "commands"+ #: A managed instructions file (``CLAUDE.md``, ``AGENTS.md``).+ INSTRUCTIONS = "instructions"+ #: Session transcripts repowise can mine after the fact.+ TRANSCRIPTS = "transcripts"+++class Tier(StrEnum):+ """Support depth, mirroring the language tiers in the README.++ Never set by hand. See :func:`derive_tier`.+ """++ FULL = "full"+ GOOD = "good"+ PASTE_CONFIG = "paste-config"+++class DoctorStatus(StrEnum):+ """The four states a target's health can be in.++ Borrowed from tokenjuice's instruction doctor, which is better than+ codegraph's two-state version for one reason: ``STALE`` is distinct from+ ``BROKEN``. A hook whose matcher names a tool the host has since renamed is+ installed, parses fine, and will never fire — reporting that as "ok" is how+ it stays invisible, and reporting it as "broken" sends the user to fix a+ file that is not damaged.+ """++ OK = "ok"+ NOT_INSTALLED = "not-installed"+ STALE = "stale"+ BROKEN = "broken"+++@dataclass(frozen=True)+class InstallMethod:+ """One route by which a target can be wired up.++ *managed_by* is the field that matters. ``"host"`` means the host owns the+ artifact's lifecycle and repowise cannot rewrite it — a plugin the user+ updates through their agent's own command — so a version skew there is+ something to report, never something to fix by writing. ``"repowise"``+ means we own the file and a refresh is ours to perform.+ """++ id: str+ provides: frozenset[Capability]+ managed_by: str+ #: Preferred when several methods are available and nothing is installed.+ preferred: bool = False+++@dataclass(frozen=True)+class Registration:+ """One place this target is currently wired to repowise.++ A target can legitimately return several: a user who installed the plugin+ *and* ran ``init`` has two, and reporting that honestly is the point of+ returning a list.+ """++ method: str+ scope: Scope+ config_path: Path+ #: Version of the artifact where the file records one; ``None`` when the+ #: format has nowhere to put it, which is most of them.+ version: str | None = None+ detail: str | None = None+++@dataclass(frozen=True)+class FileWrite:+ """What happened to one file."""++ path: Path+ action: FileAction+++@dataclass+class WriteResult:+ """Per-file log of an install or uninstall.++ Mutable and appended to as a target works through its files, because that+ is how targets are written; callers should treat a returned result as+ read-only. Doubles as the ``--format json`` payload, which is why the+ actions are a closed enum rather than prose.+ """++ files: list[FileWrite] = field(default_factory=list)+ #: One-line notes surfaced verbatim, e.g. "Restart the editor to apply."+ notes: list[str] = field(default_factory=list)++ def record(self, path: Path, action: FileAction) -> None:+ self.files.append(FileWrite(path=path, action=action))++ 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."""+ return any(+ f.action in (FileAction.CREATED, FileAction.UPDATED, FileAction.REMOVED)+ for f in self.files+ )++ def as_dict(self) -> dict:+ """JSON-ready projection, built here at the construction site.++ Built from the result itself rather than re-derived by a renderer: 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 alone.+ """+ return {+ "files": [{"path": str(f.path), "action": f.action.value} for f in self.files],+ "notes": list(self.notes),+ }+++@dataclass(frozen=True)+class DoctorReport:+ """A target's health, with exactly one thing to run about it.++ One *fix_command*, never a list. A diagnostic that hands back three+ candidate repairs has moved the diagnosis onto the user; picking the single+ next command is the job.+ """++ target_id: str+ status: DoctorStatus+ issues: tuple[str, ...] = ()+ fix_command: str | None = None++ def as_dict(self) -> dict:+ return {+ "target": self.target_id,+ "status": self.status.value,+ "issues": list(self.issues),+ "fix_command": self.fix_command,+ }+++@runtime_checkable+class AgentTarget(Protocol):+ """One agent repowise can wire up.++ Implementations compose the helpers in :mod:`.formats` rather than+ inheriting from a base class. codegraph states the rationale and our own+ evidence agrees: Codex needs TOML plus a hooks JSON, VS Code needs two JSON+ files one of which may carry comments, and a future Cursor target needs a+ frontmattered rules file. A base class would need an override hook for each+ and would force that shape on every target that does not want it.++ Every method must be safe to call when nothing was ever installed.+ """++ #: Stable id used in ``--target`` and registry lookup. Short, lowercase.+ id: str+ display_name: str+ docs_url: str | None++ #: Named entries in ``cli.agent_adapters`` / ``core.sessions.adapters``.+ #: ``None`` means this agent has no such surface, which is what keeps it+ #: out of the Full tier.+ hook_adapter: str | None+ session_adapter: str | None++ #: Routes this target can be wired through, in preference order.+ methods: tuple[InstallMethod, ...]++ #: Config key gating this agent's managed instruction file, under+ #: ``editor_files`` in ``.repowise/config.yaml``. Owned by the descriptor so+ #: the legacy CLI flag mapping can look it up rather than restate it.+ project_file_id: str++ def supports_scope(self, scope: Scope) -> bool:+ """Whether this target has a config home at *scope*."""+ ...++ def detect(self, repo_path: Path | None = None) -> list[Registration]:+ """Every place this target is currently wired.++ *repo_path* is optional because user-scope registrations are knowable+ without one — ``doctor`` run from anywhere still wants them. Passing it+ adds the project-scope registrations. Never raises: a probe that cannot+ read a config reports no registration rather than guessing at one.+ """+ ...++ def install(+ self,+ scope: Scope,+ options: object = None,+ *,+ repo_path: Path | None = None,+ ) -> WriteResult:+ """Wire this target up at *scope*, idempotently.++ *repo_path* is keyword-only and required in practice for every scope: a+ project install writes into it, and a user-scope MCP registration has to+ record which repo the server should serve.+ """+ ...++ def uninstall(self, scope: Scope, *, repo_path: Path | None = None) -> WriteResult:+ """Remove only what :meth:`install` writes, preserving siblings.++ Must be safe to call when nothing was ever installed, reporting+ ``not-found`` or ``kept`` rather than raising.+ """+ ...++ def print_config(self, scope: Scope, *, repo_path: Path | None = None) -> str:+ """The config snippet a user would paste by hand.++ MUST NOT touch the filesystem. This is the whole of the Paste-config+ tier: an agent nobody has asked us to support is still served by a+ snippet, at zero maintenance cost.+ """+ ...++ def describe_paths(self, scope: Scope, *, repo_path: Path | None = None) -> list[str]:+ """Files this target would write at *scope*, without writing them.++ May predict a superset of what one :meth:`install` call writes — an+ opt-in surface counts — but never a path install would not touch, since+ this is what a dry run shows the user.+ """+ ...++ def doctor(self) -> DoctorReport:+ """This target's health, with one command that would fix it."""+ ...+++@runtime_checkable+class InstallLifecycle(Protocol):+ """The ``init`` / ``update`` half of an integration's contract.++ Four 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.++ 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:+ ``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``.+ """++ def configure_options(self, console_obj: object, options: object) -> object:+ """Let the integration prompt or adjust setup options before writing."""+ ...++ def write_project_files(+ self, console_obj: object, repo_path: Path, options: object+ ) -> None:+ """Write project-local config or instruction files for this agent."""+ ...++ def register_client(self, console_obj: object, repo_path: Path) -> None:+ """Register user-level client configuration for this agent."""+ ...++ def refresh_project_files(+ self, console_obj: object, repo_path: Path, options: object+ ) -> None:+ """Refresh managed project files after repository content changes."""+ ...+++def capabilities_of(target: AgentTarget) -> frozenset[Capability]:+ """Everything *target* wires, unioned across its install methods."""+ provided: set[Capability] = set()+ for method in target.methods:+ provided |= set(method.provides)+ return frozenset(provided)+++def derive_tier(target: AgentTarget) -> Tier:+ """Compute a target's support tier from what it actually wires.++ The rule, and why it is this one:++ * A target that writes nothing is **Paste-config**. It has no methods, only+ :meth:`~AgentTarget.print_config`, and costs nothing to keep.+ * A target that names **both** a hook adapter and a transcript adapter is+ **Full**. Those two are the deep surfaces — intercepting tool calls, and+ mining sessions after the fact — and they are the ones that cannot be+ faked by writing a config file. Requiring both is what makes it+ structurally impossible for the docs to claim Full while the session+ adapter is missing.+ * Everything else is **Good**: a real integration, MCP and instructions and+ possibly skills, but no hook-level interception.++ Deliberately strict about Full. Breadth that overclaims depth is worse than+ narrower breadth, and the tier is the thing the README badges repeat.+ """+ if not target.methods:+ return Tier.PASTE_CONFIG+ if target.hook_adapter and target.session_adapter:+ return Tier.FULL+ return Tier.GOODdiff --git a/packages/cli/src/repowise/cli/editor_integrations/claude.py b/packages/cli/src/repowise/cli/editor_integrations/claude.pyindex 2a14c8ce0..d043c8f60 100644--- a/packages/cli/src/repowise/cli/editor_integrations/claude.py+++ b/packages/cli/src/repowise/cli/editor_integrations/claude.py@@ -7,14 +7,22 @@ from typing import Anyimport click+from repowise.cli.agent_targets.targets import claude_code as claude_targetfrom repowise.cli.editor_setup import EditorSetupOptionsfrom repowise.cli.helpers import get_db_url_for_repo, load_config, run_asyncclass ClaudeCodeSetup:- """Claude Code/Desktop setup integration preserving existing init behavior."""+ """Claude Code/Desktop setup integration preserving existing init behavior.- project_file_id = "claude_md"+ The ``init``/``update`` half of the integration. Detection, uninstall,+ ``print_config`` and ``doctor`` live on the descriptor in+ ``agent_targets.targets.claude_code``, along with every config write this+ class drives.+ """++ #: Read from the descriptor rather than restated, so the id has one home.+ project_file_id = claude_target.PROJECT_FILE_IDdef configure_options(self,diff --git a/packages/cli/src/repowise/cli/editor_integrations/codex.py b/packages/cli/src/repowise/cli/editor_integrations/codex.pyindex acd585437..c6c499287 100644--- a/packages/cli/src/repowise/cli/editor_integrations/codex.py+++ b/packages/cli/src/repowise/cli/editor_integrations/codex.py@@ -7,14 +7,20 @@ from typing import Anyimport click+from repowise.cli.agent_targets.targets import codex as codex_targetfrom repowise.cli.editor_setup import EditorSetupOptionsclass CodexSetup:- """Project-local Codex setup integration."""+ """Project-local Codex setup integration.- integration_id = "codex"- project_file_id = "agents_md"+ The ``init``/``update`` half of the integration; the descriptor in+ ``agent_targets.targets.codex`` owns the writes and everything else.+ """++ #: Read from the descriptor rather than restated, so the ids have one home.+ integration_id = codex_target.ID+ project_file_id = codex_target.PROJECT_FILE_IDdef configure_options(self,diff --git a/packages/cli/src/repowise/cli/editor_integrations/codex_config.py b/packages/cli/src/repowise/cli/editor_integrations/codex_config.pyindex b7e2ab159..08c91e8df 100644--- a/packages/cli/src/repowise/cli/editor_integrations/codex_config.py+++ b/packages/cli/src/repowise/cli/editor_integrations/codex_config.py@@ -309,22 +309,27 @@ def install_agents_md_distill_section(repo_path: Path) -> Path | None:already teaches distillation elsewhere (e.g. a future indexed-templatesection) is left untouched; otherwise the block is appended. Returns theAGENTS.md path, or None on write failure.++ The marker mechanics live in ``agent_targets.formats.marker_block``; what+ stays here is the Codex-specific policy — the section text, and the+ "already taught elsewhere" bail, which is a judgement about this file's+ content rather than about managed blocks in general."""+ from repowise.cli.agent_targets.formats import marker_block+target = _agents_md_path(repo_path)- wrapped = f"{_DISTILL_MARKER_START}\n{_DISTILL_SECTION}\n{_DISTILL_MARKER_END}"try:- if not target.exists():- content = f"{_NEW_FILE_PLACEHOLDER}\n{wrapped}\n"- else:+ if target.exists():existing = target.read_text(encoding="utf-8")- if _DISTILL_MARKER_START in existing:- pattern = re.escape(_DISTILL_MARKER_START) + r".*?" + re.escape(_DISTILL_MARKER_END)- content = re.sub(pattern, wrapped, existing, flags=re.DOTALL)- elif _DISTILL_SECTION_HEADING in existing:+ if _DISTILL_MARKER_START not in existing and _DISTILL_SECTION_HEADING in existing:return target # already taught elsewhere in the file- else:- content = existing.rstrip() + "\n\n" + wrapped + "\n"- target.write_text(content, encoding="utf-8", newline="\n")+ marker_block.upsert(+ target,+ f"\n{_DISTILL_SECTION}\n",+ _DISTILL_MARKER_START,+ _DISTILL_MARKER_END,+ new_file_prefix=_NEW_FILE_PLACEHOLDER,+ )return targetexcept OSError:return None@@ -337,32 +342,14 @@ def remove_agents_md_distill_section(repo_path: Path) -> bool:is deleted entirely so install→uninstall round-trips to "no AGENTS.md".User content is never touched."""- target = _agents_md_path(repo_path)- if not target.exists():- return False- try:- existing = target.read_text(encoding="utf-8")- except OSError:- return False- if _DISTILL_MARKER_START not in existing:- return False+ from repowise.cli.agent_targets.formats import marker_block- pattern = (- r"\n*" + re.escape(_DISTILL_MARKER_START) + r".*?" + re.escape(_DISTILL_MARKER_END) + r"\n?"+ return marker_block.remove(+ _agents_md_path(repo_path),+ _DISTILL_MARKER_START,+ _DISTILL_MARKER_END,+ delete_if_only=_NEW_FILE_PLACEHOLDER,)- remaining = re.sub(pattern, "", existing, flags=re.DOTALL)- if remaining and not remaining.endswith("\n"):- # Install rstrips before appending the block; restore the trailing- # newline that strip consumed so removal is a true inverse.- remaining += "\n"- try:- if remaining.strip() in ("", _NEW_FILE_PLACEHOLDER.strip()):- target.unlink()- else:- target.write_text(remaining, encoding="utf-8", newline="\n")- except OSError:- return False- return Truedef agents_md_distill_section_installed(repo_path: Path) -> bool:diff --git a/packages/cli/src/repowise/cli/editor_integrations/defaults.py b/packages/cli/src/repowise/cli/editor_integrations/defaults.pyindex ec183ffdd..318ca7f0f 100644--- a/packages/cli/src/repowise/cli/editor_integrations/defaults.py+++ b/packages/cli/src/repowise/cli/editor_integrations/defaults.py@@ -1,15 +1,52 @@-"""Default editor setup integration registry."""+"""Default editor integrations, and the legacy CLI flag mapping.++Two different things live here and it is worth being explicit about which is+which, because one of them is a dead end by design.++:func:`get_default_editor_integrations` is the live registry of setup+integrations ``init`` and ``update`` drive.++The three ``get_default_*`` functions below map **legacy CLI flags**+(``--no-claude-md``, ``--agents-md``, ``--codex``) onto the ids those flags+control. Each takes a keyword argument named after one agent, which is the+shape that does not scale: at three agents it is mildly redundant, at twelve it+is the flat per-host chain that made a competitor's installer 7,446 lines. So+the ids are no longer restated here — each is read from the agent's own+descriptor, and these functions are now a thin translation layer over that.++**A new agent adds nothing to this file.** It gets a descriptor and a registry+line; if it also wants a CLI flag, the flag joins the general mechanism rather+than growing a fourth keyword function. That is the whole point of the change,+and it is why these three keep their signatures instead of being deleted: they+have direct callers in ``init`` and ``update`` and direct test coverage, and+breaking a public surface adds risk to a rewrite whose value is that it changes+nothing observable.+"""from __future__ import annotations-from repowise.cli.editor_setup import EditorSetupIntegration+from repowise.cli.agent_targets.types import InstallLifecyclefrom .claude import ClaudeCodeSetupfrom .codex import CodexSetupfrom .vscode import VSCodeSetup-def get_default_editor_integrations() -> tuple[EditorSetupIntegration, ...]:+def _project_file_id(target_id: str) -> str:+ """The ``editor_files`` config key owned by *target_id*'s descriptor.++ Read from the registry rather than restated, so an agent's instruction-file+ key is defined in exactly one place — the agent's own module.+ """+ from repowise.cli.agent_targets.registry import get_target++ target = get_target(target_id)+ if target is None: # pragma: no cover - registry and callers move together+ raise LookupError(f"no agent target registered for {target_id!r}")+ return target.project_file_id+++def get_default_editor_integrations() -> tuple[InstallLifecycle, ...]:"""Return the editor integrations enabled by default today."""return (ClaudeCodeSetup(), CodexSetup(), VSCodeSetup())@@ -20,7 +57,7 @@ def get_default_disabled_project_files(*, no_claude_md: bool = False) -> tuple[sdisabled: list[str] = []if no_claude_md:- disabled.append(ClaudeCodeSetup.project_file_id)+ disabled.append(_project_file_id("claude-code"))return tuple(disabled)@@ -32,7 +69,7 @@ def get_default_project_file_overrides(overrides: dict[str, bool] = {}if agents_md is not None:- overrides[CodexSetup.project_file_id] = agents_md+ overrides[_project_file_id("codex")] = agents_mdreturn overridesdiff --git a/packages/cli/src/repowise/cli/editor_integrations/vscode.py b/packages/cli/src/repowise/cli/editor_integrations/vscode.pyindex c4b624ee6..f41e451fe 100644--- a/packages/cli/src/repowise/cli/editor_integrations/vscode.py+++ b/packages/cli/src/repowise/cli/editor_integrations/vscode.py@@ -7,6 +7,7 @@ from typing import Anyimport click+from repowise.cli.agent_targets.targets import vscode as vscode_targetfrom repowise.cli.editor_setup import EditorSetupOptions@@ -18,8 +19,9 @@ class VSCodeSetup:they use the bare ``repowise`` command like the committed ``.mcp.json``."""- integration_id = "vscode"- project_file_id = "vscode_mcp"+ #: Read from the descriptor rather than restated, so the ids have one home.+ integration_id = vscode_target.ID+ project_file_id = vscode_target.PROJECT_FILE_IDdef configure_options(self,diff --git a/packages/cli/src/repowise/cli/editor_setup.py b/packages/cli/src/repowise/cli/editor_setup.pyindex 10bedf178..d8c8efa4f 100644--- a/packages/cli/src/repowise/cli/editor_setup.py+++ b/packages/cli/src/repowise/cli/editor_setup.py@@ -1,9 +1,16 @@"""AI editor setup orchestration for repowise init.The indexing command should not know the details of each editor's config files,-global settings, or managed instruction files. This module keeps that product-setup layer behind a small integration interface; concrete editor integrations-live in ``repowise.cli.editor_integrations``.+global settings, or managed instruction files. This module keeps that product+setup layer behind an integration interface; concrete editor integrations live+in ``repowise.cli.editor_integrations`` and the config writes they drive live in+``repowise.cli.agent_targets``.++The interface itself is no longer declared here. It is+:class:`~repowise.cli.agent_targets.types.InstallLifecycle`, next to the+:class:`~repowise.cli.agent_targets.types.AgentTarget` descriptor whose surface+it is a subset of — one home for integration protocols rather than two that+drift."""from __future__ import annotations@@ -12,7 +19,9 @@ import osfrom collections.abc import Iterable, Mappingfrom dataclasses import dataclass, fieldfrom pathlib import Path-from typing import Any, Protocol+from typing import Any++from repowise.cli.agent_targets.types import InstallLifecycle# When set (truthy), `repowise init` skips registering MCP servers / hooks in# the user's *global* editor config (~/.claude/settings.json, Claude Desktop).@@ -171,43 +180,9 @@ class EditorSetupOptions:)-class EditorSetupIntegration(Protocol):- """Setup hooks implemented by each AI editor integration."""-- def configure_options(- self,- console_obj: Any,- options: EditorSetupOptions,- ) -> EditorSetupOptions:- """Let the integration prompt or adjust setup options before writing files."""- ...-- def write_project_files(- self,- console_obj: Any,- repo_path: Path,- options: EditorSetupOptions,- ) -> None:- """Write project-local config or instruction files for this editor."""- ...-- def register_client(self, console_obj: Any, repo_path: Path) -> None:- """Register global or user-level client configuration for this editor."""- ...-- def refresh_project_files(- self,- console_obj: Any,- repo_path: Path,- options: EditorSetupOptions,- ) -> None:- """Refresh managed project files after repository content changes."""- ...--def _resolve_integrations(- integrations: tuple[EditorSetupIntegration, ...] | None,-) -> tuple[EditorSetupIntegration, ...]:+ integrations: tuple[InstallLifecycle, ...] | None,+) -> tuple[InstallLifecycle, ...]:if integrations is not None:return integrationsfrom repowise.cli.editor_integrations.defaults import get_default_editor_integrations@@ -222,7 +197,7 @@ def resolve_editor_setup_options(prompt_for_project_files: bool = False,project_file_overrides: Mapping[str, bool] | None = None,integration_overrides: Mapping[str, bool] | None = None,- integrations: tuple[EditorSetupIntegration, ...] | None = None,+ integrations: tuple[InstallLifecycle, ...] | None = None,) -> EditorSetupOptions:"""Build setup options, allowing integrations to own their prompts."""@@ -243,7 +218,7 @@ def write_editor_project_files(*,options: EditorSetupOptions | None = None,disabled_project_files: Iterable[str] | None = None,- integrations: tuple[EditorSetupIntegration, ...] | None = None,+ integrations: tuple[InstallLifecycle, ...] | None = None,) -> None:"""Write common MCP config and project-local editor files."""@@ -262,7 +237,7 @@ def register_editor_clients(repo_path: Path,*,no_editor_setup: bool = False,- integrations: tuple[EditorSetupIntegration, ...] | None = None,+ integrations: tuple[InstallLifecycle, ...] | None = None,) -> None:"""Register editor clients with repowise MCP and hooks where supported."""@@ -277,7 +252,7 @@ def refresh_editor_project_files(repo_path: Path,*,options: EditorSetupOptions | None = None,- integrations: tuple[EditorSetupIntegration, ...] | None = None,+ integrations: tuple[InstallLifecycle, ...] | None = None,) -> None:"""Refresh editor-managed project files without rewriting common MCP config."""diff --git a/packages/cli/src/repowise/cli/mcp_config.py b/packages/cli/src/repowise/cli/mcp_config.pyindex dce7d8b0e..a31c0719a 100644--- a/packages/cli/src/repowise/cli/mcp_config.py+++ b/packages/cli/src/repowise/cli/mcp_config.py@@ -1,20 +1,30 @@-"""Generic MCP config helpers for repowise."""+"""Generic MCP config helpers, plus the compatibility surface for the savers.++What lives here now is only what is genuinely agent-independent: how a+registration spells the repowise command, the standard ``mcpServers`` payload,+the ``.repowise/mcp.json`` write, and the Codex CLI process probes.++The per-editor ``save_*`` functions that used to hold 531 lines of flat+per-agent knowledge are now **delegators**. Their bodies live with the agent+they belong to, in ``repowise.cli.agent_targets.targets``, alongside that+agent's detection, uninstall and doctor logic. They are kept as names here for+one reason: they are a long-standing public surface with direct callers and+direct test coverage, and breaking that would be a second change riding along+with a rewrite whose whole value is that it changes nothing observable.++The property that matters is not that these names are gone — it is that a *new*+agent adds nothing to this module. Everything a fourth agent needs is a+descriptor file and a registry line.+"""from __future__ import annotations-import json-import reimport shutilimport subprocessimport sysimport tempfile-import tomllibfrom pathlib import Path-import click--from repowise.cli.agent_adapters.codex import SHELL_TOOL_MATCHER-def _looks_transient(path: Path) -> bool:"""True when *path* lives somewhere that won't survive (temp, uvx cache).@@ -86,6 +96,15 @@ def generate_mcp_config(repo_path: Path, *, command: str | None = None) -> dict:}+# ---------------------------------------------------------------------------+# Codex CLI process probes+#+# Not writers, so they stay here: they answer "is this agent usable on this+# machine" for the UI and for init's prompts, and both callers want them+# without importing the target.+# ---------------------------------------------------------------------------++def resolve_codex_executable() -> str | None:"""Return the executable path used to launch Codex, or None if unavailable."""@@ -128,404 +147,174 @@ def is_codex_logged_in() -> bool:return result.returncode == 0-def generate_codex_mcp_server_config(repo_path: Path) -> dict[str, object]:- """Generate the Codex config.toml server table for repowise."""+# ---------------------------------------------------------------------------+# Generic writes+# ---------------------------------------------------------------------------- return {- "command": "repowise",- "args": ["mcp"],- "cwd": str(repo_path.resolve()),- "startup_timeout_sec": 20,- }+def save_mcp_config(repo_path: Path) -> Path:+ """Save MCP config to .repowise/mcp.json and return the path.-def generate_codex_hooks_config() -> dict[str, object]:- """Generate project-local Codex hooks for repowise context and freshness checks.-- The shell matcher is derived from the adapter rather than spelled here.- Codex names its shell tool ``shell_command`` on current releases and- ``Bash`` on older ones, and this function hardcoded ``"Bash"`` alone, so an- install written by ``repowise init --codex`` registered a matcher that- selects nothing on a current Codex. A hook whose matcher matches nothing is- silent in exactly the way a working one is, which is why this survived the- pass that fixed the same defect in the rewrite hook and the Codex plugin.+ Agent-independent: this is repowise's own copy of the payload, not any+ particular host's config, so it stays here rather than moving to a target."""+ from repowise.cli.agent_targets.formats.json_merge import write_json_config- context_hook = {- "type": "command",- "command": "repowise-augment --client codex",- "timeout": 30,- "statusMessage": "Loading repowise context...",- }- freshness_hook = {- "type": "command",- "command": "repowise-augment --client codex",- "timeout": 30,- "statusMessage": "Checking repowise freshness...",- }- return {- "hooks": {- "SessionStart": [{"matcher": "startup|resume|clear", "hooks": [context_hook]}],- "UserPromptSubmit": [{"hooks": [context_hook]}],- "PostToolUse": [- {"matcher": SHELL_TOOL_MATCHER, "hooks": [freshness_hook]},- {"matcher": "apply_patch|Edit|Write", "hooks": [freshness_hook]},- ],- }- }+ repowise_dir = repo_path / ".repowise"+ repowise_dir.mkdir(parents=True, exist_ok=True)+ config_path = repowise_dir / "mcp.json"+ write_json_config(config_path, generate_mcp_config(repo_path))+ return config_path-def _toml_value(value: object) -> str:- if isinstance(value, bool):- return "true" if value else "false"- if isinstance(value, str):- return json.dumps(value)- if isinstance(value, int):- return str(value)- 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}")+def merge_mcp_entry(config_path: Path, new_entry: dict) -> bool:+ """Merge *new_entry* into the mcpServers block of *config_path*.+ Creates the file if it doesn't exist. Returns True on success.-def _codex_mcp_server_toml(repo_path: Path) -> str:- lines = ["[mcp_servers.repowise]"]- lines.extend(- f"{key} = {_toml_value(value)}"- for key, value in generate_codex_mcp_server_config(repo_path).items()+ The per-server merge is deep: generated fields overwrite stored ones, but+ user-added keys such as an ``env`` block are preserved across+ re-registration (see ``formats.json_merge.merge_server_entries``).+ """+ from repowise.cli.agent_targets.formats.json_merge import (+ merge_server_entries,+ write_json_config,)- return "\n".join(lines)+ try:+ if config_path.exists():+ existing = load_existing_config(config_path)+ else:+ config_path.parent.mkdir(parents=True, exist_ok=True)+ existing = {}-def _toml_table_block(table_name: str, values: dict[str, object]) -> str:- lines = [f"[{table_name}]"]- lines.extend(f"{key} = {_toml_value(value)}" for key, value in values.items())- return "\n".join(lines)+ servers = dict(existing.get("mcpServers", {}))+ merge_server_entries(servers, new_entry)+ existing["mcpServers"] = servers+ write_json_config(config_path, existing)+ return True+ except OSError:+ return False-def save_mcp_config(repo_path: Path) -> Path:- """Save MCP config to .repowise/mcp.json and return the path."""- repowise_dir = repo_path / ".repowise"- repowise_dir.mkdir(parents=True, exist_ok=True)- config_path = repowise_dir / "mcp.json"- config = generate_mcp_config(repo_path)- config_path.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")- return config_path+def load_existing_config(config_path: Path) -> dict:+ """Load an existing JSON config without silently replacing bad content."""+ from repowise.cli.agent_targets.formats.json_merge import load_json_object+ return load_json_object(config_path)-def _merge_server_entries(servers: dict, new_entry: dict) -> dict:- """Deep-merge *new_entry* server definitions into *servers* in place.- For each server key, the generated ``command``/``args``/``description``- overwrite the stored values (so path/command changes take effect), but any- other keys the user added to the entry — most importantly an ``env`` block- carrying BYOK provider keys — are preserved. A shallow ``servers.update()``- would replace the whole entry and silently wipe ``env`` on every- re-registration (``repowise init`` / ``update``). See issue #307.- """- for name, entry in new_entry.items():- current = servers.get(name)- if isinstance(current, dict) and isinstance(entry, dict):- merged_entry = dict(current)- merged_entry.update(entry)- servers[name] = merged_entry- else:- servers[name] = entry- return servers+# ---------------------------------------------------------------------------+# Per-agent delegators+#+# Each forwards to the target that owns the format. See the module docstring+# for why the names survive the move.+# ----------------------------------------------------------------------------def _ensure_valid_toml(merged_text: str, config_path: Path) -> None:- """Abort before writing if the regex merge produced invalid TOML.+def generate_codex_mcp_server_config(repo_path: Path) -> dict[str, object]:+ """Generate the Codex config.toml server table for repowise."""+ from repowise.cli.agent_targets.targets import codex- The merge validates the *existing* file, but the table-rewrite regex only- matches the bare ``[mcp_servers.repowise]`` / ``[features]`` spellings. A user- who expressed the same key differently (quoted ``["features"]`` or inline under- a parent table) would slip past the regex, and appending our block would yield a- duplicate-key file. Re-parsing the merged result turns every such case into a- clean abort with the original file untouched.- """+ return codex.server_table(repo_path)- try:- tomllib.loads(merged_text)- except tomllib.TOMLDecodeError as exc:- raise click.ClickException(- f"Cannot update {config_path}: merging the repowise entry would produce "- "invalid TOML (an existing entry may use a different key spelling). "- "No changes were written."- ) from exc+def generate_codex_hooks_config() -> dict[str, object]:+ """Generate project-local Codex hooks for repowise context and freshness checks."""+ from repowise.cli.agent_targets.targets import codex-def enable_codex_hooks_feature(repo_path: Path) -> Path:- """Enable Codex hooks in project-local .codex/config.toml."""+ return codex.hooks_config()- config_path = repo_path / ".codex" / "config.toml"- try:- if config_path.exists():- existing_text = config_path.read_text(encoding="utf-8")- doc = tomllib.loads(existing_text)- else:- config_path.parent.mkdir(parents=True, exist_ok=True)- existing_text = ""- doc = {}- except tomllib.TOMLDecodeError as exc:- raise click.ClickException(- f"Cannot update {config_path}: existing file is not valid TOML. "- "Fix or remove it and retry; no changes were written."- ) from exc-- existing_features = doc.get("features", {})- if not isinstance(existing_features, dict):- raise click.ClickException(- f"Cannot update {config_path}: [features] must be a TOML table. "- "Fix or remove it and retry; no changes were written."- )+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- features = dict(existing_features)- features["hooks"] = True- feature_block = _toml_table_block("features", features)- table_re = re.compile(r"(?ms)^\s*\[features\]\s*\n.*?(?=^\s*\[|\Z)")- merged_text = table_re.sub("", existing_text).rstrip()- merged_text = f"{merged_text}\n\n{feature_block}\n" if merged_text else f"{feature_block}\n"- _ensure_valid_toml(merged_text, config_path)- config_path.write_text(merged_text, encoding="utf-8")- return config_path+ return codex.enable_hooks_feature(repo_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- config_path = repo_path / ".codex" / "config.toml"- server_block = _codex_mcp_server_toml(repo_path)-- try:- if config_path.exists():- existing_text = config_path.read_text(encoding="utf-8")- doc = tomllib.loads(existing_text)- else:- config_path.parent.mkdir(parents=True, exist_ok=True)- config_path.write_text(f"{server_block}\n", encoding="utf-8")- return config_path- except tomllib.TOMLDecodeError as exc:- raise click.ClickException(- f"Cannot update {config_path}: existing file is not valid TOML. "- "Fix or remove it and retry; no changes were written."- ) from exc-- servers = doc.get("mcp_servers")- if servers is not None and not isinstance(servers, dict):- raise click.ClickException(- f"Cannot update {config_path}: [mcp_servers] must be a TOML table. "- "Fix or remove it and retry; no changes were written."- )- if isinstance(servers, dict):- repowise = servers.get("repowise")- if repowise is not None and not isinstance(repowise, dict):- raise click.ClickException(- f"Cannot update {config_path}: [mcp_servers.repowise] must be a TOML table. "- "Fix or remove it and retry; no changes were written."- )-- table_re = re.compile(r"(?ms)^\s*\[mcp_servers\.repowise\]\s*\n.*?(?=^\s*\[|\Z)")- merged_text = table_re.sub("", existing_text).rstrip()- merged_text = f"{merged_text}\n\n{server_block}\n" if merged_text else f"{server_block}\n"- _ensure_valid_toml(merged_text, config_path)- config_path.write_text(merged_text, encoding="utf-8")- return config_path+ return codex.write_server_config(repo_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- hooks_path = repo_path / ".codex" / "hooks.json"- new_config = generate_codex_hooks_config()-- if hooks_path.exists():- existing = load_existing_config(hooks_path)- else:- hooks_path.parent.mkdir(parents=True, exist_ok=True)- existing = {}-- hooks = existing.setdefault("hooks", {})- if not isinstance(hooks, dict):- raise click.ClickException(- f"Cannot update {hooks_path}: hooks must contain a JSON object. "- "Fix or remove it and retry; no changes were written."- )-- for event, entries in new_config["hooks"].items():- event_hooks = hooks.setdefault(event, [])- if not isinstance(event_hooks, list):- raise click.ClickException(- f"Cannot update {hooks_path}: hooks.{event} must contain a JSON array. "- "Fix or remove it and retry; no changes were written."- )- for entry in entries:- if not _has_repowise_hook_for_matcher(event_hooks, entry.get("matcher")):- event_hooks.append(entry)-- hooks_path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")- enable_codex_hooks_feature(repo_path)- return hooks_path+ return codex.write_hooks_config(repo_path)def save_root_mcp_config(repo_path: Path) -> Path:- """Write .mcp.json at repo root for MCP clients that support discovery.-- Merges the repowise server entry into any existing mcpServers block- so other MCP servers configured by the user are preserved.- """- config_path = repo_path / ".mcp.json"- new_entry = generate_mcp_config(repo_path)["mcpServers"]-- if config_path.exists():- existing = load_existing_config(config_path)- servers = dict(existing.get("mcpServers", {}))- _merge_server_entries(servers, new_entry)- existing["mcpServers"] = servers- merged = existing- else:- merged = {"mcpServers": new_entry}+ """Write .mcp.json at repo root for MCP clients that support discovery."""+ from repowise.cli.agent_targets.targets import claude_code- config_path.write_text(json.dumps(merged, indent=2) + "\n", encoding="utf-8")- return config_path+ return claude_code.write_project_mcp_config(repo_path)def generate_vscode_mcp_server_entry(repo_path: Path) -> dict:- """Generate the VS Code ``.vscode/mcp.json`` server entry for repowise.+ """Generate the VS Code ``.vscode/mcp.json`` server entry for repowise."""+ from repowise.cli.agent_targets.targets import vscode- VS Code keys stdio servers under a top-level ``servers`` map and expects a- ``type`` field. The command and path convention mirror the repo-shared- ``.mcp.json`` exactly (bare ``repowise`` command, absolute repo path,- ``--transport stdio``) so a committed workspace config resolves the same- server on every contributor's checkout.- """- entry = generate_mcp_config(repo_path)["mcpServers"]["repowise"]- return {"type": "stdio", **entry}+ return vscode.server_entry(repo_path)def save_vscode_mcp_config(repo_path: Path) -> Path:"""Merge the repowise server into ``.vscode/mcp.json`` and return the path.- Only the ``repowise`` entry under ``servers`` is added or refreshed; other- servers and unknown keys are preserved, and user-added per-server keys (an- ``env`` block carrying provider keys) survive re-registration. Raises- ``ValueError`` when an existing file is not strict JSON (VS Code allows- JSONC comments) or is not shaped as expected, so callers can skip the merge- without destroying the file.+ Raises ``ValueError`` when an existing file is not strict JSON (VS Code+ allows JSONC comments) or is not shaped as expected, so callers can skip the+ merge without destroying the file."""- config_path = repo_path / ".vscode" / "mcp.json"- new_entry = {"repowise": generate_vscode_mcp_server_entry(repo_path)}-- if config_path.exists():- existing = json.loads(config_path.read_text(encoding="utf-8"))- if not isinstance(existing, dict):- raise ValueError("mcp.json must contain a JSON object")- servers = existing.get("servers", {})- if not isinstance(servers, dict):- raise ValueError("mcp.json 'servers' must be a JSON object")- servers = dict(servers)- _merge_server_entries(servers, new_entry)- existing["servers"] = servers- merged = existing- else:- config_path.parent.mkdir(parents=True, exist_ok=True)- merged = {"servers": new_entry}-- config_path.write_text(json.dumps(merged, indent=2) + "\n", encoding="utf-8")- return config_path+ from repowise.cli.agent_targets.targets import vscode++ return vscode.write_mcp_config(repo_path)def save_vscode_extensions_config(repo_path: Path) -> Path:"""Recommend the repowise extension in ``.vscode/extensions.json``.- Appends ``repowise-dev.repowise`` to ``recommendations`` if absent,- preserving existing entries and unknown keys; running twice changes- nothing. Raises ``ValueError`` when an existing file is not strict JSON- (VS Code allows JSONC comments) or is not shaped as expected, so callers- can skip the merge without destroying the file.+ Raises ``ValueError`` on a file that is not strict JSON, for the same reason+ as :func:`save_vscode_mcp_config`."""- config_path = repo_path / ".vscode" / "extensions.json"- extension_id = "repowise-dev.repowise"-- if config_path.exists():- existing = json.loads(config_path.read_text(encoding="utf-8"))- if not isinstance(existing, dict):- raise ValueError("extensions.json must contain a JSON object")- recommendations = existing.get("recommendations", [])- if not isinstance(recommendations, list):- raise ValueError("extensions.json 'recommendations' must be a JSON array")- recommendations = list(recommendations)- if extension_id not in recommendations:- recommendations.append(extension_id)- existing["recommendations"] = recommendations- merged = existing- else:- config_path.parent.mkdir(parents=True, exist_ok=True)- merged = {"recommendations": [extension_id]}-- config_path.write_text(json.dumps(merged, indent=2) + "\n", encoding="utf-8")- return config_path+ from repowise.cli.agent_targets.targets import vscode--def merge_mcp_entry(config_path: Path, new_entry: dict) -> bool:- """Merge *new_entry* into the mcpServers block of *config_path*.-- Creates the file if it doesn't exist. Returns True on success.-- The per-server merge is deep: generated fields overwrite stored ones, but- user-added keys such as an ``env`` block are preserved across- re-registration (see :func:`_merge_server_entries`).- """- try:- if config_path.exists():- existing = load_existing_config(config_path)- else:- config_path.parent.mkdir(parents=True, exist_ok=True)- existing = {}-- servers = dict(existing.get("mcpServers", {}))- _merge_server_entries(servers, new_entry)- existing["mcpServers"] = servers- config_path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")- return True- except OSError:- return False---def load_existing_config(config_path: Path) -> dict:- """Load an existing JSON config without silently replacing bad content."""- try:- existing = json.loads(config_path.read_text(encoding="utf-8"))- except json.JSONDecodeError as exc:- raise click.ClickException(- f"Cannot update {config_path}: existing file is not valid JSON. "- "Fix or remove it and retry; no changes were written."- ) from exc- except OSError as exc:- raise click.ClickException(- f"Cannot update {config_path}: existing file could not be read. "- "Fix the file permissions and retry; no changes were written."- ) from exc- if not isinstance(existing, dict):- raise click.ClickException(- f"Cannot update {config_path}: existing file must contain a JSON object. "- "Fix or remove it and retry; no changes were written."- )- return existing+ return vscode.write_extensions_config(repo_path)+#: Re-exported for the Codex hooks writer's own use and for callers that used+#: to reach it through this module.def _is_repowise_hook(hook: dict) -> bool:- cmd = hook.get("command", "")- return "repowise-augment" in cmd or "repowise augment" in cmd+ from repowise.cli.agent_targets.targets.codex import _is_augment_hook++ return _is_augment_hook(hook)def _has_repowise_hook_for_matcher(hook_list: list, matcher: object) -> bool:"""Check if a repowise augment hook is registered for a matcher group."""-- for entry in hook_list:- if entry.get("matcher") != matcher:- continue- for hook in entry.get("hooks", []):- if _is_repowise_hook(hook):- return True- return False+ from repowise.cli.agent_targets.targets.codex import _has_augment_hook_for_matcher++ return _has_augment_hook_for_matcher(hook_list, matcher)+++__all__ = [+ "enable_codex_hooks_feature",+ "generate_codex_hooks_config",+ "generate_codex_mcp_server_config",+ "generate_mcp_config",+ "generate_vscode_mcp_server_entry",+ "is_codex_cli_installed",+ "is_codex_logged_in",+ "load_existing_config",+ "merge_mcp_entry",+ "resolve_codex_executable",+ "resolve_repowise_command",+ "save_codex_hooks_config",+ "save_codex_mcp_config",+ "save_mcp_config",+ "save_root_mcp_config",+ "save_vscode_extensions_config",+ "save_vscode_mcp_config",+]diff --git a/tests/unit/cli/data/agent_target_baseline.json b/tests/unit/cli/data/agent_target_baseline.jsonnew file mode 100644index 000000000..2a9962828--- /dev/null+++ b/tests/unit/cli/data/agent_target_baseline.json@@ -0,0 +1,50 @@+{+ "project": {+ ".codex/config.toml": {+ "content": "[mcp_servers.repowise]\ncommand = \"repowise\"\nargs = [\"mcp\"]\ncwd = \"{REPO}\"\nstartup_timeout_sec = 20\n\n[features]\nhooks = true\n",+ "newlines": "platform"+ },+ ".codex/hooks.json": {+ "content": "{\n \"hooks\": {\n \"SessionStart\": [\n {\n \"matcher\": \"startup|resume|clear\",\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"repowise-augment --client codex\",\n \"timeout\": 30,\n \"statusMessage\": \"Loading repowise context...\"\n }\n ]\n }\n ],\n \"UserPromptSubmit\": [\n {\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"repowise-augment --client codex\",\n \"timeout\": 30,\n \"statusMessage\": \"Loading repowise context...\"\n }\n ]\n }\n ],\n \"PostToolUse\": [\n {\n \"matcher\": \"Bash|shell_command\",\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"repowise-augment --client codex\",\n \"timeout\": 30,\n \"statusMessage\": \"Checking repowise freshness...\"\n }\n ]\n },\n {\n \"matcher\": \"apply_patch|Edit|Write\",\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"repowise-augment --client codex\",\n \"timeout\": 30,\n \"statusMessage\": \"Checking repowise freshness...\"\n }\n ]\n }\n ]\n }\n}\n",+ "newlines": "platform"+ },+ ".mcp.json": {+ "content": "{\n \"mcpServers\": {\n \"repowise\": {\n \"command\": \"repowise\",\n \"args\": [\n \"mcp\",\n \"{REPO}\",\n \"--transport\",\n \"stdio\"\n ],\n \"description\": \"repowise: codebase intelligence \\u2014 docs, graph, git signals, dead code, decisions\"\n }\n }\n}\n",+ "newlines": "platform"+ },+ ".repowise/config.yaml": {+ "content": "editor_files:\n claude_md: false\n agents_md: false\n",+ "newlines": "platform"+ },+ ".repowise/mcp.json": {+ "content": "{\n \"mcpServers\": {\n \"repowise\": {\n \"command\": \"repowise\",\n \"args\": [\n \"mcp\",\n \"{REPO}\",\n \"--transport\",\n \"stdio\"\n ],\n \"description\": \"repowise: codebase intelligence \\u2014 docs, graph, git signals, dead code, decisions\"\n }\n }\n}\n",+ "newlines": "platform"+ },+ ".vscode/extensions.json": {+ "content": "{\n \"recommendations\": [\n \"repowise-dev.repowise\"\n ]\n}\n",+ "newlines": "platform"+ },+ ".vscode/mcp.json": {+ "content": "{\n \"servers\": {\n \"repowise\": {\n \"type\": \"stdio\",\n \"command\": \"repowise\",\n \"args\": [\n \"mcp\",\n \"{REPO}\",\n \"--transport\",\n \"stdio\"\n ],\n \"description\": \"repowise: codebase intelligence \\u2014 docs, graph, git signals, dead code, decisions\"\n }\n }\n}\n",+ "newlines": "platform"+ },+ "AGENTS.md": {+ "content": "# AGENTS.md\n\n<!-- Add your project instructions above or below the Repowise section. Repowise only updates the managed section between markers. -->\n\n<!-- REPOWISE_DISTILL:START \u2014 Do not edit below this line. Auto-generated by Repowise. -->\n### Output Distillation\n\n- Prefer `repowise distill <cmd>` for noisy commands \u2014 test runs, builds, `git status`/`log`/`diff`, searches, file listings. It runs the command unchanged (exit code preserved) and prints a compact, errors-first rendering; every error line survives.\n- Output may contain a marker like `[repowise#a1b2c3d4e5f6: 230 lines omitted (~6.1k tokens); restore: repowise expand a1b2c3d4e5f6]`. The omitted content is fully preserved \u2014 run `repowise expand <ref>` to retrieve it, or `repowise expand <ref> -q <regex>` for just the matching lines.\n- Never re-run a command to see omitted output; expand the marker instead.\n- For structure-level questions about a large indexed file (\"what's in here\", \"which function handles X\"), `get_context([\"path\"], include=[\"skeleton\"])` returns the file with bodies elided \u2014 every signature plus the bodies of the most central symbols \u2014 at a fraction of the cost of a full Read.\n<!-- REPOWISE_DISTILL:END -->\n",+ "newlines": "lf"+ }+ },+ "user": {+ ".claude/settings.json": {+ "content": "{\n \"mcpServers\": {\n \"repowise\": {\n \"command\": \"/pinned/bin/repowise\",\n \"args\": [\n \"mcp\",\n \"{REPO}\",\n \"--transport\",\n \"stdio\"\n ],\n \"description\": \"repowise: codebase intelligence \\u2014 docs, graph, git signals, dead code, decisions\"\n }\n },\n \"hooks\": {\n \"PostToolUse\": [\n {\n \"matcher\": \"Grep|Glob|Read|Edit|Write|mcp__.*[Rr]epowise.*__.*\",\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"if command -v repowise-augment >/dev/null 2>&1; then exec repowise-augment; fi\",\n \"timeout\": 10,\n \"statusMessage\": \"Checking codebase context...\"\n }\n ]\n }\n ],\n \"SessionStart\": [\n {\n \"matcher\": \"startup|resume|clear\",\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"if command -v repowise-augment >/dev/null 2>&1; then exec repowise-augment; fi\",\n \"timeout\": 10,\n \"statusMessage\": \"Loading repowise context...\"\n }\n ]\n }\n ],\n \"PostToolUseFailure\": [\n {\n \"matcher\": \"Read|Edit|Write|Grep|Glob|NotebookEdit\",\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"if command -v repowise-augment >/dev/null 2>&1; then exec repowise-augment; fi\",\n \"timeout\": 10,\n \"statusMessage\": \"Checking codebase context...\"\n }\n ]\n }\n ],\n \"PreToolUse\": [\n {\n \"matcher\": \"Bash|PowerShell\",\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"repowise-rewrite\",\n \"timeout\": 5,\n \"statusMessage\": \"Distilling command output...\"\n }\n ]\n }\n ]\n },\n \"env\": {\n \"ENABLE_TOOL_SEARCH\": \"true\"\n },\n \"permissions\": {\n \"allow\": [\n \"Bash(repowise distill:*)\",\n \"PowerShell(repowise distill:*)\"\n ]\n }\n}\n",+ "newlines": "platform"+ },+ ".codex/hooks.json": {+ "content": "{\n \"hooks\": {\n \"PreToolUse\": [\n {\n \"matcher\": \"Bash|shell_command\",\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"repowise-rewrite --agent codex\",\n \"timeout\": 5,\n \"statusMessage\": \"Distilling command output...\"\n }\n ]\n }\n ]\n }\n}\n",+ "newlines": "platform"+ },+ "AppData/Roaming/Claude/claude_desktop_config.json": {+ "content": "{\n \"mcpServers\": {\n \"repowise\": {\n \"command\": \"/pinned/bin/repowise\",\n \"args\": [\n \"mcp\",\n \"{REPO}\",\n \"--transport\",\n \"stdio\"\n ],\n \"description\": \"repowise: codebase intelligence \\u2014 docs, graph, git signals, dead code, decisions\"\n }\n }\n}\n",+ "newlines": "platform"+ }+ }+}diff --git a/tests/unit/cli/test_agent_target_baseline.py b/tests/unit/cli/test_agent_target_baseline.pynew file mode 100644index 000000000..1b67d1880--- /dev/null+++ b/tests/unit/cli/test_agent_target_baseline.py@@ -0,0 +1,341 @@+"""Byte-level baseline of everything the three shipped integrations write.++This is the acceptance oracle for the ``agent_targets`` seam. Claude Code,+Codex and VS Code are about to be reimplemented on a common descriptor, and the+only way to know a rewrite of that size changed nothing is to pin the bytes+first and diff against them afterwards. **A one-byte diff is a bug, not a+rounding error.**++What it captures: every config file the three integrations write, in both+``project`` and ``user`` scope, under a redirected home. That is the surface+the seam replaces. It deliberately does *not* cover the generated instruction+files (``.claude/CLAUDE.md``, ``AGENTS.md`` bodies) — those come out of+``core.generation.editor_files``, which Phase 1 leaves untouched, and+generating them needs an indexed database. The two markdown generators are+stubbed so the surrounding decision logic still runs and still persists its+config opt-outs, which *are* captured.++Two sources of nondeterminism are pinned rather than tolerated:++* ``resolve_repowise_command()`` returns the absolute path of whichever install+ is running, so it is patched to a fixed sentinel.+* The temp repo and home roots differ per run, so every spelling of them that+ reaches a file (native separators, forward slashes, and the JSON-escaped+ native form) is substituted for a placeholder before comparison.++Line endings are compared as a *writer discipline* rather than as literal+bytes, because they are a platform property: ``Path.write_text`` translates to+``os.linesep`` while the marker-block writers pass ``newline="\\n"``+explicitly. Recording which of the two a file got makes the golden portable+across Windows and POSIX while still failing if the rewrite switches a file+from one writer to the other.++Regenerate with ``REPOWISE_UPDATE_AGENT_BASELINE=1 pytest+tests/unit/cli/test_agent_target_baseline.py``. Regenerating is an explicit,+reviewable act: if a diff shows up in the golden during the seam work and it+was not intended, that is the bug this file exists to catch.+"""++from __future__ import annotations++import json+import os+import sys+from pathlib import Path++import pytest+from rich.console import Console++GOLDEN_PATH = Path(__file__).parent / "data" / "agent_target_baseline.json"++#: Stand-in for the absolute console-script path a per-user registration pins.+PINNED_COMMAND = "/pinned/bin/repowise"++_REPO_PLACEHOLDER = "{REPO}"+_HOME_PLACEHOLDER = "{HOME}"++_UPDATE_ENV = "REPOWISE_UPDATE_AGENT_BASELINE"+++def _silent_console() -> Console:+ from io import StringIO++ return Console(file=StringIO(), force_terminal=False)+++def _path_spellings(root: Path) -> list[str]:+ """Every spelling of *root* that can reach a written file.++ ``generate_mcp_config`` forward-slashes its repo path, the Codex TOML+ serializer JSON-encodes the native form (so a Windows separator arrives+ doubled), and plain interpolation gives the native form. Longest first so a+ substitution never leaves a fragment of a longer spelling behind.+ """+ native = str(root)+ spellings = {native, native.replace("\\", "/"), json.dumps(native)[1:-1]}+ return sorted(spellings, key=len, reverse=True)+++def _normalize(text: str, repo: Path, home: Path) -> str:+ for spelling in _path_spellings(repo):+ text = text.replace(spelling, _REPO_PLACEHOLDER)+ for spelling in _path_spellings(home):+ text = text.replace(spelling, _HOME_PLACEHOLDER)+ return text+++def _newline_style(raw: bytes) -> str:+ """Which writer produced this file: platform-translating, or explicit LF.++ ``lf`` means every newline is bare — what ``newline="\\n"`` guarantees on+ every platform. ``platform`` means they match ``os.linesep``, i.e. the+ default ``write_text`` translation. ``mixed`` is a real answer and a+ failure worth seeing.+ """+ if b"\n" not in raw:+ return "none"+ crlf = raw.count(b"\r\n")+ lf = raw.count(b"\n")+ if crlf == 0:+ return "lf"+ if crlf == lf:+ # Every newline is CRLF. That is the platform translation on Windows+ # and something nothing here produces on POSIX, so on POSIX it is drift.+ return "platform" if os.linesep == "\r\n" else "mixed"+ return "mixed"+++def _expected_newlines(recorded: str) -> str:+ """The style a *recorded* discipline should produce on this platform."""+ if recorded == "platform":+ return "platform" if os.linesep == "\r\n" else "lf"+ return recorded+++def _capture(root: Path, repo: Path, home: Path) -> dict[str, dict[str, str]]:+ """Snapshot every file under *root* as {relative posix path: entry}."""+ captured: dict[str, dict[str, str]] = {}+ for path in sorted(root.rglob("*")):+ if not path.is_file():+ continue+ raw = path.read_bytes()+ rel = path.relative_to(root).as_posix()+ try:+ text = raw.decode("utf-8")+ except UnicodeDecodeError: # pragma: no cover - nothing binary is written+ pytest.fail(f"{rel} is not UTF-8; the baseline assumes text config")+ captured[rel] = {+ "content": _normalize(text.replace("\r\n", "\n"), repo, home),+ "newlines": _newline_style(raw),+ }+ return captured+++def _write_everything(repo: Path, console) -> None:+ """Drive every write path of the three integrations, in init's own order.++ Project scope goes through the public orchestrators rather than the+ per-editor savers, because the orchestrators are the contract the seam has+ to preserve. The opt-in distill surfaces are driven directly: they are part+ of the Claude Code and Codex integrations but are reached through+ ``repowise hook rewrite`` rather than through ``init``.+ """+ from repowise.cli.editor_integrations.claude_config import (+ add_claude_code_distill_allow_rules,+ install_claude_code_rewrite_hook,+ )+ from repowise.cli.editor_integrations.codex_config import (+ install_agents_md_distill_section,+ install_codex_rewrite_hook,+ )+ from repowise.cli.editor_setup import (+ EditorSetupOptions,+ register_editor_clients,+ write_editor_project_files,+ )++ options = EditorSetupOptions(+ # CLAUDE.md generation needs an index; the opt-out branch still+ # persists to config.yaml, which the baseline does cover.+ disabled_project_files=frozenset({"claude_md"}),+ project_file_overrides={"agents_md": False},+ # Codex is off by default; the baseline wants its files.+ integration_overrides={"codex": True},+ )++ write_editor_project_files(console, repo, options=options)+ register_editor_clients(console, repo)++ install_claude_code_rewrite_hook()+ add_claude_code_distill_allow_rules()+ install_codex_rewrite_hook()+ install_agents_md_distill_section(repo)+++def baseline_env(tmp_path_factory, monkeypatch):+ """A redirected home plus a repo outside it, with the machine pinned out.++ ``HOMEDRIVE``/``HOMEPATH`` are redirected alongside ``USERPROFILE`` per the+ standing trap: both Claude config paths derive from ``Path.home()``, so one+ redirect has to cover Claude Code and Claude Desktop. The repo lives+ *outside* the fake home so the two placeholder substitutions cannot nest.+ """+ home = tmp_path_factory.mktemp("baseline_home")+ repo = tmp_path_factory.mktemp("baseline_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)++ # Claude Desktop only registers when its config directory already exists,+ # so create it — the baseline should cover that write where the platform+ # supports it at all.+ from repowise.cli.editor_integrations import claude_config++ desktop = claude_config._claude_desktop_config_path()+ if desktop is not None:+ desktop.parent.mkdir(parents=True, exist_ok=True)++ monkeypatch.setattr(+ claude_config, "resolve_repowise_command", lambda script="repowise": PINNED_COMMAND+ )++ # Instruction-file bodies are out of scope (see the module docstring); the+ # decision logic around them is not.+ from repowise.cli.editor_integrations import claude as claude_integration+ from repowise.cli.editor_integrations import codex as codex_integration++ async def _noop(_repo_path):+ return None++ monkeypatch.setattr(claude_integration, "_write_claude_md_async", _noop)+ monkeypatch.setattr(codex_integration, "_write_agents_md_async", _noop)++ # Probing the real Codex CLI shells out and varies by machine; it steers+ # console text only, never bytes on disk.+ from repowise.cli import mcp_config++ monkeypatch.setattr(mcp_config, "is_codex_cli_installed", lambda: True)+ monkeypatch.setattr(mcp_config, "is_codex_logged_in", lambda: True)++ return home, repo+++def test_integration_writes_match_baseline(baseline_env) -> None:+ """The three integrations write exactly the bytes the golden records.++ The gate for the ``agent_targets`` rewrite. When this fails, the rewrite+ changed a file the old code produced — read the diff before touching the+ golden.+ """+ home, repo = baseline_env+ _write_everything(repo, _silent_console())++ actual = {+ "project": _capture(repo, repo, home),+ "user": _capture(home, repo, home),+ }++ if os.environ.get(_UPDATE_ENV):+ GOLDEN_PATH.parent.mkdir(parents=True, exist_ok=True)+ GOLDEN_PATH.write_text(+ json.dumps(actual, indent=2, sort_keys=True) + "\n",+ encoding="utf-8",+ newline="\n",+ )+ pytest.skip(f"baseline regenerated at {GOLDEN_PATH}")++ expected = json.loads(GOLDEN_PATH.read_text(encoding="utf-8"))++ # Claude Desktop has no config location on Linux, so its file is absent+ # there by design rather than by regression.+ from repowise.cli.editor_integrations import claude_config++ if claude_config._claude_desktop_config_path() is None:+ expected["user"] = {+ rel: entry+ for rel, entry in expected["user"].items()+ if "claude_desktop_config.json" not in rel+ }++ for scope in ("project", "user"):+ assert sorted(actual[scope]) == sorted(expected[scope]), (+ f"{scope} scope wrote a different set of files than the baseline"+ )+ for rel in sorted(expected[scope]):+ assert actual[scope][rel]["content"] == expected[scope][rel]["content"], (+ f"{scope}/{rel} content diverged from the baseline"+ )+ assert actual[scope][rel]["newlines"] == _expected_newlines(+ expected[scope][rel]["newlines"]+ ), 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.+ """+ home, repo = baseline_env+ console = _silent_console()++ def _run() -> dict[str, dict[str, dict[str, str]]]:+ _write_everything(repo, console)+ return {"project": _capture(repo, repo, home), "user": _capture(home, repo, home)}++ 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 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"+ )++[email protected](sys.platform != "win32", reason="separator handling is Windows-specific")+def test_normalization_covers_windows_separator_spellings() -> None:+ """Both Windows spellings of a path normalize, including the escaped one.++ The Codex TOML serializer routes its ``cwd`` through ``json.dumps``, so the+ repo path lands in the file with doubled backslashes. A normalizer that+ only knew the native and forward-slash forms would leave that one spelling+ machine-specific, and the golden would fail on every machine but the one+ that wrote it.+ """+ repo = Path(r"C:\tmp\repo")+ home = Path(r"C:\tmp\home")+ text = r"C:\tmp\repo C:/tmp/repo C:\\tmp\\repo"+ assert _normalize(text, repo, home) == f"{_REPO_PLACEHOLDER} " * 2 + _REPO_PLACEHOLDERdiff --git a/tests/unit/cli/test_agent_targets.py b/tests/unit/cli/test_agent_targets.pynew file mode 100644index 000000000..31c2855bb--- /dev/null+++ b/tests/unit/cli/test_agent_targets.py@@ -0,0 +1,467 @@+"""Contract tests for the agent-target seam.++Parameterized across the whole registry rather than written per agent, so a+fourth target inherits the contract by being registered. That is the property+the seam exists to provide, and a per-target test file would quietly not have+it.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from repowise.cli.agent_targets import formats # noqa: F401 (package import smoke)+from repowise.cli.agent_targets.formats import json_merge, marker_block+from repowise.cli.agent_targets.registry import (+ detect_all,+ get_target,+ list_target_ids,+ resolve_target_flag,+ tier_of,+)+from repowise.cli.agent_targets.types import (+ AgentTarget,+ FileAction,+ Scope,+ Tier,+ WriteResult,+ capabilities_of,+ derive_tier,+)++ALL_IDS = list_target_ids()+++# ---------------------------------------------------------------------------+# Registry+# ---------------------------------------------------------------------------+++def test_registry_exposes_the_three_shipped_targets() -> None:+ assert ALL_IDS == ["claude-code", "codex", "vscode"]++[email protected]("target_id", ALL_IDS)+def test_every_registered_target_satisfies_the_protocol(target_id: str) -> None:+ target = get_target(target_id)+ assert isinstance(target, AgentTarget)+ assert target.id == target_id+++def test_unknown_id_resolves_to_none_rather_than_raising() -> None:+ assert get_target("nope") is None+++def test_resolve_target_flag_handles_the_four_forms(tmp_path: Path) -> None:+ assert resolve_target_flag("none", tmp_path) == []+ assert [t.id for t in resolve_target_flag("all", tmp_path)] == ALL_IDS+ assert [t.id for t in resolve_target_flag("codex,vscode", tmp_path)] == ["codex", "vscode"]+ # Whitespace and case are user input, not a different intent.+ assert [t.id for t in resolve_target_flag(" CODEX , vscode ", tmp_path)] == [+ "codex",+ "vscode",+ ]+++def test_unknown_target_flag_names_the_known_ids(tmp_path: Path) -> None:+ """A typo must not silently resolve to nothing and report success."""+ with pytest.raises(ValueError) as excinfo:+ resolve_target_flag("cursor,codex", tmp_path)+ message = str(excinfo.value)+ assert "cursor" in message+ for target_id in ALL_IDS:+ assert target_id in message+ assert "auto" in message+++def test_auto_falls_back_to_claude_code_when_nothing_is_detected(tmp_path: Path) -> None:+ """Least surprise: an empty machine still gets the agent almost everyone has."""+ resolved = resolve_target_flag("auto", tmp_path)+ assert [t.id for t in resolved] == ["claude-code"]+++def test_detect_all_returns_a_list_per_target(tmp_path: Path) -> None:+ """Detection reports registrations, never a boolean.++ 'Configured: yes' cannot express 'configured twice', which is the state the+ method axis exists to surface.+ """+ detected = detect_all(tmp_path)+ assert set(detected) == set(ALL_IDS)+ assert all(isinstance(v, list) for v in detected.values())+++def test_detect_all_survives_a_target_whose_probe_raises(tmp_path: Path, monkeypatch) -> None:+ """One broken probe must not take the whole listing down."""+ from repowise.cli.agent_targets.targets import vscode as vscode_target++ def _boom(_repo_path=None):+ raise RuntimeError("probe exploded")++ monkeypatch.setattr(vscode_target.TARGET, "detect", _boom)+ detected = detect_all(tmp_path)+ assert detected["vscode"] == []+ assert set(detected) == set(ALL_IDS)+++# ---------------------------------------------------------------------------+# Tier derivation+# ---------------------------------------------------------------------------+++def test_tiers_are_derived_from_the_adapters_a_target_names() -> None:+ """Full requires both deep surfaces; VS Code has neither, so it cannot claim it."""+ assert tier_of("claude-code") is Tier.FULL+ assert tier_of("codex") is Tier.FULL+ assert tier_of("vscode") is Tier.GOOD+++def test_a_target_cannot_reach_full_without_a_session_adapter() -> None:+ """The structural guarantee: dropping the transcript adapter demotes the tier.++ This is the whole reason the tier is derived rather than declared. If it+ were a field, a target could keep saying Full after losing the surface, and+ the README badge generated from it would repeat the claim.+ """++ class _HooksOnly:+ id = "hooks-only"+ display_name = "Hooks Only"+ docs_url = None+ hook_adapter = "claude-code"+ session_adapter = None+ methods = get_target("claude-code").methods++ assert derive_tier(_HooksOnly()) is Tier.GOOD+++def test_a_target_that_writes_nothing_is_paste_config() -> None:+ class _Snippet:+ id = "snippet"+ display_name = "Snippet Only"+ docs_url = None+ hook_adapter = None+ session_adapter = None+ methods = ()++ assert derive_tier(_Snippet()) is Tier.PASTE_CONFIG+++def test_capabilities_union_across_install_methods() -> None:+ from repowise.cli.agent_targets.types import Capability++ caps = capabilities_of(get_target("claude-code"))+ # Commands come only from the plugin method, instructions only from direct.+ assert Capability.COMMANDS in caps+ assert Capability.INSTRUCTIONS in caps+++# ---------------------------------------------------------------------------+# Target contract+# ---------------------------------------------------------------------------++[email protected]("target_id", ALL_IDS)+def test_print_config_touches_no_filesystem(target_id: str, tmp_path: Path) -> None:+ """The Paste-config tier depends on this being true, so assert it."""+ target = get_target(target_id)+ repo = tmp_path / "repo"+ repo.mkdir()++ snippet = target.print_config(Scope.PROJECT, repo_path=repo)++ assert snippet.strip()+ assert list(repo.iterdir()) == []++[email protected]("target_id", ALL_IDS)+def test_describe_paths_predicts_what_install_writes(target_id: str, tmp_path: Path) -> None:+ """A path a target claims it would write must be one install actually writes.++ Predicting a superset is allowed (Codex's AGENTS.md is written by a separate+ opt-in surface); predicting something install never touches is not, because+ that is what a dry-run would show the user.+ """+ target = get_target(target_id)+ repo = tmp_path / "repo"+ repo.mkdir()+ if not target.supports_scope(Scope.PROJECT):+ pytest.skip(f"{target_id} has no project scope")++ predicted = {Path(p) for p in target.describe_paths(Scope.PROJECT, repo_path=repo)}+ result = target.install(Scope.PROJECT, repo_path=repo)+ written = {f.path for f in result.files}++ assert written <= predicted, f"{target_id} wrote a path it did not describe"++[email protected]("target_id", ALL_IDS)+def test_uninstall_is_safe_when_nothing_was_installed(target_id: str, tmp_path: Path) -> None:+ """Every method must be callable against a machine that never ran install."""+ target = get_target(target_id)+ repo = tmp_path / "repo"+ repo.mkdir()+ for scope in (Scope.USER, Scope.PROJECT):+ result = target.uninstall(scope, repo_path=repo)+ assert isinstance(result, WriteResult)+ assert all(+ f.action in (FileAction.NOT_FOUND, FileAction.KEPT, FileAction.REMOVED)+ for f in result.files+ )++[email protected]("target_id", ALL_IDS)+def test_doctor_offers_exactly_one_fix_command(target_id: str) -> None:+ """One command, never a list — a diagnostic that offers three has not diagnosed."""+ report = get_target(target_id).doctor()+ assert report.target_id == target_id+ if report.status.value != "ok":+ assert report.fix_command+ assert isinstance(report.fix_command, str)+++def test_vscode_declines_user_scope() -> None:+ """Scope support is a real answer, not a shrug: VS Code has no user-level file."""+ assert get_target("vscode").supports_scope(Scope.PROJECT)+ assert not get_target("vscode").supports_scope(Scope.USER)+++def test_claude_code_reports_plugin_and_direct_separately(tmp_path: Path, monkeypatch) -> None:+ """The duplicate-registration case the method axis exists for.++ A machine carrying the plugin *and* a direct install has repowise wired+ twice. Collapsing that to a boolean is what let it stay invisible.+ """+ from repowise.cli.agent_targets.targets import claude_code as target_mod++ manifest = tmp_path / "installed_plugins.json"+ manifest.write_text(+ json.dumps(+ {+ "version": 2,+ "plugins": {+ target_mod.PLUGIN_KEY: [+ {"scope": "user", "version": "0.16.0", "installPath": "/cache/repowise"}+ ]+ },+ }+ ),+ encoding="utf-8",+ )+ settings = tmp_path / "settings.json"+ settings.write_text(json.dumps({"mcpServers": {"repowise": {"command": "repowise"}}}))++ monkeypatch.setattr(target_mod, "plugin_manifest_path", lambda: manifest)+ monkeypatch.setattr(target_mod, "settings_path", lambda: settings)+ monkeypatch.setattr(target_mod, "desktop_config_path", lambda: None)++ registrations = target_mod.detect()+ methods = [r.method for r in registrations]++ assert "plugin" in methods and "direct" in methods+ plugin = next(r for r in registrations if r.method == "plugin")+ assert plugin.version == "0.16.0"+++def test_plugin_detection_degrades_to_absent_on_a_broken_manifest(+ tmp_path: Path, monkeypatch+) -> None:+ """An unreadable manifest is not evidence of a registration."""+ from repowise.cli.agent_targets.targets import claude_code as target_mod++ manifest = tmp_path / "installed_plugins.json"+ manifest.write_text("{not json", encoding="utf-8")+ monkeypatch.setattr(target_mod, "plugin_manifest_path", lambda: manifest)++ assert target_mod._plugin_installs() == []+++# ---------------------------------------------------------------------------+# WriteResult+# ---------------------------------------------------------------------------+++def test_write_result_reports_change_only_for_real_movement() -> None:+ result = WriteResult()+ result.record(Path("a.json"), FileAction.UNCHANGED)+ result.record(Path("b.json"), FileAction.NOT_FOUND)+ assert not result.changed++ result.record(Path("c.json"), FileAction.CREATED)+ assert result.changed+++def test_write_result_json_projection_is_built_at_the_construction_site() -> None:+ """The projection carries the enum's value, ready for ``--format json``."""+ result = WriteResult()+ result.record(Path("a.json"), FileAction.CREATED)+ result.note("Restart the editor.")++ payload = result.as_dict()+ assert payload["files"][0]["action"] == "created"+ assert payload["notes"] == ["Restart the editor."]+++# ---------------------------------------------------------------------------+# Format helpers+# ---------------------------------------------------------------------------+++def test_json_deep_equal_ignores_key_order_but_not_content() -> None:+ assert json_merge.json_deep_equal({"a": 1, "b": [1, {"c": 2}]}, {"b": [1, {"c": 2}], "a": 1})+ assert not json_merge.json_deep_equal({"a": 1}, {"a": 1, "b": 2})+ assert not json_merge.json_deep_equal([1, 2], [2, 1])+++def test_json_deep_equal_does_not_confuse_bool_and_int() -> None:+ """``True == 1`` in Python; for an idempotency check it must not."""+ assert not json_merge.json_deep_equal({"hooks": True}, {"hooks": 1})+++def test_json_deep_equal_separates_int_from_float() -> None:+ """The contract is "the bytes would not move", and 1 and 1.0 serialize differently.++ Treating them as equal would report ``unchanged`` for a write that does+ change the file.+ """+ assert not json_merge.json_deep_equal({"timeout": 1}, {"timeout": 1.0})+ assert json.dumps(1) != json.dumps(1.0)+++def test_atomic_write_leaves_no_temp_file_behind(tmp_path: Path) -> None:+ target = tmp_path / "nested" / "config.json"+ target.parent.mkdir()+ json_merge.atomic_write_text(target, '{"a": 1}\n')++ assert target.read_text(encoding="utf-8").startswith("{")+ assert [p.name for p in target.parent.iterdir()] == ["config.json"]+++def test_atomic_write_does_not_create_parent_directories(tmp_path: Path) -> None:+ """A missing parent stays a loud failure rather than a silently-created tree.++ ``.mcp.json`` is the one writer that never created its parent, so a+ nonexistent repo path raised. Creating it here would turn that into a+ success that writes config into a directory nobody asked for.+ """+ missing = tmp_path / "no-such-repo" / "config.json"+ with pytest.raises(OSError):+ json_merge.atomic_write_text(missing, "{}\n")+ assert not missing.parent.exists()+++def test_atomic_write_preserves_an_existing_files_permissions(tmp_path: Path) -> None:+ """A temp-file rename installs the temp's umask-derived mode; restore the original."""+ target = tmp_path / "config.json"+ target.write_text("{}\n", encoding="utf-8")+ before = target.stat().st_mode++ json_merge.atomic_write_text(target, '{"a": 1}\n')++ assert target.stat().st_mode == before+++def test_atomic_write_preserves_the_original_when_the_write_fails(+ tmp_path: Path, monkeypatch+) -> None:+ """A crash mid-write must not truncate the file it was replacing."""+ target = tmp_path / "config.json"+ target.write_text("original", encoding="utf-8")++ def _explode(*_args, **_kwargs):+ raise OSError("disk full")++ monkeypatch.setattr("os.replace", _explode)+ with pytest.raises(OSError):+ json_merge.atomic_write_text(target, "replacement")++ assert target.read_text(encoding="utf-8") == "original"+ assert [p.name for p in tmp_path.iterdir()] == ["config.json"]+++def test_marker_block_round_trips_user_content_byte_for_byte(tmp_path: Path) -> None:+ """The property the managed block lives or dies by."""+ doc = tmp_path / "AGENTS.md"+ original = "# My notes\n\nSomething I wrote.\n"+ doc.write_text(original, encoding="utf-8", newline="\n")++ marker_block.upsert(doc, "\nmanaged\n", "<!--S-->", "<!--E-->")+ assert "Something I wrote." in doc.read_text(encoding="utf-8")++ marker_block.remove(doc, "<!--S-->", "<!--E-->")+ assert doc.read_text(encoding="utf-8") == original+++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+++def test_marker_block_normalizes_a_crlf_file_whose_block_is_current(tmp_path: Path) -> None:+ """A CRLF file with an already-current block still gets normalized to LF.++ The subtle one. ``read_text`` collapses CRLF to LF in memory, so comparing+ decoded text says "identical" while the bytes on disk are not — and the+ upsert would return early, leaving the file CRLF where an unconditional+ write normalized it. That is a whole-file diff on any Windows checkout with+ ``core.autocrlf=true`` running ``repowise update``.+ """+ doc = tmp_path / "AGENTS.md"+ body = "\nmanaged\n"+ lf_content = f"# Notes\r\n\r\n<!--S-->{body}<!--E-->\n".replace("\n", "\r\n")+ doc.write_bytes(lf_content.encode("utf-8"))+ assert b"\r\n" in doc.read_bytes()++ changed = marker_block.upsert(doc, body, "<!--S-->", "<!--E-->")++ assert changed is True+ 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+++def test_marker_block_uses_lf_regardless_of_platform(tmp_path: Path) -> None:+ """These files are committed; their line endings must not depend on the OS."""+ doc = tmp_path / "AGENTS.md"+ marker_block.upsert(doc, "\nbody\n", "<!--S-->", "<!--E-->")+ assert b"\r\n" not in doc.read_bytes()+++def test_marker_block_deletes_a_file_it_created(tmp_path: Path) -> None:+ """Install then uninstall round-trips to 'no file', not to a stub."""+ doc = tmp_path / "AGENTS.md"+ placeholder = "# AGENTS.md\n"+ doc.write_text(placeholder, encoding="utf-8", newline="\n")+ marker_block.upsert(doc, "\nbody\n", "<!--S-->", "<!--E-->")++ marker_block.remove(doc, "<!--S-->", "<!--E-->", delete_if_only=placeholder)+ assert not doc.exists()+++def test_marker_block_names_the_malformed_states(tmp_path: Path) -> None:+ """Orphan and duplicate markers mean a user edited inside the block.++ Both are reported rather than silently repaired: guessing at the repair for+ an orphan marker is how you eat the paragraph that follows it.+ """+ doc = tmp_path / "AGENTS.md"++ assert marker_block.inspect(doc, "<!--S-->", "<!--E-->").state.value == "absent-file"++ doc.write_text("nothing here\n", encoding="utf-8")+ assert marker_block.inspect(doc, "<!--S-->", "<!--E-->").state.value == "absent"++ doc.write_text("<!--S-->body<!--E-->\n", encoding="utf-8")+ inspection = marker_block.inspect(doc, "<!--S-->", "<!--E-->")+ assert inspection.state.value == "present"+ assert inspection.body == "body"++ doc.write_text("<!--S-->a<!--E-->\n<!--S-->b<!--E-->\n", encoding="utf-8")+ assert marker_block.inspect(doc, "<!--S-->", "<!--E-->").state.value == "duplicated"++ doc.write_text("<!--S-->dangling\n", encoding="utf-8")+ assert marker_block.inspect(doc, "<!--S-->", "<!--E-->").state.value == "orphaned"