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.

docs: readable reference, CI, config, MCP and health docs, with repo-wide test intelligence accuracy (#4342)

Raghav Chamadiya54c80036189c
diff --git a/README.md b/README.md
index cb9ce0695..07edf65f1 100644
--- a/README.md
+++ b/README.md
@@ -328,9 +328,9 @@ repowise impacted-tests main..HEAD # only the tests this diff exercises
repowise health # untested hotspots, graph-aware
```
-<sub>Checked against real per-test coverage on this repository:
-<strong>95.7% precision</strong> on what reaches a file and <strong>97.5% on the run
-list</strong>. Every row is stamped <code>basis: "measured"</code> or
+<sub>Checked against this repository's own test coverage:
+<strong>97.7% precision</strong> on the files tests call into and <strong>97.5% on the run
+list</strong> (on a slice with per-test attribution). Every row is stamped <code>basis: "measured"</code> or
<code>"inferred"</code>, measured wins where both can answer, and an empty answer means
unknown, never "no tests".
<a href="docs/layers/TEST_INTELLIGENCE.md"><strong>Test intelligence →</strong></a></sub>
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index f4a41a823..e865ca1c8 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -1,10 +1,12 @@
# MCP Tools Reference
-repowise serves its codebase intelligence to AI coding assistants (Claude Code, Codex, Cursor, Cline, Windsurf and any other [Model Context Protocol](https://modelcontextprotocol.io) client) as a set of MCP tools. The tools answer questions from the index: the dependency graph, git history, generated docs, decision records, health and dead-code analysis. None of them edits your code. Two opt-in tools go further: `set_finding_status` records a triage verdict in the index, and `generate_refactoring_code` calls your configured LLM to draft a diff.
+repowise serves its codebase intelligence to AI coding assistants (Claude Code, Codex, Cursor, Cline, Windsurf and any other [Model Context Protocol](https://modelcontextprotocol.io) client) as MCP tools. They answer from the index: dependency graph, git history, generated docs, decision records, health and dead-code analysis. No tool edits your code.
+
+Two opt-in tools go further: `set_finding_status` records a triage verdict in the index, and `generate_refactoring_code` calls your LLM to draft a diff.
18 tools are registered in total. A single-repo server advertises 10 by default: exactly the canonical tools. Workspace mode adds the `list_repos` discovery utility, for 11. 7 specialist tools are opt-in where eligible.
-This page tells you which tool to call and with what arguments. Every response field, the full `_meta` envelope and the truncation rules are in [MCP_RESPONSE_FIELDS.md](../reference/MCP_RESPONSE_FIELDS.md).
+This page says which tool to call and with what arguments. Response fields, the `_meta` envelope and truncation rules are in [MCP_RESPONSE_FIELDS.md](../reference/MCP_RESPONSE_FIELDS.md).
## Contents
@@ -23,7 +25,6 @@ This page tells you which tool to call and with what arguments. Every response f
**Opt-in specialists (7; workspace eligibility still applies)**
[get_dependency_path](#get_dependency_path) &middot; [get_execution_flows](#get_execution_flows) &middot; [generate_refactoring_code](#generate_refactoring_code) &middot; [set_finding_status](#set_finding_status) &middot; [get_blast_radius](#get_blast_radius) &middot; [get_architecture](#get_architecture) &middot; [get_conformance](#get_conformance)
-
---
## Starting the server
@@ -34,7 +35,9 @@ repowise mcp --transport streamable-http # HTTP on port 7338
repowise mcp --transport sse --port 7338 # legacy SSE transport
```
-`repowise init` registers the server with Claude Code and installs its hooks; `repowise init --codex` writes project-local Codex MCP config and hooks. Pass `--no-editor-setup` (or set `REPOWISE_SKIP_EDITOR_SETUP=1`) for a scratch clone, worktree or CI run you do not want registered. Each Claude config holds a single `repowise` entry, so indexing a second repo repoints it; `init` prints a notice before it does.
+- `repowise init` registers the server with Claude Code and installs its hooks; `repowise init --codex` writes project-local Codex MCP config and hooks.
+- `--no-editor-setup` (or `REPOWISE_SKIP_EDITOR_SETUP=1`) skips registration for a scratch clone, worktree or CI run.
+- Each Claude config holds one `repowise` entry, so indexing a second repo repoints it; `init` prints a notice first.
---
@@ -47,7 +50,10 @@ repowise mcp --transport sse --port 7338 # legacy SSE transport
| `get_dependency_path`, `get_execution_flows`, `generate_refactoring_code`, `set_finding_status` | opt-in | single-repo and workspace |
| `get_blast_radius`, `get_architecture`, `get_conformance` | opt-in | workspace only |
-Change the surface in `.repowise/config.yaml` under `mcp.tools`:
+- **Default (single-repo):** 10 tools, exactly the canonical intelligence set.
+- **Default (workspace):** those 10 plus `list_repos`, the workspace discovery utility.
+
+Set `mcp.tools` in `.repowise/config.yaml`, or pass `--tools` per launch (it overrides the config):
```yaml
mcp:
@@ -57,8 +63,6 @@ mcp:
# tools: lean # the agent-lean profile
```
-Or per launch, which overrides the config block:
-
```bash
repowise mcp --tools "+get_execution_flows" # default set plus one
repowise mcp --tools "get_answer,get_context" # explicit allowlist
@@ -66,43 +70,32 @@ repowise mcp --tools lean # agent-lean profile
repowise mcp --all # every tool usable in this mode
```
-The dashboard Settings page has a per-repo toggle for each tool and writes the same `mcp.tools` block.
-
-- Tokens prefixed `+` or `-` adjust the default set. A list without prefixes is an allowlist.
-- Unknown names are ignored with a warning. A workspace-only tool named outside workspace mode is ignored too: it has no workspace graph to read.
-- Raw MCP clients see the surface resolved when the server started. Restart the server after changing it.
-
-- **Default (single-repo):** 10 tools, exactly the canonical intelligence set.
-- **Default (workspace):** those 10 plus `list_repos`, the workspace discovery utility.
+- `+` or `-` tokens adjust the default set; a list without prefixes is an allowlist.
+- Unknown names are ignored with a warning, as are workspace-only tools outside workspace mode (no workspace graph to read).
+- Clients see the surface resolved at server start; restart after changing it.
+- The dashboard Settings page toggles each tool per repo and writes the same block. See [CONFIG.md](../reference/CONFIG.md#the-mcp-block).
-**The `lean` profile** is `get_answer`, `get_context`, `get_symbol`, `search_codebase`, `get_risk` and `get_why`, plus `list_repos` in workspace mode. It is small enough to keep every schema loaded, so when a repo sets `mcp.tools: lean`, `repowise init` skips the Claude Code tool-search recommendation.
-
-See [CONFIG.md](../reference/CONFIG.md#the-mcp-block) for the config block itself.
+**The `lean` profile** is `get_answer`, `get_context`, `get_symbol`, `search_codebase`, `get_risk` and `get_why`, plus `list_repos` in workspace mode. It is small enough to keep every schema loaded, so with `mcp.tools: lean`, `repowise init` skips the Claude Code tool-search recommendation.
---
## Reading a response
-Every tool returns a JSON object with a `_meta` envelope. Most fields appear only when they carry a signal. An agent should check these:
-
-| Field | What to do with it |
-|-------|--------------------|
-| `stale_warning` | Present only when the index is behind in a way that changed served files, or a served file has uncommitted edits or was indexed from edits since reverted (`working_tree_dirty` counts the edited ones; run `repowise update --working-tree`). Run `repowise update` before trusting file-level detail. Its absence means current. |
-| `indexed_commit`, `live_head`, `index_behind` | Which commit the answer describes and whether HEAD has moved since. |
-| `complete` | Symbol bodies or whole files served verified against the live file. Do not re-read them. |
-| `state` | `degraded`, `partial` or `truncated` when something fired, with reasons. A degraded empty result is a failed read, not an empty repository. |
-| `omitted` | Refs to content cut for size. Restore with `repowise expand <ref>` or `get_symbol("repowise#<ref>")`. |
-| `response_budget` | The character ceiling that applied and the size delivered. Present when the budget cut something. |
+Every tool returns JSON with a `_meta` envelope ([fields](../reference/MCP_RESPONSE_FIELDS.md#the-_meta-envelope)). Check:
-`get_answer` adds a top-level `confidence`, its one trust signal, graded from the retrieval and from whether the top hit covers what the question asks; `include=["diagnostics"]` adds `retrieval_quality`, the rating of the retrieval alone. Diagnostics such as `timing_ms` and `contract_version` ride only on `get_overview`; `REPOWISE_MCP_DEBUG_META=1` restores them everywhere. Full envelope: [MCP_RESPONSE_FIELDS.md](../reference/MCP_RESPONSE_FIELDS.md#the-_meta-envelope).
+- `stale_warning`: run `repowise update` (or `repowise update --working-tree` when `working_tree_dirty` is set) before trusting file-level detail. Absent means current.
+- `complete`: content verified against the live file. Do not re-read it.
+- `state`: `degraded`, `partial` or `truncated`. A degraded empty result is a failed read, not an empty repository.
+- `get_answer`'s top-level `confidence` is its one trust signal.
+- Diagnostics such as `timing_ms` ride only on `get_overview`; `REPOWISE_MCP_DEBUG_META=1` restores them everywhere.
### Reversible truncation: `_meta.omitted`
-Responses fit 24,000 serialized characters by default and 32,000 when the call passes an expansion argument (a nonempty `include`, for most tools). Content cut to fit is stored in the repo's [omission store](DISTILL.md#the-omission-store), and `_meta.omitted` lists the refs that restore it. Capped lists carry `*_total` siblings, so a count is never lost with its rows. Details: [MCP_RESPONSE_FIELDS.md](../reference/MCP_RESPONSE_FIELDS.md#truncation-and-recovery).
+Responses fit 24,000 characters (32,000 with a nonempty `include` for most tools). Cut content goes to the [omission store](DISTILL.md#the-omission-store); restore a ref from `_meta.omitted` with `repowise expand <ref>` or `get_symbol("repowise#<ref>")`. Capped lists keep `*_total` counts. [Details](../reference/MCP_RESPONSE_FIELDS.md#truncation-and-recovery).
### Unrecognised arguments: `ignored_arguments`
-A value outside a closed vocabulary (a misspelled `kind`, `include` key or `mode`) is dropped, never applied as a filter that matches nothing. The response then names it in `ignored_arguments`, with the valid values. The key is absent when every argument was understood. Per-tool shapes: [MCP_RESPONSE_FIELDS.md](../reference/MCP_RESPONSE_FIELDS.md#ignored-arguments).
+A value outside a closed vocabulary (a misspelled `kind`, `include` key or `mode`) is dropped, never applied as a filter matching nothing, and named in `ignored_arguments` with the valid values. [Per-tool shapes](../reference/MCP_RESPONSE_FIELDS.md#ignored-arguments).
---
@@ -132,151 +125,142 @@ A value outside a closed vocabulary (a misspelled `kind`, `include` key or `mode
| How coupled is the whole system? | `get_architecture` (workspace, opt-in) |
| Does the system obey our declared dependency rules? | `get_conformance` (workspace, opt-in) |
----
+Every `repo` parameter takes a workspace repo alias and defaults to the default repo; `"all"` support is in [Workspace mode](#workspace-mode).
-## Default tools
+---
-### `get_answer`
+## `get_answer`
-Answers a how, where or why question in one call: it runs hybrid retrieval over the wiki and the symbol index, then synthesises a cited answer. Use it first for any question about the code. Skip it when you already know the exact file or symbol; go to `get_context` or `get_symbol`.
+Answers a how, where or why question in one call: hybrid retrieval over the wiki and symbol index, then a cited answer. Call it first for any question; skip it when you know the exact file or symbol (use `get_context` or `get_symbol`).
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
| `question` | string | required | The question, in plain language |
-| `scope` | string | none | Path prefix to restrict retrieval to, e.g. `"src/auth/"` |
-| `repo` | string | default repo | Workspace repo alias. `"all"` is not supported |
-| `include` | list[string] | none | `["evidence"]` returns the full evidence projection with a larger budget |
+| `scope` | string | none | Path prefix to restrict retrieval, e.g. `"src/auth/"` |
+| `include` | list[string] | none | `evidence` (full evidence, larger budget), `diagnostics` (adds `retrieval_quality`) |
+| `repo` | string | default repo | `"all"` not supported |
-**Key return fields:** `answer`, `confidence` (`high` / `medium` / `low`), `citations`, `symbol_bodies` (live bodies of symbols the answer names), `retrieval`, `best_guesses` and `fallback_targets` (on low confidence; a low `best_guesses` row carries `functions`, `lines` and `size_bytes` instead of a page excerpt), `candidate_files` (ranked file paths the citations do not already name: up to 3 at `high`, 5 otherwise), `episodes` (dated facts bearing on the question), `degraded` (synthesis could not run), `_meta.scope_hint` (areas the answer did not touch).
-
-A `high` answer can be cited directly. On `low`, read the rows the reply names, then `candidate_files`, before searching again. Without an LLM provider the tool still answers from retrieval, marked `degraded`. When retrieval is also `weak`, the reply serves `best_guesses` and `candidate_files` with one guidance line in `answer`, and no `citations`.
+**Returns** `answer`, `confidence`, `citations`, `symbol_bodies`, `candidate_files`, `best_guesses` ([fields](../reference/MCP_RESPONSE_FIELDS.md#get_answer)). On `low`, read the named rows, then `candidate_files`, before searching again. Without an LLM provider it answers from retrieval, marked `degraded`.
```
get_answer(question="How does the authentication flow work?")
```
-### `get_context`
+---
-A triage card for files, modules or symbols: summary, symbols with signatures and line numbers, hotspot and fix-history cues, ownership and decisions. It returns relationships, not source. Use it before reading or editing code, and batch every target in one call. Do not call `get_symbol` once per signature; use `include=["skeleton"]` or read the file.
+## `get_context`
+
+A triage card per file, module or symbol: summary, symbols with signatures, hotspot and fix-history cues, ownership, decisions. Relationships, not source. Use it before reading or editing, batching every target in one call; use `include=["skeleton"]` or read the file rather than calling `get_symbol` per signature.
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
-| `targets` | list[string] | required | File paths, module paths, `"path::Symbol"` ids, `"component:<name>"`, `"change:<id>"`, or `"package:<name>"` |
-| `include` | list[string] | none | Any of `full_doc`, `ownership`, `last_change`, `callers`, `callees`, `references`, `metrics`, `community`, `decisions`, `skeleton`, `health`, `doc_drift`, `symbols`, `changes`, `provenance`, `suspects` |
+| `targets` | list[string] | required | Paths, module paths, `"path::Symbol"`, `"component:<name>"`, `"change:<id>"`, `"package:<name>"` |
+| `include` | list[string] | none | `full_doc`, `ownership`, `last_change`, `callers`, `callees`, `references`, `metrics`, `community`, `decisions`, `skeleton`, `skeleton+`, `health`, `doc_drift`, `symbols`, `changes`, `provenance`, `suspects` ([what each adds](../reference/MCP_RESPONSE_FIELDS.md#context-opt-in-blocks)) |
| `compact` | bool | `true` | `false` adds the structure block, imports and docstrings |
-| `repo` | string | default repo | Workspace repo alias. `"all"` is not supported (returns an error) |
-| `symptom` | string | none | Issue text, an error message or a pasted stack trace for `include=["suspects"]` to rank against, in place of the words in the target paths |
-
-**Key return fields:** `targets` keyed by target, each with title, summary, symbols, `hotspot`, `fix_history` (files with counted bug fixes), `episodes`, decision titles, `file_preview` (for files with no symbols), `resolved_to` (a symbol miss falling back to its file); `dropped_targets` and `recovery` when the budget forced targets out; `_meta.complete` for whole files served.
-
-A `component:<name>` target returns the component's declared context (owner, system, criticality, tags) and `facts` rolled up over its files: health, hotspots, bus factor, test reach and dead code, each with a `basis` (`measured`, `inferred` or `unavailable`). Components come from [`.repowise/components.yaml`](../reference/CONFIG.md#repowisecomponentsyaml) or are derived from the index. With `include=["ownership"]` a component card adds `ownership`: declared teams with their activity over the last 90 days, a count of individual owners, and findings (`critical_no_active_owner`, `declared_owner_inactive`, `critical_bus_factor_one`, `catalog_entry_no_code`). An owner with no identity in the indexed history is `unknown` and raises no finding, so `critical_no_active_owner` does not fire when every owner is unknown; individuals match only by exact git email or forge noreply login. No other `include` applies to component targets. Health and dead code leave out files in gated languages and say how many.
-
-A `change:<id>` target (`change:pr-123`, or a commit sha the change landed) returns the [Change Record](../reference/CLI_REFERENCE.md#repowise-changes): title, forge ref, `merged_at`, category, files and provenance with its coverage. On a file target, `changes` lists the newest Change Records that touched it, and `provenance` gives the file's commits by source (agent, human-attested, unknown) with coverage; the agent share is withheld below 30% coverage. With attribution off, `provenance` reads `{"unavailable": "attribution_off"}` and change rows carry none. `suspects` adds one top-level block: the changes merged in the last 14 days ranked against the targets' files and the words in their paths, or the `symptom` text when one is given, at most 5 rows, each with the signals that fired and their evidence, plus the candidate count and window; an order to read changes in, never a cause.
+| `symptom` | string | none | Issue text, error or stack trace for `suspects` to rank against instead of path words |
+| `repo` | string | default repo | `"all"` returns an error |
-A `package:<name>` target (`package:requests`, or `package:npm:lodash`) returns where that third-party package is imported: its manifest declarations, a summary, the components and declared owner teams, and up to 25 import sites with line, `mapping` (`declared` or `inferred`) and `reachability` (`reachable`, `unreachable`, `test` or `unknown`, with a basis). See [PACKAGE_USAGE.md](../reference/PACKAGE_USAGE.md).
+Target kinds:
-A file's compact symbol list holds its top 15 symbols: types (classes, interfaces, structs, traits, enums, type aliases, impls, modules) first, then functions and methods, then the rest, each group by centrality. `symbols_truncated` gives the total, and `include=["symbols"]` lists them all. When the response budget trims the list further, it keeps symbols by kind and name match, not centrality. A row without `symbol_id` is `path::name`; methods and overload variants carry theirs, so pass a row's id to `get_symbol` when it has one.
+- `path::Symbol`: a miss falls back to the file's card.
+- `component:<name>`: declared context and rolled-up facts, from [`.repowise/components.yaml`](../reference/CONFIG.md#repowisecomponentsyaml) or derived.
+- `change:<id>` (`change:pr-123` or a commit sha): one [Change Record](../reference/CLI_REFERENCE.md#repowise-changes).
+- `package:<name>` (`package:requests`, `package:npm:lodash`): where a package is imported ([PACKAGE_USAGE.md](../reference/PACKAGE_USAGE.md)).
-`full_doc` returns the page as `content_md`, plus `digest_md` on pages that carry an agent digest: the questions the page answers, its concept index, public API and git signals. Both are dropped first when the response is over budget. `skeleton` renders a file with bodies elided: every signature, the imports, and the bodies of its most central symbols, with line ranges on every elision. `doc_drift` lists the documents that name the file and whether they carry drift. An empty `callers` or `callees` list comes with a `*_basis` saying how much of that language's calls the graph resolved; read it before concluding nothing calls a symbol.
-
-`references` is the edit set for a symbol target: every live line naming it, as `{path, line, kind, text}` with kind `definition`, `import`, `call` or `reference`. For a rename, a `complete` list is the whole edit set. Otherwise `reasons` says why. It is never complete for:
-
-- languages other than Python, TypeScript and JavaScript (same-package use needs no import)
-- more than 200 sites, a stale call line, an unreadable file, or an uncommitted edit outside the scanned files
-- a rename on import, export or destructure, a default export, or a CommonJS export
-- a dynamic use the graph recorded; access built from strings is otherwise not seen
-- more than 3 plain `reference` sites in one file: the rest are counted in `sites_omitted_by_file`, recoverable from `_meta.omitted`
+**Returns** `targets` (one card each), plus `dropped_targets` and `recovery` when the budget forced targets out ([fields](../reference/MCP_RESPONSE_FIELDS.md#get_context)). Pass a symbol row's `symbol_id` to `get_symbol`. Before concluding nothing calls a symbol, read the `*_basis` beside an empty `callers` list. `references` gives a rename's edit set.
```
get_context(targets=["src/auth/middleware.ts", "src/api/routes.ts"], include=["callers"])
get_context(targets=["src/big_module.py"], include=["skeleton"])
```
-### `get_symbol`
+---
+
+## `get_symbol`
-Returns verified, line-numbered source for one symbol, a live line range, or an omission ref. It is a follow-up read, not an entry point: use it on an id another response gave you, for a body that was elided, or to restore truncated output. `get_answer` already ships `symbol_bodies`.
+Verified, line-numbered source for one symbol, a live line range, or an omission ref. A follow-up read, not an entry point: use it on an id another response gave you, an elided body, or truncated output. `get_answer` already ships `symbol_bodies`.
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
-| `symbol_id` | string | none | `"path/file.py::Name"`, `"path/file.py:140-180"` (live range, 200 lines max), or `"repowise#<ref>"` |
+| `symbol_id` | string | none | `"path/file.py::Name"`, `"path/file.py:140-180"` (live range, 200 lines max) or `"repowise#<ref>"` |
| `id` | string | none | Alias for `symbol_id` |
-| `reference` | object | none | A `continuation_reference` or `fetch_reference` this tool emitted; pass it unchanged |
+| `reference` | object | none | A `continuation_reference` or `fetch_reference` this tool emitted, unchanged |
| `context_lines` | int | `0` | Extra lines before and after, 0 to 50 |
-| `depth` | int | `1` | 2 or 3 also returns the bodies it calls, transitively |
-| `query` | string | none | Omission refs only: keep stored lines matching this regex or substring. With no `symbol_id` or `id`, it is read as `symbol_id` |
-| `repo` | string | default repo | Workspace repo alias. `"all"` is not supported |
+| `depth` | int | `1` | 2 or 3 adds the bodies it calls, transitively |
+| `query` | string | none | Omission refs: keep lines matching this regex or substring. Read as `symbol_id` when none is given |
+| `repo` | string | default repo | `"all"` not supported |
-**Key return fields:** `source` (up to about 600 lines, each prefixed with its line number), start and end lines, `kind`, `truncated` with a continuation to pass back, `ambiguous` and `candidates` when several symbols match, `callee_bodies` (with `depth` above 1), `not_rendered` (bodies past the budget, each with a range read to fetch it), fallback lines from a live grep on a miss. A class or other container too large to serve whole returns `outlined: true`, its header in `source` and `members` (each member's `symbol_id`, signature and lines, with `members_total` when the list is capped) in place of the body, and no `_meta.complete`.
+**Returns** `source` (about 600 lines max), bounds, `kind`, `truncated`, `candidates`, `callee_bodies`, `outlined` ([fields](../reference/MCP_RESPONSE_FIELDS.md#get_symbol)).
```
get_symbol(symbol_id="src/auth/service.py::login", depth=2)
get_symbol(symbol_id="repowise#a1b2c3d4e5f6", query="FAILED")
```
-### `search_codebase`
+---
+
+## `search_codebase`
-Hybrid search that routes by the shape of the query: identifiers search the symbol index, paths resolve files, prose runs wiki-semantic search, and mixed queries run both, keeping only pages that name a file. Use it when you want ranked hits themselves: enumerating matches, resolving an identifier to a `symbol_id`, scoping a later `get_context`. For a question, call `get_answer`; it runs this retrieval internally.
+Hybrid search routed by query shape: identifiers hit the symbol index, paths resolve files, prose runs wiki-semantic search, and mixed queries run both, keeping only pages that name a file. Use it for ranked hits (enumerating matches, resolving an identifier to a `symbol_id`, scoping a `get_context`); for a question, use `get_answer`, which runs this retrieval.
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
-| `query` | string | `""` | Identifier, path or natural-language text. Required unless `pattern` is given |
-| `pattern` | string | none | Alias for `query`. When both are given, `query` is used and `pattern` is named in `ignored_arguments` |
-| `limit` | int | `5` | Max results. Outside `symbol` mode, at most this many distinct files: same-file hits share one row |
-| `mode` | string | `"auto"` | `auto`, `concept`, `symbol`, `path` or `hybrid`. An unknown mode runs as `auto` |
+| `query` | string | `""` | Identifier, path or natural language. Required unless `pattern` is given |
+| `pattern` | string | none | Alias for `query`; when both are given `query` wins and `pattern` lands in `ignored_arguments` |
+| `limit` | int | `5` | Max results; outside `symbol` mode, max distinct files |
+| `mode` | string | `"auto"` | `auto`, `concept`, `symbol`, `path`, `hybrid`; unknown runs as `auto` |
| `kind` | string | none | `implementation`, `test`, `config` or `doc` |
-| `symbol_kind` | string | none | Filter symbol hits, e.g. `function`, `class`, `method` |
+| `symbol_kind` | string | none | Symbol filter, e.g. `function`, `class`, `method` |
| `page_type` | string | none | One page type, usually `file_page` or `module_page` |
-| `repo` | string | default repo | Workspace repo alias, or `"all"` to search every repo |
-
-**Key return fields:** `results` (every row that names a file carries it in `path`, and a row naming no file has no `path`; symbol hits carry `symbol_id`, line bounds and `signature`, plus `symbols` (`name:line` of up to five other matches in that file, then `+N more`) when several matched; concept hits carry `relevance_score` and `snippet`, plus `sources` unless it would be `["fts"]` on an index without embeddings; a row leaves off `page_id` and a structural `title` (`File: <path>`) where `page_type` plus `symbol_id` or `path` rebuild them; the old `file` alias is gone, and a page keeps `target_path` only where it differs from `path`), `candidates` (up to `limit` distinct openable file paths, best first). If your next move is a Read, read `candidates`: some `results` are pages that are not files.
-
-**Page rows** also carry `symbols`: up to three `name:line` entries (`Owner.member` for members) in that file whose names match the query's words. The first three page rows whose file has a matching line also carry `matched_lines`: a sample of up to three `{line, text}` source lines read from the live file that share the most query words, code lines before comments and imports. Unlike `lines`, it is never every match.
+| `repo` | string | default repo | Or `"all"` for every repo |
-An identifier or literal query also returns `lines` (`{path, line, kind, text}`, definitions first, at most 50): the `get_context` `references` of one to three exact symbols, else a live scan for the token (kind `definition` or `match`). `complete` is true only when they are every match (see `references` above); otherwise `reasons` says why. Past 3 plain `reference` lines in one file, and past 50 lines, rows are counted in `lines_omitted_by_file` and recoverable from `_meta.omitted`; test files sort after production files. A query of several words caps `lines` at 15 (definitions, then calls, then imports) and lists the 5 files with the most omitted rows, with `lines_omitted_by_file_total` counting all of them.
+**Returns** `results`, `candidates` (openable file paths), and `lines` with `complete` for identifier queries ([fields](../reference/MCP_RESPONSE_FIELDS.md#search_codebase)). Before a Read, read `candidates`: some `results` are pages, not files.
```
search_codebase(query="GitIndexer index_repo")
search_codebase(query="login", mode="symbol", symbol_kind="method")
```
-### `get_risk`
+---
+
+## `get_risk`
-What history says about touching a file: hotspot score, bug-fix record, owners, co-change partners, dependents and security signals. Pass `changed_files` for PR mode, where the response leads with a `directive` naming what may break and which tests to run. To review a commit or diff itself, use `get_change_risk`.
+What history says about touching a file: hotspot, bug-fix record, owners, co-change partners, dependents and security signals. With `changed_files` (PR mode) it leads with a `directive`: what may break and which tests to run. To review the diff itself, use `get_change_risk`.
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
| `targets` | list[string] | `changed_files` | File paths to assess |
| `changed_files` | list[string] | none | Files in a change; switches on PR mode |
-| `include` | list[string] | none | `graph` (typed dependents, consumers, cross-repo links), `churn`, `owners` (owner percentages, bus factor, contributor count), `tests` (typed `test_recommendations` in PR mode), `blast` (`pr_blast_radius` in PR mode), `scales` (units and calibration, identical per call), `changes` (each file's newest Change Records) |
-| `repo` | string | default repo | Workspace repo alias. `"all"` is not supported |
-
-**Key return fields:** per file: `hotspot_score` (0 to 1), `health_score` (0 to 10), `dependents_count`, `co_change_partners` (`file_path`, `support`, `conf_ab`, `has_import_link`), `primary_owner` (detailed owner metrics are opt-in under `include=["owners"]`), test gaps, `security_signals`. In PR mode, `directive` with `may_break`, `missing_cochanges`, `tests_to_run` (the same selection `repowise impacted-tests` makes), `tests_to_run_basis` (`measured`, `inferred` or `none`), `tests_run_all` (with `tests_run_all_reasons` when every test must run), `tests_to_update` (test files to edit, each with a `name_pair`, `imports` or `co_change` reason), `coverage`, `recommended_reviewers`, `next_calls`, and `reach` (`localized`, `moderate` or `broad`; `null` when no structural score was computed). `include=["blast"]` adds `pr_blast_radius`; the raw 0 to 10 `structural_impact_score` and its scale appear there only with `include=["blast", "scales"]`. `missing_tests` appears only when coverage can back it. With no per-test map but stored line coverage, `coverage.reason` is `no_per_test_map_aggregate_available` and `coverage.aggregate` gives its file count and freshness. With `include=["tests"]`, measured rows match a changed file rather than its changed lines (`evidence[].match: "file"`), and a row whose test file is gone or changed since the coverage was measured carries `stale: true` and `stale_reason`. A target naming no indexed file returns `resolved: false` with a reason, never zeroed counts.
+| `include` | list[string] | none | `graph`, `churn`, `owners`, `tests`, `blast`, `scales`, `changes` ([what each adds](../reference/MCP_RESPONSE_FIELDS.md#get_risk)) |
+| `repo` | string | default repo | `"all"` not supported |
-Dependent counts are a floor over the indexed graph, and structural reach is not proof of runtime breakage. `reach` bands an uncalibrated heuristic that never sees the diff; it is not a probability.
+**Returns** per-file `hotspot_score`, `health_score`, `dependents_count`, `co_change_partners`, `primary_owner`, `security_signals`; in PR mode `directive` with `may_break`, `tests_to_run`, `tests_to_update`, `reach` ([fields](../reference/MCP_RESPONSE_FIELDS.md#pr-mode-directive)). Dependent counts are a floor; `reach` is an uncalibrated band, not a probability.
```
get_risk(targets=["src/auth/middleware.ts"])
get_risk(changed_files=["src/api/routes.ts", "src/middleware/cors.ts"])
```
-### `get_change_risk`
+---
+
+## `get_change_risk`
-Reviews one commit, a `base..head` range, or uncommitted work by comparing the two revisions directly; it needs no index refresh. It reports what the change newly made worse across defect, maintainability and performance, which tests cover the changed lines, and the changed files' bug-fix record. Use it before merging. Use `get_risk` for an indexed file's history.
+Reviews a commit, a range, or uncommitted work by comparing the two revisions directly, with no index refresh: what it made worse (defect, maintainability, performance), which tests cover the changed lines, and the files' fix record. Use it before merging; use `get_risk` for an indexed file's history.
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
| `revspec` | string | uncommitted work | A commit, `base..head`, or `base...head` (from the merge-base). Pass `HEAD` when the tree is clean |
| `extensions` | list[string] | all | File suffixes to count, e.g. `[".py", ".ts"]` |
-| `exclude_patterns` | list[string] | none | Gitignore-style paths to omit; combined with a root `.riskignore` |
-| `include_paths` | list[string] or string | all | Gitignore-style paths to keep, as a list or one comma-separated string. Like `exclude_patterns`, it scopes the score, the health delta and every per-file block; `impacted_tests` still selects over the whole change, less only repowise's own output |
-| `baseline` | int | `200` | Recent commits sampled for percentile ranking; `0` disables percentiles |
-| `include` | list[string] | none | `findings` (every finding), `diagnostics` (raw score mechanics, plus the delta's analyzer, revisions and limits), `scales` (units), `evidence` (the change's evidence checklist, the same record `repowise changes show` prints), `tests` (why each listed test runs and the evidence per changed file) |
+| `exclude_patterns` | list[string] | none | Gitignore-style paths to omit, plus a root `.riskignore` |
+| `include_paths` | list[string] or string | all | Gitignore-style paths to keep, as a list or comma-separated string |
+| `baseline` | int | `200` | Recent commits sampled for percentiles; `0` disables |
+| `include` | list[string] | none | `findings`, `diagnostics`, `scales`, `evidence` (the record `repowise changes show` prints), `tests` |
| `finding_id` | string | none | Expand one `health_delta` finding |
-| `repo` | string | default repo | Workspace repo alias. `"all"` is not supported |
+| `repo` | string | default repo | `"all"` not supported |
-**Key return fields:** `directive` (`status` of `review_required`, `review_recommended`, `clear_in_analyzed_scope` or `unknown`, with reasons and next actions), `health_delta` (introduced, worsened and resolved findings with `status` and `top_findings`), `impacted_tests`, `patch_coverage` (when coverage is stored), `fix_history`, `branch_overlap`, `independent_changes`, `diff_shape`, `risk_percentile`, `cross_repo` (workspace mode).
+`include_paths` and `exclude_patterns` scope the score, health delta and per-file blocks; `impacted_tests` still selects over the whole change, less repowise's own output.
-`directive.status` is the verdict. `health_delta.status` `partial` means files that may hold code were skipped, so the change is not cleared; docs and config files never cause it. `review_priority`, `classification` and `diff_shape` describe diff size and spread, never danger. An empty diff returns `status: "nothing_to_score"`.
+**Returns** `directive.status` (the verdict), `health_delta`, `impacted_tests`, `patch_coverage`, `fix_history`, `diff_shape` ([fields](../reference/MCP_RESPONSE_FIELDS.md#get_change_risk)).
```
get_change_risk()
@@ -284,21 +268,23 @@ get_change_risk(revspec="main..HEAD", exclude_patterns=["tests/"])
get_change_risk(revspec="main..HEAD", finding_id="chf_27a13be11e7ee33f")
```
-### `get_why`
+---
+
+## `get_why`
-Why code is shaped the way it is: decision records, with git archaeology and mined rationale comments as fallbacks when no decision governs a path. Call it before a refactor or before diverging from an existing pattern.
+Why code is shaped as it is: decision records, falling back to git archaeology and mined rationale comments when no decision governs a path. Call it before a refactor or before diverging from a pattern.
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
-| `query` | string | none | A question, or a file or module path. Omit for the decision health dashboard |
-| `targets` | list[string] | none | Paths to anchor a question to, or to ask about on their own with no `query` |
+| `query` | string | none | A question or a path. Omit for the decision health dashboard |
+| `targets` | list[string] | none | Paths to anchor a question to, or to ask about alone |
| `id` | string | none | A decision id or `ev_...` evidence id from an earlier response |
-| `reference` | object | none | An evidence reference this tool emitted; pass it unchanged |
-| `repo` | string | default repo | Workspace repo alias, or `"all"` (only with a `query`) |
+| `reference` | object | none | An evidence reference this tool emitted, unchanged |
+| `repo` | string | default repo | Or `"all"`, only with a `query` |
-Modes: a question searches decision records; a path returns that file's `decisions`, `candidates` and `history` plus its origin story and `alignment`; `targets` alone asks about those files; no arguments returns the health dashboard (stale decisions, conflicts, ungoverned hotspots); `id` resolves one record directly.
+Modes: a question searches decisions; a path (or `targets` alone) returns `decisions`, `candidates`, `history`, its origin story and `alignment`; `id` resolves one record; no arguments returns the dashboard (stale decisions, conflicts, ungoverned hotspots).
-**Key return fields:** `decisions` (accepted, binding), `candidates` (inferred, nobody accepted them: hints, not rules), `history` (accepted, since withdrawn), `answer_basis` (the strongest lane served; only `decision` is a ruling), `alignment`, `git_archaeology`, `evidence_refs`.
+**Returns** `decisions` (binding), `candidates` (hints, not rules), `history`, `answer_basis` ([fields](../reference/MCP_RESPONSE_FIELDS.md#get_why)).
```
get_why(query="why JWT over sessions?")
@@ -306,51 +292,61 @@ get_why(query="src/payments/processor.ts")
get_why()
```
-### `get_overview`
+---
+
+## `get_overview`
-Orientation for an unfamiliar repo: summary, key modules, entry points, layers, code health, the riskiest files and this week's top actions. Call it once, first. Skip it afterwards; it does not change within a session.
+Orientation for an unfamiliar repo: summary, key modules, entry points, layers, code health, riskiest files and this week's top actions. Call it once, first; it does not change within a session.
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
-| `include` | list[string] | none | Any of `content` (full essay), `outline` (wiki page tree), `tour` (guided tour and reading order), `decisions`, `graph` (community clusters), `ownership` (top owners), `components` (declared and derived components with file counts), `changes` (Change Records by category and week, and the agent share of changes with coverage), `actions` (the quarter's actions too, with `done_when`), `tools` (`tool_surface`: enabled tools, opt-ins and recipes), `scope` (the whole `_meta.index_scope`) |
-| `repo` | string | default repo | Workspace repo alias, or `"all"` for the cross-repo topology |
+| `include` | list[string] | none | `content` (full essay), `outline`, `tour`, `decisions`, `graph`, `ownership`, `components` (with file counts), `changes`, `actions` (the quarter too), `tools` (enabled tools, opt-ins, recipes), `scope` |
+| `repo` | string | default repo | Or `"all"` for the cross-repo topology, where only `include=["tools"]` applies |
-**Key return fields:** `title`, `content_md` (summary section by default), `key_modules` (one row per package or top-level directory), `entry_points`, `commands` (build, test, lint and similar commands from manifests), `architecture` (layers in stack order with their `root`, plus `dependencies`: the ten heaviest package-to-package edges with `from`, `to`, `verb` and `weight`, and `edges_total` when more exist; absent in a single-package repo), `code_health`, `git_health` (`riskiest_files`), `next_actions` (top three for the week, or the quarter when the week is empty), `more` (names the opt-in blocks), and a `workspace` footer in workspace mode.
+**Returns** `content_md`, `key_modules`, `entry_points`, `commands`, `architecture`, `code_health`, `git_health`, `next_actions`, `more` ([fields](../reference/MCP_RESPONSE_FIELDS.md#get_overview)).
```
get_overview()
get_overview(include=["outline", "content"])
```
-### `get_health`
+---
+
+## `get_health`
-Code-health scores and findings from the stored analysis, across defect risk, maintainability and performance. With no `targets` it returns a dashboard led by `fix_first`, one ranked queue of what to fix first. With `targets` it scores those files. It never recomputes: commit, then run `repowise update`, to see new numbers. No LLM calls.
+Code-health scores and findings from stored analysis, across defect risk, maintainability and performance. No `targets` gives a dashboard led by `fix_first`, one ranked queue; `targets` scores those files. It never recomputes (commit, then `repowise update`) and makes no LLM calls.
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
-| `targets` | list[string] | none (dashboard) | File paths or `module:<name>`. Misses are named in `unresolved` |
-| `include` | list[string] | none | Blocks: `biomarkers`, `refactoring`, `trend`, `coverage`, `accuracy`, `signals`, `churn_complexity`, `untested_complexity`, `doc_drift`, `semantics`, `unverified`, `recipe` (with `plan_id`), `what_if`. Dimension filters: `performance`, `defect`, `maintainability`, `advisory` |
-| `only` | list[string] | none | Keep just these top-level keys; identity, totals and recovery fields always survive. An unknown key is named in `unknown_only_keys` with `unknown_only_keys_hint` |
-| `limit` | int | `20` | Max rows in every ranked list, capped at 50; `0` for none. `fix_first` shows five unless `limit` is passed with `only=["fix_first"]`, which pages up to 25; `refactoring_plans` up to 25 |
-| `cursor` | int | `0` | Offset into a ranked list (and into `fix_first` when named in `only`); the `recovery` block names the next call |
-| `fix_id` | string | none | Open one `fix_first` item (`fix1_...`) in full, or one `get_overview` `next_actions` action (`act_...`) with its `details` and `commands` (`mode: "action"`) |
-| `finding_id`, `plan_id` | string | none | Open one finding or refactoring plan by id. With `plan_id`, `include=["recipe"]` adds `plan.recipe`: the plan's preconditions, ordered steps, postconditions and what it must not do |
-| `opportunity_id` | string | none | Open one opportunity: `perf...` for performance, `refop...` for a refactoring |
-| `refactoring_view` | string | `"diversified"` | `diversified`, `canonical` or `file_spread` |
-| `refactoring_scope` | string | `fix_first` without targets, `all` with | Which open refactoring opportunities, and their plans, to list |
-| `refactoring_type`, `refactoring_confidence`, `refactoring_effort` | string | none | Refactoring queue filters |
+| `targets` | list[string] | none (dashboard) | File paths or `module:<name>`; misses go to `unresolved` |
+| `include` | list[string] | none | Blocks: `biomarkers`, `refactoring`, `trend`, `coverage`, `accuracy`, `signals`, `churn_complexity`, `untested_complexity`, `doc_drift`, `semantics`, `unverified`, `recipe`, `what_if` ([what each adds](../reference/MCP_RESPONSE_FIELDS.md#opt-in-blocks)). Dimensions: `performance`, `defect`, `maintainability`, `advisory` |
+| `only` | list[string] | none | Keep these top-level keys; identity, totals and recovery always survive |
+| `limit` | int | `20` | Rows per ranked list, max 50; `0` for none |
+| `cursor` | int | `0` | Offset into a ranked list (or `fix_first` when named in `only`); `recovery` names the next call |
+| `fix_id` | string | none | One `fix_first` item (`fix1_...`) or `next_actions` action (`act_...`) in full |
+| `finding_id` | string | none | One finding |
+| `plan_id` | string | none | One refactoring plan; `include=["recipe"]` adds its preconditions, ordered steps, postconditions and what it must not do |
+| `opportunity_id` | string | none | `perf...` or `refop...` |
+| `refactoring_view` | string | `"diversified"` | `diversified`, `canonical`, `file_spread` |
+| `refactoring_scope` | string | `fix_first` without targets, `all` with | Which opportunities, and their plans, to list |
+| `refactoring_type` | string | none | `break_cycle`, `extract_class`, `extract_helper`, `extract_method`, `move_method`, `split_file` |
+| `refactoring_confidence` | string | none | `high`, `medium`, `low` |
+| `refactoring_effort` | string | none | `S`, `M`, `L`, `XL` |
| `performance_view` | string | `detail` | `detail` or `summary` |
-| `performance_context` | string | `production` | `production`, `tooling`, `test`, `unknown` or `all` |
-| `performance_boundary`, `performance_confidence`, `performance_actionability`, `performance_sort` | string | none | Performance queue filters. The queue lists causes whose cost is measured; unproven ones (loop size unknown) are counted in the `proof` facet and `default_queue.excluded.unmeasured_cost` |
+| `performance_context` | string | `production` | `production`, `tooling`, `test`, `unknown`, `all` |
+| `performance_boundary` | string | none | `db`, `network`, `filesystem`, `subprocess`, `lock`, `none` |
+| `performance_confidence` | string | none | `high`, `medium`, `low` |
+| `performance_actionability` | string | none | `plan_ready`, `advisory`, `investigate`, `expected` |
+| `performance_sort` | string | `rank` | `rank`, `leverage`, `observations` |
| `scope` | string | `"all"` | `production` drops test files from every figure |
| `counts` | string | `"everything"` | `code_shape` drops the git-derived half of the score |
-| `repo` | string | default repo | Workspace repo alias. `"all"` is not supported |
+| `repo` | string | default repo | `"all"` not supported |
-Only one of `fix_id`, `finding_id`, `plan_id`, `opportunity_id` per call; passing two returns `mode: "conflict"`.
+- Pass one of `fix_id`, `finding_id`, `plan_id`, `opportunity_id`; two return `mode: "conflict"`.
+- `fix_first` shows five items unless `limit` comes with `only=["fix_first"]`, which pages up to 25.
+- The response is bounded: pair `include` with `only` to keep one block, e.g. `get_health(include=["refactoring"], only=["refactoring_opportunities"])`.
-**Key return fields:** `mode`, `fix_first` (`lead` with its `next_call`, up to five `items`, `counts`, `totals`; a due lead carries its `first_step` and `verify` command, so it can be started without a `fix_id` call; `only=["fix_first"]` adds them to the other due items on the page), `kpis`, `gap_analysis`, `worst_files`, `high_leverage_files` (ranked by `weighted_deficit`), `top_findings`, `unresolved`, and the opt-in blocks you named. `_meta.health_analysis` says whether stored analysis exists and which commit it describes.
-
-The response is bounded. Pair `include` with `only` to keep one block, e.g. `get_health(include=["refactoring"], only=["refactoring_opportunities"])`.
+**Returns** `mode`, `fix_first`, `kpis`, `gap_analysis`, `worst_files`, `high_leverage_files`, `top_findings`, `unresolved` ([fields](../reference/MCP_RESPONSE_FIELDS.md#get_health)). A due `fix_first` lead carries `first_step` and `verify`, so it can be started without a `fix_id` call.
```
get_health(only=["fix_first"], limit=25)
@@ -363,17 +359,19 @@ get_health(include=["performance"], only=["performance_summary"])
get_health(include=["coverage"], only=["coverage"])
```
-### `get_dead_code`
+---
+
+## `get_dead_code`
-Unreachable files, unused exports, unused internals and zombie packages, tiered by confidence. Use it for a cleanup pass, not a targeted fix. `safe_only` leaves out anything with runtime-load risk such as dynamic imports and framework-registered functions.
+Unreachable files, unused exports, unused internals and zombie packages, tiered by confidence. For a cleanup pass, not a targeted fix.
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
-| `kind` | string | all | `unreachable_file`, `unused_export`, `unused_internal` or `zombie_package` |
-| `min_confidence` | float or string | `0.4` | Confidence floor; also accepts `"high"` (0.7), `"medium"` (0.4), `"low"` (0.0) |
-| `tier` | string | all | `high` (0.7 and up), `medium` (0.4 to 0.7) or `low` |
-| `safe_only` | bool | `false` | Deletion-ready findings only |
-| `limit` | int | `20` | Max findings per tier, clamped to 25 |
+| `kind` | string | all | `unreachable_file`, `unused_export`, `unused_internal`, `zombie_package` |
+| `min_confidence` | float or string | `0.4` | Floor; or `"high"` (0.7), `"medium"` (0.4), `"low"` (0.0) |
+| `tier` | string | all | `high` (0.7+), `medium` (0.4 to 0.7), `low` |
+| `safe_only` | bool | `false` | Deletion-ready only: drops runtime-load risk such as dynamic imports and framework-registered functions |
+| `limit` | int | `20` | Per tier, clamped to 25 |
| `directory` | string | none | Path-prefix filter |
| `owner` | string | none | Primary-owner filter |
| `group_by` | string | none | `directory` or `owner` rollup |
@@ -381,10 +379,11 @@ Unreachable files, unused exports, unused internals and zombie packages, tiered
| `include_zombie_packages` | bool | `true` | Monorepo package findings |
| `no_unreachable` | bool | `false` | Skip unreachable-file findings |
| `no_unused_exports` | bool | `false` | Skip unused-export findings |
-| `finding_id` | string | none | Open one finding by its id |
-| `repo` | string | default repo | Workspace repo alias, or `"all"` to aggregate across repos |
+| `include_unverified` | bool | `false` | Also show provisional types and gated-language findings |
+| `finding_id` | string | none | Open one finding |
+| `repo` | string | default repo | Or `"all"` to aggregate across repos |
-**Key return fields:** `tiers` (findings per tier, each with path, kind, confidence, line count and cleanup impact), `summary` (totals over every open finding, `filtered_findings`, `filters`, `withheld_types`, `call_resolution_basis`), `by_directory` or by-owner rollups with `group_by`. In workspace mode, confidence drops on findings another repo still imports.
+**Returns** `tiers`, `summary`, and `by_directory` or `by_owner` with `group_by` ([fields](../reference/MCP_RESPONSE_FIELDS.md#get_dead_code)).
```
get_dead_code()
@@ -394,13 +393,11 @@ get_dead_code(kind="unused_export", group_by="owner")
---
-## Workspace default
-
-### `list_repos`
+## `list_repos`
-Lists the repos this server serves. On by default in workspace mode only; a single-repo server is bound to its one repository. No parameters.
+Lists the repos this server serves, to find the `repo` value for other tools. Default in workspace mode only (a single-repo server is bound to one repository). No parameters.
-**Key return fields:** `workspace` (bool), `workspace_root`, `default_repo`, and per repo its `alias`, config-relative `path` and `absolute_path`. Any of those can be passed unchanged as `repo` to other tools.
+**Returns** `workspace`, `workspace_root`, `default_repo`, `repos` ([fields](../reference/MCP_RESPONSE_FIELDS.md#list_repos)).
```
list_repos()
@@ -408,106 +405,112 @@ list_repos()
---
-## Opt-in tools
+## `get_dependency_path`
-Enable with `mcp.tools: ["+name"]` or `repowise mcp --tools "+name"` (see [Configuring the tool surface](#configuring-the-tool-surface)). The last three are workspace-only.
-
-### `get_dependency_path`
-
-The shortest dependency path between two files or modules. When none exists it returns context to debug the gap: nearest common ancestors, shared neighbours, community analysis and bridge suggestions.
+Opt-in (`mcp.tools: ["+get_dependency_path"]` or `--tools "+get_dependency_path"`; the same for every opt-in). The shortest dependency path between two files or modules; with none, context to debug the gap.
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
| `source` | string | required | Source file or module path |
| `target` | string | required | Target file or module path |
-| `repo` | string | default repo | Workspace repo alias. `"all"` is not supported |
+| `repo` | string | default repo | `"all"` not supported |
```
get_dependency_path(source="src/api/routes.py", target="src/db/models.py")
```
-### `get_execution_flows`
+---
+
+## `get_execution_flows`
-The top-scored entry points and a breadth-first call trace from each, marking where a flow crosses community boundaries. Use it to see what runs end to end.
+Opt-in. The top-scored entry points with a breadth-first call trace from each, marking community-boundary crossings: what runs end to end.
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
-| `top_n` | int | `10` | Entry points to trace |
-| `max_depth` | int | `8` | Max trace depth per flow |
-| `entry_point` | string | none | Trace from this symbol, overriding `top_n` scoring |
-| `repo` | string | default repo | Workspace repo alias. `"all"` is not supported |
+| `top_n` | int | `10` | Entry points to trace, 1 to 50 |
+| `max_depth` | int | `8` | Trace depth per flow, 1 to 20 |
+| `entry_point` | string | none | Trace from this symbol, overriding `top_n` |
+| `repo` | string | default repo | `"all"` not supported |
```
get_execution_flows(entry_point="src/cli/main.py::main", max_depth=4)
```
-### `generate_refactoring_code`
+---
-Turns one refactoring plan from `get_health(include=["refactoring"])` into generated code and a unified diff, grounded on the plan and the source spans it names. Extract Class results include an LCOM4 before-and-after check. It calls the repo's configured LLM provider, and caches by content hash so an unchanged plan never regenerates.
+## `generate_refactoring_code`
-Adding the tool to the surface is the opt-in step. Generation then runs only when `.repowise/config.yaml` sets `refactoring.llm.enabled: true` (off by default); otherwise the plan is returned with `generation.available: false` and `reason: "disabled"`. With no provider configured it returns `error: "no_provider"`.
+Opt-in. Turns one plan from `get_health(include=["refactoring"])` into code and a unified diff, grounded on the plan and its source spans. Extract Class results include an LCOM4 before-and-after check. It calls the repo's LLM and caches by content hash, so an unchanged plan never regenerates. Adding it to the surface is the opt-in step; generation also needs `refactoring.llm.enabled: true` in `.repowise/config.yaml` (off by default).
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
| `suggestion_id` | string | required | A plan `id` from `get_health` |
-| `repo` | string | default repo | Workspace repo alias. `"all"` is not supported |
+| `repo` | string | default repo | `"all"` not supported |
+
+**Returns** the plan, code and diff; `generation.available: false` with `reason: "disabled"`, or `error: "no_provider"` ([fields](../reference/MCP_RESPONSE_FIELDS.md#generate_refactoring_code)).
```
generate_refactoring_code(suggestion_id="a1b2c3d4")
```
-### `set_finding_status`
+---
+
+## `set_finding_status`
-Records a durable verdict on one refactoring plan in the index, so the triage survives later analysis runs.
+Opt-in. Records a durable verdict on one refactoring plan, surviving later analysis runs. Returns the new status and its timestamp.
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
| `suggestion_id` | string | required | A plan `id` or `public_id` from `get_health` |
-| `status` | string | required | `open`, `acknowledged`, `resolved` or `false_positive` |
-| `reason` | string | `"agent"` | Free-text audit note stored on the row |
-| `repo` | string | default repo | Workspace repo alias. `"all"` is not supported |
-
-`false_positive` plans are never re-emitted. `acknowledged` stays visible but stops counting as unheard. `resolved` stays resolved even if the detector still fires. `open` resets. Returns the new status and its timestamp.
+| `status` | string | required | `false_positive` (never re-emitted), `acknowledged` (visible, no longer unheard), `resolved` (stays resolved if the detector still fires), `open` (resets) |
+| `reason` | string | `"agent"` | Free-text audit note |
+| `repo` | string | default repo | `"all"` not supported |
```
set_finding_status(suggestion_id="a1b2c3d4", status="false_positive", reason="the class is a DTO")
```
-### `get_blast_radius`
+---
+
+## `get_blast_radius`
-*Workspace only.* Which services in other repos are structurally reachable from a changed service, ranked by an uncalibrated 0 to 1 path weight. Structural edges (HTTP, gRPC, events, packages) outrank co-change. It is not a runtime-breakage probability.
+*Workspace only, opt-in.* Services in other repos structurally reachable from a changed service, ranked by an uncalibrated 0 to 1 path weight (not a breakage probability). Structural edges (HTTP, gRPC, events, packages) outrank co-change.
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
-| `targets` | list[string] | required | Node ids (`repo` or `repo::service/path`), repo aliases, or the symbol id of a published symbol |
+| `targets` | list[string] | required | Node ids (`repo` or `repo::service/path`), repo aliases, or a published symbol's id |
| `max_depth` | int | `3` | Reachability depth, 1 to 8 |
| `include_behavioral` | bool | `true` | Include co-change edges |
-**Key return fields:** impacted services with `score`, `distance` and edge kinds, `impacted_repos`, `total_impacted`, `impact_score_semantics`, and `symbol_targets` naming the consuming symbols across each contract link, with the tests that guard them.
+**Returns** impacted services with `score` and `distance`, `impacted_repos`, `symbol_targets` with guarding tests ([fields](../reference/MCP_RESPONSE_FIELDS.md#get_blast_radius)).
```
get_blast_radius(targets=["backend"])
```
-### `get_architecture`
+---
+
+## `get_architecture`
-*Workspace only.* Whole-system structure: propagation cost (the share of other services the average service reaches), the largest cyclic core, service roles, and a deterministic 1 to 10 score. Structural edges only. No parameters.
+*Workspace only, opt-in.* Whole-system structure from structural edges: propagation cost, the largest cyclic core, service roles, and a deterministic 1 to 10 score. No parameters.
-**Key return fields:** `score`, `architecture_type`, `propagation_cost_pct`, `core_members`, `cycle_count`, `role_breakdown`, `summary`.
+**Returns** `score`, `architecture_type`, `propagation_cost_pct`, `core_members`, `role_breakdown` ([fields](../reference/MCP_RESPONSE_FIELDS.md#get_architecture)).
```
get_architecture()
```
-### `get_conformance`
+---
+
+## `get_conformance`
-*Workspace only.* Cross-repo dependencies that break the rules declared under `conformance:` in `.repowise-workspace.yaml`, plus circular service dependencies. Without opting in, the same findings still reach `get_risk`'s PR-mode directive as `conformance_violations` and `dependency_cycles`.
+*Workspace only, opt-in.* Cross-repo dependencies breaking the rules under `conformance:` in `.repowise-workspace.yaml`, plus circular service dependencies. Without opting in, the same findings reach `get_risk`'s PR directive as `conformance_violations` and `dependency_cycles`.
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
-| `repo` | string | whole workspace | Limit findings to those involving this repo |
+| `repo` | string | whole workspace | Limit to findings involving this repo |
-**Key return fields:** `violations` (source and target services, the rule that fired, `edge_kind`), `cycles`, `violation_count`, `cycle_count`, `rules_evaluated`.
+**Returns** `violations`, `cycles`, `violation_count`, `rules_evaluated` ([fields](../reference/MCP_RESPONSE_FIELDS.md#get_conformance)).
```
get_conformance(repo="frontend")
@@ -517,35 +520,31 @@ get_conformance(repo="frontend")
## Workspace mode
-A server started inside a [workspace](../scale/WORKSPACES.md) serves every repo in it from one process. `repowise mcp --no-workspace` forces single-repo mode for a nested repo. Every tool with a `repo` parameter takes an alias, path or absolute path from `list_repos`; omitting it targets the default repo.
-
-Only four tools answer across every repo with `repo="all"`. The rest return an error naming the available aliases.
+A server started inside a [workspace](../scale/WORKSPACES.md) serves every repo from one process; `repowise mcp --no-workspace` forces single-repo mode for a nested repo. A `repo` parameter takes an alias, path or absolute path from `list_repos`; omitted, it targets the default repo.
| Tool | `repo="all"` |
|------|--------------|
-| `search_codebase` | Yes: federates the search and merges results |
-| `get_overview` | Yes: the cross-repo topology (co-changes, package dependencies, API contracts), with no single-repo detail |
-| `get_dead_code` | Yes: aggregates findings across repos |
-| `get_why` | Only with a `query`; not for the dashboard or an `id` lookup |
+| `search_codebase` | Yes: federated search, merged results |
+| `get_overview` | Yes: cross-repo topology (co-changes, package dependencies, API contracts), no single-repo detail |
+| `get_dead_code` | Yes: aggregated findings |
+| `get_why` | Only with a `query`, not the dashboard or an `id` |
| `get_answer`, `get_context`, `get_symbol`, `get_risk`, `get_change_risk`, `get_health` | No |
| `get_dependency_path`, `get_execution_flows`, `generate_refactoring_code`, `set_finding_status` | No |
-| `get_conformance` | No `"all"` value; it covers the whole workspace when `repo` is omitted |
-| `get_blast_radius`, `get_architecture`, `list_repos` | No `repo` parameter; they always read the whole workspace |
-
-With `repo` omitted, `get_context`, `get_symbol`, `get_risk` and `get_health` route each path or `path::Name` target to its repo: the default repo when the file exists there, else the one other repo whose checkout has it. Write `<alias>:<target>` (for example `web:src/app.ts::App`) to name the repo outright. A path found in several other repos returns its `candidates`. A path in no repo gets the default repo's usual not-found answer plus a `hint` naming `search_codebase(repo="all")` and the `<alias>:<path>` form; routed results carry `repo`. `get_context` takes a batch spanning repos, while `get_risk` and `get_health` answer one repo per call and name the per-repo calls when a batch spans several.
-
-`get_context` and `get_symbol` route a bare symbol name (`render`, `Client.send`) the same way, through the workspace store's symbol index: the default repo keeps a name it has, one other repo that has it gets the call, and several return `candidates`. A `repowise#<ref>` omission ref is found in whichever repo's omission store holds it.
+| `get_conformance` | No `"all"`; omitting `repo` covers the workspace |
+| `get_blast_radius`, `get_architecture`, `list_repos` | No `repo` parameter; always the whole workspace |
-A `repo="all"` call queries up to 4 repos at a time and gives each 60 seconds (`REPOWISE_WORKSPACE_CONCURRENCY`, `REPOWISE_WORKSPACE_REPO_TIMEOUT_S`). A repo that fails to open, errors or times out is listed in `repos_failed` with its reason while the other repos still answer. A repo whose index is behind its checkout is listed in `repos_stale` with `indexed_commit` and `live_head`, and its rows carry `stale: true`. Both keys appear only when non-empty.
+Unsupported tools return an error naming the aliases. A `repo="all"` call queries 4 repos at a time with 60 seconds each (`REPOWISE_WORKSPACE_CONCURRENCY`, `REPOWISE_WORKSPACE_REPO_TIMEOUT_S`). Failed or timed-out repos are listed in `repos_failed` with a reason while the rest answer; repos behind their checkout are in `repos_stale` with `indexed_commit` and `live_head`, their rows marked `stale: true`. Both keys appear only when non-empty.
-Single-repo tools also gain cross-repo evidence in workspace mode:
+### Routing without `repo`
-- `get_context` adds a per-target `cross_repo` block: co-change partners in other repos and contract consumers or providers.
-- `get_risk` in PR mode adds `will_break_consumers` (structural reach only), `missing_cross_repo_cochanges`, `breaking_changes`, `conformance_violations` and `dependency_cycles` to its directive.
-- `get_change_risk` adds `cross_repo`: consumers of the contracts the change touches, breaking changes, and the consumer-side tests to run.
-- `get_dead_code` lowers confidence on findings another repo still imports.
+- `get_context`, `get_symbol`, `get_risk` and `get_health` route each path or `path::Name` target: the default repo if the file is there, else the one other repo that has it. Routed results carry `repo`.
+- `<alias>:<target>` (e.g. `web:src/app.ts::App`) names the repo outright.
+- A path in several other repos returns `candidates`; a path in none gets the default repo's not-found answer plus a `hint` naming `search_codebase(repo="all")` and the `<alias>:<path>` form.
+- `get_context` takes a batch spanning repos; `get_risk` and `get_health` answer one repo per call and name the per-repo calls.
+- `get_context` and `get_symbol` route a bare symbol name (`render`, `Client.send`) through the workspace symbol index the same way: the default repo keeps a name it has, one other repo gets the call, several return `candidates`.
+- A `repowise#<ref>` ref is found in whichever repo's omission store holds it.
-See [WORKSPACES.md](../scale/WORKSPACES.md) for setup, contracts and the system graph.
+Single-repo tools also gain cross-repo evidence: `get_context` (`cross_repo`), `get_risk` PR mode (`will_break_consumers` and more), `get_change_risk` (`cross_repo`, with consumer-side tests), and `get_dead_code` (lower confidence on findings another repo imports). Fields: [MCP_RESPONSE_FIELDS.md](../reference/MCP_RESPONSE_FIELDS.md). Setup, contracts and the system graph: [WORKSPACES.md](../scale/WORKSPACES.md).
---
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.md
index 391705773..6fa141a46 100644
--- a/docs/architecture/code-health.md
+++ b/docs/architecture/code-health.md
@@ -1,1038 +1,651 @@
# Code Health: Architecture & Internals
-Companion to the user-facing [`docs/layers/CODE_HEALTH.md`](../layers/CODE_HEALTH.md). This
-document is for contributors: where every piece lives, how data flows from
-parsed source to the dashboard, and the extension points for adding
-markers, languages, coverage formats, or alerts.
-
-> **TL;DR.** Health analysis is a deterministic, zero-LLM Python pipeline:
-> tree-sitter walks every file once -> markers vote -> scores aggregate per
-> category -> results land in four SQLAlchemy tables. The MCP server, CLI,
-> and Next.js dashboard all read from those tables: no JSON cache, no
-> intermediate files, no LLM in the loop.
+How the code health layer works, for contributors. What it does and how to use it:
+[`docs/layers/CODE_HEALTH.md`](../layers/CODE_HEALTH.md).
---
## 1. Layer overview
-Code Health is the **fifth intelligence layer** in Repowise, alongside Graph,
-Git, Docs, and Decisions. It reads from Graph and Git but never modifies
-them. Its only writes are to its own four tables. It measures technical debt:
-the code shape and change history that make a file likely to need the next fix.
+Code Health is the **fifth intelligence layer**, beside Graph, Git, Docs and Decisions:
+a deterministic pipeline where tree-sitter walks every file once, markers vote, and
+scores aggregate per category into four SQLAlchemy tables. It reads Graph and Git
+without modifying them.
```
-┌─────────────┐ parsed_files ┌──────────────────┐
-│ Ingestion │ ────────────────► │ │
-│ (AST + git) │ git_meta_map │ HealthAnalyzer │ ──► HealthReport
-│ │ ────────────────► │ (engine.py) │ │
-│ │ community_labels │ │ │
-└─────────────┘ └──────────────────┘ │
- │ delete/upsert
- ▼
- ┌─────────────────────────────┐
- │ SQLite via SQLAlchemy │
- │ • health_findings │
- │ • health_file_metrics │
- │ • health_snapshots │
- │ • coverage_files │
- └──────────────┬──────────────┘
- │
- ┌────────────────────────────────┼────────────────────────────────┐
- ▼ ▼ ▼
- CLI (rich) MCP tools (FastMCP) Web dashboard
- health, status, get_health, get_risk, /repos/[id]/code-health
- health --trend get_context, get_overview (tabs, ?tab=...)
+Ingestion (parsed_files, git_meta_map, community_labels)
+ -> HealthAnalyzer (engine.py) -> HealthReport
+ -> delete/upsert -> SQLite: health_findings, health_file_metrics, health_snapshots, coverage_files
+ -> CLI (health, status, health --trend) | MCP (get_health, get_risk, get_context, get_overview)
+ | dashboard (/repos/[id]/code-health, tabs by ?tab=)
```
-Three architectural rules govern the whole layer:
-
-1. **Zero LLM.** Every marker is AST, git, or coverage math.
-2. **No JSON caches.** SQLite is the single source of truth; everything
- else reads from it.
-3. **No new runtime dependencies.** Pure Python over tree-sitter (already
- in tree). No lizard, no jscpd, no Node.
+Rules: **zero LLM** (every marker is AST, git or coverage math); **no JSON caches or
+intermediate files** (SQLite is the one source the CLI, MCP server and Next.js dashboard
+read); **no new runtime dependencies** (pure Python over tree-sitter: no lizard, jscpd or
+Node).
---
## 2. Where things live
-### Python: `packages/core/src/repowise/core/`
-
-```
-analysis/health/
-├── README.md # developer overview (this layer)
-├── __init__.py # public API: HealthAnalyzer, HealthReport
-├── engine.py # orchestrator: walker → biomarkers → scorer
-├── scoring.py # weighted aggregation, category caps, KPIs
-├── ranking.py # canonical worst-first key + deduction fold
-├── aggregation.py # module rollups, severity/biomarker/score breakdowns
-├── grading.py # the five absolute bands + NLOC-weighted distribution
-├── defect_accuracy.py # "does the score find the bugs?" self-validation
-├── trends.py # snapshot diff, Declining/Predicted alerts, per-file score series
-├── signals.py # per-file process/people/topology join (surfacing-only)
-├── churn_complexity.py # churn × complexity scatter points (surfacing-only)
-├── suggestions.py # deterministic refactoring text per biomarker
-├── config.py # HealthConfig + .repowise/health-rules.json
-├── models.py # HealthFindingData, HealthFileMetricData, HealthReport
-│
-├── complexity/ # tree-sitter AST walker
-│ ├── README.md
-│ ├── walker.py # CCN, nesting, cognitive, bumps, params, NLOC
-│ └── languages.py # per-language control-flow node-type maps
-│
-├── coverage/ # coverage report ingestion
-│ ├── README.md
-│ ├── model.py # CoverageReport, FileCoverage
-│ ├── detector.py # format auto-detect + test-file heuristic
-│ ├── lcov.py # LCOV parser (stdlib only)
-│ ├── cobertura.py # Cobertura XML parser
-│ ├── clover.py # Clover XML parser
-│ ├── jacoco.py # JaCoCo XML parser
-│ ├── goprofile.py # Go coverprofile parser (line-based)
-│ └── repowise_json.py # normalized repowise-coverage-v1 JSON parser
-│
-├── duplication/ # native Rabin-Karp clone detection
-│ ├── README.md
-│ ├── tokenizer.py # tree-sitter token stream (ID/LIT normalized)
-│ ├── rabin_karp.py # 64-bit rolling polynomial hash
-│ └── detector.py # clone-pair build + co-change weighting
-│
-└── biomarkers/ # one detector per file
- ├── README.md
- ├── base.py # Biomarker Protocol + FileContext + BiomarkerResult
- ├── registry.py # detector list + detect_all()
- ├── brain_method.py
- ├── low_cohesion.py
- ├── god_class.py
- ├── nested_complexity.py
- ├── repeated_nesting.py
- ├── complex_method.py
- ├── large_method.py
- ├── primitive_obsession.py
- ├── dry_violation.py
- ├── untested_hotspot.py
- ├── coverage_gap.py
- ├── coverage_gradient.py
- ├── untested_complexity.py
- ├── developer_congestion.py
- ├── knowledge_loss.py
- ├── hidden_coupling.py
- ├── complex_conditional.py
- ├── function_hotspot.py
- ├── code_age_volatility.py
- ├── ownership_risk.py
- ├── churn_risk.py
- ├── change_entropy.py
- ├── co_change_scatter.py
- ├── prior_defect.py
- ├── large_assertion_block.py
- ├── duplicated_assertion_block.py
- └── error_handling.py
-```
-
-### Persistence
-
-```
-core/persistence/
-├── models.py # HealthFinding, HealthFileMetric, HealthSnapshot, CoverageFile
-└── crud.py # save_/upsert_/get_ health functions
-core/alembic/versions/
-└── 000X_health_tables.py # migration that created the four tables
-```
-
-### Pipeline wiring
-
-```
-core/pipeline/
-├── orchestrator.py # _run_health_analysis(): builds community_label_map, runs analyzer
-└── persist/ # persist_pipeline_result(): writes findings/metrics/snapshot
-```
-
-### CLI
-
-```
-cli/src/repowise/cli/commands/
-├── health_cmd.py # repowise health [--trend|--refactoring-targets|--module]
-├── status_cmd.py # `Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: ...)`
-└── update_cmd.py # incremental path: HealthAnalyzer.analyze(changed_files=...)
-```
-
-### Server: MCP + REST
+| `packages/core/src/repowise/core/analysis/health/` | Holds |
+|---|---|
+| `__init__.py`, `engine.py`, `file_evaluator.py` | `HealthAnalyzer`, `HealthReport`; walker → biomarkers → scorer; one file's context, detectors and score |
+| `scoring.py`, `shape_curve.py`, `ranking.py`, `aggregation.py`, `grading.py` | Aggregation, caps, KPIs; the saturating curve; worst-first key; rollups; the five bands |
+| `crap.py`, `governance.py`, `finding_identity.py`, `defect_accuracy.py` | CRAP score; governance findings; stable ids; self-validation |
+| `trends.py`, `signals.py`, `churn_complexity.py`, `suggestions.py`, `config.py`, `models.py` | Alerts and series; per-file signals; churn × complexity; refactoring text; `HealthConfig`; dataclasses |
+| `fix_first/`, `worth.py`, `queue/`, `perf/` | Fix first (§6.3); performance opportunities (§6.4) |
+| `complexity/`, `coverage/`, `duplication/` | tree-sitter walker (`walker.py`, `languages.py`); stdlib report parsers and the test-file heuristic; Rabin-Karp clones (64-bit rolling hash, co-change weighting). Each has a `README.md` |
+| `biomarkers/` | `base.py` (Protocol, `FileContext`, `BiomarkerResult`), `registry.py` (`detect_all()`), one `<id>.py` per detector (§5) |
+
+| Elsewhere | Holds |
+|---|---|
+| `core/persistence/models.py`, `core/persistence/crud/analysis/health/` | The four ORM tables; `save_` / `upsert_` / `get_` functions |
+| `packages/core/alembic/versions/0019_code_health.py` | Created the tables; later health migrations add columns |
+| `core/pipeline/phases/analysis.py`, `core/pipeline/persist/` | `_run_health_analysis()`; `persist_pipeline_result()` |
+| `cli/.../commands/health_cmd/`, `status_cmd.py`, `update_cmd/` | CLI (§11) |
+| `server/.../mcp_server/tool_health/`, `tool_risk/`, `tool_context/`, `tool_overview/`; `server/.../routers/code_health/` | MCP (§12); REST (§13) |
+| `packages/ui/src/health/`, `packages/web/src/app/repos/[id]/code-health/` | Shared React components (web and hosted frontend); the page (§14) |
+| `tests/unit/health/`, `tests/integration/test_health_*` | Tests (§18) |
-```
-server/src/repowise/server/
-├── mcp_server/
-│ ├── tool_health/ # @mcp.tool get_health(targets, include, repo, limit)
-│ ├── tool_risk.py # enriched: health_score, top_biomarkers, line_coverage_pct
-│ ├── tool_context.py # include=["health"]: score, top 2 biomarkers, suggestion
-│ └── tool_overview.py # code_health block with KPIs
-└── routers/
- └── code_health.py # /api/repos/{id}/health/{overview,files,coverage,
- # refactoring-targets,modules,findings}
-```
+---
-### Web dashboard
+## 3. The pipeline (init path)
-```
-packages/ui/src/health/ # shared React components (used by web + future hosted frontend)
-├── file-table.tsx
-├── biomarker-list.tsx
-├── coverage-bar.tsx
-├── module-coverage-list.tsx
-├── untested-hotspot-warning.tsx
-├── refactoring-card.tsx
-├── refactoring-target-list.tsx
-├── health-badge.tsx # score pill, colored by the health band
-├── health-distribution-bar.tsx # NLOC-weighted split across the five bands
-├── trend-chart.tsx # repo KPI history (3 series)
-├── file-trend-chart.tsx # single file's score-over-time + delta + declining flag
-├── sparkline.tsx # compact inline series (drawer trend)
-└── module-rollup-list.tsx
-
-packages/web/src/app/repos/[id]/health/
-├── page.tsx # KPIs + lowest-scoring files + per-module rollup
-├── coverage/page.tsx # /health/coverage view
-└── refactoring-targets/page.tsx # /health/refactoring-targets view
-
-packages/web/src/components/health/
-└── health-risks-panel.tsx # sidecar panel on Hotspots/Ownership/Graph pages
-```
+`run_pipeline()` (`core/pipeline/orchestrator.py`) calls `_run_health_analysis()` between
+`_run_dead_code_analysis()` and `_run_decision_extraction()`. It:
-### Tests
+1. maps `{file_path: community label}` so `HealthFileMetric.module` is never NULL;
+2. loads `.repowise/health-rules.json` (`HealthConfig.load`, a no-op when absent) into
+ per-file disabled sets (`to_analyzer_config()`);
+3. builds `HealthAnalyzer` from the NetworkX graph, `git_meta_map` (hotspot bit, owners,
+ co-change, bus factor), `parsed_files` and the module map;
+4. runs `analyze_async()` (worker threads; tree-sitter releases the GIL) at `>= 500`
+ parsed files, else `analyze()`.
-```
-tests/unit/health/ # 99+ tests
-├── test_complexity_walker.py # per-language CCN/nesting assertions
-├── test_biomarkers.py
-├── test_structural_biomarkers.py # repeated_nesting, large_method, primitive_obsession
-├── test_coverage_biomarkers.py # untested_hotspot, coverage_gap
-├── test_organizational_biomarkers.py
-├── test_dry_violation.py
-├── test_duplication.py # tokenizer, hash, detector
-├── test_coverage_parsers.py # LCOV/Cobertura/Clover/JaCoCo/Go/JSON
-├── test_scoring.py # category caps, clamping
-├── test_scoring_snapshot.py # stability snapshot: locks caps + deductions
-├── test_health_config.py # .repowise/health-rules.json
-├── test_trends.py # diff_snapshots, declining/predicted alerts
-├── test_signals.py # file_signals join + no-signal/normalization
-├── test_churn_complexity.py # churn × complexity point shaping + sort + filtering
-└── test_suggestions.py
-
-tests/integration/
-├── test_health_coverage_integration.py
-└── test_health_perf_benchmark.py # 30 s budget on 3,000-file synthetic repo (slow)
-```
+`core/pipeline/persist/` writes `PipelineResult.health_report` in one session:
+`save_health_metrics`, `save_health_findings` (when there are findings) and
+`save_health_snapshot` (the KPIs, a `{path: score}` map, and `{path: total_deduction}`
+for floored files). `trends.snapshot_file_maps` builds both maps for every snapshot
+writer (also `health --recompute` and `update --full`), so history depth never depends on
+the last writer.
---
-## 3. The pipeline (init path)
+## 4. Inside `HealthAnalyzer.analyze()`
-`repowise init` runs `run_pipeline()` in `core/pipeline/orchestrator.py`.
-`_run_health_analysis()` is a phase in that orchestrator, called between
-`_run_dead_code_analysis()` and `_run_decision_extraction()`. It does four
-things:
-
-1. Builds a `{file_path: community label}` map from the graph's community
- detection so `HealthFileMetric.module` is populated (module rollups are
- never NULL).
-2. Loads per-file override rules from `.repowise/health-rules.json` via
- `HealthConfig.load(repo_path)` (a no-op when the file is absent) and
- resolves them to per-file disabled sets with `to_analyzer_config()`.
-3. Constructs the `HealthAnalyzer` with everything it needs: the NetworkX
- graph (for dependents), `git_meta_map` (hotspot bit, owners, co-change, bus
- factor), the `parsed_files` from the AST phase, and the module map.
-4. Picks the sync or parallel path by repo size. tree-sitter releases the GIL
- during parsing, so on repos with `>= 500` parsed files `analyze_async()`
- (asyncio gather over worker threads) gives a real wall-clock speedup;
- smaller repos run `analyze()` on a single thread.
-
-The returned report rides on `PipelineResult.health_report`. Then
-`core/pipeline/persist/` writes it in one session: `save_health_metrics`,
-`save_health_findings` (only when there are findings), and a
-`save_health_snapshot` carrying the three KPIs plus a `{path: score}` map for
-trend tracking (rolling 50-row window per repo), and a second
-`{path: total_deduction}` map covering only the files whose score is held at
-the floor. Both maps come from `trends.snapshot_file_maps`, which the other two
-snapshot writers (`repowise health --recompute` and `repowise update --full`) also call; a repo
-whose writers disagreed would get a history whose depth changed depending on
-which command last wrote it.
+Per file:
----
+1. **Walk** (`_walk`, `walk_file`): each `FunctionComplexity` carries name, line range,
+ nloc, ccn, max nesting, cognitive complexity, bumps and params; each
+ `ClassComplexity` carries method count and list, total nloc, LCOM4, max method ccn and
+ field count. A nested function gets its own entry; a lambda counts toward its holder.
+2. **Symbol complexity** (`_populate_symbol_complexity`): `max(ccn)` into
+ `Symbol.complexity_estimate` for the `ContextAssembler` ranker.
+3. **Evaluate** (`FileEvaluator.evaluate`): a `FileContext` (nloc, `has_test_file`,
+ module, metrics, `git_meta`, in-degree as `dependents_count`, the repo p80 in-degree,
+ coverage, the clone slice), then `detect_all()`, `score_file()` and per-finding
+ impacts.
-## 4. Inside `HealthAnalyzer.analyze()`
-
-A single pass over the parsed file list. For each file the analyzer:
-
-1. **Walks the AST** (`_walk`): `walk_file(language, source)` returns a
- `FileComplexity` of functions and classes. Each `FunctionComplexity` carries
- name, line range, nloc, ccn, max nesting, cognitive complexity, bumps, and
- param count; each `ClassComplexity` carries method count, total nloc, the
- method list, LCOM4, max method ccn, and field count. A function or method
- defined inside another function has a `FunctionComplexity` of its own: its
- branches are counted there and not in the function around it. A lambda has
- none and counts toward the function that holds it.
-2. **Populates symbol complexity** (`_populate_symbol_complexity`): writes
- `max(ccn)` into `Symbol.complexity_estimate` as a side effect, so the
- `ContextAssembler` symbol ranker benefits even when a caller never touches
- the health tables.
-3. **Evaluates the file** (`FileEvaluator.evaluate` in `file_evaluator.py`): builds a `FileContext` (nloc,
- `has_test_file`, module, per-function and per-class metrics, the per-file
- `git_meta`, graph in-degree as `dependents_count`, the repo-wide p80 of
- in-degree used as the `brain_method` floor, coverage fields when ingested,
- and the file's clone slice), runs `detect_all()`, scores with `score_file()`,
- and attaches per-finding impacts.
-
-After the loop, `compute_kpis()` runs over the metrics and the set of hotspot
-paths (`git_meta_map[path]["is_hotspot"]`), and the analyzer returns a
-`HealthReport(findings, metrics, kpis)`.
-
-Duplication runs **once up-front** (it is cross-file by nature); each
-`FileContext` gets a slice of the global clone report. The `dry_violation`
-marker reads `ctx.clones` and ranks pairs by co-change frequency from
-`git_meta_map[path]["co_change_partners_json"]`, so active clones rank higher
-than dormant ones.
+`compute_kpis()` then gives the hotspot, average (both NLOC-weighted) and worst KPIs.
+Duplication runs **once up-front**; `dry_violation` ranks clone pairs by co-change
+(`co_change_partners_json`), so active clones rank above dormant ones.
---
## 5. The markers and their categories
-Each marker is a stateless class implementing the `Biomarker` Protocol from
-`biomarkers/base.py`: a `name` (`"brain_method"`, `"nested_complexity"`, ...), a
-`category` (see `scoring.CATEGORY_CAPS`), and a `detect(ctx: FileContext)` method
-returning a list of `BiomarkerResult`s.
+Each marker is a stateless class implementing the `Biomarker` Protocol
+(`biomarkers/base.py`): `name`, `category` (`scoring.CATEGORY_CAPS`) and
+`detect(ctx: FileContext) -> list[BiomarkerResult]`. `biomarkers/registry.py` is an
+**explicit list**, so order is deterministic and tests inject extras via
+`registered_biomarkers(extra=...)`.
### The full roster
-`biomarkers/registry.py` registers **54 detectors**; counting the three
-governance findings written by the additive pass (`governance.py`) there
-are **57 marker ids**. They divide by what each is permitted to affect:
+`biomarkers/registry.py` registers **54 detectors**; counting the three governance
+findings written by the additive pass (`governance.py`) there are **57 marker ids**. They
+divide by what each is permitted to affect:
| Group | Count | Scores into |
|---|---:|---|
-| Defect-scoring | 24 | `defect` (11 of them also `maintainability`) |
+| Defect-scoring | 24 | `defect` (10 of them also `maintainability`) |
| Performance | 22 | `performance` only |
| SQL | 3 | `maintainability` only |
| Governance | 3 | nothing: the finding surfaces, the score is untouched |
-| Advisory | 5 | nothing: measured by construction, kept out of impact-ranked lists unless requested |
-
-The authority is `scoring._BIOMARKER_DIMENSIONS`. Any biomarker **not** listed
-there defaults into `defect`, which is why every `sql_*` and every performance
-name must be listed explicitly: an omission would silently break the defect
-golden guarantee (§6).
+| Advisory | 5 | nothing: measured by construction, out of impact-ranked lists unless requested |
+
+The authority is `scoring._BIOMARKER_DIMENSIONS`. An unlisted biomarker defaults into
+`defect`, so every `sql_*` and performance name is listed explicitly: an omission would
+silently break the defect golden guarantee (§6).
+
+Thresholds are the minimum for the default severity (medium unless stated), then the
+bands above it; "judged" CCN and nesting follow the dispatch rule (§5.5). Scoring gives
+the defect weight (§6.1), "maint" the maintainability and "perf" the performance weight.
+
+| `id` | Category | Flags | Threshold | Scoring |
+|---|---|---|---|---|
+| `brain_method` | Structural | A long, complex, central function | NLOC 70, judged CCN 9, file dependents ≥ min(8, max(repo p80, 3)); high at CCN 14 or NLOC 120; critical at CCN 20 and NLOC 150 | Advisory |
+| `low_cohesion` | Structural | A class split into unrelated method groups | LCOM4 2 and 5 methods; high at LCOM4 3 or 20 methods; critical at LCOM4 4 and 15 methods | 0.5; maint 1.0 |
+| `god_class` | Structural | A large class hiding a brain method | 200 NLOC, 15 methods, one method at NLOC 70 and CCN 9; high at 300 NLOC or 20 methods; critical at 400 and 25 | 1.13; maint 1.0 |
+| `nested_complexity` | Structural | Deep nesting in a function | Judged depth 4; high at 5; critical at 7 | 1.34; maint 1.0 |
+| `repeated_nesting` | Structural | Several blocks at one nesting depth | 3 bumps (low) and judged CCN 5; medium at 4 bumps, high at 5 | 0.5; maint 1.0 |
+| `complex_conditional` | Structural | A boolean expression with many operators | 3 operators (low); medium 4, high 5, critical 6; a flat chain stays low | 1.33; maint 1.0 |
+| `complex_method` | Size | High cyclomatic complexity | Judged CCN 9; high 15; critical 25 | 1.21; maint 1.0 |
+| `large_method` | Size | A long function | 60 code lines (low) and judged CCN 3; medium 90, high 120, critical 200 | 1.25; maint 1.0 |
+| `primitive_obsession` | Size | A long list of scalar parameters | 5 parameters (constructors 7), over half the typed ones primitive, file at 60 NLOC, not a test (low); medium at threshold + 2, high at + 4 | 0.5; maint 1.0 |
+| `dry_violation` | Duplication | A cross-file clone | File duplication 8% and a clone of 6 lines (low); medium with active co-change (3) or 25% duplication; high with both | 0.5; maint 1.0; hidden by default |
+| `error_handling` | Error handling | Swallowed or catch-all handler, Rust `unwrap`/panic, discarded Go error | Low, one per occurrence | 0.5; maint 1.0 |
+| `untested_hotspot` | Test coverage | A depended-on hotspot with weak test evidence | Hotspot, 4 dependents, coverage under 40% (no report: no paired or reaching test); high at ≤ 15% or 10 dependents; critical at both | 1.3 |
+| `coverage_gap` | Test coverage | A large uncovered surface (needs a report) | Under 30% with 50 coverable lines (high at 100 uncovered); under 60% with 25 uncovered is low | 1.0 |
+| `untested_complexity` | Test coverage | A complex function tests barely run | CRAP 30; high 50 and critical 100 on measured coverage only | Advisory |
+| `coverage_gradient` | Coverage gradient | Uncovered share of a file (needs a report) | `4.0 × (1 − line_coverage_pct/100)` points; label high under 40%, medium under 70% | 1.0, continuous |
+| `developer_congestion` | History | Many authors, no owner, high churn | 5 contributors, top quarter of churn, 3 commits in 90 days, nobody owns half (low); medium at 7 contributors or 12 commits; high at 10 and 20 | 0.5 |
+| `knowledge_loss` | History | A changing file whose sole real author (bus factor 1) is gone or under 20% of recent commits | Low; medium when the owner is gone and under 20% of recent commits; high on a hotspot; low on a small team (≤ 3 contributors) off a hotspot | 0.4 |
+| `hidden_coupling` | History | Files that co-change with no import edge | 5 commits each side, correlation 0.5; high 0.65 (with 8 co-changes), critical 0.8; at most 3 per file; tests skipped | Advisory |
+| `function_hotspot` | History | A complex function changed often | Changes ≥ max(repo p80, 5) with CCN 10 or nesting 3; high at 2× the bar or CCN 15; critical at 3× and CCN 20 | 1.16 |
+| `code_age_volatility` | History | A dormant function changed again | Median line age 365 days and 2 changes in 30 days; high at 730 days or 5 changes; critical at both | 1.1 |
+| `ownership_risk` | History | Many minor contributors or no dominant owner | 5 commits and 3 minor contributors (each under 5%) or no author above 40% (low when only that arm fires); medium at 3 minors, high at 5 (3 on a hotspot), critical at 6 on a hotspot; low under 40 code lines or on a small team off a hotspot | 1.38 |
+| `churn_risk` | History | Rewrote much of its own lines in 90 days | 5 commits in 90 days, top quarter of churn, relative churn 1.0 (low); medium 1.5, high 2.5, critical 4 on a hotspot | 1.2 |
+| `change_entropy` | History | Scattered, noisy changes | Entropy percentile 0.80, 3 commits in 90 days; high 0.90; critical 0.95 on a hotspot | 1.51 |
+| `co_change_scatter` | History | Coupled to many files (shotgun surgery) | Percentile 0.80, 3 commits in 90 days, not a test or barrel; high at 0.95 | 1.8 |
+| `prior_defect` | History | Recent bug-fix commits | 1 fix in 180 days at percentile 0.80 (low); medium 2, high 3-4 (critical on a hotspot), critical 5 | 1.0 |
+| `ungoverned_hotspot` | History | A hotspot no decision governs | Medium; from the decisions layer | Governance 0.7; never deducts |
+| `stale_governance` | History | A governing decision gone stale | High; from the decisions layer | Governance 0.9; never deducts |
+| `contradictory_decision` | History | Decisions that contradict each other | High; from the decisions layer | Governance 1.0; never deducts |
+| `large_assertion_block` | Test quality | One test asserting many behaviours | 15 consecutive assertions; high at 30; test files only | 1.0 |
+| `duplicated_assertion_block` | Test quality | Copy-pasted assertion runs | 5 real checks per block; test files only | 1.0; hidden by default |
+| `assertion_free_test` | Test quality | A test that checks nothing | Low; Python, JavaScript, TypeScript, TSX | Advisory |
+| `mock_saturated_test` | Test quality | Mock setup dwarfs the assertions | 6 mock setups at 3 per assertion (low); medium at 8; Python, JavaScript, TypeScript | Advisory |
+| `sql_high_complexity` | SQL | A complex SQL routine | CCN 10; high at CCN 20 | maint 0.7 |
+| `sql_select_star` | SQL | `SELECT *` | Low | maint 0.7 |
+| `sql_update_delete_without_where` | SQL | `UPDATE` or `DELETE` with no `WHERE` | Medium | maint 0.7 |
+| `sql_cartesian_join` | Performance | A cartesian join in SQL | Medium | perf 0.6 |
+| `io_in_loop` | Performance | I/O per loop iteration (N+1), across functions | Medium | perf 1.0 |
+| `string_concat_in_loop` | Performance | `+=` of a provable string in a loop | Low | perf 0.7 |
+| `blocking_sync_in_async` | Performance | A sync blocking call in `async def` | Medium; Python, Rust, C#, Kotlin, Scala | perf 0.7 |
+| `regex_compile_in_loop` | Performance | A static regex compiled per iteration | Medium; Java, Go, Rust, C++, Kotlin, Ruby, Scala | perf 0.6 |
+| `defer_in_loop` | Performance | `defer` inside a loop | Medium; Go | perf 0.6 |
+| `resource_construction_in_loop` | Performance | A client built per iteration | Medium | perf 0.7 |
+| `lock_in_loop` | Performance | A lock taken each iteration | Low | perf 0.5 |
+| `serial_await_in_loop` | Performance | Awaited I/O run serially in a loop | Low | perf 0.4 |
+| `membership_test_against_list_in_loop` | Performance | `x in list` (or `.includes`) on a provable list in a loop | Low | perf 0.7 |
+| `unbounded_read_reduced_in_memory` | Performance | An unlimited query reduced per key in code | Low; Python | perf 0.4 |
+| `lazy_load_in_loop` | Performance | An ORM lazy relation read per iteration | Low; SQLAlchemy, Django | perf 0.4 (Django 0.7) |
+| `nested_loop_with_io` | Performance | I/O in a loop nested two deep | Medium | perf 0.5 |
+| `nested_loop_quadratic` | Performance | A quadratic nested loop, widely called | Low; centrality gated | perf 0.4 |
+| `hot_path_sync_io` | Performance | Sync I/O in a widely called function | Low; centrality gated | perf 0.5 |
+| `blocking_io_under_lock` | Performance | Blocking I/O while holding a lock | Medium | perf 0.6 |
+| `list_insert_zero_in_loop` | Performance | `list.insert(0, x)` in a loop | Medium; Python | perf 0.6 |
+| `pd_concat_in_loop` | Performance | `pd.concat` accumulating in a loop | Medium; Python | perf 0.6 |
+| `pandas_iterrows_in_loop` | Performance | `df.iterrows()` | Medium; Python | perf 0.6 |
+| `json_parse_in_loop` | Performance | JSON parse or stringify per iteration | Low; JavaScript, TypeScript | perf 0.4 |
+| `array_spread_in_reduce` | Performance | `[...acc]` inside `reduce` | Medium; JavaScript, TypeScript | perf 0.5 |
+| `goroutine_in_unbounded_loop` | Performance | A goroutine per range element | Medium; Go | perf 0.4 |
+
+Notes:
+
+- `biomarker_names.py` maps the legacy id `bumpy_road` to `repeated_nesting`.
+- "Hidden by default": `analysis/finding_registry.py` keeps the type off every default
+ surface (overview, priorities, MCP, REST lists) until a re-measurement clears its
+ precision; it is still computed, stored and scored.
+- Performance markers with no language listed run in every perf dialect that models the
+ construct (§6.4, [PERFORMANCE.md](../layers/PERFORMANCE.md)).
### Defect categories and caps
-| Category | Cap | Markers |
-|------------------------|------|------------|
-| Organizational | −3.5‡ | developer_congestion, knowledge_loss, function_hotspot, code_age_volatility, ownership_risk, churn_risk, change_entropy, co_change_scatter, prior_defect, ungoverned_hotspot†, stale_governance†, contradictory_decision† |
-| Structural complexity | −2.5 | low_cohesion, god_class, nested_complexity, repeated_nesting, complex_conditional |
-| Test coverage | −2.0 | untested_hotspot, coverage_gap, untested_complexity (advisory) |
-| Test coverage gradient | −2.0 | coverage_gradient |
-| Size & complexity | −1.5 | complex_method, large_method, primitive_obsession |
-| Duplication | −1.0 | dry_violation |
-| Test quality | −0.5 | large_assertion_block, duplicated_assertion_block |
-| Error handling | −0.5 | error_handling |
-
-† The three governance markers carry a category and a weight, but the pass that
-writes them runs *after* scoring completes and never touches
-`HealthFileMetric.score`, so in practice they never deduct. They are counted
-in the table above because `scoring.py` maps them, not because they move a
-number.
-
-‡ A ceiling. The live cap is `history_cap(structure)`, `min(3.5, 1.0 + structure)`,
-where `structure` is the file's capped deduction from every other defect
-category, so git history alone costs a file at most 1.0. Before that cap, the
-history findings de-stack: the largest counts whole and each other one at 0.25
-(`destacked`), since a busy file trips several history markers for one cause.
-
-Every other defect category follows a saturating curve rather than stopping at
-its cap (`shape_curve.py`). A category's raw total `R` deducts
-`A * (1 - exp(-R / A))` with `A = 3.09 x cap`, so a second critical function
-still costs something and no category ever deducts more than 3.09 times its cap.
-Two rules feed the curve. Findings on one function count the largest in full and
-the rest at 0.25. A critical `complex_method`, `large_method` or
-`nested_complexity` finding deducts `2.0 x value / threshold` (CCN 25, 200 lines,
-nesting 7), so halving a CCN-50 function pays even while it stays critical. The
-3.09 is fitted so the corpus mean score matches the hard-capped one; the curve is
-AUC-neutral on the 66-repo corpus.
-
-`hidden_coupling` is advisory: still detected, stored and listed, it deducts
-nothing. On its own it ranks defect-prone files near chance (AUC about 0.55), and
-a pre-registered test on 12 repositories no earlier health study used found the
-score without it non-inferior at predicting defects.
-
-`brain_method` is advisory too. It fires only on a function that `complex_method`
-and `large_method` already charge, so scoring it charged one function twice, and
-dropping it left defect AUC unchanged on the 66-repo corpus. It is still listed
-under structural complexity.
-
-The maintainability dimension has its own independent tables
-(`_MAINTAINABILITY_CATEGORY`, caps: structural_complexity 4.0,
-size_and_complexity 2.0, duplication 2.0, error_handling 2.0, sql 2.0), and the
-performance dimension a single `performance` category capped at 2.0. See §6.
-
-`large_assertion_block` and `duplicated_assertion_block` are the two
-**test-quality** smells (see §5.3). They fire only on test files and sit in
-a deliberately small category so a noisy test can't dominate its own score.
-`large_method` is gated on a minimal judged CCN (≥ 3) so a long-but-flat
-body (a big data literal, a dispatch of one-line arms) reads as layout, not a
-complexity smell. In `.tsx` / `.jsx` it counts code lines only: a line holding
-nothing but JSX tags, attributes or text is markup, while a line with a `{...}`
-expression is code. Its reason gives both measures, "N lines of code (M with
-blanks and comments)", and `details.span` carries M. `complex_method` reports
-the judged CCN that sets its severity and adds the raw CCN when they differ.
-
-`ownership_risk` (long-run minor-contributor dispersion, Bird et al.) and
-`churn_risk` (size-normalized relative churn, Nagappan-Ball) are git-only
-process signals computed from `top_authors_json` / `lines_added_90d` /
-`churn_percentile`: fields the git indexer already produces. `change_entropy`
-(Hassan's History Complexity Metric) and `co_change_scatter` (breadth of
-co-change coupling, D'Ambros) are likewise git-only and read the
-`change_entropy` / `change_entropy_pct` fields (see §5.1) and
-`co_change_partners_json`. `knowledge_loss` is activity-gated so
-abandoned-but-stable files (the survivor effect) no longer fire.
-
-`prior_defect` (recent bug-fix history, Ostrand-Weyuker / Kim's "bug cache")
-is the other git-only process signal: the count of bug-fix commits touching a
-file in the trailing ~6-month window, read from `prior_defect_count`. The
-git indexer classifies a commit as a fix with the **same keyword rule the
-defect benchmark labels fixes with** (`_constants.is_fix_commit`), counts only
-non-merge commits inside the window, and anchors the window to the index's
-`as_of` reference (the indexed commit's committer date): so scoring a historical T0
-checkout measures the fixes *before* T0, never leaking the post-T0 fixes that
-form the benchmark's labels. It carries a **neutral (1.0) weight by design**:
-on the calibration corpus prior-defect history is largely redundant with the
-existing process signals (correlation ≈ +0.59 with `change_entropy`, +0.38 with
-churn; calibrated coefficient ≈ +0.02, effort-aware Popt gain within bootstrap
-noise), so it is not boosted as a predictor. It ships for its **explanatory**
-value, not for a measured accuracy lift: "this file was bug-fixed N times
-recently" is immediately actionable, and it uniquely flags a few files the
-other signals miss.
-
-`coverage_gradient` makes the test-coverage signal **continuous**. The two
-binary coverage gates (`untested_hotspot`, `coverage_gap`) only fire below hard
-thresholds (≈40–60% line coverage), so on a well-tested codebase (where most
-files sit at 85–99%) the score is effectively blind to coverage even though the
-uncovered fraction still carries defect signal. `coverage_gradient` deducts
-health in direct proportion to that fraction: `4.0 × (1 − line_coverage_pct/100)`
-health points, clamped by its category cap (binding at ≥50% uncovered). It uses
-the `deduction` override on `BiomarkerResult` (a continuous magnitude that
-replaces the discrete severity-to-deduction table for that finding) so it stays
-**linear and per-finding attributable** (the `health_impact` contract holds). It
-is **silent when no coverage report was ingested** (`line_coverage_pct is None`):
-absent coverage is never imputed as uncovered. It lives in its own capped
-category (`test_coverage_gradient`, −2.0) so the additive continuous signal
-neither squeezes nor is squeezed by the binary gates, and it skips test files.
-It and `coverage_gap` also skip a file that holds only a docstring, imports and
-export lists (`__all__`): a package `__init__.py` or an `index.ts` barrel.
-Calibrated offline against the defect corpus, it recovers **+0.043 corpus AUC
-[95% CI +0.023, +0.061]** on the covered subset (≈65% of the continuous-feature
-ceiling), Popt-neutral, and is exactly zero on repos without ingested coverage:
-a purely additive improvement.
-
-`low_cohesion` (LCOM4) and `god_class` are the two **class-level**
-structural smells. They read `ctx.class_metrics`, the per-class aggregates
-the walker now emits alongside per-function metrics (see §5.2).
-`brain_method`'s centrality gate is **language-agnostic**: instead of a
-fixed `dependents ≥ 8`, it fires when a file is in the repo's top quintile
-of connected files (`repo_dependents_p80`, computed once per analyze) or
-clears the absolute hub bar of 8: so it no longer goes silent on
-sparse-graph languages (TS barrels, Rust) whose in-degrees are lower than
-Python's.
+| Category | Defect cap | Maintainability cap |
+|---|---|---|
+| Organizational (history and governance) | 3.5‡ | none |
+| Structural complexity | 2.5 | 4.0 |
+| Test coverage | 2.0 | none |
+| Test coverage gradient | 2.0 | none |
+| Size & complexity | 1.5 | 2.0 |
+| Duplication | 1.0 | 2.0 |
+| Test quality | 0.5 | none |
+| Error handling | 0.5 | 2.0 |
+| SQL | none | 2.0 |
+
+- Maintainability caps (`_MAINTAINABILITY_CATEGORY`) and the single `performance`
+ category (2.0) are hard caps. Governance findings are written *after* scoring and never
+ touch `HealthFileMetric.score`.
+- ‡ **History** is a hard cap, `history_cap(structure) = min(3.5, 1.0 + structure)`,
+ where `structure` is the file's settled deduction from every other defect category.
+ Before it, `destacked` counts the largest history finding whole and the rest at 0.25.
+- **Every other defect category saturates** (`shape_curve.py`): raw total `R` deducts
+ `A * (1 - exp(-R / A))` with `A = 3.09 x cap`, so no category deducts more than 3.09
+ times its cap. The 3.09 is fitted so the corpus mean matches the hard-capped score;
+ the curve is AUC-neutral on the 66-repo corpus.
+- Function-shape findings (`FUNCTION_SHAPE_MARKERS`) on one function count the largest
+ whole and the rest at 0.25. A critical `complex_method`, `large_method` or
+ `nested_complexity` deducts `2.0 x value / threshold` (CCN 25, 200 lines, nesting 7),
+ so halving a CCN-50 function pays while it stays critical.
+
+### Marker notes
+
+- **Git process markers** read indexer fields: `ownership_risk` (Bird et al.;
+ `top_authors_json`), `churn_risk` (size-normalized, Nagappan-Ball; `lines_added_90d`,
+ `churn_percentile`), `change_entropy` (Hassan; §5.1), `co_change_scatter` (D'Ambros;
+ `co_change_partners_json`), `prior_defect` (Ostrand-Weyuker, Kim's "bug cache";
+ `prior_defect_count`). `knowledge_loss` is activity-gated, so abandoned-but-stable files
+ (the survivor effect) stay silent.
+- **`prior_defect`** counts non-merge fix commits in the trailing ~6 months, classified by
+ the **same keyword rule the defect benchmark labels with** (`_constants.is_fix_commit`)
+ and anchored to the index's `as_of` (the indexed commit's date), so a T0 checkout never
+ sees post-T0 fixes. Its **neutral 1.0 weight is by design**: correlation ≈ +0.59 with
+ `change_entropy` and +0.38 with churn, coefficient ≈ +0.02, Popt gain within noise. It
+ ships for its **explanatory** value and catches a few files the others miss.
+- **`coverage_gradient`** makes coverage **continuous**: the binary gates fire only below
+ ≈40-60%, blind to the 85-99% files where the uncovered share still predicts defects. Its
+ `deduction` override on `BiomarkerResult` keeps it **linear and per-finding
+ attributable** (2.0 points at 50% uncovered), in its own category so it neither squeezes nor is squeezed by the
+ gates. It is **silent without a report** (`line_coverage_pct is None`), skips tests and,
+ like `coverage_gap`, files of only a docstring, imports and `__all__` (an `__init__.py`
+ or `index.ts` barrel). It adds **+0.043 corpus AUC [95% CI +0.023, +0.061]** on the
+ covered subset (≈65% of the continuous-feature ceiling), Popt-neutral, and zero
+ without coverage.
+- **Class-level:** `low_cohesion` and `god_class` read `ctx.class_metrics` (§5.2).
+ `brain_method`'s gate is **language-agnostic**: the repo's top quintile of connected
+ files (`repo_dependents_p80`, once per analyze) or the absolute hub bar of 8, so sparse
+ graphs (TS barrels, Rust) are not silent.
+- **`large_method`** needs judged CCN ≥ 3, so a long-but-flat body (a data literal, a
+ dispatch of one-line arms) reads as layout. In `.tsx` / `.jsx` a line of only JSX tags,
+ attributes or text is markup; a `{...}` expression is code. Its reason reads "N lines of
+ code (M with blanks and comments)", with M in `details.span`. `complex_method` reports
+ the judged CCN, plus the raw CCN when they differ.
+- **`error_handling`** (advisory maintainability) flags empty or comment-only `catch` /
+ `except: pass`, Python `except:` / `except Exception:`, Rust `.unwrap()` / `.expect()` /
+ panic macros, and Go's empty `if err != nil {}` or blank-identifier error discard. A
+ whole-tree walker pass (module code included) reuses the catch kinds of the seven
+ catch-shaped languages plus Rust and Go recognizers; unsupported or unparsable is "no
+ signal". One LOW finding per occurrence (0.15 after the 0.5 floor); its 0.5-cap
+ category deducts at most 3.09 × 0.5 ≈ 1.5. It is **excluded from calibration**:
+ AUC-neutral on the 21-repo / 9-language T0 benchmark (OOF delta ≈ 0) but size-orthogonal
+ and the least redundant signal tested; users expect `except: pass` flagged.
+- **Test quality:** the two assertion-block markers (§5.3) fire only on test files, in a
+ small category so a noisy test can't dominate its score.
### 5.1 Change-entropy git-layer fields
-`change_entropy` is computed during the **single** FULL-tier co-change walk
-(`ingestion/git_indexer/co_change.py::compute_co_changes_and_entropy`): no
-extra `git log` subprocess. For each commit touching a set of tracked files
-`F` (with `2 ≤ |F| ≤ 30`; wider commits are dropped as noise, Hassan's filter),
-the commit's entropy is `log2(|F|)`, distributed uniformly (`1/|F|` per file)
-and decayed with the same τ=180d half-life as co-change. The decay-weighted sum
-per file is `git_meta["change_entropy"]`. `enrich.compute_percentiles` then
-derives `change_entropy_pct` by ranking **only files with positive entropy**
-(zero-entropy files, the ESSENTIAL tier or files only ever changed alone,
-keep pct 0.0 so the marker stays silent). Both fields are persisted on
-`git_metadata` (migration `0025`) and the additive-reconcile path back-fills
-them on legacy DBs.
+Computed in the **single** FULL-tier co-change walk
+(`ingestion/git_indexer/co_change.py::compute_co_changes_and_entropy`), no extra
+`git log`. A commit touching `2 ≤ |F| ≤ 30` tracked files has entropy `log2(|F|)` (wider
+ones are noise, Hassan's filter), spread `1/|F|` per file and decayed with co-change's
+τ=180d half-life into `git_meta["change_entropy"]`. `enrich.compute_percentiles` ranks
+**only positive-entropy files** into `change_entropy_pct`; zero-entropy files (the
+ESSENTIAL tier, files only ever changed alone) keep 0.0. Both live on `git_metadata`
+(migration `0025`), back-filled on legacy DBs by additive reconcile.
### 5.2 Class-level walker metrics (LCOM4)
-The complexity walker emits a `ClassComplexity` per class-like node for
-languages that opt in (`LanguageNodeMap.class_kinds` non-empty: Python,
-TS/JS, Java, Kotlin, Rust `impl`, C++, C#; Go has no grouping node). LCOM4 is the number of
-connected components in the graph whose nodes are the class's methods and
-whose edges link methods that share an instance field or call one another.
-Member references are detected per-language via `self`/`this`/`$this`
-member-access nodes. **Safety valve:** a class with no detected member
-references (a static utility, or an unmapped language) reports `lcom4 = 1`
-("no signal") rather than `len(methods)`, so adding a language can only
-turn signal on, never produce a false-positive flood. See
-`complexity/README.md` for the full heuristic and its limits.
-
-`error_handling` is the **advisory maintainability** marker: swallowed
-catches (an empty/comment-only `catch` / `except: pass` body), Python
-catch-all `except:` / `except Exception:`, Rust `.unwrap()` / `.expect()` /
-panic-family macros, and Go's empty `if err != nil {}` or blank-identifier
-discard of a call's error. The walker collects each occurrence (with its
-line) in a whole-tree pass (module-level code included) reusing the
-`LanguageNodeMap` catch kinds for the seven catch-shaped languages and
-dedicated recognizers for Rust/Go; an unsupported language or parse failure
-yields no hits ("no signal", never a guess). The marker emits one LOW
-finding per occurrence (0.15 after its floored 0.5 weight) in its own
-`error_handling` category capped at −0.5, mirroring `test_quality`'s
-advisory framing. It is deliberately **excluded from the defect-weight
-calibration**: on the 21-repo / 9-language T0 benchmark it is AUC-neutral
-(OOF delta ≈ 0, CI crosses zero) but size-orthogonal and the least redundant
-signal tested, and it ships because users expect `except: pass` flagged:
-bounded so it can never move a file by more than half a point.
+Languages with non-empty `LanguageNodeMap.class_kinds` (Python, TS/JS, Java, Kotlin, Rust
+`impl`, C++, C#; Go has no grouping node) get a `ClassComplexity` per class. LCOM4 counts
+connected components of the class's methods, linked by a shared instance field or a call,
+found via `self`/`this`/`$this` member access. **Safety valve:** no detected member
+references (a static utility, an unmapped language) gives `lcom4 = 1` ("no signal"), so a
+new language can only turn signal on. Details: `complexity/README.md`.
### 5.3 Assertion-block walker metrics (test-quality)
-The same single walker pass records `assertion_blocks` on each
-`FunctionComplexity`: runs of ≥ 2 consecutive assertion statements, each
-`(start_line, end_line, count)`. A statement counts as an assertion when it
-is a bare `assert` (`LanguageNodeMap.assert_kinds`) or its expression is a
-call (`assert_call_kinds`) whose callee name starts with `assert` or
-`expect`: covering `assertEqual` / `assert_eq!` / `expect(...).toBe(...)`
-across xUnit and BDD styles. Opt-in per language, with all nine full-tier
-languages (Python, TS/JS, Java, Kotlin, Go, Rust, C++, C#) mapped;
-a language that maps neither field simply emits no blocks.
-`large_assertion_block` flags a single run ≥ 15; `duplicated_assertion_block`
-intersects the clone report with assertion spans. Both gate on
-`coverage.is_test_file(path)` so production code is never touched.
+The walker records `assertion_blocks` per `FunctionComplexity`: runs of ≥ 2 consecutive
+assertions as `(start_line, end_line, count)`. An assertion is a bare `assert`
+(`assert_kinds`) or a call (`assert_call_kinds`) whose callee starts with `assert` or
+`expect` (`assertEqual`, `assert_eq!`, `expect(...).toBe(...)`). All nine full-tier
+languages (Python, TS/JS, Java, Kotlin, Go, Rust, C++, C#) are mapped; a language mapping neither field emits none. Both block markers
+gate on `coverage.is_test_file(path)`; `duplicated_assertion_block` intersects the clone
+report with assertion spans.
### 5.4 Advisory markers and their precision record
-`advisory` is not in `DIMENSIONS`, so no weight, category or cap table can key
-on it; "never deducts" is structural. A marker must appear in both
-`_BIOMARKER_DIMENSIONS` and `_ADVISORY_HOME`, or it still deducts from defect.
+`advisory` is not in `DIMENSIONS`, so no weight, category or cap table can key on it. A
+marker must be in both `_BIOMARKER_DIMENSIONS` and `_ADVISORY_HOME`, or it still deducts.
Advisory findings carry `health_impact == 0.0`, never count toward a change's
-introduced/worsened totals, never make a review verdict blocking, and stay out of
-impact-ranked lists unless the dimension or marker is named.
-
-A marker earns weight by clearing roughly 70% hand-labelled precision on a real
-corpus. Precision is measured per language because it does not transfer:
-
-- `mock_saturated_test`: 67% on Python (32 findings) and 40% on TypeScript (30),
- each the full population at the shipped gate. Both predate the assertion count
- gaining more oracle shapes, which can only suppress findings, so they are now a
- ceiling. It stays advisory until two false-positive families separate:
- `Fake*` value-object builders passed into real logic, and boundary isolation
- where the assertion reads a real artifact. Both turn on whether an assertion
- observes a double or production output, a dataflow question the pass does not
- ask.
-- `assertion_free_test`: at least 71% on TypeScript (31 findings, the full
- population of two corpora; a floor, since three false-positive families closed
- after labelling) and 86% on Python (29 labelled, a systematic sample of 172). It
- does not report on Go or Java. A test that delegates its oracle to a helper is
- resolved by name in the same file and through the call graph across files. A
- mock verification counts as an oracle here, the opposite of
- `mock_saturated_test`; the tiers are in `complexity/assertions.py`.
-- `hidden_coupling`: see §5 (near-chance AUC; non-inferior without it).
+introduced/worsened totals or make a review blocking, and stay out of impact-ranked lists
+unless named. A marker earns weight at roughly 70% hand-labelled precision, measured per
+language because it does not transfer:
+
+- `mock_saturated_test`: 67% Python (32 findings), 40% TypeScript (30), each the full
+ population at the shipped gate and a ceiling (later oracle shapes only suppress). It
+ waits on two false-positive families, `Fake*` builders passed into real logic and
+ boundary isolation where the assertion reads a real artifact: a dataflow question.
+- `assertion_free_test`: ≥ 71% TypeScript (31, the full population of two corpora; a
+ floor, three false-positive families closed after labelling), 86% Python (29 labelled,
+ a systematic sample of 172); not Go or Java. A helper's oracle resolves by name in the
+ file and via the call graph across files; a mock verification counts as an oracle, the opposite of `mock_saturated_test`
+ (tiers in `complexity/assertions.py`).
+- `hidden_coupling`: near-chance alone (AUC about 0.55); a pre-registered test on 12
+ repositories no earlier health study used found the score non-inferior without it.
+- `brain_method`: fires only where `complex_method` and `large_method` already charge;
+ dropping it left defect AUC unchanged on the 66-repo corpus.
+- `untested_complexity`: complexity and coverage already deduct elsewhere
+ ([user guide](../layers/TEST_INTELLIGENCE.md#untested-complexity)).
### 5.5 Worked example: the dispatch rule
-`nested_complexity` increments depth on each `if` / `for` / `while` / `try` /
-`switch` node and fires at depth 4 or more, severity scaling with depth. A function
-that is mostly one dispatch on one value (a `switch`, `match` or same-subject `if`
-chain holding at least 60% of its decision points) is judged by the code around the
-dispatch and its heaviest arm: `nested_complexity` skips the two levels the
-`switch` and its `case` open, and `complex_method`, `brain_method` and `repeated_nesting`
-read the CCN outside the dispatch plus the CCN of its most complex arm.
-
-In TypeScript and JavaScript (TSX / JSX included) a ternary opens no nesting level
-when it is an arm of a chain (`a ? x : b ? y : z`), sits inside JSX markup, or has a
-JSX branch: a view choosing one of ten panels is one decision per arm (each still
-counts toward CCN and adds a flat +1 to cognitive complexity, like an `else if`), not
-ten levels deep. A ternary inside another's `consequence` still nests, as does one in
-a call argument or object literal inside JSX (`{fmt(a ? b : c)}`) and one whose
-branch is not itself JSX (`cond ? c2 && <A/> : x`); so does every `if` / `for` /
-`try` in a handler written in JSX.
-
-`biomarkers/registry.py` is an **explicit list**, not auto-discovery:
-keeps the registration order deterministic and lets tests inject extras
-via `registered_biomarkers(extra=...)`.
+`nested_complexity` adds a level per `if` / `for` / `while` / `try` / `switch`. A
+function mostly one dispatch on one value (a `switch`, `match` or same-subject `if` chain
+with ≥ 60% of its decision points) is judged by the code around it plus its heaviest arm:
+`nested_complexity` skips the `switch` and `case` levels, and `complex_method`,
+`brain_method` and `repeated_nesting` read the outer CCN plus the worst arm's.
----
+<details>
+<summary>TypeScript and JavaScript ternaries</summary>
-## 6. Scoring (`scoring.py`)
+A ternary opens no level as an arm of a chain (`a ? x : b ? y : z`), inside JSX markup, or
+with a JSX branch: one decision per arm (still +CCN and a flat +1 cognitive, like
+`else if`). Still nesting: a ternary in another's `consequence`, in a call argument or
+object literal inside JSX (`{fmt(a ? b : c)}`), with a non-JSX branch
+(`cond ? c2 && <A/> : x`), and every `if` / `for` / `try` in a JSX handler.
-Every file starts at **10.0**. Each finding contributes a per-severity
-deduction (`low=0.3, medium=0.7, high=1.2, critical=2.0`), scaled by the
-marker's calibrated weight multiplier (§6.1). `score_file()` then groups the
-weighted findings by category, sums the raw deductions per category, and either
-accepts the sum or, when it exceeds the cap, scales every per-finding deduction
-in that category proportionally so the total equals the cap. This keeps the
-UI's "this finding cost you X points" honest after capping. The final score is
-clamped to `[1.0, 10.0]`. So even ten critical structural findings can drive
-structural complexity down by at most 3.5 points, not 20.
+</details>
-The per-finding scaled deduction lands on `HealthFinding.health_impact`
-via `attach_impacts()`: that's what the dashboard's "−2.0" badge shows.
+---
+
+## 6. Scoring (`scoring.py`)
-Snapshot tests in `tests/unit/health/test_scoring_snapshot.py` lock the
-category caps, severity deductions, marker-to-category mapping, and two
-known-fixture scores. A retune intentionally requires updating the
-snapshot in the same PR.
+Every file starts at **10.0** and is clamped to `[1.0, 10.0]`. A finding deducts its
+severity (`low=0.3, medium=0.7, high=1.2, critical=2.0`) times its weight (§6.1);
+`score_file()` sums per category and settles each total (§5); each finding is then scaled
+by settled/raw, so the parts still sum to the category and `HealthFinding.health_impact`
+(via `attach_impacts()`, defect pillar only, the dashboard's "−2.0") stays honest.
+`test_scoring_snapshot.py` locks caps, severity deductions, the marker-to-category map
+and two fixture scores, so a retune updates it in the same PR.
### 6.1 Calibrated weight multipliers
-`scoring._BIOMARKER_WEIGHT_MULTIPLIER` lets the strongest empirical predictors
-deduct more than the uniform severity table alone allows. The multipliers are
-**calibrated offline against a defect corpus, not hand-tuned**: each file is
-scored at the pre-window commit (T0, no leakage) and an L2-logistic regression,
-with NLOC as an explicit control, fits each marker's defect lift beyond file
-size. The runtime stays deterministic; only the learned constants ship. The
-full calibration, with confidence intervals, is published in the
-[benchmark report](https://github.com/repowise-dev/repowise-bench/blob/master/health-defect/BENCHMARK_REPORT.md);
-§6.2 describes the protocol.
-
-| Weight | Markers | Rationale |
-|---|---|---|
-| 1.8 | `co_change_scatter` | Strongest calibrated predictor. |
-| 1.51 | `change_entropy` | History Complexity Metric; second strongest. |
-| 1.38 | `ownership_risk` | Long-run minor-contributor dispersion. |
-| 1.34 | `nested_complexity` | Strongest structural predictor. |
-| 1.1–1.33 | remaining structural complexity / size markers | Moderate calibrated lift. |
-| 1.3 / 1.2 / 1.1 | `untested_hotspot` / `churn_risk` / `code_age_volatility` | Coverage-dependent and rarely-firing; keep prior weights the corpus could not fairly measure. |
-| 1.0 | `prior_defect` | Neutral by design: largely redundant with the other process signals, kept for its explanatory value. |
-| 0.5 (floored) | `developer_congestion`, `dry_violation`, `low_cohesion`, `primitive_obsession`, `repeated_nesting` | Fire widely but proved weak under leakage-free scoring; kept as maintainability and parity signals, not disabled. |
-| 0.4 (de-rated) | `knowledge_loss` | Weakest of the floored set. |
-| 0.5 (not fitted) | `error_handling` | Excluded from calibration (AUC-neutral); floored and capped at 0.5 per file. |
-
-The same marker stream feeds the **maintainability** signal under an
-independent, expert-set weight table (the floored smells deduct at full weight
-there), and the **performance** signal under its own bounded `performance`
-category. The three signals share one scoring kernel against separate
-weight/category/cap tables and never feed back into each other; see the
-[user guide](../layers/CODE_HEALTH.md#the-three-signals)
-for what each signal surfaces. The headline stays the defect score: the band
-cutoffs and every accuracy figure are claims about that pillar, and
-`test_scoring_dimensions` locks `score_file(...)["defect"]` byte-for-byte to the
-pre-split single score. Blending the pillars would need a written rationale and a
-recalibration corpus.
+`scoring._BIOMARKER_WEIGHT_MULTIPLIER` (values in [the full roster](#the-full-roster)) is
+**calibrated offline, not hand-tuned**: files scored at T0, an L2-logistic regression with
+NLOC as a control fits each marker's lift beyond size, and only the constants ship
+([benchmark report](https://github.com/repowise-dev/repowise-bench/blob/master/health-defect/BENCHMARK_REPORT.md)).
+
+- **Strongest:** `co_change_scatter` (strongest), `change_entropy` (second),
+ `ownership_risk`, `nested_complexity` (strongest structural).
+- **Prior weights kept:** `untested_hotspot`, `churn_risk`, `code_age_volatility`, which
+ are coverage-dependent or rare, so the corpus could not fairly measure them.
+- **Floored at 0.5:** `developer_congestion`, `dry_violation`, `low_cohesion`,
+ `primitive_obsession`, `repeated_nesting` fire widely but proved weak under
+ leakage-free scoring; `knowledge_loss` is de-rated to 0.4, the weakest.
+ `error_handling` is not fitted.
+
+Maintainability uses an independent expert-set table (floored smells at full weight) and
+performance its own bounded category; the three share one kernel and never feed each
+other. The headline stays the defect score: `test_scoring_dimensions` locks
+`score_file(...)["defect"]` byte-for-byte to the pre-split score, and blending pillars
+would need a written rationale and a recalibration corpus.
### 6.2 Validation and calibration
-**Protocol.** Every file is scored at a commit T0 that precedes the bug window, in
-a detached worktree whose history stops at T0. Labels are the bug-fix commits of
-the following six months. An L2-regularized logistic regression with NLOC as an
-explicit control column fits each marker's lift beyond size, with
-leave-one-repo-out cross-validation. Only the learned constants ship.
-
-**Leakage runs both ways.** Scoring at HEAD lets the bug-fix commits manufacture
-the churn, co-change and congestion the process markers then "detect". Scoring
-naively at T0 silences every recency-windowed marker, because a worktree six
-months back sees an empty "last 90 days". Recency windows are therefore anchored to
-the worktree's own HEAD (`as_of`), not wall-clock time. The evidence that this
-matters: `developer_congestion` shipped at 1.5 under HEAD scoring and came back at
-coefficient -0.08 under T0 scoring, hence its 0.5 floor.
-
-**What calibration rejected.** Graph centrality (PageRank), code naturalness,
-change bursts and error-handling density were declared equivalent to null by
-bootstrap TOST, not merely non-significant. Size-relative scoring (lifts small
-files, costs 0.07 to 0.12 AUC overall), function-level prediction (Popt at or
-below random effort ordering) and recalibrating on SZZ labels (lower out-of-fold
-AUC than the shipped weights) were all run and refuted.
-
-**Two corpora.** The cross-project result uses 21 repositories, 9 languages,
-2,826 files (379 defect-bearing). The CodeScene comparison uses the 2,770 of those
-files both tools could score. The band-separation figures (16.9x raw, 2.18x
-size-normalized, At risk vs 8.0 and above) come from the paired 2,770-file set.
-
-| Cross-project result (2,826 files) | Value |
-|---|---|
-| Mean ROC AUC | 0.737 (95% CI 0.683 to 0.787) |
-| Held out: PROMISE jEdit 4.0 / 4.1 (no git history, structural markers only) | 0.761 / 0.776 |
-| vs. recent churn | +0.100 AUC (DeLong p = 5e-10) |
-| vs. prior-defect history | +0.117 AUC (DeLong p = 3e-15) |
-| Per-repo range | 0.55 (axios) to 0.86 (zod) |
-
-Intervals come from a two-stage repo-cluster bootstrap (2,000 seeded replicates,
-repositories then files), since the repository is the unit of generalization.
-
-Limits measured on the same corpus:
-
-- LOC alone scores AUC 0.742 (delta -0.001, p = 0.92). The win is effort-aware:
- Popt +0.134 (95% CI +0.080 to +0.198).
-- Within NLOC quartiles AUC is 0.525 / 0.572 / 0.593 / 0.718. A positive control
- injecting a size-orthogonal signal of the headline magnitude was recovered with
- power 0.998 to 1.000 in those same quartiles, so the collapse is a property of
- the score, not of sample size.
-- A prior-defects baseline beats the score on Popt by 0.085 (95% CI 0.035 to
- 0.141).
-
-| Paired test vs CodeScene (2,770 files) | Repowise | CodeScene | p |
-|---|---:|---:|---|
-| Recall at 20%-of-lines budget | 0.173 | 0.074 | 0.003 |
-| Popt | 0.607 | 0.462 | 0.003 |
-| Defect density, size-normalized | 2.18x | 0.56x | 0.003 |
-| ROC AUC | 0.731 | 0.705 | 0.054 (not significant) |
-| Defect density, raw | 16.9x | 14.2x | 0.65 (not significant) |
-| Precision at 20%-of-lines budget | 0.580 | 0.636 | 0.64 (tie) |
-| Partial rho beyond size | -0.148 | -0.137 | both beat size (tie) |
-
-CodeScene flags 27 files at its most severe level where Repowise flags 132 At
-risk: a more conservative operating point, not a calibration flaw. Its "Code Red"
-correlation of -0.58 with issue-resolution time (proprietary Jira data) did not
-replicate on open GitHub data: -0.09 (95% CI -0.19 to +0.14), and six
-queue-independent effort signals were flat.
-
-**In-product check.** `defect_accuracy.py` ranks files by score, takes the 20
-lowest and counts those touched by a fix commit in the trailing 180 days against the
-repo base rate. It stays silent below 25 scored files or 5 fixed files. Because
-`prior_defect` is an input, this is an association on indexed history, not a
-forward test.
-
-Full method and data:
-[repowise-bench/health-defect](https://github.com/repowise-dev/repowise-bench/tree/master/health-defect)
-([COMPARISON_REPORT.md](https://github.com/repowise-dev/repowise-bench/blob/master/health-defect/COMPARISON_REPORT.md)).
+Headline results (jEdit 4.0 / 4.1 held out with no git history, structural markers only): [layer page](../layers/CODE_HEALTH.md#accuracy-and-limits) and
+[BENCHMARKS.md](../BENCHMARKS.md#code-health-predicts-defects).
+
+- **Protocol.** Files scored at a commit T0 before the bug window, in a detached worktree
+ whose history stops at T0; labels are the next six months of fix commits;
+ L2-regularized logistic regression with an NLOC control and leave-one-repo-out
+ cross-validation.
+- **Leakage both ways.** HEAD scoring lets fix commits manufacture the churn and
+ congestion process markers "detect"; naive T0 scoring silences recency windows, so they
+ anchor to the worktree's own HEAD (`as_of`). `developer_congestion` shipped at 1.5
+ under HEAD scoring and came back at coefficient -0.08, hence its floor.
+- **Rejected.** PageRank, code naturalness, change bursts and error-handling density were
+ equivalent to null by bootstrap TOST. Size-relative scoring (−0.07 to −0.12 AUC),
+ function-level prediction (Popt at or below random) and SZZ labels (lower out-of-fold
+ AUC) were refuted.
+- **Corpora.** 21 repositories, 9 languages, 2,826 files (379 defect-bearing); the
+ commercial-tool comparison and band separation (16.9x raw, 2.18x size-normalized) use
+ the 2,770 both tools scored. Intervals: two-stage repo-cluster bootstrap (2,000 seeded
+ replicates).
+- **More results.** +0.100 AUC over recent churn (DeLong p = 5e-10) and +0.117 over prior
+ defects (p = 3e-15); per repo 0.55 (axios) to 0.86 (zod). LOC alone: delta -0.001
+ (p = 0.92); Popt +0.134 (95% CI +0.080 to +0.198). NLOC quartiles 0.525 / 0.572 /
+ 0.593 / 0.718, with a positive control recovered at power 0.998 to 1.000, so the
+ collapse is the score's. A prior-defects baseline beats it on Popt by 0.085 (95% CI
+ 0.035 to 0.141).
+- **Paired vs the commercial tool:** Popt 0.607 vs 0.462, size-normalized density 2.18x
+ vs 0.56x (both p = 0.003); AUC 0.731 vs 0.705 (p = 0.054); raw density 16.9x vs 14.2x
+ (p = 0.65); precision 0.580 vs 0.636 (p = 0.64); partial rho beyond size -0.148 vs
+ -0.137. It flags 27 files at its most severe level where Repowise flags 132 At risk (a
+ more conservative point); its published -0.58 correlation with issue-resolution time
+ (proprietary Jira data) was -0.09 (95% CI -0.19 to +0.14) on open GitHub data, and six
+ queue-independent effort signals were flat.
+- **In-product check** (`defect_accuracy.py`): an association, since `prior_defect` is an
+ input. Data:
+ [repowise-bench/health-defect](https://github.com/repowise-dev/repowise-bench/tree/master/health-defect)
+ ([COMPARISON_REPORT.md](https://github.com/repowise-dev/repowise-bench/blob/master/health-defect/COMPARISON_REPORT.md)).
### 6.3 Fix first ranking (`fix_first/`, `worth.py`)
-Index and update save the queue and the Do next list, so these surfaces open without rebuilding them.
-
-Fix first is built once in `analysis/health/fix_first/build.py` from stored rows
-and rendered unchanged by `get_health`, `repowise health`, the dashboard and the
-generated CLAUDE.md. Every excluded unit is counted in `totals.excluded` under one
-reason. These reasons and the performance default queue's are decided in one place,
-`analysis/health/queue/`:
+`fix_first/build.py` builds Fix first once from stored rows (index and update save it and
+Do next); `get_health`, `repowise health`, the dashboard and the generated CLAUDE.md
+render it unchanged. Each excluded unit is counted in `totals.excluded` under one reason,
+decided with the performance queue's in `analysis/health/queue/`:
| Reason | What it leaves out |
|---|---|
-| `test`, `tooling`, `generated`, `vendored`, `docs_example` | Path-role classification. Tooling includes build files by type wherever they sit (Gradle, CMake, Makefiles, Bazel, MSBuild props/targets, root `setup.py`, `noxfile.py`, crate-root `build.rs`, bundler configs). Docs means a root `docs/` or `docs_src/` tree, or one beside a docs-site config; a product's own `app/docs/` route is production |
-| `unknown`, `expected`, `no_strategy`, `no_plan` | Performance causes with no classified context, expected repetition, no supported strategy, or no stored safe plan |
-| `below_min_worth` | A refactoring recovering under `MIN_WORTH` (0.5) or with no steps |
-| `unmeasured_cost`, `cold_role`, `background_unproven`, `unconfirmed_cost` | Performance causes the default queue drops, and queued causes `perf_confident_verdict` does not confirm: growth only a registry or cold-path loop shows, or no known role and no entry point reaching it |
+| `test`, `tooling`, `generated`, `vendored`, `docs_example` | Path roles (notes below) |
+| `unknown`, `expected`, `no_strategy`, `no_plan` | Performance causes: no classified context, expected repetition, no strategy, no safe plan ([PERFORMANCE.md](../layers/PERFORMANCE.md)) |
+| `below_min_worth` | Under `MIN_WORTH` (0.5) recovered, or no steps |
+| `unmeasured_cost`, `cold_role`, `background_unproven`, `unconfirmed_cost` | Dropped by the default queue, or not confirmed by `perf_confident_verdict` (registry or cold-path growth only, or no role and no reaching entry point) |
| `history_only` | Only git-history findings |
| `deprecated` | Deprecated functions |
-| `gated_off` | Functions a same-file constant-false flag switches off (`complexity/gating.py`): the body opens with `if not FLAG: return` or is one `if FLAG:` block. For performance this is the opportunity state `expected` with reason `gated_off`, and the default queue counts it under `gated_off`. `totals.dormant` counts the distinct functions |
-| `unreachable` | Targets an open dead-code finding with confidence 0.8 or more, or marked safe to delete, covers: the whole file, the symbol's lines, or its name |
-| `inherent_dispatch` | One dispatch holds 60% or more of the decision points (labels: 8 of 9 such rows rejected), unless a duplicate also sits in it |
-| `small_function` | Under 30 code lines and CCN 15 (on 67 labelled rows this cut drops 13 rejected and 4 accepted) |
+| `gated_off` | Dormant: switched off by a same-file constant-false flag (`complexity/gating.py`) |
+| `unreachable` | An open dead-code finding (confidence 0.8+ or safe to delete) covers the file, the symbol's lines, or its name |
+| `inherent_dispatch` | One dispatch holds ≥ 60% of decision points (8 of 9 labelled rows rejected), unless a duplicate sits in it |
+| `small_function` | Under 30 code lines and CCN 15 (on 67 labelled rows: drops 13 rejected, 4 accepted) |
| `no_concrete_step` | No first edit with a file and line or a named group |
| `low_value_kind` | Low cohesion (0 of 46 accepted), long method (0 of 10), long parameter lists (0 of 2) |
-| `kind_unaudited` | Plans led by Extract Class (0 of 14 accepted) or Move Method (0 of 34), kept to the full list until each passes a per-language audit |
-| `terminal_flow` | A quarter or more of the function's calls print or prompt (`complexity/terminal.py`): a status report, checklist or setup wizard |
-| `moderate_quiet` | Under CCN 80 and 200 lines, in a file outside the top fifth by churn (or changed once), with no `prior_defect` in the file and no `function_hotspot` on the function |
-
-Order: value first (the larger of health recovered and size: CCN 20/40/80/150,
-lines 100/200/400/800, nesting 5/6/8, a critical or brain-method finding, one step
-more on a hot file, where a function under 5% of its file's lines is credited that
-share of the file's importers); a performance fix's value is its cost, with production,
-entry-reachable, data-growing DB or network calls in the top band. Then tier
-`now` / `next` / `later`, with at most `HEAD_PER_KIND` (3) of the first `HEAD` (5)
-places per kind. `worth.py` decides `later` for every default list: a function
-under CCN 40, 200 lines and nesting 6 (nesting under 8 only counts at 100 lines or
-more) and not both CCN 25 and nesting 5; a dominant dispatch; nesting that is one
-else-if or ternary chain; long but CCN under 20 and nesting under 5; a single
-complex condition or error site. From CCN 80, 400 lines or nesting 8 a function is
-worth doing regardless. The hot-file bonus orders items but never lifts one out of
-`later`. Inside a band, items order by complexity removed times reach times the lead
-function's history, `1 + ln(1 + n)` for the `n` commits that changed it (`git_function_blame`);
-a repository with no function history, a file too large to blame, a unit led by no
-function and a performance cause weigh a file in the top fifth by churn 1.25 instead. Each item carries up to `MAX_TESTS` (5) tests from its validation profile.
-
-The findings list uses the same rule: worth-doing findings lead and the rest carry
-`lower_priority`. Class-design findings and history-only findings are lower
-priority there; a performance opportunity is unless production code runs it over
-growing data.
+| `kind_unaudited` | Extract Class (0 of 14) or Move Method (0 of 34) plans, until a per-language audit passes |
+| `terminal_flow` | ≥ 25% of calls print or prompt (`complexity/terminal.py`): status reports, checklists, wizards |
+| `moderate_quiet` | Under CCN 80 and 200 lines, outside the top fifth by churn (or changed once), no `prior_defect` in the file, no `function_hotspot` on it |
+
+<details>
+<summary>Path-role and dormant-function details</summary>
+
+- Tooling includes Dart's `tool/` scripts and build files by type anywhere: Gradle,
+ CMake, Makefiles, Bazel, MSBuild props/targets, root `setup.py`, `noxfile.py`,
+ crate-root `build.rs`, bundler configs.
+- Docs means a root `docs/` or `docs_src/` tree, or one beside a docs-site config; a
+ product's `app/docs/` route is production.
+- Test helpers named for a module's tests (`bot.test-harness.ts`, `card-test-helpers.ts`,
+ `test-support.mjs`) are test support and `*.bundle.js` is generated; worst-file lists
+ say how many they left out and why.
+- Dormant: the body opens with `if not FLAG: return ...` or is one `if FLAG:` block, and
+ `FLAG` is a module-level `False`, `0` or `None` (`const FLAG = false` in TS/JS) the file
+ never reassigns. Only the file is read: an imported flag, or one flipped by `setattr` or
+ a monkeypatch, still reads as off. `totals.dormant` counts distinct functions; for
+ performance it is state `expected`, reason `gated_off`.
+
+</details>
+
+#### Order
+
+1. **Value**: the larger of health recovered and size (CCN 20/40/80/150, lines
+ 100/200/400/800, nesting 5/6/8, a critical or brain-method finding), one step more on
+ a hot file (a function under 5% of its file's lines is credited that share of the
+ importers). A performance fix's value is its cost; production, entry-reachable,
+ data-growing DB or network calls are the top band.
+2. **Tier** `now` / `next` / `later`; at most `HEAD_PER_KIND` (3) of the first `HEAD` (5)
+ per kind.
+3. **Inside a band**: complexity removed × reach (a 4,000-line loop outranks a long print
+ routine) × `1 + ln(1 + n)` for the `n` commits that changed the lead function
+ (`git_function_blame`); with no function history, a file too large to blame, no lead
+ function, or a performance cause, a top-fifth-churn file weighs 1.25.
+
+`worth.py` marks `later`: under CCN 40, 200 lines and nesting 6 (nesting under 8 counts
+only from 100 lines) and not both CCN 25 and nesting 5; a dominant dispatch; nesting that
+is one else-if or ternary chain; long but CCN under 20 and nesting under 5; a single
+complex condition or error site. CCN 80, 400 lines or nesting 8 is worth doing
+regardless; the hot-file bonus orders but never lifts out of `later`. Items carry up to
+`MAX_TESTS` (5) tests. The findings list uses the same rule (`lower_priority` on the
+rest; class-design and history-only findings, and performance unless production code
+runs it over growing data).
#### Fix first steps
-A finding's first step can borrow a stored refactoring plan. A refactoring item is
-`later` when the plan of any of its steps still leaves a function above the
-break-up bar; a finding whose first step borrows such a plan keeps its tier, and
-the step says the plan alone leaves the function above the bar. An Extract Method
-step finds its lines by the text they start and end with, as the plan does, since
-line numbers move with the first edit; when that text also appears elsewhere in
-the file, the step says to keep the edit inside its function.
+- A "Break up" reason says what splitting buys: smaller, easier parts, and less
+ duplication when part is a copy. "Due" means `now` or `next`.
+- A finding whose first step borrows a plan that still leaves a function above the bar
+ keeps its tier, and the step says so.
+- An Extract Method step finds its lines by their start and end text (line numbers move
+ with the first edit); if that text repeats in the file, it says to stay inside the
+ function.
### 6.4 Performance opportunities (`perf/`)
-User guide: [PERFORMANCE.md](../layers/PERFORMANCE.md).
-
-**Sinks.** `io_in_loop` resolves a call inside a loop through the graph's
-resolver and classifies the target against the I/O-boundary lexicon
-(`io_boundaries.py`: db, network, filesystem, subprocess, lock). It fires only on a
-real round-trip, never on a query-builder chain. A non-local sink is found by
-walking the resolved call graph backwards up to three hops (`crossfn.py`), and the
-`caller -> ... -> sink` path is attached.
-
-**Gates.** Two markers use call-graph centrality as a precision gate: they fire
-only in functions at or above the 80th percentile of distinct direct callers, and
-never under two. That measures how widely a function is called, not request
-reachability. `blocking_sync_in_async` skips tests, tooling, examples, generated
-and vendored code.
-
-**Opportunities.** One opportunity per intervention site within one cost family
-and boundary: the function holding the loop, a shared helper every caller passes
-through, or `<file>::__module__` for top-level code. Sinks, call sites and
-same-family co-signals (`io_in_loop` with `nested_loop_with_io`) are members. Two
-loops in one function are one site, because findings carry the sink's line. Each
-carries one `actionability` state (`plan_ready`, `advisory`, `investigate`,
-`expected`). A group every member's name or file stem marks as a migration,
-startup, shutdown or crash recovery (`perf/cold_paths.py`) is `expected` with reason
-`cold_path`, with or without a strategy; `gated_off` takes precedence. The identity
-kernel's `execution_context` stays path-only.
-The default queue holds production `plan_ready` and `advisory` with
-`cost_proof = proven`, ranked by `rank_score`; actionability only breaks ties.
-Excluded reasons are counted in `default_queue`. A cause whose loop size nothing
-measured is stored as `cost_proof = unproven`: it never leads, and the `proof`
-filter and facet expose it. Fix first, Do next and the queue's lead take only the
-queued `plan_ready` causes `queue.eligibility.perf_confident_verdict` confirms
-(facet `growth_source = loop`); advisory causes measured 0 true of 14 on three
-repositories, so they stay in the queue.
-
-**Plans.** Proven means the transformation, not the runtime: parallelizing awaits
-against a DB or network client is advisory with a `bounded_concurrency`
-prerequisite. A loop already walking chunks is `loop_already_chunked`. When
-`io_in_loop` and `serial_await_in_loop` fire on one call they name each other in
-`siblings`. Plans list their edits (`mechanical` only when proven): one step per
-call site and loop, however many markers saw it, each naming the call it repeats
-(`details.sink_call`, or the helper a cross-function path enters). A step that adds
-a bulk form to the sink comes first only when every site reaches that one sink.
-Building a buffer or a set is one edit however many lines of the loop grow the
-string or probe the list, so `buffer_string_accumulation` and
-`replace_membership_collection` list one step per loop and variable, on the loop's
-line, naming the variable (`details.subject`) where the walk could read it as a
-plain name, and effort counts those steps.
-Plans also list validation tests (coverage, call graph, import graph, then
-`via: "name-match"`). An opportunity links to a `performance_fix` refactoring
-plan only by exact `opportunity_id`.
-
-**Dataflow promotion.** `serial_await_in_loop` and `nested_loop_quadratic` are
-promoted to `dataflow_verified: true` when a def/use pass proves iterations
-independent. Promotion changes the wording, not the score.
-
-**ORM lazy loads.** `lazy_load_in_loop` (sync SQLAlchemy, Django) needs the loop's
-rows to resolve to one model through the cross-file model index and the attribute
-to be a lazy relation the query does not eager-load. Weight is read per finding
-from `details.orm` (`_PERFORMANCE_ORM_WEIGHT`): Django measured 29/32 (90.6%) on a
-held-out sample and carries 0.7; SQLAlchemy, with under 30 held-out labels, stays at
-0.4. `unbounded_read_reduced_in_memory` (Python) flags an unlimited query whose rows
-are deduplicated per key in code.
-
-**Dialects.** `perf/dialects/` registers 12 dialects over 19 language tags (TS/JS
-also serve Vue, Svelte and Astro script blocks; C# serves Razor). C shares the C++ grammar
-but has no perf dialect. A language without one emits nothing.
-
-**Soundness.** Dynamic dispatch, monkeypatching and callbacks-as-values produce no
-call edge. ORM lazy loads are seen only where the rows can be typed. Chains beyond
-three hops are not followed; an unmodelled library has no classified sinks. The
-published linter comparison and ranking quality figures are in
-[repowise-bench/perf-detection](https://github.com/repowise-dev/repowise-bench/tree/master/perf-detection).
+User guide (states, default queue, exclusions): [PERFORMANCE.md](../layers/PERFORMANCE.md).
+
+- **Sinks.** `io_in_loop` resolves a loop call through the graph's resolver against the
+ I/O lexicon (`io_boundaries.py`: db, network, filesystem, subprocess, lock): real
+ round-trips only, never a query-builder chain. Non-local sinks are found up to three
+ hops back (`crossfn.py`) with the `caller -> ... -> sink` path.
+- **Gates.** Two markers fire only at or above the 80th percentile of distinct direct
+ callers, never under two (how widely called, not request reachability).
+ `blocking_sync_in_async` skips tests, tooling, examples, generated and vendored code.
+- **Grouping.** One opportunity per intervention site per cost family and boundary
+ (`<file>::__module__` for top-level code); members are sinks, call sites and
+ same-family co-signals (`io_in_loop` with `nested_loop_with_io`), keyed by the sink's
+ line. All-cold groups (`perf/cold_paths.py`) are `expected`/`cold_path` with or without a strategy; `gated_off`
+ wins. `execution_context` stays path-only.
+- **Queue.** Ranked by `rank_score`, exclusions counted in `default_queue`. Fix first, Do
+ next and the lead take only queued `plan_ready` causes
+ `queue.eligibility.perf_confident_verdict` confirms (`growth_source = loop`); advisory
+ causes measured 0 true of 14 on three repositories.
+- **Plans.** Proven means the transformation: awaits against a DB or network client are
+ advisory with a `bounded_concurrency` prerequisite; a chunked loop is
+ `loop_already_chunked`; `io_in_loop` and `serial_await_in_loop` on one call name each
+ other in `siblings`. Edits are `mechanical` only when proven and name the call they
+ repeat (`details.sink_call`, or the entered helper). `buffer_string_accumulation` and
+ `replace_membership_collection` take one step per loop and variable (`details.subject`),
+ which effort counts. Tests come from coverage, call graph, import graph, then
+ `via: "name-match"`; a `performance_fix` plan links only by exact `opportunity_id`.
+- **Dataflow promotion.** `serial_await_in_loop` and `nested_loop_quadratic` get
+ `dataflow_verified: true` when a def/use pass proves iterations independent (wording,
+ not score).
+- **ORM lazy loads.** `lazy_load_in_loop` needs rows resolving to one model via the
+ cross-file model index and a lazy relation the query does not eager-load. Its weight
+ comes from `details.orm` (`_PERFORMANCE_ORM_WEIGHT`): Django 0.7 (29/32, 90.6% held
+ out), SQLAlchemy 0.4 (under 30 labels).
+- **Dialects.** `perf/dialects/` has 12 dialects over 19 language tags (TS/JS also cover
+ Vue, Svelte and Astro scripts; C# covers Razor); C shares the C++ grammar but has no
+ dialect, so it emits nothing.
+- **Soundness.** No call edge for dynamic dispatch, monkeypatching or callbacks-as-values;
+ ORM lazy loads are seen only where rows can be typed;
+ chains beyond three hops are not followed; an unmodelled library has no sinks.
+ Benchmarks: [repowise-bench/perf-detection](https://github.com/repowise-dev/repowise-bench/tree/master/perf-detection).
---
## 7. KPIs
-Three repo-level numbers, computed in `compute_kpis()`:
-
-- **Hotspot Health**: NLOC-weighted average over files where
- `git_meta_map[path]["is_hotspot"]` is true.
-- **Average Health**: NLOC-weighted average over all files.
-- **Worst Performer**: lowest-scoring file + its score.
-
-These flow into `HealthSnapshot` rows (rolling 50 per repo) and feed the
-CLI status one-liner, the `get_overview()` MCP block, and the dashboard
-KPI cards.
+`compute_kpis()` (§4) writes Hotspot Health, Average Health and Worst Performer into
+`HealthSnapshot` rows; they feed the status line, `get_overview()` and the dashboard cards.
---
## 8. Trends (`trends.py`)
-State-free: callers pass an oldest-first list of snapshot rows. Both alerts
-run over every metric in `_ALERT_METRICS` (hotspot health, the composite
-headline and maintainability), skipping any a snapshot never recorded:
+State-free over an oldest-first snapshot list; alerts run on each metric in
+`_ALERT_METRICS` (hotspot health, the composite headline, maintainability) a snapshot
+recorded.
-- **Declining Health**: current is ≥ `DECLINE_THRESHOLD` (default 0.5)
- below the snapshot `DECLINE_LOOKBACK` (5) positions back. Fires on the
- 6th+ snapshot.
-- **Predicted Decline**: the three most recent snapshots are each
- strictly below the one before. Magnitude is not required; direction is
- the signal.
+- **Declining Health:** ≥ `DECLINE_THRESHOLD` (0.5) below the snapshot `DECLINE_LOOKBACK`
+ (5) back, so from the 6th snapshot.
+- **Predicted Decline:** three snapshots in a row each strictly lower; direction, not
+ magnitude.
+- **`history_drag`:** either, as a third `kind`, when the headline fell with `driver`
+ `history` and the structure half held: nothing in the code to act on, so not error red.
+ Maintainability never softens.
-Either can come back as a third `kind`, **`history_drag`**: a fall on the
-composite headline where `driver` is `history` and the structure half held or
-improved. It carries the same numbers and the opposite reading, because a
-decline the code shape did not contribute to has nothing to act on and
-reporting it in error red tells a reader their refactoring made things worse.
-Maintainability is code shape already, so it has no halves to split and never
-softens; it is the fall that always deserves the alarm.
-
-`recent_kpis(history, limit=10)` returns a newest-first serialised view
-for the CLI table and MCP `get_health(include=["trend"])` response.
+`recent_kpis(history, limit=10)` is the newest-first view for the CLI and
+`get_health(include=["trend"])`.
### Per-file trajectory
-Snapshots also store a compact `{path: score}` map (`per_file_scores_json`),
-so the same window yields a single file's score-over-time series:
-
-- `file_score_series(history, path)`: oldest-first `FileTrendPoint`s,
- skipping snapshots that don't carry the file. Returns `[]` below two
- points (silent on thin history). This is the exact function the PR bot
- reuses for its in-comment sparkline.
-- `file_trend(history, path)`: wraps the series with `current` / `previous`
- / `delta` and a `declining` flag (the per-file mirror of the alerts above:
- ≥ `DECLINE_THRESHOLD` below the lookback point, or
- `PREDICTED_DECLINE_CONSECUTIVE` consecutive drops). `snapshot_count` is the
- full window size so a young repo is distinguishable from a file missing in
- older snapshots.
-
-Both are state-free; the server serialises `FileTrend` via
-`_file_trend_to_dict` and embeds it in the file-detail health block, the
-health-breakdown response, and the standalone trend route (§13).
+- `file_score_series(history, path)` reads `per_file_scores_json`: oldest-first
+ `FileTrendPoint`s, `[]` below two points. The PR bot reuses it for its sparkline.
+- `file_trend(history, path)` adds `current` / `previous` / `delta` and `declining`
+ (threshold below the lookback point, or `PREDICTED_DECLINE_CONSECUTIVE` drops);
+ `snapshot_count` tells a young repo from a file missing in older snapshots. Served via
+ `_file_trend_to_dict` in the file block, the breakdown and the trend route (§13).
#### Below the floor
-The stored score is clamped to `[SCORE_FLOOR, SCORE_MAX]`, so files 12.9 and
-9.1 points deep both persist as `1.0` and their series is flat however much of
-the work gets done. The second snapshot map (`per_file_deductions_json`) keeps
-the pre-clamp deduction for exactly those files; for every other file the
-deduction is `SCORE_MAX - score`, so there is nothing to store.
-
-Each point therefore carries `unclamped_score` alongside `score`:
-`SCORE_MAX - deduction` where the snapshot recorded one, and `score` otherwise.
-It is the series `_file_declining` runs on, so `declining` describes the line
-that can actually move, and a file getting worse *below* the floor now trips it.
-
-Snapshots written before this existed have no deduction map. Their floored
-files stay flat, which is correct; the depth was never measured, and inventing
-one would be worse than a flat line.
+Files 12.9 and 9.1 points deep both store `1.0` (`[SCORE_FLOOR, SCORE_MAX]`).
+`per_file_deductions_json` keeps the pre-clamp deduction for floored files only, and each
+point's `unclamped_score` (`SCORE_MAX - deduction`, else `score`) feeds
+`_file_declining`, so a file worsening *below* the floor trips `declining`. Snapshots
+without the map stay flat: the depth was never measured.
### Per-file signals (`signals.py`)
-The same state-free pattern, applied to the git-layer + topology fields we
-already persist but only buried inside marker detail cards (or omitted
-entirely). `file_signals(git_meta, degrees)` joins one `GitMetadata` row with
-the file's graph degree into a `FileSignals` grouped as **Process**
-(`prior_defect_count`, `change_entropy_pct` normalized 0-100, 90-day line
-churn, `age_days`), **People** (recent vs all-time owner + commit share), and
-**Topology** (`in_degree` / `out_degree`). No recompute: pure surfacing.
-
-The honesty rule mirrors the trend: a field is `None` only when its *source
-row* is absent (no git history means process/people silent; not a graph node
-means topology silent), never imputed; a genuine `prior_defect_count` of `0` is kept
-as a real signal. The server serialises it via `_file_signals_to_dict` and
-embeds it in the file-detail health block and the breakdown response (§13); MCP
-attaches a null-dropped copy to the `get_context` health block (§12). Mirrored
-as `FileSignals` in `@repowise-dev/types/health`; rendered by the shared
-`file-signals-panel.tsx` in both the drawer and the file-page Health tab.
+`file_signals(git_meta, degrees)` joins one `GitMetadata` row and the graph degree into
+`FileSignals`, no recompute: **Process** (`prior_defect_count`, `change_entropy_pct` as
+0-100, 90-day line churn, `age_days`), **People** (recent vs all-time owner and share),
+**Topology** (`in_degree` / `out_degree`). A field is `None` only when its *source row*
+is absent (never imputed; a real `0` stays). Served via `_file_signals_to_dict` (§13),
+null-dropped in `get_context` (§12), typed as `FileSignals` in
+`@repowise-dev/types/health`, drawn by `file-signals-panel.tsx`.
---
## 9. Incremental analysis: the `repowise update` path
-Full re-analysis would be wasteful on commit-sized diffs, so
-`HealthAnalyzer.analyze()` accepts a `changed_files` set. When it is present:
-duplication still runs full-repo (a changed file's clone partner may be
-unchanged); the per-file loop skips files not in `changed_files`; and the KPIs
-are **not** recomputed, since the subset would bias them. The dashboard
-recomputes KPIs from the merged DB rows instead.
-
-`update_cmd.py` builds the changed-files set from
-`change_detector.get_changed_files()`, runs the analyzer, and persists through a
-helper that uses the **upsert** variants (`upsert_health_metrics`,
-`upsert_health_findings`, scoped to the changed paths) so unchanged files keep
-their existing rows. The full-init writers (`save_health_findings`,
-`save_health_metrics`) still use delete-then-insert: simpler, and the cost is
-amortised across the whole `repowise init`.
+With `changed_files`, duplication still runs repo-wide (a clone partner may be
+unchanged), other files are skipped, and KPIs are **not** recomputed (the dashboard
+derives them from merged rows). `update_cmd/` takes the set from
+`change_detector.get_changed_files()` and **upserts** (`upsert_health_metrics`,
+`upsert_health_findings`); full init deletes and inserts (`save_health_*`).
---
## 10. Persistence schema
-Four tables, all in the repo's `.repowise/wiki.db`. Foreign-keyed to
-`repositories.id` with `ON DELETE CASCADE`.
+Four tables in `.repowise/wiki.db`, keyed to `repositories.id` with `ON DELETE CASCADE`.
### `health_findings`
-One row per marker hit. Lifecycle: `open → acknowledged | resolved |
-false_positive` (matches Dead Code). Open rows are deleted and rewritten on
-full init and per changed file on `repowise update`; a triaged row is kept and
-refreshed when its `public_id` is detected again, and `resolved` reopens.
+One row per hit; lifecycle `open → acknowledged | resolved | false_positive` (as Dead
+Code). Columns: `id` (UUID), `repository_id`, `file_path` (indexed), `biomarker_type`,
+`severity`, nullable `function_name` / `line_start` / `line_end`, `details_json`,
+`health_impact`, `reason`, `status`, `created_at`, `updated_at`. Open rows are rewritten
+on init and per changed file on update.
-| Column | Notes |
-|---|---|
-| `id` | UUID PK |
-| `repository_id` | FK |
-| `file_path` | indexed |
-| `biomarker_type` | `brain_method`, `nested_complexity`, ... |
-| `severity` | `low` / `medium` / `high` / `critical` |
-| `function_name` | nullable for file-level findings |
-| `line_start`, `line_end` | nullable |
-| `details_json` | per-marker evidence (CCN values, clone span, etc.) |
-| `health_impact` | per-finding scaled deduction |
-| `reason` | one-line summary string |
-| `status` | lifecycle |
-| `created_at`, `updated_at` | datetime |
-
-**Identity and triage** (`finding_identity.py`). The public id
-(`finding_<digest>`) is anchored on the enclosing function or class name plus
-the finding's line offset into it, so an edit above the symbol keeps the id; a
-file-level finding keeps absolute lines. Metric values are not part of the id;
-only the detail keys a marker needs to tell two findings apart (a coupling
-partner, an error kind) are. Each index replaces open findings, and a re-detected
-finding matching a triaged row updates that row's evidence in place:
-`acknowledged` and `false_positive` stay, `resolved` reopens.
+**Identity** (`finding_identity.py`): `finding_<digest>` from the enclosing function or
+class plus the line offset (absolute lines at file level), so edits above keep it; only
+detail keys that tell findings apart (a coupling partner, an error kind) count, never
+metric values. A re-detected triaged row gets fresh evidence: `acknowledged` and
+`false_positive` stay, `resolved` reopens.
### `health_file_metrics`
-One row per file (unique on `(repository_id, file_path)`). Read directly
-by the dashboard's file table.
-
-| Column | Notes |
-|---|---|
-| `score` | 1.0–10.0 final |
-| `defect_score`, `maintainability_score`, `performance_score` | per-pillar; nullable |
-| `structure_deduction`, `history_deduction` | the two halves of the total deduction; nullable on rows written before the split. `counts=code_shape` rescores from `structure_deduction` alone, and a null pair is reported as unscored rather than counted as a ten |
-| `is_test` | stored, not re-derived per surface, so `scope` is one row filter everywhere; nullable on rows predating the column |
-| `max_ccn`, `max_nesting`, `nloc` | aggregate function metrics |
-| `duplication_pct` | percent of NLOC covered by clones; nullable |
-| `has_test_file` | paired or heuristic |
-| `line_coverage_pct`, `branch_coverage_pct` | nullable |
-| `module` | community label from graph; falls back to top-level dir |
-| `updated_at` | datetime |
+One row per `(repository_id, file_path)`: `score`; nullable `defect_score`,
+`maintainability_score`, `performance_score`; `structure_deduction` and
+`history_deduction` (null on rows before the split, reported unscored under
+`counts=code_shape`, never a ten); `is_test` (so `scope` is one row filter); `max_ccn`,
+`max_nesting`, `nloc`; nullable `duplication_pct`; `has_test_file`; nullable
+`line_coverage_pct`, `branch_coverage_pct`; `module` (community label, else top-level
+dir); `updated_at`.
-### `health_snapshots`
+### `health_snapshots` and `coverage_files`
-KPI + per-file score history. Rolling delete on insert keeps the latest
-50 per repo (`HEALTH_SNAPSHOT_RETENTION` in `crud.py`).
-
-### `coverage_files`
-
-Per-file coverage, overwritten on every `coverage add` run. Carries the
-explicit `covered_lines_json` array so the `coverage_gap` marker can
-flag the exact uncovered surface, not just the percent.
+Snapshots keep the latest 50 per repo (`HEALTH_SNAPSHOT_RETENTION`,
+`crud/analysis/health/snapshots.py`). `coverage_files` is overwritten per `coverage add`;
+its `covered_lines_json` lets `coverage_gap` name the exact uncovered surface.
---
## 11. CLI surface
-`packages/cli/src/repowise/cli/commands/health_cmd/`. Mirrors the
-dead-code command's Click structure.
+`commands/health_cmd/` mirrors the dead-code command's Click structure; every flag is in
+[CLI_REFERENCE.md](../reference/CLI_REFERENCE.md#repowise-health-path).
```bash
-repowise health # KPIs + lowest-scoring files + findings
-repowise health --file path/to/x.py # deep-dive one file
-repowise health --module packages/server # restrict to a directory prefix
-repowise health --refactoring-targets # ranked by impact / effort
-repowise health --trend # last 10 snapshots + active alerts
-repowise coverage add coverage.lcov # ingest coverage; can repeat
+repowise health --file path/to/x.py # one file; --module, --refactoring-targets, --trend
repowise coverage add coverage.xml --format cobertura
-repowise coverage check --fail-under 80 # patch-coverage gate for CI, no index needed
-repowise health --format json | jq ...
-```
-
-`repowise status` queries the same tables for a one-line summary:
-
-```
-Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: packages/server/.../app.py)
+repowise status # Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: ...)
```
-`repowise update` is unchanged from the user's perspective: health is
-silently re-scored for changed files only.
+`repowise update` silently re-scores changed files only.
---
@@ -1040,271 +653,150 @@ silently re-scored for changed files only.
### `get_health(targets?, include?, repo?, limit?)`
-Defined in `tool_health/tool.py`, which dispatches to one module per mode and block. Modes:
-
-- **Dashboard mode** (`targets=None`): returns repo-level KPIs (with the
- repo `band`) + the NLOC-weighted `distribution` across the bands +
- `worst_files` (top N lowest-scoring) + `top_findings` + a per-module
- `modules` rollup.
-- **Targeted mode** (`targets=[...]`): returns full `metrics` +
- `findings` for the listed paths, plus a per-file `trends` block (compact
- score series + `current` + `delta` + `declining`) for any target with at
- least two snapshots of history. Targets prefixed `module:foo` expand to
- the file set in that module.
+`tool_health/tool.py` dispatches per mode and block.
-`include` flags layer richer data:
-
-| Flag | Adds |
-|---|---|
-| `"biomarkers"` | full findings list (already present in target mode) |
-| `"coverage"` | per-file coverage rows + summary |
-| `"refactoring"` | deterministic `suggestion` text on every finding |
-| `"trend"` | snapshot diff + alerts + last 10 KPI rows |
-| `"accuracy"` | the in-product defect-accuracy block (§6.2) |
-| `"performance"` | performance opportunities (§6.4) |
-| `"signals"`, `"churn_complexity"`, `"doc_drift"` | per-file signals, churn x complexity points, drift |
-| `"defect"`, `"maintainability"`, `"advisory"` | dimensions for the ranked findings list (default: defect + maintainability) |
-| `"unverified"`, `"semantics"` | provisional finding types (labelled), and the shared points/percentile legend |
-
-`request.py::_KNOWN_INCLUDES` is the authority.
+- **Dashboard** (`targets=None`): KPIs with `band`, `distribution`, `worst_files`,
+ `top_findings`, `modules`.
+- **Targeted**: full `metrics` + `findings` and a `trends` block for targets with two or
+ more snapshots; `module:foo` expands to that module.
+- `include` adds blocks and picks the ranked-list dimensions (`defect`,
+ `maintainability`, `advisory`; default defect + maintainability). Flags:
+ [MCP_TOOLS.md](../agent/MCP_TOOLS.md#get_health);
+ `request.py::_KNOWN_INCLUDES` is the authority (add one in `request.py`, `loading.py`,
+ `blocks.py`).
### Enrichments on existing tools
-- `get_risk(targets)`: each per-target row carries `health_score`,
- `top_biomarkers`, `line_coverage_pct`, `branch_coverage_pct`.
-- `get_context(targets, include=["health"])`: per-file `score`,
- `max_ccn`, `max_nesting`, `nloc`, `module`, `duplication_pct`, top
- 2 markers (each with a `suggestion` string), a coverage block, and a
- null-dropped `signals` block (process/people/topology, see §8).
-- `get_overview()`: adds a `code_health` block: avg, repo `band`, hotspot,
- worst performer, open finding count, and the file count per band.
-
-Every response carries the standard `_meta` envelope via `build_meta()`.
+`get_risk(targets)`: `health_score`, `top_biomarkers`, `line_coverage_pct`,
+`branch_coverage_pct`. `get_context(include=["health"])`: `score`, `max_ccn`,
+`max_nesting`, `nloc`, `module`, `duplication_pct`, top 2 markers with a `suggestion`,
+coverage and `signals`. `get_overview()`: `code_health` with avg, `band`, hotspot, worst,
+open finding count and files per band. All carry `_meta` via `build_meta()`.
---
## 13. REST surface
-`packages/server/src/repowise/server/routers/code_health/`: a package, one
-module per surface, sharing `scope.py`, `counts.py`, `file_filters.py` and
-`statuses.py`. All routes under `/api/repos/{repo_id}/health/`:
+`server/.../routers/code_health/`: one module per surface sharing `scope.py`, `counts.py`,
+`file_filters.py`, `statuses.py`; routes under `/api/repos/{repo_id}/health/`, auth by
+`verify_api_key` (`server/deps.py`) at the router.
| Route | Returns |
|---|---|
-| `GET /overview` | summary (with repo `band`) + `distribution` + lowest-scoring files + top findings + module rollup |
-| `GET /badge.svg` | self-rendered flat SVG health badge (color + `N.N/10`, no letter) |
-| `GET /badge.json` | Shields.io endpoint-badge payload (`schemaVersion`/`label`/`message`/`color`/`band`) |
-| `GET /files` | per-file metrics |
-| `GET /files/breakdown` | one file's metric + score breakdown + findings + suggestions + per-file `trend` + `signals` |
-| `GET /files/trend` | one file's score-over-time series + current delta + `declining` flag (`?file_path=`) |
-| `GET /trend` | repo KPI history + alerts + last-two-snapshot per-file deltas |
-| `GET /findings` | findings list, filterable by `biomarker_type`, `file_path`, `dimension`, `status` and severity (`severity` exact, or the `min_severity` floor). The zero-impact dimensions, performance and advisory, are out of the ranked list: name one in `dimension`, name a marker in `biomarker_type`, or pass `include_zero_impact=true` |
-| `GET /coverage` | coverage summary + per-file rows |
-| `POST /coverage` | ingest a coverage report (used by some CI integrations) |
-| `GET /refactoring-targets` | the work queue: files carrying findings, ranked by `total_impact / effort_bucket`. Takes the findings filters plus `search`, `module` and the `only_hotspots` / `only_untested` / `only_failing` row filters, pages by `limit` + `offset`, and returns `total` with `finding_total` beside it. Impact counts open findings only, so dismissing work moves a file down |
-| `GET /churn-complexity` | churn × complexity scatter points (one per churned file: `commit_count_90d`, `max_ccn`, `nloc`, `score`, `churn_percentile`) |
-| `GET /modules` | NLOC-weighted module rollup table |
-
-`scope` and `counts` are accepted by every route whose figures they could
-change, parsed by the shared `ScopeQuery` / `CountsQuery`, and echoed back. An
-unrecognized value falls back to the default rather than answering a different
-question under the name that was asked for.
-
-`counts=code_shape` is a projection over the two stored deduction columns, not
-a rescore: it re-derives each score from `structure_deduction`, drops
-history-derived findings from the row sets so a list cannot sum past the figure
-above it, and recomputes `total` and every ranking afterwards. Rows with no
-stored split are removed and counted in `unscored_files`. Nothing is written
-back.
-
-Auth is the standard `verify_api_key` dependency from
-`server/deps.py`.
+| `overview` | summary with `band`, `distribution`, worst files, top findings, modules |
+| `badge.svg`, `badge.json` | flat SVG (`N.N/10`, no letter); Shields.io payload (`schemaVersion`/`label`/`message`/`color`/`band`) |
+| `files`, `files/breakdown`, `files/trend` | per-file metrics; one file's breakdown, suggestions, `trend`, `signals`; one file's series (`?file_path=`) |
+| `trend` | KPI history, alerts, last-two-snapshot per-file deltas |
+| `findings` | filter by `biomarker_type`, `file_path`, `dimension`, `status`, `severity` or `min_severity`; performance and advisory only when named or `include_zero_impact=true` |
+| `coverage` (GET, POST) | summary and rows; ingest a report |
+| `refactoring-targets` | queue by `total_impact / effort_bucket` (open findings only); findings filters plus `search`, `module`, `only_hotspots` / `only_untested` / `only_failing`, `limit` + `offset`, `total` and `finding_total` |
+| `churn-complexity`, `modules` | `commit_count_90d`, `max_ccn`, `nloc`, `score`, `churn_percentile` per churned file; NLOC-weighted rollup |
+| Also | `fix-first` (and `/{fix_id}`), `map`, `impact-effort`, `related-work`, `tests-reaching`, `performance-opportunities` (and `/{opportunity_id}`, `/findings`), `coverage/patch`, `findings/{id}` |
+
+`ScopeQuery` / `CountsQuery` parse `scope` and `counts` wherever they change a figure and
+echo them; an unknown value falls back to the default. `counts=code_shape` projects from
+`structure_deduction`, drops history-derived findings, recomputes totals and rankings,
+counts split-less rows in `unscored_files`, and writes nothing.
---
## 14. Web dashboard
-One page, `packages/web/src/app/repos/[id]/code-health/page.tsx`, with a map whose
-lens switches between health, maintainability, performance and churn, and tabs
-selected by `?tab=`: Overview (`triage`, leads with Fix first), Performance,
-Findings, Tests (`coverage`), Dead code, Doc drift, Security and Blast radius
-(`impact`). `scope` and `counts` controls sit above the tabs. The older
-`/repos/[id]/health/*` routes are redirects into this page;
-`code-health/refactoring-targets` and `code-health/trend` remain as sub-pages.
-
-The churn lens is paired with `ChurnComplexityQuadrant` (fed by
-`GET /churn-complexity`); the file Health tab carries the per-function
-"Functions by churn" blame table.
-
-All visual primitives live in `packages/ui/src/health/` so the hosted
-`frontend/` repo (separate git checkout) can reuse them: port is mostly
-data fetching + auth.
+`packages/web/src/app/repos/[id]/code-health/page.tsx`: a map whose lens shows health,
+maintainability, performance or churn (paired with `ChurnComplexityQuadrant` from
+`churn-complexity`), `scope` and `counts` controls, and four tabs by `?tab=` (`tabs.ts`): Map
+(default, leads with Fix first; `triage`, `heatmap`, `hotspots`, `modules`, `trend` alias
+to it), Findings, Performance, Dead code. Tests and Security are pages, Doc drift a Docs
+view and blast radius the Commits page's "Review a change"; old tab ids (`coverage`,
+`security`, `doc-drift`, `impact`) and `/repos/[id]/health/*` redirect. Sub-pages:
+`coverage`, `refactoring-targets`, `trend`. The file Health tab has the "Functions by
+churn" table. Primitives in `packages/ui/src/health/` let the hosted `frontend/` repo
+reuse them.
---
## 15. CLAUDE.md integration
-The auto-generated `CLAUDE.md` includes a `## Code health` section when
-the health tables are populated. The block is intentionally short;
-filter rules in `core/generation/editor_files/data.py`:
-
-- Score ≤ 5.0 **and** file is a hotspot
-- Any Brain Method in a file with > 10 dependents
-- Any Untested Hotspot
-- DRY violations > 70 % similarity
-- Declining trend (> 1.0 drop in last 5 snapshots)
-
-Everything else is filtered out so the CLAUDE.md doesn't drown a fresh
-agent in noise. The Jinja stanza lives in
-`core/generation/templates/_editor_block.j2`.
+The generated `CLAUDE.md` gets a short `## Code health` section
+(`core/generation/editor_files/data.py`, `templates/_editor_block.j2`) keeping only:
+score ≤ 5.0 on a hotspot, a Brain Method with > 10 dependents, any Untested Hotspot, DRY
+violations > 70 % similar, a > 1.0 drop over 5 snapshots.
---
## 16. Configuration: `.repowise/health-rules.json`
-`.repowise/health-rules.json` is user-authored (the **only** JSON file in the
-layer) and is loaded by `HealthConfig.load(repo_path)`. It carries repo-wide and
-per-path `disabled_biomarkers` and `severity_overrides`, keyed by a
-gitignore-semantics glob over the repo-relative POSIX path (every matching rule
-applies; disabled sets union) (`path`, with `path_glob` and `glob` as
-accepted aliases). `to_analyzer_config(file_paths)` resolves the globs to
-per-file disabled sets, which the engine honors in `FileEvaluator.evaluate()`. The
-schema and examples are in the
+User-authored (the layer's **only** JSON file), loaded by `HealthConfig.load`; globs use
+`path` (aliases `path_glob`, `glob`) over repo-relative POSIX paths, every match applies
+and disabled sets union; `to_analyzer_config()` feeds `FileEvaluator.evaluate()`. Schema:
[user guide](../layers/CODE_HEALTH.md#configuration).
---
## 17. Performance
-The budget is **< 30 s on a 3,000-file synthetic repo**. The
-parallel path in `HealthAnalyzer.analyze_async()` parallelises tree-sitter
-parsing across worker threads (`asyncio.gather` + `asyncio.to_thread`).
-tree-sitter releases the GIL on parse, so this scales on single-process
-CPython.
-
-The orchestrator chooses the parallel path automatically when
-`len(parsed_files) >= 500`. The benchmark lives at
-`tests/integration/test_health_perf_benchmark.py` and is marked `slow`
-(opt-in via `pytest -m slow` or `make health-bench`).
-
-Other perf notes:
-
-- **Duplication is O(total_tokens).** Bucket walk is near-linear on
- repos with low duplication.
-- **Walker re-parses files** because `ParsedFile` doesn't retain a
- tree-sitter `Tree` across the ingestion boundary. Acceptable (~1 ms
- per file); a shared parse cache would remove it.
-- **No N² loops in scoring.** Category aggregation is O(findings).
+Budget **< 30 s on a 3,000-file synthetic repo** (`test_health_perf_benchmark.py`,
+`-m slow` or `make health-bench`). `analyze_async()` uses `asyncio.gather` +
+`asyncio.to_thread`. Duplication is O(total_tokens); scoring is O(findings); the walker
+re-parses (~1 ms per file) because `ParsedFile` keeps no tree-sitter `Tree`, which a
+shared parse cache would remove.
---
## 18. Testing
-| Suite | What it locks |
-|---|---|
-| `tests/unit/health/test_complexity_walker.py` | Per-language CCN, nesting, cognitive assertions on handcrafted fixtures |
-| `tests/unit/health/test_<biomarker>.py` | Each marker: positive in two languages + one negative |
-| `tests/unit/health/test_duplication.py` | Tokenizer normalization, rolling-hash determinism, co-change weighting |
-| `tests/unit/health/test_coverage_parsers.py` | LCOV / Cobertura / Clover / JaCoCo / Go coverprofile / repowise-JSON happy paths + edge cases |
-| `tests/unit/health/test_scoring.py` | Deduction caps, clamping, KPI math |
-| `tests/unit/health/test_scoring_snapshot.py` | **Stability guard**: caps, severity table, marker-to-category mapping, two known fixture scores |
-| `tests/unit/health/test_trends.py` | Declining + predicted alerts, ordering, per-file series + `file_trend` |
-| `tests/unit/health/test_signals.py` | `file_signals` join: no-signal vs real-zero, entropy 0-1 to 0-100, owner handoff |
-| `tests/unit/health/test_churn_complexity.py` | `churn_complexity_points`: no-churn omission, complexity never filters, danger-product sort, percentile scaling |
-| `tests/unit/health/test_suggestions.py` | Suggestion strings keyed correctly |
-| `tests/unit/health/test_health_config.py` | `.repowise/health-rules.json` parsing + glob matching |
-| `tests/integration/test_health_coverage_integration.py` | End-to-end LCOV -> analyzer -> coverage_gap fires |
-| `tests/integration/test_health_perf_benchmark.py` | 30 s budget on 3,000 synthetic files (`-m slow`) |
-
-99 unit tests + 2 integration tests at time of writing. Run with
-`make health-check`.
+`make health-check` runs `tests/unit/health/`, `tests/unit/server/test_mcp.py` and a
+health report. Key suites: `test_complexity_walker.py` (per-language CCN, nesting,
+cognitive); `test_<biomarker>.py` with `test_biomarkers.py`, `test_structural_biomarkers.py`,
+`test_coverage_biomarkers.py`, `test_organizational_biomarkers.py`,
+`test_dry_violation.py` (two languages positive, one negative); `test_duplication.py`;
+`test_coverage_parsers.py`; `test_scoring.py`; `test_scoring_snapshot.py` (the
+**stability guard**); `test_scoring_dimensions.py`; `test_trends.py`; `test_signals.py`
+(no-signal vs real zero, entropy 0-1 to 0-100, owner handoff); `test_churn_complexity.py`
+(no-churn omission, danger-product sort, percentile scaling); `test_suggestions.py`;
+`test_health_config.py`. Integration: `test_health_coverage_integration.py` (LCOV ->
+`coverage_gap`) and the perf benchmark.
---
## 19. Extension points
-### Add a marker
-
-1. New file under `biomarkers/` implementing the `Biomarker` Protocol.
-2. Append to `_DETECTOR_FACTORIES` in `biomarkers/registry.py`.
-3. Add the marker-to-category mapping in
- `scoring._BIOMARKER_CATEGORY`.
-4. Add a suggestion template in `suggestions._TEMPLATES`.
-5. Add at least three test cases (two positive in different languages,
- one negative).
-6. Update `biomarkers/README.md`'s "Registered v1 detectors" list.
-
-### Add a language to the complexity walker
-
-Add one `LanguageNodeMap` entry to `complexity/languages.py` mapping the
-language's tree-sitter control-flow node-type names to abstract `BRANCH`
-/ `LOOP` / `TRY` / `BOOLEAN_OP` categories. Add a fixture under
-`tests/fixtures/lang_samples/<lang>/`. **No `.scm` files needed**: those
-are owned by the ingestion parser.
-
-### Add a coverage format
-
-Drop a parser under `coverage/` returning a `CoverageReport`. Route to it
-from `coverage/detector.parse`. Stdlib-only (no extra XML libraries).
-
-### Add a per-file override
-
-Users (not contributors) author `.repowise/health-rules.json`. To add
-a new override key (beyond `disabled_biomarkers`), extend
-`HealthConfig` and thread it through `to_analyzer_config()` ->
-`FileEvaluator.evaluate()` in `file_evaluator.py`.
+- **Marker:**
+ 1. `biomarkers/<id>.py` implementing `Biomarker`.
+ 2. Append to `_DETECTOR_FACTORIES` (`registry.py`).
+ 3. List in `scoring._BIOMARKER_DIMENSIONS` (unlisted defaults into defect).
+ 4. Add to its tables: `_BIOMARKER_CATEGORY` / `_BIOMARKER_WEIGHT_MULTIPLIER`, `_MAINTAINABILITY_*`, `_PERFORMANCE_WEIGHT_MULTIPLIER`, or `_ADVISORY_HOME`.
+ 5. A label in `BIOMARKER_LABELS` and a template in `suggestions._TEMPLATES`.
+ 6. Three tests: two languages positive, one negative.
+ 7. A row in [the full roster](#the-full-roster) and `biomarkers/README.md`.
+- **Walker language:** one `LanguageNodeMap` in `complexity/languages.py` mapping node
+ types to `BRANCH` / `LOOP` / `TRY` / `BOOLEAN_OP`, plus a fixture in
+ `tests/fixtures/lang_samples/<lang>/`; no `.scm` files.
+- **Coverage format:** a stdlib-only parser in `coverage/` returning a `CoverageReport`,
+ routed from `coverage/detector.parse`.
+- **Rules key:** extend `HealthConfig` through `to_analyzer_config()` to
+ `FileEvaluator.evaluate()`.
+- **Retune:** `scoring.CATEGORY_CAPS` / `_SEVERITY_DEDUCTION` (update the snapshot);
+ alerts in `trends.DECLINE_THRESHOLD` / `DECLINE_LOOKBACK`; a new entry point calls
+ `HealthAnalyzer.analyze()` and upserts when incremental.
---
## 20. Where the layer deliberately stops
-Things the layer **does not** do, by design.
-
-- **No LLM in scoring or suggestions.** `suggestions.py` is static
- templates. LLM code generation exists only behind the explicit
- `--generate-code` flag and the opt-in `generate_refactoring_code` MCP tool,
- and never feeds a score.
-- **No symbol-level scoring.** Score lives at the file granularity to
- match how engineers think about refactor units. Symbol-level CCN
- still feeds the file score via `all_functions`.
-- **No `complexity_estimate` propagation backfill.** The walker writes
- the field as a side effect during the current run; old indexes don't
- get touched until a re-index.
-- **No predictive ML on trends.** `Predicted Decline` is a 3-snapshot
- direction check, not a model. (Commit-level change risk is a separate,
- shipped surface: the `analysis/change_risk/` package behind
- `repowise risk` scores a commit or base..head range with a calibrated
- logistic model.)
-- **No letter grade.** The 1–10 score is the single number. The only
- categorical layer is the five absolute bands (Excellent / Good / Fair /
- Needs work / At risk, `grading.py`); a letter on top would be a third
- overlapping scale with arbitrary cliffs. Every surface that shows a band
- word or a band colour reads that one vocabulary; there is no second
- ramp.
-
----
-
-## 21. Quick lookup: where do I edit X?
-
-| I want to... | Edit... |
-|---|---|
-| Tweak a category cap | `scoring.CATEGORY_CAPS` (snapshot test will fail; update it) |
-| Tweak a severity deduction | `scoring._SEVERITY_DEDUCTION` (ditto) |
-| Add a new marker | `biomarkers/*.py`, `registry.py`, `scoring.py`, `suggestions.py` |
-| Change the suggestion text for a marker | `suggestions._TEMPLATES` |
-| Adjust the trend-alert threshold | `trends.DECLINE_THRESHOLD` / `DECLINE_LOOKBACK` |
-| Change snapshot retention | `crud.HEALTH_SNAPSHOT_RETENTION` |
-| Add a new MCP `include` flag | `tool_health/`: name it in `request.py`, read it in `loading.py`, render it in `blocks.py` beside the existing `"coverage"` / `"refactoring"` blocks |
-| Add a new REST route | `routers/code_health.py`: auth is wired at the router level |
-| Add a new dashboard view | new file under `packages/web/src/app/repos/[id]/health/`, primitives under `packages/ui/src/health/` |
-| Add a CLI flag | `packages/cli/src/repowise/cli/commands/health_cmd/` |
-| Wire the analyzer into a new entry point | call `HealthAnalyzer.analyze()` directly; persist via the upsert variants if your caller is incremental |
+- **No LLM in scoring or suggestions**: `suggestions.py` is templates; code generation
+ only behind `--generate-code` and the opt-in `generate_refactoring_code` tool.
+- **No symbol-level score**: files are the refactor unit; symbol CCN feeds it via
+ `all_functions`.
+- **No `complexity_estimate` backfill** until a re-index.
+- **No predictive ML on trends**; commit-level risk is `analysis/change_risk/`
+ (`repowise risk`, a calibrated logistic model).
+- **No letter grade**: the 1–10 score and the five bands (`grading.py`) are the only
+ scales, and every band word or colour reads that vocabulary.
---
## See also
-- [`docs/layers/CODE_HEALTH.md`](../layers/CODE_HEALTH.md): user-facing guide.
-- [`packages/core/src/repowise/core/analysis/health/README.md`](../../packages/core/src/repowise/core/analysis/health/README.md): developer overview at the layer root.
-- Sub-package READMEs under `complexity/`, `coverage/`, `duplication/`, `biomarkers/`.
+- [`packages/core/src/repowise/core/analysis/health/README.md`](../../packages/core/src/repowise/core/analysis/health/README.md) and the `complexity/`, `coverage/`, `duplication/`, `biomarkers/` READMEs.
- [`docs/architecture/graph-algorithms.md`](graph-algorithms.md): the graph layer health depends on.
diff --git a/docs/architecture/test-intelligence.md b/docs/architecture/test-intelligence.md
index eba0c7b21..0daad1102 100644
--- a/docs/architecture/test-intelligence.md
+++ b/docs/architecture/test-intelligence.md
@@ -1,23 +1,20 @@
# Test intelligence: the inferred tier
-How repowise answers "which tests reach this file" and "which tests should I
-run" with no coverage report. For the user-facing layer, see
-[layers/TEST_INTELLIGENCE.md](../layers/TEST_INTELLIGENCE.md).
+How repowise answers "which tests reach this file" and "which tests should I run" with
+no coverage report. User guide: [layers/TEST_INTELLIGENCE.md](../layers/TEST_INTELLIGENCE.md).
-Code: `packages/core/src/repowise/core/analysis/test_reach/` (the walks), `analysis/test_selection.py` (runner arguments for `impacted-tests`),
-`analysis/health/coverage/` (report parsers, discovery, path matching) and
+Code: `packages/core/src/repowise/core/analysis/test_reach/` (the walks),
+`analysis/test_selection.py` (runner arguments for `impacted-tests`),
+`analysis/health/coverage/` (parsers, discovery, path matching) and
`persistence/crud/analysis/coverage_map.py` (the measured per-test map).
## Why a graph signal
-The measured map (`test_coverage`) is filled only by a coverage report. Most
-repositories never ingest one, so without a second signal `tests_to_run` would
-be empty, `impacted_tests` would say "run the full suite", and `untested_hotspot`
-would fall back to matching filenames.
-
-Filename matching fails both ways. On this repository, five of the six worst
-bug-magnet files have no test named for them, while the graph names the tests
-that reach them:
+Only a coverage report fills the measured map (`test_coverage`), and most repositories
+never ingest one; without a second signal `tests_to_run` would be empty,
+`impacted_tests` would say "run the full suite", and `untested_hotspot` would match
+filenames. Filename matching fails both ways: five of this repository's six worst
+bug-magnet files have no test named for them, while the graph finds the tests:
| File | Filename convention | Graph |
|---|---|---|
@@ -26,26 +23,17 @@ that reach them:
| `pipeline/persist.py` | nothing | 23 |
| `mcp_server/tool_answer/answer.py` | nothing | 18 |
| `analysis/pr_blast.py` | nothing | 3 |
-| `analysis/health/engine.py` | `tests/unit/distill/test_engine.py` | 6, all under `tests/unit/health/` |
-
-The last row is the worse failure: a basename match paired the health engine
-with the distill engine's tests.
+| `analysis/health/engine.py` | `tests/unit/distill/test_engine.py` (the distill engine's tests) | 6, all under `tests/unit/health/` |
## Two graphs, two directions
-The **call graph** leads: seed the symbols a test file declares, walk
-`EXECUTION_EDGE_TYPES` forward, and every symbol reached is one the test can
-run. `EXECUTION_EDGE_TYPES` (in `ingestion/models.py`) is
-`SYMBOL_USE_EDGE_TYPES` minus `references`, because a name sitting in a
-dispatch table is a mention, not a transfer of control. Dead code asks "is this
-used", which a mention answers; this asks "is this run".
-
-The **import graph** is the weaker tier: importing a module pulls in every
-symbol it defines while the test may touch one function.
-
-Measured against real per-test coverage on this repository, over
-the slice where per-test attribution is complete, both sides seeing the same
-37 test files and 159 provably executed production files.
+The **call graph** leads: seed a test file's symbols and walk `EXECUTION_EDGE_TYPES`
+(`ingestion/models.py`: `SYMBOL_USE_EDGE_TYPES` minus `references`, since a name in a
+dispatch table is a mention, not a transfer of control; dead code asks "is this used",
+this asks "is this run"). The **import graph** is weaker: an import pulls in every
+symbol while the test may touch one. Measured against real per-test coverage on this
+repository, over the slice with complete attribution (37 test files, 159 provably
+executed production files):
**Forward, "what reaches this file"** (suppresses `untested_hotspot`):
@@ -65,41 +53,34 @@ the slice where per-test attribution is complete, both sides seeing the same
| Both unioned | 47 | 100.0% | 95.8% |
| **Call graph, else import graph** (ships) | 47 | **100.0%** | **97.5%** |
-The tiers combine differently per direction. Unioning costs the forward walk
-16.8 points of precision for 0.6 of recall, and a false "something reaches
-this" hides a real gap, so forward is call edges only. Reverse falls back: the
-import tier is spent only on targets the call graph left silent, which answers
-one more target at identical precision.
-
-Both tables compare signals uncapped over the same test set. End to end, with
-the walk seeing the whole test set and `MAX_TESTS_PER_TARGET` applied, the
-reverse walk scores 100.0% hit and 95.5% precision on the same slice; the gap
-is the cap truncating a long list.
+- **Forward is call edges only:** unioning costs 16.8 points of precision for 0.6 of
+ recall, and a false "something reaches this" hides a real gap.
+- **Reverse falls back:** the import tier answers only targets the call graph left
+ silent, one more target at identical precision.
+- The tables are uncapped. End to end, with `MAX_TESTS_PER_TARGET` truncating long
+ lists, the reverse walk scores 100.0% hit and 95.5% precision on the slice.
## Depth
-`DEFAULT_CALL_DEPTH = 3`: 3, 4 and 5 hops return the same 48 claims and 44
-confirmations, so the recall ceiling is the call graph's capture rate, not the
-depth. `DEFAULT_MAX_DEPTH = 1` for imports: a blanket second hop recovered 20
-of 128 misses while adding 50 wrong claims; a facade-only second hop through
-`__init__.py` (3 recovered, 5 added) and `conftest.py` transitivity (none
-recovered) were also tested and rejected.
+`DEFAULT_CALL_DEPTH = 3`: 3, 4 and 5 hops give the same 48 claims and 44 confirmations,
+so recall is capped by the call graph's capture rate, not depth. `DEFAULT_MAX_DEPTH = 1`
+for imports: a blanket second hop recovered 20 of 128 misses but added 50 wrong claims;
+a facade-only hop through `__init__.py` (3 recovered, 5 added) and `conftest.py`
+transitivity (none recovered) were rejected too.
## The resolution-origin filter
-"Filtered" drops call edges whose `resolution_origin` is `global_unique`: a
-name bound to the only symbol carrying it anywhere in the repository, which the
-origin vocabulary itself scores at 0.50. Dropping it costs no recall and buys
-4.0 points of forward precision (91.7% to 95.7%) and 1.1 of reverse (96.4% to
-97.5%). Filtering `receiver_global` too changes no number. A confidence floor
-of 0.90 was tried instead and cut recall from 27.7% to 23.3%.
+"Filtered" drops call edges whose `resolution_origin` is `global_unique` (a name bound to
+the only symbol carrying it in the repository, scored 0.50 by the origin vocabulary). It
+costs no recall and buys 4.0 points of forward precision (91.7% to 95.7%) and 1.1 of
+reverse (96.4% to 97.5%). Also filtering `receiver_global` changes nothing; a 0.90
+confidence floor instead cut recall from 27.7% to 23.3%.
## Why recall reads low
-Coverage records a line as run whether a test called into it or Python merely
-evaluated the module body on import, so the truth set cannot tell an imported
-file from an exercised one. Splitting the 159 truth files by how much of what
-ran was inside a function body:
+Coverage marks a line run whether a test called it or Python evaluated the module body on
+import, so the truth set cannot tell an imported file from an exercised one. The 159
+truth files by how much of what ran was inside function bodies:
| What ran inside function bodies | Files | Recall |
|---|---:|---:|
@@ -108,64 +89,62 @@ ran was inside a function body:
| A quarter to three quarters | 45 | 7% |
| Over three quarters | 56 | 77% |
-Of the 13 missed in the last group, 11 are alembic migrations the framework
-invokes by naming convention with no static caller.
+Of the 13 missed in the last group, 11 are alembic migrations the framework invokes by
+naming convention with no static caller. Repo-wide figures:
+[Accuracy and limits](../layers/TEST_INTELLIGENCE.md#accuracy-and-limits).
## Nothing is stored
-The inferred map is read from `graph_edges` when asked and never written to
-`test_coverage`:
+The inferred map is read from `graph_edges` on demand, never written to `test_coverage`:
+a shared table behind a marker column would leak inferred rows to any reader that forgot
+the marker, and the tests x sources closure would go stale whenever the graph moves, to
+answer a bounded breadth-first search over rows already stored. The health pass computes
+the whole-repo answer in one multi-source walk per run and caches it; the per-change walk
+reads the edge table `pr_blast` reads.
-1. **A consumer cannot mistake it for measured data.** Sharing the table behind
- a marker column would make every existing reader start returning inferred
- rows the day someone forgot to check the marker.
-2. **It would be a transitive closure.** Tests reach most production files;
- materialising that is tests x sources rows that go stale whenever the graph
- moves, to answer a bounded breadth-first search over rows already in the
- database.
+## One walk, two graph sources
-The health pass computes the whole-repo answer in one multi-source walk, once
-per run, and caches it. The per-change walk reads the same edge table
-`pr_blast` reads.
+The reverse walks are written once and run over the stored graph or an in-memory one
+(`build_walk_maps` on the NetworkX graph or its node-link JSON), with the same rows.
-## One walk, two graph sources
+### Reach states
-The reverse walks are written once and run over the stored graph or over a
-graph held in memory (`build_walk_maps` on the NetworkX graph or its node-link
-JSON), and both return the same rows. `reach_states` gives each file a typed
-state: `reached`, `unreached`, `new`, `no_signal`, `type_only` or
-`mocked_only`. A file is
-`unreached` only when the call walk, the helper and barrel hop and the whole
-import closure all miss it, and a test the change adds or edits that is named
-for the file or imports it, or the file's own inline tests (Rust
-`#[cfg(test)]`, a Go `_test.go` beside it), count as reaching it.
-
-A Python test that swaps a module object out (`patch("pkg.helpers")`,
-`patch.object(pkg, "helpers")`, `monkeypatch.setattr`, a `sys.modules` entry)
-does not reach that module through the swap. A file only such tests reach is
-`mocked_only`, read from the test files' text at walk time, never stored.
-Patching a name inside a module, a run-time target, or a patch with `wraps`,
-`side_effect` or `autospec` keeps the reach. In JavaScript and TypeScript,
-`vi.mock` / `jest.mock` swaps a module out when its factory takes no parameter
-and returns only literals and `vi.fn()` / `jest.fn()`; an automock, `doMock`, a
-factory that reads the original, or a non-relative specifier keeps the reach.
+`reach_states` types each file ([the six states](../layers/TEST_INTELLIGENCE.md#reach-states)).
+A file is `unreached` only when the call walk, the helper and barrel hop and the whole
+import closure all miss it. A test the change adds or edits that is named for the file or
+imports it counts as reaching it, as do the file's inline tests (Rust `#[cfg(test)]`, a
+Go `_test.go` beside it).
+
+### Mocked-only reach
+
+A test that swaps a module out for a double does not reach it through the swap; a file
+only such tests reach is `mocked_only`, read from the test text at walk time.
+
+<details>
+<summary>What counts as a swap</summary>
+
+- **Python** swaps: `patch("pkg.helpers")`, `patch.object(pkg, "helpers")`,
+ `monkeypatch.setattr`, a `sys.modules` entry. Patching a name inside a module, a
+ run-time target, or a patch with `wraps`, `side_effect` or `autospec` keeps the reach.
+- **JavaScript, TypeScript** swaps: `vi.mock` / `jest.mock` whose factory takes no
+ parameter and returns only literals and `vi.fn()` / `jest.fn()`. An automock,
+ `doMock`, a factory that reads the original, or a non-relative specifier keeps it.
+
+</details>
## Measured map internals
-- `.coverage` is opened read-only as SQLite. Repowise decodes coverage.py's
- `numbits` line bitmaps itself and falls back to the `arc` table when line
- bits are absent, so there is no runtime dependency on coverage.py.
-- Rows are indexed both ways: repo plus source file (reverse lookup) and repo
- plus test id (forward). `MAX_TEST_COVERAGE_ROWS = 250_000`.
-- Ingest records (formats merged, matched, unmatched and tied paths, a sample of
- misses, the commit measured) are kept as history,
- `COVERAGE_HISTORY_RETENTION = 50`. A local index created before the history
- table changed keeps one record per repository until rebuilt.
+`.coverage` is opened read-only as SQLite; Repowise decodes coverage.py's `numbits`
+itself, falling back to the `arc` table without line bits. Rows are indexed by repo plus
+source file (reverse) and repo plus test id (forward), capped by
+`MAX_TEST_COVERAGE_ROWS`. Ingest records (formats merged, matched, unmatched and tied
+paths, a sample of misses, the commit measured) are kept as history
+(`COVERAGE_HISTORY_RETENTION = 50`); an index created before the history table changed
+keeps one per repository until rebuilt.
## Report formats and discovery
-The parser is chosen by sniffing the file unless `--format` or `coverage.format`
-names one:
+The file is sniffed unless `--format` or `coverage.format` names a parser:
| Format | Detected by |
|--------|-------------|
@@ -180,42 +159,34 @@ names one:
With no path, `coverage add` looks for `coverage/lcov.info`, `lcov.info`,
`coverage.lcov`, `coverage.xml`, `**/cobertura.xml`, `**/clover.xml`,
`target/llvm-cov/**/*.lcov`, `coverage.out`, `cover.out`,
-`**/target/site/jacoco*/jacoco.xml`, `build/reports/jacoco/**/*.xml`, a
-repo-root `.coverage`, and a few more. `coverage.artifacts` overrides the
-globs. Multiple reports merge: covered and coverable lines are each unioned.
+`**/target/site/jacoco*/jacoco.xml`, `build/reports/jacoco/**/*.xml`, a repo-root
+`.coverage` and a few more (`coverage.artifacts` overrides them). Multiple reports merge
+by unioning covered and coverable lines.
## Report path matching
-Report paths are matched to indexed files by exact path, then by the longest
-matching tail. A tie is reported as ambiguous, never guessed. A relative path
-is tried under the report's own directory first, so
-`packages/web/coverage/lcov.info` naming `src/index.ts` maps to
-`packages/web/src/index.ts`. Cobertura paths are joined to each `<source>`
-root. Matching needs more than the basename when the report names a directory:
-`other/pkg/utils.py` never maps to `src/utils.py`. When a whole report comes
-back unmatched, `coverage.strip_prefix` trims the absolute prefix the runner
-wrote.
+Exact path first, then the longest matching tail; a tie is reported as ambiguous, never
+guessed. A relative path is tried under the report's own directory first
+(`packages/web/coverage/lcov.info` naming `src/index.ts` maps to
+`packages/web/src/index.ts`); Cobertura paths join each `<source>` root; a report naming
+a directory needs more than the basename (`other/pkg/utils.py` never maps to
+`src/utils.py`). When a whole report is unmatched, `coverage.strip_prefix` trims the
+runner's absolute prefix.
## Test wiring edges
-The graph carries test wiring no import states, which test selection reads:
-
-- Runner setup files (`setupFiles`, `globalSetup` and the like) link to the
- tests their config runs.
-- A helper a test starts by a path relative to itself links to that test.
-- A `conftest.py` links to the files pytest collects.
-- Each fixture request links the test to the fixture, so a change a conftest
- reaches only through its imports selects the tests whose fixtures use it,
- plus one import check.
+The graph links tests to wiring no import states: runner setup files (`setupFiles`,
+`globalSetup` and the like) to the tests their config runs, a helper a test starts by a
+relative path to that test, a `conftest.py` to the files pytest collects, and each
+fixture request to its fixture, so a change a conftest reaches only through imports
+selects the tests whose fixtures use it, plus one import check.
## Nearest tests per function
-Each index keeps, for every function, the few test functions nearest it in the
-call graph. Refactoring plans quote them as runnable selectors in place of
-whole test files; they are inferred like the rest of the graph map. A function
-with no resolved caller, or in a language whose tests cannot be told apart by
-name (such as Java's `@Test` or Rust's `#[test]`), is left unknown instead of
-called untested.
+Each index keeps the few test functions nearest every function in the call graph, which
+refactoring plans quote as runnable selectors; they are inferred like the rest. A
+function with no resolved caller, or in a language whose tests cannot be told apart by
+name (Java's `@Test`, Rust's `#[test]`), is unknown, not untested.
## The `impacted_tests` payload
@@ -242,16 +213,16 @@ called untested.
}
```
+Statuses other than `selected` carry `run_all: true`: `run_all` (`reasons` says why;
+`tests_to_run` is what to run first), `no_index`, `unknown` (git or index read failed),
+`config_invalid` (`tests.*` does not parse), `timeout` (over 30 seconds;
+`repowise impacted-tests` gives the same answer), `busy` (a selection is still running),
+`no_source_line_changes`.
+
## Coverage re-ingest hook
-With `hooks.coverage_reingest: true`, the hook fires after the agent runs a
-whole test suite: `pytest`, `go test ./...`, `npm test`, `cargo test`,
-`mvn test`, `./gradlew test` and similar. It re-ingests any watched report
-newer than the last ingest, in the background, and says so in one transcript
-line. It does not act:
-
-- in a repository that has never ingested coverage;
-- on a run that targets some tests (a path, `::`, `-k`, `-run`, `--filter`,
- `-p` and the like);
-- on a `.coverage` database alone;
-- on a report only a `**` glob finds.
+`hooks.coverage_reingest: true` fires after a whole-suite run (`pytest`, `go test ./...`,
+`npm test`, `cargo test`, `mvn test`, `./gradlew test` and similar). It does not act in a
+repository that never ingested coverage, on a run targeting some tests (a path, `::`,
+`-k`, `-run`, `--filter`, `-p` and the like), on a `.coverage` database alone, or on a
+report only a `**` glob finds.
diff --git a/docs/business/COMMERCIAL.md b/docs/business/COMMERCIAL.md
index 55826d6fc..bad534e08 100644
--- a/docs/business/COMMERCIAL.md
+++ b/docs/business/COMMERCIAL.md
@@ -84,8 +84,8 @@ All of the following ship in `pip install repowise` today, free for internal use
LCOV / Cobertura / Clover / JaCoCo / Go coverprofile like a coverage service,
then does the half a coverage service structurally cannot: answers *which
tests reach this file* and *which tests does this diff exercise* **with no
- report at all**, at **95.7% and 97.5% precision** measured against real
- per-test coverage. Measured and inferred rows are labelled and
+ report at all**, at **97.7% precision** on the files tests call into (against the
+ unit suite's coverage) and **97.5%** on the tests to run (against per-test coverage). Measured and inferred rows are labelled and
never averaged. Zero LLM calls, no CI integration needed.
([TEST_INTELLIGENCE.md](../layers/TEST_INTELLIGENCE.md))
- **Change evidence and governance**: Change Records with an evidence checklist
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.md
index 1ff4e87f2..4c4b16a27 100644
--- a/docs/layers/CODE_HEALTH.md
+++ b/docs/layers/CODE_HEALTH.md
@@ -1,14 +1,14 @@
# Code Health
-Repowise scores every source file from 1 to 10 and lists which files to fix
-first. It reads the parse tree, the dependency graph and git history, needs no
-LLM key or network, and runs inside `repowise init` and `repowise update`. The
-analysis is budgeted at under 30 seconds for 3,000 files, and a test enforces it.
-
-It finds code shapes and change patterns that go with bugs, slow code and code
-that is hard to change. It does not run your code or prove a bug exists. A low
+Repowise scores every source file from 1 to 10 and lists which files to fix first. It
+reads the parse tree, the dependency graph and git history, needs no LLM key or network,
+and runs inside `repowise init` and `repowise update`, budgeted (and tested) at under 30
+seconds for 3,000 files. It finds code shapes and change patterns that go with bugs, slow
+code and hard-to-change code; it does not run your code or prove a bug exists, so a low
score means "look here first", not "this is broken".
+How it works: [architecture/code-health.md](../architecture/code-health.md).
+
## Quick start
```bash
@@ -38,7 +38,7 @@ Code health: 7.4/10 [Good], Hotspot: 6.1/10, Worst: 2.3/10 (src/config/loader.py
## The three signals
-They come from one stream of findings, each with its own weights and caps. They
+Three signals come from one stream of findings, each with its own weights and caps, and
are never blended into one number.
| Signal | What it answers | Weights |
@@ -47,17 +47,16 @@ are never blended into one number.
| Maintainability | How hard the code is to read and change | Set by hand; never fitted to bugs |
| Performance risk | Where the structure wastes work | Per-marker precision weights; see [PERFORMANCE.md](PERFORMANCE.md) |
-Smells that fire often but predict bugs weakly (low cohesion, duplicated code,
-broad error handling) are down-weighted in code health and
-counted in full in maintainability.
+Smells that fire often but predict bugs weakly (low cohesion, duplicated code, broad
+error handling) are down-weighted in code health and counted in full in maintainability.
## Reading the score
-Each file starts at 10. Every finding deducts its severity times its marker
-weight, deductions are bounded per category, and the result is clamped to 1-10.
-Code categories bend toward their bound rather than stopping at it, so shrinking a
-critical function raises the score even while it stays critical, and several findings on one
-function count mostly once.
+Each file starts at 10; every finding deducts its severity times its marker weight, and
+the result is clamped to 1-10. Deductions are bounded per category; code categories bend toward their bound rather than
+stopping at it, so shrinking a critical function raises the score while it stays
+critical, and several findings on one function count mostly once
+([scoring](../architecture/code-health.md#6-scoring-scoringpy)).
| Band | Score | Meaning |
|---|---|---|
@@ -67,119 +66,45 @@ function count mostly once.
| Needs work | 4.0 to 5.5 | Worth scheduling |
| At risk | under 4.0 | Where defects concentrate |
-Bands are absolute, so a 6.2 means the same in every repository. On the
-2,770-file benchmark corpus, files under 4.0 carry 16.9 times the per-file defect
-rate of files at 8.0 and above.
-
-Repository KPIs are average health, hotspot health (hotspot files only; both
-weighted by code lines) and the worst performer. A file in an unsupported language
-is counted as not analysed, never scored as a 10.
-
-Two controls decide what a figure describes. Every response echoes them.
+Bands are absolute, so a 6.2 means the same everywhere. On the 2,770-file benchmark
+corpus, files under 4.0 carry 16.9 times the per-file defect rate of files at 8.0 and
+above. Repository KPIs are average health, hotspot health (hotspot files only; both
+weighted by code lines) and the worst performer. A file in an unsupported language is
+not analysed, never scored as a 10.
| Control | Values | Effect |
|---|---|---|
| `scope` | `all` (default), `production` | `production` drops test files, which lowers the headline because tests usually score higher |
-| `counts` | `everything` (default), `code_shape` | `code_shape` removes the git-history half of each deduction, to see whether your code improved after a refactor raised churn |
+| `counts` | `everything` (default), `code_shape` | `code_shape` removes the git-history half of each deduction, to see whether code improved after a refactor raised churn |
-`everything` is the calibrated number every accuracy claim refers to, and the
-badge always reports it.
+Every response echoes both. `everything` is the calibrated number every accuracy claim
+refers to, and the badge always reports it.
## Fix first
-Fix first is one ranked list of what to fix. `repowise health` prints the top 3;
-`get_health()` and the dashboard Overview tab show more. Each item is one unit of
-work: a refactoring plan, one performance intervention, or the strongest
-code-shape finding in a file with no plan. It gives what to change and where, why,
-the first edit, the expected gain, the effort and the tests to run.
-Among items of the same value, a function that many commits have changed comes
-before an equally complex one that rarely changes, and its reason says how many
-commits changed it. A "Break up X" item's reason names the function's shape and
-what splitting it buys: smaller parts that are easier to read and change, and less
-duplicated code when part of it is a copy.
-
-Left out, and counted with a reason:
-
-- test files, tooling (including Dart's `tool/` scripts), generated and vendored
- code, docs and examples
-- files whose only findings come from git history
-- changes that would recover under half a point, and items with no concrete first
- edit
-- kinds that reviewers found not worth doing
-- code a sure dead-code finding covers (the fix is to delete it)
-- dormant functions, which a constant flag switches off
-- print and prompt flows (status reports, checklists, setup wizards), whose
- branches choose what to show
-- functions under CCN 80 and 200 lines whose file rarely changes and has no bug
- fixes; they stay in the refactoring list
-
-Test helpers named for a module's tests (`bot.test-harness.ts`,
-`card-test-helpers.ts`, `test-support.mjs`) count as test support, and bundler
-output (`*.bundle.js`) as generated code, so neither leads Fix first, the
-refactoring list or the dashboard's worst-file lists, which say how many files
-they left out and why.
-
-A function is dormant when its body opens with `if not FLAG: return ...` (or is
-one `if FLAG:` block) and `FLAG` is a module-level `False`, `0` or `None`
-(`const FLAG = false` in TypeScript or JavaScript) that nothing in the same file
-assigns again. Dormant functions are counted next to the excluded totals, not
-dropped silently. Only the file itself is read: a flag imported from another
-module, or flipped from outside with `setattr` or a test's monkeypatch, still
-reads as off.
-
-Items rank by value first (how far the code sits past size and complexity bars,
-one step more in a widely imported file), then by tier. Within a value, the
-complexity a fix removes times how widely the file is imported decides, so a
-4,000-line loop outranks a long print routine. A performance fix ranks by what
-runs it: a request or message handler, then a scheduled job, then code with no
-role evidence. No kind takes more than 3 of the first 5 places while another has
-work worth doing. Exact ordering rules:
-[architecture/code-health.md](../architecture/code-health.md#63-fix-first-ranking-fix_first-worthpy).
-
-| Tier | Meaning |
+Fix first is one ranked list of what to fix: `repowise health` prints the top 3,
+`get_health()` and the dashboard Map tab show more. Each item is one unit of work (a
+refactoring plan, one performance intervention, or the strongest code-shape finding in a
+file with no plan) with what to change and where, why, the first edit, the expected
+gain, the effort and the tests to run.
+
+| Rule | What it means |
|---|---|
-| `now` | Worth doing, safe to start |
-| `next` | Worth doing, needs judgment |
-| `later` | Real but can wait; the reason is shown |
-
-A refactoring item is `later` when the plan of any of its steps would still leave
-a function above the break-up bar: it needs more stages before it is worth
-starting. A finding whose first step comes from a stored Extract Method plan that
-makes its function smaller leads with that plan: its title names the first lift,
-and its next call opens the plan. A finding with no such plan reads "Break up".
-
-A `now` or `next` item shows its first step and the command that checks it
-without opening it, on the card, and over MCP for the lead and for each item of an
-`only=["fix_first"]` page. When no test reaches the code, Verify says to add a
-characterization test first. An Extract Method step shows the helper's header and
-the call that replaces the lines, ready to copy. How a step borrows a plan and
-finds its lines: [Fix first steps](../architecture/code-health.md#fix-first-steps).
-
-Findings, performance causes, refactoring plans and Fix first items are counted
-the same way everywhere: open in the inventory, in scope, eligible, due (tier
-`now` or `next`) and shown, with every exclusion named by its reason. The numbers
-on the dashboard, in `get_health` and in `repowise health --format json`
-(`queue_counts`) agree.
+| Left out, counted by reason | Tests, tooling, generated and vendored code, docs and examples; history-only files; gains under half a point or with no concrete first edit; kinds reviewers rejected; code a sure dead-code finding covers |
+| Also left out | Dormant functions (switched off by a constant flag); print and prompt flows; functions under CCN 80 and 200 lines in a quiet file with no bug fixes, which stay in the refactoring list ([every reason](../architecture/code-health.md#63-fix-first-ranking-fix_first-worthpy)) |
+| Ranking | Value first (how far past size and complexity bars), then tier; a frequently changed function beats an equally complex quiet one and says how many commits changed it |
+| Performance ranking | By what runs it: a request or message handler, then a scheduled job, then code with no role evidence |
+| Variety | No kind takes more than 3 of the first 5 places while another has work worth doing |
+| Tiers | `now` (worth doing, safe to start), `next` (needs judgment), `later` (can wait; reason shown); a refactoring stays `later` while any step's plan leaves a function above the break-up bar |
+| First step | A stored Extract Method plan that shrinks the function leads (title names the first lift; next call opens the plan), else "Break up" with the function's shape and what splitting buys |
+| Shown | A `now` or `next` item shows its first step and check command on the card and over MCP (the lead, and each `only=["fix_first"]` item); Extract Method shows the helper header and replacing call ([how](../architecture/code-health.md#fix-first-steps)) |
+| Verify | When no test reaches the code, add a characterization test first |
+| Counts | Counted the same everywhere (open, in scope, eligible, due, shown, each exclusion by reason), so the dashboard, `get_health` and `repowise health --format json` (`queue_counts`) agree |
### Do next
`repowise next` prints the cross-layer list the dashboard calls Do next and
-`get_overview` returns as `next_actions`. It reads stored actions, so it is
-instant. Fix first items sit beside a live secret, fresh regressions, fragile
-files, files with fading ownership, broken doc references, a dead-code batch,
-missing or stale coverage, and decisions waiting for review. Rows are grouped as
-Now, Worth planning and Improve what Repowise can see. Within a group, rows rank
-by value times confidence over effort, and the top due Fix first item leads its
-group, so Do next and Fix first lead with the same work. Dismissing or snoozing a
-row takes effect at once.
-A fresh regression is in Now only when this week's commits added a proven
-performance cause (one in the performance queue) or lost measured coverage. The
-long, complex or nested code a week of work leaves becomes one row to plan.
-A fragile file asks for tests only when no measured coverage and no test in the
-code graph reaches it; otherwise the row asks you to simplify its lead function. A
-folder where bug fixes concentrate names its first step, the most fixed file's, or
-is left out. An index with fewer than five commits leaves out the rows ranked by
-history.
+`get_overview` returns as `next_actions`, from stored actions, so it is instant.
```bash
repowise next # top 5 this week (the quarter if the week is empty)
@@ -187,17 +112,33 @@ repowise next --horizon quarter --all
repowise next --json # the whole stored view
```
+- Fix first items sit beside a live secret, fresh regressions, fragile files, fading
+ ownership, broken doc references, a dead-code batch, missing or stale coverage and
+ decisions waiting for review, grouped as Now, Worth planning and Improve what Repowise
+ can see.
+- Rows rank by value times confidence over effort; the top due Fix first item leads its
+ group. Dismissing or snoozing takes effect at once.
+- A fresh regression is in Now only when this week's commits added a proven performance
+ cause (one in the performance queue) or lost measured coverage; the long, complex or nested code a week leaves is one
+ row to plan.
+- A fragile file asks for tests only when no measured coverage and no test in the graph
+ reaches it, else to simplify its lead function. A folder where fixes concentrate names
+ its most fixed file's first step, or is left out. Under five commits, history-ranked
+ rows are left out.
+
## Findings
-Findings are the observations behind the score. The dashboard Findings tab lists
-them by dimension and severity, and `get_health(targets=[...])` returns them per
-file. Each has a stable id that survives edits above it. Mark one `acknowledged`,
-`false_positive` or `resolved` in the dashboard, over REST, or with the opt-in
-`set_finding_status` MCP tool. Triage survives re-indexing, and a `resolved`
-finding that is detected again reopens.
+Findings are the observations behind the score: the dashboard Findings tab lists them by
+dimension and severity, and `get_health(targets=[...])` per file. Each has a stable id
+that survives edits above it. Mark one `acknowledged`, `false_positive` or `resolved` in
+the dashboard, over REST or with the opt-in `set_finding_status` MCP tool; triage
+survives re-indexing, and a re-detected `resolved` finding reopens.
+
+### Detector families
-The 53 detectors fall into families. Category caps keep any one family from
-dominating a file.
+The 54 detectors fall into families whose caps keep any one from dominating a file.
+Every id with its threshold and weight:
+[the full roster](../architecture/code-health.md#the-full-roster).
| Family | Detectors | Cap | Catches |
|---|---:|---|---|
@@ -206,65 +147,59 @@ dominating a file.
| Duplication | 1 | 1.0 | Cloned blocks |
| Error handling | 1 | 0.5 | Swallowed or catch-all handlers, `unwrap`/panic, discarded Go errors |
| Change history | 10 | 1.0 to 3.5 | Churn, change entropy, co-change scatter, ownership, fading ownership, prior bug fixes |
-| Test coverage | 4 | 2.0 + 2.0 | Untested hotspots, coverage gaps, uncovered lines (needs a coverage report), untested complex functions (advisory) |
+| Test coverage | 4 | 2.0 + 2.0 | Untested hotspots, coverage gaps, uncovered lines (needs a report), untested complex functions (advisory) |
| Test quality | 4 | 0.5 | Oversized or duplicated assertion blocks; two advisory markers |
-| SQL | 4 | none | Complex SQL, `SELECT *`, `UPDATE`/`DELETE` with no `WHERE`, cartesian joins; maintainability or performance only |
-| Performance | 21 | none | See [PERFORMANCE.md](PERFORMANCE.md); performance only |
-
-Twenty-four detectors move code health. Five markers are advisory: they are
-listed, carry zero impact, and stay out of impact-ranked lists unless you ask for
-the advisory dimension. Three governance findings (an ungoverned hotspot, stale
-governance, a contradictory decision) come from the
-[decisions layer](DECISIONS.md) and never deduct. Every detector id:
-[architecture/code-health.md](../architecture/code-health.md#the-full-roster).
-
-History amplifies code risk and does not stand alone. Git history costs a file at
-most 1.0 point, plus one point for each point its code-shape findings deduct, up
-to 3.5. A simple file that changes often reads as busy, not broken, and never
-drops below 9.0 from history alone. Several history findings on one file count
-the largest in full and the rest at a quarter, because they usually describe the
-same burst of activity.
-
-| Detector | Fires when |
-|---|---|
-| `knowledge_loss` | A file still changing has one real author (bus factor 1) who is gone from recent commits or makes under 20% of them |
-| `ownership_risk` | 5 or more commits and either 3 or more minor contributors (each under 5%) or no author above 40% |
-| `developer_congestion` | 5 or more contributors, top quarter of churn, and nobody owns half |
-| `assertion_free_test` | Advisory. A Python or TypeScript/JavaScript test that checks nothing |
-| `mock_saturated_test` | Advisory. Many mock setup statements per assertion (same languages) |
-| `untested_complexity` | Advisory. A function's CRAP score (complexity weighted by how little of it tests run) is 30 or more |
-
-On a small team, `knowledge_loss` and `ownership_risk` are capped at low severity
-unless the file is a hotspot, and the `small-team` profile lowers them further.
-`ownership_risk` is also low on a file under 40 code lines.
-`large_assertion_block` and `duplicated_assertion_block` fire only in test files.
-House assertion helpers go in the
-[`assertions:` block](../reference/CONFIG.md#the-assertions-block).
-Per-language coverage: [LANGUAGE_SUPPORT.md](LANGUAGE_SUPPORT.md#code-health-coverage).
+| SQL | 4 | none | Complex SQL, `SELECT *`, `UPDATE`/`DELETE` with no `WHERE`, cartesian joins |
+| Performance | 21 | none | See [PERFORMANCE.md](PERFORMANCE.md) |
+
+- Caps are code-health caps; SQL deducts only in maintainability (2.0) and performance
+ findings, cartesian joins included, only in performance risk (2.0).
+- Twenty-four detectors move code health. Five are advisory: listed with zero impact,
+ out of impact-ranked lists unless you ask for the advisory dimension. Three governance
+ findings from the [decisions layer](DECISIONS.md) never deduct.
+- `dry_violation` and `duplicated_assertion_block` stay off every default surface (overview, priorities, MCP, REST lists) until
+ a re-measurement clears their precision; they are still scored. Assertion-block
+ markers fire only in test files; house assertion helpers go in the
+ [`assertions:` block](../reference/CONFIG.md#the-assertions-block).
+- History amplifies code risk: alone it costs a file at most 1.0 point, so a simple file
+ that changes often reads as busy, not broken, and never drops below 9.0 from history
+ alone. On a small team, `knowledge_loss` and `ownership_risk` stay low off a hotspot,
+ and the `small-team` profile lowers them further.
+- Per-language coverage: [LANGUAGE_SUPPORT.md](LANGUAGE_SUPPORT.md#code-health-coverage).
## Trends, coverage and badges
-Every `init`, `update` and `health --recompute` stores a snapshot (the last 50
-per repository). Alerts: declining (fell 0.5 or more against five snapshots back),
-predicted decline (three falls in a row) and history drag (either, where only the
-git-history half moved, so there is nothing in the code to act on).
-`repowise health --trend` prints the last 10.
-
-Coverage reports (LCOV, Cobertura, Clover, JaCoCo, Go coverprofile, Repowise JSON)
-feed the coverage detectors: `repowise coverage add coverage.lcov`. With no report,
-only `untested_hotspot` runs, and no file is treated as uncovered. `untested_complexity`
-scores each function as `CC² × (1 − coverage)³ + CC`: medium from 30, and high
-from 50 or critical from 100 when a report measured the function. Without a
-measurement its coverage is a tier (a test calls it, tests reach it, or neither),
-never a percentage. Only measured findings are listed by default; estimated ones
-appear when you ask for the type by name or opt into unverified findings. After adding a
-report, run `repowise health --recompute`, which analyzes the working tree
-instead of reading the stored analysis and, on a whole-repo table run, writes the
-result to the index. `repowise health --badge` prints README badge Markdown.
+- Every `init`, `update` and `health --recompute` stores a snapshot (the last 50 per
+ repository); `repowise health --trend` prints the last 10 with declining, predicted
+ decline and history-drag alerts ([rules](../architecture/code-health.md#8-trends-trendspy)).
+- Coverage reports feed the coverage detectors (`repowise coverage add coverage.lcov`);
+ with none, only `untested_hotspot` and the reach-tier `untested_complexity` (hidden by
+ default) run, and no file is treated as uncovered
+ ([coverage findings](TEST_INTELLIGENCE.md#coverage-in-code-health)).
+- After adding a report, `repowise health --recompute` analyzes the working tree instead
+ of the stored analysis and, on a whole-repo table run, writes the result to the index.
+- `repowise health --badge` prints README badge Markdown.
## In CI: `repowise health check`
-`repowise health check origin/main...HEAD` analyses the changed files at the base and the head, with no index, and exits `1` only on a code-shape finding the change wrote at high severity or above (`--fail-at` moves the floor). A lower one warns, as does a finding it made worse (`--fail-on worsened` fails on it too), and one it moved or renamed never fails. Git-history markers, coverage and file scores never decide the gate, so a squash merge cannot change its verdict. `.repowise/health-rules.json` is read from the change's base, so a change cannot loosen its own gate. It also warns when the change adds a suppression comment, skips or removes tests, loosens a coverage threshold, or adds a test-environment branch to production code; `--diff-risk error` makes those fail. Exit codes, formats and setup are in [Repowise in CI](../start/CI.md).
+`repowise health check` analyses the changed files at the base and the head, with no
+index, and fails only on a code-shape finding the change wrote.
+
+```bash
+repowise health check origin/main...HEAD
+```
+
+- It exits `1` only on a new code-shape finding at high severity or above (`--fail-at`
+ moves the floor). A lower one warns, as does a worsened one (`--fail-on worsened`
+ fails on it); a moved or renamed one never fails.
+- History markers, coverage and file scores never decide it, so a squash merge cannot
+ change the verdict; `.repowise/health-rules.json` is read from the base, so a change
+ cannot loosen its own gate.
+- It warns when the change adds a suppression comment, skips or removes tests, loosens a
+ coverage threshold, or adds a test-environment branch to production code;
+ `--diff-risk error` makes those fail.
+
+Exit codes, formats and setup: [Repowise in CI](../start/CI.md).
## Configuration
@@ -281,28 +216,28 @@ Per-file rules live in `.repowise/health-rules.json`:
}
```
-`path` uses gitignore semantics, and every matching rule applies. `small-team`
-lowers the people signals a 1-3 person repository cannot support, and an explicit
-`severity_overrides` entry wins over it. Only severity labels are tunable; weights
-and caps are the calibrated constants the published accuracy rests on. Full
-schema:
+`path` uses gitignore semantics and every matching rule applies. `small-team` lowers the
+people signals a 1-3 person repository cannot support; an explicit `severity_overrides`
+entry wins over it. Only severity labels are tunable: weights and caps are the
+calibrated constants the published accuracy rests on. Full schema:
[CONFIG.md](../reference/CONFIG.md#the-health-rulesjson-file).
## Accuracy and limits
-Measured without leakage: files scored before the bug window, checked against the
-next six months of bug fixes.
+Measured without leakage: files scored before the bug window, checked against the next
+six months of bug fixes ([method](../architecture/code-health.md#62-validation-and-calibration)).
-- ROC AUC 0.737 (95% CI 0.683 to 0.787) across 21 repositories, 9 languages and
- 2,826 files. Held out on PROMISE jEdit: 0.761 and 0.776.
-- Against CodeScene on the same files, recall at a 20%-of-lines review budget is
- 0.173 vs 0.074 (p = 0.003), 2.3 times the defects. AUC and precision are ties.
-- Lines of code alone scores AUC 0.742, a tie. The gain is in ordering a fixed
- review budget and saying why. Within size quartiles AUC is 0.525 to 0.718.
+- ROC AUC 0.737 (95% CI 0.683 to 0.787) across 21 repositories, 9 languages and 2,826
+ files; held out on PROMISE jEdit, 0.761 and 0.776.
+- Against a commercial code-health tool on the same files, recall at a 20%-of-lines
+ review budget is 0.173 vs 0.074 (p = 0.003), 2.3 times the defects; AUC and precision
+ are ties.
+- Lines of code alone scores AUC 0.742, a tie: the gain is in ordering a fixed review
+ budget and saying why. Within size quartiles AUC is 0.525 to 0.718.
- On open data, the score does not track GitHub merge time.
-- `get_health(include=["accuracy"])` reports how many of your 20 lowest-scoring
- files had a bug fix in the last 180 days against the base rate. It is an association,
- not a forward test, and stays silent below 25 scored files or 5 fixed ones.
+- `get_health(include=["accuracy"])` reports how many of your 20 lowest-scoring files had
+ a bug fix in the last 180 days against the base rate: an association, not a forward
+ test, silent below 25 scored files or 5 fixed ones.
Every test: [BENCHMARKS.md](../BENCHMARKS.md#code-health-predicts-defects).
@@ -313,6 +248,5 @@ Every test: [BENCHMARKS.md](../BENCHMARKS.md#code-health-predicts-defects).
| CLI | `repowise health`, `repowise next`, `repowise status`; flags in [CLI_REFERENCE.md](../reference/CLI_REFERENCE.md#repowise-health-path) |
| MCP | [`get_health`](../agent/MCP_TOOLS.md#get_health); health fields on `get_risk`, `get_context` and `get_overview` |
| Editor | Per-file findings in the [VS Code extension](../agent/VSCODE.md) |
-| Refactoring | Plans per file, from `repowise health --refactoring-targets`. Break Cycle is advisory: shown beside a file's steps, never as one, and never in Fix first. A Split File or Extract Class plan with an unnamed group is held the same way (`needs_design`). See [REFACTORING.md](REFACTORING.md) |
-| Layers | [PERFORMANCE.md](PERFORMANCE.md), [REFACTORING.md](REFACTORING.md), [TEST_INTELLIGENCE.md](TEST_INTELLIGENCE.md), [BUG_HISTORY.md](BUG_HISTORY.md), [DOC_DRIFT.md](DOC_DRIFT.md) |
-| Internals | [architecture/code-health.md](../architecture/code-health.md) |
+| Refactoring | Plans per file from `repowise health --refactoring-targets` ([REFACTORING.md](REFACTORING.md)). Break Cycle is advisory: beside a file's steps, never one, never in Fix first; a Split File or Extract Class plan with an unnamed group is held the same way (`needs_design`) |
+| Layers | [PERFORMANCE.md](PERFORMANCE.md), [TEST_INTELLIGENCE.md](TEST_INTELLIGENCE.md), [BUG_HISTORY.md](BUG_HISTORY.md), [DOC_DRIFT.md](DOC_DRIFT.md) |
diff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.md
index 2e2f48257..e306cc38d 100644
--- a/docs/layers/TEST_INTELLIGENCE.md
+++ b/docs/layers/TEST_INTELLIGENCE.md
@@ -2,15 +2,13 @@
Test intelligence answers two questions your CI cannot: which files are risky *and*
untested, and which tests a given change exercises. The second turns a 4,000-test suite
-into the few dozen tests that guard the change you just made.
+into the few dozen tests that guard the change you just made. **Measured** answers come
+from an ingested coverage report; **inferred** ones from the dependency graph, always
+labelled and never a percentage. No LLM key, no network: ingesting is a parse and a
+database write, every later question an index lookup, and the pull-request gate needs
+only git and a report ([Patch coverage in CI](#patch-coverage-in-ci)).
-It works at two levels of evidence. Ingest a coverage report and the answers are
-**measured**: this test ran these lines. Without one, Repowise still answers from the
-dependency graph, which records which tests reach which files; those answers are
-**inferred**, always labelled as such, and never turned into a percentage. No LLM key,
-no network. Ingesting a report is a parse and a database write; every question after
-that is an index lookup. The patch-coverage gate for pull requests needs only git and a
-report (see [Patch coverage in CI](#patch-coverage-in-ci)).
+How the inferred tier works: [architecture/test-intelligence.md](../architecture/test-intelligence.md).
## Quick start
@@ -28,12 +26,14 @@ repowise impacted-tests main...HEAD # the tests guarding this branch
repowise impacted-tests main...HEAD --format list | xargs pytest
```
-Agents read the same answers through MCP ([From an agent](#from-an-agent)); the
-dashboard shows coverage on the **Tests** tab of a repository's health page. Longer
-walkthrough: [examples/health-coverage/](../../examples/health-coverage/).
+Agents read the same answers through MCP ([From an agent](#from-an-agent)); the dashboard
+shows coverage on a repository's **Tests** page. Walkthrough:
+[examples/health-coverage/](../../examples/health-coverage/).
## Measured and inferred
+The two kinds are shown side by side and never averaged.
+
| | Per-file aggregate | Per-test map | Inferred map |
|---|---|---|---|
| Comes from | Any coverage report | A report that records which test ran each line | The call and import graph, already indexed |
@@ -42,29 +42,44 @@ walkthrough: [examples/health-coverage/](../../examples/health-coverage/).
| May produce a percentage | Yes | Yes | **Never** |
| Goes stale | Yes: tied to the commit it was measured at | Yes | No: read from the current graph |
| Labelled | `measured` | `measured` | `inferred` |
-| Powers | Code-health coverage findings, the Tests tab | `impacted-tests`, `impacted_tests`, `tests_to_run` | The fallback under every row, when nothing measured answers |
+| Powers | Code-health coverage findings, the Tests page | `impacted-tests`, `impacted_tests`, `tests_to_run` | The fallback under every row, when nothing measured answers |
+
+A call edge says control *can* reach a file, not that a run did, so inference is safe as
+a floor ("something reaches this, do not call it untested") and unsafe as a quantity.
+Refactoring plans also name the test functions nearest each function as runnable
+selectors ([how](../architecture/test-intelligence.md#nearest-tests-per-function)).
+
+### Reach states
-The two kinds are shown side by side and never averaged. A call edge says control *can*
-reach a file, not that a run did, so inference is safe as a floor ("something reaches
-this, do not call it untested") and unsafe as a quantity. Refactoring plans name the
-test functions nearest each function in the call graph as runnable selectors
-([how](../architecture/test-intelligence.md#nearest-tests-per-function)).
+Each inferred answer about a file is one of six states
+([how each is decided](../architecture/test-intelligence.md#one-walk-two-graph-sources)):
+
+| State | Meaning |
+|---|---|
+| `reached` | Tests reach the file; the answer names them and how |
+| `unreached` | No walk reaches the file |
+| `new` | The index has not seen the file |
+| `no_signal` | The index holds no tests |
+| `type_only` | Declares only types: nothing a test could run, so never a gap |
+| `mocked_only` | Every reaching test replaces the file with a double |
## Supported formats
-| Format | Per-test map |
-|--------|--------------|
-| **LCOV** | Yes, when each record carries a non-blank `TN:` test name |
-| **Cobertura**, **Clover** and **JaCoCo** XML | No |
-| **Go coverprofile** (`go test -coverprofile`) | No |
-| **coverage.py `.coverage`** | Yes, when recorded with per-test contexts |
-| **Normalized JSON** (`repowise-coverage-v1`) | No |
+**LCOV**, **Cobertura**, **Clover** and **JaCoCo** XML, **Go coverprofile**
+(`go test -coverprofile`), **coverage.py `.coverage`** and **normalized JSON**
+(`repowise-coverage-v1`). Two carry a per-test map: LCOV when each record has a
+non-blank `TN:` test name, and `.coverage` when recorded with per-test contexts.
-The format is sniffed from the file
-([detection rules](../architecture/test-intelligence.md#report-formats-and-discovery));
-force one with `--format lcov|cobertura|clover|repowise-json|go-coverprofile|jacoco`. Go
-percentages are line-based, not the statement percentage `go tool cover` prints. Any
-other runner can be fed through the normalized JSON:
+- The format is sniffed and found in the usual locations
+ ([rules](../architecture/test-intelligence.md#report-formats-and-discovery)); force
+ one with `--format lcov|cobertura|clover|repowise-json|go-coverprofile|jacoco`. Go
+ percentages are line-based, not `go tool cover`'s statement percentage.
+- Paths map by suffix, a tie is reported, never guessed
+ ([rules](../architecture/test-intelligence.md#report-path-matching)); `--strict` fails
+ on any unmapped report file. The coverage summary (`get_health`, the REST coverage
+ route) says how each report mapped and whether it matches the indexed commit.
+
+Feed any other runner through the normalized JSON:
```json
{ "format": "repowise-coverage-v1",
@@ -75,27 +90,18 @@ other runner can be fed through the normalized JSON:
`covered_lines` and `coverable_lines` are optional. Patch coverage needs
`coverable_lines`; without it a file reads as having no line data, never as 0%.
-With no path, `coverage add` finds reports in the
-[usual locations](../architecture/test-intelligence.md#report-formats-and-discovery);
-multiple reports merge. Report paths map to indexed files by path suffix, and a tie is
-reported, never guessed
-([rules](../architecture/test-intelligence.md#report-path-matching)). If a whole report
-comes back unmatched, set `coverage.strip_prefix`; `--strict` fails when any report file
-did not map. The coverage summary (`get_health`, the REST coverage route) reports how
-each report mapped and whether it was measured at the indexed commit.
-
-**Building a per-test map.** The main path is coverage.py dynamic contexts:
-`pytest --cov=<package> --cov-context=test` (needs pytest-cov), then `repowise coverage add .coverage`.
-Contexts like `tests/test_auth.py::TestLogin::test_ok|run` become test ids, with no
-runtime dependency on coverage.py. Per-test LCOV works too: each record carries a
-distinct `TN:` name, and blank `TN:` records are skipped. If the report has no contexts,
-`coverage add` says so and still stores the per-file aggregate. The map is capped at
-250,000 rows and the CLI reports how many were dropped.
+### Per-test map
+
+coverage.py dynamic contexts ([Quick start](#quick-start)) like
+`tests/test_auth.py::TestLogin::test_ok|run` become test ids, with no runtime dependency
+on coverage.py; per-test LCOV uses distinct `TN:` names and skips blank ones. A report
+with no contexts still stores the per-file aggregate, and `coverage add` says so. The
+map is capped at 250,000 rows, and the CLI reports how many were dropped.
## Impacted tests
-`repowise impacted-tests` diffs a change, looks up the changed lines in the per-test
-map, and returns the tests whose recorded coverage touches them.
+`repowise impacted-tests` diffs a change, looks up the changed lines in the per-test map,
+and returns the tests whose recorded coverage touches them.
```bash
repowise impacted-tests # staged changes (the default outside CI)
@@ -103,27 +109,25 @@ repowise impacted-tests main...HEAD # a branch or PR, from the merge-
repowise impacted-tests main...HEAD --format args --runner pytest # for CI
```
-`base...head` diffs from the merge-base, so it is what a pull request changed;
-`base..head` is the plain range, and a single SHA is one commit. Change risk follows the
-same rule. Each result says how it was found, and a guess never passes for evidence:
-
-| Situation | Reported as |
-|-----------|-------------|
-| Per-test coverage on the changed lines | The covering tests, `via: coverage` |
-| The changed file is itself a test | Itself, `via: changed-test` |
-| No coverage rows, but a test reaches the file in the graph | Those test files, `via: call-graph` or `via: import-graph`, in a separate "NOT coverage-backed" table |
-| No coverage and no graph edge, but a name-shaped match | That file, `via: filename-pattern`, in the same table |
-| None of the above | "unknown, run the full suite to be safe" |
-| No map ingested at all | A prompt to run `coverage add` on a report with contexts |
-
-The graph also links tests to wiring no import states: runner setup files, helpers a
-test starts by path, `conftest.py` files and the fixtures a test requests
-([details](../architecture/test-intelligence.md#test-wiring-edges)).
-
-With `--format list` the caveats go to stderr so the pipe stays clean. The command exits
-`0` in every case: it reports, it does not gate. `--format args` prints runner
-arguments, or `:all` whenever any part of the answer is unknown. Rules, `tests.*` config
-keys and CI recipes:
+`base...head` diffs from the merge-base (what a pull request changed), `base..head` is
+the plain range, and a single SHA is one commit; change risk follows the same rule.
+
+- Each result says how it was found (`via: coverage`, `changed-test`, then in a separate
+ "NOT coverage-backed" table `call-graph`, `import-graph`, `filename-pattern`), and a
+ guess never passes for evidence: otherwise it says "unknown, run the full suite to be
+ safe", and with no map it prompts for `coverage add` on a report with contexts
+ ([every case](../reference/CLI_REFERENCE.md#repowise-impacted-tests-revspec)).
+- The graph also links tests to wiring no import states
+ ([details](../architecture/test-intelligence.md#test-wiring-edges)).
+- The headline counts the tests the change reaches. Two groups run but are counted
+ apart: `selected.broadcast` (a `conftest.py` autouse fixture, hook or module-level code
+ uses the change) and `selected.import_closure` (reached only through imports, more
+ than one file away, no call path).
+- `--format list` sends caveats to stderr; `--format args` prints runner arguments, or
+ `:all` when any part is unknown. It reports, never gates: exit `0` either way, `2` only
+ when the change or config cannot be read.
+
+Rules, `tests.*` config keys and CI recipes:
[Selecting the tests a change needs](../start/CI.md#selecting-the-tests-a-change-needs).
## Patch coverage in CI
@@ -135,117 +139,96 @@ lines the report marks executable, what share did the tests run?
repowise coverage check origin/main...HEAD --report coverage/lcov.info --fail-under 80
```
-It needs git and a report, nothing else: no index, no ingest, no LLM key. The same
-figure appears in `get_change_risk`'s `patch_coverage` block and in the REST
-patch-coverage route the editor reads.
-
-| File status | Meaning | Counts in the % |
-|-------------|---------|-----------------|
-| `measured` | The report names the file and some changed lines are executable | Yes |
-| `no_coverable_changes` | The report names the file, but no changed line is executable | No |
-| `not_in_report` | The report does not name the file (e.g. a new file no test loaded) | No; listed, never 0% |
-| `no_line_data` | The report names the file but gives no executable-line set | No |
-| `stale_file` | Stored coverage only: the file changed since the commit the coverage was measured at | No; listed, no figures |
-
-Exit `0` passes or had nothing to judge, `1` is below a gate, `2` means the check could
-not run (no usable report, unknown revision, shallow clone without a merge-base, bad
-config). With an index, each uncovered range also names the test file to extend. The
-GitHub Action, GitLab template, per-language reports, path-scoped and risk-weighted
-gates, branches, project coverage and monorepos: [Repowise in CI](../start/CI.md). All
-flags and JSON fields: the
-[`coverage check` reference](../reference/CLI_REFERENCE.md#repowise-coverage-check-revspec).
-
-## Untested hotspots
-
-Coverage feeds the [code health](CODE_HEALTH.md) layer. The sharpest finding is
-`untested_hotspot`, the "write tests before you refactor" case. It fires only when a
+It needs only git and a report (no index, ingest or LLM key); the same figure is in
+`get_change_risk`'s `patch_coverage` block and the REST route the editor reads. Only
+`measured` files count; `not_in_report` is listed, never 0%, and stored coverage marks
+files changed since measurement `stale_file`. Exit `0` passes or had nothing to judge,
+`1` is below a gate, `2` could not run (no usable report, unknown revision, shallow
+clone without a merge-base, bad config). With an index, each uncovered range names the
+test file to extend. Statuses, flags and JSON:
+[`coverage check` reference](../reference/CLI_REFERENCE.md#repowise-coverage-check-revspec);
+the GitHub Action, GitLab template, per-language reports, path-scoped and risk-weighted
+gates, branches, project coverage and monorepos: [Repowise in CI](../start/CI.md).
+
+## Coverage in code health
+
+Coverage feeds the [code health](CODE_HEALTH.md) layer through `untested_hotspot`,
+`coverage_gap` (thin-but-present coverage), `coverage_gradient` (deducts in proportion to
+the uncovered share) and the advisory `untested_complexity`. Every threshold:
+[the full roster](../architecture/code-health.md#the-full-roster).
+
+### Untested hotspots
+
+`untested_hotspot` is the "write tests before you refactor" case. It fires only when a
file is all three of:
| Condition | Threshold |
|---|---|
-| A hotspot | Flagged by the git layer, which means top-quartile churn in this repository plus absolute activity floors |
+| A hotspot | Flagged by the git layer: top-quartile churn in this repository plus absolute activity floors |
| Depended on | At least 4 dependents |
| Under-tested | Line coverage below 40%. With no coverage ingested, only when *nothing* says a test touches the file: no paired test file by name and no test reaching it in the graph |
-The file must also be code with at least one function (a config file or a
-module of constants has nothing a test could exercise) and must not itself be
-a test file.
-
-Severity is `CRITICAL` at 15% coverage or less with 10+ dependents, `HIGH` at one of
-those two, `MEDIUM` otherwise. `coverage_gap` covers thin-but-present coverage, and
-`coverage_gradient` deducts in proportion to the uncovered share. Per function,
-`untested_complexity` reads the CRAP score: complexity weighted by the share of
-the function a report measured as run, or by its reach tier when no report covers
-it. A tier never becomes a percentage, and only measured findings are listed by
-default. A `coverage_gap` finding, and an `untested_complexity` finding on measured
-coverage or a direct test, carries `actions`: a prompt to add tests (or to split
-the function at complexity 30 and above) naming the nearest test file to extend,
-and the `.repowise/health-rules.json` rule that silences it for that file. The graph check
-matters because a filename convention misses tests in both directions
+The file must be code with at least one function, not a test. The graph check matters
+because a filename convention misses tests in both directions
([examples](../architecture/test-intelligence.md#why-a-graph-signal)).
+### Untested complexity
+
+`untested_complexity` (advisory) reads each function's CRAP score,
+`CC² × (1 − coverage)³ + CC`. Coverage is the share a report measured as run; without
+one it is a tier, never a percentage: `direct` (a test calls the function), `reached`
+(tests reach it or its file) or `none`, read as `coverage_basis: estimated`. Only
+measured findings are listed by default; estimated ones appear when you name the type
+or opt into unverified findings.
+
+### Fix actions
+
+`coverage_gap`, and `untested_complexity` on measured coverage or a direct test, carry
+`actions`: a prompt to add tests (or split the function at complexity 30+) naming the
+nearest test file, and the `.repowise/health-rules.json` rule that silences it for the
+file. They show in the file drawer and `get_health(finding_id=...)`.
+
## From an agent
`get_risk(changed_files=[...], include=["tests"])` leads with a `directive` whose
-`test_recommendations` names up to ten tests for the changed files. Each row keeps its
-`basis`:
-
-| `basis` | Holds | Means |
-|---|---|---|
-| `measured` | A test node id | The per-test map shows the test covering a changed file |
-| `inferred` | A test file path | The graph shows the test reaching the change; a candidate, not proof |
-
-`tests_to_run`, sent without the include, is the run list `repowise impacted-tests`
-makes, with `tests_to_run_basis`, `tests_to_run_why`, `tests_run_all` and
-`tests_run_all_reasons` ([PR mode](CHANGE_RISK.md#pr-mode-get_risk-with-changed_files)).
-`coverage_analysis` says whether coverage is available, partial, degraded or stale;
-without a coverage map the directive carries `coverage: {status, reason}`.
-
-`get_change_risk(revspec=...)` returns `impacted_tests`, the same selection over the
-change's diff, so a measured map at either end of it matches by line
-([payload](../architecture/test-intelligence.md#the-impacted_tests-payload)). In its
-`line_coverage` block, `untested_changes` is the strong signal: the file is in the map
-but nothing covers the lines you touched. `stale_test_candidates` flags covered lines
-whose guarding test is absent from the diff. `no_coverage_data`: the file is not in the
-map.
-
-**Self-check before a push.** `get_change_risk` without a `revspec` measures
-`patch_coverage` over everything a push would bring: the working tree (untracked files
-included) or `HEAD`, diffed from the merge-base with the branch CI compares against.
-Uncommitted code is `current` when the last ingest came after the newest edit of the
-changed files, else `stale`. When changed lines are uncovered, the directive adds one
-`next_actions` line naming the tests to extend, or saying to rerun tests with coverage.
-
-**Re-ingest after a test run** (opt-in). With `hooks.coverage_reingest: true` in
-`.repowise/config.yaml` (or `REPOWISE_HOOK_COVERAGE_REINGEST=1` for one session), a
-whole-suite test run by the agent re-ingests any watched report newer than the last
-ingest, in the background, with one transcript line
-([trigger rules](../architecture/test-intelligence.md#coverage-re-ingest-hook)). It
-costs a process start after each shell command in that repository. Claude Code runs it
-from [repo-local hook entries](../agent/HOOKS.md#what-gets-written-where); Codex only
-after a successful command.
+`test_recommendations` names up to ten tests for the changed files. A `measured` row holds
+a test node id the per-test map shows covering a changed file; an `inferred` row holds a
+test file path the graph shows reaching the change, a candidate, not proof.
+
+- `tests_to_run`, sent without the include, is the run list `repowise impacted-tests`
+ makes ([fields](CHANGE_RISK.md#pr-mode-get_risk-with-changed_files)).
+- `coverage_analysis` says whether coverage is available, partial, degraded or stale;
+ without a coverage map the directive carries `coverage: {status, reason}`.
+- `get_change_risk(revspec=...)` returns `impacted_tests`, the same selection over the
+ diff, matching a measured map at either end by line
+ ([payload](../architecture/test-intelligence.md#the-impacted_tests-payload)). Its
+ `line_coverage` holds `untested_changes` (the strong signal: in the map, but nothing
+ covers the touched lines), `stale_test_candidates` (covered lines whose guarding test
+ is absent from the diff) and `no_coverage_data` (not in the map).
+- **Self-check before a push:** `get_change_risk` without a `revspec` measures
+ `patch_coverage` over what a push would bring (the working tree with untracked files,
+ or `HEAD`) from the merge-base with CI's branch. Uncommitted code is `current` when the
+ last ingest is newer than the changed files' newest edit, else `stale`; uncovered
+ lines add one `next_actions` line naming tests to extend or to rerun with coverage.
+- **Re-ingest after a test run** (opt-in: `hooks.coverage_reingest: true`, or
+ `REPOWISE_HOOK_COVERAGE_REINGEST=1` for one session): a whole-suite run re-ingests any
+ watched report newer than the last ingest, in the background, with one transcript line
+ ([triggers](../architecture/test-intelligence.md#coverage-re-ingest-hook)). It costs a
+ process start per shell command; Claude Code runs it from
+ [repo-local hook entries](../agent/HOOKS.md#what-gets-written-where), Codex only after
+ a successful command.
## Empty means unknown
**An empty test list never means the change is untested.** Every surface carries a
-discriminator beside the list. For `get_change_risk`, `impacted_tests.status` is one of:
+discriminator beside the list.
-| `status` | Meaning |
-|---|---|
-| `selected` | The selection vouches for `tests_to_run`. Empty here means the change needs no test (documentation, a deleted test) |
-| `run_all` | Every test must run; `reasons` says why, and `tests_to_run` is what to run first |
-| `no_index` | Nothing indexed yet |
-| `unknown` | The git or index read failed |
-| `config_invalid` | `tests.*` in `.repowise/config.yaml` does not parse |
-| `timeout` | The selection took over 30 seconds; `repowise impacted-tests` gives the same answer |
-| `busy` | A selection for this repository is still running |
-| `no_source_line_changes` | No changed source lines to map |
-
-Every status but `selected` carries `run_all: true`: nothing vouches for a subset.
-`get_risk` keeps coverage availability, freshness and map presence explicit in
-`test_impact.coverage`; an empty list under unavailable analysis is unknown, never "no
-tests needed". The CLI prints "unknown, run the full suite", and the per-file lookups
-report a file with no data as `no_coverage_data`, not as uncovered.
+Only `impacted_tests.status: selected` vouches for `tests_to_run` (empty there means no
+test is needed, as for docs or a deleted test); every other status carries
+`run_all: true` ([statuses](../architecture/test-intelligence.md#the-impacted_tests-payload)).
+`get_risk` keeps coverage availability, freshness and map presence in
+`test_impact.coverage`, the CLI prints "unknown, run the full suite", and per-file
+lookups report a file with no data as `no_coverage_data`, not uncovered.
## Configuration
@@ -269,48 +252,50 @@ coverage:
- {name: api, paths: ["/services/api/"], fail_under: 85}
```
-`init` and `update` also discover and ingest coverage; `update` re-reads a report
-written after the last ingest;
-`repowise init --coverage-report <path>` takes explicit reports (repeatable).
-`--coverage-report` is test coverage; `--coverage` controls documentation breadth. When
-`update` re-reads reports: [CONFIG.md](../reference/CONFIG.md#the-coverage-block).
+`init` and `update` also discover and ingest coverage, and `update` re-reads a report
+written after the last ingest ([when](../reference/CONFIG.md#the-coverage-block)).
+`repowise init --coverage-report <path>` takes explicit reports (repeatable);
+`--coverage-report` is test coverage, while `--coverage` controls documentation breadth.
## Accuracy and limits
-The inferred tier is measured on the Repowise repository against a real
-`coverage run --contexts=test`, over a slice with complete per-test attribution (37 test
-files, 159 production files provably executed):
+The inferred tier is measured on the Repowise repository against the line coverage of
+its whole unit suite: 2,223 Python production files, 1,935 of them with a function body
+run. A claim is checked twice, against any line of the file running and against a
+function body running; recall counts the 1,935.
+
+| Question | Claims | A line ran | A function body ran | Recall |
+|---|---:|---:|---:|---:|
+| "A test calls into this file" (suppresses `untested_hotspot`) | 1,515 | 100% | 97.7% | 76.5% |
+| "A test reaches this file" (the Tests page and a file's page) | 2,191 | 99.9% | 88.3% | 99.9% |
-| Question | Precision | Reach |
-|---|---:|---:|
-| "What reaches this file" (suppresses `untested_hotspot`) | 95.7% (44 of 46 claims) | 27.7% recall |
-| "Which tests do I run" (`tests_to_run`, `impacted_tests`) | 97.5% | 100% of 47 targets answered |
+A slice with complete per-test attribution (37 test files, 159 production files) puts
+`tests_to_run` at 97.5% precision.
-- Recall reads low because coverage counts a file as run when it was merely imported.
- Among files where over three quarters of what ran was inside function bodies, recall
- is 77%.
+- Files a test reaches only by importing them run their module code but often no
+ function, which is most of the gap between the two precision columns of the second row.
- Framework-invoked code with no static caller (migrations run by naming convention, for
example) is not reached by the graph.
-- The Tests tab and a file's page share one definition of reached: a test calls into the
- file or imports it, directly or through a chain of imports.
- The tab's unreached list is a floor, so routes, CLI commands and plugin registries a
- framework invokes can appear there with tests behind them.
+- The Tests page and a file's page share one definition of reached: a test calls into the
+ file or imports it, directly or through a chain of imports. The page's unreached list
+ is a floor, so routes, CLI commands and plugin registries a framework invokes can
+ appear there with tests behind them.
- Inferred answers are file-level; only measured data is line-level.
- Measured data is only as current as the last ingest: each ingest replaces the previous
rows, so ingest at the commit you intend to query. Rows read `stale` once the index
- moves past their commit. The Tests tab trends the repo-wide totals of the newest 50
- ingests once there are three, leaving partial ingests out.
+ moves past their commit.
+- The Tests page trends the repo-wide totals of the newest 50 ingests once there are
+ three, leaving partial ingests out.
Method: [architecture/test-intelligence.md](../architecture/test-intelligence.md) and,
across layers, [BENCHMARKS.md](../BENCHMARKS.md).
## Reference
-Commands: `repowise coverage add [PATHS...]` (ingest; auto-discovers with no path),
+`repowise coverage add [PATHS...]` (ingest; auto-discovers with no path),
`coverage status` (summary plus per-test map counts), `coverage check [REVSPEC]`
(patch-coverage gate, no index needed), `coverage suggest-gates` (proposes
-`coverage.gates` YAML, writes nothing) and `repowise impacted-tests [REVSPEC]` (the
-tests a change exercises, or runner arguments). Every flag:
-[CLI_REFERENCE.md](../reference/CLI_REFERENCE.md#repowise-coverage). MCP:
+`coverage.gates` YAML, writes nothing) and `repowise impacted-tests [REVSPEC]` (the tests
+a change exercises, or runner arguments). Every flag: [CLI_REFERENCE.md](../reference/CLI_REFERENCE.md#repowise-coverage). MCP:
[`get_change_risk`](../agent/MCP_TOOLS.md#get_change_risk),
[`get_risk`](../agent/MCP_TOOLS.md#get_risk).
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 2042404c7..206594b6b 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -1,114 +1,77 @@
# CLI Reference
-Complete reference for all `repowise` commands. For a guided introduction, see the [Quickstart](../start/QUICKSTART.md).
+Every `repowise` command and flag. For a guided introduction, see the [Quickstart](../start/QUICKSTART.md).
-Command list (in registration order): `augment`, `init`, `delete`, `generate-claude-md`, `costs`, `update`, `generate`, `dead-code`, `doc-drift`, `health`, `risk`, `overlap`, `decision`, `coverage`, `impacted-tests`, `search`, `ask`, `context`, `symbol`, `why`, `distill`, `expand`, `saved`, `savings`, `security`, `corrections`, `export`, `hook`, `agents`, `uninstall`, `status`, `next`, `doctor`, `watch`, `serve`, `mcp`, `reindex`, `restyle`, `wiki-styles`, `whats-new`, `telemetry`, `login`, `logout`, `whoami`, `workspace`. Two more ship as separate console scripts, not subcommands: `repowise-augment`, `repowise-rewrite` (both hook entry points, not meant to be run by hand).
+Top-level commands (alphabetical): `agents`, `ask`, `attribution`, `augment`, `changes`, `check`, `components`,
+`config`, `context`, `corrections`, `costs`, `coverage`, `dead-code`, `decision`, `delete`, `distill`, `doc-drift`,
+`doctor`, `events`, `expand`, `export`, `generate`, `generate-claude-md`, `health`, `hook`, `impacted-tests`, `init`,
+`login`, `logout`, `mcp`, `next`, `overlap`, `packages`, `plugins`, `publish`, `reindex`, `report`, `restyle`, `risk`,
+`saved`, `savings`, `search`, `security`, `serve`, `status`, `suspects`, `symbol`, `telemetry`, `uninstall`, `update`,
+`watch`, `whats-new`, `whoami`, `why`, `wiki-styles`, `workspace`. `repowise --version` prints the version.
+`repowise-augment` and `repowise-rewrite` are separate console scripts (hook entry points, not run by hand).
-**Do you need an LLM key?** Most commands are pure index/analysis and never call an LLM. `init` never requires a key: without one it renders the wiki from structure. It calls an LLM only when a provider is resolvable or `--prose` is passed. The exceptions: `update` (unless `--index-only` or `--no-docs`), `generate`, `restyle`, `watch` (when it regenerates a page), `health --generate-code`, and `workspace add --docs`. Everything else, `search`, `dead-code`, `doc-drift`, `health`, `risk`, `impacted-tests`, `decision`, `coverage`, `security`, `export`, `mcp`, `reindex`, `doctor`, and so on, works index-only, with no provider configured.
+**Do you need an LLM key?** Usually not; most commands only read the index.
+
+- `init` never needs one: it calls an LLM only with a resolvable provider or `--prose`, else renders from structure.
+- LLM callers: `update` (unless `--index-only` or `--no-docs`), `generate`, `restyle`, `watch` (when it regenerates a page), `health --generate-code`, `workspace add --docs`.
+- Index-only, no provider: everything else (`search`, `dead-code`, `doc-drift`, `health`, `risk`, `impacted-tests`, `decision`, `coverage`, `security`, `export`, `mcp`, `reindex`, `doctor`, ...).
## Contents
-Grouped by what you're trying to do, not alphabetically. `PATH` and flag details are on each command's own section.
-
-**Indexing**
-[`init`](#repowise-init-path) ·
-[`update`](#repowise-update-path) ·
-[`generate`](#repowise-generate-path) ·
-[`restyle`](#repowise-restyle-style-path) ·
-[`wiki-styles`](#repowise-wiki-styles-path) ·
-[`watch`](#repowise-watch-path) ·
-[`reindex`](#repowise-reindex-path)
-
-**Querying**
-[`search`](#repowise-search-query-path) ·
-[`ask`](#repowise-ask-question) ·
-[`context`](#repowise-context-targets) ·
-[`symbol`](#repowise-symbol-symbol_id) ·
-[`why`](#repowise-why-query) ·
-[shared `ask`/`context`/`symbol`/`why` options](#shared-options-ask-context-symbol-why) ·
-[`status`](#repowise-status-path) ·
-[`next`](#repowise-next-path)
-
-**Health and risk**
-[`health`](#repowise-health-path) ·
-[`health check`](#repowise-health-check-revspec) ·
-[`risk`](#repowise-risk-revspec) ·
-[`overlap`](#repowise-overlap) ·
-[`dead-code`](#repowise-dead-code-path) ·
-[`doc-drift`](#repowise-doc-drift-path) ·
-[`security`](#repowise-security) ·
-[`check`](#repowise-check-revspec) ·
-[`impacted-tests`](#repowise-impacted-tests-revspec) ·
-[`coverage`](#repowise-coverage) ·
-[`components`](#repowise-components) ·
-[`changes`](#repowise-changes) ·
-[`events`](#repowise-events) ·
-[`report assessment`](#repowise-report-assessment-path)
-
-**Decisions**
-[`decision`](#repowise-decision)
-
-**Agent wiring**
-[`agents`](#repowise-agents) ·
-[`generate-claude-md`](#repowise-generate-claude-md-path) ·
-[`AGENTS.md`](#agentsmd)
-
-**Hooks and distill**
-[`distill`](#repowise-distill-command) ·
-[`expand`](#repowise-expand-ref) ·
-[`saved`](#repowise-saved-path) ·
-[`savings sync`](#repowise-savings-sync-path) ·
-[`corrections`](#repowise-corrections-path) ·
-[`hook install`](#repowise-hook-install) ·
-[`hook status`](#repowise-hook-status) ·
-[`hook uninstall`](#repowise-hook-uninstall) ·
-[`hook stats`](#repowise-hook-stats) ·
-[`hook backfill`](#repowise-hook-backfill) ·
-[`hook rewrite`](#repowise-hook-rewrite-installuninstallstatus) ·
-[`augment`](#repowise-augment)
-
-**Server**
-[`serve`](#repowise-serve-path) ·
-[`mcp`](#repowise-mcp-path)
-
-**Workspace**
-[`workspace list`](#repowise-workspace-list) ·
-[`workspace add`](#repowise-workspace-add-path) ·
-[`workspace remove`](#repowise-workspace-remove-alias) ·
-[`workspace scan`](#repowise-workspace-scan-path) ·
-[`workspace set-default`](#repowise-workspace-set-default-alias) ·
-[`workspace diagnostics`](#repowise-workspace-diagnostics) ·
-[`workspace check`](#repowise-workspace-check) ·
-[`workspace metrics`](#repowise-workspace-metrics-path) ·
-[`workspace impacted-tests`](#repowise-workspace-impacted-tests-repopath)
-
-**Maintenance**
-[`doctor`](#repowise-doctor-path) ·
-[`whats-new`](#repowise-whats-new) ·
-[`telemetry`](#repowise-telemetry) ·
-[`plugins`](#repowise-plugins) ·
-[`login`](#repowise-login) ·
-[`logout`](#repowise-logout) ·
-[`whoami`](#repowise-whoami) ·
-[`delete`](#repowise-delete-repo_id) ·
-[`uninstall`](#repowise-uninstall-path) ·
-[`costs`](#repowise-costs) ·
-[`export`](#repowise-export-path)
+Grouped by task; `PATH` and flags are in each command's section.
+
+- **Indexing:** [`init`](#repowise-init-path), [`update`](#repowise-update-path), [`generate`](#repowise-generate-path),
+ [`restyle`](#repowise-restyle-style-path), [`wiki-styles`](#repowise-wiki-styles-path),
+ [`watch`](#repowise-watch-path), [`reindex`](#repowise-reindex-path)
+- **Querying:** [`search`](#repowise-search-query-path), [`ask`](#repowise-ask-question),
+ [`context`](#repowise-context-targets), [`symbol`](#repowise-symbol-symbol_id), [`why`](#repowise-why-query), [shared
+ `ask`/`context`/`symbol`/`why` options](#shared-options-ask-context-symbol-why), [`status`](#repowise-status-path),
+ [`next`](#repowise-next-path)
+- **Health and risk:** [`health`](#repowise-health-path), [`health check`](#repowise-health-check-revspec),
+ [`risk`](#repowise-risk-revspec), [`overlap`](#repowise-overlap), [`dead-code`](#repowise-dead-code-path),
+ [`doc-drift`](#repowise-doc-drift-path), [`security`](#repowise-security), [`check`](#repowise-check-revspec),
+ [`impacted-tests`](#repowise-impacted-tests-revspec), [`coverage`](#repowise-coverage),
+ [`components`](#repowise-components), [`packages`](#repowise-packages), [`changes`](#repowise-changes),
+ [`suspects`](#repowise-suspects), [`events`](#repowise-events), [`report
+ assessment`](#repowise-report-assessment-path)
+- **Decisions:** [`decision`](#repowise-decision)
+- **Agent wiring:** [`agents`](#repowise-agents), [`generate-claude-md`](#repowise-generate-claude-md-path), [`AGENTS.md`](#agentsmd), [`attribution`](#repowise-attribution)
+- **Hooks and distill:** [`distill`](#repowise-distill-command), [`expand`](#repowise-expand-ref),
+ [`saved`](#repowise-saved-path), [`savings sync`](#repowise-savings-sync-path),
+ [`corrections`](#repowise-corrections-path), [`hook install`](#repowise-hook-install), [`hook
+ status`](#repowise-hook-status), [`hook uninstall`](#repowise-hook-uninstall), [`hook stats`](#repowise-hook-stats),
+ [`hook backfill`](#repowise-hook-backfill), [`hook rewrite`](#repowise-hook-rewrite-installuninstallstatus), [`hook
+ read-skeleton|search-digest|read-reread`](#repowise-hook-read-skeletonsearch-digestread-reread),
+ [`augment`](#repowise-augment)
+- **Server:** [`serve`](#repowise-serve-path), [`mcp`](#repowise-mcp-path)
+- **Workspace:** [`workspace list`](#repowise-workspace-list), [`workspace add`](#repowise-workspace-add-path),
+ [`workspace remove`](#repowise-workspace-remove-alias), [`workspace scan`](#repowise-workspace-scan-path), [`workspace
+ set-default`](#repowise-workspace-set-default-alias), [`workspace diagnostics`](#repowise-workspace-diagnostics),
+ [`workspace check`](#repowise-workspace-check), [`workspace metrics`](#repowise-workspace-metrics-path), [`workspace
+ impacted-tests`](#repowise-workspace-impacted-tests-repopath)
+- **Maintenance:** [`doctor`](#repowise-doctor-path), [`whats-new`](#repowise-whats-new),
+ [`telemetry`](#repowise-telemetry), [`plugins`](#repowise-plugins), [`config hints`](#repowise-config-hints-onoff),
+ [`login`](#repowise-login), [`logout`](#repowise-logout), [`whoami`](#repowise-whoami),
+ [`publish`](#repowise-publish-path), [`delete`](#repowise-delete-repo_id), [`uninstall`](#repowise-uninstall-path),
+ [`costs`](#repowise-costs), [`export`](#repowise-export-path)
---
## Workspace auto-detect (cross-cutting)
-Most commands auto-detect whether you're in a workspace root and route accordingly. When auto-detection fires, the command prints a one-line `[workspace] …` notice. You can always override:
+Most commands detect a workspace root and route to it, with a one-line `[workspace] …` notice.
-| Flag | Effect |
-|------|--------|
-| `--workspace` / `-w` | Force workspace mode. Errors if no `.repowise-workspace.yaml` is found. |
-| `--no-workspace` | Force single-repo mode even when invoked from a workspace root. |
-| `--repo <alias>` | Scope a workspace command to one repo. Available on commands where it makes sense. |
-| `--all` | Fan out across every workspace repo (on `costs`, `search`). |
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--workspace` / `-w` | Force workspace mode; errors without `.repowise-workspace.yaml`. | auto-detect |
+| `--no-workspace` | Force single-repo mode. | auto-detect |
+| `--repo <alias>` | Scope to one repo, where sensible. | all repos or primary, per command |
+| `--all` | Fan out across every repo (`costs`, `search`). | off |
-The commands that grew these flags: `update`, `status`, `watch`, `doctor`, `costs`, `search`, `dead-code`, `doc-drift`, `decision`, `coverage`, `generate-claude-md`, `hook install/status/uninstall`.
+- `--workspace`: `update`, `status`, `watch`, `doctor`, `generate-claude-md`, `hook` (install, status, uninstall,
+ rewrite, read-skeleton, search-digest, read-reread), `report assessment`/`inventory`/`changes`.
+- `--no-workspace`: those, plus `search`, `dead-code`, `doc-drift`, `costs`, `health`, `next`, `mcp`, `ask`, `context`, `symbol`, `why`.
+- `--repo`: `update`, `report`, and the `--no-workspace` extras except `mcp`.
---
@@ -116,347 +79,304 @@ The commands that grew these flags: `update`, `status`, `watch`, `doctor`, `cost
### `repowise init [PATH]`
-Index a codebase and generate wiki documentation. This is the starting point.
-
-**Single repo:**
-
-```bash
-cd your-project
-repowise init
-```
-
-**Multi-repo workspace:**
-
-```bash
-cd my-workspace/ # parent dir containing multiple git repos
-repowise init .
-```
-
-**What it does (4 phases):**
-
-1. **Ingestion**, walks every file, parses AST with tree-sitter, builds a two-tier dependency graph (file + symbol nodes), indexes git history (churn, hotspots, ownership, bus factor)
-2. **Analysis**, detects dead code, extracts architectural decisions from inline markers, READMEs, and git history. Runs Leiden community detection and execution flow tracing.
-3. **Generation**, generates file-level, module-level, and repo-level wiki pages, either by prompting the LLM or, with `--no-prose`, by rendering them from the parsed structure
-4. **Persistence**, stores everything in `.repowise/wiki.db`, builds search indexes, generates editor instruction files, registers MCP server and hooks
-
-In workspace mode, adds: repo scanning, per-repo indexing, cross-repo analysis (co-changes, contracts, package deps), workspace CLAUDE.md generation.
-
-**Plan screen.** Running `repowise init` on a TTY (no `--provider`, `--no-prose`, `--mode fast`, `--resume` or `--yes`) opens one screen with the repo scan, an ETA, the plan, and an opt-in model line with what a model adds and costs. Enter starts the free run (documentation built from code). `m` picks a model, `e` edits the plan (advanced options, the agent checklist, the post-commit hook, and keeping machine-specific files out of git through `.git/info/exclude`, off by default), `s` leaves the global MCP entry where it is, and `q` quits. In a folder of repos the screen lists them, and `r` chooses the repos and the primary.
-
-**Page volume.** File pages are rendered from structure and cost no model tokens, so what bounds them buys wiki size, embedding calls and less retrieval noise, never spend. Two numbers govern it, both derived from the size distribution of real indexed repos. Above **2,000** documentable files (p95), the plan screen's `e` step offers the top 2,000 by importance instead of one page per file, quoted in pages and megabytes; nothing is capped automatically at that size. Above **4,500** file pages (about 40 MB of file layer, near p99), every run holds the bucket to 4,500 and says so in its output, because that is where the tail is the difference between a wiki that publishes and one that does not. `--max-file-pages N` sets a cap directly and `--max-file-pages 0` refuses one; either way the answer is saved as `max_file_pages` in `config.yaml`, which `update --full` and `generate` honour. A hosted or scripted caller sets the same field with no terminal involved.
-
-If the screen reads EOF (common when an agent pipes stdin), init prints a notice and continues with defaults instead of aborting.
-
-**Cost gate.** Before any tokens are spent, init shows the estimate and asks for confirmation. It never prompts when stdin is not a TTY: it auto-declines, keeps the index it already built, and renders the structural wiki instead. The default answer is Yes up to $25 and flips to No above that.
-
-**Options:**
-
-| Flag | Description |
-|------|-------------|
-| `--provider` | LLM provider: `anthropic`, `openai`, `openrouter`, `gemini`, `deepseek`, `kimi`, `ollama`, `litellm`, `codex_cli`, `claude_cli`, `opencode`, `edenai`, `mock` |
-| `--model` | Model name override (e.g., `claude-sonnet-4-6`) |
-| `--embedder` | Embedder for semantic search: `gemini`, `openai`, `openrouter`, `ollama`, `edenai`, `mock` (default: auto-detect) |
-| `--prose` / `--no-prose` | The single knob over LLM spend. The file, symbol, cycle (SCC), API and infra pages are rendered from structure either way, with no key and no cost. The model-written set is the subsystem (concept) tree plus the repo overview, the architecture diagram, and the onboarding collection: `--prose` writes those as model prose and needs a key; `--no-prose` leaves them as structural stubs, so the whole wiki is keyless and free. Default: prose when a key is available. Full-text search works either way; semantic search needs an embedder. `--no-prose` makes no model calls even when a key is set, so decision extraction from PRs, commit history and comments waits for a model run. Fill or refill that prose, and add those decisions, later with [`repowise generate`](#repowise-generate-path). |
-| `--index-only` | Deprecated hidden alias for `--no-prose`. |
-| `--docs` | Deprecated hidden alias: `--docs llm` == `--prose`, `--docs deterministic` == `--no-prose`. Prefer `--prose` / `--no-prose`. |
-| `--mode` | Pipeline depth: `standard` (default) or `fast` (graph + essential-git only, no per-file blame/co-change, no LLM docs, for very large repos; upgrade later with `update --full`) |
-| `--skip-tests` | Exclude test files from doc generation |
-| `--skip-infra` | Exclude infrastructure files (Dockerfiles, Makefiles, Terraform) |
-| `--exclude` / `-x` | Gitignore-style exclusion pattern. Repeatable. |
-| `--include-submodules` | Include git submodule directories (excluded by default) |
-| `--concurrency` | Max concurrent LLM calls (default: 10) |
-| `--reasoning` | Reasoning mode for supported providers: `auto`, `off`/`none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` (default: `auto`) |
-| `--max-file-pages` | Most file pages to emit, highest importance first. Omit to let the size policy decide (see Page volume above), `0` for one page per eligible file however many that is, or a positive number for a hard cap. Saved to `config.yaml`. |
-| `--coverage-report` | Test-coverage report to ingest (LCOV / Cobertura / Clover / JaCoCo / Go coverprofile). Repeatable. Auto-discovered when omitted. This is test coverage for code-health, not a documentation-breadth knob: every code file is documented either way. |
-| `--onboarding` / `--no-onboarding` | Generate the curated Onboarding collection (up to 8 overview pages). Default: on; slots without enough signal are skipped. |
-| `--wiki-style` | Documentation voice/density: `comprehensive` (default), `caveman` (token-condensed, AI-first), `reference` (API-manual), `tutorial` (beginner-friendly). Interactive full runs prompt when omitted. Saved to config so `update` keeps the style. See [WIKI.md](../layers/WIKI.md#styles). |
-| `--language` | Output language for generated wiki pages: `en` (default), `ar`, `de`, `es`, `fr`, `hi`, `it`, `ja`, `ko`, `nl`, `pl`, `pt`, `ru`, `tr`, `zh`. Code, file paths, and symbol names stay untranslated. Saved to config so `update` keeps the language. Also asked in advanced interactive mode. To switch an existing wiki's language, set the flag and re-run `init --force`. |
-| `--resume` | Continue a previous run instead of redoing it: completed phases (indexing, analysis) are skipped, the earlier run's git tier is kept, and generation writes only the pages this repo does not have yet. Use it after an interrupted run, and after one that finished with failed pages (a provider outage, rate limiting) — pages already written are skipped with no model call, so nothing is paid for twice. Matching is per page, not per model, so switching provider still keeps what the old one wrote. |
-| `--force` | Regenerate all pages even if they exist. Re-indexes this checkout from scratch in the mode you invoked, so inside a linked worktree it also skips seeding (a re-index is what seeding exists to avoid) and runs as a normal full init. Never triggers a model: `--force --no-prose` re-renders the whole wiki from templates at no cost. Use `repowise update --full` to regenerate with a model. |
-| `--commit-limit` | Max commits to analyze per file (default: 5000, capped at 10000) |
-| `--follow-renames` | Track file renames in git history |
-| `--no-claude-md` | Don't generate `CLAUDE.md` |
-| `--agents` / `--no-agents` | Generate or skip managed `AGENTS.md` for Codex. Persists the preference. |
-| `--codex` / `--no-codex` | Generate or skip project-local Codex MCP/hooks setup. Interactive runs prompt when Codex CLI is installed and logged in; non-interactive runs require `--codex`. |
-| `--distill-hook` / `--no-distill-hook` | Install or skip the Distill command-rewrite hook (Claude Code PreToolUse). Strictly opt-in: interactive runs prompt (default No); `--no-distill-hook` also gates the repo off in config so a globally installed hook stays inert here. In workspace mode the verdict applies to every selected repo. See [DISTILL.md](../agent/DISTILL.md). |
-| `--hook` / `--no-hook` | Install or skip the post-commit hook that runs `repowise update` after each commit. Default: on. Interactive runs ask; `--yes` and non-interactive runs install it and print how to undo it (`repowise hook uninstall`). `--no-editor-setup` skips it too, since a git hook is a write outside `.repowise/`. In workspace mode the choice applies to every selected repo. |
-| `--editor-setup` / `--no-editor-setup` | Wire repowise into your editors, both halves at once. Machine-wide: the Claude Code (`~/.claude/settings.json`) and Claude Desktop MCP server entry, plus the Claude Code PostToolUse/SessionStart hooks. Project-local: `.mcp.json`, `.claude/CLAUDE.md`, `.vscode/mcp.json`, `.vscode/extensions.json`. Default: on. `--no-editor-setup` indexes the repo writing nothing into it and nothing outside it — only `.repowise/` is touched — which is what you want for a scratch checkout, a throwaway venv, a git worktree, or a CI run: each config holds a single `repowise` MCP key, so a second `init` repoints it at the newest repo instead of adding a second entry. `repowise mcp .` still prints the config to connect a client by hand. It also skips the post-commit auto-sync hook (a write into the git hooks directory) and the `--distill-hook` offer, which installs a user-level hook; `--no-distill-hook`, `--no-claude-md` and `--no-agents-md` still record their opt-outs in this repo's config, because those flags mean "never", not "not this run". `REPOWISE_SKIP_EDITOR_SETUP=1` is the same switch for CI and sandboxes, and it wins: with it set, an explicit `--editor-setup` does not turn setup back on. |
-| `--save-key` / `--no-save-key` | Save the provider API key this run authenticated with into `.repowise/.env` (git-ignored, owner-only). Default: on, because a scripted `init` that succeeds must leave a repo whose MCP server can actually answer, and a key supplied through the environment would otherwise vanish with the shell that set it. The file is what `repowise mcp`, `serve` and `update` read back; without it `get_answer` degrades to `no-llm-provider` and returns retrieval-only output. Use `--no-save-key` when the key is injected per-process (CI secrets, a shared machine) and must not reach disk; `REPOWISE_NO_SAVE_KEY=1` is the same switch for CI and sandboxes. Answering No to the interactive key prompt also wins over the default. Note this writes one line to the repo's `.gitignore`, so pair it with `--no-save-key` when you need `--no-editor-setup`'s "nothing written into the repo" guarantee. |
-| `--seed-from` | Seed the index from an explicit base checkout instead of the auto-detected one. Rarely needed: inside a linked git worktree the base is detected and seeded automatically. See [WORKTREES.md](../scale/WORKTREES.md). |
-| `--no-seed` | Disable worktree auto-seeding and run a full init even inside a linked worktree. |
-| `--yes` / `-y` | Skip the plan screen and every question, with each answer at its default. A model writes the documentation only when a provider is configured; a logged-in Claude Code, Codex or OpenCode is used only with `--provider`. Add `--no-prose` to guarantee no model calls |
-| `--dry-run` | Show the generation plan and cost estimate. Writes no wiki |
-| `--test-run` | Write docs with the model for only the top 10 files (by PageRank). Not with `--no-prose` or `--mode fast` |
-| `--all` | In a folder with several repos, index every detected repo without prompting. `--yes` and a piped stdin do the same and print which repos they took |
-| `--repos` | In a folder with several repos, index only these, with no picker: `--repos api,web`. Each name is a repo's alias, directory name, or its path relative to the folder when two repos share a name. In a new workspace the first one listed is primary; an existing workspace keeps its primary. An unknown name stops the run and lists the available ones |
-| `--no-workspace` | Force single-repo mode even when invoked from a workspace root (indexes only the target PATH instead of fanning out across workspace repos) |
-| `--progress` | `rich` (default): a live checklist in a terminal, one short line per step (at most 100 columns) anywhere else. `json`: one JSON event per line on stdout, ending with a summary line; see below. |
-
-**Examples:**
-
-```bash
-repowise init # interactive
-repowise init --provider anthropic --yes # automated
-repowise init --provider codex_cli --codex --yes # use authenticated Codex CLI
-repowise init --provider opencode --yes # use local OpenCode CLI
-repowise init --no-prose # free, wiki rendered from structure
-repowise init --dry-run # preview cost
-repowise init --test-run # quick test (10 files)
-repowise init --provider openai --model qwen3 --reasoning off
-repowise init --provider openrouter --model openai/gpt-5 --reasoning minimal
-repowise init --language zh # wiki docs in Chinese
-repowise init -x vendor/ -x "*.gen.go" # exclude patterns
-repowise init --include-submodules # include submodules
-repowise init --no-codex --no-agents # skip Codex project files
-repowise init --no-editor-setup --yes # index only, leave global MCP config alone
-repowise init --provider openai --yes --no-save-key # CI: index, but never write the key to disk
-repowise init . # workspace mode
-repowise init . --no-prose -x "node_modules/" # workspace, no LLM
-repowise init . --yes --repos api,web # workspace, two of its repos
-repowise init . --no-workspace # force single-repo, even in a workspace root
-```
-
-**Exit codes.** `0` ready. `2` finished with gaps: everything is saved, and the
-last line names what is missing and the command that adds it (for example
-documentation built from code because the cost estimate needed confirmation and
-there was no terminal, so re-run with `--yes`). `130` interrupted: run
-`repowise init --resume` to continue. Any other non-zero code is a failure; a
-usage error (a bad flag) also exits `2`, before anything runs.
-
-**Driving init from an agent or script.** `repowise init --yes --no-prose --progress json`
-writes only JSON lines to stdout; human text goes to stderr. Every line has `v`
-(schema version, `1`) and `event`: `stage`, `phase` (`state` is `start`, `done`
-or `failed`, with `completed`, `total`, `unit` and `elapsed_s`), `warning`, and
-last `summary`. The summary's `status` is `ready`, `degraded`, `interrupted` or
-`failed`, matching exit `0`, `2`, `130` or any other code, and it carries
-`mode` (`key` from the index scope, `label`, `run_mode`), `restart_required`
-(the editor needs a restart or `/mcp` to load the tools), `spend` (`tokens`,
-`usd`), `warnings`, `files_written` and `next` (commands, `repowise serve` first).
-
-With a real embedder (anything but `mock`), a run whose page vectors fail to
-write, for example because the LanceDB install is broken, keeps its pages and
-full-text index, records `search.semantic: unavailable` in the index scope, and
-exits `2` naming the fix: reinstall the dependency, then `repowise reindex`. A
-workspace `init` exits `2` after saving every repo, naming the repos with gaps.
-`update` exits `1` on a failed embed. The keyless `mock` embedder never fails a
-run this way.
-
-**Documentation output limit.** Set `max_tokens` in
-`.repowise/config.yaml` to bound each model-written page. It is persistent, not
-a per-run flag, and is honored by `init`, `update`, `generate`, `restyle`,
-workspace generation, and server-triggered generation. See
-[Configuration](CONFIG.md#configyaml).
+Index a codebase and generate its wiki; the starting point.
+
+```bash
+repowise init # interactive
+repowise init --provider codex_cli --codex --yes # authenticated Codex CLI
+repowise init --no-prose -x vendor/ -x "*.gen.go" # free, wiki from structure
+repowise init --provider openai --yes --no-save-key # CI: key never on disk
+repowise init . --yes --repos api,web # workspace dir, two of its repos
+```
+
+**Phases.** (1) Ingestion: tree-sitter ASTs, file and symbol dependency graph, git history (churn, hotspots, ownership,
+bus factor). (2) Analysis: dead code, decisions (inline markers, READMEs, git), Leiden communities, execution flows. (3)
+Generation: file, module, repo pages (LLM, or structure with `--no-prose`). (4) Persistence: `.repowise/wiki.db`, search
+indexes, editor files, MCP server, hooks.
+
+Workspaces add repo scanning, per-repo indexing, cross-repo analysis (co-changes, contracts, package deps), workspace CLAUDE.md.
+
+**Model, content and scope**
+
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--provider` | `anthropic`, `openai`, `openrouter`, `gemini`, `deepseek`, `kimi`, `ollama`, `litellm`, `codex_cli`, `copilot_cli`, `claude_cli`, `opencode`, `edenai`, `mock`. Terminals prompt for a missing key (`openai`: plus optional compatible base URL). | from environment |
+| `--model` | Model (e.g. `claude-sonnet-4-6`). | provider default |
+| `--embedder` | `gemini`, `openai`, `openrouter`, `ollama`, `edenai`, `mock`. | auto-detect |
+| `--prose` / `--no-prose` | The one LLM-spend knob; see notes. | prose when a key exists |
+| `--index-only` | Deprecated hidden alias of `--no-prose`. | |
+| `--docs` | Deprecated hidden alias: `llm` = `--prose`, `deterministic` = `--no-prose`. | |
+| `--mode` | `standard`, or `fast` (graph and essential git; no per-file blame, co-change or LLM docs; for very large repos; upgrade with `update --full`). | `standard` |
+| `--reasoning` | `auto`, `off`/`none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` (supported providers). | `auto` |
+| `--concurrency` | Max concurrent LLM calls. | `10` |
+| `--wiki-style` | `comprehensive`, `caveman` (token-condensed, AI-first), `reference` (API manual), `tutorial` (beginner). Saved for `update`. [WIKI.md](../layers/WIKI.md#styles). | `comprehensive`; interactive full runs prompt |
+| `--language` | `en`, `ar`, `de`, `es`, `fr`, `hi`, `it`, `ja`, `ko`, `nl`, `pl`, `pt`, `ru`, `tr`, `zh`. Saved for `update`. Code, paths, symbols untranslated. Advanced mode asks. Switch: `init --force`. | `en` |
+| `--onboarding` / `--no-onboarding` | Onboarding collection (up to 8 pages); see notes. | on |
+| `--max-file-pages` | File-page cap by importance; `0`: no cap, a page per eligible file. Saved to `config.yaml`. | size policy (Page volume) |
+| `--test-run` | Model docs for top 10 files by PageRank. Not with `--no-prose` or `--mode fast`. | off |
+| `--dry-run` | Plan and cost estimate; no wiki. | off |
+| `--exclude` / `-x` | Gitignore-style pattern. Repeatable. | |
+| `--skip-tests` | No docs for test files. | off |
+| `--skip-infra` | No docs for infra (Dockerfiles, Makefiles, Terraform). | off |
+| `--include-submodules` | Include git submodules. | excluded |
+| `--coverage-report` | LCOV, Cobertura, Clover, JaCoCo, Go coverprofile. Repeatable. Feeds code health only; every code file is documented regardless. | auto-discovered |
+| `--commit-limit` | Max commits per file and for co-change; cap 10000. Saved. | `5000` |
+| `--follow-renames` | Track renames via `git log --follow` (slower, more accurate). Saved. | off |
+| `--resume` | Continue a previous run; see notes. | off |
+| `--force` | Regenerate all pages; see notes. | off |
+| `--seed-from` | Explicit base checkout to seed from; rarely needed (linked worktrees auto-seed). [WORKTREES.md](../scale/WORKTREES.md). | auto-detected base |
+| `--no-seed` | Full init even in a linked worktree. | seeding on |
+
+**Agent wiring and running**
+
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--no-claude-md` | Skip `CLAUDE.md`; saves `editor_files.claude_md: false`. | generated |
+| `--agents` / `--no-agents` | Managed Codex `AGENTS.md`. Persists. | config, else on |
+| `--codex` / `--no-codex` | Project-local Codex MCP and hooks. Required for non-interactive runs. | prompt if Codex CLI is logged in |
+| `--distill-hook` / `--no-distill-hook` | Distill hooks (Claude Code PreToolUse) compacting what the agent sees; notes, [DISTILL.md](../agent/DISTILL.md). | off; interactive prompt (default No) |
+| `--hook` / `--no-hook` | Post-commit `repowise update` hook; see notes. | on |
+| `--editor-setup` / `--no-editor-setup` | Editor wiring; see notes. | on |
+| `--save-key` / `--no-save-key` | Save the run's key to `.repowise/.env` (git-ignored, owner-only); see notes. | on |
+| `--yes` / `-y` | No plan screen, all defaults; see notes. | off |
+| `--all` | Folder of repos: index all (as do `--yes` and piped stdin, printing the repos taken). | picker |
+| `--repos` | Folder of repos: only these (`api,web`); see notes. | picker |
+| `--no-workspace` | Index only PATH from a workspace root. | auto-detect |
+| `--progress` | `rich`: live checklist (TTY), else one line per step (max 100 columns). `json`: JSON event lines on stdout, ending in a summary. | `rich` |
+| `--no-cost-tracking` | Skip DB-backed LLM cost tracking. | tracking on |
+| `-v`, `--verbose` | Per-phase internals, debug logs (else debug and info logs are suppressed). | off |
+
+**Flag notes**
+
+- **`--prose` / `--no-prose`.** File, symbol, cycle (SCC), API, infra pages: always from structure, free.
+ - Model set: subsystem (concept) tree, repo overview, architecture diagram, onboarding. `--prose` writes it (key needed); `--no-prose` leaves stubs.
+ - `--no-prose` makes no model calls even with a key, so decision extraction from PRs, commits and comments waits; [`repowise generate`](#repowise-generate-path) fills both later.
+ - Full-text search always; semantic search needs an embedder.
+- **`--onboarding`.** Slots: Project Overview, Architecture Guide, Getting Started, Codebase Map, Key Concepts, How It Works, Development Guide, Active Landscape; thin ones skipped.
+- **`--resume`.** No-op when fully indexed. Skips done phases (indexing, analysis), keeps the git tier, writes only
+ missing pages, never paying twice: for interrupted runs or failed pages (outage, rate limits). Per-page matching
+ survives provider switches.
+- **`--force`.** Re-indexes from scratch in the invoked mode, skipping worktree seeding. Never calls a model (`--force --no-prose` re-renders free); `repowise update --full` does.
+- **`--distill-hook`.** One consent, four behaviours: noisy commands (tests, builds, git, searches) run through
+ `repowise distill`; whole-file Reads return a skeleton (`hooks.read_skeleton`); many-file greps a per-file digest
+ (`hooks.search_digest`); re-reads of unchanged, unedited files a pointer (`hooks.read_reread`). `--no-distill-hook`
+ also gates the repo off in config, keeping a global hook inert.
+- **`--hook`.** Asked interactively; `--yes` and non-interactive runs install it, printing the undo (`repowise hook uninstall`).
+- **Workspace.** `--distill-hook` and `--hook` apply to every selected repo.
+- **`--editor-setup`.** Machine-wide: Claude Code (`~/.claude/settings.json`) and Claude Desktop MCP entry, Claude Code
+ PostToolUse/SessionStart hooks. Repo: `.mcp.json`, `.claude/CLAUDE.md`, `.vscode/mcp.json`, `.vscode/extensions.json`.
+- **`--no-editor-setup`.** Writes only `.repowise/` (scratch checkouts, throwaway venvs, worktrees, CI); skips the post-commit hook (git hooks dir) and `--distill-hook` offer (user-level hook).
+ - One `repowise` MCP key per config, so a second `init` repoints it; `repowise mcp .` prints config for manual setup.
+ - `--no-distill-hook`, `--no-claude-md`, `--no-agents` still save to repo config: they mean "never".
+ - `REPOWISE_SKIP_EDITOR_SETUP=1`: same switch, beats `--editor-setup`.
+- **`--save-key`.** On so scripted `init` leaves an answering MCP server (env keys die with their shell). Read by
+ `repowise mcp`, `serve`, `update`; without it `get_answer` degrades to `no-llm-provider` (retrieval-only).
+ - `--no-save-key` or `REPOWISE_NO_SAVE_KEY=1` for per-process keys (CI secrets, shared machines); a No at the key prompt also wins.
+ - Adds a `.gitignore` line, so use `--no-save-key` for `--no-editor-setup`'s nothing-in-the-repo guarantee.
+- **`--yes`.** Model docs only with a configured provider (key in env or `.repowise/.env`), else from code; logged-in
+ Claude Code, Codex or OpenCode needs `--provider`; `--no-prose` guarantees no model calls.
+ - Accepts the cost prompt; advanced defaults (standard mode at any size, comprehensive style); connects detected agents; repoints the global MCP entry here, printing old and new.
+ - Installs the post-commit hook, not distill. With `--no-prose`, replaces model-written docs unasked.
+- **`--repos`.** Alias, directory name, or relative path (for duplicates). First listed is a new workspace's primary; existing ones keep theirs. Unknown names stop the run, listing options.
+
+**Plan screen.** TTY runs without `--provider`, `--no-prose`, `--mode fast`, `--resume` or `--yes` show scan, ETA, plan,
+and an opt-in model line (adds, costs). EOF (agent-piped stdin): notice, then defaults. Keys:
+
+- Enter: free run (docs from code). `m`: pick a model. `s`: leave the global MCP entry. `q`: quit.
+- `e`: edit plan (advanced options, agent checklist, post-commit hook, `.git/info/exclude` for machine-specific files, off).
+- `r`: folder of repos (listed): pick repos and primary.
+
+**Page volume.** File pages cost no tokens; caps cut wiki size, embeddings, retrieval noise. Thresholds from real repos:
+
+- Over **2,000** documentable files (p95): the `e` step offers the top 2,000 by importance, in pages and MB. No automatic cap.
+- Over **4,500** file pages (~40 MB, near p99): every run caps at 4,500 and says so; beyond it a wiki may not publish.
+- `--max-file-pages` sets `max_file_pages` in `config.yaml`, honoured by `update --full` and `generate`; hosted or scripted callers set it directly.
+
+**Cost gate.** Confirms the estimate before spending (Yes up to $25, No above). No TTY: declines unprompted, keeps the index, renders the structural wiki.
+
+**Exit codes.**
+
+- `0` ready; `130` interrupted (`repowise init --resume`); other non-zero: failure.
+- `2`: gaps, all saved; the last line names the gap and fix (e.g. docs from code as the cost prompt needed a terminal: re-run with `--yes`). Also usage errors, before running.
+- Real-embedder vector-write failure (e.g. broken LanceDB): pages and full-text kept, index scope gets `search.semantic:
+ unavailable`, exit `2` names the fix (reinstall, `repowise reindex`). Keyless `mock` never fails so.
+- Workspace `init` exits `2` after saving every repo, naming those with gaps. `update` exits `1` on a failed embed.
+
+<details><summary>Driving init from an agent or script</summary>
+
+`repowise init --yes --no-prose --progress json`: JSON lines on stdout, human text on stderr.
+
+- Each line: `v` (schema, `1`), `event` (`stage`, `phase`, `warning`, last `summary`). `phase`: `state` (`start`/`done`/`failed`), `completed`, `total`, `unit`, `elapsed_s`.
+- `summary`: `status` (`ready`/`degraded`/`interrupted`/`failed` = exit `0`/`2`/`130`/other), `mode` (`key` from index
+ scope, `label`, `run_mode`), `restart_required` (restart or `/mcp` to load tools), `spend` (`tokens`, `usd`),
+ `warnings`, `files_written`, `next` (commands, `repowise serve` first).
+
+</details>
+
+**Documentation output limit.** `max_tokens` in `.repowise/config.yaml` (not a flag) caps each model page for `init`,
+`update`, `generate`, `restyle`, workspace and server generation. See [Configuration](CONFIG.md#configyaml).
---
### `repowise update [PATH]`
-Incrementally refresh the index for files changed since the last sync: the
-dependency graph, git metadata, health and dead-code findings, and, when the
-graph shape changed, the knowledge graph (layers, guided tour, entry points)
-plus the exported `knowledge-graph.json`. In docs mode it also regenerates the
-affected wiki pages. Index-only updates carry forward the previously generated
-layer names and node summaries, so no LLM call is ever made without docs mode.
-
-Docs-mode updates (and `init`) can also mine local coding-agent session
-transcripts for durable decisions: user corrections, explicit choices with a
-stated reason, and failed approaches replaced by working ones. Candidates
-pass deterministic gates and a verbatim-quote grounding check; a decision
-observed in two or more sessions (or one direct user correction) is promoted
-into the decision records with `source: session`. Everything stays on your
-machine. **This lane is off by default**; `repowise decision source set session
---on` enables it (see [CONFIG.md](CONFIG.md)).
-
-If any best-effort step fails (git metadata, decisions, dead code, ...), the
-run still exits 0 but lists the degraded steps in the completion panel (and in
-the `done` event's `degraded` array with `--progress json`); the next update
-retries them. In docs mode each regenerated page is persisted as it completes,
-so an interrupted run never pays for the finished pages again, the rerun's
-prompt-hash check skips them.
-
-Inside an unindexed linked git worktree, `update` first seeds the index from
-the base checkout automatically, then proceeds with the incremental update.
-See [WORKTREES.md](../scale/WORKTREES.md).
-
-**Options:**
-
-| Flag | Description |
-|------|-------------|
-| `--provider` | Override LLM provider for this run |
-| `--model` | Override model |
-| `--since` | Git ref to diff from (overrides `state.json`) |
-| `--reasoning` | Reasoning mode for supported providers: `auto`, `off`/`none`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max` |
-| `--cascade-budget` | Max pages to regenerate (default: auto) |
-| `--dry-run` | Show what would be updated without regenerating |
-| `--workspace` / `-w` | Update all stale repos in the workspace + cross-repo analysis. Each repo picks docs vs index-only the same way a single-repo update does, from its own persisted `docs_enabled` plus any `--docs` / `--no-docs` / `--index-only` override on the command. Docs repos regenerate through the full single-repo docs path (pages, diagrams, decisions) so a workspace wiki stays as fresh as one updated repo by repo; the rest take the fast parallel index-only path. |
-| `--no-workspace` | Force single-repo mode (handy when running from a workspace root) |
-| `--repo` | Update a specific workspace repo by alias |
-| `--index-only` | Refresh the index only, skip doc regeneration for this run. In workspace mode, forces every stale repo to index-only. |
-| `--working-tree` | Also index uncommitted work (staged, unstaged and untracked files) on top of the commits since the last sync, so a rename you have not committed yet shows up in the graph. Off by default, so hooks and plain `update` stay anchored to commits. In workspace mode a repo with uncommitted changes counts as stale and is updated the same way. `repowise watch` always does this. |
-| `--docs` / `--no-docs` | Regenerate wiki pages for changed files, or skip doc regeneration entirely. Works in workspace mode too: `--docs` fans out to every stale repo's docs update (each needs an LLM provider/key configured, or pass `--provider`), and `--no-docs` forces index-only across the workspace. Without either flag each repo follows its own `docs_enabled`. |
-| `--full` | Upgrade a fast (`--mode fast`) index to a full one, see below. Single-repo only; errors in workspace mode. |
-| `--no-cost-tracking` | Don't record LLM spend for this run |
-| `--agents` / `--no-agents` | Generate or skip managed `AGENTS.md` after update. Persists the preference. |
-| `-v`, `--verbose` | Show the full changed-file list and per-phase internals (cascade budget, decision-marker/evolution counts, best-effort skip warnings, detailed generation report). Off by default for a compact summary. |
-| `--progress` | `rich` (default) for the interactive progress bar, or `json` for newline-delimited JSON events on stdout (for driving update from another process) |
-
-**First-time indexing:** `update --workspace` runs full first-time indexing for workspace entries that have no `.repowise/` dir yet (previously skipped with `"not_indexed"`). The pipeline runs index-only, no LLM cost, and writes a state.json marker. Doc generation then follows on the next update once the repo has an index: pass `--docs` (or set its `docs_enabled`) and it regenerates pages like any other member.
-
-**Upgrading a fast index to full (`--full`):** a repo first indexed with `repowise init --mode fast` has the full dependency graph + metrics persisted, but only the *essential* git tier (last commits, no per-file blame or co-change) and no model-written docs. `repowise update --full` upgrades it **incrementally**: it backfills the git tier to FULL using a resumable checkpoint, reuses the persisted graph, builds the missing documentation, rebuilds full-text search, embeds pages when the resolved embedder is available, and recomputes health against FULL history. The command records the transition before work and checkpoints each completed stage; failure or cancellation leaves the prior scope truthful and a retryable upgrade instead of stamping the repository full early. Persisted provider/model/embedder choices are reused when valid, overrides remain explicit, and estimated model cost is shown before paid generation. If embedding is unavailable the completed scope says so and gives the exact recovery command, `repowise reindex`; it never implies semantic search was built. It needs no key: with no model configured the documentation is built from code, with no model calls and no spend, and the embedder stays the free one unless you chose another. With a model configured, the model writes it. One repo at a time; in a workspace, pass `--repo <alias>`.
-
-`state.json:index_scope` is the canonical machine-readable description used by `status --format json`, `/api/repos`, generated agent guidance, and MCP `_meta.index_scope`. It separately records run mode, content provenance (`none`, `template`, or `model`), Git tier, configured commit cap, achieved Git-history coverage, configured/effective file-page caps, eligible/generated/omitted file-page counts, unavailable/skipped analysis, search availability, provider choices, and upgrade state. Older indexes project missing facts as `unknown`/`null`; a configured cap is never reported as achieved coverage and a missing analysis result is never reported as a clean result.
-
-Over MCP, an ordinary tool response carries a **compact projection** of this object rather than all of it: the run mode, content provenance, Git tier, a `status` of `complete`, `partial`, `degraded`, `upgrading` or `unknown`, the names of any degraded analyses, and a `fingerprint` identifying the canonical object. `get_overview(include=["scope"])` carries the canonical object in full, with the same `fingerprint` beside it, so a held copy can be checked against a later digest without either side resending it. `status` reaches `complete` only when the evidence exists and is clean; an index whose coverage was never recorded reports `unknown`. Since `_meta` contract 3 an ordinary response leaves a `complete` digest out, so only a gap rides on it. Set `REPOWISE_MCP_INDEX_SCOPE=full` to put the canonical object on every MCP response, as builds before `_meta.contract_version` 2 did.
-
-**Examples:**
+Refresh the index for files changed since the last sync, plus affected wiki pages in docs mode.
```bash
repowise update # diff since last sync
-repowise update --dry-run # preview
-repowise update --since v1.0.0 # diff from a tag
-repowise update --working-tree # include uncommitted edits
-repowise update --reasoning off # one-off supported-provider thinking-off run
-repowise update --workspace # all workspace repos (docs where enabled, incl. first-time indexing)
-repowise update --workspace --docs # force docs regeneration across every stale repo
-repowise update --repo backend # specific workspace repo
-repowise update --no-workspace # force single-repo mode in a workspace root
-repowise update -v # verbose: full file list + per-phase internals
-repowise update --full --provider anthropic # upgrade a fast index to full
-```
+repowise update --since v1.0.0 --working-tree
+repowise update --workspace --docs # every stale repo, docs forced
+repowise update --repo backend # one workspace repo
+repowise update --full --provider anthropic # fast index to full
+```
+
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--provider` / `--model` | Override for this run. | persisted choice |
+| `--reasoning` | Same choices as `init`. | |
+| `--since` | Git ref to diff from (overrides `state.json`). | last sync |
+| `--cascade-budget` | Max pages to regenerate. | auto-scaled |
+| `--concurrency` | Max concurrent LLM calls. | `10` |
+| `--yes` / `-y` | Skip the `--full` cost prompt. | off |
+| `--dry-run` | Preview only. | off |
+| `--docs` / `--no-docs` | This run: `--docs` LLM-regenerates changed pages (even if indexed without docs); `--no-docs` = `--index-only`. | `docs_mode` in `.repowise/state.json` (from `init`) |
+| `--index-only` | No doc regeneration; in a workspace, for every stale repo. | off |
+| `--working-tree` | Also index staged, unstaged, untracked work; see notes. | off |
+| `--full` | Fast (`--mode fast`) index to full (below). Errors in workspace mode. | off |
+| `--workspace` / `-w` | All stale workspace repos plus cross-repo analysis; see notes. | auto-detect |
+| `--repo` | One workspace repo by alias (implies `--workspace`). | |
+| `--no-cost-tracking` | Don't record spend; see notes. | tracking on |
+| `--agents` / `--no-agents` | Managed `AGENTS.md` after update. Persists. | |
+| `-v`, `--verbose` | Changed-file list, per-phase internals (cascade budget, decision-marker and evolution counts, best-effort skip warnings, generation report), debug logs. | compact summary |
+| `--progress` | `rich` bar, or `json` events on stdout for another process. | `rich` |
+
+**What it refreshes.** Graph, git metadata, health, dead code; on graph-shape changes, the knowledge graph (layers, guided tour, entry points) and `knowledge-graph.json`.
+
+- Index-only runs reuse stored layer names and node summaries (no LLM call). Docs mode saves pages as they finish; reruns skip them by prompt hash.
+- Failed best-effort steps (git metadata, decisions, dead code, ...) still exit 0, listed in the completion panel and `done` event's `degraded` array (`--progress json`); the next update retries.
+- Unindexed linked worktrees seed from the base checkout first ([WORKTREES.md](../scale/WORKTREES.md)).
+
+**Flag notes**
+
+- **`--working-tree`.** Uncommitted renames reach the graph. Off so hooks and plain runs stay commit-anchored. Workspace: uncommitted changes make a repo stale. `repowise watch` always does this.
+- **`--workspace`.** Each repo's `docs_mode` (`docs_enabled` beside it) plus `--docs` / `--no-docs` / `--index-only`
+ picks docs or index-only. `--docs` needs each repo's provider and key (or `--provider`).
+ - Docs repos run the full single-repo docs path (pages, diagrams, decisions); others the fast parallel index-only path.
+ - Entries without `.repowise/` get first-time indexing (index-only, free, `state.json` marker); docs follow on a later `--docs` run or `docs_enabled`.
+- **`--no-cost-tracking`.** No second `wiki.db` engine contending with generation; live readout stays, `repowise costs` history is skipped. Also `REPOWISE_NO_COST_TRACKING`.
+
+**Session decisions.** Docs-mode updates (and `init`) can mine local agent transcripts for user corrections, reasoned
+choices, failed approaches replaced by working ones. Past deterministic gates and a verbatim-quote grounding check, 2+
+sessions (or one direct correction) promote a decision (`source: session`). Local only; **off by default**: `repowise
+decision source set session --on` ([CONFIG.md](CONFIG.md)).
+
+**Upgrading a fast index to full (`--full`).** A `--mode fast` index has the full graph and metrics, but *essential* git
+only (last commits, no per-file blame or co-change) and no model docs. `update --full` upgrades **incrementally**:
+
+- Backfills git to FULL from a resumable checkpoint, reuses the graph, builds missing docs, rebuilds full-text search, embeds pages if possible, recomputes health on FULL history.
+- Records the transition first and checkpoints each stage: failure leaves the prior scope truthful and retryable, never marked full early.
+- Reuses valid persisted provider, model, embedder; overrides explicit; shows model cost before paid generation. Unavailable embedding is stated in the scope with the fix, `repowise reindex`.
+- No key needed: without a model, docs come from code (no spend), embedder stays free unless chosen; else the model writes them. One repo at a time (`--repo <alias>` in a workspace).
+
+<details><summary>Index scope and its MCP projection</summary>
+
+**Index scope (`state.json:index_scope`).** Canonical index description for `status --format json`, `/api/repos`, agent guidance, MCP `_meta.index_scope`.
+
+- Run mode, content provenance (`none`, `template`, `model`), Git tier, configured commit cap, achieved Git coverage,
+ configured/effective file-page caps, eligible/generated/omitted file-page counts, unavailable or skipped analysis,
+ search availability, provider choices, upgrade state.
+- Older indexes show `unknown`/`null`. Caps never count as achieved coverage, nor missing analysis as clean.
+
+**Index scope over MCP.** A **compact projection**: run mode, provenance, Git tier, `status`, degraded analyses, canonical-object `fingerprint`.
+
+- `status`: `complete` (evidence exists and is clean), `partial`, `degraded`, `upgrading`, `unknown` (coverage never recorded).
+- `get_overview(include=["scope"])`: full object plus `fingerprint`, so held copies check against later digests.
+- Since `_meta` contract 3 a `complete` digest is omitted; only gaps ride.
+- `REPOWISE_MCP_INDEX_SCOPE=full` always sends the full object, as builds before `_meta.contract_version` 2 did.
+
+</details>
---
### `repowise generate [PATH]`
-Write the subsystem (concept) pages with a model, on demand. This is the upgrade
-path for a `--no-prose` repo: it fills the subsystem stubs with model prose, one
-page, one directory, or the whole concept layer at a time, each behind a cost
-estimate, and rewrites already-written pages.
-
-Like `update --full` and `restyle`, it reuses the persisted index: the graph and
-git metadata are rehydrated from SQL, only the per-file parse and the LLM
-generation for the pages you selected run. A provider is required; a missing one
-is an actionable error naming the key-setup path.
-
-`generate` writes the model-written pages, and only those: the numbered concept
-tree above the file level plus the repo overview, the architecture diagram, and
-the onboarding collection. Every structural page (file, symbol, API, infra,
-cycle) is rendered from structure and refreshes on `repowise update`, so
-naming one with `--page` is an actionable error rather than a silent LLM
-re-render.
-
-**Decisions a keyless index skipped.** An index built without a model (no key,
-or `--no-prose`) cannot read decisions from PRs, git history or code comments.
-The first `generate` (or `update --full`) with a model runs those lanes too, and
-the cost estimate prices them on their own line. Later runs skip them, and
-`repowise status` shows a Decisions row while they are still pending.
-
-**Interactive chooser.** Run `repowise generate` with no selection flag on a
-terminal and it prints the wiki's state (written / unwritten / stale on the
-concept layer), writes the unwritten subsystem pages, asks about cascade only
-when the choice would change which pages get written, and ends at the normal cost
-confirm. Piped, `--yes`, or flagged runs stay non-interactive with the same
-`--unwritten` default.
-
-**Selection.** These name which subsystem pages to write, combined as a union:
-
-| Flag | Selects |
-|------|---------|
-| `--unwritten` | Every subsystem page still on a stub. The default for a non-interactive run. This is "finish writing the wiki". |
-| `--all` | Every subsystem page, stub or already written. Rewrites the prose. |
-| `--stale` | Every subsystem page marked stale (its code changed since it was written). |
-| `--path <glob>` | Subsystem pages under a path prefix or glob, e.g. `--path src/api` (repeatable). |
-| `--page <id>` | One explicit subsystem page id, e.g. `--page module_page:src/api` (repeatable). Naming a structural page is an error. |
+Write subsystem (concept) pages with a model: the upgrade path for a `--no-prose` repo.
-**Cascade.** Rewriting a subsystem page makes the pages that summarize it drift:
-its layer page, the repo overview, and the architecture and onboarding pages.
-`--cascade` decides what happens to them:
-
-| Value | Behavior |
-|-------|----------|
-| `none` | Generate exactly what you asked for; mark the dependents stale (truthful, free, instant). |
-| `dependents` (default) | Also regenerate the overview / layer pages that summarize a regenerated concept page; mark the rest stale. |
-| `full` | Also regenerate the repo overview, architecture and onboarding pages. Nothing is left stale. |
-
-The cost estimate includes the cascade fallout, so it does not under-quote.
-
-**Options:**
-
-| Flag | Description |
-|------|-------------|
-| `--unwritten` / `--all` / `--stale` | Selection (see above). Default for a non-interactive run: `--unwritten`. |
-| `--path <glob>` | Restrict to a path prefix or glob (repeatable). |
-| `--page <id>` | An explicit subsystem page id (repeatable). |
-| `--cascade none\|dependents\|full` | Dependent-page policy. Default: `dependents`. |
-| `--provider` / `--model` / `--reasoning` | LLM overrides for this run. |
-| `--concurrency` | Max concurrent LLM calls (default: 12). |
-| `--dry-run` | Print the plan and the cost estimate; generate nothing. |
-| `--yes` / `-y` | Skip the cost confirmation (and the interactive chooser). |
-| `--verbose` / `-v` | Show pipeline debug logs. |
-
-```bash
-repowise generate # write the unwritten subsystem pages
-repowise generate --dry-run # what would that write, and cost?
-repowise generate --all # rewrite the prose on every subsystem page
-repowise generate --path src/api # just the subsystem pages under src/api
+```bash
+repowise generate # write the unwritten subsystem pages
+repowise generate --path src/api
repowise generate --page module_page:src/api --cascade none # one page, nothing else
-repowise generate --stale # refresh subsystem pages whose code moved on
```
-> **Embedding.** `generate` embeds the pages it writes. On a repo indexed
-> without a key (`embedder: mock` in `config.yaml`), it re-resolves a real
-> embedder from your environment rather than honouring that pin, since you are
-> already paying a model to write the prose, and prints
-> `Embedder: openai (was mock, index-only's default)`. Switching embedder
-> changes the vector width, which rebuilds the store, so it then re-embeds the
-> whole wiki automatically (embedding calls only, no LLM) and records the
-> embedder in `config.yaml` so later `update` runs stay on it.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--unwritten` | Pages still on a stub ("finish writing the wiki"). | on, non-interactive |
+| `--all` | Every page; rewrites written prose. | off |
+| `--stale` | Pages whose code changed since written. | off |
+| `--path <glob>` | Pages under a prefix or glob. Repeatable. | |
+| `--page <id>` | One page id. Repeatable; structural ids error. | |
+| `--cascade none\|dependents\|full` | Dependent-page policy, below. | `dependents` |
+| `--provider` / `--model` / `--reasoning` | LLM overrides. | |
+| `--concurrency` | Max concurrent LLM calls. | `12` |
+| `--dry-run` | Print plan and cost estimate only. | off |
+| `--yes` / `-y` | Skip cost confirm and chooser. | off |
+| `--verbose` / `-v` | Pipeline debug logs. | off |
+
+- Selection flags combine as a union.
+- **Cascade** (priced in the estimate). A rewritten page makes its layer page, overview, architecture and onboarding
+ pages drift. `none`: dependents marked stale (truthful, free, instant). `dependents`: also regenerate summarizing
+ overview / layer pages; rest stale. `full`: regenerate all; nothing stale.
+- **Writes** only model pages: the numbered concept tree above file level, overview, architecture diagram, onboarding.
+ Structural pages (file, symbol, API, infra, cycle) refresh on `repowise update`, never an LLM re-render.
+- **Reuses the index** like `update --full` and `restyle`: graph and git metadata rehydrate from SQL. No provider: an error naming the key-setup path.
+- **Chooser.** No selection flag on a terminal: shows written / unwritten / stale, asks about cascade only if it changes
+ the pages, then confirms cost. Piped, `--yes` or flagged runs just use `--unwritten`.
+
+<details><summary>Skipped decisions and embedding</summary>
+
+A keyless or `--no-prose` index cannot read decisions from PRs, git history or code comments. The first `generate` (or
+`update --full`) with a model runs those lanes once, priced on their own line; `repowise status` shows a Decisions row
+until then.
+
+`generate` embeds what it writes. Over `embedder: mock` in `config.yaml` it resolves a real embedder from the
+environment and prints `Embedder: openai (was mock, index-only's default)`. The new vector width rebuilds the store: the
+whole wiki re-embeds (no LLM) and `config.yaml` records the embedder for later `update` runs.
+
+</details>
---
### `repowise restyle [STYLE] [PATH]`
-Switch a repo's wiki **style** and regenerate every page in the new voice. Reuses
-the existing index, the dependency graph and git metadata are rehydrated from
-SQL (no re-resolution, no re-blame), so only the per-file parse + LLM generation
-run. Requires a provider and an existing wiki. On an `--index-only` (template)
-repo it doubles as the upgrade: it warns that it will spend, then writes every
-page in the chosen style. To write only part of a template wiki, or to preserve
-the current style, use [`repowise generate`](#repowise-generate-path) instead.
-
-With no `STYLE`, prints the current style and the available choices.
-
-Styles only differ in voice and density; the markdown structure (headings,
-sections) stays the same, so search, the table of contents, and cross-links keep
-working. See [WIKI.md](../layers/WIKI.md#styles).
-
-**Options:**
-
-| Flag | Description |
-|------|-------------|
-| `--provider` | Override LLM provider for this run |
-| `--model` | Override model |
-| `--concurrency` | Max concurrent LLM calls (default: 12) |
-| `--reasoning` | Reasoning mode for supported providers |
-| `--verbose` / `-v` | Show debug logs from the pipeline |
-| `--yes` / `-y` | Skip the confirmation prompt |
+Switch a repo's wiki **style** and regenerate every page in the new voice.
```bash
repowise restyle # show current style + options
repowise restyle caveman # condensed, AI-first
repowise restyle reference --yes # API-manual, skip the confirm
-repowise restyle tutorial --verbose # show pipeline debug logs
+repowise restyle tutorial
```
-> Editing `wiki_style` in `config.yaml` by hand and running `update` does **not**
-> regenerate existing pages (that path only re-scores health). Use `restyle`.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--provider` / `--model` | LLM overrides. | |
+| `--concurrency` | Max concurrent LLM calls. | `12` |
+| `--reasoning` | Reasoning mode, supported providers. | |
+| `--verbose` / `-v` | Pipeline debug logs. | off |
+| `--yes` / `-y` | Skip the confirmation. | off |
+
+- Needs a provider and a wiki; rehydrates graph and git metadata from SQL (no re-resolution, no re-blame).
+- On an `--index-only` (template) repo it upgrades every page after a spend warning; for part, or the same style, use [`repowise generate`](#repowise-generate-path).
+- Styles change voice and density, not headings, so search, table of contents and cross-links work. See [WIKI.md](../layers/WIKI.md#styles).
+
+> Editing `wiki_style` in `config.yaml` and running `update` does **not**
+> regenerate pages (it only re-scores health). Use `restyle`.
---
### `repowise wiki-styles [PATH]`
-List the available wiki styles (built-ins plus any custom styles defined under
-`.repowise/styles/`) and the repo's current one.
+List wiki styles (built-ins plus custom ones under `.repowise/styles/`) and the current one. No flags.
```bash
repowise wiki-styles
@@ -468,71 +388,48 @@ repowise wiki-styles
Start the API server and web UI.
-**Options:**
-
-| Flag | Description |
-|------|-------------|
-| `--port` | API server port (default: 7337; env `REPOWISE_PORT`) |
-| `--host` | Host to bind to (default: 127.0.0.1) |
-| `--workers` | Uvicorn workers (default: 1) |
-| `--ui-port` | Web UI port (default: 3000) |
-| `--no-ui` | Start API server only |
-| `--refresh-ui` | Force re-download of the web UI tarball, ignoring any cache |
-
```bash
-repowise serve # API + Web UI
-repowise serve --no-ui # API only
repowise serve --port 8080 --ui-port 8081
-repowise serve --refresh-ui # bypass cache, pull latest UI tarball
```
-The web UI needs Node >= 20; without it `serve` falls back to API-only.
-
-**Web UI sources, in order of precedence:**
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--port` | API port. Env `REPOWISE_PORT`. | `7337` |
+| `--host` | Bind host. | `127.0.0.1` |
+| `--workers` | Uvicorn workers. | `1` |
+| `--ui-port` | Web UI port. | `3000` |
+| `--no-ui` | API only. | off |
+| `--refresh-ui` | Re-download the UI tarball (skips sources 1 and 2). | off |
-1. **Local monorepo build** at `packages/web/.next/standalone/...`, used when the CLI is run from inside a checkout. The bundle's mtime is compared against source under `packages/web/`, `packages/ui/src/`, and `packages/types/src/`; if any source is newer the bundle is rebuilt with `npm run build` (or skipped if `npm` is unavailable).
-2. **Cached download** at `~/.repowise/web/`, keyed by the CLI version in `.version`.
-3. **Fresh download** of `repowise-web.tar.gz` from the GitHub release matching the CLI version.
+The UI needs Node >= 20, else API-only. UI sources, in precedence:
-Pass `--refresh-ui` to skip (1) and (2) and force (3).
+1. **Local build** at `packages/web/.next/standalone/...` in a checkout; `npm run build` (if `npm` exists) when `packages/web/`, `packages/ui/src/` or `packages/types/src/` is newer.
+2. **Cached download** at `~/.repowise/web/`, keyed by CLI version in `.version`.
+3. **Fresh download** of `repowise-web.tar.gz` from the matching GitHub release.
---
### `repowise watch [PATH]`
-Watch for file changes and auto-update wiki pages. Press `Ctrl+C` to stop.
-
-Unlike the post-commit hook, this indexes **uncommitted** work: staged,
-unstaged and untracked files all reach the index, so what you see in the wiki
-matches what is on disk rather than what you last committed.
-
-Writes inside `.repowise/`, `.git/`, `node_modules/`, build output and the
-files repowise manages itself (`CLAUDE.md`, `AGENTS.md`, `.mcp.json`) never
-trigger an update.
-
-**Options:**
-
-| Flag | Description |
-|------|-------------|
-| `--provider` | LLM provider |
-| `--model` | Model override |
-| `--debounce` | Delay in ms after last change (default: 2000) |
-| `--workspace` / `-w` | Watch all workspace repos |
-| `--no-workspace` | Force single-repo mode |
-| `--index-only` | Skip LLM page regeneration on every trigger (workspace mode is index-only either way) |
-| `--verbose` / `-v` | Show debug logs from the pipeline and triggered updates |
+Watch for file changes and auto-update wiki pages. `Ctrl+C` stops.
```bash
-repowise watch # single repo (auto-detects)
repowise watch --debounce 5000 # 5s debounce
-repowise watch --workspace # all workspace repos
-repowise watch --index-only # no model calls per save
-repowise watch --verbose # show pipeline debug logs
+repowise watch --workspace --index-only
```
-On a repo indexed with docs, every trigger is a page regeneration with a model
-behind it. `--index-only` keeps the index, graph and health current for free
-and leaves the prose to a later `repowise update`.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--provider` / `--model` | LLM overrides. | |
+| `--debounce` | Ms after the last change. | `2000` |
+| `--workspace` / `-w` | All workspace repos. | auto-detect |
+| `--no-workspace` | Single-repo mode. | auto-detect |
+| `--index-only` | No LLM page regeneration per trigger (workspace mode always). | off |
+| `--verbose` / `-v` | Pipeline and update debug logs. | off |
+
+- Unlike the post-commit hook, indexes staged, unstaged and untracked files.
+- Writes in `.repowise/`, `.git/`, `node_modules/`, build output, `CLAUDE.md`, `AGENTS.md`, `.mcp.json` never trigger.
+- With docs each trigger calls a model; `--index-only` keeps index, graph and health current free, prose waits for `repowise update`.
---
@@ -540,116 +437,78 @@ and leaves the prose to a later `repowise update`.
### `repowise search QUERY [PATH]`
-Search wiki pages by keyword, meaning, or symbol name. Runs the same retrieval
-as the `search_codebase` MCP tool: the full-text and vector legs are fused
-rather than chosen between, per-repo excludes and tombstones are honoured, and
-decision / test pages are demoted on queries that did not ask for them.
-
-**Options:**
+Search wiki pages by keyword, meaning, or symbol name.
-| Flag | Description |
-|------|-------------|
-| `--mode` | `fulltext` (default), `semantic`, `symbol`, plus the tool's own `auto`, `concept`, `path`, `hybrid` |
-| `--limit` | Max results (default: 10) |
-| `--repo` | Scope to a specific workspace repo by alias |
-| `--all` | Fan out across every workspace repo and merge results |
-| `--workspace` / `--no-workspace` | Force workspace / single-repo mode |
-| `--format` | `table` (default) or `json` |
-| `--full` | Emit the complete tool payload as JSON (implies `--format json`) |
-
-`fulltext` and `semantic` both run the tool's fused `concept` search, which is
-the successor to picking one leg or the other; on an index built without an
-embedder the vector leg drops out by itself and `--mode semantic` says so.
-`auto` routes on the query's shape — an identifier goes to the symbol index, a
-path resolves files, prose stays conceptual, and a mixed query runs `hybrid`.
-
-```bash
-repowise search "rate limiting"
+```bash
repowise search "how are errors handled" --mode semantic
repowise search "AuthService" --mode symbol
-repowise search "cli/output.py" --mode path
-repowise search "where is resolve_console_width called" --mode auto
-repowise search "rate limit" --repo backend # workspace, one repo
repowise search "rate limit" --all # workspace, fan-out
```
-The default payload is a trimmed projection carrying `score`, `title`,
-`page_type`, `path` and `snippet` per hit (symbol hits carry `name`,
-`qualified_name`, `kind`, `path`, `line` and the `symbol_id` you pass to
-`repowise symbol`), plus `candidates` — the distinct openable files the hits
-resolve to. `--full` returns the tool's own dict instead.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--mode` | `fulltext`, `semantic`, `symbol`, `auto`, `concept`, `path`, `hybrid`. | `fulltext` |
+| `--limit` | Max results. | `10` |
+| `--all` | Every workspace repo, merged. | off |
-For a synthesized answer rather than a keyword lookup, use `repowise ask`.
+Plus `--repo`, `--no-workspace`, `--format` and `--full` as in the [shared options](#shared-options-ask-context-symbol-why).
+
+- `search_codebase` retrieval: full-text and vector fused, excludes and tombstones honoured, decision / test pages demoted unless asked for.
+- `fulltext` and `semantic` both run the fused `concept` search; without an embedder the vector leg drops and `--mode
+ semantic` says so. `auto` routes identifier to symbol, path to files, prose to concept, mixed to `hybrid`.
+- Hits: `score`, `title`, `page_type`, `path`, `snippet`, plus `candidates` (openable files). Symbol hits add `name`,
+ `qualified_name`, `kind`, `line`, `symbol_id`. Synthesized answers: `repowise ask`.
---
### `repowise ask QUESTION`
-Answer a question about the codebase, with citations. The same synthesis the
-`get_answer` MCP tool performs: hybrid retrieval followed by an LLM answer over
-what it found, so this command costs an LLM call where the other query commands
-do not.
-
-**Options:**
-
-| Flag | Description |
-|------|-------------|
-| `--scope` | Restrict retrieval to a path prefix (e.g. `packages/cli/`) |
+Answer a question about the codebase, with citations.
```bash
-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
```
-`confidence: high` is content-grounded, so it can be cited directly. A
-low-confidence answer returns `best_guesses` (a file plus why it is in the
-running) instead of an empty one.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--scope` | Restrict retrieval to a path prefix. | whole repo |
----
+Plus the [shared options](#shared-options-ask-context-symbol-why).
-### `repowise context TARGETS...`
+- `get_answer` synthesis (hybrid retrieval, then LLM): the one query command that costs an LLM call.
+- `confidence: high` is content-grounded, citable directly. Low confidence returns `best_guesses` (a file plus why) instead of nothing.
-Triage card for files, modules or symbols: title, summary, architectural layer,
-hotspot and bug-fix history, doc freshness, and the shape of the verified
-skeleton. Relationships and risk signals, not source bytes. Batch targets in one
-call.
+---
-**Options:**
+### `repowise context TARGETS...`
-| Flag | Description |
-|------|-------------|
-| `--include` | Opt-in block, repeatable: `full_doc`, `ownership`, `last_change`, `callers`, `callees`, `metrics`, `community`, `decisions`, `health`, `skeleton`, `doc_drift`, `symbols` |
-| `--no-compact` | Add structure, imports and docstrings to each card |
-| `--symptom` | Issue text, an error or a stack trace for `--include suspects` to rank against |
+Triage card for files, modules or symbols: relationships and risk signals, not source bytes. Batch targets in one call.
```bash
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 # + the file's source
```
-**No source bytes by default.** A card is relationships and risk signals:
-title, summary, signatures with line numbers, hotspot, fix history. Pass
-`--include skeleton` for the whole file body-elided and line-verified in one
-call, or just read the file. `--full` returns the raw tool dict, which carries
-a skeleton only when one was asked for.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--include` | Opt-in block, repeatable; values below. | |
+| `--no-compact` | Add structure, imports, docstrings. | off |
+| `--symptom` | Issue text, error or stack trace for `--include suspects`. | |
----
+Plus the [shared options](#shared-options-ask-context-symbol-why).
-### `repowise symbol SYMBOL_ID`
+**`--include` values:** `full_doc`, `ownership`, `last_change`, `callers`, `callees`, `references`, `metrics`,
+`community`, `decisions`, `health`, `skeleton`, `skeleton+`, `doc_drift`, `symbols`, `changes`, `provenance`,
+`suspects`.
-Read one function, class or constant with live-verified line bounds. `source`
-arrives in the same line-numbered format a file read produces; `verified: true`
-means the bounds were checked against the live file.
+- Card: title, summary, layer, signatures with lines, hotspot and bug-fix history, doc freshness, skeleton shape.
+ `--include skeleton` adds the file body-elided and line-verified; `--full` only then carries one.
-**Options:**
+---
-| Flag | Description |
-|------|-------------|
-| `--context-lines` | Extra lines before and after the body (0-50) |
-| `--query` | Omission refs only: regex or substring filter on the restored lines |
+### `repowise symbol SYMBOL_ID`
+
+Read one function, class or constant with live-verified line bounds.
```bash
repowise symbol "src/api/routes.py::login"
@@ -657,77 +516,61 @@ repowise symbol "src/api/routes.py:140-180" # live range read
repowise symbol "repowise#a1b2c3d4e5f6" # a distill omission ref
```
-An ambiguous id (overloads, re-exports) returns every matching body rather than
-silently picking one. A truncated body carries a `continuation` you can pass
-straight back to `repowise symbol`.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--context-lines` | Extra lines around the body (0-50). | `0` |
+| `--query` | Omission refs: regex or substring filter on restored lines. | |
----
+Plus the [shared options](#shared-options-ask-context-symbol-why).
-### `repowise why [QUERY]`
+- `source` is line-numbered like a file read; `verified: true` means bounds checked against the live file.
+- An ambiguous id (overloads, re-exports) returns every body. A truncated body carries a `continuation` to pass back.
-Why the code is shaped this way: decision records, rationale and git
-archaeology. Worth running before a refactor or a deliberate divergence from a
-pattern.
+---
-**Options:**
+### `repowise why [QUERY]`
-| Flag | Description |
-|------|-------------|
-| `--target` | File path to anchor the search to. Repeatable |
+Why the code is shaped this way (decisions, rationale, git archaeology); run before a refactor or pattern divergence.
```bash
-repowise why "why is auth using JWT?" # question
-repowise why src/api/auth.py # governing decisions + origin story
repowise why "why the retry cap?" --target src/api/client.py
+repowise why src/api/auth.py # governing decisions + origin story
repowise why # decision health dashboard
```
-Falls back to git archaeology when a path has no decisions, so it is never
-empty.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--target` | File to anchor the search. Repeatable. | |
+
+Plus the [shared options](#shared-options-ask-context-symbol-why). A path without decisions falls back to git archaeology, so it is never empty.
---
### Shared options: `ask`, `context`, `symbol`, `why`
-These four are thin adapters over the MCP tools of the same name, so they share
-one option block.
+Thin adapters over the same-named MCP tools.
-| Flag | Description |
-|------|-------------|
-| `--path` | Repo (or workspace) root. Defaults to the current directory |
-| `--repo` | Workspace repo alias to query |
-| `--no-workspace` | Force single-repo mode even inside a workspace |
-| `--format` | `table` (default) or `json` |
-| `--full` | Emit the complete tool payload as JSON (implies `--format json`) |
-
-The repo is `--path` here rather than the trailing positional `[PATH]` the older
-commands take: `context` accepts a variadic list of targets, which would swallow
-a trailing path.
-
-`--format json` emits a **trimmed CLI projection**, not the tool's whole
-response. What each one keeps and drops is documented on the `project()`
-function in its command module. `--full` returns the raw dict, which is what an
-editor's MCP client receives. Measured on this repository:
-
-| Command | trimmed | `--full` |
-|---------|--------:|---------:|
-| `ask` | 3.4 KB | 19.5 KB |
-| `context` (one file) | 0.9 KB | 12.4 KB |
-| `why` (question) | 10.4 KB | 20.9 KB |
-| `why` (path) | 10.4 KB | 28.5 KB |
-| `symbol` | 0.7 KB | 1.0 KB |
-| `search` (8 hits) | 4.9 KB | 6.8 KB |
-| `search --mode symbol` | 4.2 KB | 5.7 KB |
-| `risk --target` (one file) | 4.5 KB | 5.3 KB |
-
-`symbol` barely moves because its payload *is* its answer — only the call
-envelope is dropped. `search` and `risk --target` are close for the same
-reason: a ranked hit and a risk card are already mostly the answer, so the trim
-takes ranking internals rather than content. The point of `--full` there is
-exactness, not size. Nothing that changes the *answer* is ever trimmed: an
-error, a not-found, a did-you-mean list, a truncation marker, a continuation
-token, and the ambiguity signals all survive at every format. `ask` reports the
-names of the heavy blocks it left out in `dropped_blocks`.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--path` | Repo or workspace root (a flag, since `context`'s variadic targets would swallow a trailing `[PATH]`). | cwd |
+| `--repo` | Workspace repo alias. | |
+| `--no-workspace` | Single-repo mode inside a workspace. | auto-detect |
+| `--format` | `table` or `json`. | `table` |
+| `--full` | Raw tool payload, as an MCP client gets it (implies `--format json`). | off |
+
+`--format json` is a **trimmed CLI projection** (see each module's `project()`). Errors, not-founds, did-you-mean lists,
+truncation markers, continuation tokens and ambiguity signals always survive. `ask` names omitted blocks in
+`dropped_blocks`.
+
+<details><summary>Measured sizes on this repository</summary>
+
+Trimmed / `--full`: `ask` 3.4 / 19.5 KB; `context` (one file) 0.9 / 12.4 KB; `why` (question) 10.4 / 20.9 KB; `why`
+(path) 10.4 / 28.5 KB; `symbol` 0.7 / 1.0 KB; `search` (8 hits) 4.9 / 6.8 KB; `search --mode symbol` 4.2 / 5.7 KB; `risk
+--target` (one file) 4.5 / 5.3 KB.
+
+`symbol` drops only the envelope; `search` and `risk --target` drop ranking internals, so `--full` there means exactness, not size.
+
+</details>
---
@@ -736,30 +579,39 @@ names of the heavy blocks it left out in `dropped_blocks`.
Show wiki sync state, page statistics, and coverage.
```bash
-repowise status # auto-detects mode
-repowise status --workspace # all workspace repos
-repowise status --no-workspace # force single-repo even in a workspace
-repowise status --format json # machine-readable
+repowise status --workspace --format json
```
-In workspace mode, the table includes a **Docs** column with each repo's page count and a per-repo **Docs status** block listing skip reasons (e.g. `cost gate declined`) and the exact remediation command.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--workspace` / `-w` | All workspace repos. | auto-detect |
+| `--no-workspace` | Single-repo mode. | auto-detect |
+| `--format` | `table` or `json`. | `table` |
-For a single repo it ends with a short **Next** block: how many things are worth doing this week (or this quarter, when the week is quiet) and the first of them. `--format json` carries the counts as `next_actions`; `repowise next` has the list.
+- **Workspace:** a **Docs** column (page count) and per-repo **Docs status** with skip reasons (e.g. `cost gate declined`) and fix command.
+- **Single repo:** a **Next** block: count worth doing this week (or quarter if quiet) and the first; JSON `next_actions`; `repowise next` lists them.
---
### `repowise next [PATH]`
-The few things worth doing next, ranked from the index. The same stored actions the web app's overview and MCP `get_overview` (`next_actions`) read, so all three agree.
+The few things worth doing next, ranked from the index.
```bash
-repowise next # this week, or the quarter when the week holds no work
-repowise next --horizon quarter # the 90-day window
-repowise next --all # up to 20 rows instead of 5
-repowise next --format json # the whole stored view (--json also works)
+repowise next --horizon quarter --all
```
-Rows are grouped as **Now**, **Worth planning** and **Improve what Repowise can see**, each with its impact, the facts behind it, when it counts as done, and a command when one applies. An index built before a store existed names that store and suggests `repowise update` rather than reporting it as empty. With fewer than five commits, the rows ranked by history are left out and the JSON sets `context.history_too_short`.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--horizon` | `week` or `quarter` (90 days). | week, or quarter if the week holds no work |
+| `--all` | Up to 20 rows instead of 5. | off |
+| `--repo` | Workspace: one repo by alias. | |
+| `--no-workspace` | Single-repo mode. | auto-detect |
+| `--format` | `table` or `json` (whole stored view). Hidden alias `--json`. | `table` |
+
+- Same stored actions as the web overview and MCP `get_overview` (`next_actions`).
+- Groups **Now**, **Worth planning**, **Improve what Repowise can see**; rows give impact, facts, done-when, and any command.
+- An index predating a store names it and suggests `repowise update`. Under five commits, history-ranked rows are dropped and JSON sets `context.history_too_short`.
---
@@ -769,459 +621,320 @@ Rows are grouped as **Now**, **Worth planning** and **Improve what Repowise can
Detect dead and unused code.
-**Options:**
-
-| Flag | Description |
-|------|-------------|
-| `--min-confidence` | Minimum confidence threshold (default: 0.4) |
-| `--safe-only` | Only show findings marked safe to delete |
-| `--kind` | Filter: `unreachable_file`, `unused_export`, `unused_internal`, `zombie_package` |
-| `--format` | Output: `table` (default), `json`, `md` |
-| `--include-internals` / `--no-include-internals` | Include private/underscore symbols (default: off) |
-| `--include-zombie-packages` / `--no-include-zombie-packages` | Include unused declared packages (default: on) |
-| `--no-unreachable` | Skip unreachable-file findings |
-| `--no-unused-exports` | Skip unused-export findings |
-| `--repo` | In workspace mode, target a specific repo (defaults to primary) |
-| `--workspace` / `--no-workspace` | Force workspace / single-repo mode |
-
```bash
-repowise dead-code
-repowise dead-code --safe-only --min-confidence 0.8
-repowise dead-code --format json
-repowise dead-code --repo backend # workspace, single repo
+repowise dead-code --safe-only --min-confidence 0.8 --repo backend
```
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--min-confidence` | Minimum confidence. | `0.4` |
+| `--safe-only` | Only safe-to-delete findings. | off |
+| `--kind` | `unreachable_file`, `unused_export`, `unused_internal`, `zombie_package`. | all |
+| `--format` | `table`, `json`, `md`. | `table` |
+| `--include-internals` / `--no-include-internals` | Private/underscore symbols. | off |
+| `--include-zombie-packages` / `--no-include-zombie-packages` | Unused declared packages. | on |
+| `--no-unreachable` | Skip unreachable files. | off |
+| `--no-unused-exports` | Skip unused exports. | off |
+| `--repo` | Workspace repo. | primary |
+| `--no-workspace` | Force single-repo mode. | auto-detect |
+| `-v`, `--verbose` | Live-analysis debug logs (table only). | off |
+
---
### `repowise doc-drift [PATH]`
-Show documentation this repository's own tree no longer satisfies: a path a
-document names that no longer exists, a link pointing at a heading that was
-renamed, a `make` target the manifest no longer declares.
-
-By default it reads what the last `init` or `update` stored instead of
-re-scanning, so it agrees with `get_health(include=["doc_drift"])` on the same
-tree. With `--check` it reads the working tree directly, needs no index,
-and exits non-zero when the gate fails: the mode for CI.
+Docs the tree does not satisfy: a missing named path, a link to a renamed heading, a `make` target the manifest lacks.
-It checks only references it can resolve. Most references in a typical
-repository are uncheckable by design and are neither counted nor reported, so a
-clean run is not a claim that every sentence is true.
+```bash
+repowise doc-drift --check --format sarif > drift.sarif
+repowise doc-drift --check --baseline .doc-drift-baseline.json --since auto
+```
-Where the analysis can see a likely replacement, a finding carries it: a module
-that became a package, a file git recorded as renamed, a heading or build target
-with a close match, a symbol its defining file shows renamed. It is a suggestion
-to check, never applied.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--min-confidence` | Hide findings below this. | show everything stored |
+| `--kind` | `path`, `link`, `anchor`, `command`, `symbol`. Repeatable. | all |
+| `--document` | Only this document. Repeatable. | all |
+| `--check` | CI gate on the working tree, no index; non-zero on failure. `--kind symbol` needs an index (else 2). | off |
+| `--fail-on-confidence` | With `--check`: fail at or above this. | `0.7` |
+| `--baseline` | With `--check`: accept findings in this file; new ones fail. | |
+| `--write-baseline` | With `--check`: record findings to this file, exit 0. | |
+| `--fail-on-baseline-growth` | With `--baseline`: as in `security check`; base is `--since`, else the CI target branch. | off |
+| `--since` | With `--check`: gate only drift this change answers for; see notes. | |
+| `--format` | `table`, `json`, `markdown`, `github` (annotations; markdown to `$GITHUB_STEP_SUMMARY` if set), `sarif`, `gitlab` (GitLab Code Quality report). | `table` |
+| `--repo` | Workspace repo. | primary |
+| `--no-workspace` | Force single-repo mode. | auto-detect |
-**Options:**
+- **`--since`**: gates edited documents and anchors into them, documents naming deleted or renamed files, edited
+ manifests' commands, symbols whose file is edited or removed. Bare ref: `REF...HEAD` plus uncommitted; `auto`: CI
+ target branch.
+- Without `--check`: reads what `init` / `update` stored, as `get_health(include=["doc_drift"])` does.
+- Checks only resolvable references (most are uncheckable by design); clean does not mean every sentence is true.
+- Suggested fixes (never applied): module turned package, git rename, close heading or build target, renamed symbol.
-| Flag | Description |
-|------|-------------|
-| `--min-confidence` | Hide findings below this confidence (default: show everything stored) |
-| `--kind` | Only this reference class: `path`, `link`, `anchor`, `command`, `symbol`. Repeatable |
-| `--document` | Only findings in this document. Repeatable |
-| `--check` | Read the working tree without an index and gate on the result. With `--kind symbol` it checks symbol references, which needs an index (exit 2 without one) |
-| `--fail-on-confidence` | With `--check`, fail on findings at or above this confidence (default: 0.7) |
-| `--baseline` | With `--check`, accept the findings recorded in this file; only new ones fail |
-| `--write-baseline` | With `--check`, record the current findings to this file and exit 0 |
-| `--fail-on-baseline-growth` | With `--baseline`, exit 1 when the file lists a finding the same file at the change's base does not (the `--since` base, else the CI target branch). A baseline the base lacks is new and passes |
-| `--since` | With `--check`, gate only drift this change is answerable for: documents it edits, documents naming files it deletes or renames, anchors into documents it edits, commands whose manifest it edits, and symbols whose defining file it edits or removes. A bare ref means `REF...HEAD` plus uncommitted changes; `auto` reads the target branch from CI |
-| `--format` | Output: `table` (default), `json`, `markdown`, `github`, `sarif`, `gitlab` (GitLab Code Quality report) |
-| `--repo` | In workspace mode, target a specific repo (defaults to primary) |
-| `--no-workspace` | Force single-repo mode |
-
-```bash
-repowise doc-drift
-repowise doc-drift --kind anchor # just the renamed-heading links
-repowise doc-drift --min-confidence 0.9 # the near-certain ones
-repowise doc-drift --format json
-
-repowise doc-drift --check # CI gate, no index needed
-repowise doc-drift --check --format github # annotations + step summary
-repowise doc-drift --check --format sarif > drift.sarif # code scanning upload
-repowise doc-drift --check --format gitlab > gl-code-quality-doc-drift.json # merge request widget
-repowise doc-drift --check --write-baseline .doc-drift-baseline.json
-repowise doc-drift --check --baseline .doc-drift-baseline.json
-repowise doc-drift --check --since auto # only drift this PR is answerable for
-```
-
-`github` prints workflow annotations and, when `$GITHUB_STEP_SUMMARY` is set,
-appends a markdown summary to it.
-
-Without `--check`, exits non-zero when there is no readable index, or when the
-index predates drift storage; in both cases `--format json` still emits a
-document naming the reason, not an empty finding list that would read as
-a clean tree. With `--check`, exit codes are `0` gate passed, `1` gate failed,
-`2` could not evaluate (not a git repository, unreadable baseline, a `--since`
-revision that cannot be diffed).
+**Exit codes.** Without `--check`: non-zero for no readable index or one predating drift storage (JSON names why; no
+empty list). `--check`: `0` passed; `1` failed; `2` not evaluable (no git repository, unreadable baseline, undiffable
+`--since` revision).
---
### `repowise risk [REVSPEC]`
-Just-in-time change-risk scoring for a commit or diff range. Scores the defect
-risk of a change from the same calibrated signals the code-health layer uses -
-no LLM calls, and it works without `repowise init` (pure git + learned
-constants). With no `REVSPEC` it scores your uncommitted work, falling back to
-`HEAD` when the tree is clean; pass `HEAD` to always mean the last commit, or a
-`base..head` range to score a whole branch / PR as one change (`base...head`
-diffs from the merge-base, so commits that landed on `base` meanwhile stay out).
+Score a commit or range with code-health's calibrated signals: pure git + learned constants, no LLM, no `repowise init`. Model: [`docs/layers/CHANGE_RISK.md`](../layers/CHANGE_RISK.md).
-The headline is **repo-relative**: the change's percentile by size and spread
-within the repo's own recent commits, sampled live. It ranks diff size, not
-danger; the bug-fix record of the touched files follows it. The raw 0–10 model score is still shown, but as a secondary,
-corpus-anchored number (it skews high on repos whose typical commit is large, so
-the percentile is the signal to act on). Each risk driver is reported relative
-to the model's baseline commit, not this repo.
+```bash
+repowise risk main..HEAD -x 'tests/' -x '*.spec.ts'
+repowise risk --fail-above-percentile 95 --format github
+```
-**Options:**
+**REVSPEC.** None: uncommitted work, else `HEAD`. `HEAD`: last commit. `base..head`: a branch as one change. `base...head`: from the merge-base, excluding commits landed on `base`.
-| Flag | Description |
-|------|-------------|
-| `--path` | Path to the git repository (default: current directory) |
-| `--ext` | Comma-separated file suffixes to count (e.g. `.py` or `.ts,.tsx`) |
-| `--exclude` / `-x` | Gitignore-style path pattern to omit. Repeatable; filters both the change and baseline. Root `.riskignore` patterns also apply. |
-| `--baseline` | Recent commits to sample for the repo-relative percentile (default 200; `0` shows only the absolute per-commit model-score band) |
-| `--target` / `-t` | Score what history says about these **files** instead of a change. Repeatable; switches the command to the `get_risk` tool |
-| `--changed-file` | With `--target`: PR mode. Leads with a directive naming what may break, which co-changes and tests are missing, and what to run |
-| `--fail-above-percentile` | CI size gate (0-100): exit `1` when the change ranks above this percentile of recent commits (`risk_percentile`, never the 0-10 score), `2` when it has no percentile (`--baseline 0`, or fewer than 8 commits to rank against). Without `REVSPEC` it scores the CI change: the target branch `...HEAD` |
-| `--format` | Output format: `table` (default), `json`, `markdown` or `github`. `markdown` and `github` are not for `--target`; without `REVSPEC` they score the CI change. `github` writes an `::error::` when the gate fails (else a `::notice::`) and the markdown to `$GITHUB_STEP_SUMMARY` |
-| `--full` | With `--target`: emit the complete tool payload as JSON (implies `--format json`) |
-
-```bash
-repowise risk # score uncommitted work, else HEAD
-repowise risk HEAD # score the last commit
-repowise risk main..HEAD # score a branch / PR range as one change
-repowise risk --ext .ts,.tsx # restrict to specific suffixes
-repowise risk main..HEAD -x 'tests/' -x '*.spec.ts' # omit tests from scoring
-repowise risk --fail-above-percentile 95 --format github # gate the CI change
-```
-
-With `--fail-above-percentile`, `--format json` adds `"gate":
-{"fail_above_percentile": P, "percentile": <unrounded>, "status": "pass" |
-"fail"}`; `percentile` is what the gate compared, since `risk_percentile` is
-rounded. A revspec git cannot read exits `2` (it used to exit `1`), gated or
-not, with a `{"error", "message"}` document under `--format json`. At a
-percentile P roughly (100 - P)% of changes fail by construction; a failure asks
-for a split or a second reviewer, not a code fix, and there is no baseline to
-accept it with.
-
-**`--target`: what history says about touching some files.** Two questions, one
-command, because they are the same question asked of different subjects. A
-`REVSPEC` scores a *change* from its diff shape; `--target` reports bug-fix
-pressure, churn trend, dependents, co-change partners and ownership for the
-named *files*. That half reads the index, so unlike the REVSPEC path it needs
-`repowise init` to have run. It is the `get_risk` MCP tool.
-
-```bash
-repowise risk --target src/auth.py # one file's history
-repowise risk -t src/auth.py -t src/session.py # several
-repowise risk -t src/auth.py --changed-file src/auth.py # PR mode + directive
-```
-
-Note `--path` on this command already means "the git repository", which is why
-the files are named with `--target`.
-
-**Independent changes.** When the index can be read, the command also prints
-whether the diff is one change or several: the changed files grouped by what
-connects them, which is the links the index holds (imports, calls, type
-references, stored co-change pairs) plus, for a `base..head` range, the files each
-commit touched, since putting two files in one commit is the author's own
-statement that they belong together. Only indexed, non-test source files a
-resolver can link are grouped; docs, config, data and tests are always printed
-under `Left out of the grouping:`, never as a change of their own, and only the
-first ten names are listed. Each group prints its files and the files that alone
-hold it together, where moving one out would split the group. A closing `Basis:`
-line says what was checked, naming a shared commit only when there were commits to
-read. It is silent when the diff is one change, and it carries no score.
-`--format json` puts the same object under `independent_changes`. See
-[Independent changes](../layers/CHANGE_RISK.md#independent-changes).
-
-See [`docs/layers/CHANGE_RISK.md`](../layers/CHANGE_RISK.md) for the scoring model.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--path` | Git repository. | cwd |
+| `--ext` | Comma-separated suffixes (`.py`, `.ts,.tsx`). | all |
+| `--exclude` / `-x` | Gitignore-style pattern omitted from change and baseline; repeatable; root `.riskignore` too. | |
+| `--baseline` | Recent commits sampled for the percentile; `0`: absolute model-score band only. | `200` |
+| `--target` / `-t` | History for these **files**, not a change (`get_risk`); repeatable. | |
+| `--changed-file` | With `--target`: PR mode; a directive leads: what may break, missing co-changes and tests, what to run. | |
+| `--fail-above-percentile` | CI size gate (0-100); see notes. | off |
+| `--format` | `table`, `json`, `markdown`, `github` (`::error::` on gate failure, else `::notice::`; markdown to `$GITHUB_STEP_SUMMARY`). Last two: not for `--target`; no `REVSPEC` means the CI change. | `table` |
+| `--full` | With `--target`: full payload as JSON (implies `--format json`). | off |
----
+- **`--fail-above-percentile`**: exit `1` above this percentile of recent commits (`risk_percentile`, not the 0-10
+ score), `2` with none (`--baseline 0`, under 8 commits). No `REVSPEC`: CI target branch `...HEAD`. JSON: `"gate":
+ {"fail_above_percentile": P, "percentile": <unrounded>, "status": "pass" | "fail"}`. About (100 - P)% fail by design;
+ answer with a split or second reviewer, not a fix (no baseline).
+- Unreadable revspec: exit `2` even ungated; JSON `{"error", "message"}`.
+- **Headline**: live percentile by size and spread among recent repo commits (size, not danger), then touched files'
+ bug-fix record. Raw 0-10 score: secondary, corpus-anchored, high where commits run large. Drivers: versus the model's
+ baseline commit.
+- **`--target`**: bug-fix pressure, churn trend, dependents, co-change partners, ownership; needs `repowise init`; `--path` is the repository.
-### `repowise overlap`
+**[Independent changes](../layers/CHANGE_RISK.md#independent-changes).** With an index, says if the diff is one change
+or several, linking files by indexed imports, calls, type references, co-change pairs and, for `base..head`, shared
+commits (the author's grouping).
-Which other open branches edit the files this change edits. Pure git for the
-answer, so it works in a fresh clone with no index; when an index is readable it
-orders the shared files and adds the files history pairs with them. Every row
-states its basis in words, `same file` or `co-change pair, N of M commits`, and
-there is no score anywhere in the output.
+- Groups indexed non-test source files a resolver links; docs, config, data, tests list under `Left out of the grouping:` (first ten).
+- Each group lists files and those alone holding it together; `Basis:` names what was checked (a shared commit only if commits existed).
+- Silent for one change; no score; JSON `independent_changes`.
-Branches stacked on the current one (and the ones it is stacked on) are skipped,
-as are noise paths and dependency manifests, which every branch touches. A branch
-that shares no file produces no row. The scan is bounded to the newest branches by
-committer date and reports how many it scanned of how many exist.
+---
-**Options:**
+### `repowise overlap`
-| Flag | Description |
-|------|-------------|
-| `--base` | Base ref to diff both sides against (default: the repository's trunk, from `origin/HEAD`, else `main` or `master`) |
-| `--branch` | The change to compare (default: `HEAD`) |
-| `--path` | Path to the git repository (default: current directory) |
-| `--limit` | How many branches to diff, newest committer date first (default 50) |
-| `--format` | Output format: `table` (default) or `json` |
+Other open branches editing the files this change edits.
```bash
-repowise overlap # who else is editing what you are editing
-repowise overlap --base main --limit 100 # a wider scan against an explicit base
+repowise overlap --base main
```
-When nothing overlaps, the command prints one line saying so with the scan
-counts. See [Branch overlap](../layers/CHANGE_RISK.md#branch-overlap).
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--base` | Base ref for both sides. | trunk from `origin/HEAD`, else `main` or `master` |
+| `--branch` | The change. | `HEAD` |
+| `--path` | Git repository. | cwd |
+| `--limit` | Branches diffed, newest committer date first. | `50` |
+| `--format` | `table` or `json`. | `table` |
+
+- Pure git (fresh clones work); an index orders shared files, adds history pairs.
+- Rows give a basis (`same file`, `co-change pair, N of M commits`), never a score.
+- Skips stacked branches (either way), noise paths, dependency manifests; no shared file, no row.
+- Reports branches scanned of existing; one line if no overlap. [Branch overlap](../layers/CHANGE_RISK.md#branch-overlap).
---
### `repowise security`
-Security signal scanning. Working-tree scanning already runs during
-`repowise init` / `repowise update`. The CLI group exists so you can also walk
-**full git history** for leaked secrets and risky patterns that were later
-removed (something the working-tree scan cannot see), and to gate a change in
-CI.
+`scan` walks **full git history** for leaked secrets and risky patterns later removed; `check` gates a change in CI. `init` / `update` scan the working tree.
-**Subcommands:**
+**`security scan`**
```bash
-repowise security scan --history [OPTIONS]
-repowise security check [REVSPEC] [OPTIONS] # CI gate on what a change adds
+repowise security scan --history --since v1.0.0 --to HEAD
```
-Without `--history`, `security scan` prints a short hint and exits — it does
-not re-run the working-tree scan.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--history` | Required; else a hint and exit (no working-tree rescan). | off |
+| `--since <rev>` | Lower bound (exclusive). | all history |
+| `--to <rev>` | Upper bound (inclusive). | HEAD / all history |
+| `--path <dir>` | Repo path. | cwd / workspace primary |
+| `--all-patterns` | Code smells (`eval`, `os.system`, weak hashes, …) besides leaked secrets (credential assignments, vendor key shapes). | off |
+| `--format` | `table` or `json`; deprecated alias `--output` wins. | `table` |
-**`security scan` options:**
+Findings land in `security_findings` (idempotent; local server security API / UI); the command prints counts.
-| Flag | Description |
-|------|-------------|
-| `--history` | Required for a real scan: walk the full git history (not just the working tree) |
-| `--since <rev>` | Lower git revision bound (exclusive). Defaults to all history |
-| `--to <rev>` | Upper git revision bound (inclusive). Defaults to HEAD / all history |
-| `--path <dir>` | Repo path (defaults to cwd / workspace primary) |
-| `--all-patterns` | History mode: also report code-smell patterns (`eval`, `os.system`, weak hashes, …). Default history mode reports only leaked-secret patterns (the credential assignments and vendor key shapes) to avoid noise |
-| `--format` | `table` (default) or `json`. `--output` is a deprecated alias, still accepted; when both are given `--output` wins |
+#### `repowise security check [REVSPEC]`
+
+Gate a change on security findings it adds.
```bash
-repowise security scan --history
-repowise security scan --history --since v1.0.0 --to HEAD
-repowise security scan --history --all-patterns --format json
+repowise security check origin/main...HEAD --format github --baseline .security-baseline.json
```
-Findings are written to the `security_findings` table (idempotent on re-run)
-and surface in the local server security API / UI. The command prints counts;
-read the findings there.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--fail-on` | Exit 1 at this or above: `high`, `med`, `low` (secrets on test, fixture, spec, mock, example paths). | `high` |
+| `--baseline` | Accept findings in this file; new ones fail. | |
+| `--write-baseline` | Add the change's findings to this file (keeping its and `--baseline`'s); exit 0. | |
+| `--fail-on-baseline-growth` | With `--baseline`: exit 1 on findings the file lacks at the change's base (re-saving hides nothing); new baselines pass. | off |
+| `--path` | Path inside the repository. | cwd |
+| `--staged` | Staged lines from the index (pre-commit hook): no history scan or REVSPEC; working-tree `security.patterns`. | off |
+| `--format` | `table`, `json`, `markdown`, `github`, `sarif`, `gitlab` (GitLab Code Quality report). | `table` |
-#### `repowise security check [REVSPEC]`
+- **CI-ready:** git only (no index, database, API key); stores nothing. Keeps findings on changed lines of touched files
+ at head; checks secrets per commit (added then deleted still fails). Snippets masked.
+- **REVSPEC:** `origin/main...HEAD` (pull-request view), `base..head`, or a commit; else base from CI pull-request variables (GitHub, GitLab, Jenkins, Bitbucket) or the remote default branch.
+- Custom secrets: [`security.patterns`](CONFIG.md#the-security-block). Use `fetch-depth: 0`. Scoping, GitHub Actions SARIF recipe: [In CI](../layers/SECURITY.md#in-ci-repowise-security-check).
-Gate a change on the security findings it adds. Built for CI: it needs git and
-nothing else (no index, no database, no API key) and stores nothing. It scans
-the files the change touched, as its head has them, and keeps the findings on
-changed lines; secret kinds are also checked in every commit of the change, so
-a key committed and then deleted inside it still fails. Snippets are masked in
-every format.
+<details><summary>Silencing a finding</summary>
-REVSPEC is the change: `origin/main...HEAD` (the pull-request view),
-`base..head`, or one commit. Without it, the base comes from the CI's
-pull-request variables (GitHub, GitLab, Jenkins, Bitbucket), else the remote's
-default branch.
+A `repowise-security-ignore` comment silences its own line only (exact, case-sensitive; no next-line or whole-file form).
-| Flag | Description |
-|------|-------------|
-| `--fail-on` | Exit 1 on a finding of this severity or above: `high` (default), `med`, `low`. A secret under a test, fixture, spec, mock or example path is `low` |
-| `--baseline` | Accept the findings recorded in this file; only new ones fail |
-| `--write-baseline` | Add this change's findings to this file, keeping its entries and those of `--baseline`, and exit 0 |
-| `--fail-on-baseline-growth` | With `--baseline`, exit 1 when the file lists a finding the same file at the change's base does not, so a re-saved baseline cannot hide new findings. A baseline the base lacks is new and passes |
-| `--path` | A path inside the repository (defaults to cwd) |
-| `--staged` | Check the staged lines, read from the index, for a pre-commit hook: no history scan, no REVSPEC; `security.patterns` still comes from the working tree |
-| `--format` | `table` (default), `json`, `markdown`, `github`, `sarif`, `gitlab` (GitLab Code Quality report) |
+- Bare: every kind; `: kind, kind`: those (`custom:<name>` for custom patterns); free text: nothing.
+- A secret from an earlier commit stays silenced only if that commit has the marker (squash or rotate).
+- Silenced: never fail or enter `--write-baseline`. JSON: `gate.suppressed` (no matched text), `gate.suppressed_count`;
+ SARIF: `inSource`; table, markdown, `github`: counted; GitLab: omitted, count logged.
-A `repowise-security-ignore` comment on a finding's line silences it:
+</details>
-- The token is exact and case-sensitive and covers its own line only; there is no next-line or whole-file form.
-- Bare, it silences every kind on the line; `: kind, kind` silences only those (`custom:<name>` for a custom pattern). Free text after the colon names no kind and silences nothing.
-- A secret found in an earlier commit of the change stays silenced only if that commit carries the marker; squash or rotate.
-- Silenced findings never fail and never enter `--write-baseline`. JSON lists them in `gate.suppressed` (never the matched text) with `gate.suppressed_count`; SARIF marks them `inSource`; table, markdown and `github` count them; the GitLab report omits them and logs the count.
+**Exit codes.** `0` passed; `1` failed; `2` not evaluable: no git repository, unknown revision, shallow clone missing
+the merge-base or a change commit, unreadable baseline, invalid `security.patterns`, internal error, REVSPEC with
+`--staged`.
-Custom secret shapes go in [`security.patterns`](CONFIG.md#the-security-block).
+---
+
+### `repowise impacted-tests [REVSPEC]`
+
+Tests a change exercises, so CI runs "these 40 tests, not all 4,000".
```bash
-repowise security check origin/main...HEAD
-repowise security check --staged
-repowise security check --format github --baseline .security-baseline.json
-repowise security check --format sarif > security.sarif
-repowise security check --format gitlab > gl-code-quality-security.json
-repowise security check --write-baseline .security-baseline.json
+repowise impacted-tests main..HEAD --format list | xargs pytest
+repowise impacted-tests main...HEAD --format args --runner pytest --prioritize
```
-Exit codes: `0` gate passed, `1` gate failed, `2` could not evaluate (not a git
-repository, unknown revision, a shallow clone missing the merge-base or cutting
-a commit of the change, an unreadable baseline, an invalid `security.patterns`,
-an unexpected internal error, a REVSPEC given with `--staged`). Check out with
-full history (`fetch-depth: 0`). See [In CI](../layers/SECURITY.md#in-ci-repowise-security-check)
-for the scoping rules and a GitHub Actions recipe with SARIF upload.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--path` | Repo path. | cwd / workspace primary |
+| `--staged` | Staged changes (`git diff --cached`). | on with no range outside CI (in CI: the pull request's change) |
+| `--format` | `table`, `json` (report + selection), `list` (an id per line), `args` (runner arguments or `:all`; reasons on stderr). | `table` |
+| `--runner` | For `args`: `auto` (`files` when mixed), `pytest` (node ids or files), `go` (package dirs), `jest` (files; use `--runTestsByPath`), `files`. | `auto` |
+| `--explain` | Test file or node id: why (not) selected (changed file, evidence, import route, or rule), run-order place; JSON `explain`. | |
+| `--prioritize` | With `args`, `list`, `json`: whole suite, selected first; skips nothing; orders full runs. | off |
----
+**REVSPEC**: `base...head` (since the fork, as a pull request), `base..head`, or a commit; none: staged. Looks up
+changed lines (no LLM, no network) in the per-test map from [`repowise coverage add`](#repowise-coverage), naming the
+path that fired:
-### `repowise impacted-tests [REVSPEC]`
+- per-test coverage: covering tests (`via: coverage`);
+- a test file: itself (`via: changed-test`);
+- no coverage rows, reached in the import graph: those tests (`via: import-graph`), under "NOT coverage-backed";
+- else a name match (`via: filename-pattern`), same table;
+- nothing: "unknown, run the full suite" (never "no tests needed");
+- no map: a prompt to `repowise coverage add` a report with contexts, plus graph guesses.
-Print the tests a change actually exercises, so CI can run "these 40 tests, not
-all 4,000". For each changed line it consults the per-test test-to-code map
-built by [`repowise coverage add`](#repowise-coverage) and returns the tests
-whose recorded coverage intersects the diff. No LLM, no network - a straight
-index lookup.
+Only `coverage` proves lines ran; passing others clears nothing. The map needs per-test contexts (coverage.py `.coverage` with dynamic contexts, per-test lcov); score at the ingested `head`.
-`REVSPEC` is a `base...head` range (the change since the branch forked from
-`base`, what a pull request shows), a `base..head` range, or a single commit;
-with no argument (or `--staged`) it diffs the staged changes. It is honest about what it does not
-know, and always says which path fired:
+**Exit codes.** `--format args`: `0` for a subset or all; `2` for an unreadable change (unknown revision, missing
+history) or `tests.*` config. Full runs: [CI](../start/CI.md#selecting-the-tests-a-change-needs).
-- a changed file with per-test coverage -> the exact covering tests (`via: coverage`);
-- a changed file that is itself a test -> itself (`via: changed-test`);
-- a changed file with no coverage rows, but a test reaching it in the import graph -> those test files (`via: import-graph`), in a table headed "NOT coverage-backed";
-- neither of those, but a name-shaped match -> that file (`via: filename-pattern`), in the same table;
-- none of the above -> reported as "unknown, run the full suite" (never implied as "no tests needed");
-- no map ingested at all -> a prompt to run `repowise coverage add` on a report with contexts first, alongside whatever the graph could infer.
+<details><summary>JSON fields and run order</summary>
-The `via` marker is not decoration. `coverage` is proof that a test executed the
-changed lines; the other two are candidates that over-claim, and passing them
-does not clear the change.
+- `indexed_commit`, `map_current`; per-file `selected.basis`: `full-run`, `no-tests-needed`, `test-tree`,
+ `test-package`, `conftest`, `helper-importers`, `deleted-test`, `coverage`, `changed-test`, `call-graph`,
+ `import-graph`, `filename-pattern`, `unknown`, `none` (no index).
+- Per-test `selected.why`: first changed file and evidence, or why it always runs.
+- `selected.broadcast`: test file -> the conftest or test-package `__init__.py` on a route keeping every test under it
+ (sole reason to run). `selected.import_closure`: test file reached only via imports, over one file away, no call path
+ -> distance. Agent views count both apart.
-The map only exists when coverage was ingested from a report that carries
-per-test contexts (a coverage.py `.coverage` written with dynamic contexts, or a
-per-test lcov). Score the same `head` the map was ingested at so line numbers
-line up.
+Run order (`args`, `json`; `list` keeps report order unless `--prioritize`), likeliest failure first:
-**Options:**
+- Tiers: edited by the change; map hits a changed line, then file; calls, fixtures or direct import reach it; reached via other files; runs with every subset.
+- In a tier: failed last local pytest run (`.pytest_cache`, repo-root ids), fewer hops (if measured), more co-changes with changed files, more changed files reached, path.
+- JSON `order`: `tier`, `hops`, `co_change`, `failed_last_run`. `--prioritize` runs a file selected by some node ids whole.
-| Flag | Description |
-|------|-------------|
-| `--path` | Repo path (defaults to cwd / workspace primary) |
-| `--staged` | Diff the staged changes (`git diff --cached`); the default with no range outside CI (in CI: the pull request's change) |
-| `--format` | `table` (default), `json` (full report plus the selection), `list` (test ids one per line), or `args` (one line of runner arguments, or `:all`; reasons on stderr) |
-| `--runner` | For `--format args`: `auto` (default; `files` when mixed), `pytest` (node ids or files), `go` (package dirs), `jest` (files; pass with `--runTestsByPath`), `files` |
-| `--explain` | A test file or node id: say why it was or was not selected (the changed file, the evidence and the import route, or the rule that runs it) and its place in the run order. Added to `--format json` as `explain` |
-| `--prioritize` | With `--format args`, `list` or `json`: the whole suite, the selected tests first in run order, then every other test. Skips nothing; a full run is ordered too |
-
-```bash
-repowise impacted-tests # staged changes
-repowise impacted-tests main...HEAD # a branch / PR (diffed from the merge-base)
-repowise impacted-tests main..HEAD # a plain range
-repowise impacted-tests abc123 # a single commit
-repowise impacted-tests main..HEAD --format list | xargs pytest
-repowise impacted-tests main...HEAD --format args --runner pytest
-repowise impacted-tests main...HEAD --explain tests/unit/test_api.py
-repowise impacted-tests main...HEAD --format args --prioritize
-```
-
-`--format args` exits `0` whether it selects a subset or everything, and `2`
-when it cannot read the change (unknown revision, missing history) or `tests.*`
-in the config. `--format json` adds `indexed_commit`, `map_current` and a
-per-file `selected.basis`: `full-run`, `no-tests-needed`, `test-tree`,
-`test-package`, `conftest`, `helper-importers`, `deleted-test`, `coverage`,
-`changed-test`, `call-graph`, `import-graph`, `filename-pattern`, `unknown`,
-or `none` (no index), and a per-test `selected.why`: the first changed file and
-evidence that selected it, or why it runs with every subset. `selected.broadcast`
-maps each selected test file that runs only because a conftest or test-package
-`__init__.py` on a route keeps every test under it to that file; agent views
-count these apart from the tests the change reaches. `selected.import_closure`
-maps each selected test file the change reaches only through imports, more than
-one file away and with no call path, to its distance; these are counted apart
-too. When it runs everything:
-[CI](../start/CI.md#selecting-the-tests-a-change-needs).
-
-**Run order.** `--format args` and `json` list the selected tests likeliest to fail
-first (`--format list` without `--prioritize` keeps the report's order). Tiers, in
-order: a test the change edits; one the per-test map runs on a changed line, then on
-a changed file; one whose calls, fixtures or direct import reach the change; one
-reaching it through other files; tests that run with every subset. Within a tier:
-a failure in the last local pytest run (`.pytest_cache`, ids relative to the
-repository root), fewer graph hops (when measured), more changes shared with the
-changed files, more changed files reached, then path. `--format json` lists each test under
-`order` with its `tier`, `hops`, `co_change` and `failed_last_run`. With
-`--prioritize`, a file selected only by some node ids runs whole at its place.
+</details>
---
### `repowise health [PATH]`
-Report per-file code-health scores from 51 deterministic detectors (McCabe complexity, nesting, brain methods, LCOM4 cohesion, god classes, native clone detection, untested hotspots, coverage gradient, function/ownership/churn/change-entropy organizational risk, test-quality smells, and more). Zero LLM calls by default, pure Python over tree-sitter + git data. See [`docs/layers/CODE_HEALTH.md`](../layers/CODE_HEALTH.md) for the user guide and [`docs/architecture/code-health.md`](../architecture/code-health.md) for the internals.
-
-By default it reads the analysis the last `repowise init` or `repowise update` stored, the same rows MCP and the web UI serve, and writes nothing. `--recompute` analyzes the working tree in-process instead.
+Per-file scores from 51 deterministic detectors, pure Python over tree-sitter + git; no LLM by default.
+
+```bash
+repowise health # KPIs + lowest-scoring files
+repowise coverage add coverage.lcov && repowise health --recompute # or wait for the next update
+```
+
+Detectors: McCabe complexity, nesting, brain methods, LCOM4 cohesion, god classes, native clones, untested hotspots,
+coverage gradient, function/ownership/churn/change-entropy organizational risk, test-quality smells, more. Guide:
+[`docs/layers/CODE_HEALTH.md`](../layers/CODE_HEALTH.md); internals:
+[`docs/architecture/code-health.md`](../architecture/code-health.md).
+
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--file <path>` | One file in depth (relative path). | |
+| `--module <prefix>` | Files under this path prefix. | all |
+| `--scope` | `all` or `production`: files every figure covers (`production` scores lower with no defect: tests score higher). | `all` |
+| `--counts` | `everything` or `code_shape` (drops the git-derived half, which rises as a file is worked on: is the code itself improving?). | `everything` |
+| `--refactoring-targets` | Stored queue: per file, graph-aware plans (Extract Class / Helper / Method, Move Method, Split File) as ordered steps, Break Cycle advisory; MCP and web UI order. Needs `repowise init`; [REFACTORING.md](../layers/REFACTORING.md). | off |
+| `--recompute` | Analyze the working tree in-process (slow on large repos; needed without an index); see notes. | off |
+| `--score <path>` | Score on-disk files pre-update or PR; repeatable. Bytes give structure, the index the rest (history, coverage, test pairing, dependents), as the next update would; no index: code shape. JSON: `files`, `score_change`. | |
+| `--against <rev>` | With `--score`: before, after, change, nloc-weighted average at `<rev>`. | |
+| `--generate-code <selector>` | Patch for one `path::symbol` target; the only LLM flag (needs a provider). | |
+| `--plan <id>` | Stored plan as an agent prompt; JSON: recipe (preconditions, steps, postconditions). Reads the index. | |
+| `--trend` | Last 10 snapshots + alerts (declining / predicted decline). | off |
+| `--badge` | shields.io badge URL/JSON. | off |
+| `--format` | `table`, `json`, `md`. | `table` |
+| `--repo` | Workspace repo. | primary |
+| `--no-workspace` | Force single-repo mode. | auto-detect |
+| `--verbose`, `-v` | Pipeline debug logs. | off |
+
+- **`--recompute`**: whole-repo `table` runs write scores, findings, trend snapshot to the index; `json`, `md`, `--file`/`--module` never do. Applies `--scope`/`--counts` to `--refactoring-targets`.
+- **Default**: reads, never writes, what `init` / `update` stored (MCP and web UI rows, with `repowise coverage add`
+ coverage). `repowise status`: `Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: <path>)`.
+- **Preview languages**: a dim line per layer and language, e.g. `Refactoring on Java: preview, measured 22% precision
+ on 55 judged plans from 2 Java repos, 2026-10-15` (`repowise dead-code` too). Previews: health on C++; refactoring,
+ performance, dead code on Java, C#, C, C++ (dead code also Kotlin, Swift); none held back.
-When a listed finding or plan sits on a language its layer serves as a preview, the report prints one dim line per layer and language with the measurement behind it, for example `Refactoring on Java: preview, measured 22% precision on 55 judged plans from 2 Java repos, 2026-10-15`. `repowise dead-code` does the same. Today that is health on C++, and refactoring, performance and dead code on Java, C#, C and C++ (dead code on Kotlin and Swift too); no language is held back.
+#### `repowise health check [REVSPEC]`
-**Options:**
+Gate a change on code-health findings it introduces.
-| Flag | Description |
-|------|-------------|
-| `--file <path>` | Deep-dive a single file (relative path) |
-| `--module <prefix>` | Restrict the report to files whose path starts with this prefix |
-| `--scope` | `all` (default) or `production`. Which files every figure describes. Tests score higher than production code, so narrowing lowers the number without a defect being found. |
-| `--counts` | `everything` (default) or `code_shape`. `code_shape` drops the git-derived half of the deduction, which rises as a file is worked on — the reading that answers whether the code itself is improving. |
-| `--refactoring-targets` | Print the refactoring queue the index stored: one opportunity per file with its structured, graph-aware plans (Extract Class / Helper / Method, Move Method, Split File) as ordered steps and Break Cycle as advisory evidence, in the same order MCP and the web UI serve. Reads the index, so it needs `repowise init` first. See [REFACTORING.md](../layers/REFACTORING.md) |
-| `--recompute` | Analyze the working tree in-process instead of reading the stored analysis. A whole-repo `table` run writes the result back to the index (scores, findings, a trend snapshot); `json`, `md` and `--file`/`--module` runs never write. Slow on a large repo; the only option outside an indexed one. With `--refactoring-targets`, `--scope` and `--counts` apply only here. |
-| `--score <path>` | Score these files as they are on disk now (repeatable), before an update or a PR. Structure comes from the bytes; history, coverage, test pairing and dependents from the index, so a file reads as the next update would score it. With no index, the code-shape reading. `--format json` gives `files` and `score_change`. |
-| `--against <rev>` | With `--score`: also score the files at this revision and print before, after and the change, plus the average weighted by nloc at `<rev>`. |
-| `--generate-code <selector>` | Generate an actual refactoring patch for one target. The only `health` flag that calls an LLM; needs a configured provider. |
-| `--plan <id>` | Print one stored refactoring plan as the prompt an agent applies; with `--format json`, its recipe (preconditions, steps, postconditions). Reads the index. |
-| `--trend` | Print the last 10 health snapshots + any active alerts (declining / predicted decline) |
-| `--badge` | Print a shields.io-compatible badge URL/JSON for the repo's health score |
-| `--format` | Output: `table` (default), `json`, `md` |
-| `--repo` | In workspace mode, target a specific repo (defaults to primary) |
-| `--no-workspace` | Force single-repo mode |
-| `--verbose`, `-v` | Show debug logs from the analysis pipeline |
-
-```bash
-repowise health # KPIs + lowest-scoring files
-repowise health --file packages/server/.../app.py # one file in detail
-repowise health --module packages/server # restrict to a directory
-repowise health --refactoring-targets # the stored queue, as MCP serves it
-repowise health --generate-code packages/server/app.py::handler # LLM patch for one target
-repowise health --trend # snapshot history + alerts
-repowise health --counts code_shape # ignore the git-derived half
-repowise health --score src/app.py --against origin/main # live score, before and after
-repowise coverage add coverage.lcov # ingest coverage, then:
-repowise health --recompute # fold it into the scores now (or wait for the next update)
-repowise health --format json | jq .kpis # machine-readable
-```
-
-`repowise init` and `repowise update` populate the health tables automatically -
-no separate command needed. `repowise status` shows a one-line summary
-(`Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: <path>)`).
-Health automatically folds in whatever coverage was already ingested via `repowise coverage add`, no flag needed.
+```bash
+repowise health check origin/main...HEAD --format sarif > health.sarif
+```
-#### `repowise health check [REVSPEC]`
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--fail-on` | `introduced` or `worsened`. | `introduced` |
+| `--fail-at` | Lowest failing severity: `medium`, `high`, `critical`. | `high` |
+| `--diff-risk` | `warn`, `error`, `off`; `LEVEL` for all three rules, `RULE=LEVEL` for one; repeatable. | `warn` |
+| `--path` | Path inside the repository. | cwd |
+| `--format` | `table`, `json`, `markdown`, `github`, `sarif`, `gitlab` (GitLab Code Quality report). | `table` |
-Gate a change on the code-health findings it introduces. Built for CI: it needs git and nothing else (no index, no database, no API key). It analyses the changed files at the change's base and head and compares their findings by file, marker and symbol, never by line.
+Git only (no index, database, API key); matches changed files' base and head findings by file, marker, symbol, never line:
-| Finding | Default | With `--fail-on worsened` |
-|---------|---------|---------------------------|
-| Introduced on lines the change wrote, at `--fail-at` severity or above | fails | fails |
-| Made worse by the change, at `--fail-at` severity or above | warns | fails |
-| Either of those below `--fail-at`, or in a test file | warns | warns |
-| Moved or renamed with its code, away from the changed lines, or not code shape (performance, history, coverage) | context only | context only |
+- Introduced on changed lines, at `--fail-at` or above: fails.
+- Worsened, at `--fail-at` or above: warns; fails with `--fail-on worsened`.
+- Either below `--fail-at`, or in a test file: warns.
+- Moved or renamed with its code, off changed lines, or not code shape (performance, history, coverage): context only.
-| Flag | Description |
-|------|-------------|
-| `--fail-on` | `introduced` (default) or `worsened` |
-| `--fail-at` | Lowest severity that can fail: `medium`, `high` (default), `critical` |
-| `--diff-risk` | Level of the diff-risk rules: `warn` (default), `error` or `off`. `LEVEL` sets all three, `RULE=LEVEL` one; repeatable |
-| `--path` | A path inside the repository (defaults to cwd) |
-| `--format` | `table` (default), `json`, `markdown`, `github`, `sarif`, `gitlab` (GitLab Code Quality report) |
+**Diff-risk rules** read changed text in any supported language; markers moved with their code to another file are ignored.
-Three diff-risk rules read the changed text in any supported language and warn by default: `added-suppression` (a new lint, type-check, coverage or repowise suppression comment or attribute, or a biomarker newly disabled in `.repowise/health-rules.json`), `weakened-tests` (a new unconditional skip or focus marker, fewer test cases or assertions, a loosened coverage threshold) and `test-only-branch` (a new test-environment check in production code). A marker that moved to another file with its code does not count.
+- `added-suppression`: new lint, type-check, coverage or repowise suppression comment or attribute, or biomarker newly disabled in `.repowise/health-rules.json`.
+- `weakened-tests`: new unconditional skip or focus marker, fewer test cases or assertions, looser coverage threshold.
+- `test-only-branch`: new test-environment check in production code.
-REVSPEC is the change, resolved as for [`security check`](#repowise-security-check-revspec). Rules in `.repowise/health-rules.json` are read as the change's base has them and apply to both sides, so a change cannot loosen its own gate; an invalid file there exits `2`. A changed code file left unread (unparsable, or over 1.5 MB) warns; a change touching no file health reads passes with a note.
+**REVSPEC** as for [`security check`](#repowise-security-check-revspec). Both sides use the base's
+`.repowise/health-rules.json`; a change cannot loosen its gate. An unread code file (unparsable, over 1.5 MB) warns;
+touching no readable file passes with a note.
-```bash
-repowise health check origin/main...HEAD
-repowise health check --format github
-repowise health check --format sarif > health.sarif
-```
-
-Exit codes: `0` passed (warnings included), `1` gate failed, `2` could not evaluate (not a git repository, unknown revision, no merge-base in a shallow clone, an invalid `health-rules.json` at the base, more than 300 changed code files, no changed code file could be read, an unexpected internal error).
+**Exit codes.** `0` passed (warnings included); `1` failed; `2` not evaluable: no git repository, unknown revision, no
+merge-base in a shallow clone, invalid `health-rules.json` at the base, over 300 changed code files, no readable changed
+code file, internal error.
---
@@ -1229,129 +942,121 @@ Exit codes: `0` passed (warnings included), `1` gate failed, `2` could not evalu
Manage architectural decision records.
-**Subcommands:**
-
-```bash
-repowise decision list [PATH] # list records
-repowise decision show ID [PATH] # full details
-repowise decision add [PATH] # interactive add
-repowise decision add --kind agreement # a rule about how the work is done
-repowise decision candidates [PATH] # what is awaiting review; these govern nothing
-repowise decision confirm ID... [PATH] # accept candidates: this is what makes them govern
-repowise decision confirm ID --agent SLUG # an agent signing as itself, not as you
- # (also on dismiss and deprecate)
-repowise decision dismiss ID... [PATH] # tombstone them (sticky; never re-proposed)
-repowise decision merge ID INTO_ID # fold a candidate into an existing decision
-repowise decision dedupe [PATH] # fold candidates that duplicate another candidate (dry run by default)
-repowise decision split ID [PATH] # flag a candidate as bundling two choices
-repowise decision deprecate ID [PATH] # retire a decision, optionally naming its successor
-repowise decision health [PATH] # health dashboard
-repowise decision status [PATH] # what capture did, and what it cost
-
-repowise decision export [PATH] # write accepted decisions to .repowise/decisions.yaml
-repowise decision import [PATH] # reconcile the store to that file
-repowise decision migrate [PATH] # classify pre-split rows (dry run unless --apply)
-
-repowise decision config show [PATH] # the resolved capture policy
-repowise decision config preset NAME [PATH] # default | off | local_only | balanced | full
-repowise decision config discovery [PATH] # budget for the one broad discovery call
-repowise decision config agent-acceptance --on|--off # may an agent grant authority? off by default
-repowise decision config capture-prompt --on|--off # ask the agent to record what it just committed;
- # off by default, and --on installs the shell hook it needs
-repowise decision source list [PATH] # the source registry and its state
-repowise decision source set SRC --on|--off # switch one source
-repowise decision source set SRC --llm|--no-llm # switch only its model stage
-repowise decision llm --on|--off [PATH] # all decision-extraction model calls
-```
-
-**Review options:**
-
-| Flag | Description |
-|------|-------------|
-| `--reason TEXT` | On `confirm`: the rationale, or why a constraint needs none. Also corrects the record. |
-| `--scope PATH` | On `confirm`: a file or module this governs. Repeatable, and replaces the proposed scope. |
-| `--evidence REF` | On `confirm`: a commit, file or link it rests on. Repeatable. |
-| `--as NAME` | On `confirm`: record a different accepter than the repo's git identity. |
-| `--preview` | On `confirm` and `dismiss`: report what each id would do, and write nothing. |
-| `--reason TEXT` | On `dismiss`: why it was tombstoned. |
-| `--superseded-by ID` | On `deprecate`: writes an explicit lineage edge and keeps the retired id resolving. |
-| `--state STATE` | On `candidates`: `open` (default), `accepted`, `merged`, `needs_split`, `dismissed`, `all`. |
-| `--lane NAME` | On `candidates`: only candidates raised by that extraction lane (`pr`, `session`, `session_discovery`, `comment`, `git_archaeology`, `adr`, `inline_marker`, `conventions`, `cli`). Unrelated to the review lanes the Decisions page splits on. |
-| `--apply` | On `migrate`: write the plan. Without it the command reports and writes nothing. |
-| `--dry-run` | On `import`: report and write nothing. |
-
-`candidates` is a review queue, so it leads with the candidates the acceptance
-contract would take, as judged at the last index, and puts the rest below them.
-Its `Acceptable` column is either `yes` or the same blockers `confirm` would
-refuse with, so the work you can finish and the work waiting on somebody is
-separated before you start. Under `--format json` each row carries a `blockers`
-array.
-
-`confirm` refuses rather than storing a blank acceptance: a candidate needs a
-reason, a scope and an evidence reference, and the flags above supply whatever
-is missing. Under `--format json` the refusal is a document
-(`{"error": "acceptance_refused", "blockers": [...]}`) and the exit code is 1,
-so a scripted review can tell it apart from a crash.
-
-`confirm` and `dismiss` take one id or many, with the optional repository path
-still last. A refused id does not stop the others, and each id is applied
-independently, so a batch that refuses one commits the rest and exits 1.
-`--preview` puts every id through the same acceptance contract and then rolls
-the whole run back, so what it reports is what the write would have said.
-
-One id keeps the transition document those verbs already emitted
-(`{"id", "status", "action"}`). Two or more, or `--preview`, emit a results
-document instead:
-
-```json
-{
- "action": "accepted",
- "preview": false,
- "results": [
- {"given": "9f3c", "id": "...", "title": "...", "ok": true, "action": "accepted", "status": "active"},
- {"given": "2b70", "id": "...", "title": "...", "ok": false,
- "error": "acceptance_refused", "blockers": ["no scope: name the files or modules it governs"]}
- ],
- "succeeded": 1,
- "failed": 1
-}
-```
-
-**Capture-control options:**
-
-| Flag | Description |
-|------|-------------|
-| `--dry-run` | Print the change and write nothing. On `config preset`, `config discovery`, `source set`, `llm`. |
-| `--format` | `table` (default) or `json`. `json` returns the full source registry. |
-| `--max-sessions` | `config discovery` only: session deltas one broad call may read (1-24, default 12). |
-| `--max-input-tokens` | `config discovery` only: input-token ceiling for one broad call (2000-60000, default 30000). |
-
-`config discovery` with neither budget flag just prints the resolved policy.
-Broad discovery itself is a source, so it is switched with
-`repowise decision source set session_discovery --on|--off`; it is off in the
-`default` policy and on in the `balanced` and `full` presets.
-
-`confirm` is the acceptance event. Nothing else promotes a record to `active`:
-extraction, recurrence across sessions, and confidence all stop at `proposed`.
-
-`--status` filters the status column, which is a projection of the acceptance
-kept in step for readers that predate the split, so it is not the same question
-as "what governs". `repowise decision candidates` is the authoritative list of
-what nobody has accepted, and the Decisions page splits the same repository
-into five lanes over the acceptance join.
-
-**Reporting on capture:** `repowise decision status` answers what the sources
-actually did, in one screen: the effective policy and preset, every source with
-its state and the reason it made no call, what each one has captured and when,
-the five review lanes, how much of the unreviewed backlog a reviewer can accept
-today against how much is blocked, the age of that backlog, the staging queues,
-and the model spend booked to decision extraction.
-
-Nothing records a capture run, so every figure is derived from a durable trace
-rather than a run ledger. That has two consequences the command states rather
-than papering over: spend is all-time with the last call named, because no
-stored boundary says which call belonged to which run; and a queue that a
-store predates is reported absent rather than as zero.
+```bash
+repowise decision list
+repowise decision show ID
+repowise decision add # interactive
+repowise decision add --title T --decision D # no prompts, lands proposed
+repowise decision candidates # awaiting review; these govern nothing
+repowise decision confirm ID... # accept: this makes them govern
+repowise decision dismiss ID... # tombstone (sticky; never re-proposed)
+repowise decision merge ID INTO_ID # fold into an existing decision
+repowise decision dedupe # fold duplicate candidates (dry run unless --apply)
+repowise decision split ID # flag as bundling two choices; never splits it
+repowise decision deprecate ID # optionally naming its successor
+repowise decision health
+repowise decision status # what capture did and cost
+repowise decision export # accepted decisions to .repowise/decisions.yaml
+repowise decision import # reconcile the store to that file
+repowise decision migrate # classify pre-split rows (dry run unless --apply)
+repowise decision config show # resolved capture policy
+repowise decision config preset NAME # default | off | local_only | balanced | full
+repowise decision config discovery # broad discovery call budget
+repowise decision config agent-acceptance --on|--off # may an agent grant authority? (off)
+repowise decision config capture-prompt --on|--off # agent records what it committed (off);
+ # --on installs the shell hook
+repowise decision source list # source registry and state
+repowise decision source set SRC --on|--off # switch one source
+repowise decision source set SRC --llm|--no-llm # switch only its model stage
+repowise decision llm --on|--off # all decision-extraction model calls
+```
+
+Every subcommand takes `--format` (`table` default, or `json`) and an optional `[PATH]` last.
+
+**`add`**
+
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--title` | Short title. | |
+| `--decision` | What was chosen. | |
+| `--context` | What forced it. | |
+| `--rationale` | Why. | |
+| `--alternative` | Rejected alternative. Repeatable. | |
+| `--consequence` | Accepted tradeoff. Repeatable. | |
+| `--affects` | File or module governed. Repeatable. | |
+| `--tag` | Tag. Repeatable. | |
+| `--evidence-commit` | Commit it was made in. Repeatable. | |
+| `--kind` | `architectural` governs code; `agreement` governs how work is done (no files, never checked against code). | `architectural` |
+
+- `--title` plus `--decision`: no prompts, prints the new id. Any flag, or `--format json`, without both is refused.
+- Flag-driven records land `proposed`, interactive `active`; promote with `repowise decision confirm <id>`.
+
+**`candidates`**
+
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--state` | `open`, `accepted`, `merged`, `needs_split`, `dismissed`, `all`. | `open` |
+| `--lane` | Extraction lane: `pr`, `session`, `session_discovery`, `comment`, `git_archaeology`, `adr`, `inline_marker`, `conventions`, `cli`. Not the Decisions page review lanes. | all lanes |
+| `--limit` | Max listed. | `30` |
+
+**`confirm`, `dismiss`, `deprecate`, `split`**
+
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--reason TEXT` | `confirm`: rationale, or why a constraint needs none; corrects the record. `dismiss`: why. `split`: what the two choices are. | |
+| `--scope PATH` | `confirm`: file or module governed. Repeatable; replaces the proposed scope. | proposed scope |
+| `--evidence REF` | `confirm`: commit, file or link. Repeatable. | |
+| `--as NAME` | `confirm`: accepter other than git identity. | git identity |
+| `--superseded-by ID` | `deprecate`: lineage edge to the replacement; deprecated id keeps resolving. | |
+| `--agent SLUG` | Not `split`: sign as an agent (e.g. `claude_code`). | |
+| `--session ID` | Not `split`: signing agent session. | |
+| `--yes` / `-y` | `dismiss`: skip the prompt (as does `--format json`). | off |
+| `--preview` | `confirm`, `dismiss`: report each id's outcome, write nothing. | off |
+
+**`dedupe`, `migrate`, `export`, `import`**
+
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--apply` | `dedupe`, `migrate`: write the plan; else report only. | off |
+| `--tau` | `dedupe`: cosine fold threshold, `0.5` to `1.0`. | `0.83` |
+| `--limit` | `dedupe`: clusters listed. `migrate`: reasons listed. | `10` |
+| `--force` | `export`: overwrite a committed manifest from a store that accepted nothing. | off |
+| `--dry-run` | `import`: write nothing. | off |
+
+**`list`**
+
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--status` | `active`, `proposed`, `deprecated`, `superseded`, `dismissed`, `all`. | `all` |
+| `--source` | `adr`, `cli`, `comment`, `commit`, `conventions`, `git_archaeology`, `inline_marker`, `llm_inferred`, `pr`, `session`, `all`. | `all` |
+| `--proposed` | `--status proposed`. | off |
+| `--stale-only` | Only stale. | off |
+
+**Capture control**
+
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--dry-run` | `config preset`, `config discovery`, `source set`, `llm`: print the change, write nothing. | off |
+| `--format` | `json` returns the full source registry. | `table` |
+| `--max-sessions` | `config discovery`: session deltas one broad call reads (1-24). | `12` |
+| `--max-input-tokens` | `config discovery`: input-token ceiling per broad call (2000-60000). | `30000` |
+
+- `config discovery` without budget flags prints the resolved policy. Broad discovery is the `session_discovery` source: off in `default`, on in `balanced` and `full`.
+
+**Acceptance.** Only `confirm` promotes to `active`; extraction, recurrence across sessions and confidence stop at `proposed`.
+
+- `confirm` needs a reason, a scope and an evidence reference (flags supply what is missing), else refuses. JSON refusal: `{"error": "acceptance_refused", "blockers": [...]}`, exit 1 (not a crash).
+- `candidates` lists first what the contract would accept at the last index; `Acceptable` reads `yes` or `confirm`'s blockers (JSON: `blockers`).
+- `list --status` filters a status column kept for pre-split readers, not "what governs"; `candidates` is the
+ authoritative unaccepted list. The Decisions page shows five lanes over the acceptance join.
+- `confirm` and `dismiss` take many ids, each applied independently: a refused id commits the rest and exits 1. `--preview` runs the contract, then rolls back.
+- JSON: one id emits `{"id", "status", "action"}`; several, or `--preview`, emit `action`, `preview`, `succeeded`,
+ `failed` and `results[]` (`given`, `id`, `title`, `ok`, then `action` / `status` or `error` / `blockers`, e.g. `"no
+ scope: name the files or modules it governs"`).
+
+**`status`.** Policy, preset; per source: state, why no call, what it captured and when; five review lanes, backlog
+acceptable today versus blocked, its age; staging queues; decision-extraction model spend. No run ledger: spend is
+all-time with the last call named; a queue the store predates reads absent, not zero.
```
repowise decision status
@@ -1366,1091 +1071,1010 @@ repowise decision status
session_discovery disabled 0 0 - This source is switched off.
```
-**Scripting these:** every subcommand takes `--format json`, and `confirm`,
-`dismiss`, `deprecate`, and `show` exit non-zero on an unknown id with
-`{"error": "decision_not_found", "decision_id": "..."}` so a caller can tell a
-typo from a successful transition. `dismiss` skips its confirmation prompt under
-`--format json`, or with `--yes`.
-
-**List options:**
-
-| Flag | Description |
-|------|-------------|
-| `--status` | `active`, `proposed`, `deprecated`, `superseded`, `dismissed`, `all` |
-| `--source` | `adr`, `cli`, `comment`, `commit`, `conventions`, `git_archaeology`, `inline_marker`, `llm_inferred`, `pr`, `session`, `all` |
-| `--proposed` | Shortcut for `--status proposed` |
-| `--stale-only` | Only stale decisions |
-| `--format` | `table` (default) or `json` |
-
-`--format json` is available on every `decision` subcommand. In JSON, `decision list` emits full ids rather than the table's 8-character prefixes, and `show` / `health` skip the caps the human output applies to keep a panel readable.
+**Scripting.** Unknown id: `confirm`, `dismiss`, `deprecate`, `show` exit non-zero with `{"error": "decision_not_found",
+"decision_id": "..."}`. JSON `list` gives full ids (table: 8-character prefixes); JSON `show` / `health` skip display
+caps.
---
### `repowise coverage`
-Ingest and inspect test-coverage reports, and gate a change on its patch
-coverage in CI. Coverage is auto-discovered and ingested during `init` /
-`update`; `add` is the manual path, point it at a report (or let it
-auto-discover one) to populate per-file line/branch coverage, which clears
-`untested_hotspot` findings for files that are tested regardless of where
-their tests live.
-
-**Subcommands:**
+Ingest coverage reports and gate a change on patch coverage in CI.
```bash
-repowise coverage add [PATHS...] # ingest coverage reports (+ per-test map when contexts are present)
-repowise coverage status # show ingested coverage + the map
-repowise coverage check [REVSPEC] # gate a change on its patch coverage (CI)
-repowise coverage suggest-gates # propose path-scoped gates for coverage.gates
-```
-
-**`add` options:**
-
-| Flag | Description |
-|------|-------------|
-| `--path` | Repo path (defaults to cwd / workspace primary) |
-| `--format` | Force a parser instead of auto-detecting: `lcov`, `cobertura`, `clover`, `repowise-json`, `go-coverprofile`, `jacoco` |
-| `--strict` | Also exit non-zero when some report files did not map to the repo tree |
-| `--allow-partial` | Store the coverage even when more than half the report did not map to the repo tree; the rows are flagged partial |
-| `--verbose` / `-v` | Show debug logs while discovering and ingesting coverage |
-
-When more than half the report did not map to the repo tree, `add` stores
-nothing, exits `1`, and suggests the `coverage.strip_prefix` or
-`coverage.path_prefix` that would map it. `init` and `update` keep no coverage
-from such a report either, so an `update` that re-reads it clears a fragment
-stored with `--allow-partial`.
-
-Each `PATH` is a report path or a quoted glob, relative to cwd, as in
-`coverage check --report`; only when it matches nothing is it read as
-`PATH=PREFIX`, prepending `PREFIX` to the paths inside the report (like
-`path_prefix` in `coverage.paths`). A `PATH` matching no file exits 2. A
-successful ingest also syncs the opt-in coverage re-ingest hook
-(`hooks.coverage_reingest`).
-
-`add` ingests per-file line/branch coverage from LCOV, Cobertura, Clover,
-JaCoCo XML, or a Go coverprofile (`go test -coverprofile`). A coverage.py
-`.coverage` file records the lines that ran but not which lines are executable,
-so it gives the per-test map only; export it with `coverage lcov` for per-file
-coverage. It auto-discovers `coverage/lcov.info`, `.coverage`,
-`coverage.out`, `target/site/jacoco/jacoco.xml`, and similar reports when no
-path is given, and
-merges multiple reports (hit wins). When the report carries per-test contexts,
-a coverage.py `.coverage` recorded with per-test contexts
-(`pytest --cov=<package> --cov-context=test`, needs pytest-cov), or a
-per-test lcov, `add` also builds the per-test *test-to-code map*, which test
-covers which source lines. A text report without contexts still ingests the
-per-file coverage; it just skips the map.
-
-```bash
-repowise coverage add # discover coverage/lcov.info, .coverage, etc.
-repowise coverage add coverage/lcov.info
-repowise coverage add web.lcov api.lcov # merged, hit wins
-repowise coverage add 'artifacts/**/lcov.info' # every shard's report
-repowise coverage add web/coverage/lcov.info=web # report paths are relative to web/
-repowise coverage add --verbose # show ingestion debug logs
-pytest --cov=<package> --cov-context=test # produce .coverage with contexts (needs pytest-cov)
-repowise coverage add .coverage # per-test map
-repowise coverage status # coverage summary + "Test-to-code map" counts
-repowise coverage status --format json # machine-readable (note: the --format on `coverage add` names the input parser instead)
-```
-
-> The per-test map is a separate dimension from the per-file aggregate that
-> `add` always stores (a file is covered, merged over all tests) and from what
-> `health` reads. It's used to answer "which tests exercise this change".
+repowise coverage add [PATHS...] # ingest (+ per-test map when contexts exist)
+repowise coverage status # ingested coverage + "Test-to-code map" counts
+repowise coverage check [REVSPEC] # gate a change on patch coverage (CI)
+repowise coverage suggest-gates
+repowise coverage add web.lcov api.lcov # merged, hit wins
+repowise coverage add 'artifacts/**/lcov.info' # every shard
+repowise coverage add web/coverage/lcov.info=web # paths relative to web/
+pytest --cov=<package> --cov-context=test # .coverage with contexts (needs pytest-cov)
+repowise coverage add .coverage # per-test map
+```
+
+`init` / `update` auto-ingest; `add` is the manual path. Per-file line/branch coverage clears `untested_hotspot` for tested files wherever their tests live.
+
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--path` | Repo path. | `add`: cwd / workspace primary; `status`: cwd |
+| `--format` | `add`: force a parser (`lcov`, `cobertura`, `clover`, `repowise-json`, `go-coverprofile`, `jacoco`). `status`: `table` or `json`. | `add`: auto-detect; `status`: `table` |
+| `--strict` | `add`: also exit non-zero when some report files do not map. | off |
+| `--allow-partial` | `add`: store even when over half does not map; rows flagged partial. | off |
+| `--verbose` / `-v` | `add`: debug logs. | off |
+
+- `PATH`: report path or quoted glob, relative to cwd, as in `check --report`; read as `PATH=PREFIX` (like `path_prefix`
+ in `coverage.paths`) only when it matches nothing. No match exits 2. Success syncs the opt-in hook
+ `hooks.coverage_reingest`.
+- Over half unmapped: stores nothing, exits `1`, suggests a `coverage.strip_prefix` or `coverage.path_prefix`. `init` /
+ `update` keep nothing from it, so their re-read clears an `--allow-partial` fragment.
+- Formats: LCOV, Cobertura, Clover, JaCoCo XML, Go coverprofile (`go test -coverprofile`). With no path, discovers
+ `coverage/lcov.info`, `.coverage`, `coverage.out`, `target/site/jacoco/jacoco.xml` and similar.
+- *Test-to-code map* (which test covers which lines: "which tests exercise this change"): from a context-recorded
+ `.coverage` or per-test lcov; without contexts, per-file only. Separate from the per-file aggregate and `health`.
+ `.coverage` lacks executable lines, so gives only this map; `coverage lcov` exports per-file data.
#### `repowise coverage check [REVSPEC]`
-Gate a change on its **patch coverage**: of the changed lines the report calls
-executable, the share the tests ran. Built for CI: it needs git and a coverage
-report, nothing else (no index, no LLM key). Report paths are resolved against
-`git ls-files`, so a file the change adds resolves too.
-
-`REVSPEC` is the change: `base...head` (the change since the branch forked
-from `base`, the pull-request view), `base..head`, or a single commit. Without
-it the check diffs `<base>...HEAD`, taking the base branch from `GITHUB_BASE_REF`,
-`CI_MERGE_REQUEST_TARGET_BRANCH_NAME`, `CHANGE_TARGET` or
-`BITBUCKET_PR_DESTINATION_BRANCH` (read as `origin/<name>`),
-else `origin/HEAD`, a local `main` / `master`, or `origin/main` /
-`origin/master`; with none of those it exits 2 and asks for `REVSPEC`. Pass it
-explicitly in CI so the job says what it measures.
-
-Reports come from `--report`, else `coverage.paths` in `.repowise/config.yaml`,
-else discovery (when `coverage.auto_discover` is on) of the usual locations,
-including `coverage/lcov.info`, `coverage.xml`, `coverage.out`,
-`**/target/site/jacoco*/jacoco.xml` and a root-module
-`build/reports/jacoco/**/*.xml`. A nested Gradle module's report needs
-`--report`. Config is read at the repository root (git toplevel), even with
-`--path`.
-
-A changed comment or blank line is neither covered nor uncovered. Each changed
-file lands in one status:
-
-| Status | Meaning | Counts toward the % |
-|--------|---------|---------------------|
-| `measured` | The report names the file and some changed lines are executable | Yes |
-| `no_coverable_changes` | The report names the file, but no changed line is executable | No |
-| `not_in_report` | Code of a kind the report measures (same extension), but the report does not name it, e.g. a new untested file | No, listed as "not in report", never 0% |
-| `no_line_data` | The report names the file but carries no executable-line set for it | No |
-
-Changed test files and file types the report never measures (docs, config)
-are out of scope and only counted.
-
-**Options:**
-
-| Flag | Description |
-|------|-------------|
-| `--report` | Coverage report to read: a path or a glob (`artifacts/**/lcov.info`), relative to cwd; `**` skips dependency, cache and build directories. `PATH=PREFIX` prepends `PREFIX` to that report's paths: the whole argument is tried first, and only when it matches nothing is it split on the last `=`. Repeatable, merged hit-wins. Defaults to `coverage.paths`, else discovery |
-| `--report-format` | Force a parser: `lcov`, `cobertura`, `clover`, `repowise-json`, `go-coverprofile`, `jacoco` |
-| `--fail-under` | Exit 1 when patch coverage is below this percentage (0-100). Defaults to `coverage.fail_under` in `.repowise/config.yaml`; with neither set the command reports without gating |
-| `--min-coverable-lines` | Small-change tolerance: a change with fewer changed executable lines than this (counting only lines the report measures, as the percentage does) is reported against the threshold but never fails (`gate` reads `too_small`). Defaults to `coverage.min_coverable_lines` |
-| `--fail-under-risky` | Exit 1 when patch coverage of the risky files alone is below this percentage. Risky: hotspots or bug magnets from the index; on git alone, the top quartile of files with bug-fix history. Defaults to `coverage.fail_under_risky`. With no risky file changed the gate is not applied (`no_data`, exit `0`) |
-| `--fail-under-branches` | Exit 1 when the share of branches taken on changed lines is below this percentage (0-100), never blended with patch coverage. Defaults to `coverage.fail_under_branches`. No changed branching line: not applied (`no_data`, exit `0`) |
-| `--base-report` | Report measured at the change's base commit (the merge-base for `A...B`), read like `--report`, repeatable. Adds `project` |
-| `--max-drop` | Exit 1 when project coverage falls more than this many points from the base (0-100). Defaults to `coverage.max_drop`. Needs `--base-report` or an index's ingest at the base commit |
-| `--path` | A path inside the repository (defaults to cwd) |
-| `--format` | `table` (default), `json`, `markdown`, or `github` |
-
-Each changed file carries its risk: git bug-fix history always, plus hotspot,
-bug-magnet and dependent counts when an index opens (a missing index never
-fails the check). Rows, annotations and the markdown table list risky files
-first, and the table has a "Risk" column in words. With an index, each
-uncovered range also names the test file to extend when one is found: an
-"Extend" column in the table and markdown ("extend tests/test_auth.py
-(inferred: calls reach `login`)", "(measured: runs other lines of `login`)",
-"(inferred: imports this file)", or "no test reaches this; add one"), the same
-phrase at the end of each annotation, and `hints` in `json`. Hints never
-change the verdict.
-
-`github` writes up to 10 `::warning` annotations (riskiest file, then largest
-uncovered range, first; titled "Uncovered change in a risky file" for a risky
-one), a `::notice` counting the rest, an `::error::` for each gate that fails
-(the whole change, each path-scoped gate that is not informational, the
-risky-file gate, the branch gate), a `::notice::` per informational gate below
-its threshold, a `::notice::` when the small-change tolerance exempts a gate or
-a branch gate was set but not applied, a `::warning` titled "Partly taken
-branch" per partly taken range (sharing the cap), then
-appends the markdown summary to `$GITHUB_STEP_SUMMARY` when set. `json`
-carries `patch_coverage_pct`, `covered_line_count`, `coverable_line_count`,
-`threshold`, `min_coverable_lines`, `gate` (`pass`, `fail`, `no_data`,
-`not_set`, `too_small`; `fail` when any gate fails), `file_counts`
-(`measured`, `not_in_report`, `no_line_data`, `no_coverable_changes`,
-`stale_file` (stored coverage only, always 0 here), `out_of_scope`), `files[]` (`file_path`, `status`, `changed_line_count`,
-`coverable_line_count`, `covered_line_count`, `patch_coverage_pct`,
-`uncovered_ranges`, `branch_taken`, `branch_total`, `partial_ranges` (0 and
-empty without branch data), `risk`: `fix_pressure`, `dependents`, `hotspot`,
-`bug_magnet`, `basis`, `risky`, `reasons`; `hints`, null without an index, one
-per uncovered range: `range`, `symbol`, `tests`, `basis` (`per_test`,
-`call_graph`, `import_graph`, `none`), `total`), `scope` (`label`,
-`source_formats`, `reports`, `report_path_count`,
-`unmatched_report_path_count`, `ignored_file_count`, `config_errors`,
-`branch_data`: `per_line`, `none` or `stored_before`),
-`path_gates[]` (`name`, `paths`, `threshold`, `informational`,
-`measured_file_count`, `unmeasured_file_count`, `covered_line_count`,
-`coverable_line_count`, `patch_coverage_pct`, `gate`), `risky`
-(`file_count`, `covered_line_count`, `coverable_line_count`,
-`patch_coverage_pct`, `threshold`, `gate`) and `project`, null without a base
-measurement (`basis`: `base_report` or `history`, `base_commit`,
-`head_commit`, `base` and `head` with `covered_line_count`,
-`coverable_line_count`, `coverage_pct`, `delta_pct` in points, `max_drop`,
-`gate`, `incomparable` reasons, `outside_change_note`, and `outside_change[]`,
-null on the history basis or when most files did not line up:
-`file_path`, `status` (`changed`, `no_longer_measured`),
-`newly_uncovered_ranges`, `newly_uncovered_line_count`,
-`newly_covered_line_count`, `base_pct`, `head_pct`, `causes`: `kind`
-(`test_deleted`, `test_modified`, `dependent_changed`), `path`, `basis`
-(`per_test`, `graph`, `name`)), and `branches`, null when no changed line has
-branch data and no branch gate was set (`branch_taken`, `branch_total`,
-`branch_coverage_pct`, `partial_line_count`, `threshold`, `gate`). The
-markdown and `github` formats also list files that lost coverage outside the
-change. Changed files and report entries
-matching `coverage.ignore` (gitignore syntax) are left out and counted as
-ignored. Go coverprofile paths under a `go.mod`'s module path are mapped to
-that module's directory unless the report has a per-report prefix or
-`coverage.path_prefix` is set. Percentages are shown floored to one decimal
-(79.99% reads 79.9%); the gate compares the unrounded figure.
-
-**Exit codes:** `0` the gate passes or there is nothing to judge (no
-threshold, no measurable changed lines, or a change under the small-change
-tolerance); `1` patch coverage is below `--fail-under`, a path-scoped gate
-that is not informational fails, the risky files' is below
-`--fail-under-risky`, the branches taken on changed lines are below
-`--fail-under-branches`, or project coverage fell more than `--max-drop` points;
-`2` the check could not run: no report found, a
-`--report` path or glob matching no file, none readable, none matching a
-repository file, or every entry matching `coverage.ignore`; an unknown
-revision; no merge-base (a shallow clone); a single commit at a shallow
-clone's boundary; bad config or a malformed `coverage.fail_under` /
-`coverage.min_coverable_lines` / `coverage.fail_under_risky` /
-`coverage.fail_under_branches`, or an unusable
-`coverage.gates` entry (named in the message); not a git repository;
-`--fail-under-risky` set on a shallow clone, or with a measured file whose
-risk could not be read (unless the flat, a path-scoped or the branch gate
-already failed, which exits `1`); `--fail-under-branches` over coverage with
-no per-line branch data (`no_branch_data`; from `coverage.fail_under_branches`
-alone it is a note, exit `0`); under the `--max-drop` or `--base-report` flag,
-a base that is missing, not comparable with the head, or has no coverable line
-on a side (same exception; from `coverage.max_drop` alone it is a note, exit `0`).
-
-**Path-scoped gates.** Each entry of `coverage.gates` (`name`, `paths` as
-gitignore-style globs relative to the repository root, optional `fail_under`
-0-100, optional `informational`) is judged on the measured changed files its
-globs match, with the same rule as the whole change; a file can count in
-several gates. The small-change tolerance is the whole change's: every gate
-(the risky-file gate too) reads `too_small` when the change is under
-`min_coverable_lines`, never a small slice of a big one. Matching changed
-files the report does not measure are counted as `unmeasured_file_count`,
-outside the percentage. `gate` reads `fail` when any gate that is not
-informational fails, whatever the whole-change figure, and the headline then
-leads with that gate and its counts. The table output lists every gate; the
-markdown lists up to 10, failing ones first. See
-[Path-scoped gates](../start/CI.md#path-scoped-gates) and
-`repowise coverage suggest-gates`.
-
-A coverage.py `.coverage` database is not a text report: export it first with
-`coverage lcov` or `coverage xml`. A new file no test loads must still appear
-in the report, or it is "not in report" and not counted; the per-language
-commands are in
-[Coverage reports per language](../start/CI.md#coverage-reports-per-language).
+Gate a change on its **patch coverage**: the share of changed executable lines the tests ran.
```bash
repowise coverage check origin/main...HEAD --report coverage/lcov.info --fail-under 80
-repowise coverage check HEAD --format json # one commit, machine-readable
-repowise coverage check origin/main...HEAD --report coverage.out --report-format go-coverprofile
repowise coverage check origin/main...HEAD --report 'artifacts/**/lcov.info' --min-coverable-lines 5
-repowise coverage check origin/main...HEAD --report web/coverage/lcov.info=web
```
-CI clones are often shallow, so the merge-base is missing and the check exits 2.
-Fetch full history. The GitHub Action, the GitLab template and recipes for
-other CI systems are in [Repowise in CI](../start/CI.md).
+Needs only git and a report (no index, no LLM key). Paths resolve against `git ls-files`, added files included.
+
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--report` | Path or glob, relative to cwd; `PATH=PREFIX` as in `add`. Repeatable, merged hit-wins. | `coverage.paths`, else discovery |
+| `--report-format` | Force a parser (as `add --format`). | auto-detect |
+| `--fail-under` | Exit 1 below this % (0-100). Unset anywhere: no gating. | `coverage.fail_under` |
+| `--min-coverable-lines` | Fewer changed measured executable lines: reported, never fails (`too_small`). | `coverage.min_coverable_lines` |
+| `--fail-under-risky` | Exit 1 when risky files' % is below this. | `coverage.fail_under_risky` |
+| `--fail-under-branches` | Exit 1 when branches taken on changed lines are below this % (0-100); never blended. | `coverage.fail_under_branches` |
+| `--base-report` | Report at the base (merge-base for `A...B`), read like `--report`, repeatable. Adds `project`. | |
+| `--max-drop` | Exit 1 when project coverage drops over this many points (0-100). Needs `--base-report` or an index ingest at the base. | `coverage.max_drop` |
+| `--path` | Path inside the repo. | cwd |
+| `--format` | `table`, `json`, `markdown`, `github`. | `table` |
+
+- `--report`: `**` skips dependency, cache, build dirs; `=` splits on the last one.
+- Risky: index hotspots or bug magnets, else the top bug-fix quartile. No risky or no branching changed line: `no_data`, exit `0`.
+- REVSPEC: `base...head` (since the fork, the PR view), `base..head`, or one commit; explicit in CI. Omitted:
+ `<base>...HEAD`, base from `GITHUB_BASE_REF`, `CI_MERGE_REQUEST_TARGET_BRANCH_NAME`, `CHANGE_TARGET` or
+ `BITBUCKET_PR_DESTINATION_BRANCH` (as `origin/<name>`), else `origin/HEAD`, local `main` / `master`, `origin/main` /
+ `origin/master`; else exit 2.
+- Reports: `--report`, else `coverage.paths` in `.repowise/config.yaml`, else (with `coverage.auto_discover`)
+ `coverage/lcov.info`, `coverage.xml`, `coverage.out`, `**/target/site/jacoco*/jacoco.xml`, root-module
+ `build/reports/jacoco/**/*.xml`; nested Gradle modules need `--report`. Config is read at the git toplevel, even with
+ `--path`.
+- Export `.coverage` with `coverage lcov` or `coverage xml`. A new untested file must still be in the report; see [Coverage reports per language](../start/CI.md#coverage-reports-per-language).
+
+**File statuses.** Changed comment or blank lines count as neither.
+
+| Status | Meaning | Counts toward the % |
+|--------|---------|---------------------|
+| `measured` | Named; some changed lines executable | Yes |
+| `no_coverable_changes` | Named; no changed line executable | No |
+| `not_in_report` | Measured extension, not named (e.g. new untested file) | No, listed "not in report", never 0% |
+| `no_line_data` | Named without an executable-line set | No |
+
+- Out of scope, only counted: changed tests, unmeasured types (docs, config). Left out, counted as ignored: `coverage.ignore` (gitignore syntax) matches.
+- Go coverprofile paths under a `go.mod` module path map to its directory, unless a per-report prefix or `coverage.path_prefix` is set.
+- Percentages floor to one decimal (79.99% shows 79.9%); the gate uses the unrounded value.
+
+**Risk and hints.** Risk per file: git bug-fix history, plus hotspot, bug-magnet and dependent counts with an index (a
+missing one never fails). Risky files first; worded "Risk" column. With an index, each uncovered range names a test to
+extend ("Extend" column, annotation suffix, JSON `hints`): "extend tests/test_auth.py (inferred: calls reach `login`)",
+"(measured: runs other lines of `login`)", "(inferred: imports this file)", "no test reaches this; add one". Hints never
+change the verdict.
+
+**Path-scoped gates.** Each `coverage.gates` entry (`name`, `paths` as gitignore-style globs from the repo root,
+optional `fail_under` 0-100 and `informational`) judges its matching measured changed files like the whole change; a
+file can count in several.
+
+- The whole change's small-change tolerance applies: every gate (risky too) reads `too_small` under it.
+- Matched unmeasured files: `unmeasured_file_count`, outside the %.
+- A failing non-informational gate makes `gate` `fail` and leads the headline with its counts.
+- Table lists every gate; markdown up to 10, failing first. See [Path-scoped gates](../start/CI.md#path-scoped-gates) and `repowise coverage suggest-gates`.
+
+**`github` format**, in order: up to 10 `::warning` annotations (riskiest file, then largest range; risky ones titled
+"Uncovered change in a risky file") plus a `::notice` counting the rest; `::error::` per failing gate (whole,
+non-informational path, risky, branch); `::notice::` per informational gate below threshold, tolerance-exempted gate, or
+set but unapplied branch gate; "Partly taken branch" `::warning` per partly taken range (same cap); markdown to
+`$GITHUB_STEP_SUMMARY` when set. Markdown and `github` also list files that lost coverage outside the change.
+
+<details><summary><code>json</code> fields</summary>
+
+- Top: `patch_coverage_pct`, `covered_line_count`, `coverable_line_count`, `threshold`, `min_coverable_lines`, `gate` (`pass`, `fail`, `no_data`, `not_set`, `too_small`; `fail` if any gate fails).
+- `file_counts`: `measured`, `not_in_report`, `no_line_data`, `no_coverable_changes`, `stale_file` (stored coverage only, always 0 here), `out_of_scope`.
+- `files[]`: `file_path`, `status`, `changed_line_count`, `coverable_line_count`, `covered_line_count`,
+ `patch_coverage_pct`, `uncovered_ranges`, `branch_taken`, `branch_total`, `partial_ranges` (0/empty without branch
+ data); `risk` (`fix_pressure`, `dependents`, `hotspot`, `bug_magnet`, `basis`, `risky`, `reasons`); `hints` (null
+ without index; per range: `range`, `symbol`, `tests`, `basis` `per_test`/`call_graph`/`import_graph`/`none`, `total`).
+- `scope`: `label`, `source_formats`, `reports`, `report_path_count`, `unmatched_report_path_count`, `ignored_file_count`, `config_errors`, `branch_data` (`per_line`, `none`, `stored_before`).
+- `path_gates[]`: `name`, `paths`, `informational`, `measured_file_count`, `unmeasured_file_count`; `risky`:
+ `file_count`. Both also carry `covered_line_count`, `coverable_line_count`, `patch_coverage_pct`, `threshold`, `gate`.
+- `project` (null without base): `basis` (`base_report`, `history`), `base_commit`, `head_commit`, `base` / `head`
+ (`covered_line_count`, `coverable_line_count`, `coverage_pct`), `delta_pct` (points), `max_drop`, `gate`,
+ `incomparable` reasons, `outside_change_note`, `outside_change[]` (null on history basis or when most files do not
+ line up: `file_path`, `status` `changed`/`no_longer_measured`, `newly_uncovered_ranges`, `newly_uncovered_line_count`,
+ `newly_covered_line_count`, `base_pct`, `head_pct`, `causes` (`kind`
+ `test_deleted`/`test_modified`/`dependent_changed`, `path`, `basis` `per_test`/`graph`/`name`)).
+- `branches` (null with no branch data and no branch gate): `branch_taken`, `branch_total`, `branch_coverage_pct`, `partial_line_count`, `threshold`, `gate`.
+
+</details>
+
+**Exit codes.** `0` pass or nothing to judge (no threshold, no measurable lines, under tolerance). `1` a gate fails
+(`--fail-under`, non-informational path gate, `--fail-under-risky`, `--fail-under-branches`, `--max-drop`). `2` could
+not run:
+
+<details><summary>Exit 2 cases</summary>
+
+- No report, a `--report` matching nothing, none readable or matching a repo file, all in `coverage.ignore`; unknown
+ revision, no merge-base (shallow clone), single commit at a shallow boundary, not a git repo.
+- Malformed `coverage.fail_under` / `coverage.min_coverable_lines` / `coverage.fail_under_risky` / `coverage.fail_under_branches`, or an unusable `coverage.gates` entry (named).
+- `--fail-under-risky` on a shallow clone or a measured file with unreadable risk, unless the flat, a path or the branch gate already failed (then `1`).
+- `--fail-under-branches` without per-line branch data (`no_branch_data`); from config alone, a note, exit `0`.
+- `--max-drop` / `--base-report` with a base missing, incomparable, or with no coverable line on a side (same exception); from `coverage.max_drop` alone, a note, exit `0`.
+
+</details>
+
+**Shallow clones.** Shallow CI clones lack the merge-base (exit 2); fetch full history. Action, GitLab template, recipes: [Repowise in CI](../start/CI.md).
#### `repowise coverage suggest-gates`
-Propose path-scoped gates for `coverage.gates`. Sources, in order, each
-labelled in a comment:
-
-- CODEOWNERS: the first of `.github/CODEOWNERS`, `CODEOWNERS`,
- `docs/CODEOWNERS` and `.gitlab/CODEOWNERS`; one gate per owner. A later
- pattern that may overlap an owner's paths and is not theirs (owner-less
- lines included) is carried as a `!` exclusion; a catch-all (`*`) drops the
- gates before it and is itself none; an owner whose every pattern a later one
- overrides gets no gate. Escaped spaces, tab-separated comments and GitLab
- `[Section] @owners` defaults are understood.
-- Top-level packages from `git ls-files`: each directory under `packages/`,
- `apps/`, `services/` or `libs/` holding a source file that is not a test,
- else each top-level source directory.
-- Graph communities when the repository is indexed: each with 3 or more
- source files, over the directories holding them, named by their common
- directory; the 10 largest, minus any with the same globs as a package gate.
- The comment names the indexed commit, and says when there is no index, it
- cannot be read, or it holds no communities.
-
-The first two need no index. Nothing is written and no `fail_under` is set.
-The YAML block is indented to paste directly below your `coverage:` line;
-names repeated across sources get a `-2` suffix, so it is valid config as
-printed.
-
-| Flag | Description |
-|------|-------------|
-| `--path` | A path inside the repository (defaults to cwd) |
-| `--format` | `yaml` (default), a block to paste below `coverage:`; or `json`, `{"sources": [{"source", "detail", "gates": [{"name", "paths"}]}]}` |
+Propose path-scoped gates for `coverage.gates`.
```bash
-repowise coverage suggest-gates
repowise coverage suggest-gates --format json
```
----
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--path` | Path inside the repo. | cwd |
+| `--format` | `yaml` (paste below `coverage:`) or `json`: `{"sources": [{"source", "detail", "gates": [{"name", "paths"}]}]}`. | `yaml` |
+
+**Sources**, in order, each labelled in a comment:
+
+- **CODEOWNERS:** first of `.github/CODEOWNERS`, `CODEOWNERS`, `docs/CODEOWNERS`, `.gitlab/CODEOWNERS`; a gate per
+ owner. A later, possibly overlapping pattern not theirs (owner-less too) becomes a `!` exclusion; `*` drops earlier
+ gates, makes none; a fully overridden owner gets none. Handles escaped spaces, tab-separated comments, GitLab
+ `[Section] @owners` defaults.
+- **Top-level packages from `git ls-files`:** each directory under `packages/`, `apps/`, `services/`, `libs/` with a non-test source file, else each top-level source directory.
+- **Graph communities** (indexed): 3+ source files, over their directories, named by common directory; 10 largest, minus
+ package-gate glob duplicates. Comment names the indexed commit, or no index, unreadable, no communities.
+
+**Output.** First two sources need no index. Writes nothing, sets no `fail_under`. Pastes below `coverage:`; repeated names get `-2`, so it is valid config as printed.
### `repowise components`
-`check` validates `.repowise/components.yaml` and a repo-root `catalog-info.yaml` (Backstage entities, see [CONFIG.md](CONFIG.md#repowisecomponentsyaml)) against the files git tracks, and exits 1 on any error, so it fits a CI step. `list` shows declared and derived components with their file counts. `ownership` compares each component's declared owners (catalog `spec.owner`, CODEOWNERS, [`.repowise/teams.yaml`](CONFIG.md#repowiseteamsyaml)) with indexed commits in the last 90 days and lists findings: a high or critical component with no active declared owner or a bus factor of 1, a declared owner with no recent changes, and a catalog entry that claims no files. An owner none of whose identities appears in the indexed history is unknown, never inactive, so `critical_no_active_owner` does not fire when every declared owner is unknown. Individuals match only through an exact git email or a forge noreply login, and a bare `@name` outside `.github/CODEOWNERS` that names no declared team stays unresolved (on GitLab it may be a group). Findings name components and teams; individual owners are counted, never named.
+Validate, list and audit ownership of declared components.
```bash
-repowise components check [--path PATH] [--format table|json]
-repowise components list [--path PATH] [--format table|json]
-repowise components ownership [--path PATH] [--format table|json]
+repowise components check --format json
+repowise components ownership
```
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--path` | Repo path. | cwd |
+| `--format` | `table` or `json`. | `table` |
+
+- **`check`**: validates `.repowise/components.yaml` and a repo-root `catalog-info.yaml` (Backstage, see
+ [CONFIG.md](CONFIG.md#repowisecomponentsyaml)) against git-tracked files. Exits 1 on any error (CI-ready).
+- **`list`**: declared and derived components with file counts.
+- **`ownership`**: declared owners (catalog `spec.owner`, CODEOWNERS,
+ [`.repowise/teams.yaml`](CONFIG.md#repowiseteamsyaml)) against indexed commits of the last 90 days. Flags a high or
+ critical component with no active declared owner or bus factor 1, an owner with no recent changes, a catalog entry
+ claiming no files.
+
+<details><summary>Ownership matching</summary>
+
+- An owner with no identity in indexed history is unknown, never inactive; `critical_no_active_owner` does not fire when every declared owner is unknown.
+- Individuals match only by exact git email or forge noreply login. A bare `@name` outside `.github/CODEOWNERS` naming no declared team stays unresolved (on GitLab it may be a group).
+- Findings name components and teams; individuals are counted, never named.
+
+</details>
+
---
### `repowise packages`
-`where` lists the files that import a third-party package (a name or `ecosystem:name`) with the import line, component, declared owner teams and reachability, each with its basis. `export --format cyclonedx` writes the declared packages and their import sites as CycloneDX 1.6 JSON (`evidence.occurrences`); it is not an SBOM. `import` joins a Syft, SPDX, CycloneDX or OSV JSON file you supply to usage by package name; nothing is fetched and no vulnerability is matched. See [PACKAGE_USAGE.md](PACKAGE_USAGE.md).
+Find third-party package imports; export or join package data. See [PACKAGE_USAGE.md](PACKAGE_USAGE.md).
```bash
-repowise packages where NAME [--path PATH] [--format text|json]
-repowise packages export [--format cyclonedx] [-o FILE] [--path PATH]
-repowise packages import FILE [--path PATH] [--format text|json]
+repowise packages where requests
+repowise packages export -o usage.cdx.json
+repowise packages import sbom.json
```
----
+| Flag | Subcommands | What it does | Default |
+|------|-------------|--------------|---------|
+| `--path` | all | Repo path. | cwd |
+| `--format` | all | `text` or `json`; `export`: `cyclonedx`. | `text`; `export`: `cyclonedx` |
+| `--output` / `-o` | `export` | Output file. | stdout |
-### `repowise changes`
+- **`where NAME`** (name or `ecosystem:name`): importing files with import line, component, owner teams and reachability, each with basis.
+- **`export`**: declared packages and import sites as CycloneDX 1.6 JSON (`evidence.occurrences`). Not an SBOM.
+- **`import FILE`**: joins your Syft, SPDX, CycloneDX or OSV JSON to usage by package name. Fetches nothing, matches no vulnerability.
-Merged changes read back from git at each index and update: one per first-parent commit, identified by the PR or MR number its message names, then a Gerrit `Change-Id`, then the merge or commit sha. A merge lands the commits its branch brought in, and rebase merges read as one change per commit. `show` takes an id (`pr-123`) or any commit sha the change landed, and prints the versioned JSON record or, with `--format in-toto`, an in-toto Statement v1 whose subjects are the commits.
+---
-`show` also prints the change's evidence checklist: components touched, declared owners, suggested reviewers, reaching tests, contracts, consumers in other repos, decisions crossed, health delta, AI provenance and the diff size rank, each with a status (`ok`, `attention`, `unknown`) and the basis it rests on. The checklist is built on first read and kept on the change; `--refresh` rebuilds it. `export` writes every change merged in a `--since`/`--until` window (UTC, `--until` exclusive) with its checklist, streamed as JSON Lines (one record per line) or CSV rows (one row per change and item); building a missing checklist costs a few seconds per change. `list --needs-attention` keeps only changes whose kept checklist flags an item for attention; it reads checklists already built and builds none, so a change nobody has opened or exported is not listed.
+### `repowise changes`
-The last item, `outcomes`, says what later history records about the change, and is read again whenever HEAD moves. It lists reverts that name the change and later commits that name it as the cause of what they fix in their own words (a `Fixes: <sha>` trailer, "regression from/in/since", "caused by", "broken by"), each quoting the message, and only from commits the change is an ancestor of. Beside those it reports how many of the change's files later received fix commits within 30 days (`changes.outcome_fix_days` in `.repowise/config.yaml`), a rate that says where fixes landed, never that the change caused them.
+List, show and export merged changes read from git at each index and update.
```bash
-repowise changes list [--path PATH] [--category C] [--shape merge|squash|commit] [--grep TEXT] [--needs-attention] [--limit N] [--offset N] [--format table|json]
-repowise changes show REF [--path PATH] [--format table|json|in-toto] [--no-evidence] [--refresh]
-repowise changes export [--path PATH] [--since DATE] [--until DATE] [--format json|csv] [--refresh]
+repowise changes list --needs-attention
+repowise changes show pr-123 --format in-toto
```
+A change is one first-parent commit, identified by its message's PR or MR number, then Gerrit `Change-Id`, then merge or
+commit sha. A merge lands its branch's commits; rebase merges give one change per commit.
+
+| Flag | Subcommand | What it does | Default |
+|------|-----|--------------|---------|
+| `REF` | `show` | Id (`pr-123`) or any sha the change landed. | |
+| `--path` | all | Repo path. | cwd |
+| `--category` | `list` | Category (feature, fix, ...). | |
+| `--shape` | `list` | `merge`, `squash` or `commit`. | |
+| `--grep` | `list` | Substring of title, id or a file path. | |
+| `--needs-attention` | `list` | Kept checklist flags an item. Builds none, so unopened, unexported changes are skipped. | off |
+| `--limit` / `--offset` | `list` | Page size / skip. | `30` / `0` |
+| `--since` / `--until` | `export` | Merged on or after / before (UTC, `--until` exclusive). | |
+| `--format` | all | `table`, `json` (`show`: versioned record); `show` adds `in-toto` (Statement v1, commits as subjects); `export` is `json` (JSON Lines) or `csv` (row per change and item). | `table`; `export`: `json` |
+| `--evidence` / `--no-evidence` | `show` | Print the checklist. | on |
+| `--refresh` | `show`, `export` | Rebuild checklists. | off |
+
+**Evidence checklist**: components touched, declared owners, suggested reviewers, reaching tests, contracts, consumers
+in other repos, decisions crossed, health delta, AI provenance, diff size rank. Items carry a status (`ok`, `attention`,
+`unknown`) and basis. Built on first read and kept; `export` streams each change with it, building a missing one in a
+few seconds.
+
+<details><summary>Outcomes item</summary>
+
+The last item, `outcomes`, is reread whenever HEAD moves. It quotes reverts naming the change and later descendant
+commits naming it as their fix's cause (`Fixes: <sha>`, "regression from/in/since", "caused by", "broken by"). It also
+counts the change's files that got fix commits within 30 days (`changes.outcome_fix_days` in `.repowise/config.yaml`):
+where fixes landed, never that the change caused them.
+
+</details>
+
---
### `repowise suspects`
-Ranks the indexed changes merged in a window (default the 14 days before `--until`, which defaults to now) against a symptom: free text, files, a stack trace file. Each row lists the signals that fired (text match, import distance, co-change, recency, trace hits) with their evidence; the order is where to start reading, never a cause, and `git bisect run` confirms one. Text match carries most of the ranking, and most regressions surface later than 14 days, so a change outside the list is not cleared; widen `--since`. `--symptom` is read up to 20,000 characters and `--files` up to 50. Measured results and the bisect recipe are in [CHANGES.md](../layers/CHANGES.md#suspects).
+Rank changes merged in a window against a symptom: where to start reading.
```bash
-repowise suspects [--symptom TEXT] [--files PATH]... [--trace FILE] [--since DATE] [--until DATE] [--limit N] [--path PATH] [--format table|json]
+repowise suspects --symptom "TypeError in checkout" --trace trace.txt
```
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--symptom` | Issue text or error message; first 20,000 characters read. | |
+| `--files` | A file involved. Repeatable, up to 50. | |
+| `--trace` | Stack trace file. | |
+| `--since` | Merged on or after (UTC). | 14 days before `--until` |
+| `--until` | Merged before (UTC); when the symptom was seen. | now |
+| `--limit` | Changes ranked. | `10` |
+| `--path` | Repo path. | cwd |
+| `--format` | `table` or `json`. | `table` |
+
+- Rows list fired signals (text match, import distance, co-change, recency, trace hits) with evidence. Order is where to read first, never a cause; `git bisect run` confirms one.
+- Text match dominates and most regressions surface after 14 days, so an unlisted change is not cleared: widen `--since`. Results and bisect recipe: [CHANGES.md](../layers/CHANGES.md#suspects).
+
---
### `repowise check [REVSPEC]`
-Evaluates `.repowise/policies.yaml` (see [CONFIG.md](CONFIG.md#repowisepoliciesyaml)) against a change: components touched and their tags, provenance from public git markers, and, with an index, reaching tests, governing decisions crossed and bus factor. Rules that wrap a gate run `security check`, `coverage check` or `doc-drift --check` exactly as those commands run alone, and without a policy file every gate behaves as before while `check` reports nothing to evaluate. Exit 1 when a `fail` rule fires, 2 when the policy is invalid or a `fail` gate cannot be evaluated, else 0; `--sarif-file` writes SARIF 2.1.0 for code scanning or reviewdog and `--junit-file` a JUnit report from the same run.
+Evaluate `.repowise/policies.yaml` (see [CONFIG.md](CONFIG.md#repowisepoliciesyaml)) against a change.
```bash
-repowise check [REVSPEC] [--path PATH] [--policies FILE] [--sarif-file FILE] [--junit-file FILE] [--format table|json|sarif|junit]
+repowise check origin/main..HEAD --sarif-file check.sarif
```
-Teams that already run OPA can use the `evidence` object of `repowise check --format json` as OPA `input`: it is the change's evidence checklist, one item per kind (`components_touched`, `provenance`, `reaching_tests`, `decisions_crossed`, `contracts`) with its status, basis and per-file details. `opa eval --input check.json --data policy.rego 'data.repowise.deny'` then evaluates Rego rules over `input.evidence.items` next to, or instead of, `policies.yaml`.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--path` | A path inside the repository. | cwd |
+| `--policies` | Policy file. | `.repowise/policies.yaml` |
+| `--sarif-file` | Also write SARIF 2.1.0 (code scanning, reviewdog). | |
+| `--junit-file` | Also write JUnit from the same run. | |
+| `--format` | `table`, `json`, `sarif` or `junit`. | `table` |
+
+- Evaluates components touched, tags, git-marker provenance; with an index also reaching tests, decisions crossed, bus factor.
+- Gate rules run `security check`, `coverage check` or `doc-drift --check` exactly as alone; with no policy file gates run as alone and `check` reports nothing to evaluate.
+- Exit `0` no `fail` rule fired; `1` one did; `2` invalid policy or an unevaluable `fail` gate.
+- **OPA.** `evidence` from `--format json` is OPA `input`: one checklist item per kind (`components_touched`,
+ `provenance`, `reaching_tests`, `decisions_crossed`, `contracts`) with status, basis, per-file details. `opa eval
+ --input check.json --data policy.rego 'data.repowise.deny'` runs Rego over `input.evidence.items`, beside or instead
+ of `policies.yaml`.
---
### `repowise events`
-Typed events between consecutive index runs. Each `init` and `update` stores a snapshot of every component (ownership counts, bus factor, hotspots, dead code, governing decisions, provided contracts, test reach) under the analyzer and parser stamp it ran with. When an index run and the run right before it share a stamp, what moved is stored as an event. A stamp change starts a new baseline, and so does the first run after one that took no snapshot (events switched off, or the snapshot failed); a run on the commit already snapshotted, including `--working-tree` on it, is skipped. Events are written as CloudEvents JSON lines to `.repowise/events.jsonl` and read back here, oldest first.
+List typed events recorded between consecutive index runs, oldest first.
```bash
-repowise events [--path PATH] [--since 7d|12h|ISO-DATE] [--kind KIND]... [--limit N] [--format table|json|jsonl]
+repowise events --since 7d --kind bus_factor_drop
```
-Kinds: `ownership_shift`, `owner_inactive`, `bus_factor_drop` (critical components), `new_hotspot` (off by default), `contract_added`, `contract_broken`, `decision_stale`, `dead_code_growth`, `test_reach_drop`. Contract kinds need a workspace: after the cross-repo pass extracts contracts at the run's commit, the run's contract facts are measured and its contract events stored; outside a workspace contracts stay unavailable and those kinds never fire. An index-only `update` (the post-commit hook) skips the cross-repo pass to stay fast, so its run keeps contracts unavailable; contract kinds compare each measured run with the last earlier run that measured them, passing over those runs. Known limit: consumer counts are read at the provider's own runs, so a change in a consumer repo alone moves no contract event. Known limit: past `compact_after_days` compaction keeps one run per week, so the measured run a later run would compare with can be dropped, and the comparison falls back to an older measured run or none. The `events:` block in `.repowise/config.yaml` sets `enabled`, `retention_days` (365), `compact_after_days` (30; older runs keep one per week), per-kind switches under `kinds`, and the `sinks` to deliver to (`jsonl` by default, `stdout` for CI).
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--path` | Repo path. | cwd |
+| `--since` | `7d`, `12h` or ISO date. | |
+| `--kind` | Only this kind. Repeatable. | all kinds |
+| `--limit` | 1 to 10000. | `200` |
+| `--format` | `table`, `json` or `jsonl`. | `table` |
-The web UI lists the same events in the Events view of the Commits page, newest first. An empty list says why: `GET /api/repos/{id}/events` returns `snapshot_runs` and `empty_reason` (`baseline_only` until two snapshots exist, `nothing_moved`, or `no_match` under filters), and the same sentence this command prints as `empty_note`.
+**Kinds**: `ownership_shift`, `owner_inactive`, `bus_factor_drop` (critical components), `new_hotspot` (off by default),
+`contract_added`, `contract_broken`, `decision_stale`, `dead_code_growth`, `test_reach_drop`.
+
+- Each `init` and `update` snapshots every component (ownership counts, bus factor, hotspots, dead code, governing decisions, provided contracts, test reach) under its analyzer and parser stamp.
+- Same stamp as the previous run: what moved becomes an event. A stamp change, or a run after one with no snapshot
+ (events off, snapshot failed), starts a baseline. Already snapshotted commits (even `--working-tree`) are skipped.
+- Stored as CloudEvents JSON lines in `.repowise/events.jsonl`.
+
+<details><summary>Contract kinds (workspace only)</summary>
+
+- Measured after the cross-repo pass extracts contracts at the run's commit; outside a workspace they never fire.
+- Index-only `update` (post-commit hook) skips that pass, leaving contracts unavailable; contract kinds compare with the last earlier measured run, passing over those.
+- Known limit: consumer counts are read at the provider's runs, so a consumer-only change moves no event.
+- Known limit: past `compact_after_days`, one run per week is kept; the comparison run can be dropped, falling back to an older measured run or none.
+
+</details>
+
+**Config**: `events:` in `.repowise/config.yaml`.
+
+| Key | What it sets | Default |
+|-----|--------------|---------|
+| `enabled` | On or off. | |
+| `retention_days` | Days kept. | `365` |
+| `compact_after_days` | Age after which runs keep one per week. | `30` |
+| `kinds` | Per-kind switches. | |
+| `sinks` | `jsonl`, or `stdout` for CI. | `jsonl` |
+
+**Web UI**: Commits page Events view, newest first; `GET /api/repos/{id}/events` adds `snapshot_runs`, `empty_reason`
+(`baseline_only` before two snapshots, `nothing_moved`, `no_match`) and `empty_note` (this command's empty-list
+sentence).
---
### `repowise report assessment [PATH]`
-One document a team hands to someone else, for a repo or every repo of a workspace: component posture, hotspots, bus factor per component, dead code by tier, measured and inferred test reach, contracts, governing decisions, provenance coverage with the agents and models named, and what moved since a snapshot a quarter older. Every item keeps the OpenSSF Scorecard check keys (`name`, `score` 0 to 10 or -1 inconclusive, `reason`, `details`, `documentation`) plus `method` and `basis`. A descriptive item (a count or a list) has `score: null`, and missing or held-back evidence is always -1, never a low score. The report is evidence about code and components, not a score of people: owners are counted, never ranked or named. JSON is canonical (`schema_version: 1`); the HTML is one file with inline CSS, no scripts and a policy that blocks every fetch, so it opens offline and prints as is.
+One hand-off document for a repo or every workspace repo.
```bash
-repowise report assessment [PATH] [--sections a,b] [--format json|markdown|html|csv] [--out FILE] [--workspace | --no-workspace] [--repo ALIAS]
+repowise report assessment --format html --out assessment.html
+repowise report inventory --format csv
+repowise report changes --since all --no-build
```
-| Section | Measures | Basis |
-|---|---|---|
-| `components` | Each component's NLOC-weighted health, catalog facts and `components ownership` findings | `measured`; `gated` on a language health is held back on |
-| `inventory` | Each component's declared owner teams, languages, entry points and the third-party packages its files import ([package usage](PACKAGE_USAGE.md)) | `measured`; owners `declared` |
-| `hotspots` | Files with high recent churn, per component | `measured` |
-| `bus-factor` | Fewest primary owners holding over half of each component's owned files; components at 1 or 2 are counted and named in the summary unless the catalog marks them | `measured`; `inferred` under five owned files |
-| `dead-code` | Open findings by confidence tier; `safe_to_delete` is not used | `inferred`; `gated` for held-back languages |
-| `test-reach` | Line coverage from ingested reports, and production files a test reaches, as separate items | `measured` and `inferred` |
-| `contracts` | Contracts each component provides and their consumers in other repos | `measured` when the workspace store matches the indexed commit |
-| `decisions` | Accepted decisions governing each component's files, and the stale ones | `declared` |
-| `outcomes` | Changes a later commit reverted or named as the cause of what it fixed, in its own words, per component; read from the checklists already kept on Change Records, and left out when none is kept | `declared` |
-| `provenance` | Commits in the last 90 indexed days with a known source (a count, not a score), and the agents and models named (listed, not counted) | `measured`, `declared`; `unresolved` with no markers |
-| `trend` | What moved since a same-stamp snapshot at least 90 days older, by the `events` diff rules and only for the event kinds the repository has on | `measured` |
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--sections` | Comma-separated section ids. | all |
+| `--format` | `json`, `markdown`, `html`, `csv`, or a plugin renderer. | `markdown` |
+| `--out` | Output file. | stdout |
+| `--workspace` / `--no-workspace` | Every workspace repo / force single repo. | auto-detect |
+| `--repo` | Workspace repo alias. | |
-`repowise report inventory [PATH]` renders the `inventory` section alone, with the same `--format`, `--out`, `--workspace`, `--no-workspace` and `--repo` options: the component inventory a software inventory review (PCI DSS 6.3.2) asks for. Its JSON `data` keeps every component's owner teams, languages, entry points and packages; the text lists the components with no declared owner team.
+- Items keep OpenSSF Scorecard keys (`name`, `score` 0 to 10 or -1 inconclusive, `reason`, `details`, `documentation`)
+ plus `method` and `basis`. Counts and lists have `score: null`; missing or held-back evidence is -1, never a low
+ score; basis `unresolved` means missing.
+- Owners are counted, never ranked or named. Local paths removed.
+- JSON is canonical (`schema_version: 1`). HTML is one file, inline CSS, no scripts, all fetches blocked: opens offline, prints as is.
-`repowise report changes [PATH] [--since DATE|all] [--until DATE] [--format json|markdown|html|csv] [--out FILE] [--refresh] [--no-build]` is the change-management evidence an audit asks for (SOC 2 CC8.1, ISO 27001 A.8.32, PCI DSS 6.5): for every change merged in the period, its components and owning teams, its review record (git holds none, so it reads "not recorded in git" unless `Approved-by` trailers or a `change-metadata` source supply one), measured and inferred reaching tests, the verdict of the condition rules in `.repowise/policies.yaml` ("no policy configured" without one; gate rules are not re-run), its provenance, and whether a later commit reverted it or named it as the cause of a fix. A period summary counts those answers and a method appendix states what git alone cannot attest; unknown is counted apart, never as a failure, and people are counted, never named. It shares one evidence pass with `changes export`, which builds and stores any missing checklist in the index, a few at a time, after printing to stderr how many it will build and roughly how long; `--no-build` reports kept checklists only and counts the rest as unknown. Without `--since` the period is the 90 days before the newest indexed commit (or before `--until`, when earlier), and `--since all` covers every indexed change; the period summary and the method appendix state which window the report used.
+<details><summary>Sections</summary>
-Basis `unresolved` means the evidence is missing. Each per-component section opens with one summary row counting components by outcome; a component gets its own item only when there is something to note (an ownership finding, a bus factor of 2 or less on a component the catalog gives a criticality or tags, hotspots, a stale decision, provided contracts, or unresolved or gated evidence), the rest are named in the summary, and the JSON `data` keeps every component's figures. Local paths are removed from every item. A section is a `Section` on `SeamRegistry("report-section")`: each module in `repowise/core/report/sections/` registers one, a plugin registers its own the same way, and a section whose data is absent returns `None` and is left out, as `outcomes` is until a change's checklist has been opened. Renderers live on `SeamRegistry("report-renderer")` and are picked with `--format`. Modernization candidates are not reported, since no existing signal measures them.
+| Section | Measures | Basis |
+|---|---|---|
+| `components` | NLOC-weighted health, catalog facts, `components ownership` findings | `measured`; `gated` where language health is held back |
+| `inventory` | Owner teams, languages, entry points, imported packages ([package usage](PACKAGE_USAGE.md)) | `measured`; owners `declared` |
+| `hotspots` | High recent churn files | `measured` |
+| `bus-factor` | Fewest primary owners holding over half of owned files; 1 or 2 named in summary unless the catalog marks them | `measured`; `inferred` under five owned files |
+| `dead-code` | Open findings by tier; no `safe_to_delete` | `inferred`; `gated` for held-back languages |
+| `test-reach` | Ingested line coverage and test-reached production files, separate items | `measured`, `inferred` |
+| `contracts` | Provided contracts and other-repo consumers | `measured` when workspace store matches the indexed commit |
+| `decisions` | Accepted governing decisions, and stale ones | `declared` |
+| `outcomes` | Changes later reverted or named as a fix's cause; from checklists kept on Change Records, omitted when none | `declared` |
+| `provenance` | Commits in the last 90 indexed days with known source (count, not score); agents and models listed, not counted | `measured`, `declared`; `unresolved` with no markers |
+| `trend` | Moves since a same-stamp snapshot 90+ days older, by `events` rules, for enabled kinds | `measured` |
+
+Per-component sections open with a summary row counting components by outcome. A component gets its own item only for an
+ownership finding, bus factor 2 or less where the catalog gives criticality or tags, hotspots, a stale decision,
+provided contracts, or unresolved or gated evidence; the rest are named in the summary and JSON `data` keeps all
+figures.
+
+**Extending.** Sections are `Section`s on `SeamRegistry("report-section")`, one per module in
+`repowise/core/report/sections/`; plugins register the same way. Absent data returns `None` and omits the section (like
+`outcomes` before any checklist is opened). Renderers live on `SeamRegistry("report-renderer")`, chosen by `--format`.
+No modernization candidates: no signal measures them.
+
+</details>
+
+**`repowise report inventory [PATH]`** renders `inventory` alone, for software inventory review (PCI DSS 6.3.2). Same
+flags as `assessment` minus `--sections`. JSON `data` keeps all owner teams, languages, entry points and packages; text
+lists components with no owner team.
+
+**`repowise report changes [PATH]`**: change-management audit evidence (SOC 2 CC8.1, ISO 27001 A.8.32, PCI DSS 6.5).
+
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--since` | Merged on or after (UTC); `all` for every change. | 90 days before newest indexed commit (or `--until`, when earlier) |
+| `--until` | Merged before (UTC). | |
+| `--format`, `--out`, `--workspace` / `--no-workspace` / `--repo` | As `assessment`. | |
+| `--refresh` | Rebuild every checklist in the period. | off |
+| `--no-build` | Use kept checklists only; rest count unknown. | off |
+
+- Per change: components and owning teams, review record ("not recorded in git" unless `Approved-by` trailers or a
+ `change-metadata` source supply one), measured and inferred reaching tests, policy verdict (condition rules of
+ `.repowise/policies.yaml`, else "no policy configured"; gates not re-run), provenance, later revert or fix-cause
+ naming.
+- A period summary and a method appendix (what git alone cannot attest) both state the window. Unknown counts apart, never as failure; people counted, never named.
+- Shares the `changes export` evidence pass: missing checklists are built and stored a few at a time, after stderr says how many and how long.
---
### `repowise distill <command>`
-Run a command and print a compact, reversible rendering of its output. Noise
-(pass parades, progress spam, boilerplate) is dropped; errors, failures, and
-summaries always survive; the command's exit code is preserved. Dropped
-content is stored in `.repowise/omissions/` and referenced by an inline
-`[repowise#<ref>: ...]` marker. On any filter problem the raw output is
-printed unchanged. See [DISTILL.md](../agent/DISTILL.md) for the full feature guide.
+Run a command and print a compact, reversible rendering of its output. Guide: [DISTILL.md](../agent/DISTILL.md).
```bash
repowise distill pytest -x
repowise distill git status
-repowise distill npm run build
```
-Honors the `distill:` block in `.repowise/config.yaml` (master switch,
-disabled filters, omission-store sizing).
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--source` | Hidden ledger surface label; the rewrite hook sets `hook-bash` / `hook-powershell`. On Windows, `hook-bash` runs POSIX syntax in a POSIX shell, not cmd.exe. | `cli` |
+
+- Drops noise (pass parades, progress spam, boilerplate); errors, failures, summaries and exit code survive.
+- Dropped content goes to `.repowise/omissions/` behind an inline `[repowise#<ref>: ...]` marker. Any filter problem prints raw output.
+- Honors `distill:` in `.repowise/config.yaml` (master switch, disabled filters, omission-store sizing).
---
### `repowise expand REF`
-Restore the original output behind a `[repowise#<ref>: ...]` omission marker.
-Accepts a bare 12-hex ref or a pasted whole marker. Looks in the current
-repo's store first, then the user-level fallback store.
-
-| Flag | Description |
-|------|-------------|
-| `--query / -q` | Return only the lines matching this regex (or substring) |
+Restore the output behind a `[repowise#<ref>: ...]` omission marker.
```bash
-repowise expand a1b2c3d4e5f6
repowise expand a1b2c3d4e5f6 -q "FAILED"
```
----
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `REF` | 12-hex ref or a whole pasted marker. | |
+| `--query` / `-q` | Only lines matching this regex (or substring). | all lines |
-### `repowise saved [PATH]`
+Checks the repo's store, then the user-level fallback store.
-Report the input tokens your coding agent never had to read, and what they were
-worth. Reads the canonical savings ledger through the same report service the
-savings endpoint and the dashboard overview use, so the three cannot disagree.
-Covers the `repowise distill` path, the hooks that replace a tool result, and
-MCP calls; group `--by surface` to split them.
-
-Two figures travel with the total rather than being folded into it. *Measured*
-savings compare a known before and after; *inferred* savings estimate the
-exploration an answer replaced. And because each event is priced at the rate
-recorded when it happened, savings recorded without a rate are counted but not
-valued — reported as unpriced rather than valued at today's model.
+---
-| Flag | Description |
-|------|-------------|
-| `--by` | Grouping: `operation` (default), `surface`, `agent`, `model`, `day` |
-| `--since` | Only count savings on or after this ISO date. Converted to a whole-day window, rounded up, so the named day is always fully included |
-| `--model` | Pricing model for the `--missed` opportunity estimates. Recorded savings are priced per event, so this does not affect them. Defaults to the model detected from this repo's most recent agent session, falling back to `claude-sonnet-4-6` |
-| `--missed` | Report commands that looked distillable but weren't rewritten |
-| `--missed-days` | Window in days for `--missed` (default 7.0) |
-| `--format` | `table` (default) or `json` |
+### `repowise saved [PATH]`
-JSON folds the table, the net, and every trailing advisory line into one document.
+Input tokens your coding agent never had to read, and their worth.
```bash
-repowise saved # per-operation rollup + totals
-repowise saved --by surface # distill vs hooks vs MCP
-repowise saved --by agent # which agent the savings went to
-repowise saved --since 2026-06-01
-repowise saved --missed # what's slipping past the hook
+repowise saved --by surface
+repowise saved --missed
```
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--by` | `operation`, `surface`, `agent`, `model`, `day`. | `operation` |
+| `--since` | ISO date; rounded up to whole days, that day included. | |
+| `--model` | Prices `--missed` estimates only. | latest agent session model, else `claude-sonnet-4-6` |
+| `--missed` | Distillable-looking commands not rewritten. | off |
+| `--missed-days` | `--missed` window. | `7.0` |
+| `--format` | `table` or `json` (table, net and advisories in one document). | `table` |
+
+- Same ledger and report service as the savings endpoint and dashboard overview. Covers `repowise distill`, tool-result hooks, MCP calls.
+- *Measured* (known before and after) and *inferred* (exploration replaced) savings are the two parts of the total, shown with it.
+- Each event uses its recorded rate; rateless savings count as unpriced, never valued at today's model.
+
---
### `repowise savings sync [PATH]`
-Record savings your agents were shown but the ledger never banked. Reads only
-what was appended to agent transcripts since the last run, so repeating it is
-cheap. A non-zero `deferred` count means the time budget ran out and there is
-more to read; run it again.
-
-| Flag | Description |
-|------|-------------|
-| `--dry-run` | Report what would be recorded without writing anything |
-| `--budget` | Seconds of transcript reading. Raise it to finish a large backlog sooner |
-| `--format` | `table` (default) or `json` |
+Record savings agents were shown but the ledger never banked.
```bash
-repowise savings sync
repowise savings sync --dry-run
```
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--dry-run` | Report, write nothing. | off |
+| `--budget` | Seconds of transcript reading; raise for a big backlog. | `20.0` |
+| `--format` | `table` or `json`. | `table` |
+
+Reads only transcript text appended since the last run. Non-zero `deferred` means the budget ran out; run again.
+
---
### `repowise corrections [PATH]`
-Mine local agent transcripts for recurring command fumbles, consecutive runs
-of the same base command where the first failed and a later variant succeeded
-(wrong tool, wrong path, unknown flag, missing argument). Report-only by
-default; entirely local. See [DISTILL.md](../agent/DISTILL.md#repowise-corrections-recurring-command-fumbles).
-
-| Flag | Description |
-|------|-------------|
-| `--days` | Transcript window for the scan (default 30) |
-| `--write` | Maintain the "Known command corrections" managed block in `.claude/CLAUDE.md` / `AGENTS.md` (opt-in) |
-| `--min-count` | Occurrences a rule needs before `--write` includes it (default 2) |
-| `--format` | `table` (default) or `json` |
+Mine local agent transcripts for recurring command fumbles. See [DISTILL.md](../agent/DISTILL.md#repowise-corrections-recurring-command-fumbles).
```bash
-repowise corrections # report recurring fumbles
-repowise corrections --days 60
-repowise corrections --write # seed the agent guidance block
+repowise corrections --write
```
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--days` | Transcript window. | `30` |
+| `--write` | Opt-in: maintain the "Known command corrections" block in `.claude/CLAUDE.md` / `AGENTS.md`. | off |
+| `--min-count` | Occurrences a rule needs for `--write`. | `2` |
+| `--format` | `table` or `json`. | `table` |
+
+A fumble: same base command run consecutively, first failing, a later variant succeeding (wrong tool, path, unknown flag, missing argument). Local, report-only by default.
+
---
### `repowise costs`
Show LLM spend tracking.
-| Flag | Description |
-|------|-------------|
-| `--by` | Grouping: `operation`, `model`, `day` |
-| `--repo` | Scope to a specific workspace repo |
-| `--all` | Aggregate across every workspace repo |
-| `--workspace` / `--no-workspace` | Force workspace / single-repo mode |
-| `--format` | `table` (default) or `json` |
-
```bash
-repowise costs # auto-detects mode
-repowise costs --by operation # grouped by operation
-repowise costs --by model # grouped by model
-repowise costs --by day # grouped by day
-repowise costs --all # workspace-wide aggregate
-repowise costs --repo backend # one workspace repo
+repowise costs --all --by model
```
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `PATH` / `--repo-path` | Repository path. | cwd |
+| `--since` | ISO date. | |
+| `--by` | `operation`, `model`, `day`. | `operation` |
+| `--repo` | One workspace repo (implies workspace mode). | primary repo |
+| `--all` | Every workspace repo. | off |
+| `--no-workspace` | Force single repo. | auto-detect |
+| `--format` | `table` or `json`. | `table` |
+
---
### `repowise export [PATH]`
Export wiki pages to files, or the architecture model as Structurizr DSL.
-**Options:**
-
-| Flag | Description |
-|------|-------------|
-| `--format` | `markdown` (default), `html`, `json`, `structurizr` |
-| `--output / -o` | Output directory (default: `.repowise/export`). For `structurizr`, a path ending in `.dsl` names the file itself |
-| `--full` | Include decisions, dead code, hotspots, provenance metadata (JSON only) |
-| `--standalone` | `structurizr` only: emit a complete workspace with default views instead of a model fragment |
-| `--components` | `structurizr` only: include the component level (one box per directory) |
-| `--no-externals` | `structurizr` only: leave third-party dependencies out |
-
```bash
-repowise export
-repowise export --format json --full
repowise export --format html -o ./wiki/
-repowise export --format structurizr # repowise-model.dsl
-repowise export --format structurizr --standalone -o arch/ # renders on its own
+repowise export --format structurizr --standalone -o arch/
```
-The `structurizr` format writes one file describing the architecture rather
-than a directory of pages. See
-[Structurizr DSL export](../architecture/structurizr-export.md).
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--format` | `markdown`, `html`, `json`, `structurizr`. | `markdown` |
+| `--output` / `-o` | Output directory; for `structurizr`, a `.dsl` path names the file. | `.repowise/export` |
+| `--full` | JSON: add decisions, dead code, hotspots, provenance. | off |
+| `--standalone` | `structurizr`: full workspace with default views (renders alone), not a fragment. | off |
+| `--components` | `structurizr`: component level, one box per directory. | off |
+| `--no-externals` | `structurizr`: omit third-party dependencies. | externals included |
+| `--force` | `structurizr`: overwrite a file Repowise did not write (`--standalone` writes `workspace.dsl`, maybe yours). | off |
+
+`structurizr` writes one file (`repowise-model.dsl` by default), not pages. See [Structurizr DSL export](../architecture/structurizr-export.md).
---
## Workspace Commands
-### `repowise workspace list`
+Full multi-repo guide: [Workspaces](../scale/WORKSPACES.md).
-Show all repos in the workspace with their index status.
+### `repowise workspace list`
-### `repowise workspace add <path>`
+Show workspace repos and their index status.
-Add a new repo to an existing workspace and index it.
+```bash
+repowise workspace list
+```
-By default the added repo is indexed and its documentation is built from code, with no model calls, so it never spends. Pass `--docs` (or `--provider`) to have a model write it, `--no-docs` to index only, or `--no-index` to only register the entry. The provider, model, embedder, and exclude patterns are inherited from the primary repo's `.repowise/config.yaml` unless overridden.
+### `repowise workspace add <path>`
-| Flag | Description |
-|------|-------------|
-| `--alias` | Short name for the repo (defaults to directory name) |
-| `--index` / `--no-index` | Run the index pipeline (default: on) |
-| `--docs` / `--no-docs` | `--docs`: documentation written by the model. `--no-docs`: index only. Default: documentation built from code |
-| `--provider` / `--model` | Override the inherited provider/model |
-| `--concurrency` | Max concurrent LLM calls for this repo's generation |
-| `--primary` | Mark this repo as the workspace default |
-| `--verbose`, `-v` | Show debug logs from indexing and doc generation |
+Add a repo to the workspace and index it.
```bash
repowise workspace add ../new-service --alias api-gateway
-repowise workspace add ../mobile --no-docs # index only, no documentation
-repowise workspace add ../billing --docs # documentation written by the model
repowise workspace add ../shared --no-index # register only
```
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--alias` | Short name. | directory name |
+| `--index` / `--no-index` | Run the index pipeline; `--no-index` only registers. | on |
+| `--docs` / `--no-docs` | Model writes docs / index only. Ignored with `--no-index`. | docs built from code, no model calls |
+| `--provider` / `--model` | Override (`--provider` also means model docs). | primary repo's |
+| `--concurrency` | Max concurrent LLM calls. | `10` |
+| `--save-key` / `--no-save-key` | Save this run's provider key to the repo's git-ignored `.repowise/.env`, so its MCP server can answer. As in `init`. | on |
+| `--verbose`, `-v` | Debug logs. | off |
+
+- Provider, model, embedder and excludes inherit from the primary repo's `.repowise/config.yaml`.
+- To make it the default: [`repowise workspace set-default`](#repowise-workspace-set-default-alias).
+
### `repowise workspace remove <alias>`
-Remove a repo from the workspace (does not delete files).
+Remove a repo from the workspace; files stay.
-### `repowise workspace scan [PATH]`
+```bash
+repowise workspace remove api-gateway
+```
-Re-scan the workspace directory for new repos not yet added.
+### `repowise workspace scan [PATH]`
-| Flag | Description |
-|------|-------------|
-| `--yes` / `-y` | Auto-add all discovered repos without prompting |
-| `--verbose`, `-v` | Show debug logs while scanning for repositories |
+Find repos in the workspace directory not yet added.
```bash
-repowise workspace scan
repowise workspace scan --yes
```
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--yes` / `-y` | Add all without prompting. | off |
+| `--exclude` | Skip paths matching this glob, relative to the workspace root (e.g. `'test-repos/*'`). Repeatable. | |
+| `--verbose`, `-v` | Debug logs. | off |
+
### `repowise workspace set-default <alias>`
-Change which repo is the default for MCP queries.
+Set the default repo for MCP queries.
-### `repowise workspace diagnostics`
+```bash
+repowise workspace set-default api-gateway
+```
-Explain the cross-repo contract link count: per-repo provider/consumer counts, unmatched consumers grouped by reason, and orphan providers (declared but never consumed).
+### `repowise workspace diagnostics`
-| Flag | Description |
-|------|-------------|
-| `--repo` | Limit the report to one repo alias |
-| `--format` | `table` (default) or `json`. `--json` is a deprecated alias, still accepted |
+Explain the cross-repo contract link count: per-repo provider/consumer counts, unmatched consumers by reason, orphan providers (never consumed).
```bash
-repowise workspace diagnostics # human-readable report
-repowise workspace diagnostics --format json # raw JSON
-repowise workspace diagnostics --repo api # limit to one repo alias
+repowise workspace diagnostics --repo api --format json
```
-### `repowise workspace check`
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--repo` | One repo alias. | all |
+| `--format` | `table` or `json` (`--json` deprecated alias). | `table` |
-Architecture lint: check the declared `conformance:` rules against the system graph and detect dependency cycles. Exits non-zero on any finding, so it gates CI.
+### `repowise workspace check`
-| Flag | Description |
-|------|-------------|
-| `--format` | `table` (default) or `json`. `--json` is a deprecated alias, still accepted |
+Architecture lint: declared `conformance:` rules and dependency cycles over the system graph. Exits 1 on any finding (CI gate).
```bash
-repowise workspace check # human-readable report; exit 1 on findings
-repowise workspace check --format json # raw report JSON
+repowise workspace check --format json
```
-### `repowise workspace metrics [PATH]`
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--breaking` / `--no-breaking` | Also fail on breaking contract changes (a removed endpoint or retyped field another repo still calls), read from the last `repowise update --workspace` report; nothing to declare. `--no-breaking`: your rules only. | on |
+| `--format` | `table` or `json` (`--json` deprecated alias). | `table` |
-Architecture-complexity metrics over the system graph built by `repowise update --workspace`: propagation cost (how coupled the whole system is), the cyclic core (which services form circular dependency groups), and a single deterministic 1-10 score. Uses structural edges only (co-change is excluded); declared conformance violations, if any, are folded into the score. Requires a system graph, run `repowise update --workspace` first.
+### `repowise workspace metrics [PATH]`
-| Flag | Description |
-|------|-------------|
-| `--format` | `table` (default) or `json`. `--json` is a deprecated alias, still accepted |
+Architecture-complexity metrics over the system graph; run `repowise update --workspace` first.
```bash
-repowise workspace metrics
repowise workspace metrics --format json
```
-### `repowise workspace impacted-tests <repo:path>...`
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--format` | `table` or `json` (`--json` deprecated alias). | `table` |
-Given changed provider files (`repo:path`), list the tests in consumer repos worth running. Each consumer call site lands in one state (measured, inferred, none, unresolved). See [Cross-repo test impact](../scale/WORKSPACES.md#cross-repo-test-impact).
+Reports propagation cost (system coupling), the cyclic core (services in circular groups) and a deterministic 1-10
+score, from structural edges only (no co-change), with declared conformance violations folded in.
-| Flag | Description |
-|------|-------------|
-| `--path` | Workspace root (default: auto-detect from cwd) |
-| `--call-depth` | Call graph walk depth, 1-8 (default: 3) |
-| `--import-depth` | Import graph fallback depth, 1-3 (default: 1) |
-| `--no-measured` | Exclude coverage-backed recommendations |
-| `--no-inferred` | Exclude graph-inferred recommendations |
-| `--min-confidence` | Minimum contract link confidence, 0.0-1.0 (default: 0.0) |
-| `--target-repo` | Limit to these consumer repo aliases (repeatable) |
-| `--format` | `table` (default), `json`, or `list` (one `repo:test-file` per line). `--json` is a deprecated alias |
+### `repowise workspace impacted-tests <repo:path>...`
+
+List consumer-repo tests worth running for changed provider files.
```bash
-repowise workspace impacted-tests backend:app/routers/users.py
repowise workspace impacted-tests backend:app/routers/users.py --target-repo frontend --format list
```
-See [Workspaces](../scale/WORKSPACES.md) for the full multi-repo guide.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--path` | Workspace root. | auto-detect from cwd |
+| `--call-depth` | Call graph depth, 1-8. | `3` |
+| `--import-depth` | Import fallback depth, 1-3. | `1` |
+| `--no-measured` / `--no-inferred` | Drop coverage-backed / graph-inferred picks. | off |
+| `--min-confidence` | Min contract link confidence, 0.0-1.0. | `0.0` |
+| `--target-repo` | Consumer aliases. Repeatable. | all |
+| `--format` | `table`, `json`, or `list` (`repo:test-file` lines). `--json` deprecated alias. | `table` |
----
+Each consumer call site is measured, inferred, none or unresolved; see [Cross-repo test impact](../scale/WORKSPACES.md#cross-repo-test-impact).
## Auto-Sync Commands
+All sync methods (hooks, file watcher, webhooks, polling): [Auto-Sync](../scale/AUTO_SYNC.md). `hook install`, `status`
+and `uninstall` take an optional `PATH` plus `--workspace`/`-w` (every workspace repo) or `--no-workspace` (single
+repo); default auto-detect.
+
### `repowise hook install`
-Install a post-commit git hook that runs `repowise update` in the background after every commit.
+Install a post-commit hook that runs `repowise update` in the background.
```bash
-repowise hook install # current repo
-repowise hook install --workspace # all workspace repos
-repowise hook install --security # also a pre-commit security check
+repowise hook install --workspace --security
```
-`--security` adds a marked block at the top of the pre-commit script that runs
-`repowise security check --staged`: exit 1 (a finding at or above `high`)
-blocks the commit; exit 2 or a missing `repowise` lets it through. `hook status`
-reports it. Skip it once with `git commit --no-verify`.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--security` | Add a marked pre-commit block running `repowise security check --staged`: exit 1 (finding at `high`+) blocks, exit 2 or no `repowise` passes. Skip once: `git commit --no-verify`. | off |
### `repowise hook status`
-Check if hooks are installed.
+Report whether the post-commit hook and `--security` block are installed.
```bash
repowise hook status
-repowise hook status --workspace
```
### `repowise hook uninstall`
-Remove everything `hook install` added: the post-commit hook and, when
-installed, the `--security` pre-commit block.
+Remove the post-commit hook and any `--security` block.
```bash
repowise hook uninstall
-repowise hook uninstall --workspace
```
-See [Auto-Sync](../scale/AUTO_SYNC.md) for all sync methods (hooks, file watcher, webhooks, polling).
-
### `repowise hook stats`
-Show what the Claude Code agent hooks said and whether the agent acted on it,
-per surface, plus hook invocation counts and wall time. Reads the local ledger
-in `.repowise/sessions/sessions.db`.
+Per surface: what the Claude Code agent hooks said, whether the agent acted, invocation counts and wall time, from `.repowise/sessions/sessions.db`.
```bash
-repowise hook stats
-repowise hook stats --format json # raw per-surface rows
+repowise hook stats --format json
```
-Notices that ask for nothing (stale-read, the silent read-after-served
-measurement) report `n/a` rather than a rate.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--format` | `table` or `json` (raw per-surface rows). | `table` |
+
+Notices that ask nothing (stale-read, silent read-after-served) show `n/a`, not a rate.
### `repowise hook backfill`
-Replay Claude Code transcripts into the ledger, so `hook stats` starts with
-history instead of only what has fired since you upgraded. Local, single-pass,
-and safe to re-run: a firing is keyed by a hash of its own text, so a replay
-settles the row it already owns.
+Replay Claude Code transcripts into the ledger so `hook stats` has pre-upgrade history. Local, single-pass, re-runnable
+(firings keyed by text hash); usually one-time, as `repowise update` classifies recent sessions.
```bash
-repowise hook backfill # this checkout's transcripts
-repowise hook backfill --all-projects # include this repo's worktrees
-repowise hook backfill --days 30 # only recent transcripts
-repowise hook backfill --reset # rebuild the hook surfaces from scratch
+repowise hook backfill --days 30
```
-`repowise update` classifies recent sessions automatically, so a backfill is
-normally a one-time catch-up. Use `--reset` once when upgrading from a release
-that keyed rows by hook input rather than by emitted text; it clears only the
-hook surfaces, never decisions.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--all-projects` | Include this repo's worktrees. | this checkout |
+| `--days` | Transcripts modified in the last N days. | all |
+| `--reset` | Clear hook-surface rows (never decisions) first; once, after upgrading from a release keyed by hook input, not emitted text. | off |
### `repowise hook rewrite install|uninstall|status`
-Manage the Distill command-rewrite hooks (Claude Code + Codex PreToolUse).
-When installed, noisy agent commands (tests, builds, git status/log/diff,
-searches, listings) are rewritten to `repowise distill <command>` without a
-prompt by default (`permission: allow`), so the agent sees a compact,
-errors-first rendering. `--allow-rule` seeds a `Bash(repowise distill:*)` /
-`PowerShell(repowise distill:*)` allow rule, needed only under `permission: ask`.
+Manage the Distill command-rewrite hooks (Claude Code + Codex PreToolUse): noisy commands (tests, builds, git
+status/log/diff, searches, listings) run as `repowise distill <command>` (errors-first) with no prompt by default
+(`permission: allow`).
```bash
repowise hook rewrite install # writes ~/.claude/settings.json (idempotent)
-repowise hook rewrite install -w # also re-enable every workspace repo
-repowise hook rewrite status
repowise hook rewrite uninstall # removes only the repowise entries
```
-`install` also re-enables the target's `distill.commands` config if a prior
-`repowise init` opt-out had gated it off, the target repo by default, or
-every workspace repo with `--workspace`/`-w` (accepts an optional `PATH` and
-`--no-workspace`, like `repowise hook install`). `uninstall` removes the
-global hook entries plus the repo's AGENTS.md awareness section and leaves
-per-repo config untouched. Per-repo posture (`permission: ask | allow`,
-per-family overrides) lives under `distill.commands` in
-`.repowise/config.yaml`, see [DISTILL.md](../agent/DISTILL.md#configuration).
-
-When `~/.codex` exists, `install` also writes a Codex hook entry to
-`~/.codex/hooks.json` (Codex ≥ 0.137 only, older builds can't apply a
-rewrite) and maintains an "Output Distillation" section in the repo's
-`AGENTS.md` that works without any hook. Codex cannot show a rewritten
-command for approval, so there rewrites fire only for families resolving to
-`permission: allow` (the default) and a family set to `ask` passes through
-unchanged; `status` reports exactly what your build supports. See
-[DISTILL.md](../agent/DISTILL.md#3-the-command-rewrite-hook-claude-code--codex).
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--workspace` / `-w`, `--no-workspace` | Every workspace repo / single repo (all three). | auto-detect |
+| `--allow-rule` / `--no-allow-rule` | `install`: seed a `Bash(repowise distill:*)` / `PowerShell(repowise distill:*)` allow rule, needed only under `permission: ask`. | off |
----
+- `install` takes an optional `PATH` and re-enables `distill.commands` where an `init` opt-out turned it off.
+- `uninstall` removes the global entries and the AGENTS.md awareness section; repo config stays. Posture (`permission:
+ ask | allow`, per-family overrides): `distill.commands` in `.repowise/config.yaml`, see
+ [DISTILL.md](../agent/DISTILL.md#configuration).
+- **Codex** (`~/.codex` exists): also writes `~/.codex/hooks.json` (Codex ≥ 0.137 only; older versions cannot apply a rewrite) and a hook-free "Output Distillation"
+ section in `AGENTS.md`. Codex cannot approve a rewrite, so only `allow` families rewrite; `ask` passes through.
+ `status` shows what your build supports
+ ([DISTILL.md](../agent/DISTILL.md#3-the-command-rewrite-hook-claude-code--codex)).
-## Utility Commands
+### `repowise hook read-skeleton|search-digest|read-reread`
-### `repowise mcp [PATH]`
+Toggle the Claude Code read and search surfaces per repo. Each has `install`, `uninstall`, `status`, optional `PATH`, `-w`/`--no-workspace`.
-Start the MCP server for AI editor integration.
+```bash
+repowise hook read-reread status -w
+```
-If `PATH` is omitted, `repowise mcp` first walks upward from the current directory to the nearest initialized `.repowise` repository. This lets project-local Codex config use `args = ["mcp"]` with `cwd` set to the repo root.
+| Group | Config key | What `install` turns on |
+|-------|------------|-------------------------|
+| `read-skeleton` | `hooks.read_skeleton` | Unbounded Read of a large indexed file returns signatures, bodies elided with the line range to read each; a second Read returns it whole. |
+| `search-digest` | `hooks.search_digest` | A grep over many files returns per-file match counts and anchor lines plus a dropped-tail count; single-file `-C`/`-A`/`-B` untouched. |
+| `read-reread` | `hooks.read_reread` | Re-reading an unchanged, unedited file returns a notice naming the earlier read; changed content comes in full, flagged; reading again returns content. |
-**Options:**
+- No hook to install: `init`'s PostToolUse hook carries all three; these set the verdict in `.repowise/config.yaml` (`init` sets it from `--distill-hook`).
+- `uninstall` returns whole results (the digest rides alongside again). `status` says on/off and, when off, points to `repowise saved`. With no `.repowise/` it asks for `repowise init`.
-| Flag | Description |
-|------|-------------|
-| `--transport` | `stdio` (default, for editors), `streamable-http` (for HTTP clients), or `sse` (legacy) |
-| `--port` | Port for HTTP/SSE transports (default: 7338) |
-| `--tools` | Override which tools are exposed. A comma-separated list is an explicit allowlist; prefix names with `+`/`-` to adjust the default set (e.g. `+get_dependency_path,-get_dead_code`); `lean` selects the six-tool agent-lean profile. Overrides the `mcp.tools` config block. |
-| `--all` | Expose every available tool, including opt-in and workspace tools |
+## Utility Commands
+
+### `repowise mcp [PATH]`
+
+Start the MCP server. Without `PATH`, walks up from cwd to the nearest `.repowise` repo (so Codex config can use `args = ["mcp"]` with `cwd` at the repo root).
```bash
-repowise mcp --transport stdio # for Claude Code, Codex, Cursor, etc.
-repowise mcp --transport streamable-http # for HTTP clients
-repowise mcp --transport sse --port 7338 # legacy SSE
+repowise mcp --transport sse --port 7338
repowise mcp --tools "+get_dependency_path,-get_dead_code"
-repowise mcp --tools lean
-repowise mcp --all
```
-See [MCP Tools](../agent/MCP_TOOLS.md) for all exposed tools.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--transport` | `stdio` (editors), `streamable-http` (HTTP clients), or `sse` (legacy). | `stdio` |
+| `--port` | HTTP/SSE port. | `7338` |
+| `--host` | HTTP/SSE bind; `0.0.0.0` without `REPOWISE_API_KEY` warns that every tool is unauthenticated and network-accessible. | `REPOWISE_HOST`, else `127.0.0.1` |
+| `--tools` | Comma list = allowlist; `+`/`-` adjust defaults; `lean` selects the six-tool agent-lean profile. Overrides config. | `mcp.tools` config block |
+| `--all` | Every tool, including opt-in and workspace. | off |
+| `--no-workspace` | Nested repo ignores the enclosing workspace's default. | auto-detect |
----
+Tool list: [MCP Tools](../agent/MCP_TOOLS.md).
### `repowise generate-claude-md [PATH]`
-Generate or update `CLAUDE.md` with codebase intelligence. Custom instructions above the Repowise markers are preserved; the managed section between markers is auto-updated from the index.
-
-**Options:**
-
-| Flag | Description |
-|------|-------------|
-| `--output` | Write to a custom path (default: `.claude/CLAUDE.md`) |
-| `--stdout` | Print generated content to stdout instead of writing a file |
-| `--workspace` / `-w` | Force workspace mode: generates a workspace-level `CLAUDE.md` at the workspace root with cross-repo contracts, co-changes, and per-repo summaries |
-| `--no-workspace` | Force single-repo mode even when invoked from a workspace |
-| `--verbose` / `-v` | Show debug logs from the pipeline |
-
-Auto-detects workspace mode when invoked from a workspace root.
+Generate `CLAUDE.md`; `init` and `update` keep it current. Text above the Repowise markers is kept; between them updates from the index.
```bash
-repowise generate-claude-md
-repowise generate-claude-md -o custom-path.md
repowise generate-claude-md --stdout
-repowise generate-claude-md --workspace # workspace-level CLAUDE.md
-repowise generate-claude-md --verbose # show pipeline debug logs
```
-`repowise init` and `repowise update` keep it current automatically; you rarely need to run this directly.
-
----
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--output` | Custom path. | `.claude/CLAUDE.md` |
+| `--stdout` | Print, don't write. | off |
+| `--workspace` / `-w`, `--no-workspace` | Workspace file at the root (contracts, co-changes, per-repo summaries) / single repo. | auto-detect |
+| `--verbose` / `-v` | Debug logs. | off |
### `AGENTS.md`
-`repowise init --codex` generates managed `AGENTS.md` for Codex. `repowise update` refreshes it when `editor_files.agents_md` is enabled in config, or when `--agents` is passed. User content outside the Repowise managed markers is preserved.
-
----
+`repowise init --codex` writes a managed `AGENTS.md`; `repowise update` refreshes it with `editor_files.agents_md` or `--agents`. Text outside the markers is kept.
### `repowise agents`
-Manage the agent integrations repowise can wire up on this machine: Claude
-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: support
-tier, whether it looks installed, and every place it is currently wired to
-repowise.
+Wire agents after `init`: Claude Code, Codex, VS Code, Cursor, OpenCode, Hermes, GitHub Copilot CLI, Kiro, and any host
+via `print-config`. With no subcommand, lists each agent for the cwd repo: tier, installed or not, every wiring.
```bash
-repowise agents # list every known agent and its wiring
-repowise agents add [PATH] --target=<id> # wire one or more agents up
-repowise agents remove [PATH] --target=<id> # remove repowise from one or more agents
-repowise agents refresh [PATH] # rewrite configs already wired
-repowise agents print-config <target_id> [PATH] # print the config snippet, writing nothing
+repowise agents --format json
+repowise agents add [PATH] --target=opencode --scope=project
+repowise agents remove [PATH] --target=hermes --scope=user
+repowise agents refresh [PATH]
+repowise agents print-config claude-code [PATH]
```
-**`add` options:**
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--format` | Listing and `add`/`remove`/`refresh`: `table` or `json` (writes: every file and outcome). | `table` |
+| `--target` | `add`/`remove`: comma-separated ids or `auto`/`all`/`none`. Required for `remove` (destructive). | `add`: prompts, installed pre-ticked |
+| `--scope` | `add`/`remove`/`refresh`: `project` (repo), `user` (machine), `both`. | `both` |
+| `--yes` / `-y` | `add`: never prompt. | off |
+| `print-config --scope` | `project` or `user` snippet. | `project` |
+| `print-config --format` | `table`: bare paste-ready snippet; `json`: with target, scope, repo, docs URL. | `table` |
-| Flag | Description |
-|------|-------------|
-| `--target` | Comma-separated agent ids, or one of `auto`, `all`, `none`. Prompts on a terminal when omitted, with installed agents pre-ticked. |
-| `--scope` | `project`, `user`, or `both` (default). Where to write: repo-local config, per-machine config, or both. |
-| `--yes` / `-y` | Never prompt. |
-| `--format` | `table` (default) or `json`. `json` reports every file touched and what happened to it. |
+- `refresh` only repoints wired agents (after an upgrade or repo move), never adds, so `repowise doctor --repair` calls it.
+- `print-config` prints the MCP entry, writing nothing, for hosts like Cline, Windsurf, Zed, Gemini CLI.
-**`remove` options:**
-
-| Flag | Description |
-|------|-------------|
-| `--target` | Required. Comma-separated agent ids, or `auto`/`all`/`none`. No default, since silently removing everything is not a safe default for a destructive verb. |
-| `--scope` | `project`, `user`, or `both` (default). |
-| `--format` | `table` (default) or `json`. |
-
-**`refresh`** rewrites the configs of agents already wired up. It never adds
-an agent: it repoints what exists after an upgrade or a repo move, and leaves
-everything else alone, which is what makes it safe for `repowise doctor
---repair` to call.
-
-**`print-config`** prints the MCP server entry for `target_id` (e.g.
-`claude-code`) without writing anything, for a host repowise has no dedicated
-integration for (Cline, Windsurf, Zed, Gemini CLI, and similar).
-
-```bash
-repowise agents # what's wired, and where
-repowise agents add --target=cursor # wire Cursor up, both scopes
-repowise agents add --target=opencode --scope=project # repo-local only
-repowise agents remove --target=hermes --scope=user # unregister the per-machine MCP entry
-repowise agents refresh # repoint every wired agent after an upgrade
-repowise agents print-config claude-code # paste-ready snippet for another MCP client
-```
-
-See [Agent integrations](../agent/INTEGRATIONS.md) for the full support matrix
-and per-agent guides.
-
----
+Support matrix: [Agent integrations](../agent/INTEGRATIONS.md).
### `repowise reindex [PATH]`
-Rebuild the vector search index by re-embedding all wiki pages. No LLM calls, only embedding API calls.
-
-**Options:**
-
-| Flag | Description |
-|------|-------------|
-| `--embedder` | `gemini`, `openai`, `openrouter`, `ollama`, `edenai`, `mock`, or `auto` (default: auto) |
-| `--batch-size` | Embedding batch size (default: 32) |
-
-A reindex that writes every item with a real embedder marks semantic search
-available again in the index scope, clearing what a failed `init` or `update`
-recorded.
+Re-embed all wiki pages; embedding calls only, no LLM. A full run with a real embedder marks semantic search available again, clearing a failed `init`/`update` record.
```bash
-repowise reindex
repowise reindex --embedder gemini --batch-size 50
```
----
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--embedder` | `gemini`, `openai`, `openrouter`, `ollama`, `edenai`, `mock`, `auto`. | `auto` |
+| `--batch-size` | Batch size. | `32` |
### `repowise doctor [PATH]`
-Run health checks on the wiki setup. Auto-detects workspace mode; in workspace mode runs a workspace-level table (directory exists, git repo, state.json ↔ workspace config drift) followed by the per-repo check battery for every indexed entry.
-
-| Flag | Description |
-|------|-------------|
-| `--repair` | Repair detected issues: rebuild FTS, re-embed missing pages, sync drifted workspace state, drop dead workspace entries |
-| `--workspace` / `-w` | Force workspace mode |
-| `--no-workspace` | Force single-repo mode |
-| `--format` | Output: `table` (default) or `json` |
-
-A `Vector store` row fails when `.repowise/lancedb` exists but cannot be
-opened, and names the error. A store that opens but holds none of the indexable
-pages reports them all missing rather than in sync. `--repair` does not re-embed
-such a store with a paid embedder: it prints the page count and points to
-`repowise reindex`.
-
-```bash
-repowise doctor # auto-detects
-repowise doctor --repair # fix detected store mismatches
-repowise doctor --workspace # every workspace repo
-repowise doctor --workspace --repair # also drop dead entries / sync drift
-```
-
-**CLI update check.** `doctor` also prints a best-effort `CLI version` row that
-compares your installed CLI against the latest release on PyPI and, when an
-update is available, shows the suggested upgrade command (e.g. `uv tool upgrade
-repowise`, `pipx upgrade repowise`, or `python -m pip install -U repowise`). It
-shows both the `repowise` resolved on your `PATH` and the command that launched
-the current process, since these can differ. This check is advisory: it never
-updates anything automatically and does not fail `doctor` when PyPI is
-unreachable. After upgrading, **restart Claude/Codex/Cursor or any MCP client**
-so it picks up the new executable.
-
-**Distill checks.** `doctor` also validates the `distill:` config block
-(unknown keys, bad permission values, unknown filter names, non-positive store
-sizing), reports the omission store's size against its configured cap, and
-shows whether the command-rewrite hook is installed. The hook is opt-in, so
-its absence never fails doctor.
+Health-check the setup.
----
+```bash
+repowise doctor --workspace --repair
+```
-### `repowise whats-new`
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--repair` | Rebuild FTS, re-embed missing pages, sync workspace drift, drop dead workspace entries. | off |
+| `--workspace` / `-w`, `--no-workspace` | Workspace table (dir exists, git repo, state.json ↔ config drift) then per-repo checks / single repo. | auto-detect |
+| `--format` | `table` or `json`. | `table` |
-Show release notes for repowise versions you haven't seen yet. By default it
-lists releases newer than the last one you viewed, then records the current
-version as seen. Works offline from the changelog bundled with the install.
+- **Vector store** fails when `.repowise/lancedb` won't open, naming the error. An open store with no indexable pages
+ reports all missing; `--repair` won't re-embed it with a paid embedder, it prints the count and points to `repowise
+ reindex`.
+- **`CLI version`** (best-effort, vs PyPI): upgrade command (`uv tool upgrade repowise`, `pipx upgrade repowise`,
+ `python -m pip install -U repowise`), the `repowise` on `PATH` and the launching command. Never updates, never fails
+ offline. After upgrading, **restart Claude/Codex/Cursor or any MCP client**.
+- **Distill:** validates `distill:` (unknown keys, bad permission values, unknown filters, non-positive store sizing);
+ shows omission store size vs cap and whether the opt-in rewrite hook is installed (absence passes).
-| Flag | Description |
-|------|-------------|
-| `--version X.Y.Z` | Show notes for a single release |
-| `--all` | Show the full changelog history |
-| `--format` | `table` (default) or `json` |
+### `repowise whats-new`
-Each release leads with its highlights and a one-line "By the numbers" (pull requests, contributors, files and lines changed). JSON carries every selected release with its `summary`, `highlights` and `stats`; the panel caps at 5 releases and 8 bullets each.
+Release notes since you last looked, then marks the current version seen. Offline, from the bundled changelog.
```bash
-repowise whats-new # what changed since you last looked
-repowise whats-new --version 0.21.0 # one specific release
-repowise whats-new --all # full history
+repowise whats-new --version 0.21.0
```
-`repowise update` shows a short "what's new" panel automatically after you
-upgrade to a newer version, and both `update` and `serve` print a one-line,
-non-blocking notice when a newer release is available on PyPI. See
-[docs/reference/UPGRADING.md](UPGRADING.md) for the full upgrade flow.
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--version X.Y.Z` | One release. | unseen releases |
+| `--all` | Full history. | off |
+| `--format` | `table` or `json` (`summary`, `highlights`, `stats` per release). | `table` |
----
+- Each release: highlights and a "By the numbers" line (pull requests, contributors, files and lines changed). The panel caps at 5 releases, 8 bullets each.
+- `repowise update` shows a short panel after an upgrade; `update` and `serve` print a non-blocking line when PyPI is newer. See [docs/reference/UPGRADING.md](UPGRADING.md).
### `repowise telemetry`
Inspect and control anonymous, opt-out usage telemetry.
```bash
-repowise telemetry status # show whether telemetry is enabled, and why
-repowise telemetry enable
-repowise telemetry disable
+repowise telemetry status # enabled or not, and why
+repowise telemetry disable # or: enable
```
----
-
### `repowise plugins`
-List the plugins repowise loaded (from `repowise.plugins` entry points and
-`REPOWISE_PLUGINS`), whether each loaded or why it failed, the seams each
-registered, and the implementation chosen for each seam. `--format json` gives
-the same as JSON. Commands a plugin adds load only when you run a name the CLI
-does not know or list the commands. See [pluggable storage and capability seams](../architecture/pluggable-storage.md).
+List plugins from `repowise.plugins` entry points and `REPOWISE_PLUGINS`: loaded or why not, seams registered,
+implementation per seam. Plugin commands load only for an unknown command name or a command listing.
----
+```bash
+repowise plugins --format json
+```
+
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--format` | `table` or `json`. | `table` |
+
+See [pluggable storage and capability seams](../architecture/pluggable-storage.md).
### `repowise attribution`
-Inspect and clear AI attribution for a repository.
+Inspect and clear AI attribution. Settings: [CONFIG.md](CONFIG.md#the-attribution-block) `attribution:`.
```bash
repowise attribution status [PATH] [--format json] # what is on, capture per agent, coverage, last backfill
-repowise attribution backfill [PATH] --agent claude-code,codex [--format json] # bind past commits from local transcripts
-repowise attribution purge [PATH] [--yes] # delete derived attribution, captured edits and our notes
+repowise attribution backfill [PATH] --agent claude-code,codex [--format json]
+repowise attribution purge [PATH] [--yes]
```
-`backfill` reads the Claude Code and Codex transcripts on this machine, keeps only line hashes of edits to this repository (worktrees included), and binds them to commits made within 14 days after each edit. It runs only when you ask, for agents that `capture` and `agents` allow in both configs, and prints the commits scanned, bound, and their coverage before and after; when it binds new commits in an indexed repo, the next `repowise update` re-reads git history once to label these commits. The first run reads every transcript these agents keep (about 4 minutes for 7 GB on a laptop); a later run reads only what they wrote since.
-
-`purge` deletes the index labels, the `.repowise/attribution/` sidecar and the git-ai notes Repowise wrote locally. Git history, trailers and notes written by anything else stay as they are.
-Settings live in the `attribution:` block of [CONFIG.md](CONFIG.md#the-attribution-block).
-
----
+- **`backfill`** (on request; agents both `capture` and `agents` allow): hashes lines of edits to this repo (worktrees
+ too) from local Claude Code/Codex transcripts, binds them to commits within 14 days after, prints commits scanned,
+ bound, coverage before/after. The next `update` re-reads git history once to label them. First run reads all
+ transcripts (about 4 minutes for 7 GB on a laptop), later runs only new ones.
+- **`purge`** deletes index labels, `.repowise/attribution/` and git-ai notes Repowise wrote; history, trailers and others' notes stay.
### `repowise config hints on|off`
-Now and then, at a moment where it would help (a finished `init`, a slow
-`update`), the CLI prints one dim line on stderr about
-what repowise.dev adds, with a link. At most one per run, each at most once a
-week. Never under `--format json`, in CI, when stderr is not a terminal, when
-you are signed in, or from `mcp`, `serve`, `watch` and hooks.
+Toggle the repowise.dev hint: one dim stderr line with a link at a helpful moment (finished `init`, slow `update`); max
+one per run, each once a week. Never with `--format json`, in CI, non-terminal stderr, signed in, or from `mcp`,
+`serve`, `watch`, hooks.
```bash
repowise config hints off # also: REPOWISE_NO_HINTS=1 or DO_NOT_TRACK=1
-repowise config hints on
```
----
-
### `repowise login`
-Sign in to your hosted repowise.dev account. This is unrelated to LLM provider
-keys (`--provider`/`--model` elsewhere), it adds the hosted layer: your
-indexed repos on repowise.dev, reindex from local tools, and account status in
-`doctor`. Every local feature works without signing in.
-
-Sign-in is browser-based OAuth with PKCE by default: the command opens the
-hosted consent page and stores tokens at `~/.repowise/credentials.json`.
-
-| Flag | Description |
-|------|-------------|
-| `--with-token` | Paste a personal API key (`rw_live_...`) instead of using the browser. Reads from stdin when piped, otherwise prompts. For SSH/headless machines. |
-| `--device-name` | Label this machine in your connected apps (default: hostname) |
+Sign in to repowise.dev (browser OAuth with PKCE; tokens in `~/.repowise/credentials.json`). Not an LLM key; adds hosted
+repos, reindex from local tools and account status in `doctor`. Local features never need it.
```bash
-repowise login # browser sign-in
-repowise login --with-token # headless, paste an API key
-repowise login --device-name "build-box"
+repowise login --with-token
```
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--with-token` | Paste an API key (`rw_live_...`): stdin when piped, else prompt. For SSH/headless. | off (browser) |
+| `--device-name` | Machine label in connected apps. | hostname |
+
### `repowise logout`
-Sign out of your Repowise account on this machine (best-effort server-side revocation, local credentials always removed).
+Sign out here: best-effort server revocation, local credentials always removed.
```bash
repowise logout
@@ -2458,7 +2082,7 @@ repowise logout
### `repowise whoami`
-Show the Repowise account this machine is signed in to.
+Show the signed-in account.
```bash
repowise whoami
@@ -2466,121 +2090,93 @@ repowise whoami
### `repowise publish [PATH]`
-Put this repo on repowise.dev. The command reads the GitHub `origin` remote and
-asks repowise.dev to index it there: nothing is uploaded from your machine, so
-only what you have pushed is published. Signed out, it runs the `repowise login`
-browser sign-in first. A hosted index usually takes about 10 minutes.
-
-On success it prints the indexing page (and opens it), the repo page for when it
-is ready, and the MCP address to add in Claude.ai or ChatGPT. When repowise.dev
-refuses, it says why and links the next step: a private repo on a free account
-goes to the repo's page, which starts the Pro trial (10 days free, card
-required) and the GitHub App install; a paid account without the GitHub App
-gets the install link; the free plan's 2-repo limit links the trial checkout.
-A repo without a GitHub remote is not published.
-
-| Flag | Description |
-|------|-------------|
-| `--ref` | Branch or tag on GitHub to publish (default: the branch you are on if it is pushed, else the default branch) |
-| `--no-open` | Don't open the indexing page in the browser |
+Have repowise.dev index the GitHub `origin` (nothing uploads: pushed work only; no GitHub remote, no publish). Signs in
+first if needed. About 10 minutes; prints (and opens) the indexing page, plus the repo page and MCP address for
+Claude.ai or ChatGPT.
```bash
-repowise publish # publish the repo in this directory
-repowise publish --ref release # publish another pushed branch
-repowise publish --no-open
+repowise publish --ref release --no-open
```
----
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--ref` | GitHub branch or tag. | current branch if pushed, else default |
+| `--no-open` | Don't open the browser. | off |
+| `--format` | `table` or `json` (one object, never a browser sign-in; signed out = `signed_out`). | `table` |
-### `repowise delete [REPO_ID]`
+Refusals say why and link the fix: private repo on free → repo page (Pro trial, 10 days free, card required, plus GitHub
+App install); paid without the App → install link; free 2-repo limit → trial checkout.
-Delete a repository's index and all stored intelligence (wiki, graph, embeddings,
-git metadata). Does **not** touch your source files. Prompts for confirmation
-unless `--force` is passed. The index may live in a shared database configured
-with `REPOWISE_DB_URL`; no repository-local `.repowise/wiki.db` is required.
-
-| Flag | Description |
-|------|-------------|
-| `--force` / `-f` | Skip the confirmation prompt |
-| `--path` / `-p` | Path to the repository directory |
+### `repowise delete [REPO_ID]`
-With `--path`, the repository whose stored `local_path` matches that path is
-selected, so a shared `REPOWISE_DB_URL` (PostgreSQL) database does not prompt
-for a numbered choice. Without `--path` the command lists every repository in
-the database and prompts.
+Delete a repo's index and stored intelligence (wiki, graph, embeddings, git metadata); source files untouched. Works on a shared `REPOWISE_DB_URL` database with no local `.repowise/wiki.db`.
```bash
-repowise delete # delete the current repo's index (prompts)
-repowise delete <repo-id> --force # delete a specific repo's index, no prompt
-repowise delete --path /workspace/api -f # delete the repo indexed at that path
+repowise delete --path /workspace/api -f
```
----
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--force` / `-f` | No confirmation. | prompts |
+| `--path` / `-p` | Pick the repo whose stored `local_path` matches (no numbered choice on shared PostgreSQL). | list all, prompt |
### `repowise uninstall [PATH]`
-Remove what repowise has written, and report everything it did not remove and
-why. Wider than `repowise delete`, which removes one repository's rows from the
-index database and no files at all.
+Remove what repowise wrote; report what stays and why. Wider than `delete` (index rows only). Terminal, no flags: shows the inventory and asks. The four groups are chosen independently; without a terminal, name what to remove (`--all`, `--keep-index`).
-Four groups, chosen independently:
+```bash
+repowise uninstall --keep-index # drop the wiring, keep the index
+repowise uninstall --all --dry-run --format json
+```
| Group | What it covers |
|------|-------------|
-| `agents` | Every wired agent, both scopes, through each target's own uninstall |
-| `repo-files` | The managed blocks in `.claude/CLAUDE.md` and `AGENTS.md` |
-| `index` | The repo's `.repowise/` directory |
+| `agents` | Every wired agent, both scopes, via each target's uninstall |
+| `repo-files` | Managed blocks in `.claude/CLAUDE.md`, `AGENTS.md` |
+| `index` | The repo's `.repowise/` |
| `global` | `~/.repowise/`: login, caches, telemetry preference |
-With a terminal and no flags it prints the inventory and asks. Otherwise say
-what you want removed:
+| Flag | What it does | Default |
+|------|--------------|---------|
+| `--all` | Everything, including index and machine-wide state. | off |
+| `--keep-index` | Reinstall case: wiring and generated blocks only. | off |
+| `--dry-run` | Plan only. | off |
+| `--format table\|json` | `json`: plan, every path, outcome. | `table` |
-| Flag | Description |
-|------|-------------|
-| `--all` | Everything, including the index and machine-wide state |
-| `--keep-index` | The reinstall case: agent wiring and generated blocks only |
-| `--dry-run` | Print the plan and change nothing |
-| `--format table\|json` | `json` reports the plan, every path and what happened to it |
+- **No `--yes`:** a partial uninstall is no safe default. No terminal and no scope: prints inventory, removes nothing, exits non-zero.
+- **Never pre-selected:** the index (costly to rebuild), `~/.repowise/` (shared by every repo). **Never touched:** the
+ package (pip, uv, pipx) and Claude Code plugin (`/plugin uninstall`); it prints each command.
+- One agent only: [`repowise agents remove --target=<id>`](../agent/INTEGRATIONS.md).
-**There is no `--yes`.** On every other command it means "run the default", and
-a partial uninstall is not a safe default, so the scope is named instead. With
-no terminal and no scope flag the command prints the inventory, removes nothing
-and exits non-zero.
+**Exit codes** (each refusal prints its reason on the row):
-The index and machine-wide state are never pre-selected. The index is expensive
-to rebuild, and `~/.repowise/` is shared by every repo on the machine, which a
-command running inside one of them cannot see.
+| Code | Meaning |
+|------|---------|
+| `0` | All selected removed. |
+| `1` | A removal failed. |
+| `3` | A removal was refused; something remains. |
+| `4` | No scope and nobody to ask. |
-Exit codes: `0` everything selected is gone, `1` a removal failed, `3` a removal
-was refused and something remains, `4` no scope was given and nobody could be
-asked. Each refusal prints its reason on the row.
+### `repowise augment`
-Two things it never touches: the package, which belongs to pip, uv or pipx, and
-the Claude Code plugin, which only `/plugin uninstall` can remove. It prints the
-right command for each.
+Context enrichment run by `init`'s Claude Code and Codex hooks, not by hand.
```bash
-repowise uninstall # show what is there, then ask
-repowise uninstall --all # everything, including index and login
-repowise uninstall --keep-index # drop the wiring, keep the index
-repowise uninstall --all --dry-run # what --all would do, changing nothing
-repowise uninstall --all --format json # the same, machine-readable
+repowise augment --client codex # payload on stdin
```
-To remove a single agent rather than all of them, use
-[`repowise agents remove --target=<id>`](../agent/INTEGRATIONS.md).
-
----
-
-### `repowise augment`
-
-Hook-driven context enrichment engine. Not meant to be called manually, invoked by Claude Code and Codex hooks installed during `repowise init`. Claude Code uses it for search-result enrichment, stale-wiki checks, and decision injection: session start gets the standing decisions relevant to the session's working set (relevance-ranked, hard token cap, silent when nothing clears the floor), and editing a governed file gets a one-line "governed by" notice once per session per decision. Codex uses it for `SessionStart` and `PostToolUse` lifecycle guidance. Shown decisions are recorded in `.repowise/sessions/sessions.db` so the next `repowise update` can judge whether the guidance was followed or contradicted and adjust decision staleness.
+| Flag | Meaning | Default |
+|---|---|---|
+| `--client` | `codex` or `cursor`, passed by those hooks. | Claude Code |
+| `--coverage-only` | Only the shell-tool coverage re-ingest (repo-local hook). | off |
+| `--verbose`, `-v` | Debug logs. | off |
-| Flag | Meaning |
-|---|---|
-| `--client` | Hook client marker: `codex`. Codex lifecycle hooks pass this explicitly. |
-| `--verbose`, `-v` | Show debug logs from the hook pipeline. |
+- **Claude Code:** search enrichment, stale-wiki checks, decisions: relevant standing decisions at session start
+ (ranked, hard token cap, silent below the floor), one "governed by" line per decision per session on editing a
+ governed file.
+- **Codex:** `SessionStart` and `PostToolUse` guidance.
+- Shown decisions land in `.repowise/sessions/sessions.db`; the next `update` judges followed or contradicted and adjusts staleness.
### `repowise-augment` / `repowise-rewrite`
-Two separate console scripts (not `repowise` subcommands) installed alongside the CLI: `repowise-augment` is an import-isolated entry point for the Claude Code/Codex augment hooks above; `repowise-rewrite` backs the Distill command-rewrite hook (`repowise hook rewrite install`). Neither is meant to be run by hand.
+Console scripts installed with the CLI, not subcommands, not run by hand: `repowise-augment` is the import-isolated augment hook entry; `repowise-rewrite` backs `repowise hook rewrite install`.
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index b37b8b68c..0a76d23e4 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -1,75 +1,12 @@
# Configuration
-The `.repowise/` directory, provider setup, API keys, and what's customizable.
-
----
-
-## Contents
-
-**Files and `config.yaml`**
-[The `.repowise/` directory](#the-repowise-directory) ·
-[`config.yaml`](#configyaml) ·
-[Grounded generation context](#grounded-generation-context) ·
-[The `distill:` block](#the-distill-block) ·
-[The `hooks:` block](#the-hooks-block) ·
-[The `mcp:` block](#the-mcp-block) ·
-[The `editor_files:` block](#the-editor_files-block) ·
-[The `decisions:` block](#the-decisions-block) ·
-[`policies.yaml`](#repowisepoliciesyaml) ·
-[The `coverage:` block](#the-coverage-block) ·
-[The `security:` block](#the-security-block) ·
-[The `attribution:` block](#the-attribution-block) ·
-[The `events:` block](#the-events-block) ·
-[The `refactoring:` block](#the-refactoring-block) ·
-[The `assertions:` block](#the-assertions-block)
-
-**Code health rules**
-[The `health-rules.json` file](#the-health-rulesjson-file)
-
-**LLM providers**
-[Overview](#llm-providers) ·
-[Anthropic](#anthropic-claude) ·
-[OpenAI](#openai-gpt) ·
-[OpenRouter](#openrouter) ·
-[Gemini](#gemini-google) ·
-[DeepSeek](#deepseek) ·
-[Kimi](#kimi) ·
-[Ollama](#ollama-local-no-api-key) ·
-[LiteLLM](#litellm-100-providers) ·
-[Provider auto-detection](#provider-auto-detection)
-
-**Embeddings and keys**
-[Embeddings (for semantic search)](#embeddings-for-semantic-search) ·
-[BYOK (Bring Your Own Key)](#byok-bring-your-own-key)
-
-**Environment variables**
-[Overview](#environment-variables) ·
-[Provider API keys](#provider-api-keys) ·
-[Provider base URLs](#provider-base-urls) ·
-[Provider and model overrides](#provider-and-model-overrides) ·
-[Embeddings](#embeddings) ·
-[Server and database](#server-and-database) ·
-[Telemetry](#telemetry) ·
-[Misc](#misc)
-
-**Repo scope**
-[Exclude patterns](#exclude-patterns) ·
-[Submodules](#submodules) ·
-[PostgreSQL](#postgresql)
-
-**Workspace**
-[Workspace config (`.repowise-workspace.yaml`)](#workspace-config-repowise-workspaceyaml) ·
-[The `conformance:` block](#the-conformance-block)
-
-**Reference**
-[Deprecated / legacy aliases](#deprecated--legacy-aliases)
-
----
+The `.repowise/` directory, `config.yaml` and its blocks, providers, keys and
+environment variables.
## The `.repowise/` directory
-Everything repowise knows about your repository lives here. It's created at the
-repo root on first `init`.
+Everything Repowise knows about your repository, created at the repo root by
+`init`.
```
.repowise/
@@ -85,336 +22,297 @@ repo root on first `init`.
└── .env # API keys (gitignored automatically)
```
-repowise adds `.repowise/` to your `.gitignore` automatically. The directory
-should not be committed; it's a local cache, not a source of truth.
-
----
+Repowise adds `.repowise/` to `.gitignore`: it is a local cache, not a source
+of truth. Only [`decisions.yaml`](#repowisedecisionsyaml) is meant to be
+committed.
## `config.yaml`
-The main configuration file. Created after first `init`, updated when you pass
-flags like `--commit-limit`, `--follow-renames`, or `--wiki-style`.
-
-> **Limited schema validation.** `config.yaml` is loaded as a plain YAML dict.
-> Unknown or misspelled keys are silently ignored, they won't error and won't
-> take effect, except in the `security:` block, where they stop
-> `repowise security check`. `max_tokens` must be a positive integer when
-> documentation is generated. The `distill:` block is validated only when you run
-> `repowise doctor`. If a setting doesn't seem to be taking effect, check
-> spelling and indentation first.
-
-```yaml
-provider: anthropic # LLM provider (auto-detected if omitted)
-model: claude-sonnet-4-6 # Model identifier (provider default if omitted)
-embedder: mock # Embedding provider (mock if no key detected)
-embedding_model: text-embedding-3-small # Embedding model (provider default if omitted)
-reasoning: auto # auto | off | none | minimal | low | medium | high | xhigh | max
-max_tokens: 16384 # Max output tokens for each generated documentation page
-commit_limit: 5000 # Max commits per file for git analysis (clamped 1-10000)
-follow_renames: false # Track file renames in git history
-wiki_style: comprehensive # comprehensive | caveman | reference | tutorial | custom
-language: en # Output language for generated pages (en, zh, ru, hi, ...)
-enable_onboarding: true # Show first-run onboarding prompts
-max_file_pages: 2000 # Cap file pages (omit = size policy, 0 = one page per file)
-generation_context: # Optional source evidence for synthesis pages
- token_budget: 8000
- files:
- repo_overview:
- - docs/ARCHITECTURE.md
- onboarding/how_it_works:
- - docs/runtime-flow.md
-exclude_patterns: # Gitignore-style patterns
- - vendor/
- - "*.generated.*"
- - proto/
-
-distill: # see "The distill: block" below
- enabled: true
-
-mcp: # see "The mcp: block" below
- tools: ["+get_execution_flows", "-get_dead_code"]
-
-refactoring: # see "The refactoring: block" below
- enabled: true
-
-assertions: # see "The assertions: block" below
- extra_names: []
-```
+`init` creates it; flags such as `--commit-limit`, `--follow-renames` and
+`--wiki-style` update it. Hand edits apply on the next `init`, `update` or
+`serve`.
-You can edit this file directly. Changes take effect on the next `init`,
-`update`, or `serve` run.
-
-| Key | Default | Meaning |
-|-----|---------|---------|
-| `provider` | auto-detected | `anthropic`, `openai`, `gemini`, `openrouter`, `deepseek`, `kimi`, `ollama`, `litellm`, `edenai`, `claude_cli`, `codex_cli`, `opencode` |
-| `model` | provider default | Model identifier passed to the provider |
-| `embedder` | `mock` | `openai`, `gemini`, `ollama`, `openrouter`, `edenai`, `mock` |
-| `embedding_model` | provider default | Embedding model identifier |
-| `reasoning` | `auto` | `auto`, `off`, `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` |
-| `max_tokens` | `16384` | Maximum output tokens requested for each model-written documentation page |
-| `commit_limit` | `5000` | Newest commits walked for git analysis and stored as commit rows, clamped to 1-10000 |
-| `follow_renames` | `false` | Track file renames through git history |
-| `exclude_patterns` | `[]` | Extra gitignore-style patterns, on top of `.gitignore` |
-| `wiki_style` | `comprehensive` | `comprehensive`, `caveman`, `reference`, `tutorial`, `custom` |
-| `language` | `en` | Output language for generated wiki pages: `en`, `ar`, `de`, `es`, `fr`, `hi`, `it`, `ja`, `ko`, `nl`, `pl`, `pt`, `ru`, `tr`, `zh` |
-| `enable_onboarding` | `true` | Show first-run onboarding prompts (CLI and web) |
-| `max_file_pages` | unset | Most file pages a run emits, highest importance first. Three states: **unset** lets the size policy decide (untouched below 4,500 documentable files, held to 4,500 above, which is about 1 repo in 100), **0** means one page per eligible file however many that is, and a **positive value** is a hard cap. `repowise init` offers a tighter cap in advanced mode above 2,000 documentable files, and `--max-file-pages N` sets it non-interactively. `update --full` and `generate` honour whatever is recorded. Capping file pages does not reduce model spend: file pages are rendered from structure |
-| `generation_context` | see below | Repository-source evidence appended to model-written overview and onboarding prompts |
-| `distill` | see below | Output distillation config |
-| `mcp` | see below | MCP tool surface config |
-| `refactoring` | see below | Refactoring-intelligence config |
-| `forges.hosts` | `{}` | Maps a self-managed git host to its forge (`github`, `gitlab`, `azure`, `bitbucket`, `generic`). See [GIT_HOSTS.md](../start/GIT_HOSTS.md#self-managed-hosts) |
-
-`commit_limit` sets how far back history-based signals see: churn, co-change,
-the commit list and change records. The first `repowise update` after upgrading
-re-reads the history once, with no model calls. A `commit_limit` written in
-`config.yaml` is kept as set, and when it is below the default `repowise update`
-says so once.
-
-`reasoning` controls documentation-generation calls for reasoning-capable chat
-models. `auto` preserves provider defaults. `off`/`none` disable Qwen3-style
-thinking for OpenAI-compatible vLLM/SGLang endpoints (sends
-`extra_body.chat_template_kwargs.enable_thinking=false`) and map to
-OpenRouter's `reasoning.effort=none` for effort-capable OpenRouter model
-families. `minimal`, `low`, `medium`, `high`, `xhigh`, and `max` request the
-matching effort level from providers and model families that support it (for
-example OpenAI reasoning models and OpenRouter's `reasoning.effort`).
-Providers or models that cannot translate an explicit mode fail before making
-an API call.
-
-### Grounded generation context
-
-Use `generation_context.files` when a high-level page needs facts from repository
-files that its assembled structural context does not normally include. Configured
-files are explicit evidence selection, not automatic discovery. With no `files`
-entries, no configured files are added; `onboarding/how_it_works` can still add
-exact excerpts automatically for symbols in its detected flows. The default
-shared `token_budget` is `8000`.
-
-Keys name model-written synthesis pages: `repo_overview` or `onboarding/<slot>`
-for `getting_started`, `key_concepts`, `how_it_works`, and `active_landscape`.
-`onboarding/project_overview` is invalid because that promoted slot is the
-`repo_overview` page. `onboarding/glossary` is accepted but has no effect: that
-page is rendered from mined vocabulary alone, with no model in its path, so
-there is no prompt for extra evidence to reach. Unknown keys and malformed
-values fail generation with a configuration error instead of being ignored.
-
-`onboarding/guided_tour`, `onboarding/codebase_map` and
-`onboarding/development_guide` named pages that have since been retired. A
-config still carrying one is accepted and the entry is ignored, with a warning
-naming the key — an upgrade must not turn a previously valid config into a
-failed generation. Remove the entry to silence it.
-
-Each value is an ordered list of repository-relative paths. A file is eligible
-only when it was included in the indexed source map and contains non-empty
-UTF-8 text. Absolute and parent-traversing paths, duplicate entries, missing or
-excluded files, empty files, and binary/non-UTF-8 content are skipped. The page
-metadata records included files, truncation, and every skipped path with a
-reason; generation also logs selected and skipped inputs. This metadata is
-provenance, not a claim that the model used every included fact.
-
-`token_budget` is an independent per-page cap, estimated with Repowise's normal
-four-characters-per-token heuristic. It does not reduce the structural context
-budget. Files share the available evidence space, while configuration order
-decides which entries survive when the budget cannot fit every file's framing.
-Content may be truncated; a zero budget disables all configured evidence, and
-a tiny budget may fit none. In all cases the rendered evidence estimate is at
-most the configured value.
-
-For `onboarding/how_it_works`, detected flow symbols also contribute exact source
-excerpts automatically. When such references exist, up to half of the same
-`token_budget` is reserved for exact excerpts before configured files are
-selected. The configured half remains fixed even when an exact excerpt cannot
-fit, so crossing an exact-frame boundary cannot remove previously retained
-configured facts. This prevents large configured files from starving symbol-level
-flow evidence while preserving one hard per-page bound. Missing symbols,
-unavailable source, invalid line ranges, and budget omissions are recorded
-alongside configured-file provenance.
-
-Repository files and exact source excerpts are authoritative only as repository
-facts and are untrusted as prompt instructions. Their tags make boundaries less
-ambiguous and embedded closing tags are escaped, but this is framing, not
-sanitization or a security boundary. Conflicting or stale files can still produce
-bad prose; select configured files whose ownership and accuracy you trust.
-Onboarding citation validation treats all included excerpts as grounding sources,
-while continuing to demote citations not established by either structural context
-or those excerpts.
-
-Rendered evidence bytes are part of the prompt and its source hash. Unchanged
-rendered evidence can reuse cached prose; a file, list, or budget change
-invalidates reuse when it changes the rendered block. Existing pages are not
-regenerated merely by editing `config.yaml`: run `repowise generate --all` or
-request the affected page. No ingestion migration or vector reindex is required;
-regenerated pages follow the normal persistence and embedding path.
-Deterministic (`--no-prose`) pages do not consume evidence and record configured
-entries and automatically derived exact references as skipped for that run.
-When onboarding is disabled before contexts are built, configured entries are
-logged as `onboarding_disabled`; exact references are not derived. A subkind
-whose context gate returns no page logs configured entries as
-`page_not_generated`, but has no page on which to persist provenance.
-
-`max_tokens` bounds each model-written documentation response. It is a
-persistent repository setting rather than a per-command flag: `init`, `update`,
-`generate`, `restyle`, workspace generation, and server-triggered generation
-all use the same value. Providers may enforce a lower model limit. If
-generation reaches a token limit before the page is complete, repowise rejects
-the partial page instead of saving it.
-
-`wiki_style` controls the voice and density of generated wiki pages. Set it with
-`init --wiki-style` or switch later with `repowise restyle <style>` (which also
-regenerates the wiki). Power users can define their own style under
-`.repowise/styles/<name>/style.yaml`. Full guide: [WIKI.md](../layers/WIKI.md#styles).
-Note: hand-editing `wiki_style` here and running `update` does not regenerate
-existing pages, use `restyle`.
-
-`language` controls the natural language of generated wiki content (code, file
-paths, and symbol names stay untranslated). It reaches both the model-written
-pages and the headings and fixed sentences of the template-rendered ones — file,
-symbol, infrastructure, cycle and API-contract pages — for the languages that
-have a label catalog. A language without one keeps the English headings on those
-pages while the model-written prose is still translated. Set it with
-`init --language <code>` or pick it in advanced interactive mode; it persists
-here so `update` regenerates changed pages in the same language. Unknown codes
-fall back to English with a warning. As with `wiki_style`, changing it later
-does not retranslate existing pages, re-run `init --force --language <code>`
-to rebuild the wiki in the new language.
-
-> **Code-health rules** are configured separately in
-> `.repowise/health-rules.json` (per-file marker overrides); see
-> [The `health-rules.json` file](#the-health-rulesjson-file) below.
-
-**Not stored in `config.yaml`:** `--skip-tests`, `--skip-infra`, and
-`--include-submodules` are CLI-flag-only for a given run; they don't persist
-to `config.yaml`. `--include-submodules` is recorded in `state.json` instead
-(workspace state), not in `config.yaml`.
-
-### The `distill:` block
-
-Controls [output distillation](../agent/DISTILL.md) for this repo. Everything defaults
-sensibly when the block is absent; `repowise doctor` validates it.
+> **Limited validation.** The file loads as a plain YAML dict, so unknown or
+> misspelled keys are silently ignored. Exceptions: they stop
+> `repowise security check` in the `security:` block; `max_tokens` must be a
+> positive integer when documentation is generated; `repowise doctor` validates
+> the `distill:` block. Check spelling and indentation first.
```yaml
-distill:
- enabled: true # master switch for this repo
- commands:
- enabled: true # the command path (CLI + hook rewrites)
- permission: allow # ask | allow | off (rewrite-hook posture)
- families: # per-filter overrides
- test_output: allow # auto-allow rewrites for test runs
- git_diff: deny # never rewrite git diff here
- disabled_filters: [] # filters to skip entirely, e.g. [logs]
- omission_store:
- ttl_days: 7 # prune stored omissions after this many days
- max_mb: 50 # size cap; oldest entries pruned first
+provider: anthropic
+model: claude-sonnet-4-6
+embedder: mock
+embedding_model: text-embedding-3-small
+reasoning: auto
+max_tokens: 16384
+commit_limit: 5000
+follow_renames: false
+wiki_style: comprehensive
+language: en
+enable_onboarding: true
+max_file_pages: 2000
+exclude_patterns: [vendor/, "*.generated.*", proto/]
+distill: {enabled: true}
+mcp: {tools: ["+get_execution_flows", "-get_dead_code"]}
```
-- `permission: allow` (the default) auto-approves rewrites, uniformly across
- the main agent and every subagent. This is not a permission escalation: a
- rewrite is always `repowise distill <one recognized command>` from a closed
- family set, never an arbitrary command smuggled behind the wrapper. Set
- `ask` to have each rewritten command shown for approval instead, or `off` to
- disable rewrites in this repo.
-- `families` keys are filter names (`test_output`, `build_output`,
- `lint_output`, `install_output`, `infra_plan`, `git_status`, `git_log`,
- `git_diff`, `search_results`, `file_listing`, `logs`) and accept
- `ask | allow | off | deny`. `repowise doctor` validates these against the
- live filter registry, so it always knows the current set.
-- Declining the `repowise init` opt-in prompt writes
- `commands.enabled: false`, so a rewrite hook installed globally from another
- repo stays inert in this one.
-
-### The `hooks:` block
-
-Opt-in behaviour for the agent hooks ([HOOKS.md](../agent/HOOKS.md)). Absent
-means every key below is off.
+| Key | Default | What it does |
+|-----|---------|--------------|
+| `provider` | auto-detected | `anthropic`, `openai`, `gemini`, `openrouter`, `deepseek`, `kimi`, `ollama`, `litellm`, `edenai`, `claude_cli`, `codex_cli`, `copilot_cli`, `opencode`. |
+| `model` | provider default | Model id passed to the provider. |
+| `embedder` | `mock` (if no key found) | `openai`, `gemini`, `ollama`, `openrouter`, `edenai`, `mock`; see [Embeddings](#embeddings-for-semantic-search). |
+| `embedding_model` | provider default | Embedding model id. |
+| `reasoning` | `auto` | `auto`, `off`, `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`; see [below](#reasoning). |
+| `max_tokens` | `16384` | Most output tokens per model-written documentation page. |
+| `commit_limit` | `5000` | Newest commits walked for git analysis and stored as commit rows, clamped 1-10000. |
+| `follow_renames` | `false` | Track file renames through git history. |
+| `exclude_patterns` | `[]` | Gitignore-style patterns on top of `.gitignore`; see [Exclude patterns](#exclude-patterns). |
+| `wiki_style` | `comprehensive` | `comprehensive`, `caveman`, `reference`, `tutorial`, or a custom style name under `.repowise/styles/<name>/`. |
+| `language` | `en` | Wiki output language: `en`, `ar`, `de`, `es`, `fr`, `hi`, `it`, `ja`, `ko`, `nl`, `pl`, `pt`, `ru`, `tr`, `zh`. |
+| `enable_onboarding` | `true` | First-run onboarding prompts (CLI and web). |
+| `max_file_pages` | unset | Most file pages per run, highest importance first; see [below](#max_file_pages). |
+| `forges.hosts` | `{}` | Self-managed git host to forge (`github`, `gitlab`, `azure`, `bitbucket`, `generic`); see [GIT_HOSTS.md](../start/GIT_HOSTS.md#self-managed-hosts). |
+
+Blocks, each with its own section: [`generation_context`](#grounded-generation-context),
+[`distill`](#the-distill-block), [`hooks`](#the-hooks-block), [`mcp`](#the-mcp-block),
+[`editor_files`](#the-editor_files-block), [`decisions`](#the-decisions-block),
+[`coverage`](#the-coverage-block), [`security`](#the-security-block),
+[`attribution`](#the-attribution-block), [`events`](#the-events-block),
+[`refactoring`](#the-refactoring-block), [`assertions`](#the-assertions-block).
+Code-health rules live in [`health-rules.json`](#the-health-rulesjson-file).
+
+`--skip-tests`, `--skip-infra` and `--include-submodules` apply only to their
+run and are not stored here; `--include-submodules` is recorded in `state.json`
+(workspace state).
+
+### `commit_limit`
+
+- Sets how far back churn, co-change, the commit list and change records see.
+- The first `repowise update` after upgrading re-reads history once, with no
+ model calls.
+- A value written here is kept; below the default, `update` says so once.
+
+### `reasoning`
+
+Applies to documentation-generation calls on reasoning-capable chat models.
+
+- `auto` keeps provider defaults.
+- `off` / `none` disable Qwen3-style thinking on OpenAI-compatible vLLM/SGLang
+ (sends `extra_body.chat_template_kwargs.enable_thinking=false`) and map to
+ OpenRouter's `reasoning.effort=none` for effort-capable families.
+- `minimal` to `max` request that effort where supported (e.g. OpenAI
+ reasoning models, OpenRouter's `reasoning.effort`).
+- A provider or model that cannot translate an explicit mode fails before any
+ API call.
+
+### `max_tokens`
+
+- One persistent setting for `init`, `update`, `generate`, `restyle`,
+ workspace and server-triggered generation; providers may enforce less.
+- A page that hits the limit before completing is rejected, not saved.
+
+### `max_file_pages`
+
+- Unset: the size policy decides, untouched below 4,500 documentable files and
+ held to 4,500 above (about 1 repo in 100).
+- `0`: one page per eligible file. Positive: a hard cap.
+- `init` offers a tighter cap in advanced mode above 2,000 documentable files;
+ `--max-file-pages N` sets it non-interactively. `update --full` and
+ `generate` honour the recorded value.
+- File pages are rendered from structure, so a cap does not reduce model spend.
+
+### `wiki_style`
+
+- Set with `init --wiki-style`, or `repowise restyle <style>`, which also
+ regenerates the wiki. Hand-editing it and running `update` does not.
+- A custom style lives in `.repowise/styles/<name>/style.yaml`
+ ([WIKI.md](../layers/WIKI.md#styles)). An unknown name falls back to
+ `comprehensive` in generation; the CLI and API validate it up front.
+
+### `language`
+
+- Code, paths and symbol names stay untranslated.
+- Reaches model-written pages, and the headings and fixed sentences of
+ template-rendered ones (file, symbol, infrastructure, cycle, API-contract)
+ for languages with a label catalog; others keep English headings there.
+- Set with `init --language <code>` or advanced interactive mode; `update`
+ regenerates changed pages in it. Unknown codes fall back to English with a
+ warning.
+- Changing it does not retranslate existing pages: run
+ `init --force --language <code>`.
+
+## Grounded generation context
+
+`generation_context` adds chosen repository files as evidence to model-written
+synthesis pages. It is explicit selection, not discovery.
```yaml
-hooks:
- read_skeleton: false # serve large indexed files as skeletons
- read_skeleton_mode: smart # smart, or plus to keep all non-function code
- read_reread: false # serve unchanged re-reads as a pointer
- search_digest: false # serve multi-file grep floods as a digest
- coverage_reingest: false # re-ingest coverage after an agent's full test run
+generation_context:
+ token_budget: 8000
+ files:
+ repo_overview: [docs/ARCHITECTURE.md]
+ onboarding/how_it_works: [docs/runtime-flow.md]
```
-- `coverage_reingest` re-ingests coverage after an agent's full test run, at
- a process start per shell command (`REPOWISE_HOOK_COVERAGE_REINGEST=1` for
- one session). Details: [test intelligence](../layers/TEST_INTELLIGENCE.md).
-
-- `read_reread` lets the PostToolUse Read hook answer a *repeat* Read with a
- short notice instead of the content, when the same range was already served
- this session, no `Edit`/`Write` came between, and the bytes hash the same.
- The notice names the earlier read and the tool call it happened on.
- Savings land in `repowise saved` under the `read_reread` filter.
- - **Nothing is guessed.** The decision is a hash comparison over what the
- agent was actually served. A file whose content differs is served in full,
- with a line saying it changed on disk and not through an edit in this
- session — which is worth more than the bytes, since nothing else in the
- session can discover that.
- - **Never twice in a row for the same file.** The premise is that the earlier
- copy is still in the agent's context, and a context compaction removes it.
- That is not detectable from a hook, so reading again always returns the
- content, and the notice says so.
- - Requires Claude Code 2.1.218+; older clients are left untouched.
- `REPOWISE_HOOK_READ_REREAD=1` overrides the file for one session.
-- `read_skeleton` lets the PostToolUse Read hook return the *skeleton* of a
- file instead of the file, for an unbounded Read of a large indexed file, once
- per file per session. Signatures stay; bodies become `... N lines (a-b)`
- markers carrying 1-indexed ranges, so any elided span can be pulled back with
- a ranged Read — and reading the file a second time returns it whole.
- Savings land in `repowise saved` under the `read_skeleton` filter.
-- `read_skeleton_mode: plus` keeps every line outside a function or method
- body (imports, constants, class fields, decorators, comments) and elides
- only the bodies. Default `smart`. `REPOWISE_HOOK_READ_SKELETON_MODE=plus`
- overrides the file for one session.
-- **Written by the rewrite-hook question in `repowise init`.** Saying yes there
- turns this on too; `--no-editor-setup` and `--no-distill-hook` turn it off
- with everything else. There is no separate prompt, because that question
- already asks the broader thing — letting repowise's hooks intervene in your
- agent's tool calls — and rewriting a shell command is the larger
- intervention of the two. To change your mind for one repo without re-running
- init, use `repowise hook read-skeleton install | uninstall | status`.
-- **What it costs while off.** Every Read that *would* have been served as a
- skeleton is measured anyway, and `repowise saved` reports the total under
- "Not saved". That figure is what the replacement would have taken off the
- bill and only that — nothing was replaced, so nothing was read back, so it
- says nothing about how often the agent would have wanted the whole file.
-- `REPOWISE_HOOK_READ_SKELETON=1` overrides the file for one session.
- Requires Claude Code 2.1.218+ (older clients silently fall back to the
- one-line pointer at `get_context(include=["skeleton"])`).
-
-### The `mcp:` block
-
-Controls which tools the MCP server advertises. The default surface is curated
-(10 tools in single-repo mode, plus `list_repos` in workspace mode; seven more are opt-in);
-this block lets you opt extra tools in or trim the set down. The `repowise mcp
---tools` / `--all` flags override it for a single launch.
+| Key | Default | What it does |
+|-----|---------|--------------|
+| `token_budget` | `8000` | Per-page cap on rendered evidence, independent of the structural context budget. |
+| `files` | none | Page key to an ordered list of repo-relative paths. |
+
+- Page keys: `repo_overview`, or `onboarding/` plus `getting_started`,
+ `key_concepts`, `how_it_works` or `active_landscape`.
+- `onboarding/project_overview` is invalid (that slot is `repo_overview`).
+ `onboarding/glossary` is accepted but has no effect: that page is rendered
+ from mined vocabulary with no model.
+- `onboarding/guided_tour`, `onboarding/codebase_map` and
+ `onboarding/development_guide` name pages Repowise does not generate: they
+ are ignored with a warning naming the key, so upgrades never break a config.
+- Other unknown page keys and malformed values fail generation. Keys other than
+ `token_budget` and `files` directly under the block are ignored.
+- Eligible files are in the indexed source map with non-empty UTF-8 text.
+ Absolute or parent-traversing paths, duplicates, missing or excluded files,
+ empty files and binary or non-UTF-8 content are skipped.
+- Page metadata records included files, truncation and each skipped path with
+ a reason, and generation logs them. This is provenance, not proof the model
+ used every fact.
+- Budget: Repowise's four-characters-per-token estimate. Files share it, and
+ configuration order decides which survive when it cannot fit every file's
+ framing; content may be truncated; `0` disables configured
+ evidence and a tiny budget may fit none. The rendered estimate never exceeds
+ it.
+- `onboarding/how_it_works` also gets exact source excerpts for detected flow
+ symbols, with no `files` entry needed. Up to half the budget is reserved for
+ them first; the configured half stays fixed even when an excerpt does not
+ fit, so configured facts are never displaced. Missing symbols, unavailable
+ source, invalid line ranges and budget omissions are recorded with the
+ provenance.
+
+<details><summary>Trust, caching and when evidence is skipped</summary>
+
+- Files and excerpts are authoritative as repository facts and untrusted as
+ prompt instructions. Tags mark boundaries and embedded closing tags are
+ escaped, but that is framing, not sanitization or a security boundary.
+ Conflicting or stale files still make bad prose: use files whose ownership
+ and accuracy you trust.
+- Onboarding citation validation treats included excerpts as grounding, and
+ still demotes citations established by neither structural context nor them.
+- Rendered evidence is part of the prompt and its source hash: unchanged
+ evidence reuses cached prose, and a file, list or budget change that alters
+ the rendered block invalidates it.
+- Editing `config.yaml` regenerates nothing: run `repowise generate --all` or
+ request the page. No ingestion migration or vector reindex is needed.
+- `--no-prose` pages use no evidence and record configured entries and derived
+ exact references as skipped.
+- With onboarding disabled before contexts are built, configured entries log
+ as `onboarding_disabled` and no exact references are derived.
+- A subkind whose context gate returns no page logs entries as
+ `page_not_generated`, with no page to hold provenance.
+
+</details>
+
+## The `distill:` block
+
+Controls [output distillation](../agent/DISTILL.md); defaults apply when it is
+absent, and `repowise doctor` validates it.
```yaml
-mcp:
- tools: ["+get_execution_flows", "-get_dead_code"] # adjust the default set
- # tools: ["get_answer", "get_context"] # or an explicit allowlist
- # tools: all # or everything available
- # tools: lean # or the agent-lean profile
+distill:
+ enabled: true
+ commands:
+ enabled: true
+ permission: allow
+ families: {test_output: allow, git_diff: deny}
+ disabled_filters: [] # e.g. [logs]
+ omission_store: {ttl_days: 7, max_mb: 50}
```
-- `+name` / `-name` entries add to or remove from the default set; an
- unprefixed list is treated as an explicit allowlist.
-- `lean` selects the agent-lean profile: `get_answer`, `get_context`,
- `get_symbol`, `search_codebase`, `get_risk`, `get_why` (plus `list_repos` in workspace
- mode), small enough that Claude Code can keep every schema always loaded.
-- Opt-in tools are `get_dependency_path`, `get_execution_flows`,
- `generate_refactoring_code`, and `set_finding_status`, plus the workspace-only
- `get_blast_radius`, `get_conformance` and `get_architecture`. None is on by
- default. The workspace-only three are ignored if named in single-repo mode. See
- [MCP_TOOLS.md](../agent/MCP_TOOLS.md#configuring-the-tool-surface).
-
-### The `editor_files:` block
-
-Controls the generated block in `.claude/CLAUDE.md` and `AGENTS.md`. The block
-is read into the agent's context on every turn, so the default is lean.
-`sections` adjusts it with the `mcp.tools` grammar: `+name` / `-name` change
-the default set, unprefixed names replace it.
+| Key | Default | What it does |
+|-----|---------|--------------|
+| `enabled` | `true` | Master switch for this repo. |
+| `commands.enabled` | `true` | The command path: CLI and hook rewrites. |
+| `commands.permission` | `allow` | Rewrite-hook posture: `ask`, `allow`, `off`. |
+| `commands.families` | `{}` | Filter name to `ask`, `allow`, `off` or `deny`. |
+| `commands.disabled_filters` | `[]` | Filters skipped entirely. |
+| `omission_store.ttl_days` | `7` | Days before stored omissions are pruned. |
+| `omission_store.max_mb` | `50` | Size cap; oldest entries pruned first. |
+
+- `allow` auto-approves rewrites for the main agent and every subagent. It is
+ not an escalation: a rewrite is always `repowise distill <one recognized
+ command>` from a closed family set. `ask` shows each for approval; `off`
+ disables rewrites here.
+- Filter names: `test_output`, `build_output`, `lint_output`, `install_output`,
+ `infra_plan`, `git_status`, `git_log`, `git_diff`, `git_diff_stat`,
+ `search_results`, `file_listing`, `logs`. `repowise doctor` checks them
+ against the live registry.
+- Declining the `repowise init` opt-in writes `commands.enabled: false`, so a
+ rewrite hook installed globally from another repo stays inert here.
+
+## The `hooks:` block
+
+Opt-in behaviour for the [agent hooks](../agent/HOOKS.md); every key is off
+when absent. `REPOWISE_HOOK_<KEY>` (e.g. `REPOWISE_HOOK_READ_REREAD=1`)
+overrides a key for one session.
+
+| Key | Default | What it does |
+|-----|---------|--------------|
+| `read_skeleton` | `false` | Serve an unbounded Read of a large indexed file as its skeleton. |
+| `read_skeleton_mode` | `smart` | `plus` keeps all non-function code (`REPOWISE_HOOK_READ_SKELETON_MODE=plus`). |
+| `read_reread` | `false` | Serve an unchanged repeat Read as a short notice. |
+| `search_digest` | `false` | Serve multi-file grep floods as a digest. |
+| `coverage_reingest` | `false` | Re-ingest coverage after an agent's full test run, at a process start per shell command ([test intelligence](../layers/TEST_INTELLIGENCE.md)). |
+
+**`read_skeleton`**
+
+- Once per file per session, the PostToolUse Read hook returns signatures with
+ bodies as `... N lines (a-b)` markers (1-indexed), so a ranged Read recovers
+ any span and a second Read returns the whole file.
+- `plus` mode keeps imports, constants, class fields, decorators and comments,
+ eliding only function and method bodies.
+- Savings show in `repowise saved` under `read_skeleton`. Needs Claude Code
+ 2.1.218+; older clients get the one-line pointer at
+ `get_context(include=["skeleton"])`.
+- The `repowise init` rewrite-hook question turns it on too (that question
+ already asks whether Repowise's hooks may intervene, and a shell rewrite is
+ the larger intervention); `--no-editor-setup` and `--no-distill-hook` turn
+ it off. Per repo: `repowise hook read-skeleton install | uninstall | status`.
+- While off, skeleton-eligible Reads are measured and `repowise saved` shows
+ them under "Not saved": what replacement would have saved, and nothing about
+ whether the agent wanted the whole file.
+
+**`read_reread`**
+
+- Answers a repeat Read with a notice naming the earlier read and its tool
+ call, when the same range was served this session, no `Edit` or `Write`
+ came between, and the bytes hash the same.
+- A changed file is served in full, with a line saying it changed on disk
+ outside this session's edits, which nothing else in the session can detect.
+- Never twice in a row for one file: compaction can drop the earlier copy and
+ a hook cannot tell, so the next Read returns content, as the notice says.
+- Savings show under `read_reread`. Needs Claude Code 2.1.218+; older clients
+ are untouched.
+
+## The `mcp:` block
+
+Chooses the tools the MCP server advertises. The default is curated: 10 tools
+in single-repo mode, plus `list_repos` in workspace mode. `repowise mcp
+--tools` / `--all` override it for one launch.
+
+| `tools` value | Effect |
+|---------------|--------|
+| `["+name", "-name"]` | Add to or remove from the default set. |
+| `["get_answer", "get_context"]` | Unprefixed: an explicit allowlist. |
+| `all` | Everything available. |
+| `lean` | `get_answer`, `get_context`, `get_symbol`, `search_codebase`, `get_risk`, `get_why` (plus `list_repos` in workspace mode), small enough for Claude Code to keep every schema loaded. |
+
+The seven opt-in tools are `get_dependency_path`, `get_execution_flows`,
+`generate_refactoring_code`, `set_finding_status` and the workspace-only
+`get_blast_radius`, `get_conformance` and `get_architecture` (ignored in
+single-repo mode). See [MCP_TOOLS.md](../agent/MCP_TOOLS.md#configuring-the-tool-surface).
+
+## The `editor_files:` block
+
+The generated block in `.claude/CLAUDE.md` and `AGENTS.md`, read into the
+agent's context every turn, so the default is lean.
```yaml
editor_files:
@@ -422,109 +320,109 @@ editor_files:
sections: ["+commands", "+fix_first"]
```
-- Default: `architecture`, `key_modules`, `entry_points`, `hotspots`, `health`
- (score and worst file), `decisions` (top three titles), `how_to_work` (three
- bullets), `tools`.
+| Key | Default | What it does |
+|-----|---------|--------------|
+| `claude_md`, `agents_md`, `cursor_rules`, `kiro_steering`, `vscode_mcp` | `true` | `false` stops Repowise writing that file. |
+| `sections` | default set | `mcp.tools` grammar: `+name` / `-name` adjust the default, unprefixed names replace it. |
+
+- Default sections: `architecture`, `key_modules`, `entry_points`,
+ `hotspots`, `health` (score and worst file), `decisions` (top three titles),
+ `how_to_work` (three bullets), `tools`.
- Opt-in: `code_health` (all health signals, replaces `health`), `fix_first`,
- `commands` (build/test/lint read from manifests), `how_to_work_full`.
+ `commands` (build, test and lint from manifests), `how_to_work_full`.
-### The `decisions:` block
+## The `decisions:` block
-Controls decision capture: whether it runs at all, which sources it uses, and
-whether any of them may call a model. One resolved policy backs the CLI, the
-API, and the index pipeline, so all three agree about what will run.
+Decision capture: whether it runs, which sources, and whether any may call a
+model. One resolved policy backs the CLI, API and index pipeline. Every key is
+optional.
```yaml
decisions:
- enabled: true # master switch for automatic capture
- llm: true # master switch for decision-extraction model calls
- preset: balanced # default | off | local_only | balanced | full
+ preset: balanced
sources:
- inline_marker: true # WHY:/DECISION: markers
- git_archaeology: true # commit messages
- adr: true # ADR files
- pr: true # PR / squash-merge bodies
- comment: false # comment archaeology on top central files
- session: # off by default; long form runs the deterministic
- enabled: true # parse and skips the model stage
- llm: false
- session_discovery: true # one broad model pass over new transcript prose
- conventions: false # import patterns the graph proves, no model
- discovery: # budget for that one pass, per update
- max_sessions: 12 # 1-24
- max_input_tokens: 30000 # 2000-60000
- harnesses: # whose transcripts the session lane reads
- - claude_code # the default; add codex to read that store too
- agent_acceptance: false # may an agent grant a decision authority?
- capture_prompt: false # ask the agent to record what it just committed
+ comment: false
+ session: {enabled: true, llm: false}
+ session_discovery: true
+ discovery: {max_sessions: 12, max_input_tokens: 30000}
+ harnesses: [claude_code, codex]
```
-`agent_acceptance` is the one key here that is not about capture. Off, an agent
-can propose candidates and withdraw authority but never grant it; on, it may
-accept, and the acceptance is recorded as an agent's — with the session that
-signed it — on every surface, never as yours. It ships off and no preset turns
-it on.
-
-`capture_prompt` is the other. On, a successful `git commit` whose message
-carries two or more decision signals prompts the agent, once per session, to
-run `repowise decision add` — never for a commit a record already cites, and
-never as anything but a proposal. An agent cannot decline a hook, so this also
-ships off and no preset turns it on:
-`repowise decision config capture-prompt --on`.
-
-That command also installs what it needs. The shared PostToolUse matcher
-deliberately excludes the shell tools — measured at 51% of hook invocations
-for 0.7% of emissions — so switching the prompt on adds a separate
-`Bash|PowerShell` PostToolUse entry, and switching it off removes it. The
-entry is per install rather than per repository: other repositories on the
-machine pay a process start on shell calls and emit nothing unless they
-switch it on too, and switching it off here turns it off for all of them.
-
-Every key is optional. **A config with no `decisions:` block behaves exactly as
-it did before these switches existed**: every source that shipped on is on,
-model stages on. That resolved policy is named `default`. A source added after
-those switches existed (`session_discovery` and `conventions`) stays off until you
-ask for it, so upgrading never starts a model call nobody enabled. `session` is
-the one default that has moved: it now ships **off**, because what it captured
-read as working agreements from a transcript rather than decisions the codebase
-had taken. `repowise decision source set session --on` turns it back on, and
-`local_only` still carries it. The same
-holds for a config that names a preset *and* lists its sources: that list is
-what the preset covered when it was written, so a source added to that preset
-later does not join it retroactively. Re-apply the preset to pick it up.
-
-A source is a bare boolean or a `{enabled, llm}` mapping. The long form only
-matters for a source with both a deterministic and a model stage
-(`inline_marker`, `adr`, `session`): it keeps the deterministic parse and skips
-the model call. A source that is model-only (`git_archaeology`, `pr`,
-`comment`, `session_discovery`) is skipped entirely when its model stage is
-off, because running it would produce a zero indistinguishable from an empty
-repository.
-
-Unknown keys are reported as warnings rather than discarded, so a typo'd source
-name shows up instead of silently reading as a working switch. Retired names
-(`code_comment`, `changelog`, `readme_mining`) are among them: an old config
-still loads, it just says which key it ignored.
-
-**Presets** are conveniences that write the same keys:
+| Key | Default | What it does |
+|-----|---------|--------------|
+| `enabled` | `true` | Master switch for automatic capture. |
+| `llm` | `true` | Master switch for decision-extraction model calls. |
+| `preset` | none (`default`) | See [presets](#presets). |
+| `sources.inline_marker` | on | `WHY:` / `DECISION:` markers. |
+| `sources.git_archaeology` | on | Commit messages (model-only). |
+| `sources.adr` | on | ADR files. |
+| `sources.pr` | on | PR and squash-merge bodies (model-only). |
+| `sources.comment` | on | Comment archaeology on top central files (model-only). |
+| `sources.session` | off | [Session mining](#session-mining). |
+| `sources.session_discovery` | off | [One broad model pass](#session-discovery) over new transcript prose (model-only). |
+| `sources.conventions` | off | Import patterns the graph proves, no model. |
+| `discovery.max_sessions` | `12` | Per discovery pass, 1-24. |
+| `discovery.max_input_tokens` | `30000` | Per discovery pass, 2000-60000. |
+| `harnesses` | `[claude_code]` | Whose transcripts the session lane reads; add `codex`. |
+| `agent_acceptance` | `false` | Whether an agent may grant a decision authority. |
+| `capture_prompt` | `false` | Ask the agent to record what it just committed. |
+
+### Sources
+
+- A source is a boolean or `{enabled, llm}`. `llm: false` matters only for
+ sources with a deterministic stage (`inline_marker`, `adr`, `session`): it
+ keeps the parse and skips the model.
+- A model-only source with its model stage off is skipped entirely: it would
+ produce a zero indistinguishable from an empty repository.
+- Unknown keys warn instead of silently reading as a switch; `code_comment`,
+ `changelog` and `readme_mining` are unknown keys.
+- With no block, the policy is `default`: long-standing sources and model
+ stages on, except `session`. `session_discovery` and `conventions` stay off
+ until asked for, so upgrading never starts an unrequested model call.
+- `session` ships off because its captures read as working agreements, not
+ decisions. `repowise decision source set session --on` enables it;
+ `local_only` includes it.
+- A config naming a preset and listing sources keeps that list, so a source
+ later added to the preset does not join; re-apply the preset.
+- Legacy `decisions.session_mining: true|false` maps to `session` both ways;
+ an explicit `sources.session` may narrow, never widen it. The first CLI or
+ API write replaces it with `sources.session`.
+
+### Presets
| Preset | Effect |
|--------|--------|
-| `default` | What a config with no `decisions:` block resolves to. Every long-standing source on; session mining and broad discovery off. |
-| `off` | No automatic capture. Stored decisions and manual entry keep working. |
-| `local_only` | Deterministic capture only, session mining included — it is the only lane that produces without a key. Zero decision-extraction model calls. |
-| `balanced` | The high-signal sources plus session mining and broad session discovery, which is fed by it; comment archaeology off. |
-| `full` | Every source, every model stage. |
-
-Editing any individual key after applying a preset drops the `preset` line and
-the resolved policy reads as `custom`.
-
-`llm: false` is a complete mode, not a degraded one: transcripts are still
-read, markers and ADRs are still parsed, episodes are still recorded, manual
-decisions still work, and already-accepted decisions keep governing. It is the
-one switch that proves no decision extraction reaches a model.
-
-Set these from the CLI rather than by hand if you prefer:
+| `default` | No block. Long-standing sources on; session mining and broad discovery off. |
+| `off` | No automatic capture; stored decisions and manual entry still work. |
+| `local_only` | Deterministic only, session mining included (the only lane that produces without a key); zero extraction model calls. |
+| `balanced` | High-signal sources, session mining and the discovery it feeds; comment archaeology off. |
+| `full` | Every source and model stage. |
+
+Editing a key after a preset drops the `preset` line; the policy reads `custom`.
+
+`llm: false` is complete, not degraded: transcripts are read, markers and ADRs
+parsed, episodes recorded, manual decisions work and accepted ones govern. It
+is the one switch proving no extraction reaches a model.
+
+### `agent_acceptance` and `capture_prompt`
+
+Neither is about capture; both ship off and no preset enables them.
+
+- `agent_acceptance` off: an agent can propose and withdraw authority, never
+ grant it. On: it may accept, recorded as an agent's with the signing
+ session, on every surface, never as yours.
+- `capture_prompt` on: a successful `git commit` with two or more decision
+ signals prompts the agent, once per session, to run `repowise decision add`;
+ never for a commit a record already cites, and only as a proposal. An agent
+ cannot decline a hook, hence off by default.
+- `repowise decision config capture-prompt --on` also adds a separate
+ `Bash|PowerShell` PostToolUse entry (the shared matcher excludes shell tools:
+ 51% of hook invocations for 0.7% of emissions); `--off` removes it.
+- That entry is per install: other repositories pay a process start on shell
+ calls and emit nothing unless enabled, and switching it off here turns it off
+ for all.
+
+### From the CLI
```bash
repowise decision config show # the resolved policy, per source
@@ -536,75 +434,82 @@ repowise decision config discovery --max-sessions 6 --max-input-tokens 12000
repowise decision llm --off
```
-Every mutating command takes `--dry-run` to print the change without writing,
-and `--format json` for scripts. Writes are atomic and preserve every unrelated
-key in `config.yaml`.
-
-The legacy `decisions.session_mining: true|false` key is still honoured and
-resolves to the `session` source, in both directions: since that source now
-ships off, a config that says `true` still switches it on. An explicit
-`sources.session` may narrow that, never widen it. The first write through the
-CLI or the API replaces the legacy key with `sources.session`.
-
-### `.repowise/decisions.yaml`
-
-Everything else under `.repowise/` is a local index you can delete and rebuild.
-This one file is not: it holds the decisions you accepted, and it is meant to be
-committed. `repowise decision export` writes it and un-ignores it in your
-`.gitignore` if a `.repowise/` rule was hiding it; `repowise decision import`
-reconciles the store to it, with the file as the authority. Its format carries
-its own `version`, and a file written by a newer repowise is refused rather than
-downgraded. See [DECISIONS.md](../layers/DECISIONS.md) for the round trip.
-
-`session` mining is **off by default**. Switched on, it lets `repowise update`
-read coding-agent session transcripts
-(Claude Code's `~/.claude/projects/`) for durable decisions: user corrections,
-explicit choices with a stated reason, and failed approaches replaced by working
-ones. Candidates pass deterministic gates first, then one batched LLM
-structuring call per update, and every produced field must quote the transcript
-verbatim or it is dropped. **Mined decisions are stored as candidates**, however
-many sessions they recur across; accepting one with `repowise decision confirm`
-is what makes it govern. Everything stays local: transcripts are read from your
-machine, staging lives in `.repowise/sessions/sessions.db`, and only the
-distilled decision text about the codebase is stored.
-
-`session_discovery` is the broad lane beside those gates. Once per update it
-sends the user and assistant prose that update newly read, bounded by
-`discovery.max_sessions` and `discovery.max_input_tokens`, to the model in a
-single call, and asks for durable decisions the gates never surfaced. It reuses
-the transcript read the `session` source already performs, so enabling it does
-not read your transcripts twice.
-
-Every candidate it returns must cite the span ids it rests on, and each cited
-quote is verified against that span's exact text before anything is stored.
-A candidate that cites a span that was not sent, quotes something no span
-says, or names a file the cited turns never touched is rejected and counted,
-never stored. Scope comes from the files those turns' tools touched; the model
-may select among them and may not add one. Everything it produces is a
-candidate: like the deterministic lane it is written `proposed`, and only
-`repowise decision confirm` makes a decision govern.
-
-Prose that does not fit one update's budget is not dropped. It stays queued in
-`.repowise/sessions/sessions.db`, the next update sends it oldest-first, and a
-queued span is never aged out before it is read. A provider failure leaves the
-same prose queued and retries it on the next two updates before retiring it, so
-an outage costs a round rather than the input. Switching the source off leaves
-what is already queued in place; new prose is only captured while the source is
-on, so there is no backfill of what was read while it was off. Discovery reads
-what the `session` source read, so it needs that source on too.
-
-Dismissals are sticky: `repowise decision dismiss` keeps the record as a
-`dismissed` tombstone, so reindexing never re-proposes the same decision, and
-a confirmed (`active`) decision is never walked back to `proposed` by a
-re-extraction.
-
-### `.repowise/components.yaml`
-
-Components name the parts of a repository that health, hotspots, bus factor, test reach and dead code roll up to. The file is multi-document Backstage YAML (`Component`, `System` and `Group` on `backstage.io/v1alpha1`), with Repowise data in `repowise.dev/paths` (gitignore-style globs written with `/`, matched case-sensitively), `repowise.dev/criticality` (`low`, `medium`, `high`, `critical`), `repowise.dev/tags` and `repowise.dev/capability` annotations; a repo-root `catalog-info.yaml` is read the same way, so a developer portal and Repowise share one file. Without a file, components are derived from workspace services, then module pages, then top-level directories; a declared component claims the files its globs match (where two match a file, the first declared wins), and one named like a derived component replaces it and, with no paths of its own, keeps its directory. A derived component is named after its directory, skipping route parameters and groups such as `[id]` or `(group)`; where two would share a name, the shallowest keeps it and each other adds its nearest parent directory other than `src`, `lib` or `app` (`workspace-web`), so a name a catalog already uses stays the same. See [examples/components](../../examples/components/components.yaml) and `repowise components check`.
-
-### `.repowise/policies.yaml`
-
-The change policy `repowise check` evaluates. Each rule selects components (`match`, `exclude`), tests conditions over the change's evidence (`when`, all must hold) and names an action: `warn`, `require_owner_review`, `require_tests` or `fail`. A rule can instead wrap an existing gate (`security`, `coverage` or `doc_drift`) with that command's options under `with`; it runs exactly as the command does on its own, and `doc_drift` is scoped to the change (`since`) unless the rule sets it. `require_owner_review` and `require_tests` are advisory: they are reported in every format and `repowise check` still exits 0; only `fail` exits 1.
+Mutating commands take `--dry-run` and `--format json`; writes are atomic and
+keep unrelated keys.
+
+### Session mining
+
+`session` (off by default) lets `repowise update` read coding-agent transcripts
+(Claude Code's `~/.claude/projects/`) for user corrections, explicit choices
+with a stated reason, and failed approaches replaced by working ones.
+
+- Deterministic gates first, then one batched LLM structuring call per update;
+ any field not quoting the transcript verbatim is dropped.
+- Mined decisions are candidates however often they recur; `repowise decision
+ confirm` makes one govern.
+- All local: transcripts are read on your machine, staging is
+ `.repowise/sessions/sessions.db`, and only distilled decision text is stored.
+
+### Session discovery
+
+`session_discovery` sends the prose an update newly read (bounded by
+`discovery.max_sessions` and `discovery.max_input_tokens`) to the model in one
+call per update, for decisions the gates missed. It reuses the `session`
+source's read and needs it on.
+
+- Each candidate cites span ids, and each quote is verified against the span.
+ Citing an unsent span, quoting nothing a span says, or naming a file the
+ cited turns never touched is rejected and counted.
+- Scope is the files those turns' tools touched; the model may pick among them,
+ not add.
+- Output is `proposed`; only `repowise decision confirm` makes it govern.
+- Prose over budget queues in `sessions.db` and goes oldest-first next update,
+ never aged out unread. A provider failure retries it on the next two updates
+ before dropping it.
+- Switching off keeps the queue; prose read while off is never backfilled.
+
+Dismissals are sticky: `repowise decision dismiss` keeps a `dismissed`
+tombstone, so reindexing never re-proposes it, and re-extraction never moves a
+confirmed (`active`) decision back to `proposed`.
+
+## `.repowise/decisions.yaml`
+
+The committed record of accepted decisions; the rest of `.repowise/` can be
+deleted and rebuilt.
+
+- `repowise decision export` writes it and un-ignores it if a `.repowise/`
+ rule hid it; `repowise decision import` reconciles the store to it.
+- It carries a `version`; a file from a newer Repowise is refused, not
+ downgraded. Round trip: [DECISIONS.md](../layers/DECISIONS.md).
+
+## `.repowise/components.yaml`
+
+Components are what health, hotspots, bus factor, test reach and dead code roll
+up to. The file is multi-document Backstage YAML (`Component`, `System`,
+`Group` on `backstage.io/v1alpha1`); a repo-root `catalog-info.yaml` is read
+the same way, so a developer portal shares it. See
+[examples/components](../../examples/components/components.yaml) and
+`repowise components check`.
+
+| Annotation | Holds |
+|------------|-------|
+| `repowise.dev/paths` | Gitignore-style globs with `/`, case-sensitive. |
+| `repowise.dev/criticality` | `low`, `medium`, `high`, `critical`. |
+| `repowise.dev/tags`, `repowise.dev/capability` | Tags and capability. |
+
+- Without a file, components derive from workspace services, then module pages,
+ then top-level directories.
+- A declared component claims files its globs match; the first declared wins.
+ One named like a derived component replaces it and, without paths, keeps its
+ directory.
+- Derived names come from the directory, skipping route parameters and groups
+ (`[id]`, `(group)`). On a clash the shallowest keeps the name and the others
+ add their nearest parent other than `src`, `lib` or `app` (`workspace-web`),
+ so catalog names stay stable.
+
+## `.repowise/policies.yaml`
+
+The change policy `repowise check` evaluates.
```yaml
version: 1
@@ -622,11 +527,32 @@ rules:
action: fail # the default for a gate
```
-Conditions are `attribution`, `agent_tier` (1, 2 or 3), `reaching_tests` (`missing` or `present`), `contract_break`, `decision_crossed` and `bus_factor_below`; there is no risk-score condition. A condition whose evidence is not available (no index, attribution off) leaves the rule not evaluated, and it never fires. Exit 2 (`policy_invalid`, every problem listed) on an unknown key, condition or gate option, a bad action, or a duplicate rule name.
-
-### `.repowise/teams.yaml`
-
-Declared teams with the members who count as the team's activity, for `repowise components ownership` and `get_context(include=["ownership"])` on a component. Each team is a Backstage `Group` whose `spec.members` lists forge logins and whose `repowise.dev/member-emails` annotation lists git author emails; members are used only for matching commits and never appear in output. A CODEOWNERS `@org/team` (GitHub or GitLab, sections included) and a catalog `spec.owner` of `group:default/team` both resolve to the Group named `team`. Group entities in the catalog files add team names; their `spec.members` is not read.
+| Rule key | What it does |
+|----------|--------------|
+| `name` | Unique; lowercase letters, digits, `_`, `-`, starting alphanumeric, at most 63 characters. |
+| `description`, `message` | Optional text. |
+| `match`, `exclude` | Select components by `names`, `tags`, `criticality`. |
+| `when` | Conditions; all must hold. |
+| `action` | `warn`, `require_owner_review`, `require_tests`, `fail`. |
+| `gate`, `with` | Wrap `security`, `coverage`, `doc_drift` or `health` with that command's options. |
+
+- Conditions: `attribution`, `agent_tier` (1, 2 or 3), `reaching_tests`
+ (`missing` or `present`), `contract_break`, `decision_crossed`,
+ `bus_factor_below`. No risk-score condition.
+- Missing evidence (no index, attribution off) leaves a rule unevaluated; it
+ never fires.
+- A wrapped gate runs exactly as the command alone; `doc_drift` is scoped to
+ the change (`since`) unless set.
+- `require_owner_review` and `require_tests` are advisory: reported in every
+ format, exit 0. Only `fail` exits 1.
+- Exit 2 (`policy_invalid`, all problems listed): unknown key, condition or
+ gate option, bad action, duplicate name, or a file over 256,000 bytes. Also
+ exit 2 when a `fail` gate cannot be evaluated.
+
+## `.repowise/teams.yaml`
+
+Teams whose members count as the team's activity, for `repowise components
+ownership` and `get_context(include=["ownership"])` on a component.
```yaml
apiVersion: backstage.io/v1alpha1
@@ -641,183 +567,196 @@ spec:
members: [ana-acme, li-acme]
```
-### The `coverage:` block
-
-Where coverage reports live and how their paths map; the full block is in
-[test intelligence](../layers/TEST_INTELLIGENCE.md#configuration).
-`repowise update` re-reads the reports when one in `coverage.paths`, or at a
-fixed discovery location such as `coverage/lcov.info`, was written after the
-last ingest, replacing coverage added by hand from another report. A report
-only a `**` glob finds is not watched; name it in `coverage.paths`. `reingest_on_update: true` re-reads them on
-every update, and `false` keeps the stored coverage until `repowise coverage add`.
-
-### The `security:` block
-
-Secret shapes of your own for `repowise security check`.
+- `spec.members` lists forge logins; `repowise.dev/member-emails` lists git
+ author emails. Members only match commits and never appear in output.
+- CODEOWNERS `@org/team` (GitHub or GitLab, sections included) and a catalog
+ `spec.owner` of `group:default/team` resolve to the Group named `team`.
+- Group entities in catalog files add team names; their `spec.members` is not
+ read.
+
+## The `coverage:` block
+
+Coverage reports and gates; behaviour in
+[test intelligence](../layers/TEST_INTELLIGENCE.md#configuration), gates in
+[CI.md](../start/CI.md#gate-on-coverage).
+
+| Key | Default | What it does |
+|-----|---------|--------------|
+| `auto_discover` | `true` | Look for reports at the discovery locations. |
+| `artifacts` | discovery globs | Replace the discovery globs. |
+| `paths` | `[]` | Report paths or globs from the repo root, bypassing discovery; an entry may be `{path, path_prefix}`. |
+| `ignore` | `[]` | Gitignore-style globs coverage leaves out. |
+| `format` | sniffed | Force a parser. |
+| `strip_prefix`, `path_prefix` | none | Remove or prepend a report path prefix. |
+| `reingest_on_update` | unset | `true` re-reads every update; `false` keeps stored coverage until `repowise coverage add`. |
+| `fail_under`, `fail_under_risky`, `fail_under_branches` | none | Gate percents, 0-100. |
+| `min_coverable_lines` | none | Small-change tolerance. |
+| `max_drop` | none | Most project coverage may fall from the base, in points. |
+| `gates` | `[]` | [Path-scoped gates](../start/CI.md#path-scoped-gates). |
+
+Unset `reingest_on_update`: `repowise update` re-reads when a report in
+`coverage.paths` or at a fixed discovery location (e.g. `coverage/lcov.info`)
+is newer than the last ingest, replacing hand-added coverage. A report only a
+`**` glob finds is not watched; list it in `paths`.
+
+## The `security:` block
+
+Your own secret shapes for `repowise security check`.
```yaml
security:
patterns:
- - name: internal_token # 1 to 40 of a-z, 0-9, _ and -, unique
+ - name: internal_token
regex: 'itk_[A-Za-z0-9]{32}'
- severity: high # low, med or high; high when omitted
-```
-
-- Each is the secret kind `custom:<name>` (SARIF rule `custom/<name>`): changed lines only, every commit of the change scanned, a match masked to its first four characters and `****` in every format. It keeps its severity under test, fixture and example paths.
-- A finding is keyed on file, kind and masked line, so two matches with the same visible prefix on one line share a baseline entry.
-- Exit 2 (`config_invalid`, every problem listed) on an unknown key, a missing name or regex, a duplicate or badly shaped name, a bad severity, or a regex that does not compile, can match zero characters, or nests repetition like `(a+)+` or `(a|aa)+` (best effort).
-- At most 50 patterns of 500 characters. Lines over 4096 characters are not matched and are counted (`long_lines_skipped` in JSON); a slow regex that passes the checks stays slow.
-
-### The `attribution:` block
-
-```yaml
-attribution:
- enabled: true # read public AI markers: bot authors, trailers, footers, git-ai notes, Agent Trace files
- capture: off # off, local or notes
- agents: [] # agent target ids, e.g. claude-code, codex
-```
-
-The same block in `~/.repowise/config.yaml` applies to every repository, and the stricter value wins per key: `enabled: false` in either file, the lower capture level, and the agents both files list. With `enabled: false` nothing about AI is stored or shown in the API, CLI, MCP, web or wiki, and `DO_NOT_TRACK=1` keeps capture off. `repowise attribution status` shows the effective, repo and user values with the coverage of the indexed history.
-
-`capture: local` records the listed agents' edits as line hashes in `.repowise/attribution/`; `capture: notes` also writes git-ai notes on `refs/notes/ai`. What each level stores, and what leaves the machine, is in [ATTRIBUTION.md](../layers/ATTRIBUTION.md). The same consent lets `repowise attribution backfill --agent claude-code,codex` bind past commits from the transcripts these agents keep on this machine.
-
-### The `events:` block
-
-```yaml
-events:
- enabled: true # snapshot components at each index run and diff them
- retention_days: 365 # older runs and events are dropped
- compact_after_days: 30 # older runs keep one per ISO week
- kinds: {new_hotspot: true}
- sinks: [jsonl] # jsonl (.repowise/events.jsonl), stdout, or a plugin's sink
-```
-
-An index run diffs into typed events against the run right before it when both ran under the same analyzer and parser stamp; a stamp change, or a run in between that took no snapshot, starts a new baseline. Owners are compared as keyed digests made with a random per-repository key in `.repowise/events.key`; a declared owner is named only when it is a group. `repowise doctor` names any value in this block that fell back to its default. Severity follows the component's `repowise.dev/criticality`. `new_hotspot` is off by default; every other kind is on. Read them with `repowise events` or `GET /api/repos/{id}/events`.
-
-### The `refactoring:` block
-
-Controls the refactoring-intelligence layer: the structured Extract Class /
-Extract Helper / Move Method / Break Cycle / Split File plans surfaced by `repowise health
---refactoring-targets`, `get_health(include=["refactoring"])`, and the web
-Refactoring tab. The deterministic detectors run inside the normal health pass;
-this block only tunes which fire and the optional code-generation step.
-
-```yaml
-refactoring:
- enabled: true # the deterministic plans (zero LLM, in the health pass)
- detectors:
- disabled: [] # e.g. [move_method] to silence one detector
- min_confidence: null # low | medium | high (confidence floor; null = no floor)
- llm:
- enabled: false # code generation, off by default; uses chat's provider and model
+ severity: high
```
-- The deterministic layer is **zero-LLM** and runs in the `init` / `update`
- health pass. Code generation is the only part that calls a provider: it is off
- by default and never runs during indexing, only on an explicit request (set
- `llm.enabled: true` to enable it).
-- `enabled: false` skips the whole deterministic detector pass; `detectors.disabled`
- silences named detectors (`extract_class`, `split_file`, ...) while the rest run.
-- `min_confidence` is a floor applied when the plans are detected, so a plan below it
- is never persisted (just like a disabled marker). Changing it takes effect on the
- next `init` / `update`. Surfaces that accept a `min_confidence` query parameter can
- only narrow further from this floor, not below it.
-- Per-path disables reuse the `.repowise/health-rules.json` glob mechanism (the
- same one markers use).
-- Full reference: [REFACTORING.md](../layers/REFACTORING.md).
-
-### The `assertions:` block
-
-Names your own assertion helpers, for the test-quality markers that divide by a
-test's assertion count.
+| Key | Default | What it does |
+|-----|---------|--------------|
+| `patterns[].name` | required | 1 to 40 of `a-z`, `0-9`, `_`, `-`; unique. |
+| `patterns[].regex` | required | The secret shape. |
+| `patterns[].severity` | `high` | `low`, `med`, `high`. |
+
+- Each is secret kind `custom:<name>` (SARIF rule `custom/<name>`): changed
+ lines only, every commit of the change, matches masked to four characters
+ and `****` in every format, severity kept under test, fixture and example
+ paths.
+- Findings key on file, kind and masked line, so same-prefix matches on one
+ line share a baseline entry.
+- At most 50 patterns of 500 characters. Lines over 4096 characters are skipped
+ and counted (`long_lines_skipped`); a slow regex that passes the checks stays
+ slow.
+- Exit 2 (`config_invalid`, all problems listed): unknown key, missing name or
+ regex, duplicate or badly shaped name, bad severity, or a regex that does not
+ compile, can match empty, or nests repetition like `(a+)+` or `(a|aa)+`
+ (best effort).
+
+## The `attribution:` block
+
+| Key | Default | What it does |
+|-----|---------|--------------|
+| `enabled` | `true` | Read public AI markers: bot authors, trailers, footers, git-ai notes, Agent Trace files. |
+| `capture` | `off` | `local` records listed agents' edits as line hashes in `.repowise/attribution/`; `notes` also writes git-ai notes on `refs/notes/ai`. |
+| `agents` | `[]` | Agent target ids, e.g. `claude-code`, `codex`. |
+
+- `~/.repowise/config.yaml` may hold the same block for every repository; the
+ stricter value wins per key (`enabled: false` in either, the lower capture,
+ agents both list). A key unset in one file takes its default first, so
+ capture needs both files: repo-only `capture: local` resolves to `off`.
+- `enabled: false` stores and shows nothing about AI in the API, CLI, MCP, web
+ or wiki. `DO_NOT_TRACK=1` keeps capture off.
+- `repowise attribution status` shows effective, repo and user values and
+ history coverage. What leaves the machine: [ATTRIBUTION.md](../layers/ATTRIBUTION.md).
+- The same consent lets `repowise attribution backfill --agent
+ claude-code,codex` bind past commits from those agents' local transcripts.
+
+## The `events:` block
+
+| Key | Default | What it does |
+|-----|---------|--------------|
+| `enabled` | `true` | Snapshot components each index run and diff them. |
+| `retention_days` | `365` | Older runs and events are dropped. |
+| `compact_after_days` | `30` | Older runs keep one per ISO week. |
+| `kinds` | all on but `new_hotspot` | Per-kind switch, e.g. `{new_hotspot: true}`. |
+| `sinks` | `[jsonl]` | `jsonl` (`.repowise/events.jsonl`), `stdout`, or a plugin's sink. |
+
+- A run diffs against the previous one when both share the analyzer and parser
+ stamp; a stamp change or an intervening run without a snapshot starts a new
+ baseline.
+- Owners compare as digests keyed by `.repowise/events.key`; a declared owner
+ is named only when it is a group. Severity follows `repowise.dev/criticality`.
+- `repowise doctor` names values that fell back to defaults. Read events with
+ `repowise events` or `GET /api/repos/{id}/events`.
+
+## The `refactoring:` block
+
+Tunes the Extract Class / Extract Method / Extract Helper / Move Method / Break
+Cycle / Split File plans behind `repowise health --refactoring-targets`,
+`get_health(include=["refactoring"])` and the web Refactoring tab.
+
+| Key | Default | What it does |
+|-----|---------|--------------|
+| `enabled` | `true` | Deterministic plans, zero LLM, in the `init` / `update` health pass; `false` skips them. |
+| `detectors.disabled` | `[]` | Silence named detectors (`extract_class`, `split_file`, `move_method`, ...). |
+| `min_confidence` | `null` | Floor: `low`, `medium`, `high`. |
+| `llm.enabled` | `false` | Code generation with chat's provider and model, only on explicit request, never in indexing. |
+
+- Code generation is the only part that calls a provider.
+- `min_confidence` applies at detection, so plans below it are never persisted
+ (like a disabled marker); changes apply on the next `init` / `update`. A
+ `min_confidence` query parameter can only narrow further.
+- Per-path disables use the `health-rules.json` glob mechanism markers use.
+ Full reference: [REFACTORING.md](../layers/REFACTORING.md).
+
+## The `assertions:` block
+
+Your own assertion helpers, for test-quality markers that divide by a test's
+assertion count.
```yaml
assertions:
extra_names: [ensureInvariant, mustMatch] # exact callee names, not prefixes
```
-Repowise recognises the xUnit and BDD families out of the box (`assert*`,
-`expect*`) plus a per-language vocabulary for the idioms those miss, such as
-Go's `t.Fatalf` and testify's `require`. A house helper that follows neither
-convention is invisible to it, and a test built entirely of those helpers reads
-as having no assertions at all. This block is the escape hatch, the same one
-SonarQube, Qodana and ESLint's `expect-expect` rule each provide.
-
-- **Names are exact and case-insensitive, never prefixes.** `ensureInvariant`
- matches `ensureInvariant(...)` and not `ensureConnectionPool(...)`. Prefix
- matching was measured against three real test corpora and matched production
- functions under test far more often than assertions.
-- A name matches whether it is the call itself or the receiver of one, so both
- `ensureInvariant(x)` and `ensureInvariant(x).isTrue()` count.
-- **Nothing here can change a health score.** These names reach only the
- advisory assertion total; the calibrated `large_assertion_block` and
- `duplicated_assertion_block` markers read a separate count that takes no
- configuration. Adding a wrong name costs you signal, never a wrong score.
-- Changing the list re-walks the affected files on the next `init` / `update`.
-
----
+Repowise knows the xUnit and BDD families (`assert*`, `expect*`) and
+per-language idioms such as Go's `t.Fatalf` and testify's `require`. A house
+helper outside those is invisible, and a test of only such helpers reads as
+assertion-free; this block is the escape hatch other test linters also offer.
+
+- Names are exact and case-insensitive, never prefixes: `ensureInvariant`
+ does not match `ensureConnectionPool`. Prefixes, measured on three real test
+ corpora, matched production functions more often than assertions.
+- A name counts as the call or as its receiver (`ensureInvariant(x).isTrue()`).
+- These names reach only the advisory assertion total; the calibrated
+ `large_assertion_block` and `duplicated_assertion_block` markers use a
+ separate count, so a wrong name costs signal, never a score.
+- Changes re-walk affected files on the next `init` / `update`.
## The `health-rules.json` file
-A separate JSON file (not part of `config.yaml`) that tunes code-health
-biomarkers: which ones run, their severity, and per-path overrides. Malformed
-JSON never raises, repowise warns and falls back to an empty config.
+A separate JSON file tuning code-health biomarkers: which run, their severity,
+and per-path overrides. Malformed JSON warns and falls back to an empty config.
```json
{
"profile": null,
"disabled_biomarkers": [],
- "severity_overrides": {
- "high_churn": "low"
- },
+ "severity_overrides": {"high_churn": "low"},
"rules": [
{
"path": "legacy/**",
"disabled_biomarkers": ["long_function"],
- "severity_overrides": {
- "duplication": "critical"
- }
+ "severity_overrides": {"duplication": "critical"}
}
]
}
```
-| Key | Default | Meaning |
-|-----|---------|---------|
-| `profile` | `null` | Named calibration profile; only `"small-team"` is defined today |
-| `disabled_biomarkers` | `[]` | Biomarker names to skip repo-wide |
-| `severity_overrides` | `{}` | Maps a biomarker name to a severity label |
-| `rules[]` | `[]` | Per-path overrides, evaluated in order |
-| `rules[].path` | required | Glob matched against the file path (aliases `path_glob` and `glob` are also accepted and treated the same) |
-| `rules[].disabled_biomarkers` | `[]` | Biomarkers to skip for files matching `path` |
-| `rules[].severity_overrides` | `{}` | Severity overrides for files matching `path` |
-
-Valid severity labels are `low`, `medium`, `high`, `critical`. Only the
-severity **label** is overridable this way, never the underlying numeric
-weights or caps that produce the health score.
-
+| Key | Default | What it does |
+|-----|---------|--------------|
+| `profile` | `null` | Calibration profile; only `"small-team"` exists. |
+| `disabled_biomarkers` | `[]` | Biomarkers skipped repo-wide. |
+| `severity_overrides` | `{}` | Biomarker name to severity label. |
+| `rules[]` | `[]` | Per-path overrides, in order. |
+| `rules[].path` | required | Gitignore-style glob (`*` stops at `/`; use `**` for nested files); aliases `path_glob`, `glob`. |
+| `rules[].disabled_biomarkers`, `rules[].severity_overrides` | `[]`, `{}` | As above, for matching files. |
+
+Labels are `low`, `medium`, `high`, `critical`; only the label is overridable,
+never the weights or caps behind the score.
Full reference: [CODE_HEALTH.md](../layers/CODE_HEALTH.md#configuration).
----
-
## LLM providers
### Anthropic (Claude)
```bash
export ANTHROPIC_API_KEY="sk-ant-..."
-```
-
-| Model | Notes |
-|-------|-------|
-| `claude-sonnet-5-5` | Best balance of quality and cost |
-| `claude-opus-5-5` | Highest quality, higher cost |
-| `claude-haiku-5-5` | Default, fastest, lowest cost |
-
-```bash
repowise init --provider anthropic --model claude-haiku-5-5
```
+Models: `claude-haiku-5-5` (default, fastest, cheapest), `claude-sonnet-5-5`
+(best balance), `claude-opus-5-5` (highest quality, higher cost).
+
### OpenAI (GPT)
```bash
@@ -825,17 +764,18 @@ export OPENAI_API_KEY="sk-..."
repowise init --provider openai --model gpt-5.6-luna
```
-For an OpenAI-compatible Qwen3 endpoint served by vLLM or SGLang:
+An OpenAI-compatible Qwen3 endpoint on vLLM or SGLang:
```bash
export OPENAI_BASE_URL="http://localhost:8000/v1"
repowise init --provider openai --model qwen3 --reasoning off
```
-The same adapter works with local gateways such as 9router and with any
-OpenAI-compatible custom provider. Set the gateway's API key under
-`OPENAI_API_KEY`, point `OPENAI_BASE_URL` at its `/v1` endpoint, and use the
-model id returned by that endpoint's `/models` response:
+The same adapter serves local gateways such as 9router and any
+OpenAI-compatible provider: the gateway key in `OPENAI_API_KEY`,
+`OPENAI_BASE_URL` at its `/v1` endpoint, and a model id from its `/models`
+(namespaced ids work as-is, no `gpt-` prefix needed). For another local
+provider, swap the key, URL and model.
```bash
export OPENAI_API_KEY="your-9router-dashboard-key"
@@ -843,16 +783,12 @@ export OPENAI_BASE_URL="http://localhost:20128/v1"
repowise init --provider openai --model ag/gemini-3.7-flash-medium
```
-Repowise discovers namespaced model ids from compatible gateways as-is, so
-the model does not need to start with `gpt-`. For another local provider,
-replace the key, URL, and model with that provider's values.
+<details><summary>Interactive gateway setup</summary>
-In an interactive `repowise init`, choose **OpenAI-compatible (Custom / local
-gateway)**. Repowise then validates the endpoint, collects the key without
-echoing it, verifies the gateway through `/models`, and lets you search the
-discovered models or enter an exact model id. If `/models` is unavailable, you
-can retry the endpoint/key, continue with a manual model id, or return to the
-provider menu:
+In interactive `repowise init`, choose **OpenAI-compatible (Custom / local
+gateway)**. Repowise validates the endpoint, takes the key without echo,
+verifies it through `/models`, and lets you search the models or type an id.
+Without `/models` you can retry, enter an id manually, or go back:
```text
Base URL [http://localhost:20128/v1]:
@@ -861,12 +797,14 @@ API key (hidden): <paste the gateway key>
Select model: ag/gemini-3.7-flash-medium
```
-The endpoint is placed in the repo's gitignored `.repowise/.env`; the key is
-saved there only after confirmation, and `--no-save-key` always keeps it
-process-local. The selected runtime provider (`openai`) and exact model id are
-written to `config.yaml`. Choose the separate **openai** row for the official
-OpenAI endpoint. Scripted runs (`--yes`, CI, or non-TTY) remain non-interactive
-and should continue to use environment variables and `--provider openai`.
+- The endpoint goes in the gitignored `.repowise/.env`; the key only after
+ confirmation, never with `--no-save-key`.
+- `config.yaml` gets `provider: openai` and the exact model id.
+- The separate **openai** row is the official endpoint.
+- Scripted runs (`--yes`, CI, non-TTY) stay non-interactive: use environment
+ variables and `--provider openai`.
+
+</details>
### OpenRouter
@@ -883,7 +821,7 @@ export GEMINI_API_KEY="AI..." # or GOOGLE_API_KEY
repowise init --provider gemini
```
-Gemini is also the default embedding provider when `GEMINI_API_KEY` is set.
+With `GEMINI_API_KEY` set, Gemini is also the default embedder.
### DeepSeek
@@ -899,22 +837,16 @@ export KIMI_API_KEY="..."
repowise init --provider kimi --model kimi-for-coding
```
-The default Kimi Code endpoint supports `kimi-for-coding` and
-`kimi-for-coding-highspeed`. Repowise automatically uses their required
-sampling parameters.
-
-K2.x models use the separate Kimi Open Platform. Supply a key from that
-platform together with its OpenAI-compatible endpoint:
+The default Kimi Code endpoint serves `kimi-for-coding` and
+`kimi-for-coding-highspeed`. K2.x models need a Kimi Open Platform key and its
+OpenAI-compatible endpoint. Repowise sets the required sampling parameters for
+both, including K2.x thinking or instant mode.
```bash
-export KIMI_API_KEY="..."
export KIMI_BASE_URL="https://api.moonshot.ai/v1"
repowise init --provider kimi --model kimi-k2.6
```
-For K2.x models, Repowise selects the required sampling parameters for
-thinking or instant mode.
-
### Ollama (local, no API key)
```bash
@@ -922,11 +854,10 @@ export OLLAMA_BASE_URL="http://localhost:11434"
repowise init --provider ollama --model llama3.2
```
-Repowise sizes the model's context window (`num_ctx`) to each prompt, so pages
-are not cut to Ollama's small default window. Set `REPOWISE_OLLAMA_NUM_CTX` to
-pin it instead, for example to stay within a machine's memory. Requests are sent
-one at a time; if the server runs with `OLLAMA_NUM_PARALLEL` above 1, set the
-same value where you run repowise to send that many at once.
+- `num_ctx` is sized to each prompt, so pages are not cut to Ollama's small
+ default; `REPOWISE_OLLAMA_NUM_CTX` pins it (e.g. to fit memory).
+- Requests go one at a time; with server `OLLAMA_NUM_PARALLEL` above 1, set the
+ same value where Repowise runs.
### LiteLLM (100+ providers)
@@ -938,54 +869,35 @@ repowise init --provider litellm --model azure/gpt-4
### Eden AI (hosted, with an EU endpoint)
[Eden AI](https://www.edenai.co/) is a hosted gateway with an EU endpoint, so
-inference can stay in the EU without self-hosting anything. That is the reason to
-reach for it here: every other hosted provider in this list terminates in the US,
-and the alternatives for a team working under a DPA are Ollama or LiteLLM on your
-own infrastructure.
-
-Point at the EU endpoint with `EDENAI_BASE_URL`. It covers the embedder as well,
-since both read the same variable:
+inference stays in the EU without self-hosting. Every other hosted provider
+here terminates in the US; under a DPA the alternatives are Ollama or LiteLLM
+on your own infrastructure. `EDENAI_BASE_URL` selects the EU endpoint for the
+LLM and the embedder; without it, requests use the global endpoint.
```bash
export EDENAI_API_KEY="..."
export EDENAI_BASE_URL="https://api.eu.edenai.run/v3"
repowise init --provider edenai --model mistral/mistral-small-latest
-```
-
-Without that variable, requests go to the global endpoint:
-
-```bash
-export EDENAI_API_KEY="..."
repowise init --provider edenai --model openai/gpt-5-mini --reasoning low
```
-Beyond residency it is also an aggregator: one key reaches many vendors (Mistral,
-GPT, Claude, Gemini, Cohere, DeepSeek, Llama) through a single
-OpenAI-compatible endpoint, with models addressed as `vendor/model`. The live
-catalogue is public and needs no authentication at
-<https://api.edenai.run/v3/models>, with the embedding models at
-<https://api.edenai.run/v3/embeddings/models>.
-
-The same key also selects `edenai` as the embedder for semantic search. Its
-default is `amazon/amazon.titan-embed-text-v2:0`, chosen because it is served
-from an EU region and is the cheapest per token of the models this adapter
-declares. Pick another with `REPOWISE_EMBEDDING_MODEL`:
-
-```bash
-export REPOWISE_EMBEDDING_MODEL="google/gemini-embedding-001"
-```
-
-Only the models in `EdenAIEmbedder._DIMS` are accepted, because a wrong
-dimension count would silently mis-size stored vectors. Adding one means adding
-its measured width to that table.
-
-`reasoning` is forwarded as OpenAI `reasoning_effort` for OpenAI reasoning models
-routed through Eden (e.g. `openai/gpt-5*`); other models expose only `auto`.
+- One key reaches many vendors (Mistral, GPT, Claude, Gemini, Cohere,
+ DeepSeek, Llama) through one OpenAI-compatible endpoint, as `vendor/model`.
+- Public catalogue, no auth: <https://api.edenai.run/v3/models>; embedding
+ models: <https://api.edenai.run/v3/embeddings/models>.
+- `reasoning` maps to OpenAI `reasoning_effort` for OpenAI reasoning models
+ (e.g. `openai/gpt-5*`); other models accept only `auto`.
+- The key also selects the `edenai` embedder, default
+ `amazon/amazon.titan-embed-text-v2:0` (EU-served, cheapest per token here).
+ Change it with `REPOWISE_EMBEDDING_MODEL`, e.g.
+ `google/gemini-embedding-001`.
+- Only models in `EdenAIEmbedder._DIMS` are accepted, since a wrong width
+ silently mis-sizes stored vectors; adding one means adding its measured width.
### Provider auto-detection
The CLI, `repowise serve` chat and jobs, and the MCP server resolve provider,
-model, and base URL the same way, first match wins:
+model and base URL the same way; first match wins:
1. `--provider` / `--model` flags, or a per-request choice in the web UI
2. `provider`, `model`, and `<provider>: {base_url: ...}` in `.repowise/config.yaml`
@@ -993,17 +905,14 @@ model, and base URL the same way, first match wins:
4. `REPOWISE_PROVIDER` / `REPOWISE_MODEL` and the provider's `*_BASE_URL` variable
5. API key env vars: `ANTHROPIC_API_KEY` → `OPENAI_API_KEY` → `OPENROUTER_API_KEY` → `OLLAMA_BASE_URL` → `GEMINI_API_KEY` → `DEEPSEEK_API_KEY` → `KIMI_API_KEY` → `EDENAI_API_KEY`
-Picking a model in the web UI for a repo writes it to that repo's `config.yaml`,
-so the CLI uses it too. A local OpenAI-compatible server such as LM Studio works
-as `provider: openai` with `openai: {base_url: http://localhost:1234/v1}`.
-Because `config.yaml` may be committed, a non-local base URL there only receives a key
-that is not in the repo's `.repowise/.env` after you confirm it in Settings or with `repowise init`.
-You can set all of this from the repo's Settings page instead of editing the
-file: the model field lists the provider's live models and takes any id, and
-Test connection checks a base URL before you save it. A loopback base URL needs
-no API key.
-
----
+- A model picked in the web UI is written to the repo's `config.yaml`, so the
+ CLI uses it too.
+- A local OpenAI-compatible server such as LM Studio: `provider: openai` with
+ `openai: {base_url: http://localhost:1234/v1}`. Loopback URLs need no key.
+- Since `config.yaml` may be committed, a non-local base URL there gets a key
+ not in `.repowise/.env` only after you confirm in Settings or `repowise init`.
+- The repo's Settings page sets all this: the model field lists live models
+ and takes any id, and Test connection checks a base URL before saving.
## Embeddings (for semantic search)
@@ -1011,54 +920,41 @@ The embedder is separate from the LLM provider.
| Embedder | Env var | Notes |
|----------|---------|-------|
-| `gemini` | `GEMINI_API_KEY` (or `GOOGLE_API_KEY`) | Default when key is present |
-| `openai` | `OPENAI_API_KEY` | OpenAI `text-embedding-3-small` |
+| `gemini` | `GEMINI_API_KEY` (or `GOOGLE_API_KEY`) | Default when the key is present |
+| `openai` | `OPENAI_API_KEY` | `text-embedding-3-small` |
| `openrouter` | `OPENROUTER_API_KEY` | Routed through OpenRouter |
-| `ollama` | `OLLAMA_EMBEDDING_MODEL` | Local Ollama embeddings, no API key |
-| `edenai` | `EDENAI_API_KEY` | Eden AI gateway, see [Eden AI](#eden-ai-hosted-with-an-eu-endpoint) |
-| `mock` | n/a | Dummy embeddings, no semantic search (default when no key is detected) |
-
-Which embedder a run uses, first match wins: `--embedder`, then
-`REPOWISE_EMBEDDER`, then the `embedder` pin in `.repowise/config.yaml`, then
-the first key present in the order gemini, openai, openrouter, ollama, edenai,
-then `embedder` in `~/.repowise/config.yaml`, then `mock`. `reindex` skips a
-`mock` pin when a real embedder can be found.
+| `ollama` | `OLLAMA_EMBEDDING_MODEL` | Local, no API key |
+| `edenai` | `EDENAI_API_KEY` | See [Eden AI](#eden-ai-hosted-with-an-eu-endpoint) |
+| `mock` | n/a | No semantic search; default when no key is found |
```bash
repowise init --embedder openai
repowise reindex --embedder gemini # switch embedder and rebuild index
```
-The `embedder` key in `config.yaml` is the record of what built the vector
-store, so it is what both writers and readers use. `search`, `serve`, and the
-MCP server resolve it from there first and only fall back to the environment
-when nothing is pinned; otherwise a repo indexed without a key would be queried
-with whatever API key happened to be exported, and the wider query vectors
-would match nothing in the narrower stored table.
-
-`reindex` writes the embedder it used back to `config.yaml`. Without that, the
-next `update` would read the old pin, write vectors at the old width, and the
-store would be rebuilt from scratch, discarding what the reindex just built.
-
-`REPOWISE_EMBEDDING_MODEL` overrides the model for whichever embedder is
-active. `REPOWISE_EMBEDDING_DIMS` and `REPOWISE_EMBEDDING_TIMEOUT` apply the
-same way; the provider-prefixed variants below (`OPENAI_*`, `GEMINI_*`,
-`OLLAMA_*`, `OPENROUTER_*`, `EDENAI_*`) narrow a setting to one embedder and take
-precedence over the shared name.
-
----
+Resolution, first match wins: `--embedder`, `REPOWISE_EMBEDDER`, the
+`embedder` pin in `.repowise/config.yaml`, the first key present (gemini,
+openai, openrouter, ollama, edenai), `embedder` in `~/.repowise/config.yaml`,
+then `mock`. `reindex` skips a `mock` pin when a real embedder is found.
+
+- The pin records what built the vector store. `search`, `serve` and MCP read
+ it first and use the environment only when unpinned; otherwise a keyless
+ index would be queried with whatever key is exported, and wider query vectors
+ would match nothing in the narrower table.
+- `reindex` writes its embedder back to the pin; otherwise the next `update`
+ would write old-width vectors and rebuild the store, discarding the reindex.
+- `REPOWISE_EMBEDDING_MODEL`, `REPOWISE_EMBEDDING_DIMS` and
+ `REPOWISE_EMBEDDING_TIMEOUT` apply to the active embedder; [provider-prefixed
+ variants](#embeddings) take precedence for theirs.
## BYOK (Bring Your Own Key)
-API keys are resolved in this order:
+Keys resolve in order:
-1. **Environment variable**: set before running repowise
-2. **`.repowise/.env`**: persisted from interactive setup, loaded automatically
-3. **Interactive prompt**: repowise asks during `init` if no key is found, then saves to `.repowise/.env`
-
-The `.repowise/.env` file is gitignored automatically.
-
----
+1. **Environment variable**
+2. **`.repowise/.env`**: saved by interactive setup, loaded automatically, gitignored
+3. **`~/.repowise/provider_config.json`**: keys saved from the web UI
+4. **Interactive prompt** during `init`, saved to `.repowise/.env`
## Environment variables
@@ -1066,12 +962,12 @@ The `.repowise/.env` file is gitignored automatically.
| Variable | Description |
|----------|-------------|
-| `ANTHROPIC_API_KEY` | Anthropic API key |
-| `OPENAI_API_KEY` | OpenAI or OpenAI-compatible gateway API key |
-| `GEMINI_API_KEY` / `GOOGLE_API_KEY` | Google Gemini API key |
-| `OPENROUTER_API_KEY` | OpenRouter API key |
-| `DEEPSEEK_API_KEY` | DeepSeek API key |
-| `KIMI_API_KEY` | Kimi API key |
+| `ANTHROPIC_API_KEY` | Anthropic |
+| `OPENAI_API_KEY` | OpenAI or an OpenAI-compatible gateway |
+| `GEMINI_API_KEY` / `GOOGLE_API_KEY` | Google Gemini |
+| `OPENROUTER_API_KEY` | OpenRouter |
+| `DEEPSEEK_API_KEY` | DeepSeek |
+| `KIMI_API_KEY` | Kimi |
| `LITELLM_API_KEY` | LiteLLM proxy key |
| `LITELLM_API_BASE` | LiteLLM proxy base URL |
@@ -1079,146 +975,139 @@ The `.repowise/.env` file is gitignored automatically.
| Variable | Description |
|----------|-------------|
-| `ANTHROPIC_BASE_URL` | Override the Anthropic API base URL |
-| `OPENAI_BASE_URL` | Override the OpenAI API base URL (used for vLLM/SGLang, 9router, and other compatible endpoints) |
-| `GEMINI_BASE_URL` | Override the Gemini API base URL |
-| `OLLAMA_BASE_URL` | Ollama server URL (default: `http://localhost:11434`) |
-| `REPOWISE_OLLAMA_NUM_CTX` | Fixed Ollama context window; unset sizes it to each prompt |
-| `OLLAMA_NUM_PARALLEL` | Ollama requests repowise sends at once (default: 1) |
-| `DEEPSEEK_BASE_URL` | Override the DeepSeek API base URL |
-| `KIMI_BASE_URL` | Override the Kimi API base URL |
-| `LITELLM_BASE_URL` | Override the LiteLLM proxy base URL |
+| `ANTHROPIC_BASE_URL`, `GEMINI_BASE_URL`, `DEEPSEEK_BASE_URL`, `KIMI_BASE_URL`, `LITELLM_BASE_URL` | Override that provider's API base URL |
+| `OPENAI_BASE_URL` | Override the OpenAI base URL (vLLM/SGLang, 9router, other compatible endpoints) |
+| `OLLAMA_BASE_URL` | Ollama server (default `http://localhost:11434`) |
+| `REPOWISE_OLLAMA_NUM_CTX` | Fixed Ollama context window; unset sizes it per prompt |
+| `OLLAMA_NUM_PARALLEL` | Ollama requests sent at once (default 1) |
### Provider and model overrides
| Variable | Description |
|----------|-------------|
-| `REPOWISE_PROVIDER` | Provider when neither a flag nor `config.yaml` names one (skips auto-detection) |
-| `REPOWISE_MODEL` | Model when neither a flag nor `config.yaml` names one |
-| `REPOWISE_DOC_MODEL` | Override the model used for `get_answer` synthesis specifically |
-| `REPOWISE_REASONING` | Override `reasoning` (see valid values above) |
-| `REPOWISE_ANSWER_TIMEOUT_S` | Seconds `get_answer` waits for synthesis before giving up. Defaults to a per-provider budget: 60s for the remote API providers, 120s for `ollama` and `litellm`, 180s for `codex_cli` and `opencode`. Raise it if your model is slower than its class suggests, lower it if you would rather an agent fail fast than block. Capped at 600s. Note your MCP client enforces its own tool timeout underneath this one, so setting a value above it produces a client-side error instead of repowise's diagnosable "synthesis exceeded its budget" response |
+| `REPOWISE_PROVIDER` | Provider when no flag or `config.yaml` names one (skips auto-detection) |
+| `REPOWISE_MODEL` | Model when no flag or `config.yaml` names one |
+| `REPOWISE_DOC_MODEL` | Model for `get_answer` synthesis only |
+| `REPOWISE_REASONING` | Overrides [`reasoning`](#reasoning) |
+| `REPOWISE_ANSWER_TIMEOUT_S` | Seconds `get_answer` waits for synthesis, capped at 600 |
+
+`REPOWISE_ANSWER_TIMEOUT_S` defaults to 60s for remote API providers, 120s
+for `ollama` and `litellm`, and 180s for agent CLI providers (`claude_cli`,
+`codex_cli`, `copilot_cli`, `opencode`). Raise it for a slow model, lower it to
+fail fast. Your MCP client's own tool timeout sits underneath: a higher value
+yields a client error instead of Repowise's "synthesis exceeded its budget".
### Embeddings
| Variable | Description |
|----------|-------------|
-| `REPOWISE_EMBEDDER` | Embedder: `gemini`, `openai`, `ollama`, `openrouter`, `edenai`, or `mock` |
-| `REPOWISE_EMBEDDING_MODEL` | Embedding model, applies to any embedder |
-| `REPOWISE_EMBEDDING_DIMS` | Embedding output dimensions (optional; inferred from the model otherwise) |
-| `REPOWISE_EMBEDDING_TIMEOUT` | Embed request timeout in seconds (default: `30` for `ollama`, `10` elsewhere). Raise it for a local endpoint — one request embeds a whole batch, and an expired batch is reported only as `N/N items failed to embed`. An unparseable value warns and keeps the default |
-| `REPOWISE_VECTOR_SEARCH_TIMEOUT_S` | Seconds one vector-store query may take (default: `30`, capped at `120`). The first query in a process pays for the store open, the first embed and the first ANN probe, which can run past 13s on a cold index where a warm query takes under a second. Raise it on a slow disk or a very large wiki; a timeout drops the semantic leg and logs a warning, leaving full-text hits only. An unparseable value warns and keeps the default |
-| `OPENAI_EMBEDDING_TIMEOUT` | As above, `openai` only; takes precedence over the shared variable |
-| `GEMINI_EMBEDDING_TIMEOUT` | As above, `gemini` only |
-| `OPENROUTER_EMBEDDING_TIMEOUT` | As above, `openrouter` only |
-| `EDENAI_EMBEDDING_TIMEOUT` | As above, `edenai` only |
-| `OLLAMA_EMBEDDING_MODEL` | Ollama embedding model (also selects the `ollama` embedder) |
-| `OLLAMA_EMBEDDING_DIMS` | Ollama embedding output dimensions (optional; inferred from the model otherwise) |
-| `OLLAMA_EMBEDDING_TIMEOUT` | As above, `ollama` only. With neither variable set, an Ollama request gets 30s plus 2ms per input character, so a full chunk of long pages on a CPU-only model is not cut off. Setting either variable pins the timeout to that value |
+| `REPOWISE_EMBEDDER` | `gemini`, `openai`, `ollama`, `openrouter`, `edenai` or `mock` |
+| `REPOWISE_EMBEDDING_MODEL` | Embedding model for any embedder |
+| `REPOWISE_EMBEDDING_DIMS` | Output dimensions (optional; inferred from the model) |
+| `REPOWISE_EMBEDDING_TIMEOUT` | Embed request timeout, seconds (default `30` for `ollama`, `10` elsewhere) |
+| `OPENAI_`, `GEMINI_`, `OPENROUTER_`, `EDENAI_`, `OLLAMA_EMBEDDING_TIMEOUT` | That embedder only; wins over the shared variable |
+| `REPOWISE_VECTOR_SEARCH_TIMEOUT_S` | Seconds per vector-store query (default `30`, capped at `120`) |
+| `OLLAMA_EMBEDDING_MODEL` | Ollama embedding model; also selects the `ollama` embedder |
+| `OLLAMA_EMBEDDING_DIMS` | Ollama output dimensions (optional; inferred from the model) |
+
+- Raise the embed timeout for a local endpoint: one request embeds a whole
+ batch, and an expired batch shows only as `N/N items failed to embed`.
+- With no Ollama or shared timeout set, an Ollama request gets 30s plus 2ms
+ per input character, so long pages on a CPU-only model are not cut off.
+- A cold first vector query pays for the store open, first embed and first ANN
+ probe (past 13s where a warm query takes under a second). Raise the timeout
+ on a slow disk or large wiki; a timeout drops the semantic leg with a
+ warning, leaving full-text hits.
+- An unparseable timeout warns and keeps the default.
### Server and database
| Variable | Description |
|----------|-------------|
-| `REPOWISE_DB_URL` | Use PostgreSQL instead of SQLite (e.g. `postgresql+asyncpg://...`) |
+| `REPOWISE_DB_URL` | PostgreSQL instead of SQLite (e.g. `postgresql+asyncpg://...`) |
| `REPOWISE_DATABASE_URL` | Legacy alias for `REPOWISE_DB_URL`, still honored |
-| `REPOWISE_HOST` | API server host (default: `127.0.0.1`) |
-| `REPOWISE_PORT` | API server port (default: `7337`) |
-| `REPOWISE_MCP_PORT` | MCP SSE server port (default: `7338`) |
-| `REPOWISE_API_URL` | Frontend only; backend URL for the web UI (default: `http://localhost:7337`) |
-| `REPOWISE_API_KEY` | Bearer token required by clients calling the server API. Without it the server answers local callers only, and refuses any request from another host with 403 |
-| `REPOWISE_CONFIG_DIR` | Override where repowise looks for its config directory |
-| `REPOWISE_GITHUB_WEBHOOK_SECRET` | Secret for verifying GitHub webhook signatures |
-| `REPOWISE_GITLAB_WEBHOOK_TOKEN` | Token for verifying GitLab webhook requests |
+| `REPOWISE_HOST` | Default host for `repowise mcp` over HTTP/SSE (`127.0.0.1`); `repowise serve` sets it from `--host` |
+| `REPOWISE_PORT` | API server port (default `7337`) |
+| `REPOWISE_API_URL` | Frontend only: backend URL for the web UI (default `http://localhost:7337`) |
+| `REPOWISE_API_KEY` | Bearer token for API clients; without it the server answers local callers only and refuses other hosts with 403 |
+| `REPOWISE_CONFIG_DIR` | Where Repowise looks for its config directory |
+| `REPOWISE_GITHUB_WEBHOOK_SECRET` | Verifies GitHub webhook signatures |
+| `REPOWISE_GITLAB_WEBHOOK_TOKEN` | Verifies GitLab webhook requests |
+
+The MCP SSE port is the `repowise mcp --port` flag (default `7338`).
### Telemetry
-Anonymous usage telemetry is **enabled by default** (opt-out).
+Anonymous usage telemetry is **on by default** (opt-out).
| Variable | Description |
|----------|-------------|
-| `DO_NOT_TRACK` | Any truthy value disables telemetry (respects the cross-tool convention) |
-| `REPOWISE_TELEMETRY_DISABLED` | Disables telemetry, repowise-specific |
-| `REPOWISE_TELEMETRY_DEBUG` | Prints the telemetry payload to stderr instead of sending it |
+| `DO_NOT_TRACK` | Any truthy value disables it (cross-tool convention) |
+| `REPOWISE_TELEMETRY_DISABLED` | Disables it, Repowise-specific |
+| `REPOWISE_TELEMETRY_DEBUG` | Prints the payload to stderr instead of sending |
### Misc
| Variable | Description |
|----------|-------------|
-| `REPOWISE_GIT_WINDOW_ANCHOR` | Git history windows (90-day churn, prior defects, decay, blame age) are measured from the indexed commit's committer date by default. Set to `now` to measure them from wall-clock time instead |
-| `REPOWISE_SKIP_EDITOR_SETUP` | Truthy value stops `init` writing to your machine-wide editor config: the Claude Code / Claude Desktop MCP entry, the Claude Code hooks, and the distill rewrite-hook offer. Same switch as `init --no-editor-setup` ([CLI_REFERENCE.md](CLI_REFERENCE.md#repowise-init-path)); the env var is the one to use for CI, sandboxes, and benchmark runs that index many repos. Project-local files (`.repowise/mcp.json`, `CLAUDE.md`, Codex config) are written either way |
-| `REPOWISE_FORGE_HOSTS` | Self-managed git hosts as `host=forge` pairs separated by commas (`git.corp.com=gitlab,tfs.corp.com=azure`). Wins over `forges.hosts` in `config.yaml` |
-| `REPOWISE_CHANGELOG` | Override the changelog source used by the "what's new" check |
-| `REPOWISE_PARSE_WORKERS` | How many processes parse files during indexing. Defaults to your CPU count capped at 8, and never exceeds the number of files to parse. Each worker is a separate interpreter holding roughly 50 MB, so lower it on a memory-constrained machine; raising it above 8 is not measurably faster |
-
----
+| `REPOWISE_GIT_WINDOW_ANCHOR` | `now` measures git windows (90-day churn, prior defects, decay, blame age) from wall-clock time instead of the indexed commit's committer date |
+| `REPOWISE_SKIP_EDITOR_SETUP` | Truthy: `init` skips machine-wide editor config (Claude Code / Claude Desktop MCP entry, Claude Code hooks, distill rewrite-hook offer), like `init --no-editor-setup` ([CLI_REFERENCE.md](CLI_REFERENCE.md#repowise-init-path)); use it for CI, sandboxes and benchmark runs. Project files (`.repowise/mcp.json`, `CLAUDE.md`, Codex config) are still written |
+| `REPOWISE_FORGE_HOSTS` | `host=forge` pairs, comma separated (`git.corp.com=gitlab,tfs.corp.com=azure`); wins over `forges.hosts` |
+| `REPOWISE_CHANGELOG` | Changelog source for the "what's new" check |
+| `REPOWISE_PARSE_WORKERS` | Indexing parse processes: default CPU count capped at 8, never above the files to parse. Each holds about 50 MB; above 8 is not measurably faster |
## Exclude patterns
-repowise respects your `.gitignore` automatically (same `gitwildmatch` format git
-uses). Like git, it reads **nested `.gitignore` files** too, so a `.gitignore` in
-any subdirectory applies to that directory's contents. This matters for
-monorepos and yarn/npm workspaces, where a package keeps its own `.gitignore`
-excluding that package's build output (e.g. `dist/`, `coverage/`, generated
-bundles), so those exclusions are now honoured without duplicating them at the
-repo root.
-
-On top of that, add extra patterns via `--exclude` / `-x`:
+Repowise honours `.gitignore` (git's `gitwildmatch` format), including nested
+`.gitignore` files, so a monorepo or workspace package's own build exclusions
+(`dist/`, `coverage/`, generated bundles) apply without repeating them at the
+root.
```bash
repowise init -x vendor/ -x "*.generated.ts" -x proto/ -x "**/*.pb.go"
```
-Patterns are saved to `config.yaml` (`exclude_patterns`) and applied on
-subsequent `update` runs. You can also create a `.repowiseIgnore` file (same
-gitignore syntax) at the repo root or in any subdirectory for more granular
-control without touching `.gitignore`.
-
-Built-in exclusions (always applied): `.git/`, `.repowise/`, `node_modules/`,
-`__pycache__/`, `*.pyc`, `.venv/`, binary files, lockfiles, and minified assets.
-
-`--skip-tests` excludes test files and `--skip-infra` excludes Dockerfiles,
-Makefiles, and shell scripts. Both are CLI-flag-only for the run they're
-passed on; they aren't written to `config.yaml`, so pass them again on
-subsequent `init`/`update` calls if you want the same exclusions.
-
----
+- `--exclude` / `-x` patterns are saved to `exclude_patterns` and reused by
+ `update`.
+- A `.repowiseIgnore` file (gitignore syntax) at the root or in any
+ subdirectory excludes without touching `.gitignore`.
+- Always excluded: `.git/`, `.repowise/`, `node_modules/`, `__pycache__/`,
+ `*.pyc`, `.venv/`, binary files, lockfiles, minified assets.
+- `--skip-tests` (test files) and `--skip-infra` (Dockerfiles, Makefiles,
+ shell scripts) apply only to their run; pass them again each time.
## Submodules
-Git submodule directories are excluded by default. To include them:
+Submodule directories are excluded by default; Repowise finds them in
+`.gitmodules`.
```bash
repowise init --include-submodules
```
-repowise reads `.gitmodules` to detect submodule paths. This flag isn't
-written to `config.yaml`; for a workspace, the choice is recorded in
-`state.json` instead.
-
----
+The flag is not written to `config.yaml`; a workspace records it in
+`state.json`.
## PostgreSQL
-For team deployments or larger repos, use PostgreSQL instead of SQLite:
+For team deployments or larger repos:
```bash
export REPOWISE_DB_URL="postgresql+asyncpg://user:pass@localhost:5432/repowise"
repowise init
```
-`REPOWISE_DATABASE_URL` is a legacy alias for `REPOWISE_DB_URL` and is still
-honored. The schema is managed with Alembic migrations.
-
----
+`REPOWISE_DATABASE_URL` is a still-honored alias. Alembic manages the schema.
## Workspace config (`.repowise-workspace.yaml`)
-A multi-repo [workspace](../scale/WORKSPACES.md) is configured by a `.repowise-workspace.yaml` at the workspace root. Alongside the repo list it carries two optional blocks.
+A multi-repo [workspace](../scale/WORKSPACES.md) is configured at its root.
+Beside the repo list it takes `repos[].tags`, `conformance:`, and a
+`contracts:` block that tunes cross-repo contract detection.
### `repos[].tags`
-Each repo entry may declare free-form `tags` used to group services in conformance rules:
+Free-form tags that group services in conformance rules:
```yaml
repos:
@@ -1232,35 +1121,35 @@ repos:
### The `conformance:` block
-Declares architecture conformance rules (allow/deny dependency rules) checked by `repowise workspace check` and the workspace Conformance view. See [Architecture Conformance](../scale/WORKSPACES.md#architecture-conformance).
+Allow/deny dependency rules checked by `repowise workspace check` and the
+Conformance view ([Architecture Conformance](../scale/WORKSPACES.md#architecture-conformance)).
```yaml
conformance:
rules:
- - source: frontend # matcher: a glob over node id / repo / name
- target: db # matcher
- allow: false # optional, default false (deny). true = exception
- description: "..." # optional, shown in reports
- - source: "tag:ui" # matcher: tag:<name> (repos carrying that tag)
+ - source: frontend
+ target: db
+ allow: false
+ description: "..."
+ - source: "tag:ui"
target: "tag:data"
- - source: "*" # matcher: * (any service)
+ - source: "*"
target: legacy-payments
```
-| Field | Type | Default | Meaning |
-|-------|------|---------|---------|
-| `source` | string (matcher) | required | The dependent side. `*`, `tag:<name>`, or a glob over node id / repo alias / display name |
-| `target` | string (matcher) | required | The depended-upon side (same matcher forms) |
-| `allow` | bool | `false` | `false` = deny (a matching dependency is a violation); `true` = whitelist an otherwise-denied edge |
-| `description` | string | `""` | Human-readable rationale, surfaced in reports |
-
-Rules are evaluated only against structural edges (HTTP, gRPC, event, package, db); behavioral co-change is never treated as a dependency.
+| Field | Default | Meaning |
+|-------|---------|---------|
+| `source` | required | Dependent side: `*` (any service), `tag:<name>` (repos with that tag), or a glob over node id / repo alias / display name |
+| `target` | required | Depended-upon side, same forms |
+| `allow` | `false` | `false` denies (a match is a violation); `true` whitelists an otherwise-denied edge |
+| `description` | `""` | Rationale shown in reports |
----
+Rules apply only to structural edges (HTTP, gRPC, socket, event, package, db),
+never to behavioral co-change.
## Deprecated / legacy aliases
| Old name | Current name | Notes |
|----------|--------------|-------|
-| `max_pages_pct` | `coverage_pct` | Internal alias, still read for backward compatibility |
+| `max_pages_pct` | `coverage_pct` | Internal alias, still read |
| `REPOWISE_DATABASE_URL` | `REPOWISE_DB_URL` | Still honored |
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index d8cc1fd07..a2fee847c 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -1,6 +1,6 @@
# MCP Response Fields
-The field dictionary for every repowise MCP tool response. [MCP_TOOLS.md](../agent/MCP_TOOLS.md) says which tool to call and with what arguments; this page says what comes back and how to read it.
+The field dictionary for every repowise MCP tool response. [MCP_TOOLS.md](../agent/MCP_TOOLS.md) says which tool to call and with what arguments; this page says what comes back.
## Contents
@@ -16,51 +16,64 @@ The field dictionary for every repowise MCP tool response. [MCP_TOOLS.md](../age
## The `_meta` envelope
-Every response carries `_meta`. Fields are present only when they carry a signal, so read absence as "nothing to report", never as an error.
+Every response carries `_meta`. A field is present only when it carries a signal; absence means "nothing to report", never an error.
-Routine responses carry a lean envelope. `get_overview`, called once per session, keeps the full one: `contract_version`, `timing_ms`, `response_budget` and `completeness` on every call. Its `index_scope` is the same digest as elsewhere (left out when `complete`); `include=["scope"]` adds the whole object. Setting `REPOWISE_MCP_DEBUG_META=1` in the server's environment restores the diagnostic fields on every tool (`contract_version`, `timing_ms`, `response_budget`, `completeness`, `tokens_saved`, `replaced_tokens`) for diagnosis; it is read per call, so no restart is needed.
+Routine responses carry a lean envelope. `get_overview` (called once per session) always carries `contract_version`, `timing_ms`, `response_budget` and `completeness`. `REPOWISE_MCP_DEBUG_META=1` restores those plus `tokens_saved` and `replaced_tokens` on every tool; it is read per call, so no restart is needed.
| Field | When present | Meaning |
|-------|--------------|---------|
-| `contract_version` | `get_overview`, or with `REPOWISE_MCP_DEBUG_META=1` | Version of the response contract (currently 3). It stays the version of record for wire-shape changes even when not emitted |
-| `timing_ms` | `get_overview`, or with `REPOWISE_MCP_DEBUG_META=1` | Tool wall time |
-| `hint` | Sometimes | A short follow-up suggestion. On a `get_answer` reply graded `low` while the index is behind HEAD, it says to run `repowise update` and ask again |
+| `contract_version` | `get_overview`, or debug meta | Response contract version (currently 3); the version of record even when not emitted |
+| `timing_ms` | `get_overview`, or debug meta | Tool wall time |
+| `hint` | Sometimes | A short follow-up suggestion |
| `cached` | Only when `true` | The response came from cache |
-| `index_age_days` | When a repository is resolved | Days since the last `repowise update` |
-| `indexed_commit` | When a repository is resolved | Short SHA the index was built from |
-| `live_head` | When `.git/HEAD` is readable | Short SHA of the current checkout; equal to `indexed_commit` when current |
-| `index_behind` | When the live-versus-indexed comparison ran | `true` if HEAD moved, `false` if it matches. Absent means the comparison could not run |
-| `stale_warning` | Only on a real signal | HEAD moved and the move changed files this response serves, a file this response serves has uncommitted edits the index has not seen or was indexed from uncommitted edits since reverted, or the index is very old and git is unreachable. Two commits with identical trees set `index_behind` with no warning |
-| `working_tree_dirty` | Only when above zero | How many served targets have uncommitted edits no `repowise update --working-tree` has indexed. Source reads are live; graph and index facts for those files predate the edit. A dirty tree elsewhere never sets it |
-| `index_scope` | When the index records it and its `status` is not `complete` (whole object on `get_overview(include=["scope"])`, or everywhere with `REPOWISE_MCP_INDEX_SCOPE=full`) | Compact description of how the index was built: run mode, provenance, git tier, whether it is whole |
-| `embedder_degraded` | When an embedder is resolved | `true` or `false` |
-| `embedder`, `embedder_warning` | Only when the embedder fell back to a mock or degraded mode, or the semantic index on disk could not be opened | Which embedder, and why |
-| `newer_release` | Once per server process | A newer repowise is published; restart the MCP server after upgrading |
-| `keyless_note` | Once per server process, on the first `get_answer` reply that degrades with `no-llm-provider` | Names what a model would add: `repowise generate` writes synthesized answers with a model (needs a key, or `--provider ollama` for a local model). Not repeated on later replies, and never sent when a provider is configured |
-| `response_budget` | When the budget cut something or could not fit the protected fields (`enforcement_error`); always on `get_overview` | `limit_chars` (the ceiling), `tier` (`default` or `expanded`), `serialized_chars` (size delivered) |
-| `omitted` | When content was cut | `refs`, `tokens`, `restore`. See [Truncation and recovery](#truncation-and-recovery) |
-| `recovery_unavailable` | When the omission store could not be written | Names the storage failure; the cut rows cannot be restored |
-| `scope_hint` | `get_answer` | Up to three knowledge-graph layers holding none of the served paths, with file counts: areas the answer did not touch |
-| `complete` | When whole units were served | Symbol bodies (bounds verified against the live file) or whole files. Do not re-read them. Sliced bodies and partial ranges are never counted |
-| `completeness` | When something was capped; always on `get_overview` | `capped`, plus `shown` and `total` summed over the collections a reducing pass counted, and `reason` naming the pass that dropped most. It measures what survived reduction, not what share of the repository you hold |
-| `floor` | When a count comes from walking the graph | Names those fields. Their values are lower bounds: an unresolved edge is uncounted, not proven absent |
-| `state` | Only when something fired | `degraded` with `degraded_reasons`, `partial`, `truncated`. A roll-up of the response's own flags |
-
-`list_repos`, `get_architecture`, `get_blast_radius`, `get_conformance` and `get_dependency_path` carry no freshness fields. Neither does a workspace-wide `repo="all"` call, since there is no single indexed commit to compare; it names stale repos in a top-level `repos_stale` instead.
+| `index_age_days` | A repository is resolved | Days since the last `repowise update` |
+| `indexed_commit` | A repository is resolved | Short SHA the index was built from |
+| `live_head` | `.git/HEAD` is readable | Short SHA of the checkout; equals `indexed_commit` when current |
+| `index_behind` | The comparison ran | `true` if HEAD moved, `false` if not; absent if it could not run |
+| `stale_warning` | Only on a real signal | The index is behind in a way that matters for this response |
+| `working_tree_dirty` | Above zero | Served targets with uncommitted edits no `repowise update --working-tree` has indexed |
+| `index_scope` | Recorded, and `status` not `complete` | How the index was built: run mode, provenance, git tier, whether it is whole |
+| `embedder_degraded` | An embedder is resolved | `true` or `false` |
+| `embedder`, `embedder_warning` | Embedder fell back, or the semantic index could not open | Which embedder, and why |
+| `newer_release` | Once per server process | A newer repowise is published; restart the server after upgrading |
+| `keyless_note` | Once per server process | What a model would add to a keyless `get_answer` |
+| `response_budget` | The budget cut something; always on `get_overview` | `limit_chars`, `tier` (`default` or `expanded`), `serialized_chars` |
+| `omitted` | Content was cut | `refs`, `tokens`, `restore`; see [Truncation and recovery](#truncation-and-recovery) |
+| `recovery_unavailable` | The omission store could not be written | The storage failure; cut rows cannot be restored |
+| `scope_hint` | `get_answer` | Up to three graph layers holding none of the served paths, with file counts |
+| `complete` | Whole units were served | Verified symbol bodies or whole files. Do not re-read them |
+| `completeness` | Something was capped; always on `get_overview` | `capped`, `shown`, `total`, `reason` |
+| `floor` | A count comes from walking the graph | Names fields whose values are lower bounds |
+| `state` | Something fired | `degraded` (with `degraded_reasons`), `partial` or `truncated` |
+
+Notes:
+
+- **`hint`:** on a `get_answer` graded `low` while the index is behind HEAD, it says to run `repowise update` and ask again.
+- **`stale_warning`:** HEAD moved and changed files this response serves; a served file has unseen uncommitted edits, or was indexed from edits since reverted; or the index is very old and git is unreachable. Identical trees set `index_behind` with no warning.
+- **`working_tree_dirty`:** source reads are live, but graph facts for those files predate the edit. A dirty tree elsewhere never sets it.
+- **`index_scope`:** the whole object comes with `get_overview(include=["scope"])`, or everywhere with `REPOWISE_MCP_INDEX_SCOPE=full`.
+- **`embedder`:** set when the embedder fell back to a mock or degraded mode.
+- **`keyless_note`:** on the first `get_answer` that degrades with `no-llm-provider`. It says `repowise generate` writes synthesized answers (needs a key, or `--provider ollama`). Never sent when a provider is configured.
+- **`response_budget`:** also present as `enforcement_error` when the protected fields could not fit.
+- **`complete`:** sliced bodies and partial ranges never count.
+- **`completeness`:** `shown`/`total` sum the collections a reducing pass counted; `reason` names the pass that dropped most. It measures what survived reduction, not your share of the repository.
+- **`floor`:** an unresolved edge is uncounted, not proven absent.
+- **`state`:** a roll-up of the response's own flags.
+- **No freshness fields** on `list_repos`, `get_architecture`, `get_blast_radius`, `get_conformance`, `get_dependency_path`, or a `repo="all"` call (no single commit to compare). `repo="all"` names stale repos in a top-level `repos_stale`.
---
## On the wire
-Each result carries the payload twice, as MCP allows: `structuredContent` is `{"result": <payload>}` (the tools advertise an `outputSchema`), and the text block is the same payload as compact JSON, with no indentation. Clients that read `structuredContent` see no difference; clients that forward the text block send fewer tokens. Set `REPOWISE_MCP_PRETTY_JSON=1` in the server's environment to restore indented text for a client that depends on it.
+- `structuredContent` is `{"result": <payload>}`; tools advertise an `outputSchema`.
+- The text block is the same payload as compact JSON, so clients that forward it send fewer tokens.
+- `REPOWISE_MCP_PRETTY_JSON=1` restores indented text.
---
## Truncation and recovery
-Responses fit 24,000 serialized characters by default and 32,000 when the call passes an expansion argument (for most tools, a nonempty `include`; for `get_answer`, `include=["evidence"]`). When the budget cut something, `_meta.response_budget` reports which ceiling applied.
-
-Content cut to fit is stored in the repo's [omission store](../agent/DISTILL.md#the-omission-store), and `_meta.omitted` says how to get it back:
+Responses fit 24,000 serialized characters, or 32,000 with an expansion argument (a nonempty `include` for most tools; `include=["evidence"]` for `get_answer`). Cut content goes to the repo's [omission store](../agent/DISTILL.md#the-omission-store):
```jsonc
"_meta": {
@@ -72,17 +85,17 @@ Content cut to fit is stored in the repo's [omission store](../agent/DISTILL.md#
}
```
-- A truncated skeleton block is replaced in place by a `[repowise#<ref>: ...]` marker. Other cut content goes into one combined document per response.
-- A response still over budget sheds whole blocks in an order each tool declares, cheapest loss first, and reports `truncated: true`.
-- A capped list keeps its count: it gains `<key>_total`, `<key>_emitted`, `<key>_truncated`, `<key>_omitted` and `<key>_reduced_reason` siblings as they apply. Some blocks also carry an `omission_marker` for their own tail.
-- Restore with `repowise expand <ref>` in a shell, or `get_symbol(symbol_id="repowise#<ref>")` from any MCP client. `query` filters the restored lines.
-- Include-gated blocks are projections, not omissions: a block you did not ask for is not reported as cut.
+- A truncated skeleton block becomes a `[repowise#<ref>: ...]` marker in place. Other cut content goes into one document per response.
+- A response still over budget sheds whole blocks in a per-tool order, cheapest loss first, and reports `truncated: true`.
+- A capped list gains `<key>_total`, `<key>_emitted`, `<key>_truncated`, `<key>_omitted` and `<key>_reduced_reason` as they apply. Some blocks carry an `omission_marker` for their tail.
+- Restore with `repowise expand <ref>` or `get_symbol(symbol_id="repowise#<ref>")`; `query` filters the lines.
+- Include-gated blocks you did not ask for are not reported as cut.
---
## Ignored arguments
-A value outside a closed vocabulary is dropped, not applied, so the response is the one you would have got without it. The tool names what it dropped:
+A value outside a closed vocabulary is dropped, so the response is the one you would get without it, and the tool names it. Absent when every argument was understood; one entry per argument.
```jsonc
"ignored_arguments": [
@@ -92,18 +105,16 @@ A value outside a closed vocabulary is dropped, not applied, so the response is
]
```
-The key is absent when every argument was understood. One entry per argument.
-
| Tool | Arguments checked | Shape |
|------|-------------------|-------|
-| `get_dead_code` | `kind`, `tier`, `min_confidence` | Top-level list, as above |
-| `get_context` | `include` | Top-level list |
-| `search_codebase` | `kind`, `mode` (an unknown `mode` runs as `auto`), `pattern` when `query` is also given (entry carries `"superseded_by": "query"`) | Top-level list |
-| `get_risk`, `get_change_risk`, `get_overview` | `include` | Top-level list |
-| `get_answer` | `include` | `_meta.ignored_arguments`, a map: `{"include": [...]}` |
-| `get_health` | `refactoring_*` and `performance_*` filters, `scope`, `counts` | Top-level flat map of argument to dropped value, e.g. `{"counts": "code-shape"}`. A value that belongs to the other control (`scope="code_shape"`) also gets `ignored_arguments_hint` naming the right one (not on a detail lookup, where neither control applies) |
+| `get_dead_code` | `kind`, `tier`, `min_confidence` | Top-level list |
+| `get_context`, `get_risk`, `get_change_risk`, `get_overview` | `include` | Top-level list |
+| `search_codebase` | `kind`, `mode`, `pattern` when `query` is also given | Top-level list |
+| `get_answer` | `include` | `_meta.ignored_arguments` map: `{"include": [...]}` |
+| `get_health` | `refactoring_*`, `performance_*`, `scope`, `counts` | Top-level map, e.g. `{"counts": "code-shape"}` |
-`get_health` reports a misspelled `only` key under `unknown_only_keys`. A detail lookup (`finding_id`, `plan_id`, `opportunity_id`) also lists `scope` and `counts` there, since a population control has nothing to act on for one stored row.
+- **`search_codebase`:** an unknown `mode` runs as `auto`; a `pattern` entry carries `"superseded_by": "query"`.
+- **`get_health`:** a value meant for the other control (`scope="code_shape"`) adds `ignored_arguments_hint`, except on a detail lookup. A misspelled `only` key lands in `unknown_only_keys`; a detail lookup (`finding_id`, `plan_id`, `opportunity_id`) lists `scope` and `counts` there too, since they cannot act on one row.
---
@@ -115,21 +126,21 @@ Every suggested follow-up (`get_health`'s `fix_first.lead.next_call`, the refact
|-------|---------|
| `purpose` | Why to make the call |
| `mcp` | The call as text, e.g. `get_health(opportunity_id="refop3_...")` |
-| `cli` | The terminal command giving the same answer, or null |
+| `cli` | The equivalent terminal command, or null |
| `tool`, `arguments` | The same call, structured |
---
## Workspace routing
-In workspace mode `get_context`, `get_symbol`, `get_risk` and `get_health` serve a path (or `alias:path`) from the repo that has it, when no `repo` is passed.
+In workspace mode, `get_context`, `get_symbol`, `get_risk` and `get_health` serve a path (or `alias:path`) from the repo that has it when no `repo` is passed.
| Field | Meaning |
|-------|---------|
-| `repo` | On a `get_context` card, or at the top of a `get_symbol`, `get_risk` or `get_health` response: the alias that answered, present when the target was routed away from the default repo |
-| `candidates` | On a target present in several repos (per card, or top level in `get_symbol`): their aliases, beside an `error` naming the `alias:path` form to pass. Nothing is guessed |
-| `routes` | On a refusal from a one-repo tool whose targets span repos: per target, `{"repo": alias}` or `{"candidates": [...]}`, with the per-repo calls named in `error` |
-| `hint` | On a target no workspace repo has: points at `search_codebase(query=..., repo="all")` |
+| `repo` | The alias that answered, when routed away from the default repo (per card in `get_context`, top level elsewhere) |
+| `candidates` | A target in several repos: their aliases, beside an `error` naming the `alias:path` form. Nothing is guessed |
+| `routes` | Refusal from a one-repo tool whose targets span repos: per target `{"repo": alias}` or `{"candidates": [...]}`; `error` names the per-repo calls |
+| `hint` | A target no repo has: points at `search_codebase(query=..., repo="all")` |
---
@@ -137,20 +148,29 @@ In workspace mode `get_context`, `get_symbol`, `get_risk` and `get_health` serve
| Field | Meaning |
|-------|---------|
-| `answer` | The synthesised answer, with file and symbol citations |
-| `confidence` | `high`, `medium` or `low`: the one trust signal. `high` is content-grounded, on a top hit that covers what the question asks, and can be cited directly. A why-answer whose named mechanism is absent from the retrieved source is downgraded to `medium` |
-| `retrieval_quality` | Only under `include=["diagnostics"]`. `high`, `partial` or `weak`: rates the retrieval alone, and is `weak` when the top hit leaves out most of what the question asks |
-| `symbol_bodies` | Live bodies of the symbols the answer names. Read these before calling `get_symbol` |
-| `retrieval` | Evidence rows (summary, snippet, key symbols). Shrinks as confidence rises |
-| `candidate_files` | Ranked file paths retrieval resolved, minus those already in `citations`: up to 3 at `high`, 5 at `medium`, `low` or `degraded`. Navigation, not evidence. Served at every confidence; absent when retrieval resolved no file |
-| `candidates` | The top 5 of those files as `{path, lines?, defines?}` rows. Only with `include=["evidence"]` |
-| `best_guesses`, `fallback_targets` | On low confidence: where to look, each with a one-line reason. At `low` or `degraded` a `best_guesses` row drops its page `excerpt` and carries `functions` (up to 3 `{name, line}` symbols relevant to the question) and the live file's `lines` and `size_bytes`; `include=["evidence"]` brings the excerpt back |
-| `episodes` | A dated fact recorded about this checkout that bears on the question; `still_true` says how current it is |
-| `degraded` | Synthesis could not run (no provider, or the call failed). The answer is assembled from retrieval and mined rationale with no LLM, and `confidence` is graded from the retrieval: `medium` on a dominant top hit that covers the question, else `low`, never `high` |
-
-How much evidence rides along depends on the grade. `high` keeps one quote, and one symbol body when the answer is not already grounded. `medium` keeps one body, two quotes and the top two evidence rows. `low` keeps two bodies and the top three rows. `include=["evidence"]` skips this trimming.
-
-Retrieval fuses three legs by reciprocal rank: full-text and vector search over wiki pages, and the structural symbol index keyed on the question's content words. The symbol leg reaches private helpers that a file page's public symbol table does not list.
+| `answer`, `citations` | The answer, with file and symbol citations |
+| `confidence` | `high`, `medium` or `low`: the one trust signal. Cite `high` directly |
+| `retrieval_quality` | With `include=["diagnostics"]`: `high`, `partial` or `weak`, rating retrieval alone |
+| `symbol_bodies` | Live bodies of symbols the answer names. Read before calling `get_symbol` |
+| `retrieval` | Evidence rows (summary, snippet, key symbols); shrinks as confidence rises |
+| `candidate_files` | Ranked paths not already in `citations`: up to 3 at `high`, else 5. Navigation, not evidence |
+| `candidates` | With `include=["evidence"]`: the top 5 files as `{path, lines?, defines?}` |
+| `best_guesses`, `fallback_targets` | On low confidence: where to look, each with a reason |
+| `episodes` | Dated facts about this checkout; `still_true` says how current |
+| `degraded` | Synthesis could not run (no provider, or the call failed) |
+| `grounding` | No-synthesis answers: `exact_symbol` or `extracted` |
+| `note`, `next_action_hint` | How the answer was built; on weak retrieval, which `best_guesses` row to start from |
+
+Notes:
+
+- **`confidence`:** `high` is content-grounded on a top hit covering the question. A why-answer whose mechanism is absent from the source drops to `medium`.
+- **`retrieval_quality`:** `weak` when the top hit leaves out most of the question.
+- **`candidate_files`:** served at every confidence; absent when retrieval resolved no file.
+- **`best_guesses`:** at `low` or `degraded` a row swaps its `excerpt` for `functions` (up to 3 `{name, line}`), `lines` and `size_bytes`; `include=["evidence"]` restores it.
+- **`degraded`:** built from retrieval and mined rationale with no LLM; `confidence` is `medium` on a dominant covering top hit, else `low`, never `high`. With `weak` retrieval too, the reply is `best_guesses`, `candidate_files` and one guidance line, with no `citations`.
+- **`grounding`:** `exact_symbol` serves the bodies of an exactly named symbol; `extracted` quotes a live source line verbatim.
+- **Evidence by grade** (`include=["evidence"]` skips this): `high` keeps one quote, plus one body when not already grounded; `medium` one body, two quotes, top two rows; `low` two bodies, top three rows.
+- **Retrieval** fuses full-text and vector search over wiki pages with the symbol index (keyed on the question's content words) by reciprocal rank. The symbol leg reaches private helpers a page's symbol table omits.
---
@@ -160,32 +180,110 @@ Per target, under `targets`:
| Field | Meaning |
|-------|---------|
-| title, summary, symbols | Docs summary and the symbols defined, with signatures and line numbers. Compact cards list the top 15 (types, then functions and methods, then the rest, by centrality) with `symbols_truncated` `{shown, total, hint}` and `symbols_total`; a budget trim below that keeps symbols by kind and name match, not centrality; `include=["symbols"]` lists all. A row without `symbol_id` is `path::name` |
+| title, summary, symbols | Docs summary and symbols with signatures and lines |
+| `symbols_truncated`, `symbols_total` | Compact card: `{shown, total, hint}` and the full count |
| `hotspot` | Churn flag |
-| `fix_history` | Only on files with counted bug fixes: count, age (measured to the indexed commit), `bug_magnet`. A cue to call `get_risk` |
-| `episodes` | Count of dated records bound to the target; `get_why` serves their bodies |
-| decisions | Titles by default. With `include=["decisions"]`, three lanes: `decisions` (accepted, governing), `candidates` (proposed, at most 3), `history` (accepted then withdrawn, at most 2) |
-| `file_preview` | For a file with no indexed symbols: `lines`, `chars`, and for a markdown or reST document `heading_count` with the first three `headings`; otherwise the first three non-empty lines as `head` |
-| `resolved_to`, `note` | A `path::Name` target whose symbol did not resolve answers with the file's card instead |
-| `did_you_mean` | On a symbol miss: up to five ids of the closest-named symbols (in that file when the file is real, else repo-wide), omitted when none is close |
-| `cross_repo` | Workspace mode: `co_changes_with` partners in other repos and contract `consumers` / `providers` |
-| `*_basis` | Beside an empty `callers`, `callees` or `used_by`: the language, how many call edges the index resolved for it, and the share that are guesses. An empty list means no resolved edge, not proof of none |
+| `fix_history` | Files with counted bug fixes: count, age, `bug_magnet`. A cue to call `get_risk` |
+| `episodes` | Count of dated records; `get_why` serves them |
+| decisions | Titles; with `include=["decisions"]` the lanes `decisions`, `candidates` (max 3), `history` (max 2) |
+| `file_preview` | File with no symbols: `lines`, `chars`, and `heading_count` + 3 `headings` (markdown, reST) or 3 lines as `head` |
+| `resolved_to`, `note` | A `path::Name` miss answered with the file's card |
+| `did_you_mean` | Symbol miss: up to 5 closest ids, in that file or repo-wide |
+| `cross_repo` | Workspace: `co_changes_with` in other repos, contract `consumers` / `providers` |
+| `*_basis` | Beside an empty `callers`, `callees` or `used_by`: language, resolved call edges, guess share |
+
+Top level: `targets`, `_meta`, `ignored_arguments`, `suspects` when asked, and `dropped_targets` with `recovery` when the budget dropped targets.
+
+- **symbols:** compact cards list the top 15: types (classes, interfaces, structs, traits, enums, type aliases, impls, modules), then functions and methods, then the rest, each by centrality. A budget trim below 15 keeps symbols by kind and name match. `include=["symbols"]` lists all.
+- **`symbol_id`:** absent means `path::name`; methods and overloads carry theirs.
+- **`fix_history`:** age is measured to the indexed commit.
+- **`*_basis`:** an empty list means no resolved edge, not proof of none.
+
+### Context opt-in blocks
+
+| `include` | Adds |
+|-----------|------|
+| `full_doc` | `content_md`, plus `digest_md` (questions answered, concept index, public API, git signals); dropped first over budget |
+| `ownership` | Primary owner, bus factor, contributor count |
+| `last_change`, `community` | Newest change; community |
+| `callers`, `callees` | Call-graph neighbours |
+| `references` | Symbol edit set; see [references](#references) |
+| `metrics` | PageRank, betweenness, percentiles |
+| `decisions` | The three decision lanes |
+| `skeleton` / `skeleton+` | Bodies elided; `skeleton+` keeps all non-function code and elides every body. Both asked renders `skeleton+` |
+| `health`, `doc_drift` | Health scores and biomarkers; documents naming the file |
+| `symbols` | Every symbol of a file |
+| `changes`, `provenance`, `suspects` | See below |
+
+`docs` and `freshness` are always on and legal to pass.
+
+### references
+
+Every live line naming a symbol target, as `{path, line, kind, text}` with kind `definition`, `import`, `call` or `reference`. A `complete` list is the whole rename edit set; otherwise `reasons` says why. Never complete for:
+
+- languages other than Python, TypeScript and JavaScript (same-package use needs no import)
+- over 200 sites, a stale call line, an unreadable file, or an uncommitted edit outside the scanned files
+- a rename on import, export or destructure, a default export, or a CommonJS export
+- a dynamic use the graph recorded; string-built access is otherwise unseen
+- over 3 plain `reference` sites in one file: the rest go to `sites_omitted_by_file`, recoverable from `_meta.omitted`
+
+### changes
+
+`recent_changes`: the newest five Change Records touching the file, each `{id, ref, title, merged_at, category, provenance}`; `recent_changes_total` when more exist.
+
+- `ref` is the forge number (`#123`, `!12`), absent for an unnamed change.
+- `provenance` is `{label, coverage}`, label `agent`, `human_attested` or `unknown`; absent when stored without a label or attribution is off.
+- Only the newest 500 changes are read and a change stores its first 1,000 files, so a file past either limit can be missing.
+
+### provenance
+
+`agent_commits`, `human_attested_commits`, `unknown_commits`, `coverage` (known over all), `agent_share` (agent over known), `summary`.
+
+- Below 30% coverage `agent_share` is null with `suppressed_reason: "coverage_below_floor"`, and the agent and human-attested counts are dropped.
+- Unknown never counts as human. Attribution off: `{"unavailable": "attribution_off"}`.
-Opt-in blocks: `full_doc`, `ownership` (primary owner, bus factor, contributor count), `last_change`, `callers`, `callees`, `metrics` (PageRank, betweenness, percentiles), `community`, `skeleton`, `health`, `doc_drift`, `symbols` (every symbol of a file), `changes`, `provenance`, `suspects`.
+### suspects
-**changes.** On a file target, `recent_changes` lists the newest five Change Records whose files include it, each `{id, ref, title, merged_at, category, provenance}`; `ref` is the forge's number (`#123`, `!12`) and is absent for an unnamed change, and `provenance` is `{label, coverage}` (`agent`, `human_attested` or `unknown`; absent when the change was stored without a label or attribution is off). `recent_changes_total` appears when more touched the file. The newest 500 candidate changes are read, and a change stores only its first 1,000 files, so a file past either limit can be missing from the list.
+One top-level block: `window` (`since`, `until`), `candidates` (changes merged in the last 14 days), `texts_missing` (unreadable changes, ranked on title and files), `symptom_files` (targets mapped to files at HEAD), `note`, and `suspects`.
-**provenance.** A file's commits by source: `agent_commits`, `human_attested_commits`, `unknown_commits`, `coverage` (known over all commits), `agent_share` (agent over known commits) and a one-line `summary`. Below 30% coverage `agent_share` is null with `suppressed_reason: "coverage_below_floor"`, and the agent and human-attested counts are left out. Unknown is never counted as human. With attribution off the block is `{"unavailable": "attribution_off"}`.
+- `suspects`: at most 5 rows of `{id, ref, title, merged_at, category, head_sha, files_changed, rank, signals}`, ranked against the targets' files and path words, or the `symptom` text.
+- `signals` maps each fired signal (`text`, `graph`, `co-change`, `recency`, `trace`) to its `rank` and `evidence`.
+- A reading order, never a cause: no score or probability.
-**suspects.** One top-level block, not per target: `window` (`since`, `until`), `candidates` (changes merged in the 14 days before now), `texts_missing` (changes git could not read, ranked on title and files alone), `symptom_files` (the targets mapped onto files tracked at HEAD) and `suspects`, at most five rows of `{id, ref, title, merged_at, category, head_sha, files_changed, rank, signals}`, where `signals` maps each signal that fired (`text`, `graph`, `co-change`, `recency`, `trace`) to its own `rank` and `evidence`. `note` says the order is a reading order, not a cause; no row carries a score or probability.
+### Component targets
-**Change targets.** A `change:<id>` target (an id such as `pr-123`, or a commit sha the change landed) returns `type: "change"`, `id`, `ref`, `title`, `merged_at`, `category`, `shape` (`merge`, `squash`, `commit`), `head_sha`, `commit_count`, `files_changed`, `lines_added`, `lines_deleted`, `files` (paths, the first 25 with `files_total` and an omission ref past that), `linked_issues` when the messages close any, and `provenance`: `{label, agent_commits, human_attested_commits, unknown_commits, coverage}`, `{"unavailable": "attribution_off"}`, or `{"unavailable": "not_recorded"}` for a change stored while attribution was off. An unknown id returns `error` naming the id forms; a short sha that starts commits in several changes returns `error` with their ids as `candidates`.
+`component:<name>`: declared context (owner, system, criticality, tags) and `facts` over its files: health, hotspots, bus factor, test reach, dead code, each with a `basis` (`measured`, `inferred`, `unavailable`).
-**Skeleton.** Sliced from the index's stored symbol bounds, with no parsing at query time: every signature, the import preamble, and the bodies of the top symbols ranked by centrality, hotspot and query match. Elision markers carry 1-indexed line ranges, so you can read any part back.
+- Components come from [`.repowise/components.yaml`](CONFIG.md#repowisecomponentsyaml) or the index.
+- Health and dead code skip gated-language files and say how many.
+- Only `include=["ownership"]` applies. It adds declared teams with 90-day activity, a count of individual owners, and findings `critical_no_active_owner`, `declared_owner_inactive`, `critical_bus_factor_one`, `catalog_entry_no_code`.
+- An owner with no identity in history is `unknown` and raises nothing, so `critical_no_active_owner` never fires when every owner is unknown. Individuals match only by exact git email or forge noreply login.
-**doc_drift.** `references` lists documents that name this file and still resolve to it. `documents_with_drift` says a listed document carries some assertion that no longer holds, anywhere in it, not necessarily about this file. Do not merge the two claims. `references_basis` states the limits; documents dropped by exclude rules are counted in `references_excluded`. An answer the store cannot support is a refusal: `{"unavailable": "not_computed"}` (the pass has not run yet), `"index_predates_doc_drift"`, or `"drift_read_failed"`.
+### Change targets
-**Several targets under one budget.** Each target gets an equal share, and a small target's unused share passes to the others. A target over its share drops symbols first, then its optional blocks largest first (named in `dropped_blocks`). Miss `suggestions`, `did_you_mean` and ambiguity `candidates` are never shed. When even the identity cards cannot all fit, whole targets go first; the response leads with `dropped_targets` and a `recovery` call narrowed to them.
+`change:<id>` (`pr-123` or a commit sha the change landed): `type: "change"`, `id`, `ref`, `title`, `merged_at`, `category`, `shape` (`merge`, `squash`, `commit`), `head_sha`, `commit_count`, `files_changed`, `lines_added`, `lines_deleted`, `files` (first 25, then `files_total` and an omission ref), `linked_issues` when messages close any, `provenance`.
+
+- `provenance` is `{label, agent_commits, human_attested_commits, unknown_commits, coverage}`, or `{"unavailable": "attribution_off"}`, or `{"unavailable": "not_recorded"}` for a change stored with attribution off.
+- An unknown id returns `error` naming the id forms; an ambiguous short sha returns `error` with ids as `candidates`.
+
+### Package targets
+
+`package:<name>` (`package:requests`, `package:npm:lodash`): manifest declarations, a summary, components and owner teams, and up to 25 import sites with line, `mapping` (`declared`, `inferred`) and `reachability` (`reachable`, `unreachable`, `test`, `unknown`, with a basis). See [PACKAGE_USAGE.md](PACKAGE_USAGE.md).
+
+### Skeleton
+
+Cut from stored symbol bounds, no parsing at query time: every signature, the imports, and the bodies of top symbols by centrality, hotspot and query match. Elisions carry 1-indexed line ranges.
+
+### doc_drift
+
+- `references`: documents naming this file that still resolve to it.
+- `documents_with_drift`: a listed document has some stale assertion somewhere, not necessarily about this file. Do not merge the two claims.
+- `references_basis` states the limits; `references_excluded` counts documents dropped by exclude rules.
+- Refusals: `{"unavailable": "not_computed"}` (pass not run), `"index_predates_doc_drift"`, `"drift_read_failed"`.
+
+### Several targets under one budget
+
+Each target gets an equal share; unused share passes on. Over its share, a target drops symbols, then optional blocks largest first (`dropped_blocks`). Miss `suggestions`, `did_you_mean` and ambiguity `candidates` are never shed. If identity cards still do not fit, whole targets go, and the response leads with `dropped_targets` and a narrowed `recovery` call.
---
@@ -193,14 +291,17 @@ Opt-in blocks: `full_doc`, `ownership` (primary owner, bus factor, contributor c
| Field | Meaning |
|-------|---------|
-| source | Up to about 600 lines (200 for a range read), each prefixed with its line number in `Read` format |
-| start and end lines, `kind` | Exact bounds of the symbol |
-| `truncated` | The body was cut; the response carries the continuation to pass back as `reference` |
-| `ambiguous`, `candidates` | Several indexed symbols match (overloads, re-exports, conditional definitions). Every candidate body is returned; none is chosen silently |
-| `callee_bodies` | With `depth` 2 or 3: each callee's `depth`, source and `verified` flag. Each symbol appears once, at its shallowest depth |
-| `not_rendered` | Candidates or callees past the budget, each with a `fetch_with` range read |
-| fallback lines | On a miss, the closest matches from a live grep |
-| `source`, `created_at`, `original_tokens` | For an omission ref: where the stored content came from |
+| source | Up to about 600 lines (200 for a range), line-numbered in `Read` format |
+| start and end lines, `kind` | Exact bounds |
+| `truncated` | Body cut; carries a continuation to pass back as `reference` |
+| `ambiguous`, `candidates` | Several matches (overloads, re-exports, conditional definitions); every body returned, none chosen |
+| `callee_bodies` | `depth` 2 or 3: each callee's `depth`, source, `verified`; each once, at its shallowest depth |
+| `not_rendered` | Bodies past the budget, each with a `fetch_with` range read |
+| `outlined`, `members`, `members_total` | Container too large to serve whole |
+| fallback lines | On a miss, closest matches from a live grep |
+| `source`, `created_at`, `original_tokens` | Omission ref: where the stored content came from |
+
+`outlined: true` puts the header in `source` and `members` (each `symbol_id`, signature, lines; `members_total` when capped) in place of the body, with no `_meta.complete`.
---
@@ -208,18 +309,38 @@ Opt-in blocks: `full_doc`, `ownership` (primary owner, bus factor, contributor c
| Field | Meaning |
|-------|---------|
-| `results` | Ranked hits. Symbol hits: `type: "symbol"`, `symbol_id`, `name`, `kind`, `path`, `start_line`, `end_line`, `signature`, `next: "get_symbol"`. File hits: `type: "file"`, `page_id`, `path`, `title`, `next: "get_context"`. Concept hits: wiki pages with `page_type`, `path` when the page names a file, `symbol_id` on a symbol page, `relevance_score`, `snippet`. `page_id` and `title` are left off a row that can rebuild them: the id is `{page_type}:{symbol_id or path}`, and a structural title is `File: <path>` / `Symbol: <symbol_id>` in the repo's page language. Prose titles (module, onboarding, overview) stay |
-| `path` | The repo-relative file a row names, openable as is. Absent when the row names no file (a module page's group key, an onboarding slot, the repo overview); never a page id |
-| `target_path` | On a page hit, kept only where it is not the same string as `path`: a page with no `path` keeps its group key, slot or repo name here. Where it is dropped, `page_id` stays |
-| `symbols` | On a symbol hit outside `symbol` mode: up to five other matching symbols in the same file, as `name:line`, then a `+N more` entry counting the rest. Those matches share the row instead of taking slots of their own |
-| `sources` | The retrievers that found a concept hit: `fts`, `vector`, `symbol` or a combination. Omitted when it would be `["fts"]` and `_meta.semantic_search` is `false`, since the reply already says retrieval is full-text-only |
-| `candidates` | Up to `limit` distinct openable file paths, best first |
+| `results` | Ranked symbol, file and concept rows |
+| `candidates` | Up to `limit` distinct openable file paths, best first. Read these before a Read |
+| `lines` | Identifier or literal query: `{path, line, kind, text}`, definitions first, max 50 |
+| `complete`, `reasons` | Whether `lines` is every match, and why not |
+
+| Row | Fields |
+|-----|--------|
+| Symbol | `type: "symbol"`, `symbol_id`, `name`, `kind`, `path`, `start_line`, `end_line`, `signature`, `next: "get_symbol"` |
+| File | `type: "file"`, `page_id`, `path`, `title`, `next: "get_context"` |
+| Concept | `page_type`, `path` if the page names a file, `symbol_id` on a symbol page, `relevance_score`, `snippet`, `sources` |
-Outside `mode="symbol"`, `limit` caps distinct files: hits are collapsed to one row per file, best row first, and the freed slots go to the next pages, then the next symbols. This includes concept mode, where a file page and a `symbol_spotlight` page of the same file are one row. `mode="symbol"` keeps one row per symbol, so overloads in one file each list.
+Row notes:
-Symbol hits rank by exact and qualified name match, query-token coverage, then graph centrality; non-test before test unless `kind="test"`. A `symbol_spotlight` page's id is `file.py::Symbol`; its `path` is the file.
+- **`path`:** the openable repo-relative file; absent when the row names no file (module group key, onboarding slot, overview), never a page id. There is no `file` key.
+- **`page_id`, `title`:** dropped where rebuildable: id `{page_type}:{symbol_id or path}`, title `File: <path>` / `Symbol: <symbol_id>` in the page language. Prose titles stay.
+- **`target_path`:** kept only where it differs from `path` (a page's group key, slot or repo name).
+- **`symbols`:** on a symbol hit outside `symbol` mode, up to 5 other matches in the file as `name:line`, then `+N more`. On a page row, up to 3 query-matching `name:line` (`Owner.member`).
+- **`matched_lines`:** on the first three page rows with a match, up to 3 live `{line, text}` sharing the most query words, code before comments and imports. Never every match.
+- **`sources`:** `fts`, `vector`, `symbol`, or a mix; omitted when `["fts"]` and `_meta.semantic_search` is `false`.
-`results` ranks pages, and some pages are not files: a `module_page` is named by a group key that looks like a directory, an `scc_page` by a hash. `candidates` resolves symbol pages to their file, collapses several symbols of one file into one entry, skips pages that name no file, and backfills from below the result window. If the next move is a Read, read `candidates`. A hybrid query (prose around an identifier) drops pages that name no file (module, onboarding, overview, decision pages) from `results` without refilling their slots, unless `page_type` or `kind="doc"` asks for pages; concept mode keeps them. Decision records rank below file pages unless the query is why-shaped.
+`lines` notes:
+
+- The `get_context` [references](#references) of one to three exact symbols, else a live token scan (kind `definition` or `match`).
+- Past 3 plain `reference` lines per file, or 50 total, rows go to `lines_omitted_by_file`, recoverable from `_meta.omitted`. Test files sort last.
+- A multi-word query caps `lines` at 15 (definitions, calls, imports) and lists the 5 files with most omitted rows; `lines_omitted_by_file_total` counts all.
+
+Ranking:
+
+- Outside `mode="symbol"`, `limit` counts distinct files: one row per file (a file page and its `symbol_spotlight` page included), freed slots go to the next pages, then symbols. `symbol` mode keeps one row per symbol, so overloads in one file each list.
+- Symbols rank by exact and qualified name, query-token coverage, then centrality; non-test first unless `kind="test"`. A `symbol_spotlight` id is `file.py::Symbol` with `path` the file.
+- Some pages are not files (a `module_page` group key, an `scc_page` hash). `candidates` maps symbol pages to files, merges same-file symbols, skips fileless pages, and backfills.
+- A hybrid query drops fileless pages (module, onboarding, overview, decision) without refilling, unless `page_type` or `kind="doc"` asks for pages; concept mode keeps them. Decisions rank below file pages unless the query is why-shaped.
---
@@ -229,36 +350,61 @@ Per file:
| Field | Meaning |
|-------|---------|
-| `defect_profile` | Only on files with counted bug fixes: `fix_count` (in 6-month window), `last_fix_days_ago` (measured to the indexed commit), `bug_magnet`, `top_symbols` |
+| `defect_profile` | Files with counted fixes: `fix_count` (6 months), `last_fix_days_ago` (to the indexed commit), `bug_magnet`, `top_symbols` |
| `hotspot_score` | 0 to 1 churn percentile |
| `health_score` | 0 to 10 |
-| `dependents_count` | Direct directed structural dependents; a floor over the indexed graph |
-| `co_change_partners` | Historical correlation only. Each row carries `file_path`, `support` (count of shared commits, when known), `conf_ab` (share of target file's commits that touched partner, when known), and `has_import_link`. Sorted by recency-decayed weight |
-| owners, reviewers | Primary owner (`primary_owner`) and the owner clause in `risk_summary` are unconditional; detailed owner metrics (`owner_pct`, `owner_line_pct`, `recent_owner`, `recent_owner_pct`, `bus_factor`, `contributor_count`) are opt-in under `include=["owners"]`; recommended reviewers stay in PR mode |
-| test gaps, `security_signals` | Test coverage gaps and security findings for the file |
-| `resolved`, `unresolved_reason` | A target naming no indexed file: `unsupported_target_kind` (a `module:` id), `directory`, `not_indexed`, `no_such_path`. Counts are omitted, never zeroed |
-| `signal_tier`, `signal_tier_reason` | `"history"` on a file indexed for commit history only (docs, config, query and other non-code files): the card carries commit counts, `last_commit_at`, `trend`, owner and `security_signals`, and omits hotspot, co-change, dependents and classification rather than zeroing them |
+| `dependents_count` | Direct structural dependents; a floor |
+| `co_change_partners` | `file_path`, `support` (shared commits, when known), `conf_ab` (share of the target's commits touching the partner, when known), `has_import_link`; by recency-decayed weight. Correlation only |
+| `primary_owner` | Always, with the owner clause in `risk_summary` |
+| test gaps, `security_signals` | Coverage gaps and security findings |
+| `resolved`, `unresolved_reason` | No indexed file: `unsupported_target_kind` (`module:` id), `directory`, `not_indexed`, `no_such_path`; counts omitted, not zeroed |
+| `signal_tier`, `signal_tier_reason` | `"history"` for docs, config, query and other non-code files |
-Opt-in blocks: `changes` adds `recent_changes` (and `recent_changes_total`), shaped as in `get_context`. `owners` adds `owner_pct`, `owner_line_pct`, `recent_owner`, `recent_owner_pct`, `bus_factor` and `contributor_count`. `tests` adds the PR directive's typed `test_recommendations`, and `blast` adds `pr_blast_radius`, the PR dossier behind the directive (transitive files, co-change warnings, test gaps, the structural score; reviewers stay in the directive). `graph` adds typed `dependents` (direct versus transitive), `consumers` (typed contract consumers only), `cross_repo_links`, `impact_surface` and `direct_risks`, with `relationship_analysis` distinguishing an empty analysis from an unavailable or partial one. `churn` adds `change_magnitude`, `risk_type` and `change_pattern`. `scales` adds the unit, range and calibration of every scalar; it is identical on every call, so ask once. A multi-target call also carries `global_hotspots`.
+- **`signal_tier`:** the card keeps commit counts, `last_commit_at`, `trend`, owner and `security_signals`, and omits hotspot, co-change, dependents and classification.
+- Multi-target calls add `global_hotspots`. Floats have 4 significant digits. Direct rows' `structural_score` is in pagerank-weighted hotspot units, not comparable to `get_change_risk`.
-**PR mode** (`changed_files` passed). The response starts with `directive`:
+| `include` | Adds |
+|-----------|------|
+| `owners` | `owner_pct`, `owner_line_pct`, `recent_owner`, `recent_owner_pct`, `bus_factor`, `contributor_count` |
+| `changes` | `recent_changes`, `recent_changes_total`, as in [get_context](#changes) |
+| `tests` | Typed `test_recommendations` |
+| `blast` | `pr_blast_radius`: transitive files, co-change warnings, test gaps, structural score; reviewers stay in the directive |
+| `graph` | `dependents` (direct vs transitive), `consumers` (typed contract consumers), `cross_repo_links`, `impact_surface`, `direct_risks`, `relationship_analysis` (empty vs unavailable or partial) |
+| `churn` | `change_magnitude`, `risk_type`, `change_pattern` |
+| `scales` | Unit, range and calibration per scalar; identical every call |
-| Field | Meaning |
-|-------|---------|
-| `may_break` | Production files in reverse-import reach of the change: candidates for review, not proven breakage |
-| `missing_cochanges` | Historical co-change partners absent from the change |
-| `tests_to_run`, `tests_to_run_basis` | The tests the change needs, from the same selection `repowise impacted-tests` makes, capped at ten, in `repowise impacted-tests`' [run order](CLI_REFERENCE.md#repowise-impacted-tests-revspec). `tests_to_run_basis` is `measured` when coverage decided a changed file, `inferred` when only the graph or a rule did, `none` when nothing named a test. `tests_to_run_why` gives the reason for each listed file (the changed file and evidence, or `runs with every subset: ...`). `tests_run_all` true means no subset can be vouched for and `tests_run_all_reasons` says why; the list is then what to run first. `tests_broadcast_total` counts the tests that run only because a conftest on a route keeps every test under it, and `tests_import_closure_total` those the change reaches only through imports, more than one file away, with no call path; both are left out of the list and its total and still run. A failed selection carries `tests_status` and `tests_status_reason` and names nothing |
-| `tests_to_update` | Up to three test files the change will probably need edited, each `{path, reason}` with `reason` `name_pair` (named for a changed file), `imports` (its own code imports one; a conftest or setup file reaching it does not count) or `co_change` (changes with one in git history), in that order. Only tests the selection runs because of a changed file and that a runner collects. Tests to edit, not to run: a file can appear in both lists. Empty when none qualify |
-| `missing_tests`, `files_without_measured_tests` | Changed files with no measured test. `missing_tests` is absent when coverage is unavailable or stale, since an empty list would read as no gaps |
-| `coverage` | `{status, reason}` when there is no per-test coverage map. With a map, `coverage_analysis`, `test_analysis` and `test_inference_analysis` say whether each evidence source was available, stale, partial or degraded |
-| `test_recommendations` | With `include=["tests"]`: typed rows, each with a `basis`: `measured` (the per-test coverage map found the test) or `inferred` (structural reach, not coverage proof) |
-| `recommended_reviewers` | Up to five primary owners of the affected files |
-| `reach` | Band of the uncalibrated 0 to 10 structural heuristic: `localized` below 4, `moderate` 4 to below 7, `broad` 7 and up. `null` when the analyzer computed no score. Not a breakage probability, and it never sees the diff. The raw `pr_blast_radius.structural_impact_score` and its scale appear only with `include=["blast", "scales"]` |
-| `next_calls` | `get_change_risk()` for the diff itself, then `get_context` on the first `may_break` files |
+### PR mode directive
-In workspace mode the directive also carries `will_break_consumers` (services in other repos that structurally depend on this one; structural reach only despite the name), `missing_cross_repo_cochanges`, `breaking_changes` (provider incompatibilities since the last index, with impacted consumers; a consumer link does not prove field use), `conformance_violations` and `dependency_cycles`. They are dropped when no workspace is loaded.
+With `changed_files`, the response leads with `directive`:
-Every float is rounded to 4 significant digits. Direct rows' `structural_score` values are in pagerank-weighted hotspot units and are not comparable to `get_change_risk` scores.
+| Field | Meaning |
+|-------|---------|
+| `may_break` | Production files in reverse-import reach: review candidates, not proven breakage |
+| `missing_cochanges` | Co-change partners absent from the change |
+| `tests_to_run` | The `repowise impacted-tests` selection, max 10, in [run order](CLI_REFERENCE.md#repowise-impacted-tests-revspec) |
+| `tests_to_run_basis` | `measured` (coverage decided a file), `inferred` (graph or rule), `none` |
+| `tests_to_run_why` | Per file: changed file and evidence, or `runs with every subset: ...` |
+| `tests_run_all`, `tests_run_all_reasons` | No subset can be vouched for; the list is what to run first |
+| `tests_broadcast_total`, `tests_import_closure_total` | Tests left out of the list that still run |
+| `tests_status`, `tests_status_reason` | Failed selection; names nothing |
+| `tests_to_update` | Up to 3 test files to edit, `{path, reason}` |
+| `missing_tests`, `files_without_measured_tests` | Changed files with no measured test |
+| `coverage` | Which coverage evidence was available |
+| `test_recommendations` | `include=["tests"]`: rows with `basis` `measured` (per-test map) or `inferred` (structural) |
+| `recommended_reviewers` | Up to 5 primary owners of affected files |
+| `reach` | `localized` (<4), `moderate` (4 to <7), `broad` (7+), or `null` |
+| `next_calls` | `get_change_risk()`, then `get_context` on the first `may_break` files |
+
+Notes:
+
+- **`tests_broadcast_total`:** run only because a conftest on a route keeps every test under it. **`tests_import_closure_total`:** reached only through imports over one file away, with no call path.
+- **`tests_to_update`:** reasons in order `name_pair` (named for a changed file), `imports` (its own code imports one; conftest or setup reach does not count), `co_change`. Only tests the selection runs for a changed file and a runner collects. Edit, not run; a file can be in both lists.
+- **`missing_tests`:** absent when coverage is unavailable or stale, since empty would read as no gaps.
+- **`coverage`:** `{status, reason}` with no per-test map; with stored line coverage, `reason` is `no_per_test_map_aggregate_available` and `coverage.aggregate` gives file count and freshness. With a map, `coverage_analysis`, `test_analysis`, `test_inference_analysis` say if each source was available, stale, partial or degraded.
+- **Measured `test_recommendations`** match a changed file, not its lines (`evidence[].match: "file"`); a test file gone or changed since measurement carries `stale: true` and `stale_reason`.
+- **`reach`:** bands an uncalibrated 0 to 10 heuristic that never sees the diff; not a probability. The raw `pr_blast_radius.structural_impact_score` needs `include=["blast", "scales"]`.
+
+In workspace mode the directive adds `will_break_consumers` (structural reach only), `missing_cross_repo_cochanges`, `breaking_changes` (provider incompatibilities since the last index with impacted consumers; a link does not prove field use), `conformance_violations` and `dependency_cycles`; dropped when no workspace is loaded.
---
@@ -266,37 +412,105 @@ Every float is rounded to 4 significant digits. Direct rows' `structural_score`
| Field | Meaning |
|-------|---------|
-| `directive` | `status` (`review_required`, `review_recommended`, `clear_in_analyzed_scope`, `unknown`), a headline, reasons, next actions. Findings that gate the verdict (high or critical, not performance) lead the reasons, the inspect actions and `top_findings`, so the headline's finding comes first in each; its count reads "N of M" when other findings are lower. The headline ends with the changed code's health on both sides |
-| `health_delta` | What the change newly made worse. See below |
-| `risk_percentile` | The change's diff size and spread ranked against the repo's recent commits. Size, not a verdict: `directive.status` is the verdict. `include=["scales"]` adds the `review_priority` tercile and its `classification` (`Below-typical`, `Typical` or `Above-typical diff size`) |
-| `is_fix` | Present only when the change is a bug fix |
-| `exclude_patterns` | Present only when something was excluded: the request's patterns plus `.riskignore` |
-| `diff_shape` | One sentence on size and spread; never a danger verdict |
-| `working_tree` | Present only when `revspec` was omitted: whether uncommitted work was scored, or a clean tree fell back to `HEAD` |
-| `fix_history` | Recency-weighted bug-fix record of the touched files (manifests and lockfiles not listed), with `overlap`; `density` and its `percentile` ship with `include=["diagnostics"]` |
-| `impacted_tests` | The tests the change needs, and whether every test must run |
+| `directive` | `status` (`review_required`, `review_recommended`, `clear_in_analyzed_scope`, `unknown`): the verdict. Plus headline, reasons, next actions |
+| `health_delta` | What the change newly made worse; see [health_delta](#health_delta) |
+| `risk_percentile` | Diff size and spread against recent commits. Size, not a verdict |
+| `diff_shape` | One sentence on size and spread; never danger |
+| `is_fix` | Only when the change is a bug fix |
+| `exclude_patterns` | Only when something was excluded: request patterns plus `.riskignore` |
+| `working_tree` | Only without `revspec`: uncommitted work scored, or clean tree fell back to `HEAD` |
+| `fix_history` | Recency-weighted fix record of touched files (no manifests or lockfiles), with `overlap` |
+| `impacted_tests` | Tests the change needs |
| `patch_coverage` | Share of changed executable lines the stored coverage ran |
| `branch_overlap` | Other branches editing the same files |
-| `independent_changes` | When the diff is several unrelated changes |
-| `cross_repo` | Workspace mode: consumers and breaking changes across repos |
+| `independent_changes` | The diff is several unrelated changes |
+| `cross_repo` | Workspace: consumers and breaking changes |
+| `status` | `"nothing_to_score"` on an empty diff |
-`include=["diagnostics"]` adds `score` (the raw 0 to 10 number), `fallback_band`, `risk_authority`, `score_measures`, `score_unit`, `baseline_sample_size`, `features` and `drivers`, plus `health_delta.analyzer` (analyzer and rules fingerprint, and `context`: `index_dependents` when centrality gates read the index's dependents counts on both sides, `changed_files` with no index), `health_delta.base` and `health_delta.head` (the two resolved revisions) and `health_delta.limits`. `include=["scales"]` adds each field's unit, range and calibration.
+- **Directive order:** gating findings (high or critical, not performance) lead the reasons, inspect actions and `top_findings`; the count reads "N of M" when others are lower. The headline ends with the code's health on both sides.
+- **`include=["scales"]`** adds each field's unit and calibration, and the `review_priority` tercile with `classification` (`Below-typical`, `Typical`, `Above-typical diff size`).
+- **`include=["diagnostics"]`** adds `score` (raw 0 to 10), `fallback_band`, `risk_authority`, `score_measures`, `score_unit`, `baseline_sample_size`, `features`, `drivers`, `fix_history` `density` and `percentile`, and `health_delta.analyzer` (rules fingerprint; `context` is `index_dependents` when centrality gates read the index's dependents counts on both sides, `changed_files` with no index), `.base`, `.head` (resolved revisions), `.limits`.
+- **`include=["findings"]`** lists every finding with its expand call as `inspect`. `evidence` adds the evidence checklist; `tests` adds `impacted_tests.why` and `basis_by_file`.
-**health_delta.** Both revisions are analysed from their own content, and a finding at head is reported only when the diff explains it. `scope` counts changed, eligible, analysed, skipped and failed files; `status` is `available`, `partial` or `unavailable`, and `partial` is never a clean bill. Documentation and configuration files (Markdown, JSON, YAML, TOML and the other doc or config extensions) are skipped with reason `not_code` and never make a run `partial`; a change made only of them reads `clear_in_analyzed_scope` with a headline saying health analysis does not cover them. Tree-sitter query files (`.scm` under a `queries` directory) and text templates (`.j2`, `.jinja`, `.jinja2`, `.tmpl`, `.tpl`, `.hbs`, `.mustache`, `.ejs`, `.njk`) are skipped with reason `not_analyzable_data`, which also never makes a run `partial`; a change made only of them reads `clear_in_analyzed_scope` with its own headline, since they can still change behaviour. HTML, schema and other files with no health dialect still make a run `partial`. `introduced`, `worsened` and `resolved` are totals; `top_findings` holds the three most actionable, with `findings_total`. Each finding names `dimension`, `biomarker`, `severity`, `path`, `symbol`, head-side `lines`, a `reason`, and an `attribution` (`basis` of `added_lines`, `changed_symbol`, `changed_call_edge`, `new_file`, `file_change`, `context_change` or `unknown`, with a `confidence`). Identity ignores line numbers, so moved code introduces nothing. Pass a finding's `id` as `finding_id` to expand it; with `include=["findings"]` each row carries that call as `inspect`. Ids are bound to the two revisions. A finding that matches a stored one carries `health_reference` for `get_health(finding_id=...)`. Performance findings carry `opportunity_id` and are ordered by opportunity rank.
+### health_delta
-`files` lists up to 10 analysed files, largest structure move first, each with `base_score`, `head_score`, `nloc_base` and `nloc_head`; a side the file is missing on reads null. `files_total` counts them all. `include=["diagnostics"]` adds `base_structure` and `head_structure` (the structure deduction). `score_basis` is `structure_only`: each score is 10 minus the structure deduction, the reading `get_health(counts="code_shape")` gives, from two passes that read no git history or coverage. A deleted file has a base-only row, with `moved_to` naming where its code went when it was split. `score_change` averages files scored on both sides, weighted by base nloc so a file that grows while improving keeps its gain: `base`, `head`, `delta` (two decimals), `structure_delta` (the deduction change, which still moves when a file sits on the 1.0 floor) and `files_compared`.
+Both revisions are analysed from their own content; a head finding is reported only when the diff explains it.
-**impacted_tests.** The selection `repowise impacted-tests` makes, over every path the change touched whatever the score's filters, less the repowise output the score also leaves out (the index, and a managed file whose only change is repowise's block or entry), which the CLI still reads when tracked. `status` is `selected`, `run_all` or `degraded` (or `no_index`, `unknown`, `config_invalid`, `timeout`, `busy`, `no_source_line_changes` when nothing was selected, each with `run_all` true; `timeout` means the selection took over 30 seconds and `busy` that one for this repository is still running, and `repowise impacted-tests` gives the answer); `run_all` true means no subset can be vouched for, with up to three `reasons` (`reasons_total` counts them all). `degraded` means the index predates files changed outside the change and the selection holds over half the test files; the list stands, `summary` says so, and the directive asks for every test. `tests_to_run` (capped at ten, `total` and `truncated`) is in `repowise impacted-tests`' [run order](CLI_REFERENCE.md#repowise-impacted-tests-revspec), the `always_run_total` tests that run with every subset last. `broadcast_total` counts the tests that run only because a conftest on a route keeps every test under it, and `import_closure_total` those the change reaches only through imports, more than one file away, with no call path; both are left out of `tests_to_run` and `total` and still run. When most of the suite is to run anyway, the list's tail is not stored for recovery. With `run_all` the list is what to run first. `tests_to_run_kind` is `test_id` when a coverage node id is listed, else `test_file`. `basis` is `measured` when coverage decided a changed file, `inferred` when only the graph or a rule did, `none` when nothing named a test. `include=["tests"]` adds `why` (each listed file's reason) and `basis_by_file`, the evidence per changed file (`coverage`, `changed-test`, `call-graph`, `import-graph`, `conftest`, `full-run`, `no-tests-needed`, ...). With a coverage map, `map_present` is true and `line_coverage` buckets the scored files' changed lines, matched on the side of the diff the map was measured at (by file when it was measured at neither): `untested_changes`, `stale_test_candidates` (covered lines whose test file is absent from the diff), `covered`, `no_coverage_data`. Build the measured map with `pytest --cov=<package> --cov-context=test` (needs pytest-cov) and `repowise coverage add`.
+| Field | Meaning |
+|-------|---------|
+| `scope` | Changed, eligible, analysed, skipped, failed counts |
+| `status` | `available`, `partial` or `unavailable`; `partial` is never a clean bill |
+| `introduced`, `worsened`, `resolved` | Totals |
+| `top_findings`, `findings_total` | Three most actionable, and the count |
+| `files`, `files_total` | Up to 10 files, largest structure move first |
+| `score_basis`, `score_change` | `structure_only`; nloc-weighted score change |
+
+Skips:
+
+- Docs and config (Markdown, JSON, YAML, TOML and similar): `not_code`, never `partial`. A change of only these reads `clear_in_analyzed_scope` with a headline saying health does not cover them.
+- Tree-sitter queries (`.scm` under `queries`) and templates (`.j2`, `.jinja`, `.jinja2`, `.tmpl`, `.tpl`, `.hbs`, `.mustache`, `.ejs`, `.njk`): `not_analyzable_data`, never `partial`; alone they read `clear_in_analyzed_scope` with their own headline, since they can change behaviour.
+- HTML, schema and other files with no health dialect make a run `partial`.
+
+Findings name `dimension`, `biomarker`, `severity`, `path`, `symbol`, head-side `lines`, `reason` and `attribution` (`basis` `added_lines`, `changed_symbol`, `changed_call_edge`, `new_file`, `file_change`, `context_change` or `unknown`, plus `confidence`).
+
+- Identity ignores line numbers, so moved code introduces nothing. Ids are bound to the two revisions; pass one as `finding_id` to expand it.
+- A match to a stored finding carries `health_reference` for `get_health(finding_id=...)`. Performance findings carry `opportunity_id`, ordered by opportunity rank.
+
+Files rows: `base_score`, `head_score`, `nloc_base`, `nloc_head` (null on a missing side); `base_structure`/`head_structure` with diagnostics. Each score is 10 minus the structure deduction, as `get_health(counts="code_shape")`, from passes reading no history or coverage. A deleted file has a base-only row, with `moved_to` when split.
+
+`score_change` (base-nloc weighted, so a growing improved file keeps its gain): `base`, `head`, `delta` (two decimals), `structure_delta` (moves even at the 1.0 floor), `files_compared`.
+
+### impacted_tests
+
+The `repowise impacted-tests` selection over every touched path, ignoring the score's filters, less repowise output (the index, and managed files changed only in repowise's block), which the CLI reads when tracked.
+
+| Field | Meaning |
+|-------|---------|
+| `status` | `selected`, `run_all`, `degraded`, or a nothing-selected reason |
+| `run_all`, `reasons`, `reasons_total` | No subset can be vouched for; up to 3 reasons |
+| `tests_to_run`, `total`, `truncated` | Max 10, in [run order](CLI_REFERENCE.md#repowise-impacted-tests-revspec); `always_run_total` tests last |
+| `broadcast_total`, `import_closure_total` | Left out of the list and `total`, still run (as in `get_risk`) |
+| `tests_to_run_kind` | `test_id` when a coverage node id is listed, else `test_file` |
+| `basis` | `measured`, `inferred` or `none`, as in `get_risk` |
+| `why`, `basis_by_file` | `include=["tests"]`: per-file reason and evidence |
+| `map_present`, `line_coverage` | With a coverage map |
+
+- **Nothing-selected statuses:** `no_index`, `unknown`, `config_invalid`, `timeout` (over 30 seconds), `busy` (another selection running), `no_source_line_changes`; each sets `run_all`, and `repowise impacted-tests` gives the answer.
+- **`degraded`:** the index predates files changed outside the change and the selection holds over half the tests. The list stands, `summary` says so, and the directive asks for every test.
+- With `run_all` the list is what to run first. When most of the suite runs anyway, the tail is not stored for recovery.
+- **`basis_by_file`** values: `coverage`, `changed-test`, `call-graph`, `import-graph`, `conftest`, `full-run`, `no-tests-needed`, ...
+- **`line_coverage`** buckets changed lines (matched on the side the map was measured at, else by file): `untested_changes`, `stale_test_candidates` (covered lines whose test is absent from the diff), `covered`, `no_coverage_data`. Build the map with `pytest --cov=<package> --cov-context=test` (pytest-cov) and `repowise coverage add`.
+
+### patch_coverage
+
+Present when coverage is stored. With a gate set and coverage measured at head, it is the computation and JSON `repowise coverage check --format json` gates on. Otherwise: `status` (`measured`, `not_measured`), `freshness`, nonzero `file_counts`, and totals and `files` when a changed file was measured; diagnostics keep the full shape.
+
+- `patch_coverage_pct` is null when no changed line is executable. Unnamed files read `not_in_report`.
+- `scope.freshness` `stale`: measured at another commit; files changed since read `stale_file` with no figures.
+- `path_gates` judges the path-scoped gates in `coverage.gates`.
+- File rows carry `risk` (`fix_pressure`, `dependents`, `hotspot`, `bug_magnet`, `risky`, `reasons`, `basis`) and up to 8 `hints` per uncovered range: `range`, `symbol`, up to 3 `tests` to extend, `basis` `per_test` (measured), `call_graph` or `import_graph` (inferred).
+- Without `revspec` it covers what a push would bring, from the merge-base with the default branch.
+
+### fix_history
+
+- `is_fix` is a keyword rule on the subject, not the conventional-commit type.
+- `overlap` (needs an index), per file: `fix_count`, `overlapping_lines` (`approximate`: past ranges use their own parent, so read "this area was patched before"), `last_fix_days_ago`, `changed_lines`, `share_of_change`.
+- `concentration` names a file holding at least half the changed lines.
+- Never names the commit that introduced a bug; absent without fix history.
+
+### branch_overlap
-**patch_coverage.** Present when the index stores coverage. With a gate set and coverage measured at the change's head, it is the same computation and JSON shape `repowise coverage check --format json` gates on. Otherwise it reads `status` (`measured` or `not_measured`), `freshness` and the nonzero `file_counts`, plus the totals and `files` when a changed file was measured; `include=["diagnostics"]` keeps the full shape. `patch_coverage_pct` is null when no changed line is executable; files the report never names read `not_in_report`. `scope.freshness` is `stale` when coverage was measured at another commit than the change's head; then a file git shows changed since that commit reads `stale_file`, with no figures, and only untouched files keep theirs. `path_gates` judges the path-scoped gates in `coverage.gates`. Each file row carries `risk` (`fix_pressure`, `dependents`, `hotspot`, `bug_magnet`, `risky`, `reasons`, `basis`) and up to eight `hints` per uncovered range: `range`, `symbol`, up to three `tests` to extend, and a `basis` of `per_test` (measured), `call_graph` or `import_graph` (inferred). Without a `revspec`, it covers everything a push would bring, diffed from the merge-base with the default base branch.
+Git-only, no index needed. `branches[]`: `ahead`, `behind`, `last_commit`, `files[]`, each with a `basis` (`same file` or a co-change pair with its `partner`). Scans the newest 50 branches; `scanned`, `total`, `truncated` describe the scan. Absent when no branch shares a file, or on scan timeout.
-**fix_history.** `is_fix` applies a fixed keyword rule to the commit subject, not the conventional-commit type. `overlap` adds a diff-shape filter and needs an index: per file, `fix_count`, `overlapping_lines` (labelled `approximate`: past fix ranges are numbered against their own parent commit, so read it as "this area was patched before"), `last_fix_days_ago`, `changed_lines` and `share_of_change`. `concentration` names a file holding at least half the changed lines. The block never names the commit that introduced a bug, and is absent on an index with no fix history.
+### independent_changes
-**branch_overlap.** Git-only, so it works without an index. Each `branches[]` entry has `ahead`, `behind`, `last_commit` and `files[]`; each file row states its `basis` (`same file`, or a co-change pair with its `partner`). The scan covers the newest 50 branches; `scanned`, `total` and `truncated` describe the scan, not a cap. Absent when no other branch edits a shared file, or when the scan times out.
+Groups changed files over index edges, co-change pairs and (for a range) shared commits; docs, config, data and tests are never grouped. `groups[]` has `files` and `bridging_files`; `ungrouped_files` and `summary` say what was left out and why; `basis` says what was checked. Absent when the diff is one change.
-**independent_changes.** Groups changed files by connectivity over index edges, co-change pairs, and (for a range) shared commits. Docs, config, data files and tests are never grouped. Each `groups[]` entry lists `files` and `bridging_files`; `ungrouped_files` and `summary` name what was left out and why; `basis` states what was checked. Absent when the diff is one change.
+### cross_repo
-**cross_repo.** `consumers[]` names each contract link (`provider_file`, consumer `repo`, `file`, `contract_id`, `contract_type`, `match_type`) and a `tests` block (`state` of `measured`, `inferred`, `none` or `unresolved`, up to five `tests_to_run`). `breaking_changes[]` carries `contract_id`, `kind`, `severity`, `detail` and `impacted_repos`; `breaking_changes_available` says whether detection ran, so an empty list is not an all-clear. Absent outside workspace mode or when the change touches no published file.
+- `consumers[]`: `provider_file`, consumer `repo`, `file`, `contract_id`, `contract_type`, `match_type`, and `tests` (`state` `measured`, `inferred`, `none` or `unresolved`; up to 5 `tests_to_run`).
+- `breaking_changes[]`: `contract_id`, `kind`, `severity`, `detail`, `impacted_repos`. `breaking_changes_available` says whether detection ran, so empty is not an all-clear.
+- Absent outside workspace mode or when no published file changed.
---
@@ -304,19 +518,20 @@ Every float is rounded to 4 significant digits. Direct rows' `structural_score`
| Field | Meaning |
|-------|---------|
-| `decisions` | Accepted records: someone accepted each in a recorded event. Treat as constraints |
-| `candidates` | Inferred records nobody accepted. Hints, never rules; `candidates_note` says so. At most 3 |
-| `history` | Accepted, then withdrawn. At most 2 |
-| `answer_basis` | Strongest lane served: `decision`, `episode`, `rationale`, `archaeology`, `documentation`, `candidate`. Only `decision` is a ruling |
+| `decisions` | Accepted in a recorded event. Treat as constraints |
+| `candidates` | Inferred, never accepted: hints, not rules (`candidates_note`). Max 3 |
+| `history` | Accepted, then withdrawn. Max 2 |
+| `answer_basis` | Strongest lane: `decision`, `episode`, `rationale`, `archaeology`, `documentation`, `candidate`. Only `decision` rules |
| `authority` | Per row: `accepted` or `candidate` |
-| `currency` | On accepted records: `active`, `needs_review` (files moved, still binds), `uncheckable` (names nothing), `superseded`, `dismissed`. Candidates carry `review_state: "open"` instead |
-| `alignment` | Path mode: `active_count`, `deprecated_count`, `uncheckable_count`, `candidate_count`, summing to `governing_count`. `score` comes from `active_count` alone |
-| `git_archaeology` | Present when no decision governs the path. `git_log` keeps its first five rows (the file's newest commits); the rest are recoverable through the omission marker |
-| `provenance`, `evidence_refs` | Self-contained evidence references. Matching ids mean shared evidence, not independent corroboration. Commit rows under `git_archaeology` and `origin_story.key_commits` inherit the block's `provenance` rather than repeating it per row |
+| `currency` | Accepted rows: `active`, `needs_review` (files moved, still binds), `uncheckable` (names nothing), `superseded`, `dismissed`. Candidates: `review_state: "open"` |
+| `alignment` | Path mode: `active_count`, `deprecated_count`, `uncheckable_count`, `candidate_count` (sum `governing_count`); `score` from `active_count` |
+| `git_archaeology` | No decision governs the path; `git_log` keeps its 5 newest rows, rest via the omission marker |
+| `provenance`, `evidence_refs` | Self-contained evidence refs. Matching ids mean shared evidence, not corroboration |
-Read the lane, not `status`: a record can carry `status: "active"` with no acceptance behind it. Only `repowise decision confirm` or a committed ADR marked accepted produces an acceptance.
-
-The `candidates` and `history` lanes shed first under budget pressure, so an absent lane may mean the budget was tight. The health dashboard (no arguments) returns stale decisions, conflicts, ungoverned hotspots, `retired_decisions` and `unscoped_decisions` (five rows each, full sizes in `counts`).
+- Commit rows under `git_archaeology` and `origin_story.key_commits` inherit the block's `provenance`.
+- Read the lane, not `status`: `status: "active"` can lack acceptance. Only `repowise decision confirm` or a committed ADR marked accepted accepts.
+- `candidates` and `history` shed first under budget, so an absent lane may mean a tight budget.
+- The dashboard (no arguments): stale decisions, conflicts, ungoverned hotspots, `retired_decisions`, `unscoped_decisions`, five rows each, sizes in `counts`.
---
@@ -324,22 +539,27 @@ The `candidates` and `history` lanes shed first under budget pressure, so an abs
| Field | Meaning |
|-------|---------|
-| `content_md` | The overview essay's summary section; the full essay with `include=["content"]` |
-| `key_modules` | One row per topmost module page (a package or top-level directory), in outline order, up to 12: name, path, outline section, `package` when the page sits inside one, and `pages` beneath it |
-| `entry_points` | Detected entry points with build and CI tooling set aside, each package's together |
-| `architecture` | Layer names, file counts and `root` (the directory holding most of the layer, when one does) in stack order, test layer left out |
-| `commands` | Build, test, lint, dev, format and typecheck commands read from manifests: `"."` for the root, plus each package that names a task the root does not |
-| `code_health` | Headline score and band, `production_average` (non-test files, when the reading holds tests), hotspot health, worst file, open findings, `code_files` (every code file health read; `files_scored` when some carry no score) and `files_by_band` |
-| `git_health` | Hotspot count, churn trend and `riskiest_files`: five paths, bug magnets first, then fix mass, then churn |
-| `next_actions` | The first three stored actions (`id`, `tier`, `title`, a one-line `impact`, `target`) for the week, or the quarter when the week is empty, with each horizon's `total`. `include=["actions"]` serves both horizons with `done_when` and `by_tier`. `get_health(fix_id="act_...")` opens one in full |
-| `more` | Names the opt-in blocks |
-| `workspace` | Workspace mode footer |
+| `title`, `content_md` | Summary section; full essay with `include=["content"]` |
+| `key_modules` | Up to 12 topmost module pages in outline order: name, path, section, `package`, `pages` |
+| `entry_points` | Detected entry points, build and CI tooling set aside, grouped by package |
+| `architecture` | Layers in stack order (names, file counts, `root`), no test layer, plus `dependencies` |
+| `commands` | Build, test, lint, dev, format, typecheck from manifests: `"."` plus packages naming a task the root lacks |
+| `code_health` | Score, band, `production_average`, hotspot health, worst file, open findings, `code_files`, `files_scored`, `files_by_band` |
+| `git_health` | Hotspot count, churn trend, `riskiest_files` (5: bug magnets, then fix mass, then churn) |
+| `next_actions` | First 3 actions for the week (or quarter): `id`, `tier`, `title`, `impact`, `target`, plus each horizon's `total` |
+| `more`, `workspace` | Opt-in block names; workspace footer |
+
+- **`dependencies`:** the ten heaviest package edges (`from`, `to`, `verb`, `weight`), `edges_total` when more; absent in a single-package repo.
+- **`code_health`:** `production_average` when tests are in the reading; `files_scored` when some files have no score.
+- **`next_actions`:** `include=["actions"]` serves both horizons with `done_when` and `by_tier`; `get_health(fix_id="act_...")` opens one.
+- **`repo="all"`:** each repo has `summary` (essay's first sentence), `code_files` (its `code_health.code_files`, or graph code files before health runs) and `symbol_count`; `total_code_files` sums them.
-With `repo="all"`, each repo row carries `summary` (the overview essay's first sentence), `code_files` (the same count as that repo's `code_health.code_files`, or its graph's code-language files before health has run) and `symbol_count`; `total_code_files` sums them.
+Opt-in blocks, computed only when named: `outline` (page tree, two levels), `tour` (`guided_tour`, `reading_order`), `decisions` (`key_decisions`), `graph` (`community_summary`), `ownership` (`knowledge_map`), `components`, `changes`, `actions`, `tools` (`tool_surface`), `scope` (whole `_meta.index_scope`).
-Opt-in blocks: `outline` (wiki page tree, two levels), `tour` (`guided_tour`, `reading_order`), `decisions` (`key_decisions`), `graph` (`community_summary`), `ownership` (`knowledge_map`), `components`, `changes`, `actions`, `tools` (`tool_surface`), `scope` (the whole `_meta.index_scope`). They are not computed unless named.
+**changes:** Change Records in a 90-day `window` (`since`, `until`) ending at the newest merge: `total`, `by_category` (largest first), `by_week` (`{week, changes}`, Monday weeks, zeros included), and `provenance` (`agent_changes`, `human_attested_changes`, `unknown_changes`, `coverage`, `agent_share`, `summary`).
-**changes.** Change Records over a 90-day `window` ending at the newest merged change (`since`, `until`): `total`, `by_category` (largest first), `by_week` (`{week, changes}` per week starting Monday, zero weeks included) and `provenance` over changes: `agent_changes`, `human_attested_changes`, `unknown_changes`, `coverage`, `agent_share` and `summary`. Below 30% coverage `agent_share` is null with `suppressed_reason`, and the agent and human-attested counts are left out. A change stored without a label counts as unknown, never human. `{"total": 0}` when no Change Records are stored; `provenance` is `{"unavailable": "attribution_off"}` with attribution off. Grouped by change and category only, never by person.
+- Below 30% coverage `agent_share` is null with `suppressed_reason` and agent and human-attested counts are dropped. Unlabelled changes count as unknown.
+- `{"total": 0}` with no records; `provenance` is `{"unavailable": "attribution_off"}` with attribution off. Never grouped by person.
---
@@ -347,9 +567,18 @@ Opt-in blocks: `outline` (wiki page tree, two levels), `tour` (`guided_tour`, `r
### Modes and identity
-`mode` is `dashboard` (no targets), `targeted`, `fix_item` (`fix_id`), `action` (an `act_` `fix_id`: the Do next action with its `details` and `commands`), or `conflict` (two selectors passed). `unresolved` names targets that matched nothing, with a reason: `not_indexed`, `no_such_path`, `excluded`, `not_measured`, `no_such_module` (which also returns `known_modules`). A `no_such_path` entry adds `removed_by_commit` and `moved_to` (the file or files that replaced it) when git history explains the miss. `mode`, `_meta`, `unresolved`, `known_modules` and every kept list's `*_total` survive any `only` projection. `scope` and `counts` are echoed on the response.
+| `mode` | When |
+|--------|------|
+| `dashboard` | No targets |
+| `targets` | With `targets` |
+| `fix_item`, `action` | `fix_id` `fix1_...`; `act_...` (the Do next action, with `details`, `commands`) |
+| `finding`, `refactoring_plan`, `refactoring_opportunity`, `performance_opportunity` | An id lookup |
+| `refactoring_evidence`, `performance_evidence` | Paging an opportunity's evidence |
+| `conflict` | Two selectors passed |
-`_meta.health_analysis` labels the result as stored analysis that this call did not recompute. Its `status` is `available`, `provenance_unknown` (metrics exist but no row recorded their commit) or `unavailable`. `_meta.health_analyzed_at` and `_meta.health_analyzed_commit` date the health pass, which can lag indexing; `_meta.health_analyzed_commits_distinct` appears when rows come from several passes.
+- `unresolved` reasons: `not_indexed`, `no_such_path` (with `removed_by_commit` and `moved_to` when git explains it), `excluded`, `not_measured`, `no_such_module` (with `known_modules`).
+- `mode`, `_meta`, `unresolved`, `known_modules` and every kept list's `*_total` survive `only`. `scope` and `counts` are echoed.
+- `_meta.health_analysis`: stored analysis, not recomputed; `status` `available`, `provenance_unknown` (no row recorded the commit) or `unavailable`. `_meta.health_analyzed_at` / `_commit` date the pass, which can lag indexing; `_meta.health_analyzed_commits_distinct` when rows span passes.
### fix_first
@@ -357,43 +586,49 @@ One ranked queue across refactoring, performance and code-shape work, the same o
| Field | Meaning |
|-------|---------|
-| `lead` | The queue's first item, whatever page `items` is, with its `next_call` |
-| `items` | Up to five. With `only=["fix_first"]` the list pages from `cursor` and `recovery.fix_first` names the next page; a passed `limit` sets the page size, up to 25. Each: `id`, `tier`, `kind`, `title`, `target`, `why`, `gain`, `effort`, `confidence`; a `now` or `next` `lead` also carries `first_step` (`action`, `line`, and `file` when it is not the target's) and `verify` (`command`, or `prerequisite` when no test reaches it); with `only=["fix_first"]` the other due items among a page's first five carry them too. `get_health(fix_id=...)` returns one in full, with its `next_call` |
-| `items_total`, `cursor` | The eligible items `items` was cut from, and where the page starts |
-| `counts` | `inventory` (every unit considered), `in_scope` (less units excluded for where the code lives: `test`, `tooling`, `generated`, `vendored`, `docs_example`), `eligible` (became an item), `due` (eligible items in tier `now` or `next`), `shown` (items in this response), `excluded` (every non-zero exclusion, by reason), `gated` (units a language gate holds back, counted in `inventory` only; always 0 here, since Fix first applies no gate) |
-| `tier` | `now` (worth doing, safe to start), `next` (worth doing, needs judgment), `later` |
-| `kind` | `refactor` (one file's composed refactoring), `perf_fix` (one intervention with its sinks), `finding` (a code-shape finding with no plan) |
-| `totals` | `candidates`, `eligible`, `shown`, and `dormant`: distinct functions kept out as `gated_off`. The exclusions by reason are in `counts.excluded` (`gated_off`: a constant flag in the same file switches the function off; `unreachable`: sure dead code, delete it) |
-| `by_improves`, `detail_call` | Rollup, and the call that opens the lead in full; the analysed commit and time are in `_meta.health_analysis` |
-
-Findings, performance causes and refactoring plans carry the same count object when their list is named in `only`: `top_findings_counts`, `performance_opportunities_counts`, `refactoring_plans_counts`. The CLI and dashboard report the same numbers.
-
-`top_findings_counts` is the Fix first queue's judgement of the scoring findings (performance and zero-impact findings are not queue units), while `top_findings` ranks every open production finding by impact, so `top_findings_total` can exceed `in_scope` and its `shown` (rows listed) can exceed `eligible`.
-
-Items are ordered by value first, then tier. History markers (churn, ownership, co-change, prior fixes) never create or lead an item; they ride on an item under `context`, and history-only files count under `counts.excluded.history_only`. `fix_first` always describes production code, whatever `scope` says; `limit` caps the items, never which leads.
+| `lead` | The queue's first item on any page, with `next_call` |
+| `items` | Up to 5: `id`, `tier`, `kind`, `title`, `target`, `why`, `gain`, `effort`, `confidence` |
+| `items_total`, `cursor` | Eligible items, and the page start |
+| `counts` | The funnel; see below |
+| `tier` | `now` (safe to start), `next` (needs judgment), `later` |
+| `kind` | `refactor` (one file's composed refactoring), `perf_fix` (one intervention and its sinks), `finding` (code-shape, no plan) |
+| `totals` | `candidates`, `eligible`, `shown`, `dormant` (functions kept out as `gated_off`) |
+| `by_improves`, `detail_call` | Rollup; call that opens the lead |
+
+- **Paging:** with `only=["fix_first"]`, `items` pages from `cursor` (`recovery.fix_first` names the next page) and `limit` sets the size, up to 25.
+- **Due items:** a `now`/`next` lead carries `first_step` (`action`, `line`, `file` if not the target's) and `verify` (`command`, or `prerequisite` when no test reaches it); with `only=["fix_first"]`, so do due items among the page's first five. `get_health(fix_id=...)` returns one in full.
+- **`counts`:** `inventory` (all units), `in_scope` (minus `test`, `tooling`, `generated`, `vendored`, `docs_example`), `eligible`, `due` (`now` or `next`), `shown`, `excluded` (non-zero, by reason: `gated_off` for a same-file constant flag switching it off, `unreachable` for sure dead code, `history_only`), `gated` (counted in `inventory` only; always 0, since Fix first applies no gate).
+- Lists named in `only` carry the same count object: `top_findings_counts`, `performance_opportunities_counts`, `refactoring_plans_counts`, matching the CLI and dashboard.
+- `top_findings_counts` judges scoring findings as queue units (not performance or zero-impact); `top_findings` ranks every open production finding, so `top_findings_total` can exceed `in_scope` and `shown` can exceed `eligible`.
+- Ordered by value, then tier. History markers (churn, ownership, co-change, prior fixes) never create or lead an item; they ride under `context`. Always production code, whatever `scope`; `limit` never changes the lead. Analysed commit: `_meta.health_analysis`.
### Dashboard and metric rows
| Field | Meaning |
|-------|---------|
-| `kpis` | Hotspot health, `average_health` (NLOC-weighted), `average_health_unweighted`, `average_health_weighting`, pillar averages, `production_average` (production code alone; only while tests are in `average_health`), `worst_performer_path`, `worst_test_path`, `performance_causes` (`now` in the default queue, `production`, `all`, and `per_10k_loc` over covered lines; see [PERFORMANCE.md](../layers/PERFORMANCE.md#the-default-queue)) |
-| `unanalysed_file_count` | Files in a language health has no dialect for, stored with no score and left out of every figure; absent when there are none |
-| `kpis.band`, `kpis.analysed_share` | The headline band is `null` when fewer than half the code files were analysed, since the average then speaks for a sample; `analysed_share` (scored over all code files) appears when some were left out. `get_overview` reports `code_health` the same way |
-| `gap_analysis` | Weighted points the average must recover to reach 8.0, files below it, `files_to_reach_target`, `files_for_half_gap`, `weighted_gap_points`, `weighted_gross_gap_points` |
+| `kpis` | Averages and worst-file pointers |
+| `kpis.band`, `kpis.analysed_share` | Band (`null` under half analysed); scored share when some left out |
+| `unanalysed_file_count` | Files with no health dialect, unscored and excluded; absent when none |
+| `gap_analysis` | Recovery to 8.0: points, files below, `files_to_reach_target`, `files_for_half_gap`, `weighted_gap_points`, `weighted_gross_gap_points` |
| `worst_files`, `test_worst_files` | Lowest raw scores, production and test |
-| `high_leverage_files` | Ranked by `weighted_deficit`, with `share_of_repo_gap_pct` |
-| `top_findings` / `findings`, `test_findings` | Production and test findings; their totals sum to the whole open set |
-| metric row | `score` (defect dimension and headline), `maintainability_score`, `performance_score`, `weighted_deficit` = (8 - score) x NLOC, `is_test`, `has_test_file`, `primary_biomarker`, `total_deduction`, `structure_deduction` and `history_deduction` (the score is 10 minus both, before the 1.0 floor; history reads 0.0 under `counts="code_shape"`), `history: "short"` only when the file has fewer than 5 recorded commits (new, split out, or renamed without follow), where most history markers cannot fire yet, and `withheld_deduction` when part of it comes from a withheld finding type |
+| `high_leverage_files` | By `weighted_deficit`, with `share_of_repo_gap_pct` |
+| `top_findings` / `findings`, `test_findings` | Production and test; totals sum to the open set |
+| metric row | One file's scores and deductions |
-`weighted_deficit` and the gap fields share one unit, score points x NLOC; they compare only with each other. `primary_biomarker` prefers a discrete finding over the continuous `coverage_gradient`. A finding's `details.actions` (an agent prompt and the rule that silences it) appear only on the single-finding view, `finding_id=...`. Each finding carries a `dimension`; `advisory` findings (`assertion_free_test`, `mock_saturated_test`, `hidden_coupling`, `brain_method`, `untested_complexity`) never deduct and appear only with `include=["advisory"]`.
+- **`kpis`:** hotspot health, `average_health` (NLOC-weighted), `average_health_unweighted`, `average_health_weighting`, pillar averages, `production_average` (while tests are in the average), `worst_performer_path`, `worst_test_path`, `performance_causes` (`now`, `production`, `all`, `per_10k_loc`; see [PERFORMANCE.md](../layers/PERFORMANCE.md#the-default-queue)). `get_overview` reports bands the same way.
+- **Metric row:** `score` (defect, headline), `maintainability_score`, `performance_score`, `weighted_deficit` = (8 - score) x NLOC, `is_test`, `has_test_file`, `primary_biomarker`, `total_deduction`, `structure_deduction`, `history_deduction`, `withheld_deduction`, `history: "short"` (under 5 commits, so most history markers cannot fire).
+- Score = 10 minus structure and history deductions, floored at 1.0; history is 0.0 under `counts="code_shape"`. Deficit and gap fields share score points x NLOC and compare only with each other.
+- `primary_biomarker` prefers a discrete finding over `coverage_gradient`. `details.actions` (agent prompt, silencing rule) appear only with `finding_id=...`.
+- Each finding has a `dimension`. `advisory` findings (`assertion_free_test`, `mock_saturated_test`, `hidden_coupling`, `brain_method`, `untested_complexity`) never deduct and need `include=["advisory"]`. `mode: "targets"` is not split by test.
-Provisional finding types appear only with `include=["unverified"]`, each marked `verification: "unverified"`. A withheld type never lists but still lowers the score it was counted in, so a file row reports it as `withheld_deduction` and `_meta.withheld` names the type, its count and why it is held back. Targeted mode is never split into production and test.
+### Held-back findings
-A layer on a language is gated, preview or ungated (no row), one row each in `finding_registry.py`. Gated rows are held back pending verification: still stored and addressable by id, counted in `_meta.gated` per layer and language, and listed with `include=["unverified"]`. Preview rows are served and counted like any other, and `_meta.preview` gives `{layer: {language: note}}` once for the cells a response lists, where the note is the measurement (for example `preview, measured 22% precision on 55 judged plans from 2 Java repos, 2026-10-15`). Nothing is gated today: health is ungated on Java, C# and C and preview on C++, and refactoring, performance and dead code are preview on Java, C#, C and C++ (dead code on Kotlin and Swift too).
-
-Health findings on files the index stores as vendored or generated are held back the same way, in every language: that code is changed upstream or by its generator. `_meta.gated.health` counts them under `vendored` and `generated` as plain numbers, and `_meta.gated.reasons` gives each reason once when the call lists no finding. Scores, KPIs and the worst-file order still count them.
-
-On test files, history markers (ownership, churn, change entropy, co-change and the other git-derived kinds) are held back too, counted under `test_history`: they describe how a test changes, not a defect in it. Code-shape findings on tests are still listed. On every other file they are held back from finding lists and counts under `history`: they order hotspots and Fix first, and `get_risk` still lists them.
+- **Provisional types:** only with `include=["unverified"]`, marked `verification: "unverified"`.
+- **Withheld types:** never listed but still deduct; rows show `withheld_deduction` and `_meta.withheld` names type, count and reason.
+- **Language gates:** per layer and language, gated, preview or ungated (no row), in `finding_registry.py`. Gated rows are stored, addressable by id, counted in `_meta.gated`, listed with `include=["unverified"]`. Preview rows are served; `_meta.preview` gives `{layer: {language: note}}` with the measurement (e.g. `preview, measured 22% precision on 55 judged plans from 2 Java repos, 2026-10-15`).
+- Nothing is gated. Health is ungated on Java, C#, C and preview on C++; refactoring, performance and dead code are preview on Java, C#, C, C++ (dead code also Kotlin, Swift).
+- **Vendored and generated files:** findings held back in every language (changed upstream or by a generator), counted in `_meta.gated.health` under `vendored` and `generated`; `_meta.gated.reasons` explains once when nothing is listed. Scores, KPIs and worst-file order still count them.
+- **History markers** (ownership, churn, change entropy, co-change, other git kinds): on tests, held back under `test_history` (code-shape findings still list); elsewhere, held from finding lists under `history`, though they order hotspots and Fix first and `get_risk` lists them.
### Opt-in blocks
@@ -401,38 +636,53 @@ On test files, history markers (ownership, churn, change entropy, co-change and
|-----------|------|
| `biomarkers` | Findings in dashboard mode |
| `refactoring` | `refactoring_opportunities`, `suggestion_legend` |
-| `trend` | Snapshot diff and declining or predicted-decline alerts |
-| `coverage` | Stored coverage rows and summary |
-| `accuracy` | `defect_accuracy`: of the K least-healthy files, how many were recently bug-fixed versus the base rate (precision@K, `lift`). `null` on repos with too little history |
-| `signals` | Targeted mode: per-file prior defects, change scatter, 90-day churn, owners, graph degree. `null` per missing field, never an imputed zero |
-| `churn_complexity` | One point per recently changed file: commits, max CCN, NLOC, score, churn percentile |
-| `untested_complexity` | Functions ranked by CRAP, worst first: `crap`, `ccn`, `coverage_basis`, then `coverage_pct` when measured or `coverage_tier` (`direct`, `reached`, `none`) when estimated, never both; estimated rows only with `include=["unverified"]` |
-| `doc_drift` | `findings` naming the document to edit, its line, the `target` it wrongly claims, `reason`, `kind`, `confidence`, optional `suggestion`; plus `findings_total`, `documents`, `basis`. A finding is evidence to check, not a proven defect |
-| `semantics` | `_meta.health_semantics`: the legend for deficit points and percentiles |
-| `what_if` | Up to 10 worst files (or the targets), each with `ceiling` (the score with no structure deduction left, history's cap shrinking with it: the most an edit can reach), `target_out_of_reach` when that is below 8.0, `fix_all_structure` gains and its top 3 `findings`; `top_fixes` ranks single fixes across them. Each fix has `points` (its impact, an upper bound when its category is at its cap) and `gain`: `file`, `average` (headline points) and `hotspot` (when the file is a hotspot). `structure_deduction` can include withheld finding types no listed fix accounts for |
-| `performance`, `defect`, `maintainability`, `advisory` | Filter findings to one dimension; `performance` also adds the performance queue |
-
-`only` aliases: `biomarkers` -> `findings`, `accuracy` -> `defect_accuracy`, `refactoring` -> `refactoring_plans`. Dimension names have no single key and land in `unknown_only_keys`, beside `unknown_only_keys_hint`; for `signals` in targeted mode, name `metrics`.
+| `trend` | Snapshot diff; declining or predicted-decline alerts |
+| `coverage` | Coverage rows and summary; see [Coverage](#coverage) |
+| `accuracy` | `defect_accuracy`: precision@K of least-healthy files recently bug-fixed vs base rate, `lift`; `null` with little history |
+| `signals` | Targeted: prior defects, change scatter, 90-day churn, owners, graph degree; `null` per missing field |
+| `churn_complexity` | Recently changed files: commits, max CCN, NLOC, score, churn percentile |
+| `untested_complexity` | Functions by CRAP: `crap`, `ccn`, `coverage_basis`, and `coverage_pct` (measured) or `coverage_tier` (`direct`, `reached`, `none`) |
+| `doc_drift` | `findings` (document, line, wrong `target`, `reason`, `kind`, `confidence`, `suggestion`), `findings_total`, `documents`, `basis` |
+| `semantics` | `_meta.health_semantics`: legend for deficit points and percentiles |
+| `what_if` | Up to 10 worst files (or targets) with `ceiling` and fixes |
+| `unverified`, `recipe` | Provisional and gated findings; `plan.recipe` with `plan_id` |
+| `performance`, `defect`, `maintainability`, `advisory` | One dimension; `performance` adds the queue |
+
+- **`untested_complexity`:** estimated tiers only with `include=["unverified"]`; never both measures.
+- **`doc_drift`:** evidence to check, not a proven defect.
+- **`what_if`:** `ceiling` is the score with no structure deduction (history's cap shrinking with it); `target_out_of_reach` when below 8.0; `fix_all_structure` gains, top 3 `findings`, and `top_fixes` across files. Each fix has `points` (upper bound when its category is capped) and `gain` (`file`, `average`, `hotspot`). `structure_deduction` may include withheld types no fix covers.
+- **`only` aliases:** `biomarkers` -> `findings`, `accuracy` -> `defect_accuracy`, `refactoring` -> `refactoring_plans`. Dimension names land in `unknown_only_keys` with `unknown_only_keys_hint`; for targeted `signals`, name `metrics`.
### Refactoring
-`refactoring_opportunities` holds one composed unit per file: `lead_biomarker`, `addresses_primary_problem` (`true`, `false`, or `null` when no dominant finding was recorded), ordered `steps` each with a `mechanical` or `judgment` applicability, and evidence counts. With no targets it lists what Fix first would take (`refactoring_scope: fix_first`); `refactoring_opportunities_hidden` counts the rest by reason and `refactoring_opportunities_scope` names the scope. A step with `relocated_by` refers to a symbol an earlier step moves: locate it again before applying.
+`refactoring_opportunities`: one unit per file with `lead_biomarker`, `addresses_primary_problem` (`true`, `false`, `null` without a dominant finding), ordered `steps` (`mechanical` or `judgment`) and evidence counts.
-`get_health(opportunity_id="refop...")` returns full steps, member plans, the validation profile and `next_actions`; `only=["refactoring_evidence"]` with `cursor` pages the evidence. `found` says whether the id matched; `status` is `open`, `acknowledged`, `resolved` or `false_positive`. `refactoring_summary` rolls up by type, effort, confidence and lifecycle.
+- Without targets it lists what Fix first takes (`refactoring_scope: fix_first`); `refactoring_opportunities_hidden` counts the rest by reason, `refactoring_opportunities_scope` names the scope.
+- A step with `relocated_by` names a symbol an earlier step moves: locate it again.
+- `refactoring_summary` rolls up by type, effort, confidence and lifecycle.
-`refactoring_plans`, returned only when named in `only`, lists the plans of the refactoring queue in queue order: each opportunity's steps together, in step order, under the same `refactoring_scope`, filters and view as `refactoring_opportunities`, up to 25 per page. A row is compact: `id` (for `plan_id` and `generate_refactoring_code`), `refactoring_type`, `file_path`, `target_symbol`, `line_start`, `line_end`, `effort_bucket`, `confidence`, `impact_delta`, `source_biomarker`, `opportunity_id`, `classification` (`mechanical` or `judgment`), `relocated_by` when set, and on a Split File plan `relocates`, the ids of the plans it relocates, which it stands for instead of listing them; `get_health(plan_id=...)` returns the plan in full (detector detail such as cohesion `groups` or `cut_edges`, `evidence`, `blast_radius`, validation), and for a plan the index resolved, its `payoff`. `refactoring_plans_total` and the page cursor count plans in scope, so a page that holds a Split File row can list fewer rows than the plans it covers, `refactoring_plans_opportunities_total` the opportunities they are steps of, `refactoring_plans_scope` names the scope and `refactoring_plans_hidden` counts what the `fix_first` scope leaves out, by reason. Performance plans are listed by `performance_opportunities`. An empty requested list has `refactoring_plans_status.reason`: `no_applicable_findings`, `plan_analysis_indeterminate`, `no_eligible_targets` or `analysis_unavailable`. See [REFACTORING.md](../layers/REFACTORING.md).
+- `opportunity_id="refop..."` returns full steps, member plans, validation profile, `next_actions`, `found`, and `status` (`open`, `acknowledged`, `resolved`, `false_positive`). `only=["refactoring_evidence"]` + `cursor` pages evidence.
+- `refactoring_plans` (only when named in `only`): the queue's plans in order, steps together, same scope, filters and view, up to 25 a page. Row: `id` (for `plan_id`, `generate_refactoring_code`), `refactoring_type`, `file_path`, `target_symbol`, `line_start`, `line_end`, `effort_bucket`, `confidence`, `impact_delta`, `source_biomarker`, `opportunity_id`, `classification`, `relocated_by`, and `relocates` on a Split File plan (ids it stands for).
+- `refactoring_plans_total` and the cursor count plans, so a Split File page can show fewer rows. Also `refactoring_plans_opportunities_total`, `refactoring_plans_scope`, `refactoring_plans_hidden` (by reason). Empty: `refactoring_plans_status.reason` `no_applicable_findings`, `plan_analysis_indeterminate`, `no_eligible_targets` or `analysis_unavailable`.
+- `plan_id=...` returns the full plan: detector detail (cohesion `groups`, `cut_edges`), `evidence`, `blast_radius`, validation, and `payoff` when resolved. Performance plans live in `performance_opportunities`. See [REFACTORING.md](../layers/REFACTORING.md).
### Performance
-Performance findings carry `health_impact: 0`; the pillar never blends into the score. They rank on an integer `perf_rank`, which weighs the marker (superlinear above per-iteration crossings above in-loop CPU), the boundary crossed (`details.boundary_kind`: subprocess, then network or database, then lock, then filesystem) and whether the loop crosses a function call (`details.cross_function`). It is an ordering key, not a score.
-
-A bare `get_health()` ranks performance work inside `fix_first` as `perf_fix` items. `get_health(opportunity_id="perf...")` adds `plan_steps`, `validation` and `siblings`; `only=["performance_evidence"]` with `cursor` pages the evidence. Ids are stable within a performance model version; an id from an older model resolves to `model_state.state: "stale_model"` with `refresh_required`. `lifecycle_status` is `open` or `resolved`. Evidence rows carry a public `finding_id`.
+Findings carry `health_impact: 0` and never blend into the score. `perf_rank` is an integer ordering key weighing the marker (superlinear > per-iteration crossings > in-loop CPU), the boundary (`details.boundary_kind`: subprocess, network or database, lock, filesystem) and `details.cross_function`.
-The `performance_opportunities` list holds causes whose cost is measured (`cost_proof` `proven`). A cause whose loop size nothing measured is `unproven`: it never sets `may_lead`, and every list leaves it out. `performance_summary.default_queue.excluded.unmeasured_cost` counts the ones the default queue drops, `performance_summary.proof` counts both values, and the `proof` facet counts them under the current filters. REST lists them with `proof=unproven` on `/api/repos/{id}/health/performance-opportunities`. The `growth_source` facet names the member loop that shows the cost grows (`loop`, `registry`, `cold_path`, `none`, `n/a`); `fix_first`, Do next and `performance_summary.lead` take only `plan_ready` causes with `loop` (or a per-call cause an entry point reaches), and `fix_first.totals.excluded.unconfirmed_cost` counts the rest.
+- Bare `get_health()` ranks them in `fix_first` as `perf_fix`. `opportunity_id="perf..."` adds `plan_steps`, `validation`, `siblings`; `only=["performance_evidence"]` + `cursor` pages evidence; rows carry a public `finding_id`.
+- Ids are stable per model version; older ones resolve to `model_state.state: "stale_model"` with `refresh_required`. `lifecycle_status` is `open` or `resolved`.
+- `performance_opportunities` holds `cost_proof` `proven` causes. `unproven` (loop size unmeasured) never sets `may_lead` and no list shows it; counted in `performance_summary.default_queue.excluded.unmeasured_cost`, `performance_summary.proof` and the `proof` facet. REST lists them with `proof=unproven` on `/api/repos/{id}/health/performance-opportunities`.
+- The `growth_source` facet (`loop`, `registry`, `cold_path`, `none`, `n/a`) names the loop showing growth. `fix_first`, Do next and `performance_summary.lead` take only `plan_ready` causes with `loop` (or per-call causes an entry point reaches); `fix_first.totals.excluded.unconfirmed_cost` counts the rest.
### Coverage
-`include=["coverage"]` returns per-file rows (`covered_line_count`, `total_coverable_lines`; targeted mode adds `covered_lines`) and a `summary`. `freshness.status` is `current` (measured at the indexed commit), `stale` or `unknown`. `report_paths` says how the report's entries mapped at ingest (`total`, `matched`, `unmatched`, `ambiguous`, `unmatched_sample`). `source_formats` lists merged formats. Dashboard mode adds `history`, one point per complete ingest, newest 10. Targeted rows add `decay`: `confirmed_lines`, `invalidated_lines` (now unknown, not uncovered), and `drifted` once a fifth of a file's measurement has moved.
+Per-file `covered_line_count`, `total_coverable_lines` (targeted adds `covered_lines`) and a `summary`.
+
+- `freshness.status`: `current` (at the indexed commit), `stale`, `unknown`. `source_formats` lists merged formats.
+- `report_paths`: ingest mapping `total`, `matched`, `unmatched`, `ambiguous`, `unmatched_sample`.
+- Dashboard `history`: one point per complete ingest, newest 10.
+- Targeted `decay`: `confirmed_lines`, `invalidated_lines` (unknown, not uncovered), `drifted` once a fifth has moved.
---
@@ -440,36 +690,58 @@ The `performance_opportunities` list holds causes whose cost is measured (`cost_
| Field | Meaning |
|-------|---------|
-| `tiers` | Findings by tier: `high` (0.7 and up), `medium` (0.4 to 0.7), `low`. Each has path, kind, confidence, line count, cleanup impact and a stable `id` |
-| `summary` | Totals over every open finding; `filtered_findings` counts what the filters kept; `filters` echoes non-default filters; `scope` says which is which |
-| `summary.withheld_types` | Provisional finding types held back; ask with `kind=` to see them, marked unverified |
-| `summary.gated` | Findings held back on a gated language, counted per language; `include_unverified=true` shows them. No language is gated today; dead code on Java, C#, C, C++, Kotlin and Swift is preview, labelled in `_meta.preview` |
-| `summary.call_resolution_basis` | Per language, how many call edges the index resolved and the share that are guesses: the graph the findings rest on |
+| `tiers` | `high` (0.7+), `medium` (0.4 to 0.7), `low`: path, kind, confidence, lines, cleanup impact, stable `id` |
+| `summary` | Totals over all open findings; `filtered_findings`, `filters` (non-default), `scope` |
+| `summary.withheld_types` | Provisional types; ask with `kind=` to see them, marked unverified |
+| `summary.gated` | Gated-language findings per language; `include_unverified=true` shows them |
+| `summary.call_resolution_basis` | Per language, resolved call edges and guess share |
| `by_directory`, `by_owner` | Rollups with `group_by` |
| `limit_note` | A `limit` over 25 was clamped |
-The 0.7 and 0.4 tier floors are shared by the CLI, the web UI and this tool. See [DEAD_CODE.md](../layers/DEAD_CODE.md).
+- No language is gated; dead code on Java, C#, C, C++, Kotlin and Swift is preview, labelled in `_meta.preview`.
+- Workspace mode lowers confidence on findings another repo imports.
+- The 0.7 and 0.4 floors are shared by the CLI, web UI and this tool. See [DEAD_CODE.md](../layers/DEAD_CODE.md).
---
## `list_repos`
-`workspace` (bool), `workspace_root`, `default_repo`, and per repo `alias`, config-relative `path` and `absolute_path`. In single-repo mode: `workspace: false`, `workspace_root: null`, `default_repo: "default"`.
+| Field | Meaning |
+|-------|---------|
+| `workspace`, `workspace_root`, `default_repo` | Mode, root, default alias |
+| `repos` | `alias`, `path` (config-relative), `absolute_path`, `is_default`; workspace adds `indexed_at`, `last_commit_at_index` |
+| `hint` | How to use `repo` here |
+
+Any of `alias`, `path`, `absolute_path` passes unchanged as `repo`. Single-repo mode: `workspace: false`, `workspace_root: null`, `default_repo: "default"`.
---
## Workspace tools
-**`get_blast_radius`.** Impacted services with `score` (0 to 1 relative path weight, uncalibrated), `distance` (hops), `structural` (a real dependency versus co-change only) and edge kinds; `impact_score_semantics`, `impacted_repos`, `structural_count`, `behavioral_count`, `total_impacted`, unresolved targets. `symbol_targets[].consumers[]` names consuming symbols across each contract link, each with a `tests` block shaped like `get_change_risk`'s.
+### `get_blast_radius`
+
+Impacted services with `score` (0 to 1 relative path weight, uncalibrated), `distance` (hops), `structural` (real dependency vs co-change only) and edge kinds; `impact_score_semantics`, `impacted_repos`, `structural_count`, `behavioral_count`, `total_impacted`, unresolved targets. `symbol_targets[].consumers[]` names consuming symbols per contract link, each with a `get_change_risk`-shaped `tests` block.
+
+### `get_architecture`
+
+`score` (1 to 10; higher is lower coupling, smaller core), `architecture_type` (`core-periphery`, `hierarchical`), `propagation_cost_pct` (share of other services the average service reaches), `core_size`, `core_ratio`, `core_members`, `cycle_count`, `conformance_violations`, `role_breakdown` (Core, Shared, Control, Peripheral), `summary`.
+
+### `get_conformance`
+
+`violations` (`source`, `target`, `rule_source` / `rule_target`, `edge_kind`), `cycles` (`nodes`, `length`), `violation_count`, `cycle_count`, `rules_evaluated`. A report that never ran says so, not zero counts.
+
+### `get_dependency_path`
+
+The path, or else nearest common ancestors, shared neighbours, community analysis and bridge suggestions.
-**`get_architecture`.** `score` (1 to 10, higher means lower coupling and a smaller core), `architecture_type` (`core-periphery` or `hierarchical`), `propagation_cost_pct`, `core_size`, `core_ratio`, `core_members`, `cycle_count`, `conformance_violations`, `role_breakdown` (Core, Shared, Control, Peripheral counts), `summary`.
+### `get_execution_flows`
-**`get_conformance`.** `violations` (offending `source` and `target` services, the `rule_source` / `rule_target` matchers that fired, `edge_kind`), `cycles` (`nodes`, `length`), `violation_count`, `cycle_count`, `rules_evaluated`. A report that never ran says so instead of returning zero counts.
+Scored entry points, each with a breadth-first call trace and whether it crosses community boundaries.
-**`get_dependency_path`.** The path when one exists; otherwise nearest common ancestors, shared neighbours, community analysis and bridge suggestions.
+### `generate_refactoring_code`
-**`get_execution_flows`.** Scored entry points, each with a breadth-first call trace and whether it crosses community boundaries.
+`suggestion_id`, `plan`, generated code and unified diff; or `generation: {available: false, reason: "disabled"}`; or `error: "no_provider"`.
-**`generate_refactoring_code`.** `suggestion_id`, `plan`, the generated code and unified diff, or `generation: {available: false, reason: "disabled"}`, or `error: "no_provider"`.
+### `set_finding_status`
-**`set_finding_status`.** The new status and its timestamp.
+The new status and its timestamp.
diff --git a/docs/start/CI.md b/docs/start/CI.md
index cd5a40aad..d2e0f685d 100644
--- a/docs/start/CI.md
+++ b/docs/start/CI.md
@@ -1,108 +1,83 @@
# Repowise in CI
-Five gates judge a pull request, each on what the change adds rather than on
-the whole repository's past:
-
-| Gate | Question | Needs | History |
-|------|----------|-------|---------|
-| `repowise coverage check` | Did the tests run the lines this change touched? | git and a coverage report | the merge-base with the target branch |
-| `repowise coverage check --fail-under-branches P` | Did the tests take the branches of the lines this change touched? | git and a report with per-line branch data | the merge-base with the target branch |
-| `repowise coverage check --max-drop P` | Did this change lower project coverage by more than P points? | git, a coverage report, and one measured at the change's base | the merge-base with the target branch |
-| `repowise doc-drift --check` | Does the documentation still describe files, links and commands that exist? | git | none (full history only improves rename suggestions) |
-| `repowise security check` | Did this change add a secret or a risky call? | git | every commit of the change |
-| `repowise health check` | Did this change write new complex, deeply nested, oversized or duplicated code? | git | the merge-base with the target branch |
-| `repowise risk --fail-above-percentile P` | Is this change bigger and more spread out than P% of this repository's recent commits? | git | recent commits to rank against (at least 8) |
-
-None of them needs an index, a database, a model or an API key, and none
-stores anything. They share one set of exit codes, output formats and base
-resolution, described once below. Each layer's own page has the detail:
-[test intelligence](../layers/TEST_INTELLIGENCE.md#patch-coverage-in-ci),
-[documentation drift](../layers/DOC_DRIFT.md#in-ci),
-[security](../layers/SECURITY.md#in-ci-repowise-security-check),
-[code health](../layers/CODE_HEALTH.md#in-ci-repowise-health-check),
-[change risk](../layers/CHANGE_RISK.md#in-ci).
-
-Doc drift's `--check` needs no index. `--kind symbol` adds symbol references
-(names of functions and classes a document mentions) and needs an index, so it
-exits `2` without one. It also reads `git blame`: in a shallow clone every line
-blames to the boundary commit, so give that job `fetch-depth: 0`.
-
-Not a gate, but in the same pipeline:
-[selecting the tests a change needs](#selecting-the-tests-a-change-needs).
+Repowise gates judge a pull request on what the change adds, not on the
+repository's past.
+
+| Gate | Fails when | History needed |
+|------|------------|----------------|
+| `repowise coverage check` | tests did not run the changed lines (needs a coverage report) | merge-base with the target branch |
+| `repowise coverage check --fail-under-branches P` | tests did not take the changed lines' branches (needs per-line branch data) | merge-base |
+| `repowise coverage check --max-drop P` | project coverage fell more than P points (needs a report measured at the change's base) | merge-base |
+| `repowise doc-drift --check` | docs name missing files, links or commands | none (full history only improves rename suggestions) |
+| `repowise security check` | the change adds a secret or risky call | every commit of the change |
+| `repowise health check` | the change adds complex, deeply nested, oversized or duplicated code | merge-base |
+| `repowise risk --fail-above-percentile P` | the change is bigger and more spread out than P% of recent commits | recent commits to rank against (at least 8) |
+
+- Gates need only git (no index, database, model or API key) and store nothing.
+- Detail per layer: [test intelligence](../layers/TEST_INTELLIGENCE.md#patch-coverage-in-ci),
+ [documentation drift](../layers/DOC_DRIFT.md#in-ci),
+ [security](../layers/SECURITY.md#in-ci-repowise-security-check),
+ [code health](../layers/CODE_HEALTH.md#in-ci-repowise-health-check),
+ [change risk](../layers/CHANGE_RISK.md#in-ci).
+- Not a gate, same pipeline: [selecting the tests a change needs](#selecting-the-tests-a-change-needs).
## What every gate does the same way
-**Exit codes.** `0` passed, or had nothing to judge. `1` the change failed the
-gate. `2` the gate could not evaluate: not a git repository, an unknown
-revision, no merge-base in a shallow clone, an unreadable report or baseline,
-too few recent commits to rank a change against. A setup problem never reads
-as a pass.
-
-**Formats.** `--format table` (the default) for a terminal, `json` for a
-script, `markdown` for a comment or a job artifact, and `github` for GitHub
-Actions: up to ten annotations on the changed lines, a notice counting the
-rest, and the markdown report appended to the job summary. Doc drift,
-security and health also write `sarif` for code scanning and `gitlab`, a GitLab Code
-Quality report (a JSON issue list; findings a baseline accepted are left out).
-When a gate cannot evaluate, `gitlab` still prints a valid list, `[]`, and the
-GitLab template writes `[]` whenever the output does not parse, so the report
-artifact is never an invalid file.
-
-**The change being judged.** Coverage, security, health and risk take a revision range:
-`origin/main...HEAD` (three dots: what the branch did since it forked, the
-pull request's view), `base..head`, or one commit. Without one they read the
-target branch from the CI's own variables (`GITHUB_BASE_REF`,
-`CI_MERGE_REQUEST_TARGET_BRANCH_NAME`, `CHANGE_TARGET`,
-`BITBUCKET_PR_DESTINATION_BRANCH`), else the remote's default branch. `risk`
-does so with `--fail-above-percentile` or `--format markdown` / `github`;
-otherwise an omitted range still means your uncommitted work, else `HEAD`. Doc
-drift has no range: it checks the whole working tree, and a baseline limits it
-to new findings. The variables each CI is detected by and read from, Azure
-Pipelines included, are in [GIT_HOSTS.md](GIT_HOSTS.md#ci-systems).
-
-**History.** CI checkouts are usually shallow, which leaves no merge-base.
-Fetch full history (`fetch-depth: 0` on GitHub Actions, `GIT_DEPTH: 0` on
-GitLab) and make sure the target branch exists as `origin/<branch>`. The
-gates exit `2` rather than guess.
+**Exit codes**
+
+- `0`: passed, or nothing to judge.
+- `1`: the change failed the gate.
+- `2`: could not evaluate (not a git repository, unknown revision, no
+ merge-base in a shallow clone, unreadable report or baseline, too few recent
+ commits to rank against). A setup problem never reads as a pass; fixes are in
+ [When a gate exits 2](#when-a-gate-exits-2).
+
+**Formats** (`--format`)
+
+- `table` (default) for a terminal, `json` for scripts, `markdown` for a
+ comment or artifact.
+- `github`: up to ten annotations on changed lines, a notice counting the
+ rest, and the markdown report in the job summary.
+- Doc drift, security and health only: `sarif` for code scanning, and `gitlab`,
+ a Code Quality JSON issue list without baseline-accepted findings. A gate
+ that cannot evaluate still prints `[]`, and the GitLab template writes `[]`
+ when output does not parse.
+
+**The change being judged**
+
+- Coverage, security, health and risk take a range: `origin/main...HEAD`
+ (three dots: what the branch did since it forked, the pull request's view),
+ `base..head`, or one commit.
+- Without one they read the target branch from `GITHUB_BASE_REF`,
+ `CI_MERGE_REQUEST_TARGET_BRANCH_NAME`, `CHANGE_TARGET` or
+ `BITBUCKET_PR_DESTINATION_BRANCH`, else the remote's default branch.
+- `risk` does that only with `--fail-above-percentile` or `--format markdown` /
+ `github`; otherwise no range means your uncommitted work, else `HEAD`.
+- Doc drift takes no range: it checks the whole working tree.
+- Per-CI variables, Azure Pipelines included: [GIT_HOSTS.md](GIT_HOSTS.md#ci-systems).
+
+**History.** A shallow checkout has no merge-base, so gates exit `2` rather
+than guess: fetch full history (`fetch-depth: 0` on GitHub, `GIT_DEPTH: 0` on GitLab) and the
+target branch as `origin/<branch>`.
## Adopting the gates on an existing repository
-Coverage, security and health judge only what a change adds, so an old untested file
-or an old finding never fails a new pull request. Doc drift checks the whole
-tree, so on a repository whose documentation has already drifted it fails from
-the first run. Record what is there once and fail only on new drift:
+Coverage, security and health judge only what a change adds, so old untested
+files and old findings never fail a new pull request. Doc drift checks the
+whole tree, so a repository with drift needs a [baseline](#gate-on-documentation-drift) first.
-```bash
-repowise doc-drift --check --write-baseline .doc-drift-baseline.json
-git add .doc-drift-baseline.json
-```
-
-Then pass `--baseline .doc-drift-baseline.json` (or the action's
-`doc-drift-baseline` input). Entries are keyed on the document, the reference
-and its target, so an edit above a finding does not turn it back into a new
-one. Alternatively, `repowise doc-drift --check --since auto` judges only what
-the change is answerable for (documents it edits, and documents naming files it
-deletes or renames), which needs no baseline but does need `fetch-depth: 0`.
-
-Security has a baseline too, for accepting a finding a change adds on purpose
-(a documented test key, say): `repowise security check --write-baseline
-.security-baseline.json` on that change records it, and `--baseline` accepts it
-from then on. A `repowise-security-ignore` comment silences one false positive
-([details](../layers/SECURITY.md#silencing-one-finding-repowise-security-ignore)).
-
-`--fail-on-baseline-growth` (the action's `fail-on-baseline-growth` input) keeps a
-baseline shrink-only: it fails either gate when the baseline lists a finding the
-same file at the change's base does not, so a change cannot hide new findings by
-re-saving it. A baseline the change adds for the first time passes.
-
-The health gate reads `.repowise/health-rules.json` as the change's base has it,
-so a rule a change adds or loosens applies from the next change on.
+- `--fail-on-baseline-growth` (input `fail-on-baseline-growth`) keeps a
+ baseline shrink-only: doc drift or security fails when the baseline lists a
+ finding the same file at the change's base does not, so re-saving it cannot
+ hide new findings. A baseline new in the change passes.
+- The health gate reads `.repowise/health-rules.json` as the change's base has
+ it, so a rule a change adds or loosens applies from the next change on.
## GitHub Actions
-The repository is itself an action. It installs Repowise, runs the gates you
-pick, keeps going when one fails so the job reports all of them, and fails the
-step at the end:
+The repository is an action: it installs Repowise, runs every chosen gate, then
+fails the step with `1` if any failed, else `2` if any could not evaluate.
+Snippets below are `with:` lines for this workflow:
```yaml
on: pull_request
@@ -124,73 +99,37 @@ jobs:
risk-fail-above-percentile: 95
```
-Pin a release tag rather than `main`, and set `version:` to pin the Repowise
-release the action installs.
+- Pin a release tag, not `main`; `version:` pins the Repowise release.
+- With a shallow checkout, the action fetches the history and target branch
+ that coverage, security, health and risk need; `fetch-depth: 0` skips that.
-| Input | Default | Meaning |
-|-------|---------|---------|
-| `checks` | `doc-drift,security` | Gates to run. Coverage needs a report, and health and risk are policy choices, so all three are opt-in. |
-| `version` | latest | Repowise version to install. |
-| `python-version` | `3.12` | Python to run it with (3.11 or newer). |
+| Input | Default | What it does |
+|-------|---------|--------------|
+| `checks` | `doc-drift,security` | Gates to run, separated by commas, spaces or newlines. Coverage needs a report, and health and risk are policy choices, so all three are opt-in. An unknown name exits `2`. |
+| `version` | latest | Repowise version from PyPI. |
+| `python-version` | `3.12` | Python to run it (3.11 or newer). |
| `working-directory` | `.` | Where to run from. |
-| `base` | from the pull request | Revision range for coverage, security, health and risk. |
-| `coverage-report` | config, else discovery | Reports, one per line: a path or a glob (`artifacts/**/lcov.info`), optionally `path=prefix`. |
-| `coverage-fail-under` | `coverage.fail_under` | Minimum patch coverage percent. |
-| `coverage-min-coverable-lines` | `coverage.min_coverable_lines` | Small-change tolerance: a change with fewer changed executable lines than this never fails. |
-| `coverage-fail-under-risky` | `coverage.fail_under_risky` | Minimum patch coverage percent over risky files only: hotspots or bug magnets from the index; on git alone, the top quartile of files with bug-fix history. |
-| `coverage-fail-under-branches` | `coverage.fail_under_branches` | Minimum percent of branches taken on changed lines. |
-| `coverage-base-report` | none | Reports measured at the change's base commit, one per line. See [Project coverage](#project-coverage-and-coverage-outside-the-change). |
-| `coverage-max-drop` | `coverage.max_drop` | Most project coverage may fall from the base, in percentage points. |
-| `doc-drift-baseline` | none | Committed baseline file. |
-| `security-fail-on` | `high` | Lowest severity that fails: `high`, `med`, `low`. |
-| `security-baseline` | none | Committed baseline file. |
-| `fail-on-baseline-growth` | `false` | Fail doc drift and security when their baseline gains an entry over the change's base. |
-| `health-fail-on` | `introduced` | What fails the health gate: `introduced`, or `worsened` to fail on findings the change made worse too. |
-| `health-fail-at` | `high` | Lowest severity that fails the health gate: `medium`, `high`, `critical`. |
-| `risk-fail-above-percentile` | none | With `risk` in `checks`, fail when the change ranks above this percentile of recent commits. Empty reports the rank without gating. |
-| `upload-sarif` | `false` | Upload doc drift, security and health findings to code scanning. |
-| `impacted-tests` | `false` | Select the tests the change needs (needs a cached `.repowise` index); see [below](#selecting-the-tests-a-change-needs). |
-| `impacted-tests-runner` | `auto` | `auto`, `pytest`, `go`, `jest` or `files`. |
-
-Outputs: `coverage`, `doc-drift`, `security`, `health` and `risk` hold each gate's exit
-code (empty when not run), and `sarif-dir` the SARIF directory.
-`impacted-tests` holds the runner arguments (or `:all`), and `run-all-tests` is
-`false` only when that subset is safe to run alone.
-
-The risk gate ranks the change against the repository's own recent commits,
-so at a percentile P roughly (100 - P)% of changes fail it by construction.
-A failure asks for a split or a second reviewer, not a code fix, and there is
-no baseline to accept it with.
-
-A shallow checkout still works when coverage, security, health or risk runs: the action
-fetches the missing history and the target branch first. Checking out with
-`fetch-depth: 0` skips that step.
-
-**Code scanning.** With `upload-sarif: true` the findings appear in the
-repository's Security tab and on the pull request's diff. The job then needs
-`security-events: write` (and `actions: read` in a private repository). A pull
-request from a fork runs with a read-only token, so the upload is skipped
-there with a warning; the gates still run and still decide the check.
-
-**Without the action,** each gate is one step:
+| `base` | from the pull request | Range for coverage, security, health, risk and test selection; empty reads the target branch, else the default branch. |
+| `upload-sarif` | `false` | Upload findings to [code scanning](#code-scanning-sarif). |
-```yaml
-- run: pip install repowise
-- run: repowise coverage check --report coverage/lcov.info --fail-under 80 --format github
-- run: repowise doc-drift --check --format github
-- run: repowise security check --format github
-- run: repowise health check --format github
-- run: repowise risk --fail-above-percentile 95 --format github
-```
+Gate inputs are in each gate's section.
-On a pull request the gates read the target branch from `GITHUB_BASE_REF`
-themselves. On a `push` event there is none; pass the range explicitly, for
-example `"$BEFORE..$GITHUB_SHA"` with `BEFORE: ${{ github.event.before }}` set
-under `env:`.
+| Output | Holds |
+|--------|-------|
+| `coverage`, `doc-drift`, `security`, `health`, `risk` | each gate's exit code; empty when not run |
+| `sarif-dir` | the SARIF directory, when `upload-sarif` is on and a gate wrote findings |
+| `impacted-tests` | runner arguments for the selected tests, or `:all` |
+| `run-all-tests` | `false` only when that subset is safe alone; `true` otherwise, also when selection could not run |
+
+**Without the action**, run each gate as a step after `pip install repowise`,
+with `--format github` (commands as in [Other CI systems](#other-ci-systems)).
+On a pull request the gates read `GITHUB_BASE_REF` themselves; a `push`
+event has none: pass the range, e.g.
+`"$BEFORE..$GITHUB_SHA"` with `BEFORE: ${{ github.event.before }}` under `env:`.
## GitLab
-Include the template and set variables for what you use:
+Include the template and set variables for the gates you use:
```yaml
include:
@@ -204,34 +143,34 @@ repowise-coverage:
needs: [test] # the job that writes the report as an artifact
```
-It adds one job per gate on merge request pipelines: `repowise-coverage` (only
-when `REPOWISE_COVERAGE_REPORT` is set), `repowise-doc-drift`,
-`repowise-security` and `repowise-risk` (only when
-`REPOWISE_RISK_FAIL_ABOVE_PERCENTILE` is set). Each prints its markdown report
-to the log and keeps it as an artifact. The doc drift and security jobs also
-write a Code Quality report (`gl-code-quality-doc-drift.json`,
-`gl-code-quality-security.json`), so their findings show in the merge
-request's Code Quality widget, even when the gate fails the job. One more job,
-`repowise-code-quality`, runs on the default branch and never fails the
-pipeline: it publishes the report the widget compares a merge request against,
-so only issues the merge request introduces show as new. It publishes doc
-drift only: security judges only what a change adds, and the default branch
-has no change to judge.
-`REPOWISE_COVERAGE_REPORT` is space separated and may hold globs and
-`path=prefix` entries; Repowise expands the globs, not the shell. Other
-variables: `REPOWISE_VERSION`, `REPOWISE_COVERAGE_MIN_COVERABLE_LINES`,
-`REPOWISE_COVERAGE_FAIL_UNDER_RISKY`, `REPOWISE_COVERAGE_BASE_REPORT` (space
-separated, like the report list), `REPOWISE_COVERAGE_MAX_DROP`,
-`REPOWISE_DOC_DRIFT_BASELINE`,
-`REPOWISE_SECURITY_BASELINE`, `REPOWISE_SECURITY_FAIL_ON`, and
-`REPOWISE_HEALTH: "true"` (with `REPOWISE_HEALTH_FAIL_ON` and `REPOWISE_HEALTH_FAIL_AT`) for a
-`repowise-health` job that also writes `gl-code-quality-health.json`. Override any job's
-`image`, `rules` or `needs` in your own file as usual.
-
-GitLab can also draw line coverage in the merge request diff. That comes from
-your own test job, not from Repowise: have your test runner write a Cobertura
-report (for example with pytest-cov) and declare it there. The same
-`coverage.xml` can be your `REPOWISE_COVERAGE_REPORT`.
+Each job logs its markdown report and keeps it as an artifact; override
+`image`, `rules` or `needs` in your own file.
+
+| Job | Runs on | Code Quality report |
+|-----|---------|---------------------|
+| `repowise-coverage` | merge requests, when `REPOWISE_COVERAGE_REPORT` is set | none |
+| `repowise-doc-drift` | every merge request | `gl-code-quality-doc-drift.json` |
+| `repowise-security` | every merge request | `gl-code-quality-security.json` |
+| `repowise-health` | merge requests, when `REPOWISE_HEALTH: "true"` | `gl-code-quality-health.json` |
+| `repowise-risk` | merge requests, when `REPOWISE_RISK_FAIL_ABOVE_PERCENTILE` is set | none |
+| `repowise-impacted-tests` | merge requests, when `REPOWISE_IMPACTED_TESTS: "true"` | none |
+| `repowise-code-quality` | the default branch; never fails the pipeline | `gl-code-quality-doc-drift.json` |
+
+- `REPOWISE_VERSION` pins the release; gate variables are in each gate's table.
+- Report lists (`REPOWISE_COVERAGE_REPORT`, `REPOWISE_COVERAGE_BASE_REPORT`)
+ are space separated and may hold globs and `path=prefix`; Repowise expands
+ the globs, not the shell.
+- Findings show in the merge request's Code Quality widget, even when the gate
+ fails the job.
+- `repowise-code-quality` publishes the report the widget compares against, so
+ only new issues show as new. It covers doc drift only: security judges only
+ what a change adds, and the default branch has no change.
+
+<details><summary>Line coverage in the merge request diff</summary>
+
+That comes from your test job, not Repowise: write a Cobertura report (e.g.
+with pytest-cov) and declare it. The same `coverage.xml` can be your
+`REPOWISE_COVERAGE_REPORT`.
```yaml
test:
@@ -244,10 +183,12 @@ test:
path: coverage.xml
```
+</details>
+
## Other CI systems
-The gates are plain commands. Fetch the target branch, run them, and let the
-exit code fail the build. Jenkins multibranch:
+Fetch the target branch, run the commands, and let the exit code fail the
+build. Jenkins multibranch:
```bash
git fetch --no-tags origin "+refs/heads/$CHANGE_TARGET:refs/remotes/origin/$CHANGE_TARGET"
@@ -256,177 +197,93 @@ repowise coverage check "origin/$CHANGE_TARGET...HEAD" --report coverage/lcov.in
repowise doc-drift --check
repowise security check "origin/$CHANGE_TARGET...HEAD"
repowise health check "origin/$CHANGE_TARGET...HEAD"
+repowise risk "origin/$CHANGE_TARGET...HEAD" --fail-above-percentile 95
```
-Bitbucket Pipelines and others work the same way with their own branch
-variable; `--format markdown` or `json` gives you something to post.
-
-## Selecting the tests a change needs
-
-`repowise impacted-tests --format args` prints one line of arguments for a test
-runner, or `:all` whenever any part of the answer is not known, with the
-reasons on stderr. It needs an index (cached from the default branch, below);
-a per-test coverage map (`repowise coverage add`) makes it more precise.
-
-- It exits `0` for a subset or for everything, and `2` only when it cannot read the change or the `tests.*` config.
-- Branch on the run-all flag, never on `:all`: jest and vitest read it as a pattern and run nothing.
-- It runs everything for: an empty change; a Cargo, Make, CMake, Docker or CI file; tool and runtime config (dotfiles, `.tool-versions`, root-level `*.toml`, `*.yaml` and `*.json`, shell scripts); `.repowise/config.yaml`.
-- A lockfile, manifest or test runner config runs its own ecosystem's tests: for a nested `package.json`, lockfile or `go.mod`, the tests under its directory and those reaching code there; at the root, and for Python, Ruby, PHP and Gradle or Maven files (pip requirements included), `tsconfig` and jest or vitest configs, the whole ecosystem. Tests whose code names the file from outside that scope run too (a Python test reading `package.json`); a mention written with a directory names only the files its path can mean (`packages/web/package.json` does not name `packages/ui/package.json`), a bare name, `../package.json` or a path built from parts names every file of that name. A file under a fixture tree (`tests/fixtures/<name>/`) stands for the test code that names that tree or the fixtures directory; when none does, or code outside the test trees names the tree's path, everything runs. If more than 200 non-test files outside the scope name it, everything runs.
-- A production package's `__init__.py` selects the tests reaching any module under it.
-- A doc, template, query, stylesheet, image or nested data file selects the tests reaching the code that names it, outside comments and docstrings. When no code names it, a doc, template, stylesheet or image selects its package's tests (Markdown, reST or AsciiDoc in no package and in a top-level directory without code needs none), and a query or data file runs everything. Ceiling: a test that globs docs or templates in another package is not seen.
-- It also runs everything for: non-code files in a test tree; a changed file with no known test or only a filename guess; a route through a test helper no test imports, unless every known test is selected anyway (the reasons then say so); any Python test helper while a conftest or pytest config loads plugins by name.
-- It also runs everything for: a missing or unreadable index; a per-test map at its row cap; a deleted file no known test used.
-- An index built at an older commit than the change's base is used as is. Files changed in between whose imports or module-name strings moved (any change beyond whitespace, outside Python and JavaScript/TypeScript) add the tests reaching them. It runs everything instead when that commit is not in the clone, or more than 1,000 files changed in between, or one of them is a lockfile, manifest, build or test config or `.repowise/config.yaml`. CI config and test data changed in between no longer force a full run: neither is imported.
-- Only `docs/` and root README-like files (README, CHANGELOG, LICENSE, CONTRIBUTING) are skipped, and only when no code names them (a test that reads `README.md` names it, and then runs); an empty line means only those changed.
-- Tests the graph cannot see into run with every subset, and the reasons say how many and why: a test not indexed or importing nothing it resolves; a Python, JavaScript or TypeScript test that lists and reads files under a source directory (the working directory, a module's location, or its own location climbed out of the test directory; never its fixtures, sibling data or a temporary directory); one that runs the project's own command, `python -m` module, code importing the project, or package `bin` in a child process; a Java or Kotlin `@SpringBootTest`, which loads the whole application context (a slice such as `@WebMvcTest` is selected through its imports). A test that inherits `@SpringBootTest` from a base class or carries it through a custom meta-annotation is not detected and is selected through its imports only. The indexer finds them once from each test's source and stores the reason, so selection reads it without opening test files. An index built before this check runs everything until `repowise update` checks its tests. A Python module named like a test but outside every test directory is not a test when the nearest pytest config's `testpaths` or `python_files` leaves it out, as a bare `pytest` does: it is selected through like any other code. The rule follows a bare `pytest` run, so a test that CI only names explicitly on the command line outside `testpaths` is not seen as one: list it in `tests.always_run`. Inside a JavaScript or TypeScript `src` tree a `tests/` folder is not a test directory, since it often holds a product feature: a file there is a test when its name says so (`.test.`, `.spec.`) or a test directory such as `__tests__/` holds it.
-- A test the change reaches only through imports, more than one file away and with no call path, coverage or paired name, runs but is listed in `selected.import_closure` and counted apart in the summary: an import error breaks it, though nothing it calls runs the change.
-- A changed `conftest.py`, test package `__init__.py` or imported test helper selects the tests under or importing it, not everything.
-- A change that reaches a `conftest.py` only through its imports selects the tests that ask for a fixture using that change (directly, through other fixtures, `usefixtures` or `getfixturevalue`), plus one test under the conftest as an import check.
- - Every test under the conftest still runs when an autouse fixture, a `pytest_*` hook or module-level code uses the change, or when the conftest imports it only for side effects. The tests it adds that nothing else reaches are listed in `selected.broadcast` and counted apart in the summary.
- - Patching an attribute of an imported module or of a class in it (`monkeypatch.setattr(mod.Cls, "name", ...)`) in an autouse fixture is left to the import check.
- - Reading a literal constant of an imported module, or calling one of its functions that uses nothing the module imports beyond standard modules that cannot load code by name (emptying a `functools` cache or a standard container counts), reaches only a change in that module itself. A module re-exporting such a name (`from .console import NAMES as NAMES`) passes this through to the module defining it. Ceiling: such a function that reads or runs repo files by path (`open`, `Path.read_text`, `os.system`) is judged by its imports only.
- - It also runs everything there when a fixture request cannot be read from the code (a computed name, a mark kept in a variable, a config `usefixtures`), when the conftest loads plugins or cannot be read, and on an index built before this was recorded. The reasons name the cause.
- - Ceiling: a change that only alters what the changed module does at import time, seen by a test that does not import it, is caught by the import check alone.
-- Wiring no import states counts as a use: a JS/TS setup file named under `setupFiles`, `setupFilesAfterEnv`, `globalSetup` or `globalTeardown` in a `vitest.*`, `jest.*`, `vite.*` or `playwright.*` config or a `package.json` stands for the tests in that config's package, and a helper a test names by a path relative to itself (`Path(__file__).parent / "server.py"`, `path.join(__dirname, "server.ts")`) stands for that test. A `conftest.py` links only the files pytest collects (its `python_files`), so a helper beside the tests is not on every route the conftest reaches.
-- Without a range, in CI it reads the pull request's change; locally, the staged changes.
-- `tests.full_run_on` (gitignore patterns) adds run-everything paths, and a path it matches is never scoped; `tests.always_run` is appended to every selection as written, for the runner whose language each entry is in.
-- With `--runner pytest`, `go` or `jest`, the arguments hold only that runner's tests, `tests.always_run` included. A repository with tests in several languages needs one job per runner: the tests a job leaves out are counted on stderr, and listed per runner under `left_out` with `--format json`. `--runner files` gets every test.
-- Selected tests come likeliest to fail first ([run order](../reference/CLI_REFERENCE.md#repowise-impacted-tests-revspec)).
- `--prioritize` prints the whole suite with the selection first, so a job can run the
- head with `-x` and the rest after; it skips nothing.
-- `--explain <test>` says why one test file was or was not selected: the first changed file that reached it, the evidence (coverage, call graph, import graph) and the import route from the test to that file when there is one, or the rule that runs it. With `--format json` the same answer is added as `explain`, and `selected.why` holds it for every selected test.
-- Ceiling: on the JVM and .NET, a same-package test linked only by an unresolved call is missed. So is a test that reaches the change through a plugin or registry loaded by a string name, a tree walk or child process done inside a shared helper it calls, or one in another language: list such tests in `tests.always_run`, and run the full suite on the default branch.
-
-**What to expect.** The subset is only as small as the code is loosely coupled.
-On tightly coupled code the graph alone picks most tests (over 80% of test
-files on this repository), because most tests import something that imports
-the changed file. Real savings need a per-test map measured at the change's
-base. `--format json` shows what drove each file's selection in
-`selected.basis`.
-
-On GitHub Actions, keep the index cached from the default branch and branch
-on the outputs in the pull request job:
-
-```yaml
-# .github/workflows/repowise-index.yml
-on: {push: {branches: [main]}}
-jobs:
- index:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v4
- with: {fetch-depth: 0}
- - uses: actions/cache/restore@v4
- with: {path: .repowise, key: "repowise-${{ github.sha }}", restore-keys: "repowise-"}
- - run: pip install repowise
- - run: if [ -f .repowise/state.json ]; then repowise update --index-only; else repowise init --yes --no-prose; fi
- - uses: actions/cache/save@v4
- with: {path: .repowise, key: "repowise-${{ github.sha }}"}
-```
+Bitbucket Pipelines and others use their own branch variable; `--format
+markdown` or `json` gives something to post.
-```yaml
-# in the pull request workflow
-- uses: actions/checkout@v4
- with: {fetch-depth: 0}
-- uses: actions/cache/restore@v4
- with: {path: .repowise, key: "repowise-${{ github.event.pull_request.base.sha }}", restore-keys: "repowise-"}
-- id: select
- uses: repowise-dev/repowise@main
- with: {checks: "", impacted-tests: true, impacted-tests-runner: pytest}
-- if: steps.select.outputs.run-all-tests != 'false'
- run: pytest
-- if: steps.select.outputs.run-all-tests == 'false' && steps.select.outputs.impacted-tests != ''
- env: {TESTS: "${{ steps.select.outputs.impacted-tests }}"}
- run: eval "pytest $TESTS"
-```
+## Gate on coverage
-A skipped or failed step leaves `run-all-tests` empty, so `!= 'false'` runs
-everything.
+The [shared workflow](#github-actions) shows the inputs in use.
-On GitLab, set `REPOWISE_IMPACTED_TESTS: "true"` (and optionally
-`REPOWISE_IMPACTED_TESTS_RUNNER`). The `repowise-impacted-tests` job writes the
-arguments to `impacted-tests.txt` and `RUN_ALL_TESTS` to a dotenv report:
+| Input | GitLab variable | Flag / config key | What it does |
+|-------|-----------------|-------------------|--------------|
+| `coverage-report` | `REPOWISE_COVERAGE_REPORT` | `--report` / `coverage.paths` | Reports: path or glob, optionally `path=prefix`; one per line in the action. Unset: config, else discovery. |
+| `coverage-fail-under` | `REPOWISE_COVERAGE_FAIL_UNDER` | `--fail-under` / `coverage.fail_under` | Minimum patch coverage percent; unset reports without gating. |
+| `coverage-min-coverable-lines` | `REPOWISE_COVERAGE_MIN_COVERABLE_LINES` | `--min-coverable-lines` / `coverage.min_coverable_lines` | [Small-change tolerance](#small-change-tolerance). |
+| `coverage-fail-under-risky` | `REPOWISE_COVERAGE_FAIL_UNDER_RISKY` | `--fail-under-risky` / `coverage.fail_under_risky` | Minimum over [risky files](#risk-weighted-patch-coverage). |
+| `coverage-fail-under-branches` | `REPOWISE_COVERAGE_FAIL_UNDER_BRANCHES` | `--fail-under-branches` / `coverage.fail_under_branches` | Minimum [branches taken](#branches-on-changed-lines) on changed lines. |
+| `coverage-base-report` | `REPOWISE_COVERAGE_BASE_REPORT` | `--base-report` | Reports measured at the change's base ([project coverage](#project-coverage-and-coverage-outside-the-change)). |
+| `coverage-max-drop` | `REPOWISE_COVERAGE_MAX_DROP` | `--max-drop` / `coverage.max_drop` | Most project coverage may fall, in points; needs a base report or an index that stored coverage at the base. |
-```yaml
-repowise-index:
- image: python:3.12
- variables: {GIT_DEPTH: "0"}
- script:
- - pip install repowise
- - if [ -f .repowise/state.json ]; then repowise update --index-only; else repowise init --yes --no-prose; fi
- cache: {key: repowise-index, paths: [.repowise/], policy: pull-push}
- rules:
- - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
+An empty input or unset variable falls back to the config key in
+`.repowise/config.yaml` ([keys](../reference/CONFIG.md#the-coverage-block)).
-repowise-impacted-tests:
- cache: {key: repowise-index, paths: [.repowise/], policy: pull}
+### Small-change tolerance
-test:
- needs: [{job: repowise-impacted-tests, optional: true}]
- script:
- - |
- if [ "${RUN_ALL_TESTS:-}" != "false" ]; then pytest
- elif [ -n "$(cat impacted-tests.txt 2>/dev/null)" ]; then eval "pytest $(cat impacted-tests.txt)"
- fi
-```
+Below `min_coverable_lines` changed executable lines, a miss reads "not
+applied" (a GitHub notice) and exits `0`: one uncovered line in a two-line fix
+should not block a merge. It counts only lines the report measures.
-## Coverage reports per language
+### Coverage reports per language
-The coverage gate needs the lines each file could have run, not only the lines
-it did, and a new file no test loads must still appear in the report or it is
-listed as "not in report" and left out of the figure. These commands do both:
+Reports must list every runnable line, including new files no test loads
+(otherwise "not in report" and left out):
| Stack | Produce the report | Pass |
|-------|--------------------|------|
-| Python (pytest) | `pytest --cov=src --cov-report=lcov:coverage/lcov.info` (lcov paths are relative to the working directory) | `coverage/lcov.info` |
+| Python (pytest) | `pytest --cov=src --cov-report=lcov:coverage/lcov.info` (paths relative to the working directory) | `coverage/lcov.info` |
| Python (coverage.py) | `coverage lcov` or `coverage xml` after the run | `coverage.lcov`, `coverage.xml` |
| Go | `go test -coverprofile=coverage.out -coverpkg=./... ./...` (`-coverpkg` includes packages with no tests) | `coverage.out` |
| Java or Kotlin (Gradle) | `gradle test jacocoTestReport` with the XML report on | `build/reports/jacoco/test/jacocoTestReport.xml` |
-| Java (Maven) | `mvn test jacoco:report` (`report-aggregate` for a multi-module build) | `target/site/jacoco/jacoco.xml` |
-| JavaScript or TypeScript | `c8 --all --reporter=lcov`, or a test runner's `lcov` reporter with every source file included | `coverage/lcov.info` |
+| Java (Maven) | `mvn test jacoco:report` (`report-aggregate` for multi-module) | `target/site/jacoco/jacoco.xml` |
+| JavaScript or TypeScript | `c8 --all --reporter=lcov`, or a runner's `lcov` reporter including every source file | `coverage/lcov.info` |
| Rust | `cargo llvm-cov --lcov --output-path coverage/lcov.info` | `coverage/lcov.info` |
-Several reports merge: a line any of them ran counts as run. A coverage.py
-`.coverage` database is not a text report; export it first. When report paths
-do not line up with the repository (a build directory, a container path), set
-`coverage.strip_prefix` or `coverage.path_prefix` in `.repowise/config.yaml`.
-The gate reports how many report paths matched the repository, and exits `2`
-when none did, so a wrong prefix never passes as zero. When more than half did
-not match, it suggests the prefix to set; `repowise coverage add` then stores
-nothing unless `--allow-partial` is passed.
+- Several reports merge: a line any of them ran counts as run.
+- Export a coverage.py `.coverage` database first; it is not a text report.
+- Paths that do not line up (a build directory, a container path): set
+ `coverage.strip_prefix` or `coverage.path_prefix`.
+- The gate reports how many report paths matched. None: exit `2`. More than
+ half unmatched: it suggests a prefix, and `repowise coverage add` stores
+ nothing without `--allow-partial`.
-The threshold can live in config instead of the workflow:
+### Monorepos and matrix jobs
+
+`--report` and each `coverage-report` line take a glob relative to the working
+directory (`artifacts/**/lcov.info`); matches merge hit-wins.
+
+- `**` skips dependency, cache and build directories (`node_modules`, `.venv`,
+ `dist`, ...) and nested repositories, as discovery does.
+- A missing literal path, or a glob matching nothing, exits `2`. A glob still
+ matches with one shard missing: list each shard on its own line to catch it.
+- `coverage.paths` entries matching nothing are skipped.
+- Per-report prefix: `--report web/coverage/lcov.info=web`. The whole argument
+ is tried as a path first (`artifacts/shard=1/*.info` stays one), then split
+ on the last `=`.
+- In config, `paths` entries may be globs relative to the repo root, or
+ mappings:
```yaml
-# .repowise/config.yaml
coverage:
- paths: [coverage/lcov.info]
- fail_under: 80
- min_coverable_lines: 5 # small-change tolerance
- fail_under_risky: 90 # optional, see Risk-weighted patch coverage
- fail_under_branches: 70 # optional, see Branches on changed lines
+ paths:
+ - {path: "web/coverage/lcov.info", path_prefix: web}
+ - "services/*/coverage.xml"
+ ignore: ["**/*_pb2.py", "gen/"] # gitignore syntax
```
-With `min_coverable_lines` set, a change touching fewer changed executable
-lines than that is still reported against the threshold, but a miss reads
-"not applied" (a notice on GitHub) and exits `0`: one uncovered line in a
-two-line fix should not block a merge. Like the percentage, the count is of
-lines the report measures; a file the report does not name adds nothing to it.
-
-### Monorepos and matrix jobs
+- `coverage.ignore` drops matching changed files before measuring (counted as
+ ignored, here and in editor and agent views) and matching report entries
+ from `repowise coverage add` and indexing. Ignoring every entry exits `2`.
+- Go coverprofiles name import paths. A module in a subdirectory
+ (`backend/go.mod` declaring `module example.com/m`) maps `example.com/m/` to
+ `backend/` from the checkout's `go.mod` files; a per-report prefix or
+ `coverage.path_prefix` turns that off.
-A matrix of test jobs leaves one report per shard. `--report` (and each line
-of `coverage-report`) takes a glob, relative to the working directory, so
-`artifacts/**/lcov.info` reads them all; they merge hit-wins. `**` walks the
-tree the way discovery does, skipping dependency, cache and build directories
-(`node_modules`, `.venv`, `dist`, ...) and nested repositories. A job whose
-reports never arrived exits `2`: a literal path that does not exist, or a
-glob that matches nothing, cannot be evaluated. A glob still matches when one
-shard of several is missing, so to catch that, list each shard's report on
-its own line. `coverage.paths` entries that match nothing are skipped.
+<details><summary>Matrix examples (GitHub Actions and GitLab)</summary>
-On GitHub Actions, each shard uploads its report and the gate job downloads
-them all:
+Each shard uploads its report; the gate job downloads them all:
```yaml
jobs:
@@ -453,8 +310,7 @@ jobs:
coverage-report: artifacts/**/lcov.info
```
-On GitLab, give each parallel shard its own path and let the gate job need
-them:
+On GitLab, give each parallel shard its own path:
```yaml
test:
@@ -470,46 +326,17 @@ repowise-coverage:
needs: [test]
```
-When one package's report names paths relative to that package, give it a
-per-report prefix: `--report web/coverage/lcov.info=web`. The whole argument
-is tried as a path or glob first, so `artifacts/shard=1/*.info` stays one;
-only when it matches nothing is it split on the last `=`. In config the same
-is a mapping entry, and `paths` entries may be globs, relative to the
-repository root:
-
-```yaml
-coverage:
- paths:
- - {path: "web/coverage/lcov.info", path_prefix: web}
- - "services/*/coverage.xml"
- ignore: ["**/*_pb2.py", "gen/"] # gitignore syntax
-```
-
-`coverage.ignore` leaves generated or vendored files out on both sides:
-changed files it matches are dropped before measuring (the summary counts them
-as ignored, here and in the editor and agent views), and report entries it
-matches are not stored by `repowise coverage add` or indexing. When it leaves
-out every entry of the reports, the gate exits `2` and says so.
-
-Go coverprofiles name files by import path. When a module lives in a
-subdirectory (`backend/go.mod` declaring `module example.com/m`), paths under
-`example.com/m/` are mapped to `backend/` using the `go.mod` files in the
-checkout, so files in the module's top-level package match with no prefix.
-A per-report prefix or `coverage.path_prefix` turns the mapping off.
+</details>
### Path-scoped gates
-One threshold over the whole change lets a well-tested package carry an
-untested one. `coverage.gates` adds a gate per part of the repository: each is
-judged on the changed files its globs match, with the same rules as the
-whole-change gate. Globs use gitignore syntax, like `coverage.ignore`, and are
-relative to the repository root; a leading `/` anchors one there (`/api/` is
-the top-level `api` directory, `api/` any directory of that name).
+`coverage.gates` judges parts of the repository separately, so a well-tested
+package cannot carry an untested one. Each gate covers the changed files its
+globs match, with the whole-change rules.
```yaml
-# .repowise/config.yaml
coverage:
- fail_under: 70 # the whole change, as before
+ fail_under: 70 # the whole change
gates:
- name: api
paths: ["/services/api/"]
@@ -523,117 +350,95 @@ coverage:
informational: true # reported, never fails
```
-A gate without `fail_under` is reported but judges nothing. A file can match
-several gates; each counts it. The change fails when the whole-change gate
-fails or when any gate that is not `informational` fails. The headline then
-leads with the failing gate and its counts (`Fails: path-scoped gate api 60.0%
-(6 of 10 changed executable lines), below its 85.0% gate.`) before the
-whole-change verdict, the summary adds a table of gates (failing ones first),
-and on GitHub each failing gate is its own `::error::`; an informational gate
-below its threshold is a `::notice::`. The small-change tolerance is the whole
-change's: when the change has fewer changed executable lines than
-`min_coverable_lines`, every gate reads `too_small`, but a small slice of a
-big change is judged. An entry the config cannot use (no name, a repeated
-name, no paths or only `!` exclusions, a `fail_under` outside 0-100, an
-unknown key) makes the check exit `2` naming it.
-
-Like the whole-change figure, a gate counts only changed lines the report
-measures. A changed file it matches that the report does not measure (a new
-file no test loads, a report without line data) is counted apart, as
-`unmeasured_file_count`, and left out of the percentage: a gate over only such
-files reads "no measured changed lines (2 changed files not measured)" and
-fails nothing.
-
-With one report per job, each job would judge the gates on a fragment of the
-change: run `coverage check` once over the combined reports instead, as in
-[Monorepos and matrix jobs](#monorepos-and-matrix-jobs).
-
-The gates live in the committed config, so the Action and the GitLab template
-take no input for them: every job reads the same gates. The editor, REST and
-agent views report the same verdicts when the stored coverage was measured at
-the change's head and the config is valid; on stale coverage, or beside an
-invalid entry (which they list in `scope.config_errors`), their gates read
-`no_data`. To start, let Repowise propose some:
-
-```bash
-repowise coverage suggest-gates # YAML to paste below coverage:
-repowise coverage suggest-gates --format json
-```
-
-It reads CODEOWNERS (one gate per owner), the top-level packages git tracks,
-and, when the repository is indexed, the graph's communities, labelling each
-source in a comment. The block is indented to paste directly below your
-`coverage:` line. It writes nothing and sets no `fail_under`: keep the gates
-you want and choose their thresholds.
+| Key | What it does |
+|-----|--------------|
+| `name` | Required, unique. |
+| `paths` | Gitignore globs from the repo root; a leading `/` anchors (`/api/` top-level only, `api/` anywhere); `!` excludes. |
+| `fail_under` | Percent 0-100; without it the gate is reported but judges nothing. |
+| `informational` | Reported, never fails. |
+
+- A file matching several gates counts in each.
+- The change fails if the whole-change gate or any non-informational gate
+ fails. The headline leads with it (`Fails: path-scoped gate api 60.0% (6 of
+ 10 changed executable lines), below its 85.0% gate.`), the summary lists
+ gates failing first, and GitHub gets an `::error::` per failing gate and a
+ `::notice::` per informational one below threshold.
+- The small-change tolerance is the whole change's: a small change reads
+ `too_small` in every gate; a small slice of a big change is judged.
+- An unusable entry (no or repeated name, no paths or only `!` ones,
+ `fail_under` outside 0-100, an unknown key) exits `2` naming it.
+- Changed files the report does not measure (new and unloaded, or no line data)
+ count apart as `unmeasured_file_count`; a gate with only those reads "no
+ measured changed lines (2 changed files not measured)" and fails nothing.
+- Run `coverage check` once over combined reports, not per job, or each job
+ judges a fragment ([matrix jobs](#monorepos-and-matrix-jobs)).
+- Gates live in committed config, so the Action and GitLab template take no
+ input for them.
+- Editor, REST and agent views match when stored coverage was measured at the
+ change's head and the config is valid; otherwise gates read `no_data` (invalid
+ entries listed in `scope.config_errors`).
+
+`repowise coverage suggest-gates` (or `--format json`) proposes gates from
+CODEOWNERS (one per owner), top-level tracked packages and, when indexed, graph
+communities, labelling each source. It prints YAML indented to paste below
+`coverage:`, writes nothing and sets no `fail_under`.
### Risk-weighted patch coverage
-An uncovered line in a file that keeps breaking matters more than one in a
-file nothing depends on. Every changed file in the coverage report carries its
-risk, and the table, the annotations and the summary list the riskiest files
-first, with a "Risk" column in plain words ("hotspot, bug-fix weight 3.2, 14
-dependents", "none known", or "unknown" when it could not be read). A file is
-risky when the index flags it a hotspot or a bug magnet; without an index, or
-for a file the change adds, when its recency-weighted bug-fix weight from git
-is in the top quartile of the files with bug-fix history. The report says
-which basis each row used when not every file had index data. When an index is
-present, each annotation also names the test file to extend when one is found
-("Extend tests/test_auth.py (inferred: calls reach `login`)").
-
-`--fail-under-risky` (the action's `coverage-fail-under-risky`) adds one more
-gate, stricter, over the risky files' changed lines alone, and the check fails
-when any gate fails. It follows the same rules as the others, the whole
-change's small-change tolerance included. A change that touches no risky file
-leaves it not applied (`no_data`, exit `0`). With the gate set, a shallow
-clone, or a measured file whose risk could not be read (no git history and no
-index row), exits `2`, unless the whole-change, a path-scoped or the branch
-gate already failed: that failure is reported.
+The table, annotations and summary list the riskiest changed files first, with
+a "Risk" column ("hotspot, bug-fix weight 3.2, 14 dependents", "none known",
+or "unknown").
+
+- Risky: an index hotspot or bug magnet; without an index, or for a new file,
+ top quartile of recency-weighted bug-fix weight among files with bug-fix
+ history. The report names the basis when rows differ.
+- With an index, annotations name a test to extend ("Extend tests/test_auth.py
+ (inferred: calls reach `login`)").
+- `--fail-under-risky` gates the risky files' changed lines alone, with the
+ same rules and small-change tolerance. No risky file: `no_data`, exit `0`.
+- With it set, a shallow clone, or a measured file whose risk could not be read
+ (no git history, no index row), exits `2` unless another gate already failed.
### Branches on changed lines
-When the report has per-line branch data (lcov `BRDA`, Cobertura
-`condition-coverage`, JaCoCo branch counters, Clover `cond`), the check also
-reports "Branches on changed lines 70.0% (7 of 10 taken; 2 lines partly
-taken)". A partly taken line ran with a branch never taken: it gets a "Partly
-taken" column and, on GitHub, a "Partly taken branch" warning.
-`--fail-under-branches P` (`coverage-fail-under-branches`,
-`coverage.fail_under_branches`) gates the share.
+With per-line branch data (lcov `BRDA`, Cobertura `condition-coverage`, JaCoCo
+branch counters, Clover `cond`) the check adds "Branches on changed lines 70.0%
+(7 of 10 taken; 2 lines partly taken)".
+- A partly taken line (a branch never taken) gets a "Partly taken" column and a
+ GitHub "Partly taken branch" warning.
- Line and branch coverage are reported side by side, never blended.
-- The small-change tolerance applies, and counts changed lines, not branches.
-- No changed line with branches: "not measured", never 0%, and the gate is not
- applied (exit `0`).
-- Coverage with no per-line branch data (a Go coverprofile, coverage.py without
- `--branch`, stored coverage ingested before branches were kept) exits `2`
- under the flag, unless another gate already failed, and is a note with exit
- `0` from the config key alone.
-- Several reports merge per line by the most branches taken and seen, so the
- share is a lower bound.
+- The small-change tolerance counts changed lines, not branches.
+- No changed line with branches: "not measured", never 0%, exit `0`.
+- No branch data (Go coverprofile, coverage.py without `--branch`, coverage
+ stored before branches were kept): exit `2` under the flag or input unless
+ another gate failed; only a note from the config key.
+- Reports merge per line by most branches taken and seen, so the share is a
+ lower bound.
### Project coverage and coverage outside the change
-Patch coverage cannot see a change that deletes a test or a code path other
-files relied on. Given a report measured at the change's base commit, the check
-adds project coverage at the base and the head, and lists files whose coverage
-changed outside the change with the changed test or dependent that explains it.
+Patch coverage misses deleted tests or code paths others used. With a base
+report, the check adds project coverage at base and head, and lists files whose
+coverage changed outside the change, with the test or dependent that explains it.
```bash
repowise coverage check origin/main...HEAD --report coverage/lcov.info \
--base-report base/lcov.info --max-drop 0.5
```
-- `--max-drop P` fails when project coverage falls more than `P` points. The
- small-change tolerance does not apply.
-- The base report must be measured at the merge-base (`A` for `A..B`). Files
- whose lines do not line up are left out, and a note says how many.
-- Both sides must be measured the same way: the same reports of each format,
- the same `coverage.ignore`, neither mapping fewer than half its files.
-- A base the check cannot use exits `2` under the `--max-drop` or
- `--base-report` flag (the action's inputs), and is a note with exit `0` when
- the gate comes from `coverage.max_drop` alone.
+- The small-change tolerance does not apply to `--max-drop`.
+- Measure the base report at the merge-base (`A` for `A..B`); files whose lines
+ do not line up are left out, with a count.
+- Measure both sides the same way: same reports of each format, same
+ `coverage.ignore`, neither mapping under half its files.
+- An unusable base exits `2` under `--max-drop` or `--base-report`; from
+ `coverage.max_drop` alone it is a note.
+
+<details><summary>Base reports on GitHub Actions and GitLab</summary>
-On GitHub Actions, in a job that runs on pushes to the default branch and on
-pull requests, checked out with `fetch-depth: 0`:
+GitHub Actions, one job on default-branch pushes and pull requests,
+`fetch-depth: 0`:
```yaml
- run: pytest --cov=src --cov-report=lcov:coverage/lcov.info
@@ -659,9 +464,9 @@ pull requests, checked out with `fetch-depth: 0`:
coverage-max-drop: ${{ steps.base.outputs.cache-hit == 'true' && '0.5' || '' }}
```
-On GitLab, the merge request job uses the target branch's latest `test`
-artifact only when it was measured at the merge-base (a rebased merge request,
-or merged-results pipelines); otherwise the check runs without a base:
+GitLab uses the target branch's latest `test` artifact only when it was
+measured at the merge-base (a rebased merge request, or merged-results
+pipelines); otherwise the check runs without a base:
```yaml
test:
@@ -685,24 +490,359 @@ repowise-coverage:
fi
```
+</details>
+
+## Gate on documentation drift
+
+```yaml
+checks: doc-drift
+doc-drift-baseline: .doc-drift-baseline.json
+```
+
+| Input | GitLab variable | Flag | What it does |
+|-------|-----------------|------|--------------|
+| `doc-drift-baseline` | `REPOWISE_DOC_DRIFT_BASELINE` | `--baseline` | Committed baseline; only findings it lacks fail. |
+| `fail-on-baseline-growth` | none | `--fail-on-baseline-growth` | [Shrink-only baseline](#adopting-the-gates-on-an-existing-repository), for doc drift and security; default `false`. |
+
+Record existing drift once, then pass `--baseline`:
+
+```bash
+repowise doc-drift --check --write-baseline .doc-drift-baseline.json
+git add .doc-drift-baseline.json
+```
+
+- Entries key on document, reference and target, so an edit above a finding
+ does not make it new.
+- No baseline: `--since auto` judges only documents the change edits and
+ documents naming files it deletes or renames (needs `fetch-depth: 0`).
+- `--kind symbol` adds function and class names a document mentions; it needs
+ an index and exits `2` without one.
+- Doc drift reads `git blame`, which a shallow clone blames to the boundary
+ commit: use `fetch-depth: 0`.
+
+## Gate on security
+
+```yaml
+checks: security
+security-fail-on: med
+```
+
+| Input | GitLab variable | Flag | What it does |
+|-------|-----------------|------|--------------|
+| `security-fail-on` | `REPOWISE_SECURITY_FAIL_ON` | `--fail-on` | Lowest failing severity: `high` (default), `med`, `low`. |
+| `security-baseline` | `REPOWISE_SECURITY_BASELINE` | `--baseline` | Committed baseline; only findings it lacks fail. |
+
+- Accept a deliberate finding (a documented test key): run
+ `repowise security check --write-baseline .security-baseline.json` on that
+ change, then pass `--baseline`.
+- Silence one false positive with a `repowise-security-ignore` comment
+ ([details](../layers/SECURITY.md#silencing-one-finding-repowise-security-ignore)).
+
+## Gate on code health
+
+```yaml
+checks: health
+health-fail-at: medium
+```
+
+| Input | GitLab variable | Flag | What it does |
+|-------|-----------------|------|--------------|
+| `health-fail-on` | `REPOWISE_HEALTH_FAIL_ON` | `--fail-on` | `introduced` (default; findings the change wrote) or `worsened` (also findings it made worse). |
+| `health-fail-at` | `REPOWISE_HEALTH_FAIL_AT` | `--fail-at` | Lowest failing severity: `medium`, `high` (default), `critical`. |
+
+Findings that do not fail warn. On GitLab, set `REPOWISE_HEALTH: "true"`.
+
+## Gate on change risk
+
+The [shared workflow](#github-actions) shows the input in use.
+
+| Input | GitLab variable | Flag | What it does |
+|-------|-----------------|------|--------------|
+| `risk-fail-above-percentile` | `REPOWISE_RISK_FAIL_ABOVE_PERCENTILE` | `--fail-above-percentile` | Fail above this percentile of recent commits; empty reports the rank only. The GitLab job runs only when set. |
+
+- A size-and-spread gate, not a bug predictor: at percentile P roughly
+ (100 - P)% of changes fail by construction.
+- A failure asks for a split or a second reviewer, not a code fix; no baseline
+ accepts it.
+
+## Code scanning (SARIF)
+
+```yaml
+permissions:
+ contents: read
+ security-events: write
+ actions: read # private repositories only
+# ...
+ with:
+ checks: doc-drift,security,health
+ upload-sarif: true
+```
+
+- Doc drift, security and health findings appear in the Security tab and on the
+ pull request diff.
+- A fork's pull request has a read-only token: the upload is skipped with a
+ warning, and the gates still decide the check.
+- A gate that could not evaluate writes no SARIF file.
+
+## Selecting the tests a change needs
+
+`repowise impacted-tests --format args` prints one line of runner arguments,
+or `:all` when any part of the answer is unknown, with reasons on stderr.
+
+- It needs an index cached from the default branch; a per-test coverage map
+ (`repowise coverage add`) makes it more precise.
+- Exit `0` for a subset or everything; `2` only when it cannot read the change
+ or the `tests.*` config.
+- **Branch on the run-all flag, never on `:all`:** jest and vitest read `:all`
+ as a pattern and run nothing.
+
+| Input | GitLab variable | Flag | What it does |
+|-------|-----------------|------|--------------|
+| `impacted-tests` | `REPOWISE_IMPACTED_TESTS` | none | Default `false`. Select tests and set the `impacted-tests` and `run-all-tests` outputs. |
+| `impacted-tests-runner` | `REPOWISE_IMPACTED_TESTS_RUNNER` | `--runner` | `auto` (default), `pytest`, `go`, `jest` or `files`. |
+
+The action and GitLab job first run `repowise update --index-only` on a
+restored index. If that fails, or selection cannot run, the answer is run
+everything with the reason, and the step still passes.
+
+<details><summary>Workflows: cache the index and branch on the outputs</summary>
+
+GitHub Actions. With `checks: ""` the action runs no gate.
+
+```yaml
+# .github/workflows/repowise-index.yml
+on: {push: {branches: [main]}}
+jobs:
+ index:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ with: {fetch-depth: 0}
+ - uses: actions/cache/restore@v4
+ with: {path: .repowise, key: "repowise-${{ github.sha }}", restore-keys: "repowise-"}
+ - run: pip install repowise
+ - run: if [ -f .repowise/state.json ]; then repowise update --index-only; else repowise init --yes --no-prose; fi
+ - uses: actions/cache/save@v4
+ with: {path: .repowise, key: "repowise-${{ github.sha }}"}
+```
+
+```yaml
+# in the pull request workflow
+- uses: actions/checkout@v4
+ with: {fetch-depth: 0}
+- uses: actions/cache/restore@v4
+ with: {path: .repowise, key: "repowise-${{ github.event.pull_request.base.sha }}", restore-keys: "repowise-"}
+- id: select
+ uses: repowise-dev/repowise@main
+ with: {checks: "", impacted-tests: true, impacted-tests-runner: pytest}
+- if: steps.select.outputs.run-all-tests != 'false'
+ run: pytest
+- if: steps.select.outputs.run-all-tests == 'false' && steps.select.outputs.impacted-tests != ''
+ env: {TESTS: "${{ steps.select.outputs.impacted-tests }}"}
+ run: eval "pytest $TESTS"
+```
+
+A skipped or failed step leaves `run-all-tests` empty, so `!= 'false'` runs
+everything.
+
+GitLab: `repowise-impacted-tests` writes the arguments to
+`impacted-tests.txt` and `RUN_ALL_TESTS` to a dotenv report.
+
+```yaml
+repowise-index:
+ image: python:3.12
+ variables: {GIT_DEPTH: "0"}
+ script:
+ - pip install repowise
+ - if [ -f .repowise/state.json ]; then repowise update --index-only; else repowise init --yes --no-prose; fi
+ cache: {key: repowise-index, paths: [.repowise/], policy: pull-push}
+ rules:
+ - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
+
+repowise-impacted-tests:
+ cache: {key: repowise-index, paths: [.repowise/], policy: pull}
+
+test:
+ needs: [{job: repowise-impacted-tests, optional: true}]
+ script:
+ - |
+ if [ "${RUN_ALL_TESTS:-}" != "false" ]; then pytest
+ elif [ -n "$(cat impacted-tests.txt 2>/dev/null)" ]; then eval "pytest $(cat impacted-tests.txt)"
+ fi
+```
+
+</details>
+
+### Options
+
+Full flag reference: [CLI_REFERENCE.md](../reference/CLI_REFERENCE.md#repowise-impacted-tests-revspec).
+
+| Option | What it does |
+|--------|--------------|
+| no range | CI: the pull request's change; locally: staged changes. |
+| `--runner pytest`, `go`, `jest` | Only that runner's tests, `tests.always_run` included. Several languages need one job per runner; left-out tests are counted on stderr and listed per runner under `left_out` in JSON. |
+| `--runner files` | Every test. |
+| `--prioritize` | The whole suite, selection first, so a job runs the head with `-x` and the rest after; skips nothing. Selected tests always come likeliest-to-fail first. |
+| `--explain <test>` | Why one test was or was not selected: first changed file reaching it, evidence (coverage, call graph, import graph), the import route, or the rule. JSON adds it as `explain`. |
+| `tests.full_run_on` | Gitignore patterns that run everything; a matching path is never scoped. |
+| `tests.always_run` | Appended to every selection as written, for the runner of each entry's language. |
+
+### What runs everything
+
+- An empty change.
+- A Cargo, Make, CMake, Docker or CI file.
+- Tool and runtime config: dotfiles, `.tool-versions`, root-level `*.toml`,
+ `*.yaml`, `*.json`, shell scripts.
+- `.repowise/config.yaml`, or a path `tests.full_run_on` matches.
+- A non-code file in a test tree.
+- A file with no known test, or only a filename guess.
+- A route through a test helper no test imports, unless every known test is
+ selected anyway (the reasons say so).
+- Any Python test helper while a conftest or pytest config loads plugins by
+ name.
+- A missing or unreadable index, or a per-test map at its row cap.
+- A deleted file no known test used.
+- A query or data file no code names.
+- A manifest named by over 200 non-test files outside its scope.
+- The index and conftest cases below.
+
+### What a changed file selects
+
+| Changed file | Selects |
+|--------------|---------|
+| nested `package.json`, lockfile or `go.mod` | tests under its directory and those reaching code there |
+| root lockfile, manifest or runner config; Python, Ruby, PHP, Gradle or Maven dependency files (pip requirements included); `tsconfig`; jest or vitest config | its whole ecosystem |
+| production package `__init__.py` | tests reaching any module under it |
+| doc, template, query, stylesheet, image or nested data file | tests reaching code that names it (outside comments and docstrings) |
+| doc, template, stylesheet or image no code names | its package's tests; Markdown, reST or AsciiDoc in no package and a top-level directory without code needs none |
+| `conftest.py`, test package `__init__.py`, imported test helper | tests under or importing it |
+| `docs/` or root README, CHANGELOG, LICENSE, CONTRIBUTING no code names | nothing (an empty line when only these changed); a test reading `README.md` names it |
+
+- Tests naming a manifest from outside its scope run too (a Python test reading
+ `package.json`). A path with a directory names only the files it can mean
+ (`packages/web/package.json` is not `packages/ui/package.json`); a bare name,
+ `../package.json` or a built path names every file of that name.
+- A namer under a fixture tree (`tests/fixtures/<name>/`) stands for test code
+ naming that tree or the fixtures directory; when none does, or code outside
+ the test trees names the tree's path, everything runs.
+- Wiring counts as a use: a JS/TS file under `setupFiles`,
+ `setupFilesAfterEnv`, `globalSetup` or `globalTeardown` in a `vitest.*`,
+ `jest.*`, `vite.*`, `playwright.*` config or `package.json` stands for that
+ package's tests; a helper a test names by relative path
+ (`Path(__file__).parent / "server.py"`, `path.join(__dirname, "server.ts")`)
+ stands for that test.
+- A `conftest.py` links only files pytest collects (`python_files`), so a
+ helper beside the tests is not on every conftest route.
+
+### Tests that always run
+
+Tests the graph cannot see into join every subset, with a count and reason
+(recorded once per test at index time,
+so selection opens no test file):
+
+- not indexed, or importing nothing resolvable;
+- Python, JavaScript or TypeScript tests listing and reading files under a
+ source directory (working directory, a module's location, or their own
+ location climbed out of the test directory; never fixtures, sibling data or
+ temp directories);
+- tests running the project's command, `python -m` module, project-importing
+ code or package `bin` in a child process;
+- Java or Kotlin `@SpringBootTest` (whole context); slices like `@WebMvcTest`
+ go through imports.
+
+<details><summary>Edge cases</summary>
+
+- `@SpringBootTest` inherited from a base class or carried by a custom
+ meta-annotation is not detected; such tests are selected through imports.
+- An index built before this check runs everything until `repowise update`
+ checks its tests.
+- A Python module named like a test outside every test directory is not a test
+ when the nearest pytest config's `testpaths` or `python_files` excludes it,
+ as a bare `pytest` does. A test CI only names explicitly outside `testpaths`
+ is therefore not seen: list it in `tests.always_run`.
+- In a JavaScript or TypeScript `src` tree, `tests/` is not a test directory
+ (it often holds a feature): a file there is a test only when named `.test.`
+ or `.spec.`, or held by a test directory such as `__tests__/`.
+
+</details>
+
+### Counted apart
+
+These run, but the summary counts them apart and JSON lists them:
+
+| Field | Holds |
+|-------|-------|
+| `selected.import_closure` | tests reached only through imports, over one file away, with no call path, coverage or paired name: an import error breaks them, though nothing they call runs the change |
+| `selected.broadcast` | tests a conftest adds that nothing else reaches |
+| `selected.basis` | what drove each selection |
+| `selected.why` | the `--explain` answer per selected test |
+
+### Conftest changes
+
+A change reaching a `conftest.py` only through imports selects tests asking for
+a fixture that uses it (directly, via other fixtures, `usefixtures` or
+`getfixturevalue`), plus one test under the conftest as an import check.
+
+- Every test under it runs when an autouse fixture, a `pytest_*` hook or
+ module-level code uses the change, or the conftest imports it only for side
+ effects (`selected.broadcast`).
+- Everything runs when a fixture request is unreadable (computed name, mark in
+ a variable, config `usefixtures`), the conftest loads plugins or is
+ unreadable, or the index predates this; the reasons name the cause.
+
+<details><summary>Edge cases and ceilings</summary>
+
+- `monkeypatch.setattr(mod.Cls, "name", ...)` on an imported module or its
+ class in an autouse fixture is left to the import check.
+- Reading an imported module's literal constant, or calling its function that
+ uses nothing it imports beyond standard modules that cannot load code by name
+ (emptying a `functools` cache or standard container counts), reaches only a
+ change in that module. A re-export (`from .console import NAMES as NAMES`)
+ passes this to the defining module.
+- Ceiling: such a function reading or running repo files by path (`open`,
+ `Path.read_text`, `os.system`) is judged by its imports only.
+- Ceiling: a change altering only import-time behaviour, seen by a test not
+ importing it, is caught by the import check alone.
+
+</details>
+
+### An index older than the change's base
+
+It is used as is. Files changed in between whose imports or module-name
+strings moved (outside Python and JavaScript/TypeScript, any non-whitespace
+change) add the tests reaching them; CI config and test data do not, since
+neither is imported. Everything runs when that commit is not in the clone,
+over 1,000 files changed in between, or one is a lockfile, manifest, build or
+test config, or `.repowise/config.yaml`.
+
+### Ceilings and expectations
+
+- Not seen: a test globbing docs or templates in another package; on the JVM
+ and .NET, a same-package test linked only by an unresolved call; a test
+ reaching the change through a string-loaded plugin or registry, a tree walk
+ or child process in a shared helper, or another language. List those in
+ `tests.always_run` and run the full suite on the default branch.
+- The subset is only as small as the code is loosely coupled: on this
+ repository the graph alone picks over 80% of test files, since most tests
+ import something importing the change. Real savings need a per-test map
+ measured at the change's base; `selected.basis` shows what drove each pick.
+
## When a gate exits 2
-| Message | Fix |
-|---------|-----|
-| "Could not diff ...: ... A shallow CI clone needs the base branch and enough history for a merge-base" | fetch full history |
-| "Could not tell which branch this change targets. Pass REVSPEC, e.g. origin/main...HEAD." | fetch the target branch, or pass the range |
-| "No coverage report found. Pass one with --report ..." | pass `--report`, or set `coverage.paths` |
-| "--report ...: no coverage report matches ..." | fix the path or glob, or upload the report from the test job |
-| "coverage.gates[N] ...: ..." | fix that entry of `coverage.gates` |
-| "All N report entries match coverage.ignore, so nothing is left to measure." | narrow `coverage.ignore` |
-| "No report path matched a file in this repository." | set `coverage.strip_prefix` or `coverage.path_prefix` |
-| "cannot read baseline ..." or "baseline ... is not valid JSON" | commit the file, or drop `--baseline` |
-| "Only N recent commits could be sampled; ranking a change needs at least 8." (risk) | fetch full history |
-| "The change-risk gate ranks the change against recent commits, and --baseline 0 turns that off." | drop `--baseline 0` |
-| "The risky-file gate reads bug-fix history, and this clone is shallow." | fetch full history |
-| "Could not read the risk of N changed files, so the risky-file gate cannot run." | fetch full history, or index the repository |
-| "The coverage report has no per-line branch data, so --fail-under-branches cannot be judged." | turn on branch coverage in the test run, or drop the flag |
-| "The stored coverage predates per-line branch data ..." | re-run `repowise coverage add` with the report |
-| "The max-drop gate needs coverage measured at the change's base ..." | pass `--base-report`, or ingest a report at the base commit |
-| "Project coverage cannot be compared ..." | measure the base and the head the same way (same full reports, same `coverage.ignore`) |
-| "Base report: No report path matched a file in this repository." | the base report must name files the base commit tracked; check its prefix |
+- "Could not diff ...: ... A shallow CI clone needs the base branch and enough history for a merge-base": fetch full history.
+- "Could not tell which branch this change targets. Pass REVSPEC, e.g. origin/main...HEAD.": fetch the target branch, or pass the range.
+- "No coverage report found. Pass one with --report ...": pass `--report`, or set `coverage.paths`.
+- "--report ...: no coverage report matches ...": fix the path or glob, or upload the report from the test job.
+- "coverage.gates[N] ...: ...": fix that entry of `coverage.gates`.
+- "All N report entries match coverage.ignore, so nothing is left to measure.": narrow `coverage.ignore`.
+- "No report path matched a file in this repository.": set `coverage.strip_prefix` or `coverage.path_prefix`.
+- "cannot read baseline ..." or "baseline ... is not valid JSON": commit the file, or drop `--baseline`.
+- "Only N recent commits could be sampled; ranking a change needs at least 8." (risk): fetch full history.
+- "The change-risk gate ranks the change against recent commits, and --baseline 0 turns that off.": drop `--baseline 0`.
+- "The risky-file gate reads bug-fix history, and this clone is shallow.": fetch full history.
+- "Could not read the risk of N changed files, so the risky-file gate cannot run.": fetch full history, or index the repository.
+- "The coverage report has no per-line branch data, so --fail-under-branches cannot be judged.": turn on branch coverage, or drop the flag.
+- "The stored coverage predates per-line branch data ...": re-run `repowise coverage add` with the report.
+- "The max-drop gate needs coverage measured at the change's base ...": pass `--base-report`, or ingest a report at the base commit.
+- "Project coverage cannot be compared ...": measure base and head the same way (same full reports, same `coverage.ignore`).
+- "Base report: No report path matched a file in this repository.": the base report must name files the base commit tracked; check its prefix.
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/README.md b/packages/core/src/repowise/core/analysis/health/biomarkers/README.md
index d02cf9ee2..c35243c9f 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/README.md
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/README.md
@@ -9,13 +9,23 @@ class Biomarker(Protocol):
def detect(self, ctx: FileContext) -> list[BiomarkerResult]: ...
```
-## Registered detectors (26)
+## Registered detectors
+
+`registry.py` registers 54 detectors: the 29 code-health markers below, 22
+performance markers and 3 SQL maintainability markers. Every id with its threshold
+and weight is in
+[the full roster](../../../../../../../../docs/architecture/code-health.md#the-full-roster).
+
+Caps below are per category. History (organizational) is a hard cap; every other
+defect category bends toward its cap on a saturating curve and can deduct up to
+3.09 times it (`shape_curve.py`).
Structural complexity (cap −2.5):
- `brain_method` — symbols simultaneously long, complex, and central. The
centrality gate is language-agnostic: `dependents ≥ min(8, max(repo p80, 3))`,
so it fires on sparse-graph languages (TS/Rust) instead of assuming
- Python's import density.
+ Python's import density. Advisory: listed, deducts nothing, since
+ `complex_method` and `large_method` already charge the same function.
- `low_cohesion` — a class whose methods form unrelated clusters (LCOM4 ≥ 2).
- `god_class` — a large class (≥ 200 NLOC, ≥ 15 methods) that also hides a
brain method.
@@ -25,7 +35,8 @@ Structural complexity (cap −2.5):
Size & complexity (cap −1.5):
- `complex_method` — functions with CCN ≥ 9.
-- `large_method` — functions exceeding the NLOC threshold.
+- `large_method`: functions of 60+ code lines with a judged CCN of at least 3
+ (severity bands at 60, 90, 120 and 200 lines).
- `primitive_obsession` — many primitive parameters in a single signature
(suppressed in very small modules, where a wide signature is idiomatic).
@@ -37,21 +48,17 @@ Test coverage (cap −2.0):
- `coverage_gap` — non-test files with meaningful uncovered surface.
- `untested_complexity` — functions whose CRAP score (`CC² × (1 − cov)³ + CC`,
`health/crap.py`) is 30 or more, on measured coverage or a reach tier.
- Advisory: filed here, deducts nothing, since complexity and coverage already
- deduct through their own markers.
+ Advisory.
Test coverage — continuous (cap −2.0, own category `test_coverage_gradient`):
- `coverage_gradient` — a per-file deduction that scales **continuously** with
- the uncovered fraction (`4.0 × (1 − line_coverage_pct/100)`, capped) for files
- with KNOWN coverage; silent when coverage was never ingested (absent ≠
- uncovered). Unlike the binary gates above it fires across the whole 0–100%
- range, so well-tested files at 85–99% still carry proportional signal. Uses
- the `deduction` override on `BiomarkerResult` (continuous magnitude in place of
- the discrete severity table), kept in its own capped category so it neither
- squeezes nor is squeezed by the binary gates. Calibrated offline: +0.043 corpus
- AUC [95% CI +0.023, +0.061] on the covered subset, Popt-neutral.
-
-Organizational (cap −3.5):
+ the uncovered fraction (`4.0 × (1 − line_coverage_pct/100)`) for files with
+ KNOWN coverage; silent when coverage was never ingested (absent ≠ uncovered).
+ It uses the `deduction` override on `BiomarkerResult`. Rationale and
+ calibration: `docs/architecture/code-health.md`, marker notes.
+
+Organizational (hard cap `history_cap`: 1.0 plus the file's other defect
+deduction, at most −3.5; the largest finding counts whole, the rest at 0.25):
- `developer_congestion` — too many active authors competing on a file.
- `knowledge_loss` — primary authors no longer active (de-rated to 0.4).
- `hidden_coupling` — files that co-change in history without an explicit
@@ -64,49 +71,42 @@ Organizational (cap −3.5):
- `ownership_risk` — long-run ownership dispersion: many minor
contributors (each < 5% of commits) or no dominant owner. Bird's
strongest literature defect correlate.
-- `churn_risk` — relative churn: a file whose 90-day window rewrote a
- large fraction of its own lines (size-normalized, so it doesn't simply
- re-flag big files).
+- `churn_risk`: a file whose 90-day window rewrote a large fraction of its
+ own lines (size-normalized, so it doesn't re-flag big files).
- `change_entropy` — Hassan's History Complexity Metric: how scattered a
- file's changes are across noisy commits (not a churn proxy). Reads the
- FULL-tier `change_entropy` / `change_entropy_pct` git fields.
-- `co_change_scatter` — breadth of co-change coupling: a file coupled to
- many others (shotgun surgery). Complements `hidden_coupling`, which
- flags specific undeclared pairs.
-- `prior_defect` — recent bug-fix history: the count of bug-fix commits
- touching the file in the trailing ~6-month window (same keyword rule the
- defect benchmark labels fixes with, anchored to the index's `as_of`
- reference so historical/T0 scoring stays leakage-free). Reads the
- `prior_defect_count` git field. **Neutral weight (1.0) by design** — on the
- calibration corpus it is largely redundant with `change_entropy`/`churn_risk`
- (no measured lift), so it ships as an interpretable, actionable finding
- ("bug-fixed N times recently") rather than a boosted predictor.
+ file's changes are across noisy commits. Reads `change_entropy` /
+ `change_entropy_pct`.
+- `co_change_scatter`: a file coupled to many others (shotgun surgery);
+ `hidden_coupling` flags specific undeclared pairs.
+- `prior_defect`: recent bug-fix history, bug-fix commits touching the file
+ in the trailing ~6-month window, anchored to the index's `as_of` so T0
+ scoring stays leakage-free. Reads `prior_defect_count`. **Neutral weight
+ (1.0) by design**: largely redundant with `change_entropy` / `churn_risk`, it
+ ships as an actionable finding ("bug-fixed N times recently").
Test quality (cap −0.5, test files only):
- `large_assertion_block` — a test function with a run of ≥ 15 consecutive
assertions (one case testing many behaviours at once).
- `duplicated_assertion_block` — copy-pasted assertion runs across tests,
found by intersecting the clone detector with assertion spans.
+- `assertion_free_test`: a test that checks nothing. Advisory.
+- `mock_saturated_test`: mock setup that dwarfs the assertions. Advisory.
Error handling (cap −0.5, own category `error_handling`):
- `error_handling` — swallowed-exception / unsafe-unwrap anti-patterns: an
empty or trivial `catch`/`except` body (Python/JS/TS/Java/Kotlin/C#/C++), a
Python catch-all `except:` / `except Exception:`, Rust `.unwrap()` /
`.expect()` / panic-family macros, and Go's empty `if err != nil {}` or
- blank-identifier discard of a call's error. One LOW finding per occurrence
- (0.15 after the floored 0.5 weight), bounded at 0.5/file by the category
- cap. **A maintainability flag, not a defect predictor** — AUC-neutral on
- the 21-repo T0 benchmark and deliberately excluded from the defect
- calibration roster; it ships because developers expect a health tool to
- flag `except: pass`. Detection is precision-first (unambiguous shapes only;
- unsupported language / parse failure ⇒ no signal) and runs as a whole-tree
- pass in the complexity walker, so module-level code is covered too.
-
-Caps were recalibrated to lift `organizational` (was −1.0) and de-rate
-`size_and_complexity` / `duplication` per plan §3.1. A per-marker
-weight multiplier in `scoring._BIOMARKER_WEIGHT_MULTIPLIER` lets the
-strongest empirical predictors deduct more than the uniform severity
-table alone would allow.
+ blank-identifier discard of a call's error.
+- One LOW finding per occurrence (0.15 after the floored 0.5 weight); the
+ category deducts at most about 1.5 under the curve. **A maintainability flag,
+ not a defect predictor**: AUC-neutral on the 21-repo T0 benchmark and
+ excluded from the defect calibration. Precision-first (unsupported language or
+ parse failure ⇒ no signal), in a whole-tree walker pass.
+
+A per-marker weight multiplier in `scoring._BIOMARKER_WEIGHT_MULTIPLIER` lets
+the strongest empirical predictors deduct more than the uniform severity table
+alone would allow.
## Inputs
@@ -157,12 +157,16 @@ attributable.
## Extension points
-To add a 13th marker:
+To add a marker:
1. New file `biomarkers/my_marker.py` with a class implementing the
`Biomarker` protocol.
2. Append to `_DETECTOR_FACTORIES` in `registry.py`.
-3. Add the marker → category mapping in `scoring._BIOMARKER_CATEGORY`.
-4. Add a suggestion template in `suggestions._TEMPLATES`.
+3. List it in `scoring._BIOMARKER_DIMENSIONS` (an unlisted marker defaults into
+ defect), then add it to its dimensions' category and weight tables, or to
+ `_ADVISORY_HOME` for an advisory marker.
+4. Add a label in `biomarker_labels.BIOMARKER_LABELS` and a suggestion template
+ in `suggestions._TEMPLATES`.
5. Add a unit test under `tests/unit/health/`.
-6. Update this README's "Registered v1 detectors" list.
+6. Update this README's "Registered detectors" list and the roster in
+ `docs/architecture/code-health.md`.
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/README.md b/packages/core/src/repowise/core/analysis/health/coverage/README.md
index 7166f5a97..fb660a6e6 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/README.md
+++ b/packages/core/src/repowise/core/analysis/health/coverage/README.md
@@ -28,6 +28,15 @@ from repowise.core.analysis.health.coverage import (
percentage. JaCoCo XML is read from per-line `<sourcefile>` data (lines
and branches); package paths such as `com/foo/Bar.java` and Go module
paths are mapped to repo files by suffix matching.
+- `detect_format(text)`: returns the sniffed format or ``None``.
+- `is_test_file(path, source=None, *, roots=None)`: path + optional content
+ heuristic; pass pytest `roots` so a module pytest does not collect is not a
+ test. Callers holding the stored `is_test` flag use that instead.
+- `paired_test_file(path, all_paths)`: find the conventional test partner for
+ a source path.
+- `contexts.py` (`parse_contexts_file`, `parse_lcov_contexts`): per-test readers
+ for a coverage.py `.coverage` SQLite file with contexts and for per-test LCOV
+ `TN:` records; a report without contexts yields no records.
### Repowise normalized JSON (`repowise-coverage-v1`)
@@ -53,11 +62,8 @@ normalized once (keyed by repo-relative POSIX path) and fed to
`files` may also be a list of the same objects, each with its own
`file_path`. Tolerant: any two of `(line_coverage_pct, covered_lines,
total_coverable_lines)` pin a file down; an entry that anchors none is
-skipped (absent ≠ zero).
-- `detect_format(text)` — returns the sniffed format or ``None``.
-- `is_test_file(path, source=None, *, roots=None)` — path + optional content heuristic; pass pytest `roots` so a module pytest does not collect is not a test. Callers holding the stored `is_test` flag use that instead.
-- `paired_test_file(path, all_paths)` — find the conventional test
- partner for a source path.
+skipped (absent ≠ zero). An optional `coverable_lines` array gives the
+executable-line set patch coverage needs.
## Discovery + path resolution (`discovery.py`)
@@ -94,28 +100,12 @@ writes paths relative to its own `<source>` root — so we reconcile them.
### Config (`.repowise/config.yaml`)
-All keys optional; the defaults give zero-config auto-discovery during
-`repowise init` / `repowise update`.
-
-```yaml
-coverage:
- auto_discover: true # discover reports during indexing
- artifacts: # override the default discovery globs
- - coverage/lcov.info
- paths: # explicit report paths or globs (skip discovery)
- - build/coverage/lcov.info
- - {path: "api/**/lcov.info", path_prefix: api} # per-report prefix
- format: lcov # force a parser (else content-sniffed)
- strip_prefix: build # drop a leading prefix from report paths
- path_prefix: packages/web # prepend a prefix to report paths
- ignore: ["gen/"] # gitignore-style globs coverage leaves out
- reingest_on_update: false # re-parse on every update (else reuse DB rows)
- fail_under: 80 # patch-coverage gate for `coverage check`
- min_coverable_lines: 5 # small-change tolerance for that gate
- gates: # path-scoped gates (PathGate); see below
- - {name: api, paths: ["/services/api/"], fail_under: 85}
-```
-
+All keys are optional; the defaults give zero-config auto-discovery during
+`repowise init` / `repowise update`. The full `coverage:` block is in
+`docs/layers/TEST_INTELLIGENCE.md#configuration`; besides those keys, a
+top-level `path_prefix` prepends a prefix to every report path, and
+`reingest_on_update` re-reads reports on every update when `true`, never when
+`false`, and when one is newer than the last ingest when unset.
`CoverageConfig.from_repo_config(load_repo_config(repo_path))` parses it.
Each `gates` entry is `name`, `paths` (gitignore-style globs, at least one
not a `!` exclusion), optional `fail_under` (0-100) and optional