Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
docs(agents): add the agent platform recipe for contributors (#3178)
Raghav Chamadiya3e2f2b8e3e31
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.mdindex b9ef71bb5..990e6d76e 100644--- a/.github/CONTRIBUTING.md+++ b/.github/CONTRIBUTING.md@@ -221,41 +221,24 @@ repowise/### Adding a new LLM provider-1. **Create `packages/core/src/repowise/core/providers/llm/<name>.py`**- - Subclass `BaseProvider` and implement `generate()`, `provider_name`, `model_name`- - For local CLI providers, use `asyncio.create_subprocess_exec` (never `shell=True`), validate user-supplied model names against a safe character set, and resolve paths with `Path.resolve()`- - See `opencode.py` for a clean reference implementation--2. **Register** in `registry.py`: add to `_BUILTIN_PROVIDERS` and the `_missing` package map--3. **Wire up configuration.** These live in three different packages, so the full- paths matter more than the filenames:- - `packages/core/src/repowise/core/rate_limiter.py`, add a `RateLimitConfig` to- `PROVIDER_DEFAULTS`- - `packages/server/src/repowise/server/provider_config.py`, add an entry to- `PROVIDER_CATALOG`- - `packages/cli/src/repowise/cli/ui/provider_selection.py`, add to- `_PROVIDER_DEFAULTS`, `_PROVIDER_ENV`, `_PROVIDER_SIGNUP`, and detection- - `packages/cli/src/repowise/cli/helpers.py`, add validation in- `validate_provider_config()`-- Check `registry.py` first. Several things that used to be spread across these files- now live there in one place (`PROVIDER_API_KEY_ENVS`, `PROVIDER_BASE_URL_ENVS`,- `KEYLESS_PROVIDERS`, `REPO_PATH_PROVIDERS`, `PROVIDER_AUTODETECT_ORDER`), because- three copies of the same list drifted. Add to the consolidated one, not a fourth copy.--4. **Update the web UI**: `packages/web/src/components/settings/provider-section.tsx`,- which holds `FALLBACK_PROVIDERS`, `MODEL_PLACEHOLDERS` and `PROVIDER_ENV_VARS`. The- live list comes from the server catalog at runtime; `FALLBACK_PROVIDERS` is only the- offline fallback, so keep it in step with `PROVIDER_CATALOG` above.--5. **Add tests** in `tests/unit/test_providers/`: mock the subprocess, test success/error/timeout paths (see `test_codex_cli_provider.py` for the pattern)--6. **Write docs**: `docs/agent/<NAME>.md` and `website/<name>.md`, following- `docs/agent/CODEX.md` and `docs/agent/OPENCODE.md`.+1. Create `packages/core/src/repowise/core/providers/llm/<name>.py` with a+ `BaseProvider` subclass. For an OpenAI-compatible API, subclass+ `OpenAICompatibleProvider` from `openai_compat.py`, as `deepseek.py` does.+2. Add one `ProviderSpec` to `_SPECS` in+ `packages/core/src/repowise/core/providers/llm/specs.py`: key and base-URL env vars,+ default model and model list, rate limit, package, picker rank and signup URL.+ The registry tables, the server catalog, the init picker and the web UI all read+ it, so there is no second list to edit.+3. Add tests in `tests/unit/test_providers/`. If the spec has a `picker_rank`, add+ the name to the frozen picker order in `tests/unit/cli/test_init_ux.py`.++An agent CLI used as a backend (`claude_cli`, `codex_cli`, `opencode`) follows the+agent platform recipe instead.Adding a new language has a dedicated recipe, see[docs/architecture/language-support.md](../docs/architecture/language-support.md).+Adding an agent integration or an agent CLI indexing backend has its own recipe, see+[docs/architecture/agent-platform.md](../docs/architecture/agent-platform.md).## Testingdiff --git a/docs/agent/INTEGRATIONS.md b/docs/agent/INTEGRATIONS.mdindex 881b1e5b3..72e1fe000 100644--- a/docs/agent/INTEGRATIONS.md+++ b/docs/agent/INTEGRATIONS.md@@ -62,7 +62,7 @@ the server entry and paste it into whatever config that host reads:repowise agents print-config claude-code # prints, writes nothing```-Ask for the target id whose host is closest to yours rather than editing a+Ask for the target id whose host is closest to yours instead of editing asnippet by hand. The shapes genuinely differ, and not only in their wrapper:hosts disagree about the top-level key, about whether each entry carries a`type` field, about whether the invocation is one array or a command plus a@@ -89,42 +89,28 @@ Per-tool detail: [MCP_TOOLS.md](MCP_TOOLS.md).## Adding an agent-**Adding an agent takes one identity record, one descriptor file and one-registry line.**+The step-by-step recipes, including indexing backends and hook and+transcript adapters, are in+[docs/architecture/agent-platform.md](../architecture/agent-platform.md).+In short, an integration target is:-1. Add an `AgentIdentity` to- [`identity.py`](../../packages/core/src/repowise/core/agents/identity.py):- its slug, display name, `executable` and, if its CLI can index,- `indexing_provider`.-2. Write `packages/cli/src/repowise/cli/agent_targets/targets/<id>.py`+1. An `AgentIdentity` in+ [`identity.py`](../../packages/core/src/repowise/core/agents/identity.py).+2. A descriptor module in `packages/cli/src/repowise/cli/agent_targets/targets/`exporting a `TARGET` that satisfies the `AgentTarget` protocol in[`types.py`](../../packages/cli/src/repowise/cli/agent_targets/types.py).- `vscode.py` is the smallest working example, at one install method and- one config file.-3. Add one line to `_TARGET_MODULES` in+3. One line in `_TARGET_MODULES` in[`registry.py`](../../packages/cli/src/repowise/cli/agent_targets/registry.py).- Order there is the order agents appear in prompts, in `--target=all` and- in listings, so keep it stable.-4. Run `python scripts/gen_agent_matrix.py` to add the row here.+4. A README badge under the tier `derive_tier` gives it, checked by+ `tests/unit/cli/test_agent_matrix.py`.+5. `python scripts/gen_agent_matrix.py` to add the row here.-An indexing backend adds three more pieces: a `ProviderSpec` in+An indexing backend is its own module in+`packages/core/src/repowise/core/providers/llm/` subclassing `AgentCliProvider`,+a `ProviderSpec` in[`specs.py`](../../packages/core/src/repowise/core/providers/llm/specs.py),-an `AgentCliProvider` subclass in-[`agent_cli.py`](../../packages/core/src/repowise/core/providers/llm/agent_cli.py),and one `Backend` entry in-`tests/unit/test_providers/test_agent_cli_contract.py`, which runs the shared-provider contract against it.--There is no further file for anything derived. The tier, this matrix and the-`repowise agents` listing all read the descriptor, and the contract tests in-`tests/unit/cli/test_agent_targets.py` are parameterized over the registry,-so a new target inherits them.--The README badge rows are the exception: a brand colour and a logo per agent-are not derivable, and the README is not generated, so a new agent needs a-badge added by hand and the count above them updated. That is checked rather-than trusted. `tests/unit/cli/test_agent_matrix.py` fails when the badge rows-and the registry disagree, and names what to add.+`tests/unit/test_providers/test_agent_cli_contract.py`.Declare only what the agent genuinely has. `derive_tier` reads the adapternames, so a descriptor that names a hook adapter it has not implementeddiff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.mdindex 0295ce42e..91080536a 100644--- a/docs/architecture/ARCHITECTURE.md+++ b/docs/architecture/ARCHITECTURE.md@@ -322,26 +322,25 @@ It can be rebuilt from scratch by re-parsing the source files.## 4. Provider Abstraction Layer-Every LLM call in the entire system goes through `LLMProvider`. No provider SDK-is ever imported from business logic packages.+Every LLM call in the entire system goes through `BaseProvider`+(`packages/core/src/repowise/core/providers/llm/base.py`). No provider SDK is+ever imported from business logic packages.++Each provider is described once, by a `ProviderSpec` in+`providers/llm/specs.py`: its key and endpoint env vars, models, rate limit,+whether it needs a key, and whether it drives a local agent CLI. The registry+tables, the server's `/api/providers` catalog, the init picker and the web UI+are all derived from those records.```- ┌─────────────────┐- │ LLMProvider │ (abstract base class)- │ │- │ generate() │- │ generate_stream│- │ embed() │- │ generate_batch │ (optional, default = sequential)- │ estimate_cost │ (optional, returns None if unknown)- └────────┬────────┘- │- ┌──────────────────┼──────────────────┬──────────────────┐- ▼ ▼ ▼ ▼- AnthropicProvider OpenAIProvider OllamaProvider LiteLLMProvider- (claude-*) (gpt-*, any (any local model, (100+ providers,- batch API + prompt OpenAI-compat fully offline, optional dep)- caching support) endpoint) no API key)+ BaseProvider+ |+ +-----------------------+------------------------++ | | |+ SDK providers OpenAICompatibleProvider AgentCliProvider+ (anthropic, gemini, (deepseek, kimi, edenai) (claude_cli, codex_cli,+ openai, openrouter, opencode: the user's+ ollama, litellm) logged-in agent CLI)```### 4.1 Rate Limiter@@ -353,8 +352,8 @@ Before every API call, the limiter acquires from both buckets. On a 429 responseit calls `on_rate_limit_error()` which applies exponential backoff and temporarilyreduces the refill rate. This is transparent to all callers.-Default limits are configured per provider in `.repowise/config.yaml` and can be-adjusted for users with higher API tiers.+Default limits come from each provider's `ProviderSpec.rate_limit`. Agent CLI+providers get no limiter; their own concurrency semaphore bounds them.### 4.2 Prompt Caching@@ -369,8 +368,7 @@ on large repos is typically 60–90%.### 4.3 Adding a Provider-Implement `LLMProvider`, add an entry to `LANGUAGE_CONFIGS` in `providers/registry.py`,-and add a section to `.repowise/config.yaml`. See [Section 17](#17-adding-a-new-llm-provider).+See [Section 17](#17-adding-a-new-llm-provider).---@@ -1280,7 +1278,7 @@ JobSystem│ └──────────────┬─────────────────────┘│ ││ ▼- │ LLMProvider.generate()+ │ BaseProvider.generate()│ ││ ▼│ WikiPage stored:@@ -1341,7 +1339,7 @@ ChangeDetector.get_affected_pages(cascade_budget=30)│▼For each page in `regenerate`:- ContextAssembler → LLMProvider → update SQL + VectorStore + Graph+ ContextAssembler → BaseProvider → update SQL + VectorStore + Graph│▼For each page in `rename_patch`:@@ -1598,38 +1596,16 @@ Two things worth knowing before you start:## 17. Adding a New LLM Provider-1. **Create `packages/core/providers/<name>.py`**-- Subclass `LLMProvider` and implement:- - `generate(request: GenerationRequest) -> GenerationResponse`- - `generate_stream(request: GenerationRequest) -> AsyncIterator[str]`- - `embed(request: EmbedRequest) -> EmbedResponse`- - `name` property-- Optionally override:- - `supports_batch` → `True` if the provider has a batch API- - `generate_batch(requests) -> list[GenerationResponse]`- - `estimate_cost(input_tokens, output_tokens) -> float`--2. **Register in `providers/registry.py`**-- ```python- case "myprovider": return MyProvider(config)- ```--3. **Add config section to `.repowise/config.yaml` docs**-- ```yaml- myprovider:- api_key: ${MYPROVIDER_API_KEY}- base_url: https://api.myprovider.com/v1- ```--4. **Add default rate limits** to `PROVIDER_DEFAULT_LIMITS` in `rate_limiter.py`--5. **Add a `MockProvider` fixture** for tests if the provider has unique response formats+1. Create `packages/core/src/repowise/core/providers/llm/<name>.py` with a+ `BaseProvider` subclass (or `OpenAICompatibleProvider` for an+ OpenAI-compatible API).+2. Add one `ProviderSpec` to `_SPECS` in `providers/llm/specs.py`. Nothing else+ lists providers.+3. Add tests in `tests/unit/test_providers/`.-6. **Update `CONTRIBUTING.md`** with the new provider's environment variables+The recipe, including the frozen picker test, is in+[CONTRIBUTING.md](../../.github/CONTRIBUTING.md). A backend that drives an agent's+CLI follows [agent-platform.md](agent-platform.md).---diff --git a/docs/architecture/README.md b/docs/architecture/README.mdindex 9aaed73d7..484473c7b 100644--- a/docs/architecture/README.md+++ b/docs/architecture/README.md@@ -14,6 +14,7 @@ curious; you don't need them to *use* repowise (start with| [decisions.md](decisions.md) | Decision capture internals: the source registry, evidence verification, confidence, currency, session mining and hook delivery || [test-intelligence.md](test-intelligence.md) | The inferred test tier: call and import walks, their measured precision and recall, the resolution-origin filter, and why nothing is stored || [language-support.md](language-support.md) | The language pipeline internals and the step-by-step recipe for adding a new language |+| [agent-platform.md](agent-platform.md) | Agent identities, provider specs, integration targets and adapters, and the recipes for adding an agent integration or an agent CLI indexing backend || [graph-algorithms.md](graph-algorithms.md) | The graph algorithms (PageRank, betweenness, Tarjan SCC, Leiden/Louvain community detection, shortest path) with the math and complexity || [refactoring.md](refactoring.md) | Refactoring intelligence internals: detector registration, plan shape, ranking, REST routes, and code generation || [savings-accounting.md](savings-accounting.md) | The savings accounting contract: what counts as a measured reduction versus an inferred avoidance, and what a total may claim |diff --git a/docs/architecture/agent-platform.md b/docs/architecture/agent-platform.mdnew file mode 100644index 000000000..10ba29e62--- /dev/null+++ b/docs/architecture/agent-platform.md@@ -0,0 +1,487 @@+# Agent platform internals++How repowise describes the coding agents it works with, and the recipes for+adding one. The public view of the same thing is+[agent/INTEGRATIONS.md](../agent/INTEGRATIONS.md), which is generated from the+registries described here.++An agent can touch repowise in two independent ways:++- Integration: repowise wires the agent up as an MCP host: it writes the+ server config, and depending on the agent, an instructions block, skills,+ hooks and a transcript reader.+- Indexing backend: the agent's own CLI runs as the LLM that writes the+ wiki, using the user's existing login, with no API key.++An agent can have either, both or neither. GitHub Copilot CLI, for example, is+an integration target with a registered identity and no indexing backend.++**Contents**++- [How it fits](#how-it-fits)+- [Recipe A: adding an indexing backend](#recipe-a-adding-an-indexing-backend)+- [Recipe B: adding an integration target](#recipe-b-adding-an-integration-target)+- [Recipe C: hook and transcript adapters](#recipe-c-hook-and-transcript-adapters)+- [Guards you will hit](#guards-you-will-hit)++---++## How it fits++```+AgentIdentity (core/agents/identity.py)+ slug, display name, executable, install and login hints,+ hook_adapter, session_adapter, indexing_provider+ | | |+ | indexing_provider | cli_target_id | hook_adapter / session_adapter+ v v v+ProviderSpec AgentTarget AgentAdapter (cli/agent_adapters)+(providers/llm/specs.py) (cli/agent_targets/ HarnessAdapter (core/sessions/adapters)+ | targets/<id>.py)+ | impl |+ v v+AgentCliProvider subclass derive_tier -> Full / Good / Basic / Paste-config+(providers/llm/<name>.py)+```++All paths below are under `packages/core/src/repowise/core/` or+`packages/cli/src/repowise/cli/` unless written in full.++| Piece | File | Holds |+|---|---|---|+| `AgentIdentity` | `core/agents/identity.py` | One record per agent: slug, display name, `executable`, `login_check`, `install_hint`, `login_hint`, the adapter names, and `indexing_provider`. Every other namespace derives its spelling of the agent from here. |+| `ProviderSpec` | `core/providers/llm/specs.py` | One record per LLM provider. `KEYLESS_PROVIDERS`, `REPO_PATH_PROVIDERS`, `PROVIDER_DEFAULTS`, `ZERO_COST_MODEL_PREFIXES`, the server catalog and the init picker rows are all computed from `PROVIDER_SPECS`. |+| `AgentCliProvider` | `core/providers/llm/agent_cli.py` | The shared subprocess base for agent CLI backends: executable lookup, stdin prompt, timeout and kill, cancellation, a per-loop concurrency semaphore, error tails, model labels, cost booking. |+| Integration targets | `cli/agent_targets/` | `types.py` (the `AgentTarget` protocol and `derive_tier`), `registry.py` (`_TARGET_MODULES`), `targets/<id>.py` (one descriptor per agent), `instructions.py` (the shared managed block), `formats/` (JSON, TOML, YAML and marker-block writers). |+| Hook adapters | `cli/agent_adapters/` | `AgentAdapter` in `base.py`, registered in `_REGISTRY` in `__init__.py`. |+| Transcript adapters | `core/sessions/adapters/` | `HarnessAdapter` in `base.py`, registered with `@register_adapter` and imported in `__init__.py`. |++The two registries meet in exactly one place: `ProviderSpec.agent` names the+agent slug, and `AgentIdentity.indexing_provider` names the spec back. A test+holds the two links to each other.++The tier is never declared. `derive_tier` in `agent_targets/types.py` reads the+descriptor:++- no install methods: Paste-config+- names both a hook adapter and a session adapter: Full+- wires MCP plus instructions or skills: Good+- anything else: Basic++The server exposes the provider specs at `/api/providers`+(`packages/server/src/repowise/server/provider_config.py`), and the web UI reads+its provider list, models and setup hints from there. No UI file names a+provider.++---++## Recipe A: adding an indexing backend++The worked reference is `core/providers/llm/opencode.py`. The steps below use+`copilot_cli` as the example name. Name the module after the provider: the+provider-name guard (see [Guards](#guards-you-will-hit)) lets a provider's own+module spell its name, matched by file stem.++### Step 1: the provider module++Create `packages/core/src/repowise/core/providers/llm/copilot_cli.py` <!-- repowise-drift-ignore -->+with a subclass of `AgentCliProvider`.++```python+from repowise.core.providers.llm.agent_cli import AgentCliProvider, iter_jsonl, tail+from repowise.core.providers.llm.base import GeneratedResponse, ProviderError+from repowise.core.reasoning import ReasoningMode+++class CopilotCliProvider(AgentCliProvider):+ provider_name = "copilot_cli"+ agent_slug = "copilot" # the AgentIdentity slug+ command_label = "copilot" # how errors name the invocation+ concurrency_env = "REPOWISE_COPILOT_CLI_CONCURRENCY"++ def build_command(self, system_prompt: str, reasoning: ReasoningMode) -> list[str]:+ cmd = [self._executable, ...] # non-interactive, read-only flags+ if self._model:+ cmd += ["--model", self._model]+ return cmd++ def parse_output(self, stdout: str, stderr: str) -> GeneratedResponse:+ ... # text plus token counts+```++The base derives `executable_name` and the not-found message from the identity+named by `agent_slug`, so the class fails at import if that identity has no+`executable`. Never shell out yourself or use `shell=True`: the base spawns the+process without a shell, passes the prompt on stdin and validates model names.++Required:++- `build_command(system_prompt, reasoning)` returns argv for one call. Pass the+ model as `--model <slug>` when `self._model` is set; the contract test reads+ it from there. Use the CLI's read-only or no-tools mode: indexing must never+ edit the repo.+- `parse_output(stdout, stderr)` builds the `GeneratedResponse` from a+ successful run. Raise `ProviderError` when the output carries no text.++Optional hooks on `AgentCliProvider`, override only what the CLI needs:++| Hook | Default | Override when |+|---|---|---|+| `build_stdin(system_prompt, user_prompt)` | the user prompt alone | the CLI has no system-prompt flag and the two must be combined (opencode, codex) |+| `working_dir()` | no cwd change | the CLI should run somewhere neutral, such as a scratch dir (claude_cli) |+| `subprocess_env()` | inherit the parent env | the CLI needs env vars, such as a locked-down config (opencode) |+| `exec_timeout_seconds()` | `EXEC_TIMEOUT_SECONDS` (600) | the CLI needs a different ceiling |+| `exit_error(returncode, stdout, stderr)` | `ProviderError` with the stderr tail | a non-zero exit needs a clearer message, such as "not logged in" (claude_cli) |+| `stdout_error(stdout)` | `None` | the CLI reports failures as structured events on stdout (opencode) |++Class attributes with defaults: `default_model` (`None` lets the CLI's own+config choose), `validates_model_name` (`True`; codex turns it off and lets its+model catalog decide), `records_cost` (`False`; only claude_cli+books `llm_costs` rows), `error_tail_chars`.++From `BaseProvider`, override `available_model_options()` when the CLI can list+its models (opencode runs `opencode models`, cached with `lru_cache`, with+`stdin=subprocess.DEVNULL`), and `supported_reasoning_modes()` when the CLI+takes a reasoning flag. The defaults offer one option, the configured model,+with reasoning `auto`.++`self._repo_path` holds the repo the CLI should read. Pass it with the CLI's+directory flag (opencode uses `--dir`, codex `--cd`) if the CLI has one.++### Step 2: the `ProviderSpec`++Add a record to `_SPECS` in `core/providers/llm/specs.py`. Declaration order is+the server catalog's order.++```python+ProviderSpec(+ name="copilot_cli",+ picker_rank=9,+ impl=f"{_LLM}.copilot_cli:CopilotCliProvider",+ label="GitHub Copilot (Local CLI)",+ default_model="copilot_cli/default",+ models=("copilot_cli/default",),+ keyless=True,+ needs_repo_cwd=True,+ local=True,+ zero_cost=True,+ agent="copilot",+ note="uses your Copilot CLI login",+),+```++| Field | What reads it |+|---|---|+| `name`, `impl` | `get_provider` imports `impl` lazily; `_BUILTIN_PROVIDERS` is derived from it |+| `label` | the server catalog's display name, shown in the web UI settings |+| `default_model`, `models` | the init picker's model list and the server catalog; agent CLI models are prefixed `<name>/` |+| `keyless` | `KEYLESS_PROVIDERS`: resolution never rejects the provider for a missing key |+| `needs_repo_cwd` | `REPO_PATH_PROVIDERS`: `provider_kwargs` passes `repo_path`, and a workspace init rebinds the provider to each repo. Leave it off if the CLI runs in a scratch dir |+| `local` | init warns that concurrency above 4 may time out; the server prices unknown local models at zero |+| `zero_cost` | `ZERO_COST_MODEL_PREFIXES`: the cost estimator and cost tracker price `<name>/...` models at zero |+| `agent` | the agent slug; links the spec to the identity and supplies `setup_hint` from its install and login hints |+| `picker_rank` | the row in the `repowise init` picker and inclusion in `/api/providers`; `None` makes it flag-only |+| `note` | the dim note beside the row in the picker, and the reason line when the picker defaults to it |++Agent CLIs keep `rate_limit=None`, `api_key_envs=()` and `autodetect_rank=None`.++Ranks must stay unique. Today opencode is 8, ollama 9, openrouter 10 and+litellm 11. Giving `copilot_cli` rank 9 puts it right after opencode, so+change ollama to 10, openrouter to 11 and litellm to 12.++### Step 3: link the identity++`COPILOT` already exists in `core/agents/identity.py` with `executable`,+`install_hint` and `login_hint`. The only edit is `indexing_provider="copilot_cli"`+on that record. Add `login_check` only if the CLI has a status command, verified+against its docs, that exits 0 only when signed in; the init picker uses it to+decide whether the backend is ready.++For an agent with no identity yet, add one as in+[Recipe B step 1](#step-1-the-identity), with `executable`, `install_hint` and+`login_hint` set: the CLI prints them when the executable is missing.++### Step 4: the contract test++Add one `Backend` to `BACKENDS` in+`tests/unit/test_providers/test_agent_cli_contract.py`, and import the class at+the top of the file:++```python+@dataclass(frozen=True)+class Backend:+ cls: type[AgentCliProvider]+ model: str # a native slug the CLI receives after ``--model``+ success_stdout: Callable[[str], str] # CLI output whose answer is the argument+ tokens: tuple[int, int, int] # parsed (input, output, cached)+ books_cost: bool+ repo_flag: str | None # flag that points the CLI at the repo; None = scratch cwd+ env: dict[str, str] | None # entries the subprocess env must carry+```++`success_stdout` is a function that returns real CLI output with the answer+swapped in. Build it from a real run: run the CLI once in the mode+`build_command` uses, keep the events `parse_output` reads (the text and the+usage), and write them as a builder next to `_opencode_stdout`. Provider output+samples live inline in the tests, not in `tests/fixtures/`. Do not invent+fields the CLI does not emit.++The contract then checks names, the missing-executable error, argv and stdin,+the repo flag or scratch dir, the env, cost booking, the non-zero exit, timeout+and cancellation kills, and the concurrency semaphore. CLI-specific parsing+(noise lines, error events, missing usage, the model catalog) goes in a+`tests/unit/test_providers/test_copilot_cli_provider.py` <!-- repowise-drift-ignore -->+modelled on `test_opencode_provider.py`.++### Step 5: update the frozen lists++Two tests in `tests/unit/cli/test_init_ux.py` freeze the picker on purpose, so+a new row is a deliberate edit:++- `test_picker_rows_keep_their_order`: put `"copilot_cli"` after `"opencode"` in+ the expected `_PROVIDER_CHOICES` tuple.+- `test_the_keyless_providers_get_setup_help_instead_of_a_key_prompt`: add+ `"copilot_cli"` to the expected set of `_LOCAL_PROVIDER_SETUP` keys.++Provider-name literals are fine in tests: the provider-name guard scans+`packages/*/src` only.++Then regenerate the matrix, whose `Indexing` column now reads `Yes` for the+agent:++```bash+python scripts/gen_agent_matrix.py+```++### Step 6: user docs (optional)++A user page at `docs/agent/<NAME>.md` is optional. If you add one, follow+`docs/agent/OPENCODE.md`, and put paths to files in a user's repo behind+`<!-- repowise-drift-ignore -->`.++### What you get without further edits++- A row in the `repowise init` picker with install and login help when the CLI+ is missing. When the agent is set up as a target in the repo and its CLI is+ ready, the picker defaults to it (`agent_providers_set_up` in+ `cli/ui/provider_selection.py`).+- `repowise init --provider copilot_cli` and keyless resolution in the CLI and+ the MCP server.+- An entry in `/api/providers` with its setup hint, and so in the web UI.+- Zero-cost pricing for its models, no client-side rate limiter, and the+ local-concurrency warning.+- Per-repo binding in a workspace init when `needs_repo_cwd` is set.+- The shared contract tests and the registry link tests.++### Verify++```bash+pytest tests/unit/test_providers/ tests/providers/ -q+pytest tests/unit/cli/test_init_ux.py tests/unit/cli/test_init_agent_backend.py \+ tests/unit/cli/test_agent_identity.py tests/unit/cli/test_agent_matrix.py \+ tests/unit/server/test_provider_config.py -q+ruff check .+```++Then by hand, with the CLI installed and logged in, on a small repo:++```bash+repowise init --provider copilot_cli --yes+repowise init # interactive: check the row, the note and the default+```++---++## Recipe B: adding an integration target++Before writing anything, check every host fact (config file paths, the MCP+entry shape, which instruction files the host reads, how to tell it is+installed) against the host's own docs, and cite the source in the module+docstring. `targets/copilot.py` shows the shape. Where a fact is assumed and+not documented, say so there.++### Step 1: the identity++Add an `AgentIdentity` constant (for example `MYAGENT`) in+`core/agents/identity.py` and append it to the `for _shipped in (...)` tuple at+the bottom of the file. The `--target` id is+derived: `kiro` for slug `kiro`, `claude-code` for `claude_code`. Leave+`hook_adapter` and `session_adapter` unset until Recipe C.++### Step 2: the target module++Write `packages/cli/src/repowise/cli/agent_targets/targets/<id>.py` exporting+`TARGET`, an object that satisfies the `AgentTarget` protocol in `types.py`.+`targets/vscode.py` is the smallest complete example. The usual top of the+module, where `MYAGENT` is the identity constant you added in step 1:++```python+from repowise.core.agents import identity++from ..types import (+ Capability,+ DoctorReport,+ DoctorStatus,+ FileAction,+ FileWrite,+ InstallMethod,+ Registration,+ Scope,+ WriteResult,+)++IDENTITY = identity.MYAGENT+ID = IDENTITY.cli_target_id+DISPLAY_NAME = IDENTITY.display_name+DOCS_URL = "https://..."+PROJECT_FILE_ID = "myagent_mcp" # key under editor_files in .repowise/config.yaml++METHODS = (+ InstallMethod(+ id="direct",+ provides=frozenset({Capability.MCP, Capability.INSTRUCTIONS}),+ managed_by="repowise",+ preferred=True,+ ),+)+```++The class carries the attributes `AgentTarget` requires: `id = ID`,+`display_name = DISPLAY_NAME`, `docs_url = DOCS_URL`, `methods = METHODS`,+`project_file_id = PROJECT_FILE_ID`, `hook_adapter = IDENTITY.hook_adapter` and+`session_adapter = IDENTITY.session_adapter`. The module ends with+`TARGET = MyAgentTarget()`.++Every protocol method must be safe when nothing was ever installed:+`supports_scope`, `is_present` (a PATH or directory probe, never a+subprocess), `detect` (a list of `Registration`s, never raises), `install`,+`uninstall` (removes only what `install` wrote), `print_config` (no filesystem+access), `describe_paths` and `doctor`. Use the writers in `formats/` for+JSON, TOML, YAML and marker blocks; do not hand-roll a merge.++For the instructions block, write the shared text from `instructions.py`+(`DISTILL_SECTION` between `DISTILL_MARKER_START` and `DISTILL_MARKER_END`)+with `formats.marker_block.upsert`. Text outside the markers belongs to the+user and must round-trip byte for byte.++If two targets write the same file, one owns the block and the other shares+it. `copilot` reuses `vscode.write_instructions` for+`.github/copilot-instructions.md`, and `vscode.remove_instructions` asks <!-- repowise-drift-ignore -->+`registry.other_managers_of` before stripping the block, so removing one agent+leaves the block in place while the other still reads it.++### Step 3: register it++Append one line to `_TARGET_MODULES` in `agent_targets/registry.py`. Order is+the order agents appear in prompts, in `--target=all` and in listings, so new+ids go at the end. Append the same id to the frozen list in+`test_registry_exposes_the_shipped_targets` in+`tests/unit/cli/test_agent_targets.py`.++The `repowise init` checklist only offers targets that have an+`InstallLifecycle` writer in `get_default_editor_integrations`+(`cli/editor_integrations/defaults.py`): Claude Code, Codex and VS Code. Any+other target is wired with `repowise agents add --target=<id>`, so add a row to+the host table in `docs/start/QUICKSTART.md`.++### Step 4: the README badge and the matrix++Add a badge to the `## Supported agents and editors` section of `README.md`,+under the row for the tier `derive_tier` gives it, and update the count in the+sentence above the badges. Then:++```bash+python scripts/gen_agent_matrix.py+```++### Step 5: verify++```bash+pytest tests/unit/cli/test_agent_targets.py tests/unit/cli/test_agent_identity.py \+ tests/unit/cli/test_agent_matrix.py tests/unit/agents/ -q+repowise agents add --target=<id> --scope=project --yes+repowise agents+repowise agents remove --target=<id> --scope=project+```++The protocol, idempotency, `print_config` and `describe_paths` tests in+`test_agent_targets.py` are parameterized over the registry, so the new target+is covered without new test code.++---++## Recipe C: hook and transcript adapters++A target reaches Full only when its identity names both adapters. Declare only+what is implemented and verified against the host's docs or real data. A name+on the identity is a public claim: it moves the agent to the Full row of the+README and the matrix.++### Hook adapter++Subclass `AgentAdapter` in `cli/agent_adapters/base.py` and add it to+`_REGISTRY` in `cli/agent_adapters/__init__.py`, keyed by the name its hook+config passes as `--client`. Abstract methods: `detect`,+`parse_hook_payload`, `render_response`, `install_rewrite_hook`,+`uninstall_rewrite_hook`, `rewrite_hook_installed`.++The class variables answer what the host's hook protocol can do:+`rewrite_permissions`, `replaces_tool_output`, `shell_tool_names`,+`read_tool_names`, `edit_tool_names`, `search_tool_names`, `savings_source`.+Leave a default in place until the host's docs or a captured payload show+otherwise. A wrong `replaces_tool_output=True` records savings the agent never+saw.++Module scope stays stdlib-only: this runs on the PreToolUse hot path.+`agent_adapters` must never import `agent_targets`.++Set `hook_adapter="<registry key>"` on the identity, and add+`Capability.HOOKS` to the target's install method.++### Transcript adapter++Subclass `HarnessAdapter` in `core/sessions/adapters/base.py`, decorate it+with `@register_adapter`, and import it in `core/sessions/adapters/__init__.py`.+Implement `discover(repo_root, *, projects_root=None)` and+`normalize(raw_line)`; declare `edit_tool_names` and `shell_tool_names` in the+host's own vocabulary. Test it against a real transcript, trimmed and+anonymized, as `tests/unit/sessions/test_claude_code_adapter.py` does.++Set `session_adapter="<adapter name>"` on the identity, and add+`Capability.TRANSCRIPTS` to the target's install method.++---++## Guards you will hit++`tests/unit/test_providers/test_provider_specs.py`:++- `test_no_module_branches_on_a_provider_name` parses every Python source+ under `packages/*/src` and fails when a provider name is used in a+ comparison, a `match` case, a collection, a dict key or a `.get()` key+ outside the registries. Read a `ProviderSpec` field (`spec.agent`,+ `spec.needs_repo_cwd`, `spec.local`) or call `identity_for_provider`+ instead of spelling the name. A provider's own module may spell its own name.+- `test_no_ui_source_spells_a_provider_name` scans `packages/ui`,+ `packages/web` and `packages/api-client` for quoted provider or embedder+ names. The UI reads them from `/api/providers`.+- The link tests fail when `indexing_provider` and `ProviderSpec.agent` do not+ name each other, when the identity lacks `executable`, `install_hint` or+ `login_hint`, or when an agent spec gets a rate limiter.++`tests/unit/cli/test_agent_matrix.py`:++- `docs/agent/INTEGRATIONS.md` must match `python scripts/gen_agent_matrix.py`+ output. Run the script; never edit the file. `--check` reports drift+ without writing.+- The README badge rows must match the derived tiers, and the headline count+ must match the registry.+- A target's `Capability.HOOKS` must agree with its `hook_adapter`.++`tests/unit/cli/test_agent_identity.py` fails when an identity names a hook or+session adapter that is not registered.++CI also runs `repowise doc-drift --check`, which flags a doc that names a file,+symbol or command that does not exist. A path to a file in a user's repo, or a+file you are about to create, needs `<!-- repowise-drift-ignore -->` on its+line.diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex b7bef8661..39fc00e05 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -2014,11 +2014,11 @@ repowise generate-claude-md --verbose # show pipeline debug logs### `repowise agents`Manage the agent integrations repowise can wire up on this machine: Claude-Code, Codex, Cursor, OpenCode, Hermes, and anything reachable through-`print-config`. `init` already wires the primary ones as part of a first run;-this group is for what comes after it: adding an agent installed later,-removing one, refreshing config after an upgrade, or printing a snippet for a-host repowise does not write files for at all.+Code, Codex, VS Code, Cursor, OpenCode, Hermes, GitHub Copilot CLI, Kiro, and+anything reachable through `print-config`. `init` already wires the primary+ones as part of a first run; this group is for what comes after it: adding an+agent installed later, removing one, refreshing config after an upgrade, or+printing a snippet for a host repowise does not write files for at all.With no subcommand, lists every known agent for the current repo: supporttier, whether it looks installed, and every place it is currently wired todiff --git a/docs/start/QUICKSTART.md b/docs/start/QUICKSTART.mdindex eced955c1..d5de63d3b 100644--- a/docs/start/QUICKSTART.md+++ b/docs/start/QUICKSTART.md@@ -104,6 +104,8 @@ Other hosts need one more command, run after `init`:| Cursor | `repowise agents add --target=cursor --yes` || OpenCode | `repowise agents add --target=opencode --yes` || Hermes | `repowise agents add --target=hermes --yes` |+| GitHub Copilot CLI | `repowise agents add --target=copilot --yes` |+| Kiro | `repowise agents add --target=kiro --yes` || Any other MCP client | `repowise agents print-config claude-code`, then paste the entry into the client's MCP config |`repowise agents` lists every supported host and whether it is wired.diff --git a/scripts/gen_agent_matrix.py b/scripts/gen_agent_matrix.pyindex 5e3ab86a9..e26e278d7 100644--- a/scripts/gen_agent_matrix.py+++ b/scripts/gen_agent_matrix.py@@ -365,7 +365,7 @@ def render() -> str:"repowise agents print-config claude-code # prints, writes nothing","```","",- "Ask for the target id whose host is closest to yours rather than editing a",+ "Ask for the target id whose host is closest to yours instead of editing a","snippet by hand. The shapes genuinely differ, and not only in their wrapper:","hosts disagree about the top-level key, about whether each entry carries a","`type` field, about whether the invocation is one array or a command plus a",@@ -399,42 +399,28 @@ def render() -> str:"","## Adding an agent","",- "**Adding an agent takes one identity record, one descriptor file and one",- "registry line.**",+ "The step-by-step recipes, including indexing backends and hook and",+ "transcript adapters, are in",+ "[docs/architecture/agent-platform.md](../architecture/agent-platform.md).",+ "In short, an integration target is:","",- "1. Add an `AgentIdentity` to",- " [`identity.py`](../../packages/core/src/repowise/core/agents/identity.py):",- " its slug, display name, `executable` and, if its CLI can index,",- " `indexing_provider`.",- "2. Write `packages/cli/src/repowise/cli/agent_targets/targets/<id>.py`",+ "1. An `AgentIdentity` in",+ " [`identity.py`](../../packages/core/src/repowise/core/agents/identity.py).",+ "2. A descriptor module in `packages/cli/src/repowise/cli/agent_targets/targets/`"," exporting a `TARGET` that satisfies the `AgentTarget` protocol in"," [`types.py`](../../packages/cli/src/repowise/cli/agent_targets/types.py).",- " `vscode.py` is the smallest working example, at one install method and",- " one config file.",- "3. Add one line to `_TARGET_MODULES` in",+ "3. One line in `_TARGET_MODULES` in"," [`registry.py`](../../packages/cli/src/repowise/cli/agent_targets/registry.py).",- " Order there is the order agents appear in prompts, in `--target=all` and",- " in listings, so keep it stable.",- "4. Run `python scripts/gen_agent_matrix.py` to add the row here.",+ "4. A README badge under the tier `derive_tier` gives it, checked by",+ " `tests/unit/cli/test_agent_matrix.py`.",+ "5. `python scripts/gen_agent_matrix.py` to add the row here.","",- "An indexing backend adds three more pieces: a `ProviderSpec` in",+ "An indexing backend is its own module in",+ "`packages/core/src/repowise/core/providers/llm/` subclassing `AgentCliProvider`,",+ "a `ProviderSpec` in","[`specs.py`](../../packages/core/src/repowise/core/providers/llm/specs.py),",- "an `AgentCliProvider` subclass in",- "[`agent_cli.py`](../../packages/core/src/repowise/core/providers/llm/agent_cli.py),","and one `Backend` entry in",- "`tests/unit/test_providers/test_agent_cli_contract.py`, which runs the shared",- "provider contract against it.",- "",- "There is no further file for anything derived. The tier, this matrix and the",- "`repowise agents` listing all read the descriptor, and the contract tests in",- "`tests/unit/cli/test_agent_targets.py` are parameterized over the registry,",- "so a new target inherits them.",- "",- "The README badge rows are the exception: a brand colour and a logo per agent",- "are not derivable, and the README is not generated, so a new agent needs a",- "badge added by hand and the count above them updated. That is checked rather",- "than trusted. `tests/unit/cli/test_agent_matrix.py` fails when the badge rows",- "and the registry disagree, and names what to add.",+ "`tests/unit/test_providers/test_agent_cli_contract.py`.","","Declare only what the agent genuinely has. `derive_tier` reads the adapter","names, so a descriptor that names a hook adapter it has not implemented",