Skip to content

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

feat: one shared source for both plugin hosts, Codex slash commands, and drift reporting (#1450)

Raghav Chamadiya867122cad359
diff --git a/docs/agent/CODEX.md b/docs/agent/CODEX.md
index 1e54258f6..b1c8a7b7e 100644
--- a/docs/agent/CODEX.md
+++ b/docs/agent/CODEX.md
@@ -110,7 +110,19 @@ codex
/plugins
```
-The plugin bundles Repowise MCP, lifecycle hooks, and Codex-neutral skills for exploration, pre-modification checks, architectural decisions, and dead-code cleanup. It does not add Claude-style slash commands. Plugin-bundled hooks are opt-in in current Codex releases; enable them with `[features] plugin_hooks = true` if you want hooks loaded from an installed plugin.
+The plugin bundles Repowise MCP, lifecycle hooks, and Codex-neutral skills for exploration, pre-modification checks, architectural decisions, and dead-code cleanup. Plugin-bundled hooks are opt-in in current Codex releases; enable them with `[features] plugin_hooks = true` if you want hooks loaded from an installed plugin.
+
+## Slash commands
+
+The plugin does not carry these, and cannot: a Codex plugin manifest has no slot for commands. Codex reads slash commands from `~/.codex/prompts/`, which is global and which only the CLI can write, so Repowise installs them there:
+
+```bash
+repowise agents add --target=codex
+```
+
+That writes one `repowise-*.md` per command, and `repowise agents remove --target=codex` takes them back out. Invoke them as `/prompts:repowise-risk`, `/prompts:repowise-ask` and so on. They are rendered from the same `plugins/shared/` source as the Claude Code plugin's commands, so the two hosts cannot drift.
+
+Note this is the mirror image of Claude Code, where the commands come from the plugin and `repowise init` never writes any.
## AGENTS.md
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-ask.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-ask.md
new file mode 100644
index 000000000..90a2ea769
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-ask.md
@@ -0,0 +1,43 @@
+---
+description: Ask a codebase question and get a cited, synthesised answer with a confidence rating (costs an LLM call).
+---
+
+# Repowise Ask
+
+Answer a question about this codebase with citations. This is the same
+synthesis the `get_answer` MCP tool performs: hybrid retrieval followed by an
+LLM answer over what it found. Unlike `/prompts:repowise-search`, this **costs an LLM
+call** — use it when the user wants an answer, not a hit list.
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `/prompts:repowise-init` first." Stop.
+2. Resolve the question from `$ARGUMENTS`. If empty, ask: "What do you want to know about this codebase?"
+3. Run the command and present the answer, confidence, and retrieval quality.
+ Prefer citing the paths the answer names. Do not invent citations.
+
+## Choosing the invocation
+
+- Question only → `repowise ask "<question>"`
+- Restrict retrieval to a subtree → `repowise ask "<question>" --scope packages/cli/`
+- Machine-readable → `repowise ask "<question>" --format json`
+- Raw MCP payload (including dropped blocks) → `repowise ask "<question>" --full`
+
+```
+repowise ask "how does the retry backoff work?"
+repowise ask "where is the session cookie set?" --format json
+repowise ask "how is width resolved?" --scope packages/cli/
+repowise ask "why is auth split across two modules?" --full
+```
+
+Shared targeting flags (`--path`, `--repo`, `--no-workspace`) work the same as
+the other tool-adapter commands.
+
+## How to present the result
+
+- `confidence: high` is content-grounded — cite it directly.
+- `medium` / `low` — say so, and follow any `best_guesses` / `fallback_targets`
+ into `/prompts:repowise-context` or `get_context` rather than inventing detail.
+- If a `note` warns that numbers may be synthesised, surface that caveat.
+- Prefer this over `/prompts:repowise-search` when the user asked a *question*. Prefer
+ search when they want a list of matching pages / symbols.
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-context.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-context.md
new file mode 100644
index 000000000..940c37923
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-context.md
@@ -0,0 +1,49 @@
+---
+description: Triage card for files, modules, or symbols — layer, hotspot, fix history, freshness (relationships, not source bytes).
+---
+
+# Repowise Context
+
+Pull a triage card for one or more files, modules, or symbols. This is the CLI
+adapter over `get_context`: title, summary, architectural layer, hotspot /
+bug-fix history, doc freshness, and optional relationship blocks. Relationships
+and risk signals — **not** source bytes by default.
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `/prompts:repowise-init` first." Stop.
+2. Resolve targets from `$ARGUMENTS`. If empty, ask which file / module /
+ `path::Symbol` to inspect.
+3. Run `repowise context` and present each card: layer, stale bit, hotspot,
+ summary. Call out fix history when present.
+
+## Choosing the invocation
+
+TARGETS are file paths, module paths, or `path/to/file.py::Symbol` ids. Batch
+them in one call.
+
+- Default triage → `repowise context <targets…>`
+- Opt-in blocks (repeatable) → `--include callers|callees|ownership|metrics|decisions|skeleton|…`
+- Richer card → `repowise context <targets…> --no-compact`
+- Machine-readable / raw payload → `--format json` / `--full`
+
+```
+repowise context src/api/routes.py src/api/auth.py
+repowise context src/api/routes.py::login --include callers --include metrics
+repowise context src/api/routes.py --include skeleton
+```
+
+`--include skeleton` adds the body-elided, line-verified file shape. For the
+exact function body, prefer `/prompts:repowise-symbol` (or `get_symbol`) with a
+`symbol_id` from the card.
+
+Shared targeting flags (`--path`, `--repo`, `--no-workspace`) work the same as
+the other tool-adapter commands.
+
+## Notes
+
+- Prefer this before opening many files with Read — one call batches cards.
+- A target the index cannot resolve returns an `error` card; report that
+ plainly instead of inventing structure.
+- For a synthesised Q&A answer, use `/prompts:repowise-ask`. For "why is it shaped
+ this way", use `/prompts:repowise-why`.
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-coverage.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-coverage.md
new file mode 100644
index 000000000..815aeb619
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-coverage.md
@@ -0,0 +1,42 @@
+---
+description: Ingest or inspect test-coverage reports — LCOV, Cobertura/Clover, or coverage.py .coverage (builds the per-test map when contexts are present).
+---
+
+# Repowise Coverage
+
+Ingest coverage so untested-hotspot markers light up in `repowise health` and
+so `repowise impacted-tests` can map a diff to the tests that exercise it.
+No LLM — pure report ingestion into the local index.
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `/prompts:repowise-init` first." Stop.
+2. Decide the mode from `$ARGUMENTS` (see below), run the command, and present
+ a short summary (files covered, line/branch %, whether a per-test map was
+ built). Don't dump raw JSON unless asked.
+
+## Modes
+
+Default / "status" — show what is already ingested:
+```
+repowise coverage status
+```
+
+Handle `$ARGUMENTS`:
+- "status" / "show" → `repowise coverage status`
+- A report path (`coverage.lcov`, `lcov.info`, `coverage.xml`, `.coverage`, …)
+ → `repowise coverage add <path>`
+- "add" with no path → `repowise coverage add` (auto-discover common report paths)
+- Multiple paths → `repowise coverage add <a> <b>` (merged; hit wins)
+
+Useful flags on `add`: `--verbose` for ingestion debug logs; `--path <dir>`
+to point at a different repo.
+
+## Notes
+
+- `coverage add` always stores per-file line/branch coverage.
+- The **per-test map** (needed by `/prompts:repowise-impacted-tests`) is built only
+ when the report carries per-test contexts — e.g. a coverage.py `.coverage`
+ written with `coverage run --contexts=test`, or a per-test lcov. Reports
+ without contexts ingest aggregates only; say so plainly.
+- After ingesting, suggest `repowise health` so untested-hotspot markers update.
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-dead-code.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-dead-code.md
new file mode 100644
index 000000000..53be62a58
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-dead-code.md
@@ -0,0 +1,42 @@
+---
+description: Report unreachable files, unused exports, and zombie packages, tiered by confidence.
+---
+
+# Repowise Dead Code
+
+Find dead code through graph reachability + git context. No LLM — works in
+index-only mode. Findings are tiered by confidence; only `safe_to_delete` ones
+should be proposed for removal.
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `/prompts:repowise-init` first." Stop.
+2. Run `repowise dead-code` (with any filters from `$ARGUMENTS`).
+3. Present findings grouped by confidence. Mark which are `safe_to_delete`. For
+ lower-confidence ones, frame them as "candidates to investigate," not deletions.
+
+## Filters from `$ARGUMENTS`
+
+- A path → `repowise dead-code <path>`
+- "safe" → `--safe-only` (only safe_to_delete findings)
+- "files" → `--kind unreachable_file`
+- "exports" → `--kind unused_export`
+- "packages" / "zombie" → `--kind zombie_package`
+- "strict" → `--min-confidence 0.7` (default is 0.4)
+
+Other flags: `--format json`, `--include-internals` (aggressive, private-symbol
+scan; higher false-positive rate), `--include-zombie-packages` /
+`--no-include-zombie-packages`, `--no-unreachable`, `--no-unused-exports`,
+`--repo <alias>` / `--no-workspace`.
+
+For per-directory or per-owner rollups, use the `get_dead_code` MCP tool with
+`group_by="directory"` or `group_by="owner"` (these are tool params, not CLI flags).
+
+## Before suggesting any deletion
+
+- Confirm with the user; show the name, confidence, and why it looks dead.
+- Recently-touched "dead" code is more likely a false positive — flag it.
+- Dynamically-loaded patterns (plugins, handlers, adapters, framework routes)
+ can look unused but aren't. Repowise filters the common cases; edge cases remain.
+- Double-check blast radius with `get_risk(targets=[...])` before removing files
+ or exported symbols.
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-decision.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-decision.md
new file mode 100644
index 000000000..22f282099
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-decision.md
@@ -0,0 +1,39 @@
+---
+description: Work with architectural decisions — list, inspect health, add, or confirm auto-proposed decisions.
+---
+
+# Repowise Decisions
+
+Repowise captures architectural decisions (the *why* behind the code) from eight
+sources and tracks them for staleness and conflicts. This command drives the
+`repowise decision` group.
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `/prompts:repowise-init` first." Stop.
+2. Map `$ARGUMENTS` to a subcommand, run it, and present the result clearly.
+
+## Subcommands
+
+- **list** (default) — `repowise decision list`
+ - "stale" → `--stale-only`; "proposed" → `--proposed`
+ - "active" / "deprecated" / "superseded" → `--status <value>`
+ - filter by origin → `--source <value>`
+- **health** — `repowise decision health` — stale decisions, conflicts, and
+ ungoverned hotspots (high-churn files with no recorded decision). Good first call.
+- **show** — `repowise decision show <id>` — full record: rationale, evidence
+ spans, status, and the supersession lineage.
+- **add** — `repowise decision add` — guided interactive capture (~90s). Use when
+ the user makes a decision during the session and wants it recorded.
+- **confirm** — `repowise decision confirm` — review decisions auto-proposed from
+ git history and accept or reject them.
+- **deprecate / dismiss** — `repowise decision deprecate <id>` (optionally
+ `--superseded-by <id>`) or `repowise decision dismiss <id>`.
+
+## Notes
+
+- For *querying* why code looks the way it does mid-task, prefer the `get_why`
+ MCP tool (the `architectural-decisions` skill) — it returns lineage and an
+ alignment score. This command is for *managing* the decision records themselves.
+- `add` and `confirm` are interactive; tell the user when a step needs their input.
+- If unsure of an exact subcommand or flag, run `repowise decision --help`.
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-doctor.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-doctor.md
new file mode 100644
index 000000000..14e4640af
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-doctor.md
@@ -0,0 +1,32 @@
+---
+description: Diagnose the Repowise setup — install, API keys, index/store drift — and optionally repair it.
+---
+
+# Repowise Doctor
+
+Check that Repowise is healthy: the install, configured provider / API keys, and
+whether the index and stores are consistent with the repo.
+
+## Steps
+
+1. Run `repowise doctor`.
+2. Summarize what passed and what didn't. For each problem, give the concrete fix
+ (set an env var, run `/prompts:repowise-update`, re-run `/prompts:repowise-init`, etc.).
+
+## Flags from `$ARGUMENTS`
+
+- "repair" / "fix" → `repowise doctor --repair` (attempts to fix detected
+ mismatches). Tell the user what it changed.
+- "workspace" → `repowise doctor --workspace` (check every repo in the workspace);
+ `--no-workspace` to force single-repo.
+- a path → `repowise doctor <path>`
+
+## Common findings
+
+- **repowise not installed / not on PATH** → suggest `pip install repowise` (or
+ `python -m pip install repowise` on Windows), then `/prompts:repowise-init`.
+- **No API key for the configured provider** → show the exact `export` for the
+ provider in `.repowise/config.yaml`. This is not fatal for `init`, which falls
+ back to the template wiki. Only an explicitly named `--provider` errors out.
+- **Index drift (HEAD ahead of last sync)** → run `/prompts:repowise-update`.
+- **Missing embeddings / store drift** → `/prompts:repowise-reindex`.
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-export.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-export.md
new file mode 100644
index 000000000..f31964a96
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-export.md
@@ -0,0 +1,59 @@
+---
+description: Export the wiki (or architecture model) to markdown, HTML, JSON, or Structurizr DSL.
+---
+
+# Repowise Export
+
+Export indexed wiki pages to files, or emit a Structurizr DSL architecture
+model. Use this when the user wants a shareable dump, a static site, a JSON
+archive, or a C4/Structurizr model — not when they need an interactive Q&A
+answer (`/prompts:repowise-ask`).
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `/prompts:repowise-init` first." Stop.
+2. Resolve format and output from `$ARGUMENTS` (see below).
+3. Run `repowise export` and report where files were written (page count /
+ output path). Do not invent page content.
+
+## Choosing the invocation
+
+Default — markdown under `.repowise/export`:
+```
+repowise export
+```
+
+Handle `$ARGUMENTS`:
+- "html" / "site" → `repowise export --format html`
+- "json" → `repowise export --format json`
+- "json full" / "archive" → `repowise export --format json --full`
+ (`--full` keeps tombstones and adds decisions / dead code / hotspots)
+- "structurizr" / "c4" / "dsl" → `repowise export --format structurizr`
+- "structurizr standalone" → `repowise export --format structurizr --standalone`
+- "structurizr components" → add `--components`
+- "to <dir>" / "-o <dir>" → pass `--output <dir>`
+ (for structurizr, a path ending in `.dsl` names the file itself)
+- A repo path → `repowise export <path> …`
+
+```
+repowise export
+repowise export --format html -o ./site
+repowise export --format json --full
+repowise export --format structurizr --standalone --components
+repowise export --format structurizr -o architecture.dsl
+```
+
+## Structurizr notes
+
+- Default structurizr output is a **model fragment** to include from your own
+ `workspace.dsl`. Pass `--standalone` for a complete workspace with default
+ views.
+- `--force` overwrites an output file even if Repowise did not write it
+ (`--standalone` often targets `workspace.dsl`).
+- `--no-externals` leaves third-party dependencies out of the model.
+
+## Notes
+
+- Markdown / HTML / JSON write a directory of pages; structurizr writes DSL.
+- Never fabricate export contents. If the command reports no pages, say so and
+ suggest `/prompts:repowise-init`.
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-health.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-health.md
new file mode 100644
index 000000000..e0b1b1d95
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-health.md
@@ -0,0 +1,39 @@
+---
+description: Show Repowise code-health — KPIs, lowest-scoring files, refactoring targets, trends, or per-file markers.
+---
+
+# Repowise Health
+
+Report the code-health layer: a deterministic 1–10 score per file from markers
+(complexity, deep nesting, brain methods, cohesion, duplication, untested
+hotspots, and more). No LLM — works even in index-only mode.
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `/prompts:repowise-init` first." Stop.
+2. Decide the mode from `$ARGUMENTS` (see below), run the command, and present a
+ readable summary — score(s), the top marker findings, and what they mean.
+ Don't dump the raw table verbatim.
+
+## Modes
+
+Default (no args) — dashboard KPIs + lowest-scoring files:
+```
+repowise health
+```
+
+Handle `$ARGUMENTS`:
+- A file or directory path → `repowise health <path>` (or `--file <path>` for a single file)
+- "refactoring" / "targets" → `repowise health --refactoring-targets` (ranked by impact/effort)
+- "trend" / "trends" → `repowise health --trend` (last snapshots + declining / predicted-decline alerts)
+- "module <name>" → `repowise health --module <name>`
+- a coverage file (e.g. `cov.lcov`, `coverage.xml`, `.coverage`) → `repowise coverage add <file>` to ingest it (folds into health markers, and builds the per-test map when the report has contexts), then `repowise health`
+
+Other flags: `--format json` for machine-readable output, `-v, --verbose` for
+pipeline debug logs, `--repo <alias>` / `--no-workspace` in workspace mode.
+
+## Notes
+
+- A file that is both low-health **and** a churn hotspot is the highest-priority
+ cleanup — cross-reference with `/prompts:repowise-risk` or `get_risk`.
+- If everything scores high, say so plainly rather than inventing concerns.
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-impacted-tests.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-impacted-tests.md
new file mode 100644
index 000000000..7e2740bd7
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-impacted-tests.md
@@ -0,0 +1,45 @@
+---
+description: Print the tests whose coverage intersects a change's changed lines — for a commit, base..head range, or staged diff.
+---
+
+# Repowise Impacted Tests
+
+Map a change to the tests that actually exercise its changed lines, using the
+per-test coverage map from `repowise coverage add`. No LLM, no network —
+an index lookup. Useful as a pre-merge / CI gate ("run these 40, not all 4,000").
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `/prompts:repowise-init` first." Stop.
+2. Resolve the target from `$ARGUMENTS`, run `repowise impacted-tests`, and
+ present the test ids. Be honest about gaps (see Notes).
+
+## Choosing the revspec
+
+- No args → `repowise impacted-tests` (staged changes; same as `--staged`)
+- A commit SHA → `repowise impacted-tests <sha>`
+- A range / PR / branch → `repowise impacted-tests <base>..<head>`
+ (e.g. `repowise impacted-tests main..HEAD`)
+- "staged" → `repowise impacted-tests --staged`
+
+Useful flags:
+- `--format list` — test ids one per line (pipe to `xargs pytest`)
+- `--format json` — full report
+- `--path <dir>` — point at a different repo
+
+```
+repowise impacted-tests main..HEAD --format list | xargs pytest
+```
+
+## Notes
+
+- Requires a per-test map from `repowise coverage add` on a report with
+ contexts. If none is ingested, the command prompts to run
+ `/prompts:repowise-coverage` / `repowise coverage add` — it does **not** invent an
+ empty "no tests needed" result.
+- A changed file with no coverage rows may get a filename-pattern **guess**
+ labelled as a guess — never present guesses as coverage-backed.
+- A brand-new file with neither coverage nor a paired test is "unknown, run
+ the full suite".
+- For a whole-change defect-risk score, use `/prompts:repowise-risk`. For per-file
+ blast radius / `tests_to_run`, use the `get_risk` MCP tool.
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-init.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-init.md
new file mode 100644
index 000000000..802758b56
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-init.md
@@ -0,0 +1,228 @@
+---
+description: Set up Repowise for this codebase. Installs if needed, asks about your preferences, and runs the indexing.
+---
+
+# Repowise Init
+
+You are helping the user set up Repowise for their codebase. Follow this sequence precisely.
+
+## Step 1: Check if repowise is installed
+
+Run: `repowise --version`
+
+If the command fails or is not found, ask the user:
+
+"Repowise isn't installed yet. I can install it for you. Which do you prefer?"
+- `pip install repowise` (recommended, includes every LLM provider SDK)
+- "I'll install it myself"
+
+If they want you to install it, run `pip install repowise`. If that fails, try `python -m pip install repowise`.
+
+After install, verify with `repowise --version`.
+
+If repowise IS found, print the version and move to Step 2.
+
+## Step 2: Check if this repo is already indexed
+
+Check if `.repowise/` directory exists in the project root.
+
+If it exists, tell the user:
+"This repo is already indexed by Repowise. Run `/prompts:repowise-status` to check health, or `/prompts:repowise-update` to refresh. If you want to re-index from scratch, I can run `repowise init --force`."
+
+Then stop — do not continue to Step 3 unless the user asks to re-index.
+
+If `.repowise/` doesn't exist, move to Step 3.
+
+## Step 3: Offer the mode, but do not block on it
+
+Repowise needs **no API key at all**. Never make a key a precondition for
+setting it up, and never stop and wait if you cannot get an answer.
+
+Tell the user:
+
+"Repowise indexes your repo and writes a complete wiki with no API key. I'll run
+`repowise init --yes` unless you'd rather pick:
+
+1. **Default (no key)** — full index plus a wiki rendered from your code's structure. Free, fast, nothing to configure.
+2. **Model-written wiki** — everything above, but an LLM writes the wiki prose instead of rendering it from structure, which also enables decision mining. Needs a provider key (Anthropic, OpenAI, Gemini, or Ollama locally). You can start keyless and upgrade any page later with `repowise generate`.
+3. **Show me the flags.**"
+
+If the user does not answer, or you are running unattended, take option 1.
+
+### If Default (no key):
+
+Skip provider selection entirely. Construct:
+```
+repowise init --no-prose --yes
+```
+
+Jump to Step 3b.
+
+### If Full mode:
+
+Move to Step 3b, then Step 4.
+
+### If "show me flags":
+
+Print the full flag reference:
+```
+repowise init [PATH]
+
+Core flags:
+ --provider NAME LLM provider: anthropic, openai, gemini, ollama, litellm
+ --model NAME Model identifier override
+ --prose / --no-prose Write the subsystem (concept) pages as model prose
+ (--prose, needs a key), or render the whole wiki from
+ structure with no model and no spend (--no-prose).
+ Every other page is structural either way.
+ Default: prose when a key is available.
+ --mode fast Quick first pass on very large repos: no wiki at all.
+
+Embeddings:
+ --embedder NAME Embedding provider: gemini, openai, mock (default: auto-detect)
+
+Cost control:
+ --concurrency N Max parallel LLM calls (default: 10)
+ --test-run Limit to top 10 files by PageRank for quick validation
+
+Exclusions:
+ -x, --exclude PATTERN Gitignore-style exclude patterns. Repeatable.
+ Example: -x 'vendor/**' -x 'generated/'
+ --skip-tests Skip test files
+ --skip-infra Skip infrastructure files (Dockerfile, Makefile, Terraform, shell)
+
+Git:
+ --commit-limit N Max commits to analyze per file (default: 500, max: 10000)
+ --follow-renames Track files across renames (slower but more accurate history)
+
+Editor integration:
+ --editor-setup / Register (default) or skip the global MCP server entry
+ --no-editor-setup and Claude Code hooks in ~/.claude/settings.json and
+ Claude Desktop's config, plus the distill rewrite-hook
+ offer. There is one 'repowise' MCP entry per config, so
+ a later init from another repo repoints it. See Step 3b.
+
+Output:
+ --no-claude-md Don't generate/update CLAUDE.md
+ -y, --yes Skip cost confirmation prompt
+ -v, --verbose Show per-phase internals plus debug logs (quiet by default)
+
+Recovery:
+ --resume Resume a previously interrupted init
+ --force Re-index from scratch, overwriting existing .repowise/
+
+Dry run:
+ --dry-run Show generation plan and cost estimate without running
+```
+
+Then ask if they want you to construct a command or if they'll handle it.
+
+## Step 3b: Is this repo a keeper?
+
+Every path reaches this step. It is about the repo, not the provider.
+
+By default `init` registers repowise as the user's global MCP server, in
+`~/.claude/settings.json` and Claude Desktop's config. There is **one**
+`repowise` key in each file, so this repo replaces whatever repo is registered
+now. That is the right default for the repo someone actually works in, and the
+wrong one for a checkout that is about to disappear.
+
+Add `--no-editor-setup` when either of these holds:
+
+- the path is a scratch clone, a fixture, a sample, a vendored copy, or sits
+ under a temp directory
+- it is a linked git worktree rather than the main checkout. Check with
+ `git rev-parse --git-common-dir`: a value other than `.git` means a worktree
+
+Also add it if the user says they don't want their editor or MCP setup touched.
+Do **not** infer that from "just index it" or "don't ask me questions" — those
+are about prompts, not config.
+
+The index, the wiki, and every project-local file are identical either way.
+Only the machine-wide registration is skipped, and it can be done later by
+re-running `repowise init` in that repo without the flag.
+
+Whichever you pick, say which in one line so the user can correct you.
+
+If `init` prints "Replacing the existing repowise MCP …", relay it. The global
+entry just moved to this repo, and the user may want it pointed back.
+
+Then continue to Step 4 for the model-written wiki, or Step 5 otherwise.
+
+## Step 4: Provider selection (model-written wiki only)
+
+**Skip this entire step unless the user chose the model-written wiki.** A
+missing key is not a blocker: `init` renders the template wiki and exits 0
+without one. If you cannot find a key, do not stop and do not ask again. Run
+`repowise init --yes` and tell the user their wiki is rendered from structure
+and can be upgraded per-page later with `repowise generate`.
+
+Check which API keys are already set by running:
+```bash
+echo "ANTHROPIC=${ANTHROPIC_API_KEY:+set}" "OPENAI=${OPENAI_API_KEY:+set}" "GEMINI=${GEMINI_API_KEY:+set}${GOOGLE_API_KEY:+set}" "OLLAMA=${OLLAMA_BASE_URL:+set}"
+```
+
+If one or more keys are detected, suggest the detected provider:
+- `ANTHROPIC_API_KEY` set → suggest `--provider anthropic`
+- `OPENAI_API_KEY` set → suggest `--provider openai`
+- `GEMINI_API_KEY` or `GOOGLE_API_KEY` set → suggest `--provider gemini`
+- `OLLAMA_BASE_URL` set → suggest `--provider ollama`
+
+If no key is detected, ask:
+
+"Which LLM provider do you want to use?"
+- **Anthropic** (Claude) — needs `ANTHROPIC_API_KEY`
+- **OpenAI** (GPT-4o or compatible) — needs `OPENAI_API_KEY`
+- **Google Gemini** (recommended for cost efficiency) — needs `GEMINI_API_KEY` or `GOOGLE_API_KEY`
+- **Ollama** (fully local, no API key, slower) — needs Ollama running locally
+- **LiteLLM** (100+ providers) — needs LiteLLM config
+
+Then ask them to set the required environment variable. Show the exact export command:
+```bash
+export ANTHROPIC_API_KEY="sk-ant-..."
+```
+
+Every provider SDK (anthropic, openai, google-genai, litellm) ships with `repowise`
+itself, so there is no per-provider package to install. If a provider import fails,
+the install is broken rather than incomplete: reinstall with
+`pip install --force-reinstall repowise` and run `repowise doctor`.
+
+## Step 5: Exclusions
+
+Before running the command, ask:
+
+"Any directories or patterns you want to exclude from indexing? Common ones to skip: `vendor/`, `generated/`, large data directories, build artifacts. Your `.gitignore` is already respected automatically. Press Enter to skip."
+
+Add any exclusions as `-x` flags.
+
+## Step 6: Run it
+
+For an unattended or non-interactive run, the canonical command is
+`repowise init --yes`, plus `--no-prose` when you want to guarantee no spend.
+`--yes` suppresses every prompt including the cost gate. You do not need to guard
+against prompts beyond that: init treats an unanswerable question as a signal to
+continue with defaults rather than a reason to fail, and the cost gate declines
+by itself when stdin is not a terminal, keeping the finished index and landing on
+the structural wiki.
+
+Show the user the exact command you're about to run. Ask for confirmation.
+
+Run it. For full mode, note: "This will take a while for the initial indexing. You can Ctrl+C safely — run `/prompts:repowise-init` again and I'll use `--resume` to continue where you left off."
+
+## Step 7: Post-setup
+
+After init completes successfully:
+
+1. Confirm the `.repowise/` directory was created
+2. Run `repowise status` to show the summary
+3. Tell the user:
+ - "Repowise has indexed your codebase. The MCP tools are now active — I can answer questions about your architecture, ownership, dependencies, and more."
+ **Only if you did not pass `--no-editor-setup`.** With that flag nothing was
+ registered, so say instead: "The index is built. I did not register it as
+ your global MCP server (this looked like a temporary checkout). The
+ repowise plugin's tools still work here; to make this the repo the MCP
+ server points at, re-run `repowise init` without `--no-editor-setup`."
+ - "Try asking me something like 'how does the auth module work?' or 'what depends on utils.py?'"
+ - "Run `/prompts:repowise-status` anytime to check the health of your index."
+ - "Run `/prompts:repowise-update` after making code changes to keep the wiki in sync."
+4. If CLAUDE.md was generated (default): "I've also generated a CLAUDE.md with codebase context that I'll read on every session."
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-reindex.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-reindex.md
new file mode 100644
index 000000000..829f30169
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-reindex.md
@@ -0,0 +1,33 @@
+---
+description: Rebuild the Repowise vector store by re-embedding all wiki pages. No LLM calls — only embedding API calls.
+---
+
+# Repowise Reindex
+
+Rebuild the vector store (embeddings) without regenerating documentation.
+
+This is useful when:
+- You switched embedding providers
+- The LanceDB vector data got corrupted
+- You want to refresh search quality after adding new wiki pages
+
+## Steps
+
+1. Check if `.repowise/` exists. If not: "This repo isn't indexed yet. Run `/prompts:repowise-init` first."
+
+2. Run: `repowise reindex`
+
+ This re-embeds all existing wiki pages into LanceDB. No LLM generation calls — only embedding API calls. Fast and cheap.
+
+## Available flags
+
+- `--embedder gemini|openai|auto` — embedding provider (default: auto-detect from env vars)
+- `--batch-size N` — pages per embedding batch (default: 20)
+
+## Requirements
+
+Requires either `GEMINI_API_KEY`/`GOOGLE_API_KEY` or `OPENAI_API_KEY` to be set. The mock embedder is not accepted for reindexing. If neither key is available, ask the user to set one before proceeding.
+
+## Handling $ARGUMENTS
+
+If $ARGUMENTS contains "full" or "from-scratch", confirm with the user: "This will regenerate ALL documentation from scratch, not just re-embed. It will take as long as the initial indexing and cost API tokens. Are you sure?" If yes: `repowise init --force`
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-risk.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-risk.md
new file mode 100644
index 000000000..044cac2d0
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-risk.md
@@ -0,0 +1,36 @@
+---
+description: Score the defect risk of a change — a commit or a base..head range — as a single 0–10 with drivers.
+---
+
+# Repowise Risk
+
+Score a *change* (not a file) for defect risk. Repowise reads the diff shape —
+lines added/deleted, files, directories, subsystems, change entropy, and author
+familiarity — and returns a 0–10 score with an attributable driver breakdown.
+Pure git + learned constants: no LLM, no network. A natural pre-merge / PR gate.
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `/prompts:repowise-init` first." Stop.
+2. Resolve the target from `$ARGUMENTS`, run `repowise risk`, and present the
+ score, level, and top drivers — calling out *why* it's risky (e.g. wide
+ diffusion across subsystems, low author familiarity).
+
+## Choosing the revspec
+
+- No args → `repowise risk` (scores `HEAD`)
+- A commit SHA → `repowise risk <sha>`
+- A range / PR / branch → `repowise risk <base>..<head>` (e.g. `repowise risk main..HEAD`)
+
+Useful flags:
+- `--ext .py,.ts` — only count changes in those file types
+- `-x, --exclude <pattern>` — gitignore-style pattern to drop from the diff (repeatable; also honors a `.riskignore` file)
+- `--format json` — machine-readable score + features + drivers
+- `--path <dir>` — point at a different git repo
+
+## How this differs from the other risk views
+
+- This command = the **whole change** as one number (defect-risk gate).
+- For **per-file** blast radius (what breaks, missing co-changes, missing tests),
+ use the `get_risk` MCP tool / the `change-review` skill.
+- For **per-file health** scores, use `/prompts:repowise-health`.
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-search.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-search.md
new file mode 100644
index 000000000..f2e239d1a
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-search.md
@@ -0,0 +1,45 @@
+---
+description: Search the Repowise wiki using natural language, full-text, or symbol search.
+---
+
+# Repowise Search
+
+Search the codebase wiki.
+
+## Usage
+
+If $ARGUMENTS is empty, ask: "What are you looking for? You can search with natural language like 'how does authentication work' or 'where is rate limiting handled'."
+
+If $ARGUMENTS is provided, run:
+```
+repowise search "$ARGUMENTS"
+```
+
+## Search modes
+
+The default mode is `fulltext` (SQLite FTS5). You can specify a mode:
+
+- `--mode fulltext` — fast keyword search (default)
+- `--mode semantic` — vector similarity search using embeddings. Requires an embedding provider to be configured. If this fails with an error, suggest running `/prompts:repowise-reindex` first.
+- `--mode symbol` — fuzzy match on symbol names (functions, classes, variables)
+
+Other flags:
+- `--limit N` — max results (default: 10)
+
+## Present results
+
+Show results as a clean list with the page title, type, and a brief snippet.
+
+## When search comes up empty
+
+Search needs wiki pages, and every indexed repo has them: a keyless run renders
+the whole wiki from structure. So an empty result is usually not a missing wiki.
+
+- **No pages at all** means the index never finished, or the repo was indexed
+ with `--mode fast`, which is the one mode that writes no wiki. Suggest
+ `repowise init --yes` (no API key needed), or `repowise init --resume` if a
+ previous run was interrupted.
+- **Pages exist but semantic search finds nothing** means the wiki was embedded
+ with the mock embedder, which keeps full-text search working and leaves
+ semantic search to be built later. Suggest `repowise reindex` with an embedder
+ configured. Full-text and symbol search (`--mode symbol`) work regardless.
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-security.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-security.md
new file mode 100644
index 000000000..aa4e19eaa
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-security.md
@@ -0,0 +1,51 @@
+---
+description: Scan for security signals — working-tree scanning already runs during init/update; use --history to walk full git history for leaked secrets.
+---
+
+# Repowise Security
+
+Scan for security signals with the same local pattern registry used during
+`repowise init` / `repowise update`. Working-tree scanning already happens on
+those commands. This slash command is for walking **full git history** to find
+leaked secrets (and optionally risky patterns) that were later removed.
+
+No LLM — pure local scan. Findings persist to `security_findings` and show up
+in the local server security API / UI. Re-runs are idempotent.
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `/prompts:repowise-init` first." Stop.
+2. Decide the mode from `$ARGUMENTS` (see below), run the command, and present
+ a short summary (files scanned, findings stored, by severity / kind). Do not
+ print raw secret values if any appear in output — summarize kinds and paths.
+
+## Modes
+
+Default / no useful args — remind the user that working-tree scanning already
+ran during init/update, then offer history mode:
+```
+repowise security scan
+```
+(Without `--history` this prints a hint and exits — it does **not** re-run the
+working-tree scan.)
+
+Handle `$ARGUMENTS`:
+- "history" / "full" / "scan history" → `repowise security scan --history`
+- "json" with history → `repowise security scan --history --output json`
+- "all" / "all-patterns" with history → `repowise security scan --history --all-patterns`
+- A path → `repowise security scan --history --path <dir>`
+- "since <rev>" / "to <rev>" → pass `--since` / `--to` accordingly
+
+```
+repowise security scan --history
+repowise security scan --history --since v1.0.0 --to HEAD
+repowise security scan --history --all-patterns --output json
+```
+
+## Notes
+
+- Default history mode reports **leaked-secret** patterns only
+ (`hardcoded_password` / `hardcoded_secret`) to avoid noise. Pass
+ `--all-patterns` for code-smell patterns (`eval`, `os.system`, weak hashes, …).
+- Never invent findings. If the scan stores zero findings, say so plainly.
+- For change defect risk (not secret scanning), use `/prompts:repowise-risk`.
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-status.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-status.md
new file mode 100644
index 000000000..1036fb68e
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-status.md
@@ -0,0 +1,23 @@
+---
+description: Check the health of your Repowise index — sync state, page counts, provider, and token usage.
+---
+
+# Repowise Status
+
+Check if Repowise is set up for this project and report its health.
+
+## Steps
+
+1. Check if `.repowise/` directory exists in the project root. If not: "This repo isn't indexed yet. Run `/prompts:repowise-init` to set it up."
+
+2. Run: `repowise status`
+
+3. The command outputs two tables:
+ - **Sync State**: last sync commit, total pages, provider, model, total tokens
+ - **Pages by Type**: breakdown by page type (file_page, module_page, etc.) with counts
+
+4. Present the results to the user in a readable summary.
+
+5. If pages exist but no provider is shown, the wiki is template-rendered. Tell the user: "Your wiki is rendered from structure. Run `repowise generate` to upgrade any subset to model-written prose." If total pages is 0, the run did not finish, so suggest `repowise init --resume`.
+
+6. If the user provides arguments like "$ARGUMENTS", check if they're asking for a specific path and pass it: `repowise status $ARGUMENTS`
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-symbol.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-symbol.md
new file mode 100644
index 000000000..e4dda243f
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-symbol.md
@@ -0,0 +1,47 @@
+---
+description: Read one symbol's body with live-verified line bounds (path::Name, live range, or distill omission ref).
+---
+
+# Repowise Symbol
+
+Read one function, class, or constant with live-verified line bounds. This is
+the CLI adapter over `get_symbol`. Prefer it over a raw file Read when you
+already have a `symbol_id` from `/prompts:repowise-context` or `search_codebase`.
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `/prompts:repowise-init` first." Stop.
+2. Resolve the symbol id from `$ARGUMENTS`. If empty, ask for
+ `path/to/file.py::Name`, a live range (`path:start-end`), or a
+ `repowise#<hex>` omission ref from distill.
+3. Run `repowise symbol` and present the body. Report `verified: true/false`
+ when shown. If the id is ambiguous, show every matching body — do not
+ silently pick one.
+
+## Choosing the invocation
+
+- Named symbol → `repowise symbol "src/api/routes.py::login"`
+- Live range read → `repowise symbol "src/api/routes.py:140-180"`
+- Distill omission ref → `repowise symbol "repowise#a1b2c3d4e5f6"`
+- Extra surrounding lines → `--context-lines N` (0–50)
+- Filter restored omission lines → `--query <regex-or-substring>`
+- Machine-readable / raw payload → `--format json` / `--full`
+
+```
+repowise symbol "src/api/routes.py::login"
+repowise symbol "src/api/routes.py:140-180"
+repowise symbol "repowise#a1b2c3d4e5f6"
+repowise symbol "src/api/routes.py::login" --context-lines 3
+```
+
+A truncated body carries a `continuation` you can pass straight back to
+`repowise symbol`. Shared targeting flags (`--path`, `--repo`,
+`--no-workspace`) match the other tool-adapter commands.
+
+## Notes
+
+- Cheaper and more precise than Read + offset math when you have a
+ `symbol_id`.
+- For triage (layer / hotspot / callers) without bytes, use
+ `/prompts:repowise-context`.
+- Never invent source — if the command errors or returns no body, say so.
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-update.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-update.md
new file mode 100644
index 000000000..d34672df4
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-update.md
@@ -0,0 +1,40 @@
+---
+description: Trigger an incremental Repowise update to sync documentation with recent code changes.
+---
+
+# Repowise Update
+
+Trigger an incremental update of the Repowise index.
+
+## Steps
+
+1. Check if `.repowise/` exists. If not: "This repo isn't indexed yet. Run `/prompts:repowise-init` first."
+
+2. Run: `repowise update`
+
+ This will:
+ - Detect files changed since last sync commit
+ - Update git metadata for changed files
+ - Regenerate affected wiki pages (up to cascade budget of 30)
+ - Decay confidence scores for indirectly affected pages
+ - Update dead code analysis
+ - Update CLAUDE.md if enabled
+
+3. Show the output summary to the user.
+
+## Available flags
+
+- `--provider NAME` — override the LLM provider
+- `--model NAME` — override the model
+- `--since REF` — base git ref to diff from (overrides saved last_sync_commit). Accepts a commit SHA, tag, or branch name.
+- `--cascade-budget N` — max pages to regenerate per run (default: 30)
+- `--dry-run` — show affected pages without regenerating
+- `-v, --verbose` — show the full changed-file list, per-phase internals, and debug logs (the run is quiet by default)
+
+## Handling $ARGUMENTS
+
+If the user provides arguments:
+- "dry-run" or "dry run" → add `--dry-run` flag
+- "force" or "full" → add `--cascade-budget 999` to regenerate all stale pages
+- a git ref like a SHA or tag → add `--since {ref}`
+- a file path → this is not supported by update; suggest `repowise update` which auto-detects changes
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-why.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-why.md
new file mode 100644
index 000000000..b79cecc8f
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-why.md
@@ -0,0 +1,47 @@
+---
+description: Why the code is shaped this way — decisions, rationale, and git archaeology (question, path, or decision-health dashboard).
+---
+
+# Repowise Why
+
+Answer *why* the code looks the way it does: decision records, rationale, and
+git archaeology. This is the CLI adapter over `get_why`. Worth running before a
+refactor or a deliberate divergence from a pattern.
+
+`/prompts:repowise-decision` manages decision records (list / add / confirm). This
+command **queries** why something is shaped a certain way.
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `/prompts:repowise-init` first." Stop.
+2. Map `$ARGUMENTS` to a mode (below), run `repowise why`, and present
+ decisions, alignment, and archaeology. Never invent rationale — if the
+ command falls back to git archaeology, say that plainly.
+
+## Modes
+
+- Question → `repowise why "why is auth using JWT?"`
+- File path (governing decisions + origin story) → `repowise why src/api/auth.py`
+- Target-anchored search → `repowise why "why the retry cap?" --target src/api/client.py`
+ (`--target` is repeatable)
+- No args → `repowise why` (decision-health dashboard: stale / proposed /
+ ungoverned hotspots)
+- Machine-readable / raw payload → `--format json` / `--full`
+
+```
+repowise why "why is auth using JWT?"
+repowise why src/api/auth.py
+repowise why "why the retry cap?" --target src/api/client.py
+repowise why
+```
+
+Shared targeting flags (`--path`, `--repo`, `--no-workspace`) match the other
+tool-adapter commands.
+
+## Notes
+
+- Falls back to git archaeology when a path has no decisions, so it is never
+ empty — call that out so the user knows it is reconstructed, not recorded.
+- For *managing* ADR records (add / confirm / deprecate), use
+ `/prompts:repowise-decision`.
+- Before contradicting an existing decision, surface it to the user first.
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py b/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py
index ac41def33..a32057200 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py
@@ -170,6 +170,78 @@ def _plugin_installs() -> list[dict]:
return [entry for entry in installs if isinstance(entry, dict)]
+#: What the host, not repowise, has to run to update the plugin.
+PLUGIN_UPDATE_COMMAND = "/plugin update repowise@repowise"
+
+
+def plugin_version_skew() -> list[str]:
+ """Installed plugin versions that are not this CLI's version, sorted.
+
+ The plugin is the one artifact the CLI cannot rewrite. ``pip install -U
+ repowise`` upgrades the MCP server and every command, and leaves the plugin's
+ skills and slash commands exactly where they were, so the two drift apart
+ silently, and silence is the worst of the available behaviours. Measured on a
+ real machine: an 0.16.0 plugin installed months earlier against a 0.41.0 CLI,
+ which is why five slash commands the CLI had shipped did not exist in the
+ session.
+
+ Reads the host's own manifest through :func:`_plugin_installs` rather than a
+ second parser. An entry with no ``version`` is skipped: it cannot be compared,
+ and a report the user cannot act on is noise.
+
+ Compared through :func:`release_key`, so ``0.41``, ``0.41.0`` and ``v0.41.0``
+ are one release. Spelling drift is not drift, and reporting it produces a row
+ no command can ever clear.
+ """
+ from repowise.cli import __version__
+
+ current = release_key(__version__)
+ return sorted(
+ {
+ str(entry["version"])
+ for entry in _plugin_installs()
+ if entry.get("version") and not _same_release(str(entry["version"]), current)
+ }
+ )
+
+
+def release_key(version: str) -> tuple[int, ...] | None:
+ """*version* as a comparable tuple, or None when it is not a plain release.
+
+ Deliberately **not** ``core.upgrade.release.parse_release``, which answers a
+ different question. That one exists to decide "is there a newer release", so
+ it drops everything after the first non-digit: it reads ``0.41.0rc1`` and
+ ``0.41.0.post1`` as plain ``0.41.0``, which is right for an upgrade prompt and
+ wrong here: a release candidate is not the release. It also returns None for
+ a leading ``v``, which is the single most likely way for a plugin manifest to
+ spell a version.
+
+ So: strip one leading ``v``, require every remaining part to be digits, and
+ drop trailing zeros so ``0.41`` and ``0.41.0`` land on the same key. Anything
+ with a suffix returns None and falls back to exact string comparison, which
+ reports it, the conservative direction for a version we cannot reason about.
+ """
+ text = version.strip()
+ if text[:1] in ("v", "V"):
+ text = text[1:]
+ parts = text.split(".")
+ if not text or not all(part.isdigit() for part in parts):
+ return None
+ numbers = [int(part) for part in parts]
+ while numbers and numbers[-1] == 0:
+ numbers.pop()
+ return tuple(numbers)
+
+
+def _same_release(version: str, current: tuple[int, ...] | None) -> bool:
+ installed = release_key(version)
+ if installed is None or current is None:
+ from repowise.cli import __version__
+
+ return version == __version__
+ return installed == current
+
+
def _has_repowise_server(config_path: Path) -> bool:
try:
data = json.loads(config_path.read_text(encoding="utf-8"))
@@ -375,8 +447,12 @@ class ClaudeCodeTarget:
),
# `add`, not `refresh`. A file this damaged makes detection
# find nothing, and refresh only touches what it detects — so
- # it would skip this target entirely and report success.
+ # it would skip this target entirely and report success. Which
+ # is exactly why this is not repairable: `--repair` runs that
+ # same refresh, so letting it try buys the skip and the false
+ # success this comment was written about.
fix_command="repowise agents add --target=claude-code",
+ repairable=False,
)
registrations = detect()
@@ -390,7 +466,12 @@ class ClaudeCodeTarget:
issues: list[str] = []
matcher = claude_code_rewrite_hook_matcher()
- if matcher is not None and matcher != SHELL_TOOL_MATCHER:
+ # The one issue here that `agents refresh` genuinely rewrites, so it is
+ # the one that decides `repairable`. Tracked separately from the issue
+ # list because the two questions (what is wrong, and can the repair
+ # pass fix it) have different answers per issue.
+ matcher_stale = matcher is not None and matcher != SHELL_TOOL_MATCHER
+ if matcher_stale:
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 "
@@ -406,13 +487,46 @@ class ClaudeCodeTarget:
"so its MCP tool schemas and hooks are loaded twice."
)
+ # Reported last and fixed first: an out-of-date plugin ships its own
+ # copy of the hooks, so updating it can resolve the matcher issue above
+ # as a side effect, where repairing the matcher does nothing for it.
+ fix_command = "repowise hook rewrite install"
+ skew = plugin_version_skew()
+ if skew:
+ from repowise.cli import __version__
+
+ versions = ", ".join(skew)
+ current = release_key(__version__)
+ # Ahead of the CLI is the same drift running the other way, and
+ # telling someone to update an already-newer plugin is a dead end.
+ # A version we cannot parse falls to the plugin side: an odd string
+ # in a plugin manifest is far likelier than an odd CLI version.
+ ahead = current is not None and all(
+ (key := release_key(version)) is not None and key > current for version in skew
+ )
+ issues.append(
+ f"The Claude Code plugin is at {versions} but this CLI is {__version__}. "
+ "Its skills and slash commands are the plugin's, not the CLI's, and "
+ "`pip install -U repowise` does not touch them."
+ )
+ fix_command = "pip install -U repowise" if ahead else PLUGIN_UPDATE_COMMAND
+
+ # Only the stale matcher. The plugin is host-managed and a duplicate
+ # registration is not something refresh removes, so on either of those
+ # alone `--repair` would write global config for a problem it cannot
+ # touch and then report success. But a *skewed plugin alongside* a stale
+ # matcher must stay repairable: the matcher is still broken, still
+ # rewritable, and the first cut of this let the skew suppress its repair.
+ repairable = matcher_stale
+
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",
+ fix_command=fix_command,
+ repairable=repairable,
)
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py b/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
index 911451677..886f7e379 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
@@ -1,10 +1,18 @@
"""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.
+adapter. It is asymmetric with Claude Code in a way worth stating, because it
+runs the *opposite* way round for each of the two content surfaces.
+
+Skills reach Claude Code and Codex the same way, through the plugin. Slash
+commands do not, and cannot: a Codex plugin manifest has no slot for them. A
+plugin may bundle ``skills/``, ``hooks/``, ``assets/``, ``.mcp.json`` and
+``.app.json``, and that is the whole list. The only surface that yields a Codex
+slash command is ``~/.codex/prompts/``, which is local-only (plugins cannot
+write it), so the CLI installs them from package data, off the same shared
+source that renders the plugin's skills. Claude Code gets its commands from the
+plugin and never from ``init``; Codex gets its commands from ``init``'s
+successor commands and never from the plugin.
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
@@ -53,7 +61,17 @@ METHODS = (
),
InstallMethod(
id="direct",
- provides=frozenset({Capability.MCP, Capability.HOOKS, Capability.INSTRUCTIONS}),
+ provides=frozenset(
+ {
+ Capability.MCP,
+ Capability.HOOKS,
+ Capability.INSTRUCTIONS,
+ # Slash commands come from the direct path, not the plugin.
+ # see the module docstring. This is the mirror image of Claude
+ # Code, where they come from the plugin and not the direct path.
+ Capability.COMMANDS,
+ }
+ ),
managed_by="repowise",
preferred=True,
),
@@ -83,6 +101,15 @@ def instructions_path(repo_path: Path) -> Path:
return repo_path / "AGENTS.md"
+def user_prompts_dir() -> Path:
+ """Where Codex looks for slash commands.
+
+ Global and flat. It is shared with every other tool the user has installed,
+ which is why every file we put there is prefixed ``repowise-``.
+ """
+ return Path.home() / ".codex" / "prompts"
+
+
# ---------------------------------------------------------------------------
# Config generation
# ---------------------------------------------------------------------------
@@ -265,6 +292,140 @@ def write_hooks_config(repo_path: Path) -> tuple[FileWrite, FileWrite]:
return FileWrite(path=hooks_path, action=action), enable_hooks_feature(repo_path)
+#: Namespace for every prompt this target writes. ``~/.codex/prompts`` is a flat
+#: global directory shared with every other tool the user has installed, so the
+#: prefix is what keeps our filenames from colliding with theirs.
+#:
+#: It is **not** an ownership test. A user writing their own Repowise prompt will
+#: reasonably call it ``repowise-my-team-workflow.md``, and treating the prefix as
+#: proof of ownership would delete it on uninstall. Nothing on disk distinguishes
+#: our file from theirs, so the only safe answer is to touch the names we ship and
+#: no others. See :func:`remove_prompts`.
+PROMPT_PREFIX = "repowise-"
+
+
+def bundled_prompts() -> list[tuple[str, str]]:
+ """The Codex prompts shipped in the wheel, as ``(filename, text)``, sorted.
+
+ Package data rather than ``plugins/codex/``: a Codex plugin manifest has no
+ slot for commands (``skills/``, ``hooks/``, ``assets/``, ``.mcp.json`` and
+ ``.app.json``, and nothing else), so the only surface that yields a Codex
+ slash command is this directory, and the CLI is the only thing that can
+ write it. Generated from ``plugins/shared/commands/`` by
+ ``scripts/gen_plugin_content.py``.
+ """
+ from importlib.resources import files
+
+ root = files("repowise.cli.agent_targets").joinpath("_data").joinpath("codex_prompts")
+ prompts = [entry for entry in root.iterdir() if entry.name.endswith(".md")]
+ return sorted(
+ ((entry.name, entry.read_text(encoding="utf-8")) for entry in prompts),
+ key=lambda pair: pair[0],
+ )
+
+
+def _current_prompt_text(path: Path) -> str | None:
+ """The prompt's text with line endings normalised, or None if unusable.
+
+ "Unusable" covers absent, a directory, unreadable, and *not valid UTF-8*.
+ that last one is a ``UnicodeDecodeError``, which is a ``ValueError`` and so
+ escapes an ``OSError`` handler. Nothing wraps ``install``: ``agents add``,
+ ``agents refresh`` and ``doctor --repair`` all call it bare, and the last of
+ those would abort part-way through having already written other agents'
+ configs. Every one of these states means the same thing to the caller: the
+ file we would write is not there, so they collapse to None.
+ """
+ try:
+ return path.read_text(encoding="utf-8").replace("\r\n", "\n")
+ except (OSError, ValueError):
+ return None
+
+
+def write_prompts() -> list[FileWrite]:
+ """Install the slash commands into ``~/.codex/prompts``, one file each.
+
+ LF discipline rather than the platform translation the JSON configs take:
+ these are whole files repowise owns end to end, so pinning the endings makes
+ a re-run on a different machine a no-op instead of a rewrite.
+
+ One unwritable name (a directory sitting at ``repowise-ask.md``, a
+ permission) does not stop the other seventeen. Raising instead would abort
+ ``install`` after the rewrite hook had already been written and recorded,
+ which is the part-way failure this was supposed to remove, just moved. The
+ refusal is reported as :attr:`~..types.FileAction.KEPT`, the value this
+ codebase already uses for "something is there and we did not touch it", and
+ it reaches the user as a row in the ``agents add`` output.
+ """
+ from ..formats.json_merge import atomic_write_text
+
+ directory = user_prompts_dir()
+ writes: list[FileWrite] = []
+ for name, text in bundled_prompts():
+ path = directory / name
+ current = _current_prompt_text(path)
+ if current == text:
+ writes.append(FileWrite(path=path, action=FileAction.UNCHANGED))
+ continue
+ existed = path.exists()
+ try:
+ directory.mkdir(parents=True, exist_ok=True)
+ atomic_write_text(path, text, newline="\n")
+ except OSError:
+ writes.append(FileWrite(path=path, action=FileAction.KEPT))
+ continue
+ writes.append(
+ FileWrite(path=path, action=FileAction.UPDATED if existed else FileAction.CREATED)
+ )
+ return writes
+
+
+def remove_prompts() -> list[FileWrite]:
+ """Delete the prompts repowise ships, and nothing else in that directory.
+
+ Scoped to the **currently bundled names**, deliberately, and not to
+ ``repowise-*.md``. The prefix is a namespace, not a proof of ownership: a
+ user's own ``repowise-my-team-workflow.md`` matches it, and deleting that is
+ unrecoverable.
+
+ The cost of the narrow rule is that a command retired between releases leaves
+ one stale file behind after an uninstall. That is the right way round: losing
+ a file of ours is a wasted kilobyte, losing one of theirs is data loss. That is
+ it is why :data:`PROMPT_PREFIX` documents itself as a namespace.
+ """
+ directory = user_prompts_dir()
+ if not directory.is_dir():
+ return []
+ removed: list[FileWrite] = []
+ for name, _text in bundled_prompts():
+ path = directory / name
+ try:
+ path.unlink()
+ except OSError:
+ continue
+ removed.append(FileWrite(path=path, action=FileAction.REMOVED))
+ return removed
+
+
+def stale_prompts() -> list[str]:
+ """Bundled prompts that are missing from, or out of date in, ``~/.codex/prompts``.
+
+ The drift this branch exists to close, on the one surface the CLI can
+ actually repair. The Claude Code plugin skew is *reported* because repowise
+ cannot rewrite a plugin; these it can rewrite in one command, so staying
+ silent about them would be strictly worse.
+
+ Empty when nothing is installed at all. An agent nobody wired up is not a
+ stale install, and ``doctor`` already has a ``not-installed`` answer for that.
+ """
+ directory = user_prompts_dir()
+ if not directory.is_dir():
+ return []
+ bundled = bundled_prompts()
+ if not any((directory / name).exists() for name, _ in bundled):
+ return []
+ return [name for name, text in bundled if _current_prompt_text(directory / name) != text]
+
+
def _combined(first: FileAction, second: FileAction) -> FileAction:
"""One action describing two writes to the same file.
@@ -385,10 +546,16 @@ class CodexTarget:
hooks_path = user_hooks_path()
before = read_bytes(hooks_path)
installed = install_codex_rewrite_hook()
- if not installed:
+ if installed:
+ result.record(hooks_path, observed_action(before, read_bytes(hooks_path)))
+ else:
result.record(hooks_path, FileAction.NOT_FOUND)
- return result
- result.record(hooks_path, observed_action(before, read_bytes(hooks_path)))
+
+ # Not gated on the hook install: the prompts are a separate surface in a
+ # separate directory, and a Codex build too old for PreToolUse rewriting
+ # still reads slash commands perfectly well.
+ for written in write_prompts():
+ result.record(written.path, written.action)
return result
def uninstall(self, scope: Scope, *, repo_path: Path | None = None) -> WriteResult:
@@ -404,6 +571,8 @@ class CodexTarget:
user_hooks_path(),
FileAction.REMOVED if removed else FileAction.NOT_FOUND,
)
+ for deleted in remove_prompts():
+ result.record(deleted.path, deleted.action)
return result
if repo_path is None:
@@ -427,7 +596,7 @@ class CodexTarget:
def describe_paths(self, scope: Scope, *, repo_path: Path | None = None) -> list[str]:
if scope is Scope.USER:
- return [str(user_hooks_path())]
+ return [str(user_hooks_path()), str(user_prompts_dir())]
repo = repo_path or Path.cwd()
return [
str(project_config_path(repo)),
@@ -457,10 +626,19 @@ class CodexTarget:
status=DoctorStatus.BROKEN,
issues=(f"{hooks} is not valid JSON, so Codex loads none of its hooks.",),
fix_command="repowise hook rewrite install",
+ # Not the refresh pass's job: detection cannot see a registration
+ # inside a file it could not parse, so `--repair` would skip this
+ # target and report success. Same reasoning as Claude Code's.
+ repairable=False,
)
+ # Read before the hook checks so a drifted prompt set is still reported
+ # on a machine whose rewrite hook was never installed. The two surfaces
+ # are wired by different commands and go stale independently.
+ stale = stale_prompts()
+
matcher = codex_rewrite_hook_matcher()
- if matcher is None:
+ if matcher is None and not stale:
return DoctorReport(
target_id=ID,
status=DoctorStatus.NOT_INSTALLED,
@@ -469,12 +647,26 @@ class CodexTarget:
)
issues: list[str] = []
- if matcher != SHELL_TOOL_MATCHER:
+ if stale:
+ issues.append(
+ f"{len(stale)} of the {len(bundled_prompts())} Codex slash commands in "
+ f"{user_prompts_dir()} are missing or out of date, so /prompts:repowise-* "
+ "is running an older version than this CLI."
+ )
+ # Every branch below is gated on the hook actually being installed, and
+ # the absent case is stated rather than dropped. Loosening the early
+ # return above to `and not stale` moved this whole block into reach for a
+ # machine with no hook at all, which silently lost a true fact (the hook
+ # is missing) and made a false one sayable (that it "is registered").
+ matcher_stale = matcher is not None and matcher != SHELL_TOOL_MATCHER
+ if matcher is None:
+ issues.append("The distill rewrite hook is not installed for Codex.")
+ elif matcher_stale:
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:
+ if matcher is not None and 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."
@@ -482,11 +674,23 @@ class CodexTarget:
if not issues:
return DoctorReport(target_id=ID, status=DoctorStatus.OK)
+ # Stale prompts win the fix slot: `agents add` rewrites them *and* the
+ # hook, where `hook rewrite install` only does the hook. It is also the
+ # honest command for the case `refresh` cannot reach: a machine with
+ # prompts but no user-scope hook registration has nothing for refresh to
+ # detect, so `--repair` would skip it and report success.
+ #
+ # `repairable` follows the same rule as Claude Code's: it names what the
+ # refresh pass rewrites, which is the hook, and a stale prompt set must
+ # not suppress that repair the way the first cut of this let it.
return DoctorReport(
target_id=ID,
status=DoctorStatus.STALE,
issues=tuple(issues),
- fix_command="repowise hook rewrite install",
+ fix_command=(
+ "repowise agents add --target=codex" if stale else "repowise hook rewrite install"
+ ),
+ repairable=matcher_stale,
)
diff --git a/packages/cli/src/repowise/cli/agent_targets/types.py b/packages/cli/src/repowise/cli/agent_targets/types.py
index 5336e0d1c..c77dbef14 100644
--- a/packages/cli/src/repowise/cli/agent_targets/types.py
+++ b/packages/cli/src/repowise/cli/agent_targets/types.py
@@ -230,6 +230,15 @@ class DoctorReport:
status: DoctorStatus
issues: tuple[str, ...] = ()
fix_command: str | None = None
+ #: Whether ``doctor --repair`` can actually resolve this, i.e. whether
+ #: *fix_command* is something the repair pass performs. False for anything
+ #: whose fix is a host command or a different repowise command.
+ #:
+ #: Without it, ``--repair`` fires a global refresh for a condition refresh
+ #: provably cannot touch, and then prints its "nothing moved" advice, which
+ #: names two conditions the user does not have and omits the one command
+ #: that works. A repair that cannot help should decline, not try.
+ repairable: bool = True
def as_dict(self) -> dict:
return {
@@ -237,6 +246,7 @@ class DoctorReport:
"status": self.status.value,
"issues": list(self.issues),
"fix_command": self.fix_command,
+ "repairable": self.repairable,
}
diff --git a/packages/cli/src/repowise/cli/augment_hook.py b/packages/cli/src/repowise/cli/augment_hook.py
index eecef110d..4897350e7 100644
--- a/packages/cli/src/repowise/cli/augment_hook.py
+++ b/packages/cli/src/repowise/cli/augment_hook.py
@@ -47,14 +47,16 @@ def main() -> None:
pass
# Best-effort self-heal for users whose only repowise invocation is
- # through this hook. Idempotent: rewrites settings.json only when a
- # legacy `repowise augment` entry is still present, then becomes a
- # no-op on every subsequent fire. Wrapped so a write failure never
- # propagates back to the agent.
+ # through this hook. Wrapped so a write failure never propagates back to
+ # the agent.
+ #
+ # This is the fire that runs once per matched tool call, so it is where the
+ # version stamp pays for itself: it used to parse ~/.claude/settings.json
+ # every time to discover, almost always, that there was nothing to do.
try:
- from repowise.cli.editor_integrations.claude_config import migrate_claude_code_hooks
+ from repowise.cli.self_heal import run_editor_migrations
- migrate_claude_code_hooks()
+ run_editor_migrations()
except BaseException:
pass
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
index cf492753e..8aa4feeb0 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
@@ -766,7 +766,11 @@ def _agent_target_checks() -> tuple[list[DoctorCheck], bool]:
detail = report.issues[0] if report.issues else "wired up"
checks.append(_check(name, True, detail))
continue
- needs_refresh = True
+ # Only conditions the repair pass can actually resolve drive it. A
+ # plugin the CLI cannot rewrite, or a fix that is a different command,
+ # would otherwise buy a global config write that changes nothing and
+ # then report advice for a condition the user does not have.
+ needs_refresh = needs_refresh or report.repairable
detail = "; ".join(report.issues)
if report.fix_command:
detail += f" (run: {report.fix_command})"
diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.py
index 8c4eb02ff..aa1d68914 100644
--- a/packages/cli/src/repowise/cli/main.py
+++ b/packages/cli/src/repowise/cli/main.py
@@ -14,28 +14,17 @@ from repowise.core.registry import cli_registry, register_lazy_command
@click.pass_context
def cli(ctx: click.Context) -> None:
"""repowise -- codebase intelligence for developers and AI."""
- # Self-heal: migrate any legacy `repowise augment` Claude Code hooks
- # to the import-isolated `repowise-augment` console script. Cheap,
- # silent, idempotent — only writes when there is something to change.
+ # Self-heal: repair agent hook entries whose shape a past repowise version
+ # wrote and a later one changed. Silent, idempotent, and now stamped, so it
+ # costs one small read per invocation rather than two JSON config parses.
# Skipped when invoked as the augment subcommand itself (hook hot path) —
- # `augment_hook.main` handles that case.
+ # `augment_hook.main` handles that case. See `self_heal` for why the call
+ # site stays here.
if ctx.invoked_subcommand != "augment":
try:
- from repowise.cli.editor_integrations.claude_config import migrate_claude_code_hooks
+ from repowise.cli.self_heal import run_editor_migrations
- migrate_claude_code_hooks()
- except Exception:
- pass
- # And the same for an installed Codex rewrite hook whose matcher
- # names a tool Codex has since renamed. That one cannot self-heal
- # from its own hook the way the Claude side does — a hook matching
- # nothing never runs — so the CLI is the only place it can happen.
- try:
- from repowise.cli.editor_integrations.codex_config import (
- migrate_codex_rewrite_hook,
- )
-
- migrate_codex_rewrite_hook()
+ run_editor_migrations()
except Exception:
pass
diff --git a/packages/cli/src/repowise/cli/self_heal.py b/packages/cli/src/repowise/cli/self_heal.py
new file mode 100644
index 000000000..1bfcb9196
--- /dev/null
+++ b/packages/cli/src/repowise/cli/self_heal.py
@@ -0,0 +1,156 @@
+"""The once-per-version repair of agent hook config that repowise itself owns.
+
+A hook entry becomes legacy because a *repowise* version changed its shape, so
+console script replaced a subcommand, a matcher widened. So the honest trigger is
+"have the migrations for this version run yet", not "is this an invocation".
+
+Before this, both migrations ran on **every** CLI invocation and on every
+``repowise-augment`` fire, which is once per matched tool call. Each one opens and
+parses a JSON settings file to discover, almost always, that there is nothing to
+do. The stamp turns that into a single small read, and only the version after an
+upgrade pays for the parse.
+
+Two things this is deliberately *not*:
+
+* **Not a config refresh.** There is no ``repowise upgrade`` command to hang one
+ off (``upgrade_flow.py`` upgrades an index, not the CLI), and rewriting a
+ user's global agent config unprompted on the first run after every release is a
+ much larger claim than repairing a shape repowise wrote itself. ``repowise
+ doctor`` reports what is stale; ``repowise agents refresh`` rewrites it when
+ asked.
+* **Not moved off ``main.py``.** A Codex rewrite hook whose matcher names a tool
+ Codex has since renamed cannot self-heal from its own hook, because a hook
+ matching nothing never runs. The CLI is the only place it can happen, so moving
+ the call site to ``init``/``agents``/``doctor`` would strand anyone who never
+ runs those.
+
+``REPOWISE_SKIP_EDITOR_SETUP`` now applies here too. The variable means what it
+says: a benchmark, CI or sandbox run must not touch global config. These
+were the last two writers ignoring it. The accepted consequence is that someone
+who exports it in their shell profile never gets hook migrations, which is the
+correct reading of "do not touch my global config"; ``repowise doctor`` carries a
+row per agent that names the stale hook, so it is visible rather than silent.
+
+Nothing here is imported at module scope beyond stdlib: this runs on the
+``repowise-augment`` hot path, where the whole point of the separate console
+script is that it pulls in almost nothing.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from pathlib import Path
+
+
+def stamp_path() -> Path:
+ """The file holding the repowise version whose migrations have already run.
+
+ ``~/.repowise`` is the existing home for global CLI state (``platform.json``,
+ ``update-check.json``). Plain text rather than JSON because the only thing to
+ record is one version string, and the cheapness of the read is the point.
+
+ Resolved per call, not captured at import: a module-level ``Path.home()``
+ would bind whatever ``HOME`` was when the first CLI module loaded, which is
+ the exact trap the redirected-``USERPROFILE`` tests exist to catch.
+ """
+ return Path.home() / ".repowise" / "editor-migrations"
+
+
+def _migrate_claude_code_hooks() -> None:
+ from repowise.cli.editor_integrations.claude_config import migrate_claude_code_hooks
+
+ migrate_claude_code_hooks()
+
+
+def _migrate_codex_rewrite_hook() -> None:
+ from repowise.cli.editor_integrations.codex_config import migrate_codex_rewrite_hook
+
+ migrate_codex_rewrite_hook()
+
+
+#: The migrations, named. The stamp records these names alongside the version,
+#: because the version alone is not a complete key: ``__version__`` is a literal
+#: in ``repowise/cli/__init__.py`` and a migration added without bumping it would
+#: be **permanently** skipped for anyone who had already run that version, which
+#: is every install tracking ``main``, including this repo's own. Adding an entry
+#: here changes the stamp, so the new migration runs.
+#:
+#: Real functions rather than ``module:attribute`` strings. The imports stay lazy
+#: either way, but a string path is checked by nothing: a typo in one would be an
+#: ImportError caught by the same handler as a migration failure, so the stamp
+#: would never be written and every hook fire would pay for the migrations,
+#: exactly the cost this module exists to remove, silently and forever.
+_MIGRATIONS: tuple[tuple[str, Callable[[], None]], ...] = (
+ ("claude_code_hooks", _migrate_claude_code_hooks),
+ ("codex_rewrite_hook", _migrate_codex_rewrite_hook),
+)
+
+
+def _expected_stamp() -> str:
+ from repowise.cli import __version__
+
+ return f"{__version__} {','.join(name for name, _ in _MIGRATIONS)}"
+
+
+def _read_stamp() -> str | None:
+ try:
+ return stamp_path().read_text(encoding="utf-8").strip() or None
+ except (OSError, ValueError):
+ # Absent, a directory, unreadable, or not UTF-8. All mean the same
+ # thing: no usable stamp, so run the migrations.
+ return None
+
+
+def _write_stamp(stamp: str) -> None:
+ path = stamp_path()
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(stamp, encoding="utf-8")
+ except OSError:
+ # A stamp we cannot write costs the pre-stamp behaviour (the migrations
+ # run again next time) and nothing else. Never worth failing over.
+ pass
+
+
+def run_editor_migrations() -> bool:
+ """Repair legacy agent hook shapes, at most once per repowise version.
+
+ Returns whether the migrations actually ran, which is what the tests assert
+ on; no caller acts on it.
+
+ **The stamp is read before anything else, and that ordering is the feature.**
+ Gating on ``is_editor_setup_disabled`` first reads better and costs more than
+ the problem it solves: that function lives in ``editor_setup``, whose module
+ scope imports ``agent_targets.types``, and importing it measures at roughly
+ 13ms against the ~19ms the whole self-heal was costing. On a path that fires
+ once per matched tool call, checking the environment first would have spent
+ two thirds of the saving on the check. Reading the stamp needs nothing but
+ ``pathlib``, so the common path imports nothing at all.
+
+ Reading is safe to do unconditionally: ``REPOWISE_SKIP_EDITOR_SETUP`` is
+ about not *writing* to global config, and a stamp that is absent (which it
+ will be, under that variable) short-circuits to the env check anyway.
+
+ The stamp is written only when every migration completes without raising. A
+ run that failed has not healed anything, and recording it as done would turn
+ a transient failure into a permanent one.
+ """
+ expected = _expected_stamp()
+ if _read_stamp() == expected:
+ return False
+
+ from repowise.cli.editor_setup import is_editor_setup_disabled
+
+ if is_editor_setup_disabled():
+ return False
+
+ ok = True
+ for _name, migrate in _MIGRATIONS:
+ try:
+ migrate()
+ except Exception:
+ ok = False
+
+ if ok:
+ _write_stamp(expected)
+ return True
diff --git a/plugins/codex/skills/architectural-decisions/SKILL.md b/plugins/codex/skills/architectural-decisions/SKILL.md
index bf3c4a2a6..98bebaa18 100644
--- a/plugins/codex/skills/architectural-decisions/SKILL.md
+++ b/plugins/codex/skills/architectural-decisions/SKILL.md
@@ -3,9 +3,9 @@ name: architectural-decisions
description: Use when a task asks why code is built a certain way, proposes architectural changes, compares implementation approaches, or mentions decision markers such as WHY, DECISION, TRADEOFF, or ADR in a Repowise-indexed repository.
---
-# Architectural Decisions With Repowise
+# Architectural Decisions with Repowise
-Repowise captures architectural decisions: the rationale behind how code is built.
+Repowise captures architectural decisions — the *why* behind how code is built.
`get_why` has four modes — pick by what you pass:
@@ -22,27 +22,32 @@ rationale traces to a verbatim source span, stamped exact / fuzzy / unverified.
When no decision exists for a path, `get_why` falls back to git archaeology so
the call is never empty.
-## When The User Asks Why Something Exists
+## When the user asks "why is X built this way?"
-Call `get_why(query="specific area or decision")`.
+Call `get_why(query="X")`.
-## Before Architectural Changes
+## When about to make an architectural change
-1. Call `get_why(query="the area being changed")` before introducing new patterns, restructuring modules, replacing infrastructure, or choosing between approaches.
-2. If decisions are found, summarize the relevant rationale and tradeoffs before editing.
-3. If no decision is found, state that no recorded decision governs the area and continue with normal source inspection.
+1. Call `get_why(query="the specific area you're changing")` to find existing decisions that govern that area.
+2. If decisions are found, present them to the user before proceeding — they may not want to contradict an existing architectural choice.
+3. If no decisions are found, proceed but note that no recorded decision governs this area.
-## When No Specific Query Exists
+## When called with no specific query
-Call `get_why()` to inspect decision health: stale decisions, conflicts, and ungoverned hotspots.
+Call `get_why()` with no arguments to get the decision-health dashboard:
+- Stale decisions that may no longer apply
+- Proposed decisions awaiting confirmation
+- Ungoverned hotspots (high-churn files with no recorded decisions)
-The same signals surface in the CLI via `repowise decision health`, and you can
-review auto-proposed decisions with `repowise decision confirm`.
+The same signals surface in the CLI via `repowise decision health` /
+`/prompts:repowise-decision`, and you can query *why* mid-task with `repowise why` /
+`/prompts:repowise-why` (the `get_why` adapter). Review auto-proposed decisions with
+`repowise decision confirm`.
-## When Decision Markers Appear In Code
+## When a file has decision markers
-If a file contains `WHY:`, `DECISION:`, `TRADEOFF:`, or `ADR:`, call `get_context(targets=["path/to/file"])` to retrieve the full file context and related decisions.
+If you see `# WHY:`, `# DECISION:`, `# TRADEOFF:`, or `# ADR:` comments in code, call `get_context(targets=["that_file.py"])` to see the full decision record with context and affected modules.
-## Recording New Decisions
+## Recording new decisions
-When the user makes a new architectural decision, suggest recording it with a `DECISION:` comment in the relevant code or with `repowise decision add`.
+If the user makes an architectural decision during the conversation, suggest: "Want to record this decision? Add a `# DECISION:` comment in the relevant code, or run `repowise decision add` to capture it formally."
diff --git a/plugins/codex/skills/change-review/SKILL.md b/plugins/codex/skills/change-review/SKILL.md
index 8185cde96..87b3b7ad5 100644
--- a/plugins/codex/skills/change-review/SKILL.md
+++ b/plugins/codex/skills/change-review/SKILL.md
@@ -3,9 +3,14 @@ name: change-review
description: Use when reviewing a set of changes before they merge in a Repowise-indexed repository, a PR, a branch diff, or the working-tree changes you just made. Activates for "review this PR", "is this safe to merge", "what is the blast radius of these changes", or "did I miss anything".
---
-# Change Review With Repowise
+# Change Review with Repowise
-When a diff is on the table, Repowise turns "what files changed" into "what does this change put at risk", fusing git history (churn, ownership, co-change) with graph topology (dependents, impact surface), test gaps, security signals, and the architectural decisions that govern the touched code. Use two complementary signals.
+When a diff is on the table, Repowise turns "what files changed" into "what does
+this change put at risk" — fusing git history (churn, ownership, co-change) with
+graph topology (dependents, impact surface), test gaps, security signals, and the
+architectural decisions that govern the touched code.
+
+Two complementary risk signals, use both:
- **`get_change_risk(revspec=…)` (MCP)** scores the *whole change as one unit* (a
commit or a `base..head` range) from its diff shape: a single 0-10 defect-risk
@@ -20,7 +25,7 @@ When a diff is on the table, Repowise turns "what files changed" into "what does
- **`get_risk(changed_files=…)` (MCP)** works *per file* and returns the
`directive` block, the specific things to check inside the diff.
-## Score The Whole Change First
+## Score the whole change first
```
get_change_risk(revspec="main..HEAD") # HEAD, a commit SHA, or base..head
@@ -34,29 +39,47 @@ or filters matched no files, so an all-zero score there is not a clean bill of
health. The equivalent from a terminal is `repowise risk <revspec>` (add
`--ext .py,.ts` or `--format json`).
-## Then Drill Into The Directive Block
+## Then drill into the directive block
+
+Call `get_risk` in **PR mode** by passing the changed files:
+
+```
+get_risk(targets=<changed files>, changed_files=<same changed files>)
+```
-Call `get_risk(targets=<changed files>, changed_files=<same files>)` in PR mode. The `directive` block is a few short lists, read it first:
+The response carries a `directive` block — read it first, it's a few short lists:
-- `will_break`: files or symbols that depend on what changed but are not in the diff. Likely breakages, check each one.
-- `missing_cochanges`: files that historically change together with the changed files but were left untouched. Often a forgotten update.
-- `missing_tests`: changed code with a test gap. Flag for new or updated tests.
-- `tests_to_run`: the coverage-backed complement of `missing_tests`, the tests the per-test map proves execute the changed files (pytest-runnable ids). Empty means unknown (no coverage map ingested), never "no tests exist".
+- **`will_break`** — files/symbols that depend on what changed but are *not* in
+ the diff. These are the likely breakages. Check each one.
+- **`missing_cochanges`** — files that historically change together with the
+ changed files but were left untouched. Often a forgotten update.
+- **`missing_tests`** — changed code with a test gap. Flag for new/updated tests.
+- **`tests_to_run`** — the positive complement of `missing_tests`: the tests the
+ per-test coverage map proves execute the changed files (pytest-runnable ids).
+ Recommend running these to validate the change. Empty until a coverage map is
+ ingested (`repowise coverage add`); empty is "unknown", never "no tests exist".
`pr_blast_radius` holds the fuller dossier behind those lists (including the
per-changed-file `guarding_tests` breakdown behind `tests_to_run`).
For the line-precise version from a terminal, `repowise impacted-tests <revspec>`
maps each changed line to the tests whose recorded coverage touches it, then
-prints the ids (`--format list | xargs pytest` runs exactly them).
+prints the ids (`--format list | xargs pytest` runs exactly them). It is honest
+about gaps: a changed file with no coverage rows is a labelled filename guess,
+and a brand-new file is "unknown, run the full suite", never "no tests needed".
-## Then Go Deeper Where It Matters
+## Then go deeper where it matters
-1. Call `get_why(query="<file>")` for any non-trivial changed file so the change does not silently contradict a recorded decision. Surface `conflicts_with` and `supersedes` hits.
-2. Call `get_health(targets=<changed files>, include=["biomarkers"])` to catch new complexity, deep nesting, or duplication the diff introduced.
-3. Use the `get_risk` ownership and co-change signals to suggest who should review.
+1. **Why does this code exist?** For any non-trivial changed file, call
+ `get_why(query="<file>")` — don't let a change silently contradict a recorded
+ architectural decision. Surface `conflicts_with` / `supersedes` hits.
+2. **Did the change make health worse?** `get_health(targets=<changed files>,
+ include=["biomarkers"])` — call out new complexity, deep nesting, or
+ duplication the diff introduced.
+3. **Who should review?** `get_risk` ownership + co-change signals suggest the
+ people with the most context on the touched code.
-## Getting The Diff
+## Getting the diff
- A GitHub PR: `gh pr diff <number>` (or `gh pr view <number> --json files`).
- A branch: `git diff --name-only main...HEAD`.
@@ -64,10 +87,15 @@ prints the ids (`--format list | xargs pytest` runs exactly them).
- CLI shortcut for a range: `repowise risk main..HEAD` scores a branch/PR range
for defect risk directly.
-## Write The Review Around Evidence
+## Write the review around evidence
-Lead with a risk level and the `directive` findings, each tied to a concrete file. Distinguish "will break" (a dependent outside the diff) from "worth a look" (a co-change or health regression). Do not pad with findings the tools did not support.
+Lead with a risk level and the `directive` findings, each tied to a concrete
+file. Distinguish **"will break"** (a dependent outside the diff) from **"worth a
+look"** (a co-change or health regression). Don't pad with findings the tools
+didn't support.
-## Error Handling
+## Error handling
-If `get_risk` or `get_change_risk` errors or returns nothing, the MCP server may be down or the repo unindexed. Say so, review from the raw diff, and suggest running `repowise init` if the repo is not indexed.
+If `get_risk` errors or returns nothing, the MCP server may be down or the repo
+unindexed — say so and review from the raw diff, noting that Repowise context was
+unavailable. Suggest `/prompts:repowise-init` if the repo isn't indexed.
diff --git a/plugins/codex/skills/code-health/SKILL.md b/plugins/codex/skills/code-health/SKILL.md
index 6450bac95..eabe11796 100644
--- a/plugins/codex/skills/code-health/SKILL.md
+++ b/plugins/codex/skills/code-health/SKILL.md
@@ -15,9 +15,8 @@ not just *bigger*.
## Pick the mode by what you pass
- **Dashboard** — `get_health()` (no targets): a `directive` naming what to fix
- first, then repo-level KPIs plus the
- lowest-scoring files. Start here for "how healthy is this codebase?" or "what
- should we clean up?".
+ first, then repo-level KPIs and the lowest-scoring files. Start here for "how
+ healthy is this codebase?" or "what should we clean up?".
- **Targeted** — `get_health(targets=["src/x.py", "src/y.py"])`: per-file score
and the specific marker findings driving it. Use before/after a refactor,
or to explain *why* a file is flagged.
@@ -36,7 +35,7 @@ not just *bigger*.
1. For "what should I refactor?" → dashboard mode, lead with `directive`, then
`get_health(targets=[worst files], include=["refactoring"])` and present the
- ranked suggestions, not just the scores.
+ ranked plans, not just the scores.
2. Rank by `weighted_deficit`, not `score` — the score floors at 1.0.
3. For a specific file → report the score, the top 2–3 marker findings, and
what each one means in plain language. Avoid dumping the raw payload.
@@ -58,6 +57,6 @@ not just *bigger*.
## Error handling
-If `get_health` reports no repository, suggest `repowise init --yes`. Code health is
+If `get_health` reports no repository, suggest `/prompts:repowise-init`. Code health is
computed even with a template-rendered wiki (no LLM needed), so it should be available
whenever the repo is indexed.
diff --git a/plugins/codex/skills/codebase-exploration/SKILL.md b/plugins/codex/skills/codebase-exploration/SKILL.md
index d98ea1936..0727f96fb 100644
--- a/plugins/codex/skills/codebase-exploration/SKILL.md
+++ b/plugins/codex/skills/codebase-exploration/SKILL.md
@@ -3,11 +3,14 @@ name: codebase-exploration
description: Use when exploring, understanding, or answering questions about a Repowise-indexed codebase, including architecture, where code is implemented, how a module works, or which files are relevant before reading source.
---
-# Codebase Exploration With Repowise
+# Codebase Exploration with Repowise
-This project has a Repowise intelligence layer. Use Repowise MCP tools before broad source browsing so the answer starts from indexed docs, ownership, graph structure, git signals, and decisions.
+This project has a Repowise intelligence layer. Before grepping and reading raw
+source to understand the codebase, reach for the Repowise MCP tools — they
+return documentation, ownership, history, decisions, and graph structure that
+plain file reads don't, usually in one round-trip instead of many.
-## Which Tool For Which Question
+## Which tool for which question
| You want… | Call |
|---|---|
@@ -15,9 +18,9 @@ This project has a Repowise intelligence layer. Use Repowise MCP tools before br
| A direct answer to "how/where/why does X work" | `get_answer(question="…")` — synthesised answer with citations + a `retrieval_quality` signal. Collapses the search → read → reason loop. |
| Find a symbol, file, or fuzzy concept | `search_codebase(query="…")` — hybrid search. `mode="auto"` routes an identifier to indexed symbol hits (`symbol_id`/line bounds → pipe into `get_symbol`), a path to file pages (→ `get_context`), and prose to semantic wiki search (each hit reports `search_method`: `embedding` vs `bm25`). Force a branch with `mode=symbol\|path\|concept\|hybrid`; narrow symbols with `symbol_kind`. |
| A triage card for specific files/symbols | `get_context(targets=[…])` — title, summary, signatures, hotspot bit, top callers, decision titles, symbol_ids. Batch many targets in one call. |
-| The actual source of one symbol | `get_symbol("path/to/file.py::Name")` — exact bytes with line bounds. Cheaper than a raw read + offset math. Use a `symbol_id` from `get_context`. |
+| The actual source of one symbol | `get_symbol("path/to/file.py::Name")` — exact bytes with line bounds. Cheaper than Read + offset math. Use a `symbol_id` from `get_context`. |
-## Recommended Flow
+## Recommended flow
1. New area you don't know → `get_overview()` once.
2. A specific question → `get_answer(question=…)` first.
@@ -30,10 +33,10 @@ This project has a Repowise intelligence layer. Use Repowise MCP tools before br
4. More files around a concept → `search_codebase`, then `get_context` on the
hits (batched), then `get_symbol` only for the bodies you actually need.
-Fall back to raw source reads only when the indexed context doesn't cover the
+Fall back to raw Read/Grep only when the indexed context doesn't cover the
specific detail the user asked about.
-## Trust Signals — Verify When
+## Trust signals — verify when
- `_meta.stale_warning` is present (the index has diverged from HEAD), or
- `retrieval_quality` is `partial`/`weak`, or
@@ -41,16 +44,18 @@ specific detail the user asked about.
Otherwise the response is current — act on it.
-## Error Handling
-
-- If tools report that no repositories were found, suggest running `repowise init`.
- Add `--no-editor-setup` if this repo is a scratch clone, a fixture, or a worktree:
- `init` otherwise registers repowise in the user's machine-wide editor config, which
- holds a single entry and so gets repointed at whichever repo was indexed last. The
- Codex config this skill relies on is project-local and is written either way.
-- If `get_answer`/`search_codebase` come back empty, the repository may have a
- template-rendered wiki; fall back to `get_context` with specific paths, and note
- that model-written pages (`repowise generate`, or `repowise init` with an LLM
+## Error handling
+
+- "No repositories found. Run 'repowise init' first." → suggest `/prompts:repowise-init`.
+ Add `--no-editor-setup` if this repo is a scratch clone, a fixture, or a
+ worktree: `init` otherwise repoints the user's single global `repowise` MCP
+ entry at it.
+- MCP tools unavailable → prefer the matching CLI slash commands when the
+ plugin is installed (`/prompts:repowise-ask`, `/prompts:repowise-context`, `/prompts:repowise-symbol`,
+ `/prompts:repowise-search`) rather than grepping blind.
+- `get_answer`/`search_codebase` come back empty → the repo may have a
+ template-rendered wiki. Fall back to `get_context` with explicit paths, and note
+ that model-written pages (`repowise generate`, or `/prompts:repowise-init` with an LLM
provider) unlock richer docs + semantic search.
-- If MCP tools are unavailable, proceed with normal source inspection and mention
- that Repowise context was unavailable.
+- Tools fail to connect at all → the `repowise` binary may not be installed;
+ suggest `/prompts:repowise-init`.
diff --git a/plugins/codex/skills/dead-code-cleanup/SKILL.md b/plugins/codex/skills/dead-code-cleanup/SKILL.md
index 76f36b658..0da6e0b94 100644
--- a/plugins/codex/skills/dead-code-cleanup/SKILL.md
+++ b/plugins/codex/skills/dead-code-cleanup/SKILL.md
@@ -3,38 +3,36 @@ name: dead-code-cleanup
description: Use when the user asks about unused code, cleanup, deleting files or exports, refactoring old areas, reducing bundle size, code hygiene, technical debt, or maintenance in a Repowise-indexed repository.
---
-# Dead Code Cleanup With Repowise
+# Dead Code Cleanup with Repowise
-Repowise detects dead code through graph analysis and git context. Treat findings as a cleanup plan, not automatic permission to delete.
+Repowise detects dead code through graph analysis — no LLM needed, works even with a template-rendered wiki.
-## Finding Dead Or Unused Code
+## When the user asks about dead/unused code
-Call `get_dead_code()` to get findings organized by confidence tier. Useful parameters:
+Call `get_dead_code()` to get findings sorted by confidence tier. Useful parameters:
+- `safe_only=true` — only findings confirmed safe to delete (confidence >= 0.7)
+- `kind="unreachable_file"` — files with no importers
+- `kind="unused_export"` — public symbols nobody uses
+- `kind="zombie_package"` — monorepo packages with no consumers
+- `directory="src/old/"` — limit to a specific directory
+- `tier="high"` — only high-confidence findings (>= 0.8)
+- `min_confidence=0.7` — raise the floor (default is 0.5) for a release-ready cleanup
+- `group_by="directory"` or `group_by="owner"` — roll up to see where the dead code concentrates and who owns the most of it
-- `safe_only=true` for findings already marked safe to delete.
-- `min_confidence=0.7` for high-confidence cleanup work.
-- `kind="unreachable_file"` for files with no importers.
-- `kind="unused_export"` for public symbols with no known consumers.
-- `kind="zombie_package"` for monorepo packages with no consumers.
-- `directory="src/old/"` to limit scope.
-- `tier="high"` for the highest-confidence band.
-- `group_by="directory"` or `group_by="owner"` to roll up where dead code concentrates and who owns the most of it.
+## How to present findings
-## Presenting Findings
+- Only suggest deletion for findings with `safe_to_delete: true`
+- For lower-confidence findings, present them as "candidates to investigate" not "things to delete"
+- Dynamically-loaded code (plugins, handlers, adapters) may appear as dead code but isn't — Repowise filters common patterns but edge cases exist
-- Only recommend deletion for findings with `safe_to_delete: true`.
-- Present lower-confidence findings as candidates to investigate.
-- Flag dynamic loading, plugin systems, route handlers, adapters, and public APIs as common false-positive zones.
+## Before deleting anything
-## Before Deleting Anything
+1. Confirm with the user. Present the file/symbol name, confidence score, and why Repowise thinks it's dead.
+2. Call `get_risk(targets=["path/to/file"])` to double-check dependents.
+3. Recently-modified "dead" code is more likely a false positive — flag this if the finding has recent git activity.
-1. Confirm with the user.
-2. Present the file or symbol, confidence score, and why Repowise thinks it is dead.
-3. Call `get_risk(targets=["path/to/file"])` before deleting files or exports.
-4. If the finding has recent git activity, note the higher false-positive risk.
+## Safe deletion order
-## Safe Deletion Order
-
-1. Unreachable files first.
-2. Unused internal symbols next.
-3. Unused exports last.
+1. Unreachable files first (whole file removal, cleanest)
+2. Unused internal symbols next
+3. Unused exports last (highest false-positive risk due to potential dynamic imports)
diff --git a/plugins/codex/skills/pre-modification-check/SKILL.md b/plugins/codex/skills/pre-modification-check/SKILL.md
index 4cf9a4246..5360ce67a 100644
--- a/plugins/codex/skills/pre-modification-check/SKILL.md
+++ b/plugins/codex/skills/pre-modification-check/SKILL.md
@@ -3,17 +3,16 @@ name: pre-modification-check
description: Use before modifying, refactoring, moving, or deleting files in a Repowise-indexed repository, especially shared utilities, core modules, public APIs, or files the user did not explicitly identify.
---
-# Pre-Modification Check With Repowise
+# Pre-Modification Check with Repowise
-Before editing a Repowise-indexed codebase, assess impact with the graph and git signals.
+Before modifying files in a Repowise-indexed codebase, assess the impact.
-## Before Editing Files
+## Before editing a file
Call `get_risk(targets=["path/to/file.py"])`. Per file it returns
`hotspot_score`, `trend`, `risk_type`, `impact_surface` (top 3),
`dependents_count`, `co_change_partners`, `primary_owner`, `bus_factor`,
`test_gap`, and `security_signals`. Read it for:
-
- **Bug-fix history** (`defect_profile`) — present only on files with counted
fixes: `fix_count` over the trailing 6 months, `last_fix_days_ago`, a
`bug_magnet` flag for sustained recent fix pressure, and `top_symbols` (the
@@ -26,29 +25,27 @@ Call `get_risk(targets=["path/to/file.py"])`. Per file it returns
- **Ownership / bus factor** — who owns it, and whether a single author maintains it.
- **Test gap & security signals** — flag untested or security-sensitive files before touching them.
-## When Editing Multiple Files
-
-Batch all targets in one call: `get_risk(targets=["file1.py", "file2.py", "module/"])`.
+## When modifying multiple files
-## When To Warn The User
+Batch all targets into one call: `get_risk(targets=["file1.py", "file2.py", "module/"])`.
-Warn before editing when `get_risk` shows:
+## When to warn the user
-- A `defect_profile` with `bug_magnet` set — say so plainly: this file has been fixed repeatedly and recently.
-- Hotspot score above the 90th percentile.
-- More than 10 dependents — list the top dependents; API changes here will break consumers.
-- Bus factor of 1.
-- Risk type such as `bug-prone` or `high-coupling`.
-- Missing tests around changed or affected files.
+If `get_risk` shows:
+- A `defect_profile` with `bug_magnet` set — say so plainly: this file has been fixed repeatedly and recently
+- Hotspot score above 90th percentile — mention this is a frequently-changed, high-risk file
+- More than 10 dependents — list the top dependents; API changes here will break consumers
+- Bus factor of 1 — note that a single person maintains this code
+- Risk type is "bug-prone" or "high-coupling" — flag explicitly before making changes
-## Before Refactoring Or Moving Code
+## Before refactoring or moving code
-Call `get_context(targets=["path/to/file.py"])` first to understand what uses the file, which decisions govern it, and why it is structured that way.
+Call `get_context(targets=["file.py"])` first to understand the full context: what uses this file, what decisions govern it, and why it's structured this way. This prevents accidentally violating architectural decisions.
For a heavy refactor, also call `get_health(targets=["file.py"])` — the
marker findings (complexity, deep nesting, low cohesion, duplication) tell
you *what* to improve while you're in there, and give you a before/after score.
-## Error Handling
+## Error handling
-If `get_risk` fails or the MCP server is unavailable, proceed with normal inspection and mention that Repowise risk assessment was unavailable.
+If `get_risk` returns a tool error, the MCP server may not be running. Proceed with the modification but note that risk assessment was unavailable.
diff --git a/plugins/shared/README.md b/plugins/shared/README.md
new file mode 100644
index 000000000..cc5b3ed89
--- /dev/null
+++ b/plugins/shared/README.md
@@ -0,0 +1,52 @@
+# Shared plugin content
+
+The single source for the skills and slash commands both agent plugins ship.
+
+Everything under `plugins/claude-code/skills/`, `plugins/claude-code/commands/`,
+`plugins/codex/skills/` and `packages/cli/.../agent_targets/_data/codex_prompts/`
+is **generated from here**. Edit those files and the next test run fails; edit
+these and regenerate:
+
+```
+python scripts/gen_plugin_content.py # write
+python scripts/gen_plugin_content.py --check # report drift, write nothing
+```
+
+`plugins/codex/skills/` used to be a hand-copy of the Claude Code one and had
+already drifted: descriptions rewritten, headings retitled, one directory
+renamed, with nothing detecting it. Two files that say roughly the same thing in
+different words look fine from either side alone.
+
+## Authoring
+
+One file per item. Frontmatter is stored **verbatim**, not as parsed keys, so a
+render reproduces byte for byte instead of reflowing every folded scalar.
+
+```
+---
+frontmatter: | # used by any host with no override of its own
+ description: ...
+claude-code: # optional per-host block
+ dir: pre-modification # output directory, where the hosts disagree
+ frontmatter: | # replaces the shared block entirely
+ name: ...
+---
+
+<body, shared by every host, and the thing the golden test pins>
+```
+
+Skills carry per-host frontmatter because a description is trigger text tuned to
+one host's dispatcher. Commands share one block, and each host drops the keys it
+does not define (Codex prompt frontmatter is `description` and `argument-hint`;
+`allowed-tools` is Claude Code's).
+
+Write a slash-command reference as `{{cmd:risk}}`. Claude Code renders
+`/repowise:risk`, Codex renders `/prompts:repowise-risk`.
+
+## Where the Codex commands go
+
+Not into `plugins/codex/`. A Codex plugin manifest has no slot for commands: it
+may bundle `skills/`, `hooks/`, `assets/`, `.mcp.json` and `.app.json`, and
+nothing else, so the only surface that yields a Codex slash command is
+`~/.codex/prompts/`, which is local-only and written by the CLI. They ship as
+package data and `repowise agents add --target=codex` installs them.
diff --git a/plugins/shared/commands/ask.md b/plugins/shared/commands/ask.md
new file mode 100644
index 000000000..e9b54c6f4
--- /dev/null
+++ b/plugins/shared/commands/ask.md
@@ -0,0 +1,45 @@
+---
+frontmatter: |
+ description: Ask a codebase question and get a cited, synthesised answer with a confidence rating (costs an LLM call).
+ allowed-tools: Bash, Read
+---
+
+# Repowise Ask
+
+Answer a question about this codebase with citations. This is the same
+synthesis the `get_answer` MCP tool performs: hybrid retrieval followed by an
+LLM answer over what it found. Unlike `{{cmd:search}}`, this **costs an LLM
+call** — use it when the user wants an answer, not a hit list.
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `{{cmd:init}}` first." Stop.
+2. Resolve the question from `$ARGUMENTS`. If empty, ask: "What do you want to know about this codebase?"
+3. Run the command and present the answer, confidence, and retrieval quality.
+ Prefer citing the paths the answer names. Do not invent citations.
+
+## Choosing the invocation
+
+- Question only → `repowise ask "<question>"`
+- Restrict retrieval to a subtree → `repowise ask "<question>" --scope packages/cli/`
+- Machine-readable → `repowise ask "<question>" --format json`
+- Raw MCP payload (including dropped blocks) → `repowise ask "<question>" --full`
+
+```
+repowise ask "how does the retry backoff work?"
+repowise ask "where is the session cookie set?" --format json
+repowise ask "how is width resolved?" --scope packages/cli/
+repowise ask "why is auth split across two modules?" --full
+```
+
+Shared targeting flags (`--path`, `--repo`, `--no-workspace`) work the same as
+the other tool-adapter commands.
+
+## How to present the result
+
+- `confidence: high` is content-grounded — cite it directly.
+- `medium` / `low` — say so, and follow any `best_guesses` / `fallback_targets`
+ into `{{cmd:context}}` or `get_context` rather than inventing detail.
+- If a `note` warns that numbers may be synthesised, surface that caveat.
+- Prefer this over `{{cmd:search}}` when the user asked a *question*. Prefer
+ search when they want a list of matching pages / symbols.
diff --git a/plugins/shared/commands/context.md b/plugins/shared/commands/context.md
new file mode 100644
index 000000000..fe64c2e9b
--- /dev/null
+++ b/plugins/shared/commands/context.md
@@ -0,0 +1,51 @@
+---
+frontmatter: |
+ description: Triage card for files, modules, or symbols — layer, hotspot, fix history, freshness (relationships, not source bytes).
+ allowed-tools: Bash, Read
+---
+
+# Repowise Context
+
+Pull a triage card for one or more files, modules, or symbols. This is the CLI
+adapter over `get_context`: title, summary, architectural layer, hotspot /
+bug-fix history, doc freshness, and optional relationship blocks. Relationships
+and risk signals — **not** source bytes by default.
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `{{cmd:init}}` first." Stop.
+2. Resolve targets from `$ARGUMENTS`. If empty, ask which file / module /
+ `path::Symbol` to inspect.
+3. Run `repowise context` and present each card: layer, stale bit, hotspot,
+ summary. Call out fix history when present.
+
+## Choosing the invocation
+
+TARGETS are file paths, module paths, or `path/to/file.py::Symbol` ids. Batch
+them in one call.
+
+- Default triage → `repowise context <targets…>`
+- Opt-in blocks (repeatable) → `--include callers|callees|ownership|metrics|decisions|skeleton|…`
+- Richer card → `repowise context <targets…> --no-compact`
+- Machine-readable / raw payload → `--format json` / `--full`
+
+```
+repowise context src/api/routes.py src/api/auth.py
+repowise context src/api/routes.py::login --include callers --include metrics
+repowise context src/api/routes.py --include skeleton
+```
+
+`--include skeleton` adds the body-elided, line-verified file shape. For the
+exact function body, prefer `{{cmd:symbol}}` (or `get_symbol`) with a
+`symbol_id` from the card.
+
+Shared targeting flags (`--path`, `--repo`, `--no-workspace`) work the same as
+the other tool-adapter commands.
+
+## Notes
+
+- Prefer this before opening many files with Read — one call batches cards.
+- A target the index cannot resolve returns an `error` card; report that
+ plainly instead of inventing structure.
+- For a synthesised Q&A answer, use `{{cmd:ask}}`. For "why is it shaped
+ this way", use `{{cmd:why}}`.
diff --git a/plugins/shared/commands/coverage.md b/plugins/shared/commands/coverage.md
new file mode 100644
index 000000000..b78d5238e
--- /dev/null
+++ b/plugins/shared/commands/coverage.md
@@ -0,0 +1,44 @@
+---
+frontmatter: |
+ description: Ingest or inspect test-coverage reports — LCOV, Cobertura/Clover, or coverage.py .coverage (builds the per-test map when contexts are present).
+ allowed-tools: Bash, Read
+---
+
+# Repowise Coverage
+
+Ingest coverage so untested-hotspot markers light up in `repowise health` and
+so `repowise impacted-tests` can map a diff to the tests that exercise it.
+No LLM — pure report ingestion into the local index.
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `{{cmd:init}}` first." Stop.
+2. Decide the mode from `$ARGUMENTS` (see below), run the command, and present
+ a short summary (files covered, line/branch %, whether a per-test map was
+ built). Don't dump raw JSON unless asked.
+
+## Modes
+
+Default / "status" — show what is already ingested:
+```
+repowise coverage status
+```
+
+Handle `$ARGUMENTS`:
+- "status" / "show" → `repowise coverage status`
+- A report path (`coverage.lcov`, `lcov.info`, `coverage.xml`, `.coverage`, …)
+ → `repowise coverage add <path>`
+- "add" with no path → `repowise coverage add` (auto-discover common report paths)
+- Multiple paths → `repowise coverage add <a> <b>` (merged; hit wins)
+
+Useful flags on `add`: `--verbose` for ingestion debug logs; `--path <dir>`
+to point at a different repo.
+
+## Notes
+
+- `coverage add` always stores per-file line/branch coverage.
+- The **per-test map** (needed by `{{cmd:impacted-tests}}`) is built only
+ when the report carries per-test contexts — e.g. a coverage.py `.coverage`
+ written with `coverage run --contexts=test`, or a per-test lcov. Reports
+ without contexts ingest aggregates only; say so plainly.
+- After ingesting, suggest `repowise health` so untested-hotspot markers update.
diff --git a/plugins/shared/commands/dead-code.md b/plugins/shared/commands/dead-code.md
new file mode 100644
index 000000000..8ff42c9ab
--- /dev/null
+++ b/plugins/shared/commands/dead-code.md
@@ -0,0 +1,44 @@
+---
+frontmatter: |
+ description: Report unreachable files, unused exports, and zombie packages, tiered by confidence.
+ allowed-tools: Bash, Read
+---
+
+# Repowise Dead Code
+
+Find dead code through graph reachability + git context. No LLM — works in
+index-only mode. Findings are tiered by confidence; only `safe_to_delete` ones
+should be proposed for removal.
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `{{cmd:init}}` first." Stop.
+2. Run `repowise dead-code` (with any filters from `$ARGUMENTS`).
+3. Present findings grouped by confidence. Mark which are `safe_to_delete`. For
+ lower-confidence ones, frame them as "candidates to investigate," not deletions.
+
+## Filters from `$ARGUMENTS`
+
+- A path → `repowise dead-code <path>`
+- "safe" → `--safe-only` (only safe_to_delete findings)
+- "files" → `--kind unreachable_file`
+- "exports" → `--kind unused_export`
+- "packages" / "zombie" → `--kind zombie_package`
+- "strict" → `--min-confidence 0.7` (default is 0.4)
+
+Other flags: `--format json`, `--include-internals` (aggressive, private-symbol
+scan; higher false-positive rate), `--include-zombie-packages` /
+`--no-include-zombie-packages`, `--no-unreachable`, `--no-unused-exports`,
+`--repo <alias>` / `--no-workspace`.
+
+For per-directory or per-owner rollups, use the `get_dead_code` MCP tool with
+`group_by="directory"` or `group_by="owner"` (these are tool params, not CLI flags).
+
+## Before suggesting any deletion
+
+- Confirm with the user; show the name, confidence, and why it looks dead.
+- Recently-touched "dead" code is more likely a false positive — flag it.
+- Dynamically-loaded patterns (plugins, handlers, adapters, framework routes)
+ can look unused but aren't. Repowise filters the common cases; edge cases remain.
+- Double-check blast radius with `get_risk(targets=[...])` before removing files
+ or exported symbols.
diff --git a/plugins/shared/commands/decision.md b/plugins/shared/commands/decision.md
new file mode 100644
index 000000000..c5083fbde
--- /dev/null
+++ b/plugins/shared/commands/decision.md
@@ -0,0 +1,41 @@
+---
+frontmatter: |
+ description: Work with architectural decisions — list, inspect health, add, or confirm auto-proposed decisions.
+ allowed-tools: Bash, Read
+---
+
+# Repowise Decisions
+
+Repowise captures architectural decisions (the *why* behind the code) from eight
+sources and tracks them for staleness and conflicts. This command drives the
+`repowise decision` group.
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `{{cmd:init}}` first." Stop.
+2. Map `$ARGUMENTS` to a subcommand, run it, and present the result clearly.
+
+## Subcommands
+
+- **list** (default) — `repowise decision list`
+ - "stale" → `--stale-only`; "proposed" → `--proposed`
+ - "active" / "deprecated" / "superseded" → `--status <value>`
+ - filter by origin → `--source <value>`
+- **health** — `repowise decision health` — stale decisions, conflicts, and
+ ungoverned hotspots (high-churn files with no recorded decision). Good first call.
+- **show** — `repowise decision show <id>` — full record: rationale, evidence
+ spans, status, and the supersession lineage.
+- **add** — `repowise decision add` — guided interactive capture (~90s). Use when
+ the user makes a decision during the session and wants it recorded.
+- **confirm** — `repowise decision confirm` — review decisions auto-proposed from
+ git history and accept or reject them.
+- **deprecate / dismiss** — `repowise decision deprecate <id>` (optionally
+ `--superseded-by <id>`) or `repowise decision dismiss <id>`.
+
+## Notes
+
+- For *querying* why code looks the way it does mid-task, prefer the `get_why`
+ MCP tool (the `architectural-decisions` skill) — it returns lineage and an
+ alignment score. This command is for *managing* the decision records themselves.
+- `add` and `confirm` are interactive; tell the user when a step needs their input.
+- If unsure of an exact subcommand or flag, run `repowise decision --help`.
diff --git a/plugins/shared/commands/doctor.md b/plugins/shared/commands/doctor.md
new file mode 100644
index 000000000..3f880ea68
--- /dev/null
+++ b/plugins/shared/commands/doctor.md
@@ -0,0 +1,34 @@
+---
+frontmatter: |
+ description: Diagnose the Repowise setup — install, API keys, index/store drift — and optionally repair it.
+ allowed-tools: Bash, Read
+---
+
+# Repowise Doctor
+
+Check that Repowise is healthy: the install, configured provider / API keys, and
+whether the index and stores are consistent with the repo.
+
+## Steps
+
+1. Run `repowise doctor`.
+2. Summarize what passed and what didn't. For each problem, give the concrete fix
+ (set an env var, run `{{cmd:update}}`, re-run `{{cmd:init}}`, etc.).
+
+## Flags from `$ARGUMENTS`
+
+- "repair" / "fix" → `repowise doctor --repair` (attempts to fix detected
+ mismatches). Tell the user what it changed.
+- "workspace" → `repowise doctor --workspace` (check every repo in the workspace);
+ `--no-workspace` to force single-repo.
+- a path → `repowise doctor <path>`
+
+## Common findings
+
+- **repowise not installed / not on PATH** → suggest `pip install repowise` (or
+ `python -m pip install repowise` on Windows), then `{{cmd:init}}`.
+- **No API key for the configured provider** → show the exact `export` for the
+ provider in `.repowise/config.yaml`. This is not fatal for `init`, which falls
+ back to the template wiki. Only an explicitly named `--provider` errors out.
+- **Index drift (HEAD ahead of last sync)** → run `{{cmd:update}}`.
+- **Missing embeddings / store drift** → `{{cmd:reindex}}`.
diff --git a/plugins/shared/commands/export.md b/plugins/shared/commands/export.md
new file mode 100644
index 000000000..cad70d544
--- /dev/null
+++ b/plugins/shared/commands/export.md
@@ -0,0 +1,61 @@
+---
+frontmatter: |
+ description: Export the wiki (or architecture model) to markdown, HTML, JSON, or Structurizr DSL.
+ allowed-tools: Bash, Read
+---
+
+# Repowise Export
+
+Export indexed wiki pages to files, or emit a Structurizr DSL architecture
+model. Use this when the user wants a shareable dump, a static site, a JSON
+archive, or a C4/Structurizr model — not when they need an interactive Q&A
+answer (`{{cmd:ask}}`).
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `{{cmd:init}}` first." Stop.
+2. Resolve format and output from `$ARGUMENTS` (see below).
+3. Run `repowise export` and report where files were written (page count /
+ output path). Do not invent page content.
+
+## Choosing the invocation
+
+Default — markdown under `.repowise/export`:
+```
+repowise export
+```
+
+Handle `$ARGUMENTS`:
+- "html" / "site" → `repowise export --format html`
+- "json" → `repowise export --format json`
+- "json full" / "archive" → `repowise export --format json --full`
+ (`--full` keeps tombstones and adds decisions / dead code / hotspots)
+- "structurizr" / "c4" / "dsl" → `repowise export --format structurizr`
+- "structurizr standalone" → `repowise export --format structurizr --standalone`
+- "structurizr components" → add `--components`
+- "to <dir>" / "-o <dir>" → pass `--output <dir>`
+ (for structurizr, a path ending in `.dsl` names the file itself)
+- A repo path → `repowise export <path> …`
+
+```
+repowise export
+repowise export --format html -o ./site
+repowise export --format json --full
+repowise export --format structurizr --standalone --components
+repowise export --format structurizr -o architecture.dsl
+```
+
+## Structurizr notes
+
+- Default structurizr output is a **model fragment** to include from your own
+ `workspace.dsl`. Pass `--standalone` for a complete workspace with default
+ views.
+- `--force` overwrites an output file even if Repowise did not write it
+ (`--standalone` often targets `workspace.dsl`).
+- `--no-externals` leaves third-party dependencies out of the model.
+
+## Notes
+
+- Markdown / HTML / JSON write a directory of pages; structurizr writes DSL.
+- Never fabricate export contents. If the command reports no pages, say so and
+ suggest `{{cmd:init}}`.
diff --git a/plugins/shared/commands/health.md b/plugins/shared/commands/health.md
new file mode 100644
index 000000000..43d72282b
--- /dev/null
+++ b/plugins/shared/commands/health.md
@@ -0,0 +1,41 @@
+---
+frontmatter: |
+ description: Show Repowise code-health — KPIs, lowest-scoring files, refactoring targets, trends, or per-file markers.
+ allowed-tools: Bash, Read
+---
+
+# Repowise Health
+
+Report the code-health layer: a deterministic 1–10 score per file from markers
+(complexity, deep nesting, brain methods, cohesion, duplication, untested
+hotspots, and more). No LLM — works even in index-only mode.
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `{{cmd:init}}` first." Stop.
+2. Decide the mode from `$ARGUMENTS` (see below), run the command, and present a
+ readable summary — score(s), the top marker findings, and what they mean.
+ Don't dump the raw table verbatim.
+
+## Modes
+
+Default (no args) — dashboard KPIs + lowest-scoring files:
+```
+repowise health
+```
+
+Handle `$ARGUMENTS`:
+- A file or directory path → `repowise health <path>` (or `--file <path>` for a single file)
+- "refactoring" / "targets" → `repowise health --refactoring-targets` (ranked by impact/effort)
+- "trend" / "trends" → `repowise health --trend` (last snapshots + declining / predicted-decline alerts)
+- "module <name>" → `repowise health --module <name>`
+- a coverage file (e.g. `cov.lcov`, `coverage.xml`, `.coverage`) → `repowise coverage add <file>` to ingest it (folds into health markers, and builds the per-test map when the report has contexts), then `repowise health`
+
+Other flags: `--format json` for machine-readable output, `-v, --verbose` for
+pipeline debug logs, `--repo <alias>` / `--no-workspace` in workspace mode.
+
+## Notes
+
+- A file that is both low-health **and** a churn hotspot is the highest-priority
+ cleanup — cross-reference with `{{cmd:risk}}` or `get_risk`.
+- If everything scores high, say so plainly rather than inventing concerns.
diff --git a/plugins/shared/commands/impacted-tests.md b/plugins/shared/commands/impacted-tests.md
new file mode 100644
index 000000000..c95120056
--- /dev/null
+++ b/plugins/shared/commands/impacted-tests.md
@@ -0,0 +1,47 @@
+---
+frontmatter: |
+ description: Print the tests whose coverage intersects a change's changed lines — for a commit, base..head range, or staged diff.
+ allowed-tools: Bash, Read
+---
+
+# Repowise Impacted Tests
+
+Map a change to the tests that actually exercise its changed lines, using the
+per-test coverage map from `repowise coverage add`. No LLM, no network —
+an index lookup. Useful as a pre-merge / CI gate ("run these 40, not all 4,000").
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `{{cmd:init}}` first." Stop.
+2. Resolve the target from `$ARGUMENTS`, run `repowise impacted-tests`, and
+ present the test ids. Be honest about gaps (see Notes).
+
+## Choosing the revspec
+
+- No args → `repowise impacted-tests` (staged changes; same as `--staged`)
+- A commit SHA → `repowise impacted-tests <sha>`
+- A range / PR / branch → `repowise impacted-tests <base>..<head>`
+ (e.g. `repowise impacted-tests main..HEAD`)
+- "staged" → `repowise impacted-tests --staged`
+
+Useful flags:
+- `--format list` — test ids one per line (pipe to `xargs pytest`)
+- `--format json` — full report
+- `--path <dir>` — point at a different repo
+
+```
+repowise impacted-tests main..HEAD --format list | xargs pytest
+```
+
+## Notes
+
+- Requires a per-test map from `repowise coverage add` on a report with
+ contexts. If none is ingested, the command prompts to run
+ `{{cmd:coverage}}` / `repowise coverage add` — it does **not** invent an
+ empty "no tests needed" result.
+- A changed file with no coverage rows may get a filename-pattern **guess**
+ labelled as a guess — never present guesses as coverage-backed.
+- A brand-new file with neither coverage nor a paired test is "unknown, run
+ the full suite".
+- For a whole-change defect-risk score, use `{{cmd:risk}}`. For per-file
+ blast radius / `tests_to_run`, use the `get_risk` MCP tool.
diff --git a/plugins/shared/commands/init.md b/plugins/shared/commands/init.md
new file mode 100644
index 000000000..ddde87a49
--- /dev/null
+++ b/plugins/shared/commands/init.md
@@ -0,0 +1,230 @@
+---
+frontmatter: |
+ description: Set up Repowise for this codebase. Installs if needed, asks about your preferences, and runs the indexing.
+ allowed-tools: Bash, Read, Write, AskFollowupQuestion
+---
+
+# Repowise Init
+
+You are helping the user set up Repowise for their codebase. Follow this sequence precisely.
+
+## Step 1: Check if repowise is installed
+
+Run: `repowise --version`
+
+If the command fails or is not found, ask the user:
+
+"Repowise isn't installed yet. I can install it for you. Which do you prefer?"
+- `pip install repowise` (recommended, includes every LLM provider SDK)
+- "I'll install it myself"
+
+If they want you to install it, run `pip install repowise`. If that fails, try `python -m pip install repowise`.
+
+After install, verify with `repowise --version`.
+
+If repowise IS found, print the version and move to Step 2.
+
+## Step 2: Check if this repo is already indexed
+
+Check if `.repowise/` directory exists in the project root.
+
+If it exists, tell the user:
+"This repo is already indexed by Repowise. Run `{{cmd:status}}` to check health, or `{{cmd:update}}` to refresh. If you want to re-index from scratch, I can run `repowise init --force`."
+
+Then stop — do not continue to Step 3 unless the user asks to re-index.
+
+If `.repowise/` doesn't exist, move to Step 3.
+
+## Step 3: Offer the mode, but do not block on it
+
+Repowise needs **no API key at all**. Never make a key a precondition for
+setting it up, and never stop and wait if you cannot get an answer.
+
+Tell the user:
+
+"Repowise indexes your repo and writes a complete wiki with no API key. I'll run
+`repowise init --yes` unless you'd rather pick:
+
+1. **Default (no key)** — full index plus a wiki rendered from your code's structure. Free, fast, nothing to configure.
+2. **Model-written wiki** — everything above, but an LLM writes the wiki prose instead of rendering it from structure, which also enables decision mining. Needs a provider key (Anthropic, OpenAI, Gemini, or Ollama locally). You can start keyless and upgrade any page later with `repowise generate`.
+3. **Show me the flags.**"
+
+If the user does not answer, or you are running unattended, take option 1.
+
+### If Default (no key):
+
+Skip provider selection entirely. Construct:
+```
+repowise init --no-prose --yes
+```
+
+Jump to Step 3b.
+
+### If Full mode:
+
+Move to Step 3b, then Step 4.
+
+### If "show me flags":
+
+Print the full flag reference:
+```
+repowise init [PATH]
+
+Core flags:
+ --provider NAME LLM provider: anthropic, openai, gemini, ollama, litellm
+ --model NAME Model identifier override
+ --prose / --no-prose Write the subsystem (concept) pages as model prose
+ (--prose, needs a key), or render the whole wiki from
+ structure with no model and no spend (--no-prose).
+ Every other page is structural either way.
+ Default: prose when a key is available.
+ --mode fast Quick first pass on very large repos: no wiki at all.
+
+Embeddings:
+ --embedder NAME Embedding provider: gemini, openai, mock (default: auto-detect)
+
+Cost control:
+ --concurrency N Max parallel LLM calls (default: 10)
+ --test-run Limit to top 10 files by PageRank for quick validation
+
+Exclusions:
+ -x, --exclude PATTERN Gitignore-style exclude patterns. Repeatable.
+ Example: -x 'vendor/**' -x 'generated/'
+ --skip-tests Skip test files
+ --skip-infra Skip infrastructure files (Dockerfile, Makefile, Terraform, shell)
+
+Git:
+ --commit-limit N Max commits to analyze per file (default: 500, max: 10000)
+ --follow-renames Track files across renames (slower but more accurate history)
+
+Editor integration:
+ --editor-setup / Register (default) or skip the global MCP server entry
+ --no-editor-setup and Claude Code hooks in ~/.claude/settings.json and
+ Claude Desktop's config, plus the distill rewrite-hook
+ offer. There is one 'repowise' MCP entry per config, so
+ a later init from another repo repoints it. See Step 3b.
+
+Output:
+ --no-claude-md Don't generate/update CLAUDE.md
+ -y, --yes Skip cost confirmation prompt
+ -v, --verbose Show per-phase internals plus debug logs (quiet by default)
+
+Recovery:
+ --resume Resume a previously interrupted init
+ --force Re-index from scratch, overwriting existing .repowise/
+
+Dry run:
+ --dry-run Show generation plan and cost estimate without running
+```
+
+Then ask if they want you to construct a command or if they'll handle it.
+
+## Step 3b: Is this repo a keeper?
+
+Every path reaches this step. It is about the repo, not the provider.
+
+By default `init` registers repowise as the user's global MCP server, in
+`~/.claude/settings.json` and Claude Desktop's config. There is **one**
+`repowise` key in each file, so this repo replaces whatever repo is registered
+now. That is the right default for the repo someone actually works in, and the
+wrong one for a checkout that is about to disappear.
+
+Add `--no-editor-setup` when either of these holds:
+
+- the path is a scratch clone, a fixture, a sample, a vendored copy, or sits
+ under a temp directory
+- it is a linked git worktree rather than the main checkout. Check with
+ `git rev-parse --git-common-dir`: a value other than `.git` means a worktree
+
+Also add it if the user says they don't want their editor or MCP setup touched.
+Do **not** infer that from "just index it" or "don't ask me questions" — those
+are about prompts, not config.
+
+The index, the wiki, and every project-local file are identical either way.
+Only the machine-wide registration is skipped, and it can be done later by
+re-running `repowise init` in that repo without the flag.
+
+Whichever you pick, say which in one line so the user can correct you.
+
+If `init` prints "Replacing the existing repowise MCP …", relay it. The global
+entry just moved to this repo, and the user may want it pointed back.
+
+Then continue to Step 4 for the model-written wiki, or Step 5 otherwise.
+
+## Step 4: Provider selection (model-written wiki only)
+
+**Skip this entire step unless the user chose the model-written wiki.** A
+missing key is not a blocker: `init` renders the template wiki and exits 0
+without one. If you cannot find a key, do not stop and do not ask again. Run
+`repowise init --yes` and tell the user their wiki is rendered from structure
+and can be upgraded per-page later with `repowise generate`.
+
+Check which API keys are already set by running:
+```bash
+echo "ANTHROPIC=${ANTHROPIC_API_KEY:+set}" "OPENAI=${OPENAI_API_KEY:+set}" "GEMINI=${GEMINI_API_KEY:+set}${GOOGLE_API_KEY:+set}" "OLLAMA=${OLLAMA_BASE_URL:+set}"
+```
+
+If one or more keys are detected, suggest the detected provider:
+- `ANTHROPIC_API_KEY` set → suggest `--provider anthropic`
+- `OPENAI_API_KEY` set → suggest `--provider openai`
+- `GEMINI_API_KEY` or `GOOGLE_API_KEY` set → suggest `--provider gemini`
+- `OLLAMA_BASE_URL` set → suggest `--provider ollama`
+
+If no key is detected, ask:
+
+"Which LLM provider do you want to use?"
+- **Anthropic** (Claude) — needs `ANTHROPIC_API_KEY`
+- **OpenAI** (GPT-4o or compatible) — needs `OPENAI_API_KEY`
+- **Google Gemini** (recommended for cost efficiency) — needs `GEMINI_API_KEY` or `GOOGLE_API_KEY`
+- **Ollama** (fully local, no API key, slower) — needs Ollama running locally
+- **LiteLLM** (100+ providers) — needs LiteLLM config
+
+Then ask them to set the required environment variable. Show the exact export command:
+```bash
+export ANTHROPIC_API_KEY="sk-ant-..."
+```
+
+Every provider SDK (anthropic, openai, google-genai, litellm) ships with `repowise`
+itself, so there is no per-provider package to install. If a provider import fails,
+the install is broken rather than incomplete: reinstall with
+`pip install --force-reinstall repowise` and run `repowise doctor`.
+
+## Step 5: Exclusions
+
+Before running the command, ask:
+
+"Any directories or patterns you want to exclude from indexing? Common ones to skip: `vendor/`, `generated/`, large data directories, build artifacts. Your `.gitignore` is already respected automatically. Press Enter to skip."
+
+Add any exclusions as `-x` flags.
+
+## Step 6: Run it
+
+For an unattended or non-interactive run, the canonical command is
+`repowise init --yes`, plus `--no-prose` when you want to guarantee no spend.
+`--yes` suppresses every prompt including the cost gate. You do not need to guard
+against prompts beyond that: init treats an unanswerable question as a signal to
+continue with defaults rather than a reason to fail, and the cost gate declines
+by itself when stdin is not a terminal, keeping the finished index and landing on
+the structural wiki.
+
+Show the user the exact command you're about to run. Ask for confirmation.
+
+Run it. For full mode, note: "This will take a while for the initial indexing. You can Ctrl+C safely — run `{{cmd:init}}` again and I'll use `--resume` to continue where you left off."
+
+## Step 7: Post-setup
+
+After init completes successfully:
+
+1. Confirm the `.repowise/` directory was created
+2. Run `repowise status` to show the summary
+3. Tell the user:
+ - "Repowise has indexed your codebase. The MCP tools are now active — I can answer questions about your architecture, ownership, dependencies, and more."
+ **Only if you did not pass `--no-editor-setup`.** With that flag nothing was
+ registered, so say instead: "The index is built. I did not register it as
+ your global MCP server (this looked like a temporary checkout). The
+ repowise plugin's tools still work here; to make this the repo the MCP
+ server points at, re-run `repowise init` without `--no-editor-setup`."
+ - "Try asking me something like 'how does the auth module work?' or 'what depends on utils.py?'"
+ - "Run `{{cmd:status}}` anytime to check the health of your index."
+ - "Run `{{cmd:update}}` after making code changes to keep the wiki in sync."
+4. If CLAUDE.md was generated (default): "I've also generated a CLAUDE.md with codebase context that I'll read on every session."
diff --git a/plugins/shared/commands/reindex.md b/plugins/shared/commands/reindex.md
new file mode 100644
index 000000000..e7cb865f9
--- /dev/null
+++ b/plugins/shared/commands/reindex.md
@@ -0,0 +1,35 @@
+---
+frontmatter: |
+ description: Rebuild the Repowise vector store by re-embedding all wiki pages. No LLM calls — only embedding API calls.
+ allowed-tools: Bash, Read, AskFollowupQuestion
+---
+
+# Repowise Reindex
+
+Rebuild the vector store (embeddings) without regenerating documentation.
+
+This is useful when:
+- You switched embedding providers
+- The LanceDB vector data got corrupted
+- You want to refresh search quality after adding new wiki pages
+
+## Steps
+
+1. Check if `.repowise/` exists. If not: "This repo isn't indexed yet. Run `{{cmd:init}}` first."
+
+2. Run: `repowise reindex`
+
+ This re-embeds all existing wiki pages into LanceDB. No LLM generation calls — only embedding API calls. Fast and cheap.
+
+## Available flags
+
+- `--embedder gemini|openai|auto` — embedding provider (default: auto-detect from env vars)
+- `--batch-size N` — pages per embedding batch (default: 20)
+
+## Requirements
+
+Requires either `GEMINI_API_KEY`/`GOOGLE_API_KEY` or `OPENAI_API_KEY` to be set. The mock embedder is not accepted for reindexing. If neither key is available, ask the user to set one before proceeding.
+
+## Handling $ARGUMENTS
+
+If $ARGUMENTS contains "full" or "from-scratch", confirm with the user: "This will regenerate ALL documentation from scratch, not just re-embed. It will take as long as the initial indexing and cost API tokens. Are you sure?" If yes: `repowise init --force`
diff --git a/plugins/shared/commands/risk.md b/plugins/shared/commands/risk.md
new file mode 100644
index 000000000..b3474d97f
--- /dev/null
+++ b/plugins/shared/commands/risk.md
@@ -0,0 +1,38 @@
+---
+frontmatter: |
+ description: Score the defect risk of a change — a commit or a base..head range — as a single 0–10 with drivers.
+ allowed-tools: Bash, Read
+---
+
+# Repowise Risk
+
+Score a *change* (not a file) for defect risk. Repowise reads the diff shape —
+lines added/deleted, files, directories, subsystems, change entropy, and author
+familiarity — and returns a 0–10 score with an attributable driver breakdown.
+Pure git + learned constants: no LLM, no network. A natural pre-merge / PR gate.
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `{{cmd:init}}` first." Stop.
+2. Resolve the target from `$ARGUMENTS`, run `repowise risk`, and present the
+ score, level, and top drivers — calling out *why* it's risky (e.g. wide
+ diffusion across subsystems, low author familiarity).
+
+## Choosing the revspec
+
+- No args → `repowise risk` (scores `HEAD`)
+- A commit SHA → `repowise risk <sha>`
+- A range / PR / branch → `repowise risk <base>..<head>` (e.g. `repowise risk main..HEAD`)
+
+Useful flags:
+- `--ext .py,.ts` — only count changes in those file types
+- `-x, --exclude <pattern>` — gitignore-style pattern to drop from the diff (repeatable; also honors a `.riskignore` file)
+- `--format json` — machine-readable score + features + drivers
+- `--path <dir>` — point at a different git repo
+
+## How this differs from the other risk views
+
+- This command = the **whole change** as one number (defect-risk gate).
+- For **per-file** blast radius (what breaks, missing co-changes, missing tests),
+ use the `get_risk` MCP tool / the `change-review` skill.
+- For **per-file health** scores, use `{{cmd:health}}`.
diff --git a/plugins/shared/commands/search.md b/plugins/shared/commands/search.md
new file mode 100644
index 000000000..ac58dfb54
--- /dev/null
+++ b/plugins/shared/commands/search.md
@@ -0,0 +1,47 @@
+---
+frontmatter: |
+ description: Search the Repowise wiki using natural language, full-text, or symbol search.
+ allowed-tools: Bash, Read
+---
+
+# Repowise Search
+
+Search the codebase wiki.
+
+## Usage
+
+If $ARGUMENTS is empty, ask: "What are you looking for? You can search with natural language like 'how does authentication work' or 'where is rate limiting handled'."
+
+If $ARGUMENTS is provided, run:
+```
+repowise search "$ARGUMENTS"
+```
+
+## Search modes
+
+The default mode is `fulltext` (SQLite FTS5). You can specify a mode:
+
+- `--mode fulltext` — fast keyword search (default)
+- `--mode semantic` — vector similarity search using embeddings. Requires an embedding provider to be configured. If this fails with an error, suggest running `{{cmd:reindex}}` first.
+- `--mode symbol` — fuzzy match on symbol names (functions, classes, variables)
+
+Other flags:
+- `--limit N` — max results (default: 10)
+
+## Present results
+
+Show results as a clean list with the page title, type, and a brief snippet.
+
+## When search comes up empty
+
+Search needs wiki pages, and every indexed repo has them: a keyless run renders
+the whole wiki from structure. So an empty result is usually not a missing wiki.
+
+- **No pages at all** means the index never finished, or the repo was indexed
+ with `--mode fast`, which is the one mode that writes no wiki. Suggest
+ `repowise init --yes` (no API key needed), or `repowise init --resume` if a
+ previous run was interrupted.
+- **Pages exist but semantic search finds nothing** means the wiki was embedded
+ with the mock embedder, which keeps full-text search working and leaves
+ semantic search to be built later. Suggest `repowise reindex` with an embedder
+ configured. Full-text and symbol search (`--mode symbol`) work regardless.
diff --git a/plugins/shared/commands/security.md b/plugins/shared/commands/security.md
new file mode 100644
index 000000000..a8cbc8622
--- /dev/null
+++ b/plugins/shared/commands/security.md
@@ -0,0 +1,53 @@
+---
+frontmatter: |
+ description: Scan for security signals — working-tree scanning already runs during init/update; use --history to walk full git history for leaked secrets.
+ allowed-tools: Bash, Read
+---
+
+# Repowise Security
+
+Scan for security signals with the same local pattern registry used during
+`repowise init` / `repowise update`. Working-tree scanning already happens on
+those commands. This slash command is for walking **full git history** to find
+leaked secrets (and optionally risky patterns) that were later removed.
+
+No LLM — pure local scan. Findings persist to `security_findings` and show up
+in the local server security API / UI. Re-runs are idempotent.
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `{{cmd:init}}` first." Stop.
+2. Decide the mode from `$ARGUMENTS` (see below), run the command, and present
+ a short summary (files scanned, findings stored, by severity / kind). Do not
+ print raw secret values if any appear in output — summarize kinds and paths.
+
+## Modes
+
+Default / no useful args — remind the user that working-tree scanning already
+ran during init/update, then offer history mode:
+```
+repowise security scan
+```
+(Without `--history` this prints a hint and exits — it does **not** re-run the
+working-tree scan.)
+
+Handle `$ARGUMENTS`:
+- "history" / "full" / "scan history" → `repowise security scan --history`
+- "json" with history → `repowise security scan --history --output json`
+- "all" / "all-patterns" with history → `repowise security scan --history --all-patterns`
+- A path → `repowise security scan --history --path <dir>`
+- "since <rev>" / "to <rev>" → pass `--since` / `--to` accordingly
+
+```
+repowise security scan --history
+repowise security scan --history --since v1.0.0 --to HEAD
+repowise security scan --history --all-patterns --output json
+```
+
+## Notes
+
+- Default history mode reports **leaked-secret** patterns only
+ (`hardcoded_password` / `hardcoded_secret`) to avoid noise. Pass
+ `--all-patterns` for code-smell patterns (`eval`, `os.system`, weak hashes, …).
+- Never invent findings. If the scan stores zero findings, say so plainly.
+- For change defect risk (not secret scanning), use `{{cmd:risk}}`.
diff --git a/plugins/shared/commands/status.md b/plugins/shared/commands/status.md
new file mode 100644
index 000000000..0e063a292
--- /dev/null
+++ b/plugins/shared/commands/status.md
@@ -0,0 +1,25 @@
+---
+frontmatter: |
+ description: Check the health of your Repowise index — sync state, page counts, provider, and token usage.
+ allowed-tools: Bash, Read
+---
+
+# Repowise Status
+
+Check if Repowise is set up for this project and report its health.
+
+## Steps
+
+1. Check if `.repowise/` directory exists in the project root. If not: "This repo isn't indexed yet. Run `{{cmd:init}}` to set it up."
+
+2. Run: `repowise status`
+
+3. The command outputs two tables:
+ - **Sync State**: last sync commit, total pages, provider, model, total tokens
+ - **Pages by Type**: breakdown by page type (file_page, module_page, etc.) with counts
+
+4. Present the results to the user in a readable summary.
+
+5. If pages exist but no provider is shown, the wiki is template-rendered. Tell the user: "Your wiki is rendered from structure. Run `repowise generate` to upgrade any subset to model-written prose." If total pages is 0, the run did not finish, so suggest `repowise init --resume`.
+
+6. If the user provides arguments like "$ARGUMENTS", check if they're asking for a specific path and pass it: `repowise status $ARGUMENTS`
diff --git a/plugins/shared/commands/symbol.md b/plugins/shared/commands/symbol.md
new file mode 100644
index 000000000..9e51ca00f
--- /dev/null
+++ b/plugins/shared/commands/symbol.md
@@ -0,0 +1,49 @@
+---
+frontmatter: |
+ description: Read one symbol's body with live-verified line bounds (path::Name, live range, or distill omission ref).
+ allowed-tools: Bash, Read
+---
+
+# Repowise Symbol
+
+Read one function, class, or constant with live-verified line bounds. This is
+the CLI adapter over `get_symbol`. Prefer it over a raw file Read when you
+already have a `symbol_id` from `{{cmd:context}}` or `search_codebase`.
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `{{cmd:init}}` first." Stop.
+2. Resolve the symbol id from `$ARGUMENTS`. If empty, ask for
+ `path/to/file.py::Name`, a live range (`path:start-end`), or a
+ `repowise#<hex>` omission ref from distill.
+3. Run `repowise symbol` and present the body. Report `verified: true/false`
+ when shown. If the id is ambiguous, show every matching body — do not
+ silently pick one.
+
+## Choosing the invocation
+
+- Named symbol → `repowise symbol "src/api/routes.py::login"`
+- Live range read → `repowise symbol "src/api/routes.py:140-180"`
+- Distill omission ref → `repowise symbol "repowise#a1b2c3d4e5f6"`
+- Extra surrounding lines → `--context-lines N` (0–50)
+- Filter restored omission lines → `--query <regex-or-substring>`
+- Machine-readable / raw payload → `--format json` / `--full`
+
+```
+repowise symbol "src/api/routes.py::login"
+repowise symbol "src/api/routes.py:140-180"
+repowise symbol "repowise#a1b2c3d4e5f6"
+repowise symbol "src/api/routes.py::login" --context-lines 3
+```
+
+A truncated body carries a `continuation` you can pass straight back to
+`repowise symbol`. Shared targeting flags (`--path`, `--repo`,
+`--no-workspace`) match the other tool-adapter commands.
+
+## Notes
+
+- Cheaper and more precise than Read + offset math when you have a
+ `symbol_id`.
+- For triage (layer / hotspot / callers) without bytes, use
+ `{{cmd:context}}`.
+- Never invent source — if the command errors or returns no body, say so.
diff --git a/plugins/shared/commands/update.md b/plugins/shared/commands/update.md
new file mode 100644
index 000000000..f5eab4829
--- /dev/null
+++ b/plugins/shared/commands/update.md
@@ -0,0 +1,42 @@
+---
+frontmatter: |
+ description: Trigger an incremental Repowise update to sync documentation with recent code changes.
+ allowed-tools: Bash, Read
+---
+
+# Repowise Update
+
+Trigger an incremental update of the Repowise index.
+
+## Steps
+
+1. Check if `.repowise/` exists. If not: "This repo isn't indexed yet. Run `{{cmd:init}}` first."
+
+2. Run: `repowise update`
+
+ This will:
+ - Detect files changed since last sync commit
+ - Update git metadata for changed files
+ - Regenerate affected wiki pages (up to cascade budget of 30)
+ - Decay confidence scores for indirectly affected pages
+ - Update dead code analysis
+ - Update CLAUDE.md if enabled
+
+3. Show the output summary to the user.
+
+## Available flags
+
+- `--provider NAME` — override the LLM provider
+- `--model NAME` — override the model
+- `--since REF` — base git ref to diff from (overrides saved last_sync_commit). Accepts a commit SHA, tag, or branch name.
+- `--cascade-budget N` — max pages to regenerate per run (default: 30)
+- `--dry-run` — show affected pages without regenerating
+- `-v, --verbose` — show the full changed-file list, per-phase internals, and debug logs (the run is quiet by default)
+
+## Handling $ARGUMENTS
+
+If the user provides arguments:
+- "dry-run" or "dry run" → add `--dry-run` flag
+- "force" or "full" → add `--cascade-budget 999` to regenerate all stale pages
+- a git ref like a SHA or tag → add `--since {ref}`
+- a file path → this is not supported by update; suggest `repowise update` which auto-detects changes
diff --git a/plugins/shared/commands/why.md b/plugins/shared/commands/why.md
new file mode 100644
index 000000000..10ed7b9d6
--- /dev/null
+++ b/plugins/shared/commands/why.md
@@ -0,0 +1,49 @@
+---
+frontmatter: |
+ description: Why the code is shaped this way — decisions, rationale, and git archaeology (question, path, or decision-health dashboard).
+ allowed-tools: Bash, Read
+---
+
+# Repowise Why
+
+Answer *why* the code looks the way it does: decision records, rationale, and
+git archaeology. This is the CLI adapter over `get_why`. Worth running before a
+refactor or a deliberate divergence from a pattern.
+
+`{{cmd:decision}}` manages decision records (list / add / confirm). This
+command **queries** why something is shaped a certain way.
+
+## Steps
+
+1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `{{cmd:init}}` first." Stop.
+2. Map `$ARGUMENTS` to a mode (below), run `repowise why`, and present
+ decisions, alignment, and archaeology. Never invent rationale — if the
+ command falls back to git archaeology, say that plainly.
+
+## Modes
+
+- Question → `repowise why "why is auth using JWT?"`
+- File path (governing decisions + origin story) → `repowise why src/api/auth.py`
+- Target-anchored search → `repowise why "why the retry cap?" --target src/api/client.py`
+ (`--target` is repeatable)
+- No args → `repowise why` (decision-health dashboard: stale / proposed /
+ ungoverned hotspots)
+- Machine-readable / raw payload → `--format json` / `--full`
+
+```
+repowise why "why is auth using JWT?"
+repowise why src/api/auth.py
+repowise why "why the retry cap?" --target src/api/client.py
+repowise why
+```
+
+Shared targeting flags (`--path`, `--repo`, `--no-workspace`) match the other
+tool-adapter commands.
+
+## Notes
+
+- Falls back to git archaeology when a path has no decisions, so it is never
+ empty — call that out so the user knows it is reconstructed, not recorded.
+- For *managing* ADR records (add / confirm / deprecate), use
+ `{{cmd:decision}}`.
+- Before contradicting an existing decision, surface it to the user first.
diff --git a/plugins/shared/skills/architectural-decisions.md b/plugins/shared/skills/architectural-decisions.md
new file mode 100644
index 000000000..482e7f116
--- /dev/null
+++ b/plugins/shared/skills/architectural-decisions.md
@@ -0,0 +1,67 @@
+---
+claude-code:
+ dir: architectural-decisions
+ frontmatter: |
+ name: architectural-decisions
+ description: >
+ Use when encountering questions about WHY code is built a certain way, when about to make
+ architectural changes (new patterns, restructuring, choosing between approaches), or when
+ the user asks about design rationale in a Repowise-indexed codebase (.repowise/ directory exists).
+ Also activates when commit messages or code comments contain decision signals like "WHY:",
+ "DECISION:", "TRADEOFF:", "ADR:".
+ user-invocable: false
+codex:
+ dir: architectural-decisions
+ frontmatter: |
+ name: architectural-decisions
+ description: Use when a task asks why code is built a certain way, proposes architectural changes, compares implementation approaches, or mentions decision markers such as WHY, DECISION, TRADEOFF, or ADR in a Repowise-indexed repository.
+---
+
+# Architectural Decisions with Repowise
+
+Repowise captures architectural decisions — the *why* behind how code is built.
+
+`get_why` has four modes — pick by what you pass:
+
+1. `get_why(query="why is auth using JWT?")` — keyword + semantic decision search.
+2. `get_why(query="src/auth/service.py")` — decisions governing that file, plus
+ its origin story and an alignment score (does the file still follow its own ADRs?).
+3. `get_why(query="why was caching added?", targets=["src/auth/cache.py"])` —
+ target-anchored search; decisions touching the targets get boosted.
+4. `get_why()` — the decision-health dashboard.
+
+Decisions are mined from five sources (ADR files, PR and squash-commit bodies,
+inline markers, git archaeology, and centrality-bounded code comments). Each
+rationale traces to a verbatim source span, stamped exact / fuzzy / unverified.
+When no decision exists for a path, `get_why` falls back to git archaeology so
+the call is never empty.
+
+## When the user asks "why is X built this way?"
+
+Call `get_why(query="X")`.
+
+## When about to make an architectural change
+
+1. Call `get_why(query="the specific area you're changing")` to find existing decisions that govern that area.
+2. If decisions are found, present them to the user before proceeding — they may not want to contradict an existing architectural choice.
+3. If no decisions are found, proceed but note that no recorded decision governs this area.
+
+## When called with no specific query
+
+Call `get_why()` with no arguments to get the decision-health dashboard:
+- Stale decisions that may no longer apply
+- Proposed decisions awaiting confirmation
+- Ungoverned hotspots (high-churn files with no recorded decisions)
+
+The same signals surface in the CLI via `repowise decision health` /
+`{{cmd:decision}}`, and you can query *why* mid-task with `repowise why` /
+`{{cmd:why}}` (the `get_why` adapter). Review auto-proposed decisions with
+`repowise decision confirm`.
+
+## When a file has decision markers
+
+If you see `# WHY:`, `# DECISION:`, `# TRADEOFF:`, or `# ADR:` comments in code, call `get_context(targets=["that_file.py"])` to see the full decision record with context and affected modules.
+
+## Recording new decisions
+
+If the user makes an architectural decision during the conversation, suggest: "Want to record this decision? Add a `# DECISION:` comment in the relevant code, or run `repowise decision add` to capture it formally."
diff --git a/plugins/shared/skills/change-review.md b/plugins/shared/skills/change-review.md
new file mode 100644
index 000000000..06174bfd1
--- /dev/null
+++ b/plugins/shared/skills/change-review.md
@@ -0,0 +1,114 @@
+---
+claude-code:
+ dir: change-review
+ frontmatter: |
+ name: change-review
+ description: >
+ Use when reviewing a set of changes before they merge — a PR, a branch diff, or the working-tree
+ changes you just made — in a Repowise-indexed codebase (.repowise/ directory exists). Activates
+ for "review this PR", "is this safe to merge", "what's the blast radius of these changes", "did I
+ miss anything", or "what else should change with this".
+ user-invocable: false
+codex:
+ dir: change-review
+ frontmatter: |
+ name: change-review
+ description: Use when reviewing a set of changes before they merge in a Repowise-indexed repository, a PR, a branch diff, or the working-tree changes you just made. Activates for "review this PR", "is this safe to merge", "what is the blast radius of these changes", or "did I miss anything".
+---
+
+# Change Review with Repowise
+
+When a diff is on the table, Repowise turns "what files changed" into "what does
+this change put at risk" — fusing git history (churn, ownership, co-change) with
+graph topology (dependents, impact surface), test gaps, security signals, and the
+architectural decisions that govern the touched code.
+
+Two complementary risk signals, use both:
+
+- **`get_change_risk(revspec=…)` (MCP)** scores the *whole change as one unit* (a
+ commit or a `base..head` range) from its diff shape: a single 0-10 defect-risk
+ score with drivers (lines added/deleted, files, directories, subsystems,
+ change entropy, author familiarity). No LLM, no network. Prefer this in-MCP
+ tool; it takes a revspec and diffs server-side, so you never shell out. Lead
+ with `risk_percentile` (this change ranked against sampled recent commits),
+ summarized by `review_priority` and `classification`; `score` / `level` are
+ the corpus-calibrated fallback. This is the pre-merge gate: "how risky is this
+ change overall?" The `repowise risk <revspec>` CLI is the identical scorer for
+ when you are already in a terminal.
+- **`get_risk(changed_files=…)` (MCP)** works *per file* and returns the
+ `directive` block, the specific things to check inside the diff.
+
+## Score the whole change first
+
+```
+get_change_risk(revspec="main..HEAD") # HEAD, a commit SHA, or base..head
+```
+
+Read `risk_percentile` and the top drivers: a high score from large diffusion
+(many dirs/subsystems) or low author familiarity tells you where to look
+hardest. `extensions=[".py", ".ts"]` counts only certain file types;
+`exclude_patterns=["tests/"]` omits paths. A `warning` field means the revspec
+or filters matched no files, so an all-zero score there is not a clean bill of
+health. The equivalent from a terminal is `repowise risk <revspec>` (add
+`--ext .py,.ts` or `--format json`).
+
+## Then drill into the directive block
+
+Call `get_risk` in **PR mode** by passing the changed files:
+
+```
+get_risk(targets=<changed files>, changed_files=<same changed files>)
+```
+
+The response carries a `directive` block — read it first, it's a few short lists:
+
+- **`will_break`** — files/symbols that depend on what changed but are *not* in
+ the diff. These are the likely breakages. Check each one.
+- **`missing_cochanges`** — files that historically change together with the
+ changed files but were left untouched. Often a forgotten update.
+- **`missing_tests`** — changed code with a test gap. Flag for new/updated tests.
+- **`tests_to_run`** — the positive complement of `missing_tests`: the tests the
+ per-test coverage map proves execute the changed files (pytest-runnable ids).
+ Recommend running these to validate the change. Empty until a coverage map is
+ ingested (`repowise coverage add`); empty is "unknown", never "no tests exist".
+
+`pr_blast_radius` holds the fuller dossier behind those lists (including the
+per-changed-file `guarding_tests` breakdown behind `tests_to_run`).
+
+For the line-precise version from a terminal, `repowise impacted-tests <revspec>`
+maps each changed line to the tests whose recorded coverage touches it, then
+prints the ids (`--format list | xargs pytest` runs exactly them). It is honest
+about gaps: a changed file with no coverage rows is a labelled filename guess,
+and a brand-new file is "unknown, run the full suite", never "no tests needed".
+
+## Then go deeper where it matters
+
+1. **Why does this code exist?** For any non-trivial changed file, call
+ `get_why(query="<file>")` — don't let a change silently contradict a recorded
+ architectural decision. Surface `conflicts_with` / `supersedes` hits.
+2. **Did the change make health worse?** `get_health(targets=<changed files>,
+ include=["biomarkers"])` — call out new complexity, deep nesting, or
+ duplication the diff introduced.
+3. **Who should review?** `get_risk` ownership + co-change signals suggest the
+ people with the most context on the touched code.
+
+## Getting the diff
+
+- A GitHub PR: `gh pr diff <number>` (or `gh pr view <number> --json files`).
+- A branch: `git diff --name-only main...HEAD`.
+- Working tree: `git status --porcelain`.
+- CLI shortcut for a range: `repowise risk main..HEAD` scores a branch/PR range
+ for defect risk directly.
+
+## Write the review around evidence
+
+Lead with a risk level and the `directive` findings, each tied to a concrete
+file. Distinguish **"will break"** (a dependent outside the diff) from **"worth a
+look"** (a co-change or health regression). Don't pad with findings the tools
+didn't support.
+
+## Error handling
+
+If `get_risk` errors or returns nothing, the MCP server may be down or the repo
+unindexed — say so and review from the raw diff, noting that Repowise context was
+unavailable. Suggest `{{cmd:init}}` if the repo isn't indexed.
diff --git a/plugins/shared/skills/code-health.md b/plugins/shared/skills/code-health.md
new file mode 100644
index 000000000..1c9690abf
--- /dev/null
+++ b/plugins/shared/skills/code-health.md
@@ -0,0 +1,75 @@
+---
+claude-code:
+ dir: code-health
+ frontmatter: |
+ name: code-health
+ description: >
+ Use when the user asks about code health, code quality, complexity, technical debt, which files
+ are risky or hard to maintain, what to refactor next, untested hotspots, or coverage gaps in a
+ Repowise-indexed codebase (.repowise/ directory exists). Also use to get a before/after health
+ read when planning or finishing a refactor.
+ user-invocable: false
+codex:
+ dir: code-health
+ frontmatter: |
+ name: code-health
+ description: Use when the user asks about code health, code quality, complexity, technical debt, risky or hard-to-maintain files, what to refactor next, untested hotspots, or coverage gaps in a Repowise-indexed codebase (.repowise/ directory exists). Also use for before/after health reads when planning or finishing a refactor.
+---
+
+# Code Health with Repowise
+
+Repowise scores **every file 1–10** from deterministic markers — McCabe
+complexity, deep nesting, brain methods, class cohesion (LCOM4), god classes,
+clone detection, untested hotspots, function-level churn, ownership dispersion,
+and more. Zero LLM calls; pure local analysis. The weights are calibrated
+against a real defect corpus, so a low score means *more likely to harbour bugs*,
+not just *bigger*.
+
+## Pick the mode by what you pass
+
+- **Dashboard** — `get_health()` (no targets): a `directive` naming what to fix
+ first, then repo-level KPIs and the lowest-scoring files. Start here for "how
+ healthy is this codebase?" or "what should we clean up?".
+- **Targeted** — `get_health(targets=["src/x.py", "src/y.py"])`: per-file score
+ and the specific marker findings driving it. Use before/after a refactor,
+ or to explain *why* a file is flagged.
+
+## Useful `include` flags
+
+`get_health(targets=[...], include=[...])`:
+- `"biomarkers"` — always return the findings list (what's wrong, where).
+- `"refactoring"` — deterministic, ranked refactoring suggestions (by impact/effort).
+- `"coverage"` — surface coverage data when it's been ingested.
+- `"trend"` — recent health snapshots + declining / predicted-decline signal.
+
+`include` adds blocks; `only=[...]` subtracts them.
+
+## How to use the results
+
+1. For "what should I refactor?" → dashboard mode, lead with `directive`, then
+ `get_health(targets=[worst files], include=["refactoring"])` and present the
+ ranked plans, not just the scores.
+2. Rank by `weighted_deficit`, not `score` — the score floors at 1.0.
+3. For a specific file → report the score, the top 2–3 marker findings, and
+ what each one means in plain language. Avoid dumping the raw payload.
+4. Check `unresolved` before calling a file clean: a target listed there matched
+ nothing, and `not_indexed` means run `repowise update`.
+5. Before editing a flagged file → cross-check `get_risk(targets=[...])`; a file
+ that is both low-health *and* a churn hotspot deserves the most care.
+6. Untested-hotspot / coverage questions → tell the user coverage markers
+ light up once they ingest a report: `repowise coverage add cov.lcov`
+ (LCOV / Cobertura / Clover; a coverage.py `.coverage` also builds the
+ per-test map), then re-run `repowise health`.
+
+## CLI equivalents
+
+- `repowise health` — KPIs + lowest-scoring files
+- `repowise health --refactoring-targets` — ranked by impact / effort
+- `repowise health --trend` — snapshots + declining alerts
+- `repowise coverage add <file>` — ingest coverage, light up untested-hotspot
+
+## Error handling
+
+If `get_health` reports no repository, suggest `{{cmd:init}}`. Code health is
+computed even with a template-rendered wiki (no LLM needed), so it should be available
+whenever the repo is indexed.
diff --git a/plugins/shared/skills/codebase-exploration.md b/plugins/shared/skills/codebase-exploration.md
new file mode 100644
index 000000000..f0b0ebb36
--- /dev/null
+++ b/plugins/shared/skills/codebase-exploration.md
@@ -0,0 +1,74 @@
+---
+claude-code:
+ dir: codebase-exploration
+ frontmatter: |
+ name: codebase-exploration
+ description: >
+ Use when exploring, understanding, or answering questions about a codebase that has Repowise
+ indexed (a .repowise/ directory in the project root). Activates for "how does X work",
+ "explain the architecture", "where is Y implemented", "what does this module do", or any task
+ that needs an understanding of structure before diving into source files.
+ user-invocable: false
+codex:
+ dir: codebase-exploration
+ frontmatter: |
+ name: codebase-exploration
+ description: Use when exploring, understanding, or answering questions about a Repowise-indexed codebase, including architecture, where code is implemented, how a module works, or which files are relevant before reading source.
+---
+
+# Codebase Exploration with Repowise
+
+This project has a Repowise intelligence layer. Before grepping and reading raw
+source to understand the codebase, reach for the Repowise MCP tools — they
+return documentation, ownership, history, decisions, and graph structure that
+plain file reads don't, usually in one round-trip instead of many.
+
+## Which tool for which question
+
+| You want… | Call |
+|---|---|
+| First orientation in an unfamiliar repo | `get_overview()` — architecture summary, key modules, entry points, git health, knowledge map. Skip it once you have the map. |
+| A direct answer to "how/where/why does X work" | `get_answer(question="…")` — synthesised answer with citations + a `retrieval_quality` signal. Collapses the search → read → reason loop. |
+| Find a symbol, file, or fuzzy concept | `search_codebase(query="…")` — hybrid search. `mode="auto"` routes an identifier to indexed symbol hits (`symbol_id`/line bounds → pipe into `get_symbol`), a path to file pages (→ `get_context`), and prose to semantic wiki search (each hit reports `search_method`: `embedding` vs `bm25`). Force a branch with `mode=symbol\|path\|concept\|hybrid`; narrow symbols with `symbol_kind`. |
+| A triage card for specific files/symbols | `get_context(targets=[…])` — title, summary, signatures, hotspot bit, top callers, decision titles, symbol_ids. Batch many targets in one call. |
+| The actual source of one symbol | `get_symbol("path/to/file.py::Name")` — exact bytes with line bounds. Cheaper than Read + offset math. Use a `symbol_id` from `get_context`. |
+
+## Recommended flow
+
+1. New area you don't know → `get_overview()` once.
+2. A specific question → `get_answer(question=…)` first.
+ - High confidence → answer it, cite the paths.
+ - `medium`/`low` confidence → follow `best_guesses[0].file` or
+ `fallback_targets[0]` into `get_context`, then `get_symbol` for bytes.
+3. A named symbol or a path → `search_codebase(query="Name")` /
+ `search_codebase(query="path/to/file.py")`; symbol hits pipe straight into
+ `get_symbol`, file hits into `get_context`.
+4. More files around a concept → `search_codebase`, then `get_context` on the
+ hits (batched), then `get_symbol` only for the bodies you actually need.
+
+Fall back to raw Read/Grep only when the indexed context doesn't cover the
+specific detail the user asked about.
+
+## Trust signals — verify when
+
+- `_meta.stale_warning` is present (the index has diverged from HEAD), or
+- `retrieval_quality` is `partial`/`weak`, or
+- a result's `search_method` is `bm25`.
+
+Otherwise the response is current — act on it.
+
+## Error handling
+
+- "No repositories found. Run 'repowise init' first." → suggest `{{cmd:init}}`.
+ Add `--no-editor-setup` if this repo is a scratch clone, a fixture, or a
+ worktree: `init` otherwise repoints the user's single global `repowise` MCP
+ entry at it.
+- MCP tools unavailable → prefer the matching CLI slash commands when the
+ plugin is installed (`{{cmd:ask}}`, `{{cmd:context}}`, `{{cmd:symbol}}`,
+ `{{cmd:search}}`) rather than grepping blind.
+- `get_answer`/`search_codebase` come back empty → the repo may have a
+ template-rendered wiki. Fall back to `get_context` with explicit paths, and note
+ that model-written pages (`repowise generate`, or `{{cmd:init}}` with an LLM
+ provider) unlock richer docs + semantic search.
+- Tools fail to connect at all → the `repowise` binary may not be installed;
+ suggest `{{cmd:init}}`.
diff --git a/plugins/shared/skills/dead-code-cleanup.md b/plugins/shared/skills/dead-code-cleanup.md
new file mode 100644
index 000000000..d53ea50a5
--- /dev/null
+++ b/plugins/shared/skills/dead-code-cleanup.md
@@ -0,0 +1,50 @@
+---
+claude-code:
+ dir: dead-code-cleanup
+ frontmatter: |
+ name: dead-code-cleanup
+ description: >
+ Use when the user asks about cleanup, removing unused code, refactoring, reducing bundle size,
+ or identifying dead code in a Repowise-indexed codebase (.repowise/ directory exists). Also
+ activates when discussing technical debt, code hygiene, or repository maintenance.
+ user-invocable: false
+codex:
+ dir: dead-code-cleanup
+ frontmatter: |
+ name: dead-code-cleanup
+ description: Use when the user asks about unused code, cleanup, deleting files or exports, refactoring old areas, reducing bundle size, code hygiene, technical debt, or maintenance in a Repowise-indexed repository.
+---
+
+# Dead Code Cleanup with Repowise
+
+Repowise detects dead code through graph analysis — no LLM needed, works even with a template-rendered wiki.
+
+## When the user asks about dead/unused code
+
+Call `get_dead_code()` to get findings sorted by confidence tier. Useful parameters:
+- `safe_only=true` — only findings confirmed safe to delete (confidence >= 0.7)
+- `kind="unreachable_file"` — files with no importers
+- `kind="unused_export"` — public symbols nobody uses
+- `kind="zombie_package"` — monorepo packages with no consumers
+- `directory="src/old/"` — limit to a specific directory
+- `tier="high"` — only high-confidence findings (>= 0.8)
+- `min_confidence=0.7` — raise the floor (default is 0.5) for a release-ready cleanup
+- `group_by="directory"` or `group_by="owner"` — roll up to see where the dead code concentrates and who owns the most of it
+
+## How to present findings
+
+- Only suggest deletion for findings with `safe_to_delete: true`
+- For lower-confidence findings, present them as "candidates to investigate" not "things to delete"
+- Dynamically-loaded code (plugins, handlers, adapters) may appear as dead code but isn't — Repowise filters common patterns but edge cases exist
+
+## Before deleting anything
+
+1. Confirm with the user. Present the file/symbol name, confidence score, and why Repowise thinks it's dead.
+2. Call `get_risk(targets=["path/to/file"])` to double-check dependents.
+3. Recently-modified "dead" code is more likely a false positive — flag this if the finding has recent git activity.
+
+## Safe deletion order
+
+1. Unreachable files first (whole file removal, cleanest)
+2. Unused internal symbols next
+3. Unused exports last (highest false-positive risk due to potential dynamic imports)
diff --git a/plugins/shared/skills/pre-modification.md b/plugins/shared/skills/pre-modification.md
new file mode 100644
index 000000000..f61bed981
--- /dev/null
+++ b/plugins/shared/skills/pre-modification.md
@@ -0,0 +1,64 @@
+---
+claude-code:
+ dir: pre-modification
+ frontmatter: |
+ name: pre-modification-check
+ description: >
+ Use before modifying, refactoring, or deleting files in a codebase that has Repowise indexed
+ (indicated by a .repowise/ directory). Activates when Claude is about to edit code, especially
+ shared utilities, core modules, or files the user didn't explicitly mention. Helps assess
+ impact and avoid breaking things.
+ user-invocable: false
+codex:
+ dir: pre-modification-check
+ frontmatter: |
+ name: pre-modification-check
+ description: Use before modifying, refactoring, moving, or deleting files in a Repowise-indexed repository, especially shared utilities, core modules, public APIs, or files the user did not explicitly identify.
+---
+
+# Pre-Modification Check with Repowise
+
+Before modifying files in a Repowise-indexed codebase, assess the impact.
+
+## Before editing a file
+
+Call `get_risk(targets=["path/to/file.py"])`. Per file it returns
+`hotspot_score`, `trend`, `risk_type`, `impact_surface` (top 3),
+`dependents_count`, `co_change_partners`, `primary_owner`, `bus_factor`,
+`test_gap`, and `security_signals`. Read it for:
+- **Bug-fix history** (`defect_profile`) — present only on files with counted
+ fixes: `fix_count` over the trailing 6 months, `last_fix_days_ago`, a
+ `bug_magnet` flag for sustained recent fix pressure, and `top_symbols` (the
+ per-symbol counts are approximate — read them as "mostly here"). A file that
+ keeps getting fixed is the strongest single signal that the next edit breaks
+ something; lead with it.
+- **Hotspot status** (`hotspot_score`, `trend`) — high-churn × complex? Extra care needed.
+- **Dependents** (`dependents_count`, `impact_surface`) — how wide is the blast radius?
+- **Co-change partners** — files that change together with this one (often without an import link); you may need to update them too.
+- **Ownership / bus factor** — who owns it, and whether a single author maintains it.
+- **Test gap & security signals** — flag untested or security-sensitive files before touching them.
+
+## When modifying multiple files
+
+Batch all targets into one call: `get_risk(targets=["file1.py", "file2.py", "module/"])`.
+
+## When to warn the user
+
+If `get_risk` shows:
+- A `defect_profile` with `bug_magnet` set — say so plainly: this file has been fixed repeatedly and recently
+- Hotspot score above 90th percentile — mention this is a frequently-changed, high-risk file
+- More than 10 dependents — list the top dependents; API changes here will break consumers
+- Bus factor of 1 — note that a single person maintains this code
+- Risk type is "bug-prone" or "high-coupling" — flag explicitly before making changes
+
+## Before refactoring or moving code
+
+Call `get_context(targets=["file.py"])` first to understand the full context: what uses this file, what decisions govern it, and why it's structured this way. This prevents accidentally violating architectural decisions.
+
+For a heavy refactor, also call `get_health(targets=["file.py"])` — the
+marker findings (complexity, deep nesting, low cohesion, duplication) tell
+you *what* to improve while you're in there, and give you a before/after score.
+
+## Error handling
+
+If `get_risk` returns a tool error, the MCP server may not be running. Proceed with the modification but note that risk assessment was unavailable.
diff --git a/pyproject.toml b/pyproject.toml
index 03bd5a8f0..0e9496d34 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -152,6 +152,12 @@ namespaces = true
# core (the neutral home shared by cli + server). Kept in sync with the
# canonical docs/CHANGELOG.md by a drift-guard test (see tests/unit/upgrade).
"repowise.core.upgrade" = ["_data/CHANGELOG.md"]
+# Codex slash commands. A Codex plugin manifest has no slot for commands, so
+# ~/.codex/prompts is the only surface that yields one and the CLI is the only
+# thing that can write it, which means the content has to be in the wheel.
+# Generated from plugins/shared/commands/ by scripts/gen_plugin_content.py and
+# pinned by tests/unit/cli/test_plugin_content.py.
+"repowise.cli.agent_targets" = ["_data/codex_prompts/*.md"]
# ---------------------------------------------------------------------------
# uv workspace (kept for local development)
diff --git a/scripts/gen_plugin_content.py b/scripts/gen_plugin_content.py
new file mode 100644
index 000000000..ba1e3b759
--- /dev/null
+++ b/scripts/gen_plugin_content.py
@@ -0,0 +1,321 @@
+"""Render the plugin skills and commands both hosts ship, from one shared source.
+
+``plugins/codex/skills/`` used to be a hand-copy of ``plugins/claude-code/skills/``
+and had already drifted: descriptions rewritten, headings retitled, one directory
+renamed. Nothing detected it, because two files that say roughly the same thing in
+different words look fine from either side alone. The bodies live in
+``plugins/shared/`` now and every host artifact is rendered from them, so a drift
+is a regenerate rather than a second hand-edit.
+
+What is deliberately *not* here: a manifest-driven generator with platform
+descriptors and fragment slots. That earns its place at roughly six hosts; we have
+two. What is borrowed from that design is the render discipline, which costs
+nothing and is what makes a golden test possible at all:
+
+* fixed slot order (frontmatter, blank line, body),
+* LF newlines regardless of the checkout's line-ending style,
+* and **never** a timestamp, a version or a generator banner in a rendered file,
+ a file that changes when nothing changed cannot be a golden.
+
+Run ``python scripts/gen_plugin_content.py`` to write, ``--check`` to diff without
+writing. ``tests/unit/cli/test_plugin_content.py`` runs the same renderer and fails
+when a rendered file on disk has drifted from the shared source.
+
+The shared source format, one file per item:
+
+ ---
+ frontmatter: | # used by every host that has no override
+ description: ...
+ claude-code: # optional per-host block
+ dir: pre-modification # output directory, when the hosts disagree
+ frontmatter: | # replaces the shared block entirely
+ name: ...
+ ---
+
+ <body, shared by every host>
+
+Bodies may reference a slash command as ``{{cmd:risk}}``; each host renders it in
+its own syntax. Frontmatter is stored verbatim rather than as parsed keys so a
+rendered file reproduces byte for byte, folded scalars and all.
+"""
+
+from __future__ import annotations
+
+import argparse
+import contextlib
+import re
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+
+import yaml
+
+ROOT = Path(__file__).resolve().parents[1]
+SHARED = ROOT / "plugins" / "shared"
+
+#: Codex prompts ship inside the wheel rather than in ``plugins/codex/``. Codex's
+#: plugin manifest has no slot for commands. A plugin may bundle ``skills/``,
+#: ``hooks/``, ``assets/``, ``.mcp.json`` and ``.app.json``, and nothing else, so
+#: the only surface that produces a Codex slash command is ``~/.codex/prompts/``,
+#: which is local-only and written by the CLI. Package data is therefore the one
+#: copy that actually reaches a user, and it follows the precedent already set by
+#: the bundled ``repowise.core.upgrade`` changelog.
+CODEX_PROMPT_DATA = (
+ ROOT / "packages" / "cli" / "src" / "repowise" / "cli" / "agent_targets" / "_data" / "codex_prompts"
+)
+
+
+@dataclass(frozen=True)
+class Host:
+ """Where one host's files go, and how it spells the things hosts spell differently."""
+
+ id: str
+ skills_root: Path
+ commands_root: Path
+ #: ``{id}`` is the shared item's stem.
+ command_filename: str
+ #: How this host writes a reference to its own slash command.
+ command_reference: str
+ #: Frontmatter keys the host understands for a *command*. ``None`` means all
+ #: of them. Codex prompt frontmatter defines ``description`` and
+ #: ``argument-hint`` only, so anything else (``allowed-tools``, a Claude Code
+ #: field) is dropped rather than emitted as a key the host will not read.
+ command_frontmatter_keys: frozenset[str] | None = None
+
+
+HOSTS: tuple[Host, ...] = (
+ Host(
+ id="claude-code",
+ skills_root=ROOT / "plugins" / "claude-code" / "skills",
+ commands_root=ROOT / "plugins" / "claude-code" / "commands",
+ command_filename="{id}.md",
+ command_reference="/repowise:{id}",
+ ),
+ Host(
+ id="codex",
+ skills_root=ROOT / "plugins" / "codex" / "skills",
+ commands_root=CODEX_PROMPT_DATA,
+ # Namespaced, because ~/.codex/prompts is a flat global directory shared
+ # with every other tool the user has installed.
+ command_filename="repowise-{id}.md",
+ command_reference="/prompts:repowise-{id}",
+ command_frontmatter_keys=frozenset({"description", "argument-hint"}),
+ ),
+)
+
+
+# ---------------------------------------------------------------------------
+# Shared source
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class Item:
+ """One skill or command, as authored in ``plugins/shared/``."""
+
+ id: str
+ source: Path
+ meta: dict
+ body: str
+
+ def frontmatter_for(self, host: Host) -> str:
+ block = self.meta.get(host.id, {})
+ text = block.get("frontmatter") or self.meta.get("frontmatter")
+ if not text:
+ raise ValueError(f"{self.source}: no frontmatter for host {host.id!r}")
+ return text
+
+ def directory_for(self, host: Host) -> str:
+ return self.meta.get(host.id, {}).get("dir", self.id)
+
+
+_FRONTMATTER = re.compile(r"\A---\n(.*?\n)---\n+", re.S)
+_TOKEN = re.compile(r"\{\{cmd:([a-z0-9-]+)\}\}")
+_KEY_LINE = re.compile(r"\A([A-Za-z][A-Za-z0-9_-]*):")
+
+
+def load_item(path: Path) -> Item:
+ text = path.read_text(encoding="utf-8").replace("\r\n", "\n")
+ match = _FRONTMATTER.match(text)
+ if match is None:
+ raise ValueError(f"{path}: shared content must open with a --- frontmatter block")
+ meta = yaml.safe_load(match.group(1)) or {}
+ if not isinstance(meta, dict):
+ raise ValueError(f"{path}: frontmatter must be a mapping")
+ return Item(id=path.stem, source=path, meta=meta, body=text[match.end() :])
+
+
+def load_items(kind: str) -> list[Item]:
+ """Every shared item of *kind*, in id order.
+
+ Sorted, because the render has to be reproducible and a directory listing is
+ not ordered the same way on every filesystem.
+ """
+ return [load_item(path) for path in sorted((SHARED / kind).glob("*.md"))]
+
+
+# ---------------------------------------------------------------------------
+# Render
+# ---------------------------------------------------------------------------
+
+
+def select_keys(frontmatter: str, allowed: frozenset[str] | None) -> str:
+ """Drop top-level frontmatter keys *allowed* does not name.
+
+ Line-based rather than parse-and-redump, because the stored text is verbatim
+ and re-emitting it through a YAML dumper would reflow folded scalars, which
+ turns every render into a diff and defeats the golden. A continuation line
+ (indented, or blank inside a folded scalar) follows whichever key is open, so
+ dropping a multi-line value takes its continuations with it.
+ """
+ if allowed is None:
+ return frontmatter
+ kept: list[str] = []
+ keeping = False
+ for line in frontmatter.splitlines(keepends=True):
+ key = _KEY_LINE.match(line)
+ if key is not None:
+ keeping = key.group(1) in allowed
+ if keeping:
+ kept.append(line)
+ return "".join(kept)
+
+
+def render(item: Item, host: Host, *, frontmatter_keys: frozenset[str] | None) -> str:
+ frontmatter = select_keys(item.frontmatter_for(host), frontmatter_keys)
+ if not frontmatter.strip():
+ raise ValueError(f"{item.source}: nothing left of the frontmatter for host {host.id!r}")
+ body = _TOKEN.sub(lambda m: host.command_reference.format(id=m.group(1)), item.body)
+ return f"---\n{frontmatter}---\n\n{body}"
+
+
+def rendered_files() -> dict[Path, str]:
+ """Every generated file, mapped to the text it should hold."""
+ out: dict[Path, str] = {}
+ for host in HOSTS:
+ for item in load_items("skills"):
+ path = host.skills_root / item.directory_for(host) / "SKILL.md"
+ # No key filter: skill frontmatter is authored per host in the
+ # shared file, so it already says what that host understands.
+ out[path] = render(item, host, frontmatter_keys=None)
+ for item in load_items("commands"):
+ path = host.commands_root / host.command_filename.format(id=item.id)
+ out[path] = render(item, host, frontmatter_keys=host.command_frontmatter_keys)
+ return out
+
+
+def orphaned_files() -> list[Path]:
+ """Generated files on disk that no shared source produces any more, sorted.
+
+ ``rendered_files`` says what *should* exist and nothing compared it to what
+ *does*, so deleting a shared source left both rendered copies behind and
+ ``--check`` called the tree clean. The consequences are not cosmetic: a
+ retired command keeps shipping in the wheel and keeps being written into
+ ``~/.codex/prompts`` on every install, and renaming a ``dir:`` override
+ leaves the old ``SKILL.md`` for the host to load as a *second* skill with the
+ same name, a small version of the hand-fork this whole file exists to close.
+
+ Scoped by *content*, not by location. Globbing the directory and deleting
+ everything unrecognised reaches a `README.md` a host directory carries, or a
+ command somebody hand-maintains, silently and unprompted, on a plain
+ regenerate. Every file this script writes opens with a `---` frontmatter
+ fence, so requiring one is a cheap ownership test that a README fails and a
+ generated artifact cannot.
+ """
+ expected = set(rendered_files())
+ found: list[Path] = []
+ for host in HOSTS:
+ candidates = [
+ *sorted(host.skills_root.glob("*/SKILL.md")),
+ *sorted(host.commands_root.glob("*.md")),
+ ]
+ for path in candidates:
+ if path in expected:
+ continue
+ try:
+ if path.read_text(encoding="utf-8").startswith("---\n"):
+ found.append(path)
+ except (OSError, ValueError):
+ # Unreadable or not UTF-8: not something this script wrote, and
+ # certainly not something to delete on a guess.
+ continue
+ return found
+
+
+# ---------------------------------------------------------------------------
+# Write
+# ---------------------------------------------------------------------------
+
+
+def write_if_changed(path: Path, text: str) -> bool:
+ """Write *text* as LF, and report whether it moved the file.
+
+ The comparison normalises the file's line endings first. This repo is checked
+ out with ``core.autocrlf`` on Windows, so an untouched generated file reads
+ back as CRLF, so comparing raw bytes would rewrite all thirty on every
+ run and report a drift that does not exist. Git stores LF either way.
+ """
+ if path.exists() and path.read_text(encoding="utf-8").replace("\r\n", "\n") == text:
+ return False
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with open(path, "w", encoding="utf-8", newline="\n") as handle:
+ handle.write(text)
+ return True
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument(
+ "--check",
+ action="store_true",
+ help="report drift and exit non-zero instead of writing",
+ )
+ args = parser.parse_args(argv)
+
+ files = rendered_files()
+ drifted: list[Path] = []
+ for path in sorted(files):
+ text = files[path]
+ if args.check:
+ current = (
+ path.read_text(encoding="utf-8").replace("\r\n", "\n") if path.exists() else None
+ )
+ if current != text:
+ drifted.append(path)
+ elif write_if_changed(path, text):
+ drifted.append(path)
+
+ orphans = orphaned_files()
+ if not args.check:
+ for path in orphans:
+ with contextlib.suppress(OSError):
+ path.unlink()
+ # Only a *skill* owns its directory. Doing this for every orphan
+ # removed the commands root itself once the last command retired,
+ # including the Codex package-data directory, after which
+ # ``bundled_prompts`` raised FileNotFoundError out of ``install``.
+ # ``rmdir`` refuses a non-empty directory, so a skill that also
+ # carried assets keeps them.
+ if path.name == "SKILL.md":
+ with contextlib.suppress(OSError):
+ path.parent.rmdir()
+
+ verb = "stale" if args.check else "wrote"
+ for path in drifted:
+ print(f"{verb}: {path.relative_to(ROOT).as_posix()}")
+ for path in orphans:
+ print(f"{'orphaned' if args.check else 'removed'}: {path.relative_to(ROOT).as_posix()}")
+ if args.check and (drifted or orphans):
+ print(
+ f"\n{len(drifted) + len(orphans)} generated file(s) disagree with "
+ "plugins/shared/. Run: python scripts/gen_plugin_content.py",
+ file=sys.stderr,
+ )
+ return 1
+ if not drifted and not orphans:
+ print("up to date" if args.check else "no changes")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/unit/cli/test_agent_drift_control.py b/tests/unit/cli/test_agent_drift_control.py
new file mode 100644
index 000000000..4819eeaee
--- /dev/null
+++ b/tests/unit/cli/test_agent_drift_control.py
@@ -0,0 +1,515 @@
+"""Three drift leaks that were silent, and the machinery that makes them speak.
+
+Grouped because they share one shape: something the CLI wrote, or something the
+CLI cannot write, goes out of date and nothing says so. Silence is the failure
+mode in each case, so every test here asserts on an *observable*: a doctor issue,
+a file on disk, a call count. Never on "the function returned".
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from repowise.cli import __version__
+from repowise.cli.agent_targets.targets import claude_code, codex
+from repowise.cli.agent_targets.types import FileAction, Scope
+
+
+def fake_home(tmp_path, monkeypatch) -> Path:
+ """A redirected home, per the standing trap.
+
+ ``HOMEDRIVE``/``HOMEPATH`` go with ``USERPROFILE`` because both Claude config
+ paths derive from ``Path.home()``, and ``Path.home`` itself is patched so a
+ module that already resolved it cannot reach the real one.
+ """
+ home = tmp_path / "home"
+ home.mkdir()
+ 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)
+ monkeypatch.delenv("REPOWISE_SKIP_EDITOR_SETUP", raising=False)
+ return home
+
+
+# ---------------------------------------------------------------------------
+# Leak 1 (installed half): Codex slash commands
+# ---------------------------------------------------------------------------
+
+
+def test_codex_prompts_are_installed_into_the_only_place_codex_reads(fake_home) -> None:
+ written = codex.write_prompts()
+
+ bundled = dict(codex.bundled_prompts())
+ assert bundled, "no Codex prompts are bundled in the wheel"
+ assert {w.path.name for w in written} == set(bundled)
+ assert all(w.action is FileAction.CREATED for w in written)
+
+ # Asserted on the generated files, not the return value: a renderer can be
+ # perfectly correct about text nobody wrote to disk.
+ for name, text in bundled.items():
+ landed = codex.user_prompts_dir() / name
+ assert landed.read_text(encoding="utf-8").replace("\r\n", "\n") == text
+ assert name.startswith(codex.PROMPT_PREFIX), (
+ "~/.codex/prompts is a flat global directory shared with every other "
+ "tool the user has installed"
+ )
+
+
+def test_reinstalling_prompts_reports_unchanged_rather_than_rewriting(fake_home) -> None:
+ codex.write_prompts()
+ again = codex.write_prompts()
+
+ assert {w.action for w in again} == {FileAction.UNCHANGED}
+
+
+def test_a_hand_edited_prompt_is_restored(fake_home) -> None:
+ codex.write_prompts()
+ edited = codex.user_prompts_dir() / "repowise-risk.md"
+ edited.write_text("clobbered", encoding="utf-8")
+
+ actions = {w.path.name: w.action for w in codex.write_prompts()}
+
+ assert actions["repowise-risk.md"] is FileAction.UPDATED
+ assert "clobbered" not in edited.read_text(encoding="utf-8")
+
+
+def test_uninstall_removes_what_repowise_ships_and_leaves_the_rest(fake_home) -> None:
+ """The prefix is a namespace, not a proof of ownership.
+
+ `repowise-my-team-workflow.md` is the obvious name for a prompt a user writes
+ themselves *about* repowise, and it lives in the same global directory. An
+ uninstall that globbed `repowise-*.md` deleted it, unrecoverably. The cost of
+ the narrow rule is the retired-command file below, which is the right way
+ round: a stale file of ours is a wasted kilobyte.
+ """
+ codex.write_prompts()
+ prompts = codex.user_prompts_dir()
+ theirs = prompts / "repowise-my-team-workflow.md"
+ theirs.write_text("hand written by the user\n", encoding="utf-8")
+ stranger = prompts / "someone-elses.md"
+ stranger.write_text("not ours\n", encoding="utf-8")
+ retired = prompts / "repowise-retired-command.md"
+ retired.write_text("shipped by an older release\n", encoding="utf-8")
+
+ codex.TARGET.uninstall(Scope.USER)
+
+ assert not (prompts / "repowise-risk.md").exists(), "a bundled prompt survived"
+ assert theirs.read_text(encoding="utf-8") == "hand written by the user\n"
+ assert stranger.exists()
+ assert retired.exists(), (
+ "the narrow rule cannot tell a retired prompt of ours from a hand-written "
+ "one of theirs, and must therefore keep both"
+ )
+
+
+def test_a_prompt_that_is_not_valid_utf8_does_not_crash_the_install(fake_home) -> None:
+ """`UnicodeDecodeError` is a ValueError, so an OSError handler misses it.
+
+ Nothing wraps `install`: `agents add`, `agents refresh` and `doctor --repair`
+ all call it bare, and the last would abort part-way through having already
+ written other agents' configs.
+ """
+ prompts = codex.user_prompts_dir()
+ prompts.mkdir(parents=True, exist_ok=True)
+ (prompts / "repowise-risk.md").write_bytes(b"caf\xe9 in latin-1\n")
+
+ actions = {w.path.name: w.action for w in codex.write_prompts()}
+
+ assert actions["repowise-risk.md"] is FileAction.UPDATED
+ assert "café" not in (prompts / "repowise-risk.md").read_text(encoding="utf-8")
+
+
+def test_one_unwritable_prompt_does_not_stop_the_other_seventeen(fake_home) -> None:
+ """Raising here just moved the part-way failure rather than removing it.
+
+ `bundled_prompts()` is sorted, so a directory at `repowise-ask.md` aborted
+ before any of the rest were written, and it aborted inside `install()`
+ *after* the rewrite hook had been written and recorded. The refusal is a row
+ in the result instead, which is what the caller renders.
+ """
+ (codex.user_prompts_dir() / "repowise-ask.md").mkdir(parents=True)
+
+ actions = {w.path.name: w.action for w in codex.write_prompts()}
+
+ assert actions["repowise-ask.md"] is FileAction.KEPT
+ assert actions["repowise-risk.md"] is FileAction.CREATED
+ assert actions["repowise-why.md"] is FileAction.CREATED
+ assert FileAction.KEPT not in set(actions.values()) - {actions["repowise-ask.md"]}
+
+
+def test_doctor_still_names_a_missing_rewrite_hook_when_prompts_are_stale(fake_home) -> None:
+ """Loosening the early return moved this state into the issues path.
+
+ It silently dropped a true, separately-caused fact (the hook is not
+ installed) and it made a false one sayable, because the "predates PreToolUse
+ rewriting" branch says the hook "is registered" when there is none.
+ """
+ codex.write_prompts()
+ (codex.user_prompts_dir() / "repowise-risk.md").write_text("old\n", encoding="utf-8")
+
+ report = codex.TARGET.doctor()
+
+ assert report.status.value == "stale"
+ assert any("slash commands" in issue for issue in report.issues)
+ assert any("rewrite hook is not installed" in issue for issue in report.issues)
+ assert not any("is registered but its rewrite" in issue for issue in report.issues)
+
+
+def test_doctor_reports_prompts_that_have_fallen_behind_the_cli(fake_home) -> None:
+ """The drift this branch exists to close, on the surface the CLI *can* fix.
+
+ The Claude Code plugin skew is only reportable because repowise cannot
+ rewrite a plugin. These it can rewrite in one command, so silence would be
+ strictly worse here than there.
+ """
+ codex.write_prompts()
+ assert codex.stale_prompts() == []
+
+ (codex.user_prompts_dir() / "repowise-risk.md").write_text("from v0.1\n", encoding="utf-8")
+ (codex.user_prompts_dir() / "repowise-why.md").unlink()
+
+ assert sorted(codex.stale_prompts()) == ["repowise-risk.md", "repowise-why.md"]
+
+ report = codex.TARGET.doctor()
+ assert report.status.value == "stale"
+ assert any("slash commands" in issue for issue in report.issues)
+ assert report.fix_command == "repowise agents add --target=codex"
+ # `refresh` only touches what `detect` finds, and prompts are not a
+ # registration, so `--repair` would skip this and report success.
+ assert report.repairable is False
+
+
+def test_no_prompts_installed_at_all_is_not_reported_as_stale(fake_home) -> None:
+ """An agent nobody wired up is not a stale install."""
+ assert codex.stale_prompts() == []
+ codex.user_prompts_dir().mkdir(parents=True)
+ assert codex.stale_prompts() == []
+
+
+def test_the_prompts_directory_is_named_among_the_paths_codex_owns(fake_home) -> None:
+ """``agents remove`` promising a path it does not clear was a real defect."""
+ paths = codex.TARGET.describe_paths(Scope.USER)
+
+ assert str(codex.user_prompts_dir()) in paths
+
+
+# ---------------------------------------------------------------------------
+# Leak 2: plugin version skew
+# ---------------------------------------------------------------------------
+
+
+def _install_plugin(home: Path, version: str) -> None:
+ """Write the host's own manifest, schema version 2."""
+ manifest = home / ".claude" / "plugins" / "installed_plugins.json"
+ manifest.parent.mkdir(parents=True, exist_ok=True)
+ manifest.write_text(
+ json.dumps(
+ {
+ "version": 2,
+ "plugins": {
+ claude_code.PLUGIN_KEY: [
+ {
+ "scope": "user",
+ "installPath": str(home / ".claude" / "plugins" / "repowise"),
+ "version": version,
+ "installedAt": "2026-06-03T00:00:00Z",
+ }
+ ]
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+
+
+def test_a_plugin_at_the_cli_version_is_not_skew(fake_home) -> None:
+ _install_plugin(fake_home, __version__)
+
+ assert claude_code.plugin_version_skew() == []
+ assert claude_code.TARGET.doctor().status.value == "ok"
+
+
+def test_a_stale_plugin_is_reported_with_the_host_command_that_fixes_it(fake_home) -> None:
+ """The measured case: 0.16.0 installed months earlier against a 0.41.0 CLI."""
+ _install_plugin(fake_home, "0.16.0")
+
+ report = claude_code.TARGET.doctor()
+
+ assert report.status.value == "stale"
+ assert claude_code.plugin_version_skew() == ["0.16.0"]
+ skew = [issue for issue in report.issues if "0.16.0" in issue]
+ assert skew, report.issues
+ assert __version__ in skew[0]
+ assert "pip install -U repowise" in skew[0], (
+ "the point of the message is that upgrading the CLI does not do this"
+ )
+ assert report.fix_command == claude_code.PLUGIN_UPDATE_COMMAND
+
+
+def test_a_plugin_ahead_of_the_cli_sends_the_user_to_pip_instead(fake_home) -> None:
+ """The same drift running the other way.
+
+ Telling someone to update an already-newer plugin is a dead end, and it is a
+ real state: the host updates plugins on its own schedule.
+ """
+ _install_plugin(fake_home, "99.0.0")
+
+ report = claude_code.TARGET.doctor()
+
+ assert report.status.value == "stale"
+ assert report.fix_command == "pip install -U repowise"
+
+
+def _equivalent_spellings() -> list[str]:
+ """The same release as ``__version__``, written differently.
+
+ Derived rather than hardcoded, so this keeps testing the property after the
+ next version bump instead of quietly testing a stale literal.
+ """
+ parts = __version__.split(".")
+ spellings = [__version__, __version__ + ".0", "v" + __version__, "V" + __version__]
+ if parts[-1] == "0":
+ spellings.append(".".join(parts[:-1]))
+ spellings.append("v" + ".".join(parts[:-1]))
+ return spellings
+
+
[email protected]("spelling", _equivalent_spellings())
+def test_a_version_spelled_differently_is_the_same_release(fake_home, spelling) -> None:
+ """String equality made an equivalent version a permanent, unclearable STALE.
+
+ It also sent the user to `pip install -U repowise`, which changes nothing,
+ and fired a pointless global refresh on every `doctor --repair`. The module
+ already used release-tuple comparison one block later.
+ """
+ _install_plugin(fake_home, spelling)
+
+ assert claude_code.plugin_version_skew() == []
+ assert claude_code.TARGET.doctor().status.value == "ok"
+
+
+ "version,expected",
+ [("0.41.0rc1", ["0.41.0rc1"]), ("0.41.0.post1", ["0.41.0.post1"]), ("latest", ["latest"])],
+)
+def test_a_version_that_is_not_a_plain_release_is_still_reported(
+ fake_home, version, expected
+) -> None:
+ """A release candidate is not the release.
+
+ `core.upgrade.release.parse_release` answers a different question, "is there
+ a newer release", so it drops everything after the first non-digit and reads
+ all three of these as a plain release. Right for an upgrade prompt, wrong
+ here, which is why this module has its own key function.
+ """
+ _install_plugin(fake_home, version)
+
+ assert claude_code.plugin_version_skew() == expected
+
+
+def test_the_skew_report_does_not_claim_repair_can_fix_it(fake_home) -> None:
+ """`--repair` runs `agents refresh`, which cannot rewrite a host-managed plugin.
+
+ Letting it try bought a global config write that changed nothing, then
+ printed advice for a stale matcher and a damaged file, neither of which the
+ user has, while omitting the one command that works.
+ """
+ _install_plugin(fake_home, "0.16.0")
+
+ assert claude_code.TARGET.doctor().repairable is False
+
+
+def test_a_skewed_plugin_does_not_suppress_the_stale_matcher_repair(
+ fake_home, monkeypatch
+) -> None:
+ """The repair that `repairable` must not take away.
+
+ A stale matcher is rewritten by refresh. Setting `repairable=False` because a
+ plugin is also out of date left the matcher installed, parsing, never
+ firing, with `doctor --repair` printing "Nothing to repair."
+ """
+ from repowise.cli.editor_integrations import claude_config
+
+ monkeypatch.setattr(claude_config, "claude_code_rewrite_hook_matcher", lambda: "OldToolName")
+ _install_plugin(fake_home, __version__)
+
+ matcher_only = claude_code.TARGET.doctor()
+ assert matcher_only.repairable is True
+
+ _install_plugin(fake_home, "0.16.0")
+ with_skew = claude_code.TARGET.doctor()
+
+ assert with_skew.repairable is True, "the skew suppressed a repair that works"
+ # The printed command names the half `--repair` cannot do.
+ assert with_skew.fix_command == claude_code.PLUGIN_UPDATE_COMMAND
+
+
+def test_a_damaged_settings_file_is_not_offered_to_the_repair_pass(fake_home) -> None:
+ """Its own comment says refresh would skip it and report success."""
+ settings = fake_home / ".claude" / "settings.json"
+ settings.parent.mkdir(parents=True, exist_ok=True)
+ settings.write_text("{ not json", encoding="utf-8")
+
+ report = claude_code.TARGET.doctor()
+
+ assert report.status.value == "broken"
+ assert report.repairable is False
+
+
+def test_an_install_record_with_no_version_is_not_reported_as_skew(fake_home) -> None:
+ """Unactionable, so silent, the same degradation `_plugin_installs` makes."""
+ manifest = fake_home / ".claude" / "plugins" / "installed_plugins.json"
+ manifest.parent.mkdir(parents=True, exist_ok=True)
+ manifest.write_text(
+ json.dumps({"version": 2, "plugins": {claude_code.PLUGIN_KEY: [{"scope": "user"}]}}),
+ encoding="utf-8",
+ )
+
+ assert claude_code.plugin_version_skew() == []
+
+
+# ---------------------------------------------------------------------------
+# Leak 3: the self-heal version stamp
+# ---------------------------------------------------------------------------
+
+
+def counted_migrations(monkeypatch) -> dict[str, int]:
+ """Both migrations, replaced by counters.
+
+ Patched on the modules they live in rather than on ``self_heal``, because
+ ``self_heal`` imports them inside the function, and patching a name it has not
+ bound yet would silently test nothing.
+ """
+ from repowise.cli.editor_integrations import claude_config, codex_config
+
+ calls = {"claude": 0, "codex": 0}
+
+ def claude() -> bool:
+ calls["claude"] += 1
+ return False
+
+ def codex_migration() -> bool:
+ calls["codex"] += 1
+ return False
+
+ monkeypatch.setattr(claude_config, "migrate_claude_code_hooks", claude)
+ monkeypatch.setattr(codex_config, "migrate_codex_rewrite_hook", codex_migration)
+ return calls
+
+
+def test_the_migrations_run_once_per_version_not_once_per_invocation(
+ fake_home, counted_migrations
+) -> None:
+ from repowise.cli.self_heal import run_editor_migrations, stamp_path
+
+ assert run_editor_migrations() is True
+ assert counted_migrations == {"claude": 1, "codex": 1}
+ assert stamp_path().read_text(encoding="utf-8").startswith(__version__)
+
+ for _ in range(5):
+ assert run_editor_migrations() is False
+ assert counted_migrations == {"claude": 1, "codex": 1}
+
+
+def test_an_upgrade_makes_them_run_again(fake_home, counted_migrations) -> None:
+ from repowise.cli.self_heal import run_editor_migrations, stamp_path
+
+ stamp_path().parent.mkdir(parents=True, exist_ok=True)
+ stamp_path().write_text("0.1.0 claude_code_hooks,codex_rewrite_hook", encoding="utf-8")
+
+ assert run_editor_migrations() is True
+ assert counted_migrations == {"claude": 1, "codex": 1}
+
+
+def test_a_new_migration_runs_even_without_a_version_bump(
+ fake_home, counted_migrations, monkeypatch
+) -> None:
+ """The version alone is not a complete key.
+
+ `__version__` is a literal in `repowise/cli/__init__.py`. A migration added
+ in a commit that does not bump it would be permanently skipped for anyone who
+ had already run that version, which is every install tracking `main`,
+ including this repo's own. The stamp records the migration *names* too.
+ """
+ from repowise.cli import self_heal
+
+ assert self_heal.run_editor_migrations() is True
+ assert self_heal.run_editor_migrations() is False
+ before = self_heal.stamp_path().read_text(encoding="utf-8")
+
+ ran: list[str] = []
+ monkeypatch.setattr(
+ self_heal,
+ "_MIGRATIONS",
+ (*self_heal._MIGRATIONS, ("a_third_thing", lambda: ran.append("x"))),
+ )
+
+ assert self_heal.run_editor_migrations() is True, "a new migration was skipped"
+ assert ran == ["x"]
+ assert self_heal.stamp_path().read_text(encoding="utf-8") != before
+
+
+def test_a_stamp_that_is_a_directory_degrades_to_running_them(
+ fake_home, counted_migrations
+) -> None:
+ from repowise.cli.self_heal import run_editor_migrations, stamp_path
+
+ stamp_path().mkdir(parents=True)
+
+ assert run_editor_migrations() is True
+ assert counted_migrations == {"claude": 1, "codex": 1}
+
+
+def test_skip_editor_setup_touches_no_global_config_at_all(
+ fake_home, counted_migrations, monkeypatch
+) -> None:
+ """The benchmark contract, and the closing half of the migration decision.
+
+ Both migrations write ``~/.claude/settings.json`` and ``~/.codex/hooks.json``
+ when they find something to repair, and both used to ignore this variable.
+ """
+ monkeypatch.setenv("REPOWISE_SKIP_EDITOR_SETUP", "1")
+ from repowise.cli.self_heal import run_editor_migrations
+
+ assert run_editor_migrations() is False
+ assert counted_migrations == {"claude": 0, "codex": 0}
+ # Not even the stamp: `~/.repowise` is global config too.
+ assert list(fake_home.iterdir()) == []
+
+
+def test_the_stamp_is_not_written_when_a_migration_raised(fake_home, monkeypatch) -> None:
+ """A failed run has healed nothing.
+
+ Recording it as done would turn a transient failure into a permanent one, so
+ the cost of a broken settings file is the pre-stamp behaviour and no more.
+ """
+ from repowise.cli.editor_integrations import claude_config, codex_config
+ from repowise.cli.self_heal import run_editor_migrations, stamp_path
+
+ def boom() -> bool:
+ raise OSError("settings.json is a directory")
+
+ monkeypatch.setattr(claude_config, "migrate_claude_code_hooks", boom)
+ monkeypatch.setattr(codex_config, "migrate_codex_rewrite_hook", lambda: False)
+
+ assert run_editor_migrations() is True
+ assert not stamp_path().exists()
+
+
+def test_an_unwritable_stamp_costs_the_old_behaviour_and_nothing_else(
+ fake_home, counted_migrations, monkeypatch
+) -> None:
+ from repowise.cli import self_heal
+
+ monkeypatch.setattr(self_heal, "_write_stamp", lambda version: None)
+
+ assert self_heal.run_editor_migrations() is True
+ assert self_heal.run_editor_migrations() is True
+ assert counted_migrations == {"claude": 2, "codex": 2}
diff --git a/tests/unit/cli/test_agents_cmd.py b/tests/unit/cli/test_agents_cmd.py
index a6b7b1244..75ed7f648 100644
--- a/tests/unit/cli/test_agents_cmd.py
+++ b/tests/unit/cli/test_agents_cmd.py
@@ -384,7 +384,14 @@ def test_doctor_surfaces_a_stale_hook_matcher_rather_than_calling_it_ok(
def test_doctor_fails_the_run_only_for_a_damaged_config(repo: Path) -> None:
- """The other side of that line: broken is a real fault, so it fails."""
+ """The other side of that line: broken is a real fault, so it fails.
+
+ It does **not** drive ``--repair``, and this assertion is the reverse of what
+ it once was. The target's own comment explains why: a file this damaged makes
+ detection find nothing, and refresh only touches what it detects, so the
+ repair pass would skip this target and report success. Failing the run and
+ naming ``agents add`` is the whole of the correct response.
+ """
from repowise.cli.commands.doctor_cmd.repo_checks import _agent_target_checks
settings = Path.home() / ".claude" / "settings.json"
@@ -395,7 +402,8 @@ def test_doctor_fails_the_run_only_for_a_damaged_config(repo: Path) -> None:
claude = next(c for c in checks if c.name == "Agent: claude-code")
assert claude.ok is False
- assert needs_refresh is True
+ assert "repowise agents add --target=claude-code" in claude.detail
+ assert needs_refresh is False
def test_doctor_calls_a_damaged_config_broken_not_missing(repo: Path) -> None:
diff --git a/tests/unit/cli/test_augment_hook_perf.py b/tests/unit/cli/test_augment_hook_perf.py
index 6439812ee..89c018665 100644
--- a/tests/unit/cli/test_augment_hook_perf.py
+++ b/tests/unit/cli/test_augment_hook_perf.py
@@ -85,6 +85,79 @@ def test_the_self_heal_imports_nothing_heavy(tmp_path: Path) -> None:
assert heavy == "", f"the hook self-heal pulled in:\n{heavy}"
+def test_the_stamped_self_heal_imports_nothing_heavy(tmp_path: Path) -> None:
+ """The version stamp sits in front of the migrations, so it is hot-path too."""
+ heavy = _heavy_after(
+ "from repowise.cli.self_heal import run_editor_migrations; run_editor_migrations();",
+ env=_fake_home(tmp_path),
+ )
+ assert heavy == "", f"the stamped self-heal pulled in:\n{heavy}"
+
+
+def test_the_stamped_common_path_imports_nothing_at_all(tmp_path: Path) -> None:
+ """Not "nothing heavy" but *nothing*, on the path that fires per tool call.
+
+ The version of this that only checked the heavy-prefix list could not see the
+ defect it should have caught. Gating the stamp read behind
+ ``is_editor_setup_disabled`` reads better and costs more than the problem it
+ solves: that lives in ``editor_setup``, whose module scope imports
+ ``agent_targets.types``, and the pair measured at ~13ms against the ~19ms the
+ whole self-heal was costing: two thirds of the saving spent on the check.
+ Neither module is on the heavy list, and neither ever will be, because both
+ are stdlib-only by design. Only naming them directly catches it.
+
+ So: warm the stamp, then assert the second call reaches neither.
+ """
+ probe = (
+ "import sys; "
+ "from repowise.cli.self_heal import run_editor_migrations; "
+ "run_editor_migrations(); "
+ "[sys.modules.pop(m) for m in list(sys.modules) "
+ " if m.startswith(('repowise.cli.editor_setup','repowise.cli.agent_targets',"
+ "'repowise.cli.editor_integrations'))]; "
+ "run_editor_migrations(); "
+ "print('\\n'.join(sorted(m for m in sys.modules "
+ " if m.startswith(('repowise.cli.editor_setup','repowise.cli.agent_targets',"
+ "'repowise.cli.editor_integrations')))));"
+ )
+ out = subprocess.run(
+ [sys.executable, "-c", probe],
+ capture_output=True,
+ text=True,
+ check=True,
+ env=_fake_home(tmp_path),
+ )
+ assert out.stdout.strip() == "", (
+ "the stamped common path imported these, which the heavy-prefix guard "
+ f"cannot see:\n{out.stdout}"
+ )
+
+
+def test_the_stamp_spares_the_settings_read_on_the_common_path(tmp_path: Path) -> None:
+ """The point of the stamp, measured as file access rather than asserted.
+
+ Before it, every hook fire opened and parsed ``~/.claude/settings.json`` to
+ discover there was nothing to do, once per matched tool call. The second
+ run must not open it at all.
+ """
+ env = _fake_home(tmp_path)
+ probe = (
+ "import json, pathlib; "
+ "from repowise.cli.self_heal import run_editor_migrations, stamp_path; "
+ "run_editor_migrations(); "
+ "opened = []; "
+ "import builtins; real = builtins.open; "
+ "builtins.open = lambda f, *a, **k: (opened.append(str(f)), real(f, *a, **k))[1]; "
+ "run_editor_migrations(); "
+ "builtins.open = real; "
+ "print('\\n'.join(p for p in opened if 'settings.json' in p or 'hooks.json' in p));"
+ )
+ out = subprocess.run(
+ [sys.executable, "-c", probe], capture_output=True, text=True, check=True, env=env
+ )
+ assert out.stdout.strip() == "", f"the stamped run still read:\n{out.stdout}"
+
+
def _read_payload_probe(repo: Path, rel: str) -> str:
"""Source that fires the PostToolUse Read hook against a real file.
diff --git a/tests/unit/cli/test_plugin_content.py b/tests/unit/cli/test_plugin_content.py
new file mode 100644
index 000000000..9fafaa3b5
--- /dev/null
+++ b/tests/unit/cli/test_plugin_content.py
@@ -0,0 +1,191 @@
+"""The golden that keeps the two plugin hosts from forking again.
+
+`plugins/codex/skills/` was a hand-copy of `plugins/claude-code/skills/` and had
+already drifted: every description rewritten, headings retitled ("Dead Code
+Cleanup With Repowise" against "with"), one directory renamed. Nothing caught it,
+because a stale copy of a document is indistinguishable from a deliberate variant
+unless something asserts which one it is.
+
+So the assertions here are on the **generated files**, not on the generator's
+return value. A renderer can be perfectly correct about text nobody ever wrote to
+disk; that is the failure mode this test exists to make impossible.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import importlib.util
+import sys
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[3]
+
+
+def _generator():
+ """Import `scripts/gen_plugin_content.py`, which is not on the import path."""
+ path = ROOT / "scripts" / "gen_plugin_content.py"
+ spec = importlib.util.spec_from_file_location("gen_plugin_content", path)
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+GEN = _generator()
+
+
+def _on_disk(path: Path) -> str:
+ """The file's text with line endings normalised.
+
+ The generator writes LF, but this repo is checked out with `core.autocrlf` on
+ Windows, so an untouched generated file reads back as CRLF. Comparing raw
+ bytes would fail on every Windows checkout and pass on every POSIX one, which
+ is worse than not testing it.
+ """
+ return path.read_text(encoding="utf-8").replace("\r\n", "\n")
+
+
+ "path", sorted(GEN.rendered_files()), ids=lambda p: p.relative_to(ROOT).as_posix()
+)
+def test_generated_plugin_file_matches_the_shared_source(path: Path) -> None:
+ expected = GEN.rendered_files()[path]
+ assert path.exists(), (
+ f"{path.relative_to(ROOT).as_posix()} is missing. "
+ "Run: python scripts/gen_plugin_content.py"
+ )
+ assert _on_disk(path) == expected, (
+ f"{path.relative_to(ROOT).as_posix()} has drifted from plugins/shared/. "
+ "Edit the shared source, then run: python scripts/gen_plugin_content.py"
+ )
+
+
+def test_the_two_hosts_ship_the_same_skill_bodies() -> None:
+ """The fork, stated directly rather than inferred from the file list.
+
+ The per-file test above would still pass if someone gave a host its own copy
+ of a body in the shared source. This is the property that actually matters:
+ one body, rendered twice.
+ """
+ hosts = {host.id: host for host in GEN.HOSTS}
+ for item in GEN.load_items("skills"):
+ claude = GEN.render(item, hosts["claude-code"], frontmatter_keys=None)
+ codex = GEN.render(item, hosts["codex"], frontmatter_keys=None)
+ # Strip frontmatter, since that half is allowed to differ per host.
+ claude_body = claude.split("\n---\n\n", 1)[1]
+ codex_body = codex.split("\n---\n\n", 1)[1]
+ # ...but only where the hosts spell a slash command differently.
+ assert claude_body.replace("/repowise:", "@") == codex_body.replace(
+ "/prompts:repowise-", "@"
+ ), f"{item.source.name}: the two hosts have different skill bodies"
+
+
+def test_every_skill_reaches_both_hosts() -> None:
+ """A shared file that renders for one host only is a fork with extra steps."""
+ rendered = GEN.rendered_files()
+ for item in GEN.load_items("skills"):
+ for host in GEN.HOSTS:
+ path = host.skills_root / item.directory_for(host) / "SKILL.md"
+ assert path in rendered, f"{item.source.name} renders nothing for {host.id}"
+
+
+def test_codex_prompts_carry_only_frontmatter_codex_reads() -> None:
+ """`allowed-tools` is a Claude Code field.
+
+ Emitting it into a Codex prompt is not harmful, it is just a key the host
+ ignores, which is exactly the kind of thing that accumulates until the two
+ formats are a fork again.
+ """
+ prompts = sorted(GEN.CODEX_PROMPT_DATA.glob("*.md"))
+ assert prompts, "no Codex prompts were generated"
+ for path in prompts:
+ frontmatter = _on_disk(path).split("---\n")[1]
+ keys = {line.split(":", 1)[0] for line in frontmatter.splitlines() if ":" in line}
+ assert keys <= {"description", "argument-hint"}, f"{path.name} carries {keys}"
+
+
+def test_rendering_is_idempotent() -> None:
+ """`--check` against a clean tree, which is what CI runs."""
+ assert GEN.main(["--check"]) == 0
+
+
+def test_the_tree_carries_no_generated_file_without_a_shared_source() -> None:
+ """A retired command leaves two files behind, and only this notices.
+
+ `rendered_files` says what *should* exist; nothing compared it to what does,
+ so deleting a shared source left both rendered copies on disk and `--check`
+ called the tree clean. The retired command then keeps shipping in the wheel
+ and keeps being written into `~/.codex/prompts` on every install, and a
+ renamed `dir:` override leaves the old SKILL.md for the host to load as a
+ second skill with the same name.
+ """
+ assert GEN.orphaned_files() == []
+
+
+def test_the_sweep_does_not_reach_a_hand_maintained_file() -> None:
+ """The scope the docstring promised, and the first cut did not honour.
+
+ Globbing `*.md` and deleting everything unrecognised removed a README a host
+ directory carried, silently and unprompted, on a plain regenerate. Every file
+ the generator writes opens with a `---` fence, so requiring one is an
+ ownership test a README fails.
+ """
+ readme = GEN.HOSTS[0].commands_root / "README.md"
+ notes = GEN.HOSTS[0].skills_root / "team-only" / "SKILL.md"
+ readme.write_text("# Commands\n\nHand-maintained, no frontmatter.\n", encoding="utf-8")
+ notes.parent.mkdir(parents=True, exist_ok=True)
+ notes.write_text("# Team only\n\nAlso no frontmatter.\n", encoding="utf-8")
+ try:
+ assert GEN.orphaned_files() == []
+ assert GEN.main([]) == 0
+ assert readme.exists() and notes.exists()
+ finally:
+ readme.unlink(missing_ok=True)
+ notes.unlink(missing_ok=True)
+ with contextlib.suppress(OSError):
+ notes.parent.rmdir()
+
+
+def test_retiring_every_command_does_not_delete_the_directory_itself() -> None:
+ """`rmdir` on each orphan's parent removed the commands root.
+
+ Including the Codex package-data directory, after which `bundled_prompts()`
+ raised FileNotFoundError out of `install`, `stale_prompts` and `doctor`.
+ Only a *skill* owns its directory.
+ """
+ stray = GEN.CODEX_PROMPT_DATA / "repowise-retired.md"
+ stray.write_text("---\ndescription: gone\n---\n\nbody\n", encoding="utf-8")
+ try:
+ assert GEN.main([]) == 0
+ finally:
+ stray.unlink(missing_ok=True)
+ assert GEN.CODEX_PROMPT_DATA.is_dir(), "the sweep removed the package-data directory"
+ assert GEN.HOSTS[0].commands_root.is_dir()
+ # The thing that broke when it did not.
+ from repowise.cli.agent_targets.targets import codex
+
+ assert len(codex.bundled_prompts()) == 18
+
+
+def test_a_retired_shared_source_is_detected_and_swept(tmp_path, monkeypatch) -> None:
+ """Proven by construction rather than by trusting the sweep exists.
+
+ Both hosts' copies are planted directly, because the real operation (delete
+ a file from `plugins/shared/`) cannot be done to the checkout from a test.
+ """
+ stray_claude = GEN.HOSTS[0].commands_root / "retired-command.md"
+ stray_codex = GEN.CODEX_PROMPT_DATA / "repowise-retired-command.md"
+ for stray in (stray_claude, stray_codex):
+ stray.write_text("---\ndescription: gone\n---\n\nbody\n", encoding="utf-8")
+ try:
+ assert set(GEN.orphaned_files()) == {stray_claude, stray_codex}
+ assert GEN.main(["--check"]) == 1, "--check called an orphaned tree clean"
+ assert GEN.main([]) == 0
+ assert not stray_claude.exists() and not stray_codex.exists()
+ finally:
+ stray_claude.unlink(missing_ok=True)
+ stray_codex.unlink(missing_ok=True)
+ assert GEN.main(["--check"]) == 0, "the sweep did not leave the tree clean"