Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
refactor(cli): split risk_cmd into a package and stage the risk card renderer (#4040)
Raghav Chamadiya6b6aedb9bf77
diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd.py b/packages/cli/src/repowise/cli/commands/risk_cmd.pydeleted file mode 100644index fa7e3ad24..000000000--- a/packages/cli/src/repowise/cli/commands/risk_cmd.py+++ /dev/null@@ -1,831 +0,0 @@-"""``repowise risk`` — just-in-time change risk, for a change or for paths.--Two questions, one command, because they are the same question asked of-different subjects.--A REVSPEC scores a *change* from its diff shape (size, diffusion, author-familiarity) and leads with its percentile of recent commits by size and-spread, then the bug-fix record of the files it touches, then a supporting 0-10-diff-shape score with an attributable breakdown. Runs-in-process: pure git + learned constants, no LLM, no network. A natural-pre-merge / PR gate, complementary to ``repowise health`` (which scores files).--``--target <path>`` instead asks what history says about touching those files:-bug-fix pressure, churn trend, dependents, co-change partners, ownership. That-is the ``get_risk`` MCP tool, and this command is a thin adapter over it — the-same seam ``ask`` / ``context`` / ``symbol`` / ``why`` use. It reads the index-rather than git, so the repo must be indexed.--``--fail-above-percentile P`` makes the REVSPEC path a CI size gate on the-repo-relative percentile (never the 0-10 score), with the shared CI exit codes-(:mod:`repowise.cli.ci`): 1 above the gate, 2 when the change cannot be read-or ranked.--Examples:- repowise risk # score uncommitted work, else HEAD- repowise risk HEAD # score the last commit- repowise risk abc123 # score a single commit- repowise risk main..HEAD # score a branch / PR range as one change- repowise risk --fail-above-percentile 95 --format github # gate the CI change- repowise risk --target a.py -t b.py # what history says about those files-"""--from __future__ import annotations--import json-import subprocess-from dataclasses import dataclass-from pathlib import Path--import click-from rich.markup import escape-from rich.table import Table--from repowise.cli.ci import (- CI_FORMATS,- EXIT_GATE_FAILED,- CannotEvaluateError,- append_step_summary,- cannot_evaluate,- ci_notices,- ci_revspec,- repo_root,-)-from repowise.cli.commands import _tool_adapters as _ta-from repowise.cli.helpers import console, repo_index_session, run_async-from repowise.cli.output import emit_json, format_option, full_option-from repowise.core.analysis.change_risk import (- ChangeRiskResult,- change_risk_payload,- score_live_change,-)-from repowise.core.analysis.change_risk.render import LIMITS, fix_history_text, size_text--#: Per-target keys the trim drops, and nothing else.-#:-#: A denylist, not an allowlist, and deliberately so: the failure mode of a-#: denylist is a payload slightly larger than intended, while the failure mode-#: of an allowlist is a silently discarded answer — which is the mistake the-#: adapter commands' first projections made eight times over. ``get_risk``'s-#: card is a page of small scalars rather than a block of source, so there is-#: little to win by trimming harder and a lot to lose.-#:-#: ``_base_dep_count`` is bookkeeping the tool uses to rebuild ``risk_summary``-#: after enrichment. ``impact_surface`` is the transitive dependent set, the one-#: genuinely unbounded block, and its own summary counts survive in-#: ``risk_summary`` and ``dependents_count``. It is opt-in on the tool now and-#: this command does not ask for it; the entry stays so that a caller passing a-#: hand-built payload gets the same projection.-_DROPPED_TARGET_KEYS = ("_base_dep_count", "impact_surface")---def _project_target(card: dict) -> dict:- """One ``get_risk`` target card, minus the blocks in ``_DROPPED_TARGET_KEYS``."""- return {k: v for k, v in card.items() if k not in _DROPPED_TARGET_KEYS}---def project_risk(payload: dict) -> dict:- """``get_risk``'s dict, trimmed to what a CLI caller reads.-- Kept whole: ``directive`` (in PR mode this *is* the answer, and the tool's- own docstring tells a reader to lead with it), ``pr_blast_radius``,- ``global_hotspots``, and the freshness half of ``_meta``. Dropped: the- timing half of ``_meta``, and the per-target keys named above.-- ``pr_blast_radius`` survives although ``directive`` summarises much of it,- because the tool has *already* capped its four noisy lists (15/10/10/5)- before it gets here, so keeping it costs almost nothing.- """- out: dict = {}- if payload.get("directive"):- out["directive"] = payload["directive"]- out["targets"] = {- name: _project_target(card) for name, card in (payload.get("targets") or {}).items()- }- for key in ("risk_scales", "pr_blast_radius", "global_hotspots", "omission_marker"):- if payload.get(key):- out[key] = payload[key]- note = _ta.index_note(payload)- if note:- out["index"] = note- return out---def _target_risk(- repo_path: str,- targets: tuple[str, ...],- changed_files: tuple[str, ...],- fmt: str,- full: bool,-) -> None:- """``--target``: what history says about touching these files."""- fmt = _ta.resolve_format_for(fmt, full)- repo = _ta.resolve_indexed_repo(- path=repo_path,- repo_alias=None,- no_workspace=False,- fmt=fmt,- command="risk",- )-- def _factory():- from repowise.server.mcp_server.tool_risk.get_risk import get_risk-- return get_risk(- targets=list(targets),- changed_files=list(changed_files) or None,- # _render_target_risk prints risk_type, change_magnitude, owner share,- # bus factor, contributor count, and recent owner; --format json keeps- # the PR blast radius the tool serves only on request.- include=["churn", "owners", "blast"],- )-- payload = _ta.run(repo, _factory, "get_risk")-- if full:- _ta.emit_full(payload)- return- _ta.emit_error(payload, fmt, extra={"targets": list(targets)})- projected = project_risk(payload)- if fmt == "json":- emit_json(projected)- return- _render_target_risk(projected, targets)- _ta.print_index_note(payload, fmt)---def _render_target_risk(projected: dict, requested: tuple[str, ...]) -> None:- """The human path for ``--target``: the directive first, then a card each."""- from rich.markup import escape-- directive = projected.get("directive")- if directive:- # PR mode leads with the directive because that is the tool's contract:- # what may break, what is missing, what to run.- console.print(f"\n[bold]Directive[/bold] {escape(str(directive.get('summary', '')))}")- for label, key in (- ("May break", "may_break"),- ("Missing co-changes", "missing_cochanges"),- ("Files without tests", "missing_tests"),- ("Tests to run", "tests_to_run"),- ):- _print_list(label, directive.get(key) or [])- for label, key in _DIRECTIVE_RECORD_BLOCKS:- _print_records(- label,- directive.get(key) or [],- key,- truncated=directive.get(f"{key}_truncated") or 0,- )- calls = directive.get("next_calls") or []- _print_list("Then run", [c["cli"] for c in calls if c.get("cli")])-- targets = projected.get("targets") or {}- for name in requested:- card = targets.get(name)- if card is None:- # An excluded path is filtered out of the request before the tool- # sees it, so a requested target with no card is an answer ("this- # is not indexed here"), not a gap to render as an empty section.- console.print(f"\n[yellow]{escape(name)} — not indexed (or excluded).[/yellow]")- continue- _render_card(name, card)- # Anything the tool returned that was not asked for by name (it normalises- # paths), so a caller never loses a card to a spelling difference.- for name, card in targets.items():- if name not in requested:- _render_card(name, card)-- hotspots = projected.get("global_hotspots") or []- if hotspots:- table = Table(title="Elsewhere in this repo")- table.add_column("File", style="cyan")- table.add_column("Hotspot", justify="right")- table.add_column("Owner")- table.add_column("Fixes", justify="right")- for h in hotspots:- score = h.get("hotspot_score")- fixes = h.get("fix_count")- table.add_row(- escape(str(h.get("file_path", ""))),- "?" if score is None else f"{float(score):.0%}",- escape(str(h.get("primary_owner") or "unknown")),- "" if fixes is None else str(fixes),- )- console.print(table)-- if projected.get("omission_marker"):- # Printed escaped: it opens with a bracket, which rich would parse as a- # style tag and delete outright, taking the expand handle with it.- console.print(escape(str(projected["omission_marker"])), style="cyan")---def _render_card(name: str, card: dict) -> None:- """One target's risk card."""- from rich.markup import escape-- console.print(f"\n[bold cyan]{escape(name)}[/bold cyan]")- summary = card.get("risk_summary")- if summary:- console.print(f" {escape(str(summary))}")- if card.get("resolved") is False:- # The line below defaults its missing fields to numbers rather than- # gating on them, so stop here rather than print "0 direct dependents".- reason = escape(str(card.get("unresolved_reason") or "unknown"))- console.print(f" [dim]unresolved: {reason}[/dim]")- return- trend = card.get("trend") or "unknown"- if card.get("signal_tier") == "history":- # Nothing measured a hotspot, dependents or classification for this file.- last = str(card.get("last_commit_at") or "unknown")[:10]- console.print(- f" [dim]history only · {card.get('commit_count_total', 0)} commits ({trend}) · "- f"last {escape(last)} · owned {_ta.owner_share(card.get('owner_pct'))} by "- f"{escape(str(card.get('primary_owner') or 'unknown'))}[/dim]"- )- else:- console.print(- f" [dim]hotspot {float(card.get('hotspot_score') or 0.0):.0%} ({trend}) · "- f"{card.get('dependents_count', 0)} direct dependents · "- f"{card.get('risk_type', 'unknown')} · owned "- f"{_ta.owner_share(card.get('owner_pct'))} by "- f"{escape(str(card.get('primary_owner') or 'unknown'))}[/dim]"- )- # Kept in the projection, so each owes a line here: a key kept in the- # payload that no renderer prints is the second silent failure mode of a- # trim, and the one a projection test cannot see.- health = card.get("health_score")- coverage = card.get("line_coverage_pct")- if health is not None or coverage is not None:- parts = []- if health is not None:- parts.append(f"health {float(health):.1f}/10")- if coverage is not None:- parts.append(f"coverage {float(coverage):.0f}%")- console.print(f" [dim]{escape(' · '.join(parts))}[/dim]")- # Keyed ``biomarker_type``, not ``name`` — a generic key guess prints the- # whole dict repr, which is how the directive blocks went wrong too.- biomarkers = card.get("top_biomarkers") or []- if biomarkers:- shown = []- for b in biomarkers[:3]:- if not isinstance(b, dict):- shown.append(str(b))- continue- where = f" in {b['function_name']}" if b.get("function_name") else ""- shown.append(f"{b.get('biomarker_type', '?')} ({b.get('severity', '?')}){where}")- console.print(f" [dim]{escape(', '.join(shown))}[/dim]")- magnitude = card.get("change_magnitude") or {}- if magnitude:- console.print(- f" [dim]+{magnitude.get('lines_added_90d', 0)} / "- f"-{magnitude.get('lines_deleted_90d', 0)} lines in 90d · "- f"avg commit {magnitude.get('avg_commit_size', 0)} lines · "- f"{card.get('contributor_count', 0)} contributor(s), "- f"bus factor {card.get('bus_factor', '?')}[/dim]"- )- if card.get("original_path"):- console.print(f" [dim]Renamed from {escape(str(card['original_path']))}.[/dim]")- if card.get("recent_owner") and card["recent_owner"] != card.get("primary_owner"):- # Ownership has moved: the historical owner is not who to ask now.- console.print(- f" [dim]Recently owned {_ta.owner_share(card.get('recent_owner_pct'))} by "- f"{escape(str(card['recent_owner']))}.[/dim]"- )- cross = card.get("cross_repo_impact") or {}- if cross:- repos = cross.get("affected_repos") or []- historical = cross.get("cross_repo_consumers") or []- contracts = cross.get("contract_consumers") or []- console.print(- " [bold]Crosses repo boundaries[/bold] [dim]"- f"{cross.get('cross_repo_consumers_total', len(historical))} historical co-change(s)"- + (- f", {cross.get('contract_consumers_total', len(contracts))} "- "typed contract consumer(s)"- if contracts- else ""- )- + (f" in {', '.join(str(r) for r in repos)}" if repos else "")- + "[/dim]"- )- defect = card.get("defect_profile")- if defect:- magnet = " [magenta](bug magnet)[/magenta]" if defect.get("bug_magnet") else ""- console.print(- f" [yellow]{defect.get('fix_count', 0)} bug fix(es)[/yellow], last "- f"{defect.get('last_fix_days_ago', '?')} day(s) ago{magnet}"- )- # ``top_symbols`` is a ``{name: fix_count}`` dict, not a list; iterating- # it bare prints the names and throws the counts away.- top = defect.get("top_symbols") or {}- pairs = top.items() if isinstance(top, dict) else [(s, None) for s in top]- _print_list(- "Mostly in",- [f"{name}" + (f" (x{count})" if count is not None else "") for name, count in pairs],- indent=" ",- )- if card.get("test_gap"):- console.print(" [yellow]No test file matches this file's name.[/yellow]")- for signal in card.get("security_signals") or []:- console.print(- f" [red]{escape(str(signal.get('severity', '')))}[/red] "- f"{escape(str(signal.get('kind', '')))}: {escape(str(signal.get('snippet', '')))}"- )- partners = card.get("co_change_partners") or []- if partners:- console.print(" [bold]Co-changes with[/bold]")- for p in partners[:8]:- link = " [dim](also imports)[/dim]" if p.get("has_import_link") else ""- support = p.get("support")- support_text = f" [dim]x{support}[/dim]" if support is not None else ""- console.print(- f" {escape(str(p.get('file_path', '')))}{support_text}{link}"- )- if len(partners) > 8:- console.print(f" [dim]… and {len(partners) - 8} more (--format json).[/dim]")- episodes = card.get("episodes")- if episodes:- console.print(f" [dim]{episodes} recorded episode(s) — see 'repowise why'.[/dim]")---def _print_list(label: str, values: list[str], *, indent: str = " ") -> None:- from rich.markup import escape-- if not values:- return- console.print(f"{indent}[bold]{label}[/bold] " + ", ".join(escape(str(v)) for v in values))---#: The directive blocks whose entries are dicts, with a formatter each.-#:-#: One shared "try these keys in order" chain does not work here: the six-#: blocks are built in ``tool_risk/directives.py`` with six different key sets-#: and only two of them carry any key a generic chain would guess, so the other-#: four printed as raw Python dict reprs. Each formatter is written against-#: that module's construction site.-_DIRECTIVE_RECORD_BLOCKS = (- ("Consumer structural reach", "will_break_consumers"),- ("Missing cross-repo co-changes", "missing_cross_repo_cochanges"),- ("Breaking contract changes", "breaking_changes"),- ("Conformance violations", "conformance_violations"),- ("Dependency cycles", "dependency_cycles"),- ("Governance risk", "governance_risk"),-)---def _record_text(key: str, entry: dict) -> str:- """One directive entry as a line, per the shape its block is built with."""- if key in ("will_break_consumers", "missing_cross_repo_cochanges"):- where = f" [{entry.get('repo')}]" if entry.get("repo") else ""- return f"{entry.get('service') or entry.get('repo') or '?'}{where}"- if key == "breaking_changes":- consumers = entry.get("impacted_consumers") or []- who = f" — endangers {len(consumers)} consumer(s)" if consumers else ""- return (- f"{entry.get('contract_id') or '?'}: {entry.get('kind') or '?'}"- f" ({entry.get('severity') or '?'}) {entry.get('detail') or ''}{who}".rstrip()- )- if key == "conformance_violations":- rule = entry.get("rule") or f"{entry.get('source')} -> {entry.get('target')}"- return f"{rule}{': ' + entry['description'] if entry.get('description') else ''}"- if key == "dependency_cycles":- nodes = entry.get("nodes") or []- return " -> ".join(str(n) for n in nodes) or f"cycle of {entry.get('length', '?')}"- if key == "governance_risk":- # ``reason`` alone is a bare enum-ish token; the title is what names- # the decision the change runs into.- return f"{entry.get('title') or entry.get('decision_id') or '?'} ({entry.get('reason')})"- return str(entry)---def _print_records(label: str, values: list, key: str, truncated: int = 0) -> None:- """A directive block whose entries are dicts, one line each."""- from rich.markup import escape-- if not values:- return- console.print(f" [bold]{label}[/bold]")- for entry in values:- text = _record_text(key, entry) if isinstance(entry, dict) else str(entry)- console.print(f" {escape(str(text))}")- if truncated:- console.print(f" [dim]... and {truncated} more[/dim]")---def _independent_changes_for(repo_path: str, result, revspec: str | None) -> dict | None:- """How this diff splits, per the index, or ``None`` when it cannot be read."""- from sqlalchemy.exc import SQLAlchemyError-- from repowise.core import git_refs- from repowise.core.analysis.independent_changes import independent_changes-- paths = [path for path, _ in result.features.file_churn]- if len(paths) < 2:- return None- # A diff names paths from the repository root, so a command run in a- # subdirectory has to score against that root, not against the given path.- root = Path(git_refs.toplevel(repo_path) or repo_path).resolve()- # One commit touching two files links them harder than any edge does. Read- # git before the store opens: no subprocess while a connection is held.- sets = git_refs.commit_file_sets(str(root), revspec)-- async def read() -> dict | None:- found = None- async with repo_index_session(root) as opened:- if opened is not None:- session, repo_id = opened- try:- found = await independent_changes(session, repo_id, paths, commit_sets=sets)- except (SQLAlchemyError, OSError, LookupError):- # An index written by an older version can fail the query itself.- return None- return found.to_dict() if found else None-- return run_async(read())---#: How many ungrouped names the table prints. The summary already states the-#: count, so a docs-heavy diff need not spell out hundreds of paths.-_UNGROUPED_SHOWN = 10---def _print_independent_changes(block: dict) -> None:- """The groups, plainly: no score, no percentage, no adjective."""- from rich.markup import escape-- console.print(f"\n[bold]{escape(str(block.get('summary') or ''))}[/bold]")- for number, group in enumerate(block.get("groups") or [], start=1):- files = [str(f) for f in group.get("files") or []]- plural = "" if len(files) == 1 else "s"- console.print(f" {number}. {len(files)} file{plural}: {escape(', '.join(files))}")- bridging = [str(f) for f in group.get("bridging_files") or []]- if bridging:- # Naming these files says where the group would split if one moved out.- console.print(f" [dim]held together by: {escape(', '.join(bridging))}[/dim]")- ungrouped = [str(f) for f in block.get("ungrouped_files") or []]- if ungrouped:- shown = escape(", ".join(ungrouped[:_UNGROUPED_SHOWN]))- cut = len(ungrouped) - _UNGROUPED_SHOWN- more = f" and {cut} more" if cut > 0 else ""- console.print(f" Left out of the grouping: {shown}{more}")- console.print(f" [dim]Basis: {escape(str(block.get('basis') or ''))}.[/dim]")--[email protected]("risk")[email protected]("revspec", required=False, default=None)- "--path",- "repo_path",- default=".",- type=click.Path(exists=True, file_okay=False),- help="Path to the git repository (default: current directory).",-)- "--ext",- "ext",- default=None,- help="Comma-separated file suffixes to count (e.g. '.py' or '.ts,.tsx'). "- "Default: count every changed file.",-)- "--baseline",- "baseline",- default=200,- type=click.IntRange(min=0),- help="Sample this many recent commits to rank the change within the repo "- "(0 disables; shows only the absolute per-commit model-score band).",-)- "--exclude",- "-x",- "exclude",- multiple=True,- metavar="PATTERN",- help="Gitignore-style pattern to exclude. Repeatable; also applies to the baseline.",-)- "--target",- "-t",- "targets",- multiple=True,- metavar="PATH",- help="Score what history says about these FILES instead of a change. "- "Repeatable. Reads the index, so the repo must be indexed.",-)- "--changed-file",- "changed_files",- multiple=True,- metavar="PATH",- help="With --target: PR mode. The response leads with a directive naming "- "structural review candidates, missing co-changes/tests, and what to run.",-)- "--fail-above-percentile",- "fail_above",- type=click.FloatRange(0, 100),- default=None,- help="CI gate: exit 1 when the change ranks above this percentile of recent "- "commits (risk_percentile, never the 0-10 score); exit 2 when it cannot be "- "ranked. Without REVSPEC it scores the CI change against its target branch.",-)-@format_option(- choices=CI_FORMATS,- help="Output format. ``markdown`` and ``github`` are not for --target, and "- "without REVSPEC they score the CI change against its target branch; "- "``github`` writes annotations to stdout and the markdown summary to "- "$GITHUB_STEP_SUMMARY when set.",-)-@full_option()-def risk_command(- revspec: str | None,- repo_path: str,- ext: str | None,- baseline: int,- exclude: tuple[str, ...],- targets: tuple[str, ...],- changed_files: tuple[str, ...],- fail_above: float | None,- fmt: str,- full: bool,-) -> None:- """Rank a change by size and spread, or report the history of named files.-- With no --target this scores REVSPEC (a commit, or a ``base..head``- range) from its diff. Omit REVSPEC to score your uncommitted work, or- HEAD when the tree is clean; with --fail-above-percentile, or a- markdown or github format, it scores the CI change instead (the pull- request's target branch...HEAD). With- --target it reports what the repo's history says about the named files,- the same as the get_risk MCP tool.- """- if targets:- if fmt not in ("table", "json"):- raise click.UsageError("--target supports --format table or json.")- if fail_above is not None:- raise click.UsageError("--fail-above-percentile gates a change, not --target files.")- _target_risk(repo_path, targets, changed_files, fmt, full)- return- if changed_files:- raise click.UsageError("--changed-file needs at least one --target.")- # ``--full`` means "the complete payload, as JSON" on every command that has- # it. The REVSPEC path has no tool to be raw about, but it does have a full- # payload, and silently ignoring the flag would hand a script that asked for- # JSON a rich table and exit 0.- fmt = _ta.resolve_format_for(fmt, full)- subject = _resolve_subject(repo_path, revspec, fmt, fail_above)- extensions = tuple(e.strip() for e in ext.split(",")) if ext else ()- result = _score(subject, extensions, exclude, baseline)- failed = fail_above is not None and result.percentile > fail_above- if fmt == "table":- _print_change(subject, result, failed)- else:- _emit_machine(subject, result)- if failed:- raise click.exceptions.Exit(EXIT_GATE_FAILED)---@dataclass(frozen=True)-class _Subject:- """The change a REVSPEC run scores, and how it reports it."""-- repo_path: str- revspec: str | None- fmt: str- fail_above: float | None---def _resolve_subject(- repo_path: str, revspec: str | None, fmt: str, fail_above: float | None-) -> _Subject:- """The change to score: *revspec*, else the CI change for a gate or CI format."""- if revspec is None and (fail_above is not None or fmt in ("markdown", "github")):- # A CI checkout of a pull request is a merge commit, so HEAD alone is- # the wrong subject: the change is what the branch did since the target.- try:- revspec = ci_revspec(str(repo_root(repo_path)), None)- except CannotEvaluateError as exc:- cannot_evaluate(fmt, exc.code, str(exc))- return _Subject(repo_path, revspec, fmt, fail_above)---def _score(- subject: _Subject, extensions: tuple[str, ...], exclude: tuple[str, ...], baseline: int-) -> ChangeRiskResult:- """Score the change, or exit 2 when it cannot be read or, gated, ranked."""- status = ci_notices(subject.fmt)- _verify_revision(subject)- if baseline and subject.fmt == "table":- status.print(f"[dim]Sampling up to {baseline} recent commits…[/dim]")- try:- result = score_live_change(- subject.repo_path,- subject.revspec,- extensions=extensions,- exclude_patterns=exclude,- baseline=baseline,- )- except Exception as exc:- # Git errors (bad revspec, not a repo, missing history) cannot be scored.- cannot_evaluate(- subject.fmt,- "change_unreadable",- f"Could not read change {subject.revspec or 'HEAD'!r} in {subject.repo_path}: "- f"{_git_error_detail(exc)}",- )- if subject.fail_above is not None and result.percentile is None:- from repowise.core.analysis.change_risk.render import unranked_reason-- cannot_evaluate(subject.fmt, "no_baseline", unranked_reason(result, baseline))- if result.features.nf == 0:- status.print(- f"[yellow]No counted file changes in {result.features.ref!r} "- f"(check the revspec, --ext, or exclusion filters).[/yellow]"- )- return result---def _git_error_detail(exc: Exception) -> str:- """Git's own message for a failed git call, else the exception text."""- stderr = exc.stderr if isinstance(exc, subprocess.CalledProcessError) else None- if isinstance(stderr, bytes):- stderr = stderr.decode(errors="replace")- lines = [line.strip() for line in (stderr or "").splitlines() if line.strip()]- return lines[0] if lines else str(exc)---def _verify_revision(subject: _Subject) -> None:- """Exit 2 with git's message when a single-commit revspec does not resolve.-- Checked before the sampling notice so an unknown ref is reported first and- alone. Ranges and the working tree are left to the scorer.- """- revspec = subject.revspec- if not revspec or ".." in revspec:- return- try:- commit = f"{revspec}^{{commit}}"- subprocess.run(- ["git", "rev-parse", "--verify", "--quiet", "--end-of-options", commit],- cwd=subject.repo_path,- check=True,- capture_output=True,- text=True,- )- except subprocess.CalledProcessError:- # --quiet suppresses the message; ask git again for the human one.- probe = subprocess.run(- ["git", "rev-parse", "--end-of-options", revspec],- cwd=subject.repo_path,- capture_output=True,- text=True,- )- if probe.returncode == 0:- detail = f"{revspec!r} does not name a commit"- elif "unknown revision" in probe.stderr:- detail = _git_error_detail(- subprocess.CalledProcessError(probe.returncode, probe.args, stderr=probe.stderr)- )- else:- # Not a repository, or some other git failure: the scorer reports it.- return- cannot_evaluate(- subject.fmt,- "change_unreadable",- f"Could not read change {revspec!r} in {subject.repo_path}: {detail}",- )- except OSError:- return---def _print_change(subject: _Subject, result: ChangeRiskResult, failed: bool) -> None:- """The table rendering of a scored change."""- _print_size(result, subject.fail_above, failed)- _print_fix_history_and_shape(result)- groups = _independent_changes_for(subject.repo_path, result, subject.revspec)- if groups:- _print_independent_changes(groups)---def _print_size(result: ChangeRiskResult, fail_above: float | None, failed: bool) -> None:- """Lead with the one percentile: the change's rank by diff size and spread.-- Without a usable baseline, label the offline absolute band explicitly as- the fallback.- """- console.print(f"\n[bold]{size_text(result.percentile, fail_above)}[/bold]")- if result.percentile is None:- level = result.risk.level- color = {"high": "red", "moderate": "yellow", "low": "green"}[level]- console.print(f" Absolute per-commit diff-size band: [{color}]{level}[/{color}]")- elif fail_above is not None:- from repowise.core.analysis.change_risk.render import gate_text-- color = "red" if failed else "green"- console.print(f" [{color}]Gate: {gate_text(result, fail_above)}.[/{color}]")---def _print_fix_history_and_shape(result: ChangeRiskResult) -> None:- """Where the change lands (its fix record), then the shape of its diff."""- _print_fix_headline(result)- _print_change_facts(result)- _print_hot_files(result)- _print_diff_shape(result)---def _print_fix_headline(result: ChangeRiskResult) -> None:- """Fix history remains separate evidence about where the change lands."""- color = "red" if result.hot_files else "green"- if not result.fix_history_available:- color = "yellow"- console.print(- f"\n[bold]Bug-fix record[/bold] for [cyan]{escape(result.features.ref)}[/cyan]: "- f"[{color}]{fix_history_text(result)}[/{color}]"- )---def _print_change_facts(result: ChangeRiskResult) -> None:- """What was scored: the tree, the subject, the filters and the diff's features."""- features, request_excludes = result.features, result.request_excludes- if result.working_tree:- console.print(" [dim]Scoring your uncommitted changes, not the last commit.[/dim]")- 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 · "- f"entropy {features.entropy:.2f} · author exp "- f"{'unknown' if features.exp is None else features.exp}"- + (" [magenta](fix)[/magenta]" if features.is_fix else "")- )---def _print_hot_files(result: ChangeRiskResult) -> None:- """The fix record, named in the headline above and itemized here."""- if result.hot_files:- hot = Table(show_header=True)- hot.add_column("File")- hot.add_column("Lines", justify="right")- hot.add_column("Prior fixes", justify="right")- for path, churn, pressure in result.hot_files:- hot.add_row(escape(path), str(churn), f"{pressure:.1f}")- console.print(hot)- console.print(- " [dim]Prior fixes are recency-weighted against this change's own date — "- "one from a year earlier counts a half.[/dim]"- )---def _print_diff_shape(result: ChangeRiskResult) -> None:- """The supporting 0-10 diff-size score and its drivers."""- risk = result.risk- console.print(- f" [dim]Diff-size score: {risk.score:.1f}/10 — how big and spread out the change is, "- f"not where it lands. Corpus-anchored to a single commit.[/dim]"- )- console.print(f" [dim]{LIMITS}[/dim]")-- table = Table(title="Diff shape (each driver vs. the model's baseline commit)")- table.add_column("Driver")- table.add_column("Value", justify="right")- table.add_column("Push", justify="right")- for d in risk.top_drivers:- push_color = "red" if d.contribution > 0 else "green"- sign = "+" if d.contribution >= 0 else ""- table.add_row(- d.label,- "-" if d.value is None else f"{d.value:g}",- f"[{push_color}]{sign}{d.contribution:.2f}[/{push_color}]",- )- console.print(table)---def _emit_machine(subject: _Subject, result: ChangeRiskResult) -> None:- """The json, markdown and github renderings of a scored change."""- from repowise.core.analysis.change_risk import render-- fmt, fail_above = subject.fmt, subject.fail_above- if fmt == "json":- payload = change_risk_payload(result, scales=True)- groups = _independent_changes_for(subject.repo_path, result, subject.revspec)- if groups:- payload["independent_changes"] = groups- if fail_above is not None:- payload["gate"] = {- "fail_above_percentile": fail_above,- # Unrounded, as the gate compares it: ``risk_percentile`` is- # rounded to one decimal and can read as equal to the gate.- "percentile": result.percentile,- "status": render.percentile_gate(result, fail_above),- }- click.echo(json.dumps(payload, indent=2))- elif fmt == "markdown":- click.echo(render.render_markdown(result, fail_above), nl=False)- else:- for line in render.github_annotations(result, fail_above):- click.echo(line)- append_step_summary(render.render_markdown(result, fail_above))- console.print(render.headline(result, fail_above, markdown=False), markup=False)diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd/__init__.py b/packages/cli/src/repowise/cli/commands/risk_cmd/__init__.pynew file mode 100644index 000000000..c7c4daaad--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/risk_cmd/__init__.py@@ -0,0 +1,105 @@+"""``repowise risk`` — just-in-time change risk, for a change or for paths.++Two questions, one command, because they are the same question asked of+different subjects.++A REVSPEC scores a *change* from its diff shape (size, diffusion, author+familiarity) and leads with its percentile of recent commits by size and+spread, then the bug-fix record of the files it touches, then a supporting 0-10+diff-shape score with an attributable breakdown. Runs+in-process: pure git + learned constants, no LLM, no network. A natural+pre-merge / PR gate, complementary to ``repowise health`` (which scores files).++``--target <path>`` instead asks what history says about touching those files:+bug-fix pressure, churn trend, dependents, co-change partners, ownership. That+is the ``get_risk`` MCP tool, and this command is a thin adapter over it — the+same seam ``ask`` / ``context`` / ``symbol`` / ``why`` use. It reads the index+rather than git, so the repo must be indexed.++``--fail-above-percentile P`` makes the REVSPEC path a CI size gate on the+repo-relative percentile (never the 0-10 score), with the shared CI exit codes+(:mod:`repowise.cli.ci`): 1 above the gate, 2 when the change cannot be read+or ranked.++Examples:+ repowise risk # score uncommitted work, else HEAD+ repowise risk HEAD # score the last commit+ repowise risk abc123 # score a single commit+ repowise risk main..HEAD # score a branch / PR range as one change+ repowise risk --fail-above-percentile 95 --format github # gate the CI change+ repowise risk --target a.py -t b.py # what history says about those files++Modules:++* :mod:`.command`: the Click command+* :mod:`.change`: resolving and scoring a REVSPEC+* :mod:`.change_render`: table, json, markdown and github output for a change+* :mod:`.target`: ``--target`` (the ``get_risk`` adapter and its projection)+* :mod:`.card`: one target's risk card+* :mod:`.records`: directive blocks whose entries are dicts++Names are re-exported here; patch a name on the submodule that defines it.+"""++from __future__ import annotations++from .card import _print_list, _render_card+from .change import (+ _git_error_detail,+ _resolve_subject,+ _score,+ _Subject,+ _verify_revision,+)+from .change_render import (+ _UNGROUPED_SHOWN,+ _emit_machine,+ _independent_changes_for,+ _print_change,+ _print_change_facts,+ _print_diff_shape,+ _print_fix_headline,+ _print_fix_history_and_shape,+ _print_hot_files,+ _print_independent_changes,+ _print_size,+)+from .command import risk_command+from .records import _DIRECTIVE_RECORD_BLOCKS, _print_records, _record_text+from .target import (+ _DROPPED_TARGET_KEYS,+ _project_target,+ _render_target_risk,+ _target_risk,+ project_risk,+)++__all__ = [+ "_DIRECTIVE_RECORD_BLOCKS",+ "_DROPPED_TARGET_KEYS",+ "_UNGROUPED_SHOWN",+ "_Subject",+ "_emit_machine",+ "_git_error_detail",+ "_independent_changes_for",+ "_print_change",+ "_print_change_facts",+ "_print_diff_shape",+ "_print_fix_headline",+ "_print_fix_history_and_shape",+ "_print_hot_files",+ "_print_independent_changes",+ "_print_list",+ "_print_records",+ "_print_size",+ "_project_target",+ "_record_text",+ "_render_card",+ "_render_target_risk",+ "_resolve_subject",+ "_score",+ "_target_risk",+ "_verify_revision",+ "project_risk",+ "risk_command",+]diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd/card.py b/packages/cli/src/repowise/cli/commands/risk_cmd/card.pynew file mode 100644index 000000000..7bc4429c7--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/risk_cmd/card.py@@ -0,0 +1,177 @@+"""One ``--target`` risk card, a line per block the projection keeps."""++from __future__ import annotations++from rich.markup import escape++from repowise.cli.commands import _tool_adapters as _ta+from repowise.cli.helpers import console++#: Co-change partners printed before the "and N more" line.+_PARTNERS_SHOWN = 8+++def _print_list(label: str, values: list[str], *, indent: str = " ") -> None:+ if not values:+ return+ console.print(f"{indent}[bold]{label}[/bold] " + ", ".join(escape(str(v)) for v in values))+++def _render_card(name: str, card: dict) -> None:+ """One target's risk card.++ Every key the projection keeps owes a line here: a kept key no renderer+ prints is a silent failure a projection test cannot see.+ """+ console.print(f"\n[bold cyan]{escape(name)}[/bold cyan]")+ summary = card.get("risk_summary")+ if summary:+ console.print(f" {escape(str(summary))}")+ if card.get("resolved") is False:+ # The lines below default missing fields to numbers, so stop here rather+ # than print "0 direct dependents".+ reason = escape(str(card.get("unresolved_reason") or "unknown"))+ console.print(f" [dim]unresolved: {reason}[/dim]")+ return+ _print_activity(card)+ _print_health(card)+ _print_biomarkers(card.get("top_biomarkers") or [])+ _print_magnitude(card)+ _print_ownership_moves(card)+ _print_cross_repo(card.get("cross_repo_impact") or {})+ _print_defects(card.get("defect_profile"))+ if card.get("test_gap"):+ console.print(" [yellow]No test file matches this file's name.[/yellow]")+ for signal in card.get("security_signals") or []:+ console.print(+ f" [red]{escape(str(signal.get('severity', '')))}[/red] "+ f"{escape(str(signal.get('kind', '')))}: {escape(str(signal.get('snippet', '')))}"+ )+ _print_partners(card.get("co_change_partners") or [])+ episodes = card.get("episodes")+ if episodes:+ console.print(f" [dim]{episodes} recorded episode(s) — see 'repowise why'.[/dim]")+++def _print_activity(card: dict) -> None:+ """Hotspot, dependents and ownership; history alone when nothing else was measured."""+ trend = card.get("trend") or "unknown"+ owner = escape(str(card.get("primary_owner") or "unknown"))+ if card.get("signal_tier") == "history":+ last = str(card.get("last_commit_at") or "unknown")[:10]+ console.print(+ f" [dim]history only · {card.get('commit_count_total', 0)} commits ({trend}) · "+ f"last {escape(last)} · owned {_ta.owner_share(card.get('owner_pct'))} by "+ f"{owner}[/dim]"+ )+ return+ console.print(+ f" [dim]hotspot {float(card.get('hotspot_score') or 0.0):.0%} ({trend}) · "+ f"{card.get('dependents_count', 0)} direct dependents · "+ f"{card.get('risk_type', 'unknown')} · owned "+ f"{_ta.owner_share(card.get('owner_pct'))} by "+ f"{owner}[/dim]"+ )+++def _print_health(card: dict) -> None:+ health = card.get("health_score")+ coverage = card.get("line_coverage_pct")+ if health is None and coverage is None:+ return+ parts = []+ if health is not None:+ parts.append(f"health {float(health):.1f}/10")+ if coverage is not None:+ parts.append(f"coverage {float(coverage):.0f}%")+ console.print(f" [dim]{escape(' · '.join(parts))}[/dim]")+++def _biomarker_text(b: object) -> str:+ # Keyed ``biomarker_type``: a generic key guess prints the whole dict repr.+ if not isinstance(b, dict):+ return str(b)+ where = f" in {b['function_name']}" if b.get("function_name") else ""+ return f"{b.get('biomarker_type', '?')} ({b.get('severity', '?')}){where}"+++def _print_biomarkers(biomarkers: list) -> None:+ if biomarkers:+ shown = [_biomarker_text(b) for b in biomarkers[:3]]+ console.print(f" [dim]{escape(', '.join(shown))}[/dim]")+++def _print_magnitude(card: dict) -> None:+ magnitude = card.get("change_magnitude") or {}+ if magnitude:+ console.print(+ f" [dim]+{magnitude.get('lines_added_90d', 0)} / "+ f"-{magnitude.get('lines_deleted_90d', 0)} lines in 90d · "+ f"avg commit {magnitude.get('avg_commit_size', 0)} lines · "+ f"{card.get('contributor_count', 0)} contributor(s), "+ f"bus factor {card.get('bus_factor', '?')}[/dim]"+ )+++def _print_ownership_moves(card: dict) -> None:+ """A rename, and a recent owner who is not the historical one."""+ if card.get("original_path"):+ console.print(f" [dim]Renamed from {escape(str(card['original_path']))}.[/dim]")+ if card.get("recent_owner") and card["recent_owner"] != card.get("primary_owner"):+ console.print(+ f" [dim]Recently owned {_ta.owner_share(card.get('recent_owner_pct'))} by "+ f"{escape(str(card['recent_owner']))}.[/dim]"+ )+++def _print_cross_repo(cross: dict) -> None:+ if not cross:+ return+ repos = cross.get("affected_repos") or []+ historical = cross.get("cross_repo_consumers") or []+ contracts = cross.get("contract_consumers") or []+ console.print(+ " [bold]Crosses repo boundaries[/bold] [dim]"+ f"{cross.get('cross_repo_consumers_total', len(historical))} historical co-change(s)"+ + (+ f", {cross.get('contract_consumers_total', len(contracts))} "+ "typed contract consumer(s)"+ if contracts+ else ""+ )+ + (f" in {', '.join(str(r) for r in repos)}" if repos else "")+ + "[/dim]"+ )+++def _print_defects(defect: dict | None) -> None:+ if not defect:+ return+ magnet = " [magenta](bug magnet)[/magenta]" if defect.get("bug_magnet") else ""+ console.print(+ f" [yellow]{defect.get('fix_count', 0)} bug fix(es)[/yellow], last "+ f"{defect.get('last_fix_days_ago', '?')} day(s) ago{magnet}"+ )+ # ``top_symbols`` is a ``{name: fix_count}`` dict; iterating it bare drops the counts.+ top = defect.get("top_symbols") or {}+ pairs = top.items() if isinstance(top, dict) else [(s, None) for s in top]+ _print_list(+ "Mostly in",+ [f"{name}" + (f" (x{count})" if count is not None else "") for name, count in pairs],+ indent=" ",+ )+++def _print_partners(partners: list) -> None:+ if not partners:+ return+ console.print(" [bold]Co-changes with[/bold]")+ for p in partners[:_PARTNERS_SHOWN]:+ link = " [dim](also imports)[/dim]" if p.get("has_import_link") else ""+ support = p.get("support")+ support_text = f" [dim]x{support}[/dim]" if support is not None else ""+ console.print(f" {escape(str(p.get('file_path', '')))}{support_text}{link}")+ if len(partners) > _PARTNERS_SHOWN:+ console.print(+ f" [dim]… and {len(partners) - _PARTNERS_SHOWN} more (--format json).[/dim]"+ )diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd/change.py b/packages/cli/src/repowise/cli/commands/risk_cmd/change.pynew file mode 100644index 000000000..0d17af99c--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/risk_cmd/change.py@@ -0,0 +1,122 @@+"""Resolving and scoring the change a REVSPEC names."""++from __future__ import annotations++import subprocess+from dataclasses import dataclass++from repowise.cli.ci import CannotEvaluateError, cannot_evaluate, ci_notices, ci_revspec, repo_root+from repowise.core.analysis.change_risk import ChangeRiskResult, score_live_change+++@dataclass(frozen=True)+class _Subject:+ """The change a REVSPEC run scores, and how it reports it."""++ repo_path: str+ revspec: str | None+ fmt: str+ fail_above: float | None+++def _resolve_subject(+ repo_path: str, revspec: str | None, fmt: str, fail_above: float | None+) -> _Subject:+ """The change to score: *revspec*, else the CI change for a gate or CI format."""+ if revspec is None and (fail_above is not None or fmt in ("markdown", "github")):+ # A CI checkout of a pull request is a merge commit, so HEAD alone is+ # the wrong subject: the change is what the branch did since the target.+ try:+ revspec = ci_revspec(str(repo_root(repo_path)), None)+ except CannotEvaluateError as exc:+ cannot_evaluate(fmt, exc.code, str(exc))+ return _Subject(repo_path, revspec, fmt, fail_above)+++def _score(+ subject: _Subject, extensions: tuple[str, ...], exclude: tuple[str, ...], baseline: int+) -> ChangeRiskResult:+ """Score the change, or exit 2 when it cannot be read or, gated, ranked."""+ status = ci_notices(subject.fmt)+ _verify_revision(subject)+ if baseline and subject.fmt == "table":+ status.print(f"[dim]Sampling up to {baseline} recent commits…[/dim]")+ try:+ result = score_live_change(+ subject.repo_path,+ subject.revspec,+ extensions=extensions,+ exclude_patterns=exclude,+ baseline=baseline,+ )+ except Exception as exc:+ # Git errors (bad revspec, not a repo, missing history) cannot be scored.+ cannot_evaluate(+ subject.fmt,+ "change_unreadable",+ f"Could not read change {subject.revspec or 'HEAD'!r} in {subject.repo_path}: "+ f"{_git_error_detail(exc)}",+ )+ if subject.fail_above is not None and result.percentile is None:+ from repowise.core.analysis.change_risk.render import unranked_reason++ cannot_evaluate(subject.fmt, "no_baseline", unranked_reason(result, baseline))+ if result.features.nf == 0:+ status.print(+ f"[yellow]No counted file changes in {result.features.ref!r} "+ f"(check the revspec, --ext, or exclusion filters).[/yellow]"+ )+ return result+++def _git_error_detail(exc: Exception) -> str:+ """Git's own message for a failed git call, else the exception text."""+ stderr = exc.stderr if isinstance(exc, subprocess.CalledProcessError) else None+ if isinstance(stderr, bytes):+ stderr = stderr.decode(errors="replace")+ lines = [line.strip() for line in (stderr or "").splitlines() if line.strip()]+ return lines[0] if lines else str(exc)+++def _verify_revision(subject: _Subject) -> None:+ """Exit 2 with git's message when a single-commit revspec does not resolve.++ Checked before the sampling notice so an unknown ref is reported first and+ alone. Ranges and the working tree are left to the scorer.+ """+ revspec = subject.revspec+ if not revspec or ".." in revspec:+ return+ try:+ commit = f"{revspec}^{{commit}}"+ subprocess.run(+ ["git", "rev-parse", "--verify", "--quiet", "--end-of-options", commit],+ cwd=subject.repo_path,+ check=True,+ capture_output=True,+ text=True,+ )+ except subprocess.CalledProcessError:+ # --quiet suppresses the message; ask git again for the human one.+ probe = subprocess.run(+ ["git", "rev-parse", "--end-of-options", revspec],+ cwd=subject.repo_path,+ capture_output=True,+ text=True,+ )+ if probe.returncode == 0:+ detail = f"{revspec!r} does not name a commit"+ elif "unknown revision" in probe.stderr:+ detail = _git_error_detail(+ subprocess.CalledProcessError(probe.returncode, probe.args, stderr=probe.stderr)+ )+ else:+ # Not a repository, or some other git failure: the scorer reports it.+ return+ cannot_evaluate(+ subject.fmt,+ "change_unreadable",+ f"Could not read change {revspec!r} in {subject.repo_path}: {detail}",+ )+ except OSError:+ returndiff --git a/packages/cli/src/repowise/cli/commands/risk_cmd/change_render.py b/packages/cli/src/repowise/cli/commands/risk_cmd/change_render.pynew file mode 100644index 000000000..767e25097--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/risk_cmd/change_render.py@@ -0,0 +1,203 @@+"""Output for a scored change: the table, and the json / markdown / github formats."""++from __future__ import annotations++import json+from pathlib import Path++import click+from rich.markup import escape+from rich.table import Table++from repowise.cli.ci import append_step_summary+from repowise.cli.helpers import console, repo_index_session, run_async+from repowise.core.analysis.change_risk import ChangeRiskResult, change_risk_payload+from repowise.core.analysis.change_risk.render import LIMITS, fix_history_text, size_text++from .change import _Subject++#: How many ungrouped names the table prints; the summary already states the count.+_UNGROUPED_SHOWN = 10+++def _independent_changes_for(repo_path: str, result, revspec: str | None) -> dict | None:+ """How this diff splits, per the index, or ``None`` when it cannot be read."""+ from sqlalchemy.exc import SQLAlchemyError++ from repowise.core import git_refs+ from repowise.core.analysis.independent_changes import independent_changes++ paths = [path for path, _ in result.features.file_churn]+ if len(paths) < 2:+ return None+ # A diff names paths from the repository root, so a command run in a+ # subdirectory has to score against that root, not against the given path.+ root = Path(git_refs.toplevel(repo_path) or repo_path).resolve()+ # Read git before the store opens: no subprocess while a connection is held.+ sets = git_refs.commit_file_sets(str(root), revspec)++ async def read() -> dict | None:+ found = None+ async with repo_index_session(root) as opened:+ if opened is not None:+ session, repo_id = opened+ try:+ found = await independent_changes(session, repo_id, paths, commit_sets=sets)+ except (SQLAlchemyError, OSError, LookupError):+ # An index written by an older version can fail the query itself.+ return None+ return found.to_dict() if found else None++ return run_async(read())+++def _print_independent_changes(block: dict) -> None:+ """The groups, plainly: no score, no percentage, no adjective."""+ console.print(f"\n[bold]{escape(str(block.get('summary') or ''))}[/bold]")+ for number, group in enumerate(block.get("groups") or [], start=1):+ files = [str(f) for f in group.get("files") or []]+ plural = "" if len(files) == 1 else "s"+ console.print(f" {number}. {len(files)} file{plural}: {escape(', '.join(files))}")+ bridging = [str(f) for f in group.get("bridging_files") or []]+ if bridging:+ # Naming these files says where the group would split if one moved out.+ console.print(f" [dim]held together by: {escape(', '.join(bridging))}[/dim]")+ ungrouped = [str(f) for f in block.get("ungrouped_files") or []]+ if ungrouped:+ shown = escape(", ".join(ungrouped[:_UNGROUPED_SHOWN]))+ cut = len(ungrouped) - _UNGROUPED_SHOWN+ more = f" and {cut} more" if cut > 0 else ""+ console.print(f" Left out of the grouping: {shown}{more}")+ console.print(f" [dim]Basis: {escape(str(block.get('basis') or ''))}.[/dim]")+++def _print_change(subject: _Subject, result: ChangeRiskResult, failed: bool) -> None:+ """The table rendering of a scored change."""+ _print_size(result, subject.fail_above, failed)+ _print_fix_history_and_shape(result)+ groups = _independent_changes_for(subject.repo_path, result, subject.revspec)+ if groups:+ _print_independent_changes(groups)+++def _print_size(result: ChangeRiskResult, fail_above: float | None, failed: bool) -> None:+ """Lead with the one percentile: the change's rank by diff size and spread.++ Without a usable baseline, label the offline absolute band explicitly as+ the fallback.+ """+ console.print(f"\n[bold]{size_text(result.percentile, fail_above)}[/bold]")+ if result.percentile is None:+ level = result.risk.level+ color = {"high": "red", "moderate": "yellow", "low": "green"}[level]+ console.print(f" Absolute per-commit diff-size band: [{color}]{level}[/{color}]")+ elif fail_above is not None:+ from repowise.core.analysis.change_risk.render import gate_text++ color = "red" if failed else "green"+ console.print(f" [{color}]Gate: {gate_text(result, fail_above)}.[/{color}]")+++def _print_fix_history_and_shape(result: ChangeRiskResult) -> None:+ """Where the change lands (its fix record), then the shape of its diff."""+ _print_fix_headline(result)+ _print_change_facts(result)+ _print_hot_files(result)+ _print_diff_shape(result)+++def _print_fix_headline(result: ChangeRiskResult) -> None:+ """Fix history remains separate evidence about where the change lands."""+ color = "red" if result.hot_files else "green"+ if not result.fix_history_available:+ color = "yellow"+ console.print(+ f"\n[bold]Bug-fix record[/bold] for [cyan]{escape(result.features.ref)}[/cyan]: "+ f"[{color}]{fix_history_text(result)}[/{color}]"+ )+++def _print_change_facts(result: ChangeRiskResult) -> None:+ """What was scored: the tree, the subject, the filters and the diff's features."""+ features, request_excludes = result.features, result.request_excludes+ if result.working_tree:+ console.print(" [dim]Scoring your uncommitted changes, not the last commit.[/dim]")+ 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 · "+ f"entropy {features.entropy:.2f} · author exp "+ f"{'unknown' if features.exp is None else features.exp}"+ + (" [magenta](fix)[/magenta]" if features.is_fix else "")+ )+++def _print_hot_files(result: ChangeRiskResult) -> None:+ """The fix record, named in the headline above and itemized here."""+ if result.hot_files:+ hot = Table(show_header=True)+ hot.add_column("File")+ hot.add_column("Lines", justify="right")+ hot.add_column("Prior fixes", justify="right")+ for path, churn, pressure in result.hot_files:+ hot.add_row(escape(path), str(churn), f"{pressure:.1f}")+ console.print(hot)+ console.print(+ " [dim]Prior fixes are recency-weighted against this change's own date — "+ "one from a year earlier counts a half.[/dim]"+ )+++def _print_diff_shape(result: ChangeRiskResult) -> None:+ """The supporting 0-10 diff-size score and its drivers."""+ risk = result.risk+ console.print(+ f" [dim]Diff-size score: {risk.score:.1f}/10 — how big and spread out the change is, "+ f"not where it lands. Corpus-anchored to a single commit.[/dim]"+ )+ console.print(f" [dim]{LIMITS}[/dim]")++ table = Table(title="Diff shape (each driver vs. the model's baseline commit)")+ table.add_column("Driver")+ table.add_column("Value", justify="right")+ table.add_column("Push", justify="right")+ for d in risk.top_drivers:+ push_color = "red" if d.contribution > 0 else "green"+ sign = "+" if d.contribution >= 0 else ""+ table.add_row(+ d.label,+ "-" if d.value is None else f"{d.value:g}",+ f"[{push_color}]{sign}{d.contribution:.2f}[/{push_color}]",+ )+ console.print(table)+++def _emit_machine(subject: _Subject, result: ChangeRiskResult) -> None:+ """The json, markdown and github renderings of a scored change."""+ from repowise.core.analysis.change_risk import render++ fmt, fail_above = subject.fmt, subject.fail_above+ if fmt == "json":+ payload = change_risk_payload(result, scales=True)+ groups = _independent_changes_for(subject.repo_path, result, subject.revspec)+ if groups:+ payload["independent_changes"] = groups+ if fail_above is not None:+ payload["gate"] = {+ "fail_above_percentile": fail_above,+ # Unrounded, as the gate compares it: ``risk_percentile`` is+ # rounded to one decimal and can read as equal to the gate.+ "percentile": result.percentile,+ "status": render.percentile_gate(result, fail_above),+ }+ click.echo(json.dumps(payload, indent=2))+ elif fmt == "markdown":+ click.echo(render.render_markdown(result, fail_above), nl=False)+ else:+ for line in render.github_annotations(result, fail_above):+ click.echo(line)+ append_step_summary(render.render_markdown(result, fail_above))+ console.print(render.headline(result, fail_above, markdown=False), markup=False)diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd/command.py b/packages/cli/src/repowise/cli/commands/risk_cmd/command.pynew file mode 100644index 000000000..2829e3a15--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/risk_cmd/command.py@@ -0,0 +1,125 @@+"""The ``repowise risk`` Click command."""++from __future__ import annotations++import click++from repowise.cli.ci import CI_FORMATS, EXIT_GATE_FAILED+from repowise.cli.commands import _tool_adapters as _ta+from repowise.cli.output import format_option, full_option++from .change import _resolve_subject, _score+from .change_render import _emit_machine, _print_change+from .target import _target_risk++[email protected]("risk")[email protected]("revspec", required=False, default=None)+ "--path",+ "repo_path",+ default=".",+ type=click.Path(exists=True, file_okay=False),+ help="Path to the git repository (default: current directory).",+)+ "--ext",+ "ext",+ default=None,+ help="Comma-separated file suffixes to count (e.g. '.py' or '.ts,.tsx'). "+ "Default: count every changed file.",+)+ "--baseline",+ "baseline",+ default=200,+ type=click.IntRange(min=0),+ help="Sample this many recent commits to rank the change within the repo "+ "(0 disables; shows only the absolute per-commit model-score band).",+)+ "--exclude",+ "-x",+ "exclude",+ multiple=True,+ metavar="PATTERN",+ help="Gitignore-style pattern to exclude. Repeatable; also applies to the baseline.",+)+ "--target",+ "-t",+ "targets",+ multiple=True,+ metavar="PATH",+ help="Score what history says about these FILES instead of a change. "+ "Repeatable. Reads the index, so the repo must be indexed.",+)+ "--changed-file",+ "changed_files",+ multiple=True,+ metavar="PATH",+ help="With --target: PR mode. The response leads with a directive naming "+ "structural review candidates, missing co-changes/tests, and what to run.",+)+ "--fail-above-percentile",+ "fail_above",+ type=click.FloatRange(0, 100),+ default=None,+ help="CI gate: exit 1 when the change ranks above this percentile of recent "+ "commits (risk_percentile, never the 0-10 score); exit 2 when it cannot be "+ "ranked. Without REVSPEC it scores the CI change against its target branch.",+)+@format_option(+ choices=CI_FORMATS,+ help="Output format. ``markdown`` and ``github`` are not for --target, and "+ "without REVSPEC they score the CI change against its target branch; "+ "``github`` writes annotations to stdout and the markdown summary to "+ "$GITHUB_STEP_SUMMARY when set.",+)+@full_option()+def risk_command(+ revspec: str | None,+ repo_path: str,+ ext: str | None,+ baseline: int,+ exclude: tuple[str, ...],+ targets: tuple[str, ...],+ changed_files: tuple[str, ...],+ fail_above: float | None,+ fmt: str,+ full: bool,+) -> None:+ """Rank a change by size and spread, or report the history of named files.++ With no --target this scores REVSPEC (a commit, or a ``base..head``+ range) from its diff. Omit REVSPEC to score your uncommitted work, or+ HEAD when the tree is clean; with --fail-above-percentile, or a+ markdown or github format, it scores the CI change instead (the pull+ request's target branch...HEAD). With+ --target it reports what the repo's history says about the named files,+ the same as the get_risk MCP tool.+ """+ if targets:+ if fmt not in ("table", "json"):+ raise click.UsageError("--target supports --format table or json.")+ if fail_above is not None:+ raise click.UsageError("--fail-above-percentile gates a change, not --target files.")+ _target_risk(repo_path, targets, changed_files, fmt, full)+ return+ if changed_files:+ raise click.UsageError("--changed-file needs at least one --target.")+ # ``--full`` means the complete payload as JSON on every command; the+ # REVSPEC path has a full payload too, so the flag is honoured here.+ fmt = _ta.resolve_format_for(fmt, full)+ subject = _resolve_subject(repo_path, revspec, fmt, fail_above)+ extensions = tuple(e.strip() for e in ext.split(",")) if ext else ()+ result = _score(subject, extensions, exclude, baseline)+ failed = fail_above is not None and result.percentile > fail_above+ if fmt == "table":+ _print_change(subject, result, failed)+ else:+ _emit_machine(subject, result)+ if failed:+ raise click.exceptions.Exit(EXIT_GATE_FAILED)diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd/records.py b/packages/cli/src/repowise/cli/commands/risk_cmd/records.pynew file mode 100644index 000000000..494f9eb18--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/risk_cmd/records.py@@ -0,0 +1,75 @@+"""Directive blocks whose entries are dicts, one line per entry."""++from __future__ import annotations++from rich.markup import escape++from repowise.cli.helpers import console++#: The dict-entry directive blocks. Each is built in ``tool_risk/directives.py``+#: with its own key set, so each gets its own formatter in ``_record_text``.+_DIRECTIVE_RECORD_BLOCKS = (+ ("Consumer structural reach", "will_break_consumers"),+ ("Missing cross-repo co-changes", "missing_cross_repo_cochanges"),+ ("Breaking contract changes", "breaking_changes"),+ ("Conformance violations", "conformance_violations"),+ ("Dependency cycles", "dependency_cycles"),+ ("Governance risk", "governance_risk"),+)+++def _consumer_text(entry: dict) -> str:+ where = f" [{entry.get('repo')}]" if entry.get("repo") else ""+ return f"{entry.get('service') or entry.get('repo') or '?'}{where}"+++def _breaking_change_text(entry: dict) -> str:+ consumers = entry.get("impacted_consumers") or []+ who = f" — endangers {len(consumers)} consumer(s)" if consumers else ""+ return (+ f"{entry.get('contract_id') or '?'}: {entry.get('kind') or '?'}"+ f" ({entry.get('severity') or '?'}) {entry.get('detail') or ''}{who}".rstrip()+ )+++def _conformance_text(entry: dict) -> str:+ rule = entry.get("rule") or f"{entry.get('source')} -> {entry.get('target')}"+ return f"{rule}{': ' + entry['description'] if entry.get('description') else ''}"+++def _cycle_text(entry: dict) -> str:+ nodes = entry.get("nodes") or []+ return " -> ".join(str(n) for n in nodes) or f"cycle of {entry.get('length', '?')}"+++def _governance_text(entry: dict) -> str:+ # The title names the decision; ``reason`` alone is a bare token.+ return f"{entry.get('title') or entry.get('decision_id') or '?'} ({entry.get('reason')})"+++_RECORD_FORMATTERS = {+ "will_break_consumers": _consumer_text,+ "missing_cross_repo_cochanges": _consumer_text,+ "breaking_changes": _breaking_change_text,+ "conformance_violations": _conformance_text,+ "dependency_cycles": _cycle_text,+ "governance_risk": _governance_text,+}+++def _record_text(key: str, entry: dict) -> str:+ """One directive entry as a line, per the shape its block is built with."""+ formatter = _RECORD_FORMATTERS.get(key)+ return formatter(entry) if formatter else str(entry)+++def _print_records(label: str, values: list, key: str, truncated: int = 0) -> None:+ """A directive block whose entries are dicts, one line each."""+ if not values:+ return+ console.print(f" [bold]{label}[/bold]")+ for entry in values:+ text = _record_text(key, entry) if isinstance(entry, dict) else str(entry)+ console.print(f" {escape(str(text))}")+ if truncated:+ console.print(f" [dim]... and {truncated} more[/dim]")diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd/target.py b/packages/cli/src/repowise/cli/commands/risk_cmd/target.pynew file mode 100644index 000000000..b51604d0d--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/risk_cmd/target.py@@ -0,0 +1,156 @@+"""``repowise risk --target``: the ``get_risk`` adapter and its projection."""++from __future__ import annotations++from rich.markup import escape+from rich.table import Table++from repowise.cli.commands import _tool_adapters as _ta+from repowise.cli.helpers import console+from repowise.cli.output import emit_json++from .card import _print_list, _render_card+from .records import _DIRECTIVE_RECORD_BLOCKS, _print_records++#: Per-target keys the trim drops, and nothing else. A denylist on purpose: its+#: failure mode is a slightly larger payload, an allowlist's is a lost answer.+#: ``impact_surface`` is opt-in on the tool; the entry stays for hand-built payloads.+_DROPPED_TARGET_KEYS = ("_base_dep_count", "impact_surface")+++def _project_target(card: dict) -> dict:+ """One ``get_risk`` target card, minus the blocks in ``_DROPPED_TARGET_KEYS``."""+ return {k: v for k, v in card.items() if k not in _DROPPED_TARGET_KEYS}+++def project_risk(payload: dict) -> dict:+ """``get_risk``'s dict, trimmed to what a CLI caller reads.++ Kept whole: ``directive`` (the answer in PR mode), ``pr_blast_radius``+ (already capped by the tool), ``global_hotspots``, and the freshness half+ of ``_meta``. Dropped: the timing half of ``_meta`` and the per-target+ keys in ``_DROPPED_TARGET_KEYS``.+ """+ out: dict = {}+ if payload.get("directive"):+ out["directive"] = payload["directive"]+ out["targets"] = {+ name: _project_target(card) for name, card in (payload.get("targets") or {}).items()+ }+ for key in ("risk_scales", "pr_blast_radius", "global_hotspots", "omission_marker"):+ if payload.get(key):+ out[key] = payload[key]+ note = _ta.index_note(payload)+ if note:+ out["index"] = note+ return out+++def _target_risk(+ repo_path: str,+ targets: tuple[str, ...],+ changed_files: tuple[str, ...],+ fmt: str,+ full: bool,+) -> None:+ """``--target``: what history says about touching these files."""+ fmt = _ta.resolve_format_for(fmt, full)+ repo = _ta.resolve_indexed_repo(+ path=repo_path,+ repo_alias=None,+ no_workspace=False,+ fmt=fmt,+ command="risk",+ )++ def _factory():+ from repowise.server.mcp_server.tool_risk.get_risk import get_risk++ return get_risk(+ targets=list(targets),+ changed_files=list(changed_files) or None,+ # Every block the card prints; --format json also keeps the PR blast radius.+ include=["churn", "owners", "blast"],+ )++ payload = _ta.run(repo, _factory, "get_risk")++ if full:+ _ta.emit_full(payload)+ return+ _ta.emit_error(payload, fmt, extra={"targets": list(targets)})+ projected = project_risk(payload)+ if fmt == "json":+ emit_json(projected)+ return+ _render_target_risk(projected, targets)+ _ta.print_index_note(payload, fmt)+++def _render_target_risk(projected: dict, requested: tuple[str, ...]) -> None:+ """The human path for ``--target``: the directive first, then a card each."""+ directive = projected.get("directive")+ if directive:+ _print_directive(directive)+ _print_cards(projected.get("targets") or {}, requested)+ hotspots = projected.get("global_hotspots") or []+ if hotspots:+ _print_global_hotspots(hotspots)+ if projected.get("omission_marker"):+ # Escaped: it opens with a bracket rich would parse as a style tag.+ console.print(escape(str(projected["omission_marker"])), style="cyan")+++def _print_directive(directive: dict) -> None:+ """PR mode leads with the directive: what may break, what is missing, what to run."""+ console.print(f"\n[bold]Directive[/bold] {escape(str(directive.get('summary', '')))}")+ for label, key in (+ ("May break", "may_break"),+ ("Missing co-changes", "missing_cochanges"),+ ("Files without tests", "missing_tests"),+ ("Tests to run", "tests_to_run"),+ ):+ _print_list(label, directive.get(key) or [])+ for label, key in _DIRECTIVE_RECORD_BLOCKS:+ _print_records(+ label,+ directive.get(key) or [],+ key,+ truncated=directive.get(f"{key}_truncated") or 0,+ )+ calls = directive.get("next_calls") or []+ _print_list("Then run", [c["cli"] for c in calls if c.get("cli")])+++def _print_cards(targets: dict, requested: tuple[str, ...]) -> None:+ """A card per requested target, then any the tool returned under another spelling."""+ for name in requested:+ card = targets.get(name)+ if card is None:+ # Excluded paths are filtered before the tool sees them, so no card+ # is an answer, not an empty section.+ console.print(f"\n[yellow]{escape(name)} — not indexed (or excluded).[/yellow]")+ continue+ _render_card(name, card)+ for name, card in targets.items():+ if name not in requested:+ _render_card(name, card)+++def _print_global_hotspots(hotspots: list) -> None:+ """The repo's other hotspots, as a table."""+ table = Table(title="Elsewhere in this repo")+ table.add_column("File", style="cyan")+ table.add_column("Hotspot", justify="right")+ table.add_column("Owner")+ table.add_column("Fixes", justify="right")+ for h in hotspots:+ score = h.get("hotspot_score")+ fixes = h.get("fix_count")+ table.add_row(+ escape(str(h.get("file_path", ""))),+ "?" if score is None else f"{float(score):.0%}",+ escape(str(h.get("primary_owner") or "unknown")),+ "" if fixes is None else str(fixes),+ )+ console.print(table)diff --git a/tests/unit/cli/test_risk_cmd_contract.py b/tests/unit/cli/test_risk_cmd_contract.pyindex 1d96996d5..c11c7cdfb 100644--- a/tests/unit/cli/test_risk_cmd_contract.py+++ b/tests/unit/cli/test_risk_cmd_contract.py@@ -209,7 +209,7 @@ def test_a_history_tier_card_prints_its_history_not_hotspot_zeros() -> None:from rich.console import Console- from repowise.cli.commands import risk_cmd+ from repowise.cli.commands.risk_cmd import card as risk_cardcard = {"signal_tier": "history",@@ -222,8 +222,8 @@ def test_a_history_tier_card_prints_its_history_not_hotspot_zeros() -> None:projected = project_risk({"targets": {"queries/java.scm": card}})["targets"]["queries/java.scm"]assert projected["signal_tier"] == "history" and projected["commit_count_total"] == 11rec = Console(record=True, width=300)- with patch.object(risk_cmd, "console", rec):- risk_cmd._render_card("queries/java.scm", projected)+ with patch.object(risk_card, "console", rec):+ risk_card._render_card("queries/java.scm", projected)out = rec.export_text()assert "history only · 11 commits (stable) · last 2026-03-01" in outassert "Carol" in outdiff --git a/tests/unit/cli/test_search_collapse.py b/tests/unit/cli/test_search_collapse.pyindex d2e95e360..24699702e 100644--- a/tests/unit/cli/test_search_collapse.py+++ b/tests/unit/cli/test_search_collapse.py@@ -681,7 +681,7 @@ def test_risk_without_a_target_still_scores_a_revspec(monkeypatch, repo):"""The collapse must not move the command's default subject."""called: list = []monkeypatch.setattr(- "repowise.cli.commands.risk_cmd.score_live_change",+ "repowise.cli.commands.risk_cmd.change.score_live_change",lambda *a, **k: called.append(a) or (_ for _ in ()).throw(RuntimeError("boom")),)result = CliRunner(mix_stderr=False).invoke(risk_command, ["HEAD", "--path", str(repo)])@@ -804,11 +804,11 @@ def test_risk_full_on_a_revspec_is_json_not_a_table(monkeypatch, repo):from repowise.core.analysis.change_risk import ChangeRiskResultmonkeypatch.setattr(- "repowise.cli.commands.risk_cmd.change_risk_payload",+ "repowise.cli.commands.risk_cmd.change_render.change_risk_payload",lambda r, **kw: {"risk": 4.2},)monkeypatch.setattr(- "repowise.cli.commands.risk_cmd.score_live_change",+ "repowise.cli.commands.risk_cmd.change.score_live_change",lambda *a, **k: _FakeChangeResult(),)result = CliRunner(mix_stderr=False).invoke(