Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(risk): add --exclude flag, .riskignore support, and get_change_r… (#867)
Matthew Barr70def7c29be3
diff --git a/docs/CHANGE_RISK.md b/docs/CHANGE_RISK.mdindex 4cf56b565..146baef47 100644--- a/docs/CHANGE_RISK.md+++ b/docs/CHANGE_RISK.md@@ -11,12 +11,23 @@ repowise risk # score HEADrepowise risk abc123 # score a single commitrepowise risk main..HEAD # score a branch / PR range as one changerepowise risk main..HEAD --ext .py # count only .py files+repowise risk main..HEAD -x 'tests/' -x '*.spec.ts' # omit matching pathsrepowise risk --format json # machine-readable```It runs in-process: pure `git` + learned constants. **No LLM, no network, and noblame at runtime**: SZZ labelling lives entirely in the offline calibration.+## Excluding paths++Use repeatable `--exclude` / `-x` flags with gitignore-style patterns to omit+files from a score. The same filters apply to the requested change and the+recent commits sampled for its percentile, so the comparison remains like for+like. Put project-wide, risk-only rules in a repository-root `.riskignore`;+those patterns apply automatically and are combined with any command-line+flags. For example, `tests/` excludes that directory recursively, while+`test_*.py` excludes matching test filenames anywhere in the repository.+## What it measuresThe model uses Kamei-style *change* metrics (Kamei et al., "A large-scale@@ -81,6 +92,9 @@ live in `packages/core/src/repowise/core/analysis/change_risk/model.py`.## Cross-repo change risk (workspace mode)+> **Note:** This section describes `get_risk` in PR mode (`changed_files`). `get_change_risk` is+> pure diff-shape scoring and does not access the workspace graph — it produces no cross-repo fields.+In a workspace, a change rarely stops at the repo boundary. When `get_risk` iscalled in PR mode (`changed_files`), its `directive` block gains two cross-repofields derived from the [system graph](WORKSPACES.md#system-graph):diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.mdindex 930f37c37..b66b52a42 100644--- a/docs/CLI_REFERENCE.md+++ b/docs/CLI_REFERENCE.md@@ -386,6 +386,7 @@ to the model's baseline commit, not this repo.|------|-------------|| `--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 calibrated band) || `--format` | Output format: `table` (default) or `json` |@@ -393,6 +394,7 @@ to the model's baseline commit, not this repo.repowise risk # score HEADrepowise risk main..HEAD # score a branch / PR range as one changerepowise risk --ext .ts,.tsx # restrict to specific suffixes+repowise risk main..HEAD -x 'tests/' -x '*.spec.ts' # omit tests from scoring```See [`docs/CHANGE_RISK.md`](./CHANGE_RISK.md) for the scoring model.@@ -844,7 +846,7 @@ If `PATH` is omitted, `repowise mcp` first walks upward from the current directo|------|-------------|| `--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 five-tool agent-lean profile. Overrides the `mcp.tools` config block. |+| `--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 |```bashdiff --git a/docs/CONFIG.md b/docs/CONFIG.mdindex d4d89bea2..f7fa66dde 100644--- a/docs/CONFIG.md+++ b/docs/CONFIG.md@@ -150,7 +150,7 @@ distill:### The `mcp:` blockControls which tools the MCP server advertises. The default surface is curated-(10 tools in single-repo mode, plus 2 workspace-only tools in workspace mode);+(11 tools in single-repo mode, plus 2 workspace-only tools in workspace mode);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.@@ -165,7 +165,7 @@ mcp:- `+name` / `-name` entries add to or remove from the default set; anunprefixed list is treated as an explicit allowlist.- `lean` selects the agent-lean profile: `get_answer`, `get_context`,- `get_symbol`, `search_codebase`, `get_risk` (plus `list_repos` in workspace+ `get_symbol`, `search_codebase`, `get_risk`, `get_why` (plus `list_repos` in workspacemode), 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 `get_conformance` (the last only usable indiff --git a/docs/MCP_TOOLS.md b/docs/MCP_TOOLS.mdindex c0587777a..a6c0f97c7 100644--- a/docs/MCP_TOOLS.md+++ b/docs/MCP_TOOLS.md@@ -2,7 +2,7 @@repowise exposes a curated set of tools via the [Model Context Protocol](https://modelcontextprotocol.io) (MCP). These tools give AI coding assistants (Claude Code, Codex, Cursor, Cline, Windsurf) structured access to your codebase intelligence: dependency graph, git history, documentation, and architectural decisions.-16 tools are registered in total. A single-repo server advertises 10 by default: the nine flagship tools below plus `list_repos`. Workspace mode adds 2 more automatically (`get_architecture`, `get_blast_radius`), for 12. Four further tools are off by default everywhere and must be opted in. The surface is configurable; see [Configuring the tool surface](#configuring-the-tool-surface).+17 tools are registered in total. A single-repo server advertises 11 by default: the ten flagship tools below plus `list_repos`. Workspace mode adds 2 more automatically (`get_architecture`, `get_blast_radius`), for 13. Four further tools are off by default everywhere and must be opted in. The surface is configurable; see [Configuring the tool surface](#configuring-the-tool-surface).**Start the MCP server:**@@ -16,7 +16,7 @@ repowise mcp --transport sse --port 7338 # legacy SSE transport----## The nine flagship tools+## The ten flagship tools| Tool | Purpose | Typical use ||------|---------|-------------|@@ -26,6 +26,7 @@ repowise mcp --transport sse --port 7338 # legacy SSE transport| `get_symbol` | Raw source bytes for one symbol | When you need one function/class body || `search_codebase` | Hybrid symbol / path / concept search | Finding a symbol or file, or discovering code by topic || `get_risk` | Modification risk | Before changing hotspot files |+| `get_change_risk` | Live commit or range risk | Before merging a commit or PR range || `get_why` | Architectural decisions | Before structural changes || `get_dead_code` | Unreachable code | Cleanup tasks || `get_health` | Code-health marker scores | Before refactoring, find the worst files |@@ -38,8 +39,8 @@ Also always on by default: `list_repos` (repo aliases). See [Supplementary toolsThe default surface is deliberately small: fewer, richer tools mean fewer round-trips and less schema overhead per task. What a server advertises is resolved from three things: each tool's `default`/`requires_workspace` metadata, whether the server is in workspace mode, and an optional override.-- **Default (single-repo):** 10 tools, the nine flagship tools plus `list_repos`.-- **Default (workspace):** those 10 plus `get_architecture` and `get_blast_radius`, added automatically when the server starts inside a workspace. They are never advertised outside one.+- **Default (single-repo):** 11 tools, the ten flagship tools plus `list_repos`.+- **Default (workspace):** those 11 plus `get_architecture` and `get_blast_radius`, added automatically when the server starts inside a workspace. They are never advertised outside one.- **Opt-in tools:** `get_dependency_path`, `get_execution_flows`, `generate_refactoring_code`, and `get_conformance` are registered but off by default. Turn them on per repo; `get_conformance` only does useful work in workspace mode (name it there).**Configure it in `.repowise/config.yaml`** under an `mcp.tools` key. Four shapes are supported:@@ -332,6 +333,41 @@ get_risk(changed_files=["src/api/routes.ts", "src/middleware/cors.ts"])---+## `get_change_risk`++Live risk scoring for one commit or a `base..head` range. Unlike `get_risk`,+which evaluates indexed files and can report blast radius, this scores the+shape of the live diff and needs no index refresh.++**Parameters:**++| Parameter | Type | Required | Description |+|-----------|------|----------|-------------|+| `revspec` | string | No | Commit or `base..head` range to score (default `"HEAD"`) |+| `repo` | string | No | *(workspace only)* Target repo alias |+| `extensions` | list[string] | No | File suffixes to count, such as `[".py", ".ts"]` |+| `exclude_patterns` | list[string] | No | Gitignore-style paths to omit; combined with root `.riskignore` rules |+| `baseline` | int | No | Recent commits to sample for percentile ranking (default `200`; `0` disables percentile ranking) |++**Returns:** The corpus-calibrated `score`, `probability`, and `level`, plus a+repo-relative `risk_percentile`, `review_priority`, and `classification`.+`baseline_sample_size` reports how many filtered commits informed the percentile;+`features`, `drivers`, and combined `exclude_patterns` make the result auditable.+Use the percentile and review priority for triage; the raw score is secondary+context when no repository baseline is available.++**When to use:** Before merging a commit or PR range, especially when you need+to assess the diff itself rather than the risk of an already-indexed file.++**Example calls:**++```+get_change_risk()+get_change_risk(revspec="main..HEAD", extensions=[".py"], exclude_patterns=["tests/"])+```++---+## `get_why`Architectural decision intelligence. Falls back to git archaeology when no decision records exist for a path, and further to a rationale comment mined live from the source when neither decisions nor git history explain the "why".diff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.mdindex e20f954fa..27cc90297 100644--- a/docs/QUICKSTART.md+++ b/docs/QUICKSTART.md@@ -228,7 +228,7 @@ REPOWISE_API_URL=http://localhost:7337 npm run dev --workspace packages/web- **[User Guide](USER_GUIDE.md)** — full CLI reference, web UI features, MCP setup, common workflows, and troubleshooting- **[CLI Reference](CLI_REFERENCE.md)** — every command with every flag-- **[MCP Tools](MCP_TOOLS.md)** — all 9 MCP tools with parameters and examples+- **[MCP Tools](MCP_TOOLS.md)** — full tool reference, configuration, parameters, and examples- **[Workspaces](WORKSPACES.md)** — multi-repo workspace setup and cross-repo intelligence- **[Auto-Sync](AUTO_SYNC.md)** — hooks, file watcher, webhooks, polling- **[Architecture](architecture/ARCHITECTURE.md)** — how repowise is built internallydiff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.mdindex 94ae93f73..16f2d4784 100644--- a/docs/USER_GUIDE.md+++ b/docs/USER_GUIDE.md@@ -377,7 +377,7 @@ This is how you connect repowise to Claude Code, Cursor, Cline, Windsurf, and ot| `--transport` | Protocol: `stdio` (default, for editors), `streamable-http` (for HTTP clients), or `sse` (legacy) || `--port` | Port for HTTP/SSE transports (default: 7338) |-**MCP tools exposed (9 tools):**+**Default single-repo MCP tools (11 tools):**| Tool | What it does ||------|-------------|@@ -387,9 +387,11 @@ This is how you connect repowise to Claude Code, Cursor, Cline, Windsurf, and ot| `get_symbol` | Raw source bytes for one indexed symbol with exact line bounds (cheaper/safer than `Read` + offset math) || `search_codebase` | Semantic search over wiki with git freshness boosting. In workspace mode, searches across all repos. || `get_risk` | Modification risk assessment, hotspot score, dependents, co-change partners, bus factor, blast radius, test gaps, 0–10 risk score |+| `get_change_risk` | Live commit or range risk score, ranked against recent commits in the same repository || `get_why` | Why code is structured the way it is, architectural decisions, git archaeology. Three modes: NL search, path-based, health dashboard. || `get_dead_code` | Tiered dead code report grouped by confidence with cleanup impact estimates || `get_health` | 25-marker code-health scores, dashboard KPIs + lowest-scoring files, or per-file findings; `include` for refactoring suggestions and trend alerts |+| `list_repos` | Repository aliases served by this MCP server |In workspace mode, tools are workspace-aware, pass `repo="backend"` to target a specific repo or `repo="all"` to query across the entire workspace. The default repo is used when `repo` is omitted.diff --git a/packages/cli/src/repowise/cli/commands/mcp_cmd.py b/packages/cli/src/repowise/cli/commands/mcp_cmd.pyindex 2a94056fb..be5aca380 100644--- a/packages/cli/src/repowise/cli/commands/mcp_cmd.py+++ b/packages/cli/src/repowise/cli/commands/mcp_cmd.py@@ -91,7 +91,7 @@ def _print_network_startup("Override which tools are exposed. A comma-separated list is an ""explicit allowlist; prefix names with + or - to adjust the default ""set (e.g. '+get_dependency_path,-get_dead_code'); 'lean' selects "- "the five-tool agent-lean profile. Overrides the mcp.tools config "+ "the six-tool agent-lean profile. Overrides the mcp.tools config ""block."),)@@ -112,9 +112,9 @@ def mcp_command("""Start the MCP server for editor integration.Exposes a curated set of tools for querying the repowise wiki via the MCP- protocol: ten in single-repo mode, plus three workspace-only tools in- workspace mode. Two more (get_dependency_path, get_execution_flows) are- opt-in via ``--tools`` or the ``mcp.tools`` config block. Supports stdio+ protocol: eleven by default in single-repo mode, plus two more by default+ in workspace mode. Four more are opt-in via ``--tools`` or the+ ``mcp.tools`` config block. Supports stdio(for Claude Code, Codex, Cursor, Cline), streamable HTTP, and legacy SSEtransports.@@ -127,7 +127,7 @@ def mcp_command(repowise mcp # stdio, current directoryrepowise mcp /path/to/repo # stdio, specific reporepowise mcp --tools +get_execution_flows # default set plus one- repowise mcp --tools lean # five-tool agent-lean profile+ repowise mcp --tools lean # six-tool agent-lean profilerepowise mcp --all # every available toolrepowise mcp --transport streamable-http # HTTP on port 7338"""diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd.py b/packages/cli/src/repowise/cli/commands/risk_cmd.pyindex a5d8c48a6..99ea6847f 100644--- a/packages/cli/src/repowise/cli/commands/risk_cmd.py+++ b/packages/cli/src/repowise/cli/commands/risk_cmd.py@@ -14,16 +14,17 @@ Examples:from __future__ import annotationsimport json-from dataclasses import replaceimport clickfrom rich.table import Tablefrom repowise.cli.helpers import console, err_console+from repowise.core.analysis.change_risk import (+ change_risk_payload,+ review_priority_classification,+ score_live_change,+)-# Repo-relative tercile wording — mirrors the web UI's PriorityBadge so the same-# commit reads the same in both surfaces.-_PRIORITY_LABEL = {"high": "Elevated", "moderate": "Typical", "low": "Below typical"}_PRIORITY_COLOR = {"high": "yellow", "moderate": "dim", "low": "green"}_PRIORITY_LEAD = {"low": "Lower risk than a typical commit in this repo",@@ -31,10 +32,6 @@ _PRIORITY_LEAD = {"high": "Riskier than most commits in this repo",}-# Below this many sampled commits a percentile isn't worth showing — fall back-# to the absolute calibrated band instead.-_MIN_BASELINE = 8-def _ordinal(n: int) -> str:"""1 -> '1st', 2 -> '2nd', 93 -> '93rd', 11 -> '11th'."""@@ -66,6 +63,14 @@ def _ordinal(n: int) -> str:help="Sample this many recent commits to rank the change within the repo ""(0 disables; shows only the absolute calibrated band).",)+ "--exclude",+ "-x",+ "exclude",+ multiple=True,+ metavar="PATTERN",+ help="Gitignore-style pattern to exclude. Repeatable; also applies to the baseline.",+)@click.option("--format","fmt",@@ -74,104 +79,54 @@ def _ordinal(n: int) -> str:help="Output format.",)def risk_command(- revspec: str, repo_path: str, ext: str | None, baseline: int, fmt: str+ revspec: str,+ repo_path: str,+ ext: str | None,+ baseline: int,+ exclude: tuple[str, ...],+ fmt: str,) -> None:"""Score the defect risk of a change (commit or ``base..head`` range)."""- from repowise.core.analysis.change_risk import (- baseline_scores,- extract_commit_features,- extract_range_features,- score_change,- )-- extensions = tuple(e if e.startswith(".") else f".{e}" for e in ext.split(",")) if ext else ()+ extensions = tuple(e.strip() for e in ext.split(",")) if ext else ()status = err_console if fmt != "table" else console+ if baseline and fmt == "table":+ status.print(f"[dim]Sampling up to {baseline} recent commits…[/dim]")try:- if ".." in revspec:- base, _, head = revspec.partition("..")- head = head or "HEAD"- features = extract_range_features(repo_path, base, head, extensions=extensions)- else:- features = extract_commit_features(repo_path, revspec, extensions=extensions)+ result = score_live_change(+ repo_path,+ revspec,+ extensions=extensions,+ exclude_patterns=exclude,+ baseline=baseline,+ )except Exception as exc:# Surface git errors (bad revspec, not a repo) as a clean CLI message.raise click.ClickException(f"Could not read change {revspec!r} in {repo_path}: {exc}") from exc+ features = result.features+ risk = result.risk+ percentile = result.percentile+ priority = result.priority+ request_excludes = result.request_excludes+if features.nf == 0:status.print(f"[yellow]No counted file changes in {revspec!r} "- f"(check the revspec or --ext filter).[/yellow]"+ f"(check the revspec, --ext, or exclusion filters).[/yellow]")- risk = score_change(features)-- # Repo-relative ranking: where this change sits in the repo's own recent- # distribution. The raw score is corpus-anchored and skews high on repos- # whose typical commit is large; the percentile is the portable signal.- percentile: float | None = None- priority: str | None = None- if baseline:- if ".." in revspec:- _, _, anchor = revspec.partition("..")- anchor, exclude = anchor or "HEAD", ""- else:- anchor, exclude = revspec, features.ref- if fmt == "table":- status.print(f"[dim]Sampling up to {baseline} recent commits…[/dim]")- scores = baseline_scores(repo_path, anchor, baseline, extensions, exclude)- if len(scores) >= _MIN_BASELINE:- from repowise.core.analysis.change_risk import RiskNormalizer-- normalizer = RiskNormalizer.from_scores(scores)- # Rank with experience unknown, matching the baseline (diff-shape- # percentile within the repo) — keeps the comparison like-with-like.- rank_score = score_change(replace(features, exp=None)).score- percentile = normalizer.percentile(rank_score)- priority = normalizer.priority(rank_score)-if fmt == "json":- click.echo(- json.dumps(- {- "ref": features.ref,- "score": risk.score,- "probability": round(risk.probability, 4),- "level": risk.level,- "risk_percentile": round(percentile, 1) if percentile is not None else None,- "review_priority": priority,- "is_fix": features.is_fix,- "features": {- "la": features.la,- "ld": features.ld,- "nf": features.nf,- "nd": features.nd,- "ns": features.ns,- "entropy": round(features.entropy, 4),- "exp": features.exp,- },- "drivers": [- {- "feature": d.feature,- "value": d.value,- "contribution": round(d.contribution, 4),- "label": d.label,- }- for d in risk.top_drivers- ],- },- indent=2,- )- )+ click.echo(json.dumps(change_risk_payload(result), indent=2))returnif percentile is not None and priority is not None:pcolor = _PRIORITY_COLOR[priority]console.print(f"\n[bold]Change risk[/bold] for [cyan]{features.ref}[/cyan]: "- f"[{pcolor}]{_PRIORITY_LABEL[priority]}[/{pcolor}] · "+ f"[{pcolor}]{review_priority_classification(priority)}[/{pcolor}] · "f"{_ordinal(round(percentile))} percentile of recent commits")else:@@ -184,6 +139,8 @@ def risk_command()if features.subject:console.print(f" [dim]{features.subject}[/dim]")+ if request_excludes:+ console.print(f" [dim]Excluding {len(request_excludes)} pattern(s).[/dim]")console.print(f" +{features.la} / -{features.ld} lines · {features.nf} files · "f"{features.nd} dirs · {features.ns} subsystems · "diff --git a/packages/core/src/repowise/core/analysis/change_risk/__init__.py b/packages/core/src/repowise/core/analysis/change_risk/__init__.pyindex e1b6d4ce1..fe9a23ffe 100644--- a/packages/core/src/repowise/core/analysis/change_risk/__init__.py+++ b/packages/core/src/repowise/core/analysis/change_risk/__init__.py@@ -17,16 +17,29 @@ from .features import (features_from_file_changes,)from .model import ChangeRisk, RiskDriver, score_change-from .normalize import RiskNormalizer+from .normalize import RiskNormalizer, review_priority_classification+from .service import (+ ChangeRiskResult,+ change_risk_payload,+ normalize_extensions,+ riskignore_patterns,+ score_live_change,+)__all__ = ["ChangeFeatures","ChangeRisk",+ "ChangeRiskResult","RiskDriver","RiskNormalizer","baseline_scores",+ "change_risk_payload","extract_commit_features","extract_range_features","features_from_file_changes",+ "normalize_extensions",+ "review_priority_classification",+ "riskignore_patterns","score_change",+ "score_live_change",]diff --git a/packages/core/src/repowise/core/analysis/change_risk/baseline.py b/packages/core/src/repowise/core/analysis/change_risk/baseline.pyindex c7f2adda7..9c43441b4 100644--- a/packages/core/src/repowise/core/analysis/change_risk/baseline.py+++ b/packages/core/src/repowise/core/analysis/change_risk/baseline.py@@ -10,6 +10,8 @@ from __future__ import annotationsimport subprocess+import pathspec+from .features import features_from_file_changesfrom .model import score_change@@ -19,7 +21,8 @@ def baseline_scores(anchor: str,limit: int,extensions: tuple[str, ...],- exclude: str,+ excluded_ref: str,+ exclude_patterns: tuple[str, ...] = (),) -> list[float]:"""Score the repo's recent commits to build a local risk distribution.@@ -27,6 +30,10 @@ def baseline_scores(cheap enough for a pre-merge gate. Experience is left unknown for thebaseline; the target is ranked with experience likewise unknown, so thecomparison is like-with-like: a diff-shape percentile within this repo.+ *excluded_ref* is a full or abbreviated Git ref for the target commit to+ omit from its own sample. It is unrelated to path exclusions.+ *exclude_patterns* use gitignore syntax and are applied to every sampled+ commit, matching the target change's filtering."""out = subprocess.run(["git", "log", f"-n{limit}", "--no-merges", "--format=%x1e%H", "--numstat", anchor],@@ -38,13 +45,14 @@ def baseline_scores().stdoutscores: list[float] = []+ exclude_spec = pathspec.PathSpec.from_lines("gitwildmatch", exclude_patterns)for block in out.split("\x1e"):lines = block.strip().split("\n")if not lines or not lines[0]:continuesha, rows = lines[0].strip(), lines[1:]- # Drop the target itself from its own baseline (short or full sha).- if exclude and (sha.startswith(exclude) or exclude.startswith(sha)):+ # Do not let the target commit rank against itself (short or full ref).+ if excluded_ref and (sha.startswith(excluded_ref) or excluded_ref.startswith(sha)):continuechanges: list[tuple[str, int, int]] = []for row in rows:@@ -54,6 +62,8 @@ def baseline_scores(a_raw, d_raw, path = partsif extensions and not path.endswith(extensions):continue+ if exclude_spec.match_file(path):+ continuea = int(a_raw) if a_raw.isdigit() else 0d = int(d_raw) if d_raw.isdigit() else 0changes.append((path, a, d))diff --git a/packages/core/src/repowise/core/analysis/change_risk/features.py b/packages/core/src/repowise/core/analysis/change_risk/features.pyindex b9cd3b760..cd1ab6689 100644--- a/packages/core/src/repowise/core/analysis/change_risk/features.py+++ b/packages/core/src/repowise/core/analysis/change_risk/features.py@@ -21,6 +21,8 @@ import subprocessfrom collections.abc import Iterablefrom dataclasses import dataclass+import pathspec+from ...ingestion.git_indexer._constants import is_fix_commit@@ -57,12 +59,13 @@ def _git(args: list[str], cwd: str) -> str:def _accumulate_numstat(- numstat: str, extensions: tuple[str, ...]+ numstat: str, extensions: tuple[str, ...], exclude_patterns: tuple[str, ...]) -> tuple[int, int, int, set[str], set[str], list[int]]:la = ld = nf = 0dirs: set[str] = set()subs: set[str] = set()per_file: list[int] = []+ exclude_spec = pathspec.PathSpec.from_lines("gitwildmatch", exclude_patterns)for row in numstat.strip().split("\n"):if not row:continue@@ -72,6 +75,8 @@ def _accumulate_numstat(a_raw, d_raw, path = partsif extensions and not path.endswith(extensions):continue+ if exclude_spec.match_file(path):+ continuea = int(a_raw) if a_raw.isdigit() else 0d = int(d_raw) if d_raw.isdigit() else 0la += a@@ -161,16 +166,18 @@ def extract_commit_features(sha: str,*,extensions: tuple[str, ...] = (),+ exclude_patterns: tuple[str, ...] = (),) -> ChangeFeatures:"""Extract change features for a single commit.*extensions* optionally restricts the counted files to a set of suffixes- (e.g. ``(".py",)``); empty means count every changed file.+ (e.g. ``(".py",)``); *exclude_patterns* uses gitignore syntax to omit+ changed paths. Empty filters count every changed file."""meta = _git(["show", "-s", "--format=%an%x00%s", sha], repo_path).strip("\n")author, _, subject = meta.partition("\x00")numstat = _git(["show", sha, "--numstat", "--format="], repo_path)- la, ld, nf, dirs, subs, per_file = _accumulate_numstat(numstat, extensions)+ la, ld, nf, dirs, subs, per_file = _accumulate_numstat(numstat, extensions, exclude_patterns)parent = _git(["rev-parse", "--verify", "--quiet", f"{sha}^"], repo_path).strip()exp = _author_experience(repo_path, author, parent or sha)return ChangeFeatures(@@ -194,6 +201,7 @@ def extract_range_features(head: str,*,extensions: tuple[str, ...] = (),+ exclude_patterns: tuple[str, ...] = (),) -> ChangeFeatures:"""Extract features for a ``base..head`` range scored as one change.@@ -202,7 +210,7 @@ def extract_range_features(commit count at *base*."""numstat = _git(["diff", "--numstat", f"{base}..{head}"], repo_path)- la, ld, nf, dirs, subs, per_file = _accumulate_numstat(numstat, extensions)+ la, ld, nf, dirs, subs, per_file = _accumulate_numstat(numstat, extensions, exclude_patterns)meta = _git(["show", "-s", "--format=%an%x00%s", head], repo_path).strip("\n")author, _, subject = meta.partition("\x00")# Any fix commit in the range marks the change as a fix (informational).diff --git a/packages/core/src/repowise/core/analysis/change_risk/normalize.py b/packages/core/src/repowise/core/analysis/change_risk/normalize.pyindex 3529d777a..1d53e89eb 100644--- a/packages/core/src/repowise/core/analysis/change_risk/normalize.py+++ b/packages/core/src/repowise/core/analysis/change_risk/normalize.py@@ -23,6 +23,16 @@ from dataclasses import dataclass# top third of its repo's risk distribution is the review-priority tier._HIGH_PCT = 200.0 / 3.0 # ≈ 66.67_MODERATE_PCT = 100.0 / 3.0 # ≈ 33.33+_PRIORITY_CLASSIFICATIONS = {+ "low": "Below typical",+ "moderate": "Typical",+ "high": "Elevated",+}+++def review_priority_classification(priority: str | None) -> str | None:+ """Return the human-facing label for a repo-relative review priority."""+ return _PRIORITY_CLASSIFICATIONS.get(priority) if priority is not None else None@dataclassdiff --git a/packages/core/src/repowise/core/analysis/change_risk/service.py b/packages/core/src/repowise/core/analysis/change_risk/service.pynew file mode 100644index 000000000..48821b6af--- /dev/null+++ b/packages/core/src/repowise/core/analysis/change_risk/service.py@@ -0,0 +1,147 @@+"""Shared live change-risk orchestration for CLI and MCP surfaces."""++from __future__ import annotations++import subprocess+from dataclasses import dataclass, replace+from pathlib import Path++from .baseline import baseline_scores+from .features import ChangeFeatures, extract_commit_features, extract_range_features+from .model import ChangeRisk, score_change+from .normalize import RiskNormalizer, review_priority_classification++_MIN_BASELINE = 8+++@dataclass(frozen=True)+class ChangeRiskResult:+ """A live change score and its optional repository-relative ranking."""++ features: ChangeFeatures+ risk: ChangeRisk+ percentile: float | None+ priority: str | None+ baseline_sample_size: int+ riskignore_excludes: tuple[str, ...]+ request_excludes: tuple[str, ...]+++def riskignore_patterns(repo_path: str) -> tuple[str, ...]:+ """Load non-comment patterns from the repository-root ``.riskignore``."""+ proc = subprocess.run(+ ["git", "-C", repo_path, "rev-parse", "--show-toplevel"],+ capture_output=True,+ text=True,+ encoding="utf-8",+ )+ if proc.returncode != 0:+ return ()+ ignore_file = Path(proc.stdout.strip()) / ".riskignore"+ if not ignore_file.is_file():+ return ()+ return tuple(+ line+ for line in ignore_file.read_text(encoding="utf-8").splitlines()+ if line and not line.startswith("#")+ )+++def normalize_extensions(extensions: tuple[str, ...]) -> tuple[str, ...]:+ """Add a leading dot to requested suffixes, matching the CLI contract."""+ return tuple(ext if ext.startswith(".") else f".{ext}" for ext in extensions)+++def score_live_change(+ repo_path: str,+ revspec: str = "HEAD",+ *,+ extensions: tuple[str, ...] = (),+ exclude_patterns: tuple[str, ...] = (),+ baseline: int = 200,+) -> ChangeRiskResult:+ """Score a commit or ``base..head`` range with optional live filters."""+ if baseline < 0:+ raise ValueError("baseline must be non-negative")++ extensions = normalize_extensions(extensions)+ from_riskignore = riskignore_patterns(repo_path)+ effective_excludes = from_riskignore + exclude_patterns+ if ".." in revspec:+ base, _, head = revspec.partition("..")+ # Strip leading dot(s) so three-dot syntax (main...HEAD) gives a valid anchor ref.+ head = head.lstrip(".") or "HEAD"+ features = extract_range_features(+ repo_path, base, head, extensions=extensions, exclude_patterns=effective_excludes+ )+ anchor, excluded_ref = head, ""+ else:+ features = extract_commit_features(+ repo_path, revspec, extensions=extensions, exclude_patterns=effective_excludes+ )+ anchor, excluded_ref = revspec, features.ref++ risk = score_change(features)+ percentile: float | None = None+ priority: str | None = None+ baseline_sample_size = 0+ if baseline:+ scores = baseline_scores(+ repo_path,+ anchor,+ baseline,+ extensions,+ excluded_ref=excluded_ref,+ exclude_patterns=effective_excludes,+ )+ baseline_sample_size = len(scores)+ if len(scores) >= _MIN_BASELINE:+ normalizer = RiskNormalizer.from_scores(scores)+ rank_score = score_change(replace(features, exp=None)).score+ percentile = normalizer.percentile(rank_score)+ priority = normalizer.priority(rank_score)++ return ChangeRiskResult(+ features=features,+ risk=risk,+ percentile=percentile,+ priority=priority,+ baseline_sample_size=baseline_sample_size,+ riskignore_excludes=from_riskignore,+ request_excludes=exclude_patterns,+ )+++def change_risk_payload(result: ChangeRiskResult) -> dict:+ """Render the machine-readable response shared by the CLI and MCP tool."""+ features, risk = result.features, result.risk+ return {+ "ref": features.ref,+ "score": risk.score,+ "probability": round(risk.probability, 4),+ "level": risk.level,+ "risk_percentile": round(result.percentile, 1) if result.percentile is not None else None,+ "review_priority": result.priority,+ "classification": review_priority_classification(result.priority),+ "baseline_sample_size": result.baseline_sample_size,+ "exclude_patterns": list(result.riskignore_excludes + result.request_excludes),+ "is_fix": features.is_fix,+ "features": {+ "la": features.la,+ "ld": features.ld,+ "nf": features.nf,+ "nd": features.nd,+ "ns": features.ns,+ "entropy": round(features.entropy, 4),+ "exp": features.exp,+ },+ "drivers": [+ {+ "feature": driver.feature,+ "value": driver.value,+ "contribution": round(driver.contribution, 4),+ "label": driver.label,+ }+ for driver in risk.top_drivers+ ],+ }diff --git a/packages/server/src/repowise/server/chat_tools.py b/packages/server/src/repowise/server/chat_tools.pyindex ae8947f1b..8a7b92732 100644--- a/packages/server/src/repowise/server/chat_tools.py+++ b/packages/server/src/repowise/server/chat_tools.py@@ -61,9 +61,17 @@ _TOOL_SCHEMAS: list[dict[str, Any]] = ["items": {"type": "string","enum": [- "docs", "full_doc", "ownership", "last_change",- "decisions", "freshness", "source", "callers",- "callees", "metrics", "community",+ "docs",+ "full_doc",+ "ownership",+ "last_change",+ "decisions",+ "freshness",+ "source",+ "callers",+ "callees",+ "metrics",+ "community",],},"description": "Data blocks to include. Default: docs + freshness.",@@ -91,6 +99,39 @@ _TOOL_SCHEMAS: list[dict[str, Any]] = [},"artifact_type": "risk_report",},+ {+ "name": "get_change_risk",+ "description": "Score the defect risk of a live commit or branch range from diff size, diffusion, and author familiarity. Use for pre-merge ranking; use get_risk for per-file history and blast radius.",+ "parameters": {+ "type": "object",+ "properties": {+ "revspec": {+ "type": "string",+ "description": "Commit or base..head range to score. Defaults to HEAD.",+ "default": "HEAD",+ },+ "repo": {"type": "string", "description": "Repository identifier."},+ "extensions": {+ "type": "array",+ "items": {"type": "string"},+ "description": "File suffixes to count, for example .py or .ts.",+ },+ "exclude_patterns": {+ "type": "array",+ "items": {"type": "string"},+ "description": "Gitignore-style paths to omit from the score and baseline.",+ },+ "baseline": {+ "type": "integer",+ "minimum": 0,+ "default": 200,+ "description": "Recent commits used for percentile ranking; 0 disables it.",+ },+ },+ "required": [],+ },+ "artifact_type": "risk_report",+ },{"name": "get_why","description": "Intent archaeology: understand why code was built a certain way. Path lookup returns origin story (who, when, key commits linked to decisions) and alignment score. Natural language search scores across all decision fields. Use targets to anchor search to specific files.",@@ -184,6 +225,7 @@ _TOOL_SCHEMAS: list[dict[str, Any]] = [def _build_registry() -> dict[str, ToolDef]:"""Build the tool registry by importing MCP tool functions."""from repowise.server.mcp_server import (+ get_change_risk,get_context,get_dead_code,get_overview,@@ -202,6 +244,7 @@ def _build_registry() -> dict[str, ToolDef]:func_map: dict[str, Callable] = {"get_overview": get_overview,"get_context": get_context,+ "get_change_risk": get_change_risk,"get_risk": get_risk,"get_why": get_why,"search_codebase": _search_concept,diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.pyindex 315b224ec..0ea472292 100644--- a/packages/server/src/repowise/server/mcp_server/__init__.py+++ b/packages/server/src/repowise/server/mcp_server/__init__.py@@ -1,8 +1,8 @@"""repowise MCP Server — a curated, configurable tool surface for AI agents.-By default a single-repo server exposes ten tools (get_answer, get_context,-get_symbol, search_codebase, get_overview, get_risk, get_why, get_dead_code,-get_health, list_repos); two more (get_blast_radius, get_architecture) are added+By default a single-repo server exposes eleven tools (get_answer, get_context,+get_symbol, search_codebase, get_overview, get_risk, get_change_risk, get_why,+get_dead_code, get_health, list_repos); two more (get_blast_radius, get_architecture) are addedautomatically in workspace mode. Four further tools (get_dependency_path,get_execution_flows, generate_refactoring_code, get_conformance) are registeredbut off by default and can be opted in via the ``mcp.tools`` config block or the@@ -53,6 +53,7 @@ from repowise.server.mcp_server._tool_selection import (from repowise.server.mcp_server.tool_answer import get_answerfrom repowise.server.mcp_server.tool_architecture import get_architecturefrom repowise.server.mcp_server.tool_blast_radius import get_blast_radius+from repowise.server.mcp_server.tool_change_risk import get_change_riskfrom repowise.server.mcp_server.tool_conformance import get_conformancefrom repowise.server.mcp_server.tool_context import get_contextfrom repowise.server.mcp_server.tool_dead_code import get_dead_code@@ -133,16 +134,17 @@ __all__ = ["_get_repo","_is_path","create_mcp_server",+ "generate_refactoring_code","get_answer","get_architecture","get_blast_radius",+ "get_change_risk","get_conformance","get_context","get_dead_code","get_dependency_path","get_execution_flows","get_health",- "generate_refactoring_code","get_overview","get_risk","get_symbol",diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.pynew file mode 100644index 000000000..e2720fb81--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py@@ -0,0 +1,58 @@+"""MCP tool for live commit and range change-risk scoring."""++from __future__ import annotations++import asyncio+import subprocess++from repowise.core.analysis.change_risk import change_risk_payload, score_live_change+from repowise.core.registry import mcp_tool_registry as mcp+from repowise.server.mcp_server._helpers import _resolve_repo_context+++async def get_change_risk(+ revspec: str = "HEAD",+ repo: str | None = None,+ extensions: list[str] | None = None,+ exclude_patterns: list[str] | None = None,+ baseline: int = 200,+) -> dict:+ """Score a live commit or ``base..head`` range from its diff shape.++ Use this for a pre-merge score of a commit or PR range. It is distinct from+ ``get_risk``, which assesses indexed files and PR blast radius. ``extensions``+ restricts counted suffixes; ``exclude_patterns`` omits gitignore-style paths.+ Both filters also apply to the baseline used for the repository percentile.++ Prefer ``risk_percentile`` as the indicator of change risk: it ranks this+ change against sampled recent commits in the same repository. Summarize it+ with ``review_priority`` and ``classification``. ``score``, ``probability``,+ and ``level`` are secondary corpus-calibrated context; use them as the+ fallback only when ``risk_percentile`` is unavailable.+ ``baseline_sample_size`` is the number of filtered recent commits used to+ calculate ``risk_percentile`` (normally 200); a smaller sample makes the+ percentile less representative of the repository's usual change risk.++ Args:+ revspec: Commit or ``base..head`` range to score. Defaults to ``HEAD``.+ repo: Repository alias in workspace mode; omit for the default repository.+ extensions: File suffixes to count, for example ``[".py", ".ts"]``.+ exclude_patterns: Gitignore-style paths to omit, for example ``["tests/", "*.md"]``.+ baseline: Recent commits to sample for percentile ranking; 0 disables it.+ """+ ctx = await _resolve_repo_context(repo)+ try:+ result = await asyncio.to_thread(+ score_live_change,+ ctx.path,+ revspec,+ extensions=tuple(extensions or ()),+ exclude_patterns=tuple(exclude_patterns or ()),+ baseline=baseline,+ )+ except ValueError as exc:+ return {"error": str(exc)}+ except subprocess.CalledProcessError as exc:+ return {"error": f"Could not read change {revspec!r}: {exc.stderr or exc}"}+ return change_risk_payload(result)diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.pyindex e1c6961af..a98f9fb41 100644--- a/packages/server/src/repowise/server/routers/git.py+++ b/packages/server/src/repowise/server/routers/git.py@@ -66,8 +66,8 @@ router = APIRouter(def _hotspot_from_row(r: GitMetadata) -> HotspotResponse:- # churn_percentile is stored on a 0–1 scale (rank / total) but every UI- # consumer treats it as a percentile rank in 0–100. Normalize here so+ # churn_percentile is stored on a 0-1 scale (rank / total) but every UI+ # consumer treats it as a percentile rank in 0-100. Normalize here so# the API contract is unambiguous and the dashboard ChurnBar / scatter# / hotspots-mini render correctly without per-component hacks.churn_pct = (r.churn_percentile or 0.0) * 100.0@@ -554,7 +554,7 @@ async def get_co_changes()async def get_reviewer_suggestions(repo_id: str,- paths: list[str] = Query(..., description="Repeat ?paths= for each changed file"),+ paths: list[str] = Query(..., description="Repeat ?paths= for each changed file"), # noqa: B008limit: int = Query(10, ge=1, le=50),session: AsyncSession = Depends(get_db_session), # noqa: B008) -> ReviewerSuggestionsResponse:@@ -630,7 +630,7 @@ def get_risk_range(percentile: float | None = Nonepriority: str | None = Noneif baseline:- scores = baseline_scores(local_path, head, baseline, (), "")+ scores = baseline_scores(local_path, head, baseline, (), excluded_ref="")if len(scores) >= _MIN_BASELINE:normalizer = RiskNormalizer.from_scores(scores)# Rank with experience unknown, matching the baseline (diff-shape@@ -687,7 +687,7 @@ async def get_git_summary(hotspot_count = sum(1 for m in all_meta if m.is_hotspot)stable_count = sum(1 for m in all_meta if m.is_stable)- # Normalize to 0–100 to match the rest of the HTTP API contract.+ # Normalize to 0-100 to match the rest of the HTTP API contract.avg_churn = (sum(m.churn_percentile for m in all_meta) / len(all_meta) * 100.0 if all_meta else 0.0)diff --git a/tests/unit/analysis/test_change_risk.py b/tests/unit/analysis/test_change_risk.pyindex f1d1f002e..a941092de 100644--- a/tests/unit/analysis/test_change_risk.py+++ b/tests/unit/analysis/test_change_risk.py@@ -10,6 +10,8 @@ import pytestfrom repowise.core.analysis.change_risk import (ChangeFeatures,+ ChangeRiskResult,+ change_risk_payload,extract_commit_features,extract_range_features,features_from_file_changes,@@ -84,6 +86,26 @@ def test_top_drivers_sorted_by_magnitude() -> None:assert contribs == sorted(contribs, reverse=True)+def test_payload_includes_friendly_repo_relative_classification() -> None:+ features = _feat(la=50, ld=10, nf=5, nd=3, ns=2, entropy=2.0, exp=8)+ payload = change_risk_payload(+ ChangeRiskResult(+ features=features,+ risk=score_change(features),+ percentile=66.6,+ priority="moderate",+ baseline_sample_size=200,+ riskignore_excludes=(),+ request_excludes=(),+ )+ )++ assert payload["risk_percentile"] == 66.6+ assert payload["review_priority"] == "moderate"+ assert payload["classification"] == "Typical"+ assert payload["baseline_sample_size"] == 200++# ---------------------------------------------------------------------------# Diff-only feature builder (no git repo — the bot's PR-API path).# ---------------------------------------------------------------------------@@ -110,9 +132,12 @@ def test_features_from_file_changes_aggregates_diffusion() -> None:assert f.entropy > 0.0# The diff-only builder must score identically to the git path for the# same underlying counts.- assert score_change(f).score == score_change(- ChangeFeatures(la=15, ld=3, nf=3, nd=3, ns=2, entropy=f.entropy, exp=42)- ).score+ assert (+ score_change(f).score+ == score_change(+ ChangeFeatures(la=15, ld=3, nf=3, nd=3, ns=2, entropy=f.entropy, exp=42)+ ).score+ )# ---------------------------------------------------------------------------@@ -181,6 +206,44 @@ def test_extract_filters_by_extension(git_repo: Path) -> None:assert f.is_fix is False+def test_extract_filters_by_gitignore_exclude_pattern(git_repo: Path) -> None:+ _commit(+ git_repo,+ {+ "src/app.py": "value = 1\n",+ "tests/test_app.py": "def test_value():\n assert True\n",+ "web/app.spec.ts": "it('works', () => {})\n",+ },+ "feat: add application",+ author="Dev",+ )++ f = extract_commit_features(str(git_repo), "HEAD", exclude_patterns=("tests/", "*.spec.ts"))++ assert f.nf == 1+ assert f.la == 1+ assert f.nd == 1+ assert f.ns == 1+++def test_extract_range_filters_by_gitignore_exclude_pattern(git_repo: Path) -> None:+ base = subprocess.run(+ ["git", "rev-parse", "HEAD"], cwd=git_repo, check=True, capture_output=True, text=True+ ).stdout.strip()+ _commit(git_repo, {"src/app.py": "value = 1\n"}, "feat: app", author="Dev")+ _commit(+ git_repo,+ {"tests/test_app.py": "def test_value():\n assert True\n"},+ "test: app",+ author="Dev",+ )++ f = extract_range_features(str(git_repo), base, "HEAD", exclude_patterns=("tests/",))++ assert f.nf == 1+ assert f.la == 1++def test_author_experience_accrues(git_repo: Path) -> None:_commit(git_repo, {"f1.py": "a=1\n"}, "feat: one", author="Repeat")_commit(git_repo, {"f2.py": "b=2\n"}, "feat: two", author="Repeat")@@ -204,8 +267,12 @@ def test_extract_range_features_aggregates(git_repo: Path) -> None:def test_score_change_on_real_commit(git_repo: Path) -> None:- _commit(git_repo, {"big.py": "\n".join(f"line{i} = {i}" for i in range(120)) + "\n"},- "feat: big drop", author="New")+ _commit(+ git_repo,+ {"big.py": "\n".join(f"line{i} = {i}" for i in range(120)) + "\n"},+ "feat: big drop",+ author="New",+ )f = extract_commit_features(str(git_repo), "HEAD", extensions=(".py",))risk = score_change(f)assert 0.0 <= risk.score <= 10.0diff --git a/tests/unit/analysis/test_change_risk_normalize.py b/tests/unit/analysis/test_change_risk_normalize.pyindex 6c4d15693..f0961d7b5 100644--- a/tests/unit/analysis/test_change_risk_normalize.py+++ b/tests/unit/analysis/test_change_risk_normalize.py@@ -2,7 +2,7 @@from __future__ import annotations-from repowise.core.analysis.change_risk import RiskNormalizer+from repowise.core.analysis.change_risk import RiskNormalizer, review_priority_classificationdef test_empty_distribution_is_low_zero() -> None:@@ -53,3 +53,10 @@ def test_priority_is_repo_relative_not_absolute() -> None:n = RiskNormalizer.from_scores([8.0, 8.2, 8.4, 8.6, 8.8, 9.0])assert n.priority(8.0) == "low"assert n.priority(9.0) == "high"+++def test_review_priority_classification() -> None:+ assert review_priority_classification("low") == "Below typical"+ assert review_priority_classification("moderate") == "Typical"+ assert review_priority_classification("high") == "Elevated"+ assert review_priority_classification(None) is Nonediff --git a/tests/unit/cli/test_risk_cmd.py b/tests/unit/cli/test_risk_cmd.pynew file mode 100644index 000000000..7c7e9d7e4--- /dev/null+++ b/tests/unit/cli/test_risk_cmd.py@@ -0,0 +1,70 @@+"""CLI coverage for change-risk exclusion rules."""++from __future__ import annotations++import json+import subprocess+from pathlib import Path++from click.testing import CliRunner++from repowise.cli.commands.risk_cmd import risk_command+++def _git(args: list[str], cwd: Path) -> None:+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True)+++def _commit(repo: Path, files: dict[str, str], message: str) -> None:+ for relative_path, content in files.items():+ path = repo / relative_path+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(content, encoding="utf-8")+ _git(["add", relative_path], repo)+ _git(["-c", "user.name=Dev", "-c", "[email protected]", "commit", "-m", message], repo)+++def test_risk_uses_root_riskignore_and_repeatable_excludes(tmp_path: Path) -> None:+ repo = tmp_path / "repo"+ repo.mkdir()+ _git(["init", "-q"], repo)+ _commit(repo, {"README.md": "# seed\n"}, "chore: seed")+ _commit(+ repo,+ {+ "src/app.py": "value = 1\n",+ "tests/test_app.py": "def test_value():\n assert True\n",+ "web/app.spec.ts": "it('works', () => {})\n",+ },+ "feat: app",+ )+ (repo / ".riskignore").write_text("tests/\n", encoding="utf-8")++ result = CliRunner().invoke(+ risk_command,+ [+ "HEAD",+ "--path",+ str(repo),+ "--baseline",+ "0",+ "-x",+ "*.spec.ts",+ "--format",+ "json",+ ],+ )++ assert result.exit_code == 0, result.output+ payload = json.loads(result.output)+ assert payload["features"]["nf"] == 1+ assert payload["features"]["la"] == 1+ assert payload["exclude_patterns"] == ["tests/", "*.spec.ts"]+++def test_risk_help_describes_repeatable_exclude() -> None:+ result = CliRunner().invoke(risk_command, ["--help"])++ assert result.exit_code == 0+ assert "-x, --exclude PATTERN" in result.output+ assert "Repeatable" in result.outputdiff --git a/tests/unit/server/mcp/test_change_risk.py b/tests/unit/server/mcp/test_change_risk.pynew file mode 100644index 000000000..77d8b02bf--- /dev/null+++ b/tests/unit/server/mcp/test_change_risk.py@@ -0,0 +1,66 @@+"""MCP coverage for live commit/range change-risk scoring."""++from __future__ import annotations++import importlib+import subprocess+from pathlib import Path+from types import SimpleNamespace++import pytest+++def _git(args: list[str], cwd: Path) -> None:+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True)+++def _commit(repo: Path, files: dict[str, str], message: str) -> None:+ for relative_path, content in files.items():+ path = repo / relative_path+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(content, encoding="utf-8")+ _git(["add", relative_path], repo)+ _git(["-c", "user.name=Dev", "-c", "[email protected]", "commit", "-m", message], repo)+++async def test_get_change_risk_honors_riskignore_and_request_filters(tmp_path, monkeypatch) -> None:+ repo = tmp_path / "repo"+ repo.mkdir()+ _git(["init", "-q"], repo)+ _commit(repo, {"README.md": "# seed\n"}, "chore: seed")+ _commit(+ repo,+ {+ "src/app.py": "value = 1\n",+ "tests/test_app.py": "def test_value():\n assert True\n",+ "docs/notes.md": "notes\n",+ },+ "feat: app",+ )+ (repo / ".riskignore").write_text("tests/\n", encoding="utf-8")++ module = importlib.import_module("repowise.server.mcp_server.tool_change_risk")++ async def _context(_: str | None) -> SimpleNamespace:+ return SimpleNamespace(path=str(repo))++ monkeypatch.setattr(module, "_resolve_repo_context", _context)+ result = await module.get_change_risk(+ extensions=["py", "md"], exclude_patterns=["docs/"], baseline=0+ )++ assert result["features"] == {+ "la": 1,+ "ld": 0,+ "nf": 1,+ "nd": 1,+ "ns": 1,+ "entropy": 0.0,+ "exp": 1,+ }+ assert result["exclude_patterns"] == ["tests/", "docs/"]+ assert result["risk_percentile"] is None+ assert result["review_priority"] is None+ assert result["classification"] is None+ assert result["baseline_sample_size"] == 0diff --git a/tests/unit/server/mcp/test_tool_selection.py b/tests/unit/server/mcp/test_tool_selection.pyindex ee2f23b24..df887ea09 100644--- a/tests/unit/server/mcp/test_tool_selection.py+++ b/tests/unit/server/mcp/test_tool_selection.py@@ -85,7 +85,7 @@ def test_lean_profile_workspace_adds_list_repos():def test_lean_profile_full_registry():- """Against the real registry, lean is exactly the five agent-lean tools."""+ """Against the real registry, lean is exactly the agent-lean tools."""import repowise.server.mcp_server # noqa: F401 (registers the tools)from repowise.core.registry import mcp_tool_registryfrom repowise.server.mcp_server._tool_selection import LEAN_TOOLS@@ -94,6 +94,7 @@ def test_lean_profile_full_registry():mcp_tool_registry.entries(), is_workspace=False, override="lean")assert enabled == LEAN_TOOLS+ assert "get_change_risk" not in enabledworkspace = resolve_enabled_tools(mcp_tool_registry.entries(), is_workspace=True, override="lean"diff --git a/tests/unit/server/test_risk_range.py b/tests/unit/server/test_risk_range.pyindex a08528a98..970de373b 100644--- a/tests/unit/server/test_risk_range.py+++ b/tests/unit/server/test_risk_range.py@@ -119,6 +119,30 @@ def test_baseline_scores_returns_floats(git_repo: Path) -> None:_commit(git_repo, {"src/d.py": "a = 1\nb = 2\n"}, "feat: add d")_commit(git_repo, {"src/e.py": "c = 3\n"}, "fix: crash on null")- scores = baseline_scores(str(git_repo), "HEAD", 200, (), "")+ scores = baseline_scores(str(git_repo), "HEAD", 200, (), excluded_ref="")assert len(scores) >= 1assert all(isinstance(s, float) for s in scores)+++def test_baseline_scores_filters_excluded_paths(git_repo: Path) -> None:+ _commit(git_repo, {"src/app.py": "a = 1\n"}, "feat: app")+ _commit(+ git_repo,+ {"tests/test_app.py": "\n".join(f"assert {i}" for i in range(30)) + "\n"},+ "test: app",+ )++ scores = baseline_scores(+ str(git_repo), "HEAD", 2, (), excluded_ref="", exclude_patterns=("tests/",)+ )++ assert len(scores) == 1+++def test_baseline_scores_omits_target_ref(git_repo: Path) -> None:+ _commit(git_repo, {"src/app.py": "a = 1\n"}, "feat: app")+ head = _commit(git_repo, {"src/next.py": "b = 2\n"}, "feat: next")++ scores = baseline_scores(str(git_repo), "HEAD", 2, (), excluded_ref=head)++ assert len(scores) == 1diff --git a/website/concepts.md b/website/concepts.mdindex 4868b5866..4db8bb42e 100644--- a/website/concepts.md+++ b/website/concepts.md@@ -161,7 +161,7 @@ The dependency graph is loaded into memory at server startup for fast traversal.## The MCP server-The MCP server sits on top of the persistence layer and exposes everything to AI coding assistants via 13 tools (10 single-repo + 3 workspace-only). It's the primary interface between repowise and Claude Code, Codex, Cursor, Cline, or any other MCP-compatible editor.+The MCP server sits on top of the persistence layer and exposes everything to AI coding assistants through 17 registered tools: 11 by default in a single repository, 13 by default in workspace mode, and four opt-in tools. It's the primary interface between repowise and Claude Code, Codex, Cursor, Cline, or any other MCP-compatible editor.When you run `repowise mcp`, the server starts in stdio mode and your editor can begin calling tools. The tools are designed to answer the questions an AI needs to make good decisions about your code — not just "what is this file" but "should I edit it", "why is it structured this way", and "what will break if I change it".diff --git a/website/mcp-server.md b/website/mcp-server.mdindex 0666efc05..e74be510f 100644--- a/website/mcp-server.md+++ b/website/mcp-server.md@@ -22,7 +22,7 @@ Connect repowise to Claude Code, Codex, Cursor, Cline, or any MCP-compatible edi## Overview-The MCP (Model Context Protocol) server is how repowise talks to AI coding assistants. Once connected, your editor's AI can call 13 tools (10 single-repo + 3 workspace-only) to query your codebase wiki — synthesizing answers, looking up symbols, fetching docs, ownership, risk signals, dependency paths, and architectural decisions.+The MCP (Model Context Protocol) server is how repowise talks to AI coding assistants. It registers 17 tools: a curated 11-tool default surface in a single repository, two additional default tools in workspace mode, and four opt-in tools. Once connected, your editor's AI can query your codebase wiki for synthesized answers, symbols, docs, ownership, risk signals, dependency paths, and architectural decisions.Start the server with: