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(health): bare `repowise health` reads the stored analysis (#3280)
Raghav Chamadiyabc89359e6d0a
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.mdindex 990e6d76e..a36b517a2 100644--- a/.github/CONTRIBUTING.md+++ b/.github/CONTRIBUTING.md@@ -135,7 +135,7 @@ and it can be split into its own issue so more than one person can work in paralBefore you start, check the file you are about to edit:```bash-uv run repowise health --file <path> # score, markers, findings+uv run repowise health --file <path> --recompute # score, markers, findingsuv run repowise risk HEAD # or ask get_risk from your agent```@@ -165,7 +165,7 @@ current ones. Changes there are welcome, but expect closer review and bring testuv run repowise risk main..HEAD # 0-10 defect score, plus may_break,# missing_cochanges and missing_testsuv run repowise impacted-tests --staged # the tests your diff actually exercises- uv run repowise health --file <path> # did the file you touched get worse?+ uv run repowise health --file <path> --recompute # did the file you touched get worse?```None of this is a gate, and none of it calls an LLM. It is the same signal thereviewer will be looking at, and running it yourself catches the boring problemsdiff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.mdindex b62c49a5e..b13c7095a 100644--- a/docs/architecture/code-health.md+++ b/docs/architecture/code-health.md@@ -251,7 +251,7 @@ The returned report rides on `PipelineResult.health_report`. Thentrend tracking (rolling 50-row window per repo), and a second`{path: total_deduction}` map covering only the files whose score is held atthe floor. Both maps come from `trends.snapshot_file_maps`, which the other two-snapshot writers (`repowise health` and `repowise update --full`) also call; a repo+snapshot writers (`repowise health --recompute` and `repowise update --full`) also call; a repowhose writers disagreed would get a history whose depth changed depending onwhich command last wrote it.diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.mdindex 31fd79c24..453c0bbf6 100644--- a/docs/layers/CODE_HEALTH.md+++ b/docs/layers/CODE_HEALTH.md@@ -15,7 +15,7 @@ bug exists. A low score means "look here first", not "this is broken".```bashrepowise init # full index; scores every file-repowise health # Fix first, KPIs, lowest-scoring files, top findings+repowise health # Fix first, KPIs, lowest-scoring files, top findings (stored)repowise next # the short "Do next" list across every layerrepowise update # re-scores only the files that changed```@@ -278,7 +278,7 @@ held the same way (`needs_design`). See [REFACTORING.md](REFACTORING.md).## Trends, coverage and badges-Every run stores a snapshot (the last 50 per repository) with repository KPIs and+Every `init`, `update` and `health --recompute` stores a snapshot (the last 50 per repository) with repository KPIs andper-file scores. Alerts read them: **declining** (the score fell 0.5 or moreagainst five snapshots back), **predicted decline** (three falls in a row), and**history drag** (either of those, where only the git-history half moved, so there@@ -295,7 +295,7 @@ uncovered.```bashpytest --cov --cov-report=lcov:coverage.lcovrepowise coverage add coverage.lcov-repowise health+repowise health --recompute````repowise health --badge` prints README Markdown: a static shields.io badge for the@@ -388,9 +388,9 @@ How the calibration works: [architecture/code-health.md](../architecture/code-he| `--module PREFIX` | Report only files under this path prefix || `--scope all\|production` | Population to report on (default `all`) || `--counts everything\|code_shape` | Include or drop the history half of the deduction (default `everything`) |-| `--format table\|json\|md` | Output format; `json` and `md` do not write to the index |+| `--format table\|json\|md` | Output format || `--refactoring-targets` | Print the stored refactoring queue |-| `--recompute` | With `--refactoring-targets`: analyze the working tree in-process |+| `--recompute` | Analyze the working tree in-process instead of reading the stored analysis; a whole-repo `table` run writes the result to the index || `--generate-code SELECTOR` | Opt-in: generate code and a diff for one suggestion with the configured LLM (needs an API key) || `--trend` | Print the last 10 snapshots || `--badge` | Print README badge Markdown |diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.mdindex d56694e1d..8d54e0d06 100644--- a/docs/layers/REFACTORING.md+++ b/docs/layers/REFACTORING.md@@ -216,7 +216,7 @@ Most plans answer a health finding, so per-path marker rules in| Flag | Effect ||------|--------|| `--refactoring-targets` | Print the stored refactoring queue in the order MCP and the dashboard serve it. |-| `--recompute` | With `--refactoring-targets`: analyze the working tree in-process. Slow on large repos. |+| `--recompute` | Analyze the working tree in-process instead of reading the index. Slow on large repos. || `--generate-code SELECTOR` | Generate code and a diff for one plan. `SELECTOR` is a 1-based rank or a symbol name. Needs an API key. || `--format json` | Machine-readable output. |diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 374a8d2ec..07cc5b580 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1095,7 +1095,9 @@ evidence that selected it, or why it runs with every subset. When it runs everyt### `repowise health [PATH]`-Compute per-file code-health scores from 51 deterministic detectors (McCabe complexity, nesting, brain methods, LCOM4 cohesion, god classes, native clone detection, untested hotspots, coverage gradient, function/ownership/churn/change-entropy organizational risk, test-quality smells, and more). Zero LLM calls by default, pure Python over tree-sitter + git data. See [`docs/layers/CODE_HEALTH.md`](../layers/CODE_HEALTH.md) for the user guide and [`docs/architecture/code-health.md`](../architecture/code-health.md) for the internals.+Report per-file code-health scores from 51 deterministic detectors (McCabe complexity, nesting, brain methods, LCOM4 cohesion, god classes, native clone detection, untested hotspots, coverage gradient, function/ownership/churn/change-entropy organizational risk, test-quality smells, and more). Zero LLM calls by default, pure Python over tree-sitter + git data. See [`docs/layers/CODE_HEALTH.md`](../layers/CODE_HEALTH.md) for the user guide and [`docs/architecture/code-health.md`](../architecture/code-health.md) for the internals.++By default it reads the analysis the last `repowise init` or `repowise update` stored, the same rows MCP and the web UI serve, and writes nothing. `--recompute` analyzes the working tree in-process instead.**Options:**@@ -1106,7 +1108,7 @@ Compute per-file code-health scores from 51 deterministic detectors (McCabe comp| `--scope` | `all` (default) or `production`. Which files every figure describes. Tests score higher than production code, so narrowing lowers the number without a defect being found. || `--counts` | `everything` (default) or `code_shape`. `code_shape` drops the git-derived half of the deduction, which rises as a file is worked on — the reading that answers whether the code itself is improving. || `--refactoring-targets` | Print the refactoring queue the index stored: one opportunity per file with its structured, graph-aware plans (Extract Class / Helper / Method, Move Method, Split File) as ordered steps and Break Cycle as advisory evidence, in the same order MCP and the web UI serve. Reads the index, so it needs `repowise init` first. See [REFACTORING.md](../layers/REFACTORING.md) |-| `--recompute` | With `--refactoring-targets`: analyze the working tree in-process instead of reading the index. Slow on a large repo; the only option outside an indexed one. `--scope` and `--counts` apply only here. |+| `--recompute` | Analyze the working tree in-process instead of reading the stored analysis. A whole-repo `table` run writes the result back to the index (scores, findings, a trend snapshot); `json`, `md` and `--file`/`--module` runs never write. Slow on a large repo; the only option outside an indexed one. With `--refactoring-targets`, `--scope` and `--counts` apply only here. || `--generate-code <selector>` | Generate an actual refactoring patch for one target. The only `health` flag that calls an LLM; needs a configured provider. || `--trend` | Print the last 10 health snapshots + any active alerts (declining / predicted decline) || `--badge` | Print a shields.io-compatible badge URL/JSON for the repo's health score |@@ -1124,7 +1126,7 @@ repowise health --generate-code packages/server/app.py::handler # LLM patch forepowise health --trend # snapshot history + alertsrepowise health --counts code_shape # ignore the git-derived halfrepowise coverage add coverage.lcov # ingest coverage, then:-repowise health+repowise health --recompute # fold it into the scores now (or wait for the next update)repowise health --format json | jq .kpis # machine-readable```diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-coverage.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-coverage.mdindex faad4ab3d..e3d966a76 100644--- a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-coverage.md+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-coverage.md@@ -57,4 +57,4 @@ repowise coverage check origin/main...HEAD --report coverage/lcov.info --fail-unwhen the report carries per-test contexts — e.g. a coverage.py `.coverage`written with `coverage run --contexts=test`, or a per-test lcov. Reportswithout contexts ingest aggregates only; say so plainly.-- After ingesting, suggest `repowise health` so untested-hotspot markers update.+- After ingesting, suggest `repowise health --recompute` so untested-hotspot markers update.diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-health.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-health.mdindex 5880bd56e..555432f0b 100644--- a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-health.md+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-health.md@@ -17,10 +17,13 @@ hotspots, and more). No LLM — works even in index-only mode.## Modes-Default (no args) — dashboard KPIs + lowest-scoring files:+Default (no args) — dashboard KPIs + lowest-scoring files, read from the stored+analysis (no writes):```repowise health```+After edits, `repowise update` refreshes what it reads; `repowise health --recompute`+analyzes the working tree in-process instead (slow on a large repo).Handle `$ARGUMENTS`:- A file or directory path → `repowise health <path>` (or `--file <path>` for a single file)@@ -32,7 +35,7 @@ Handle `$ARGUMENTS`:having been found; the default stays `all`)- "code shape" / "ignore churn" → `repowise health --counts code_shape` (leavesout the git-derived half: churn, co-change, ownership, prior fixes)-- a coverage file (e.g. `cov.lcov`, `coverage.xml`, `.coverage`) → `repowise coverage add <file>` to ingest it (folds into health markers, and builds the per-test map when the report has contexts), then `repowise health`+- a coverage file (e.g. `cov.lcov`, `coverage.xml`, `.coverage`) → `repowise coverage add <file>` to ingest it (folds into health markers, and builds the per-test map when the report has contexts), then `repowise health --recompute`Other flags: `--format json` for machine-readable output, `-v, --verbose` forpipeline debug logs, `--repo <alias>` / `--no-workspace` in workspace mode.diff --git a/packages/cli/src/repowise/cli/commands/coverage_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_cmd.pyindex f04f83af4..0976c8787 100644--- a/packages/cli/src/repowise/cli/commands/coverage_cmd.py+++ b/packages/cli/src/repowise/cli/commands/coverage_cmd.py@@ -3,8 +3,8 @@The single entry point for coverage. ``coverage add`` populates per-fileline/branch coverage (which clears ``untested_hotspot`` for tested files) and,when a report carries contexts (a coverage.py ``.coverage`` or a per-test-lcov), also builds the per-test "test-to-code" map. ``repowise health`` then-folds in whatever was ingested here - it no longer takes a coverage flag of+lcov), also builds the per-test "test-to-code" map. ``repowise health+--recompute`` (or the next ``repowise update``) then folds in whatever was ingested here - it no longer takes a coverage flag ofits own."""@@ -339,7 +339,7 @@ def coverage_add()return Falseconsole.print(- "Run [cyan]repowise health[/cyan] to fold coverage into the defect "+ "Run [cyan]repowise health --recompute[/cyan] to fold coverage into the defect ""scores, or [cyan]repowise coverage status[/cyan] to review it.")return Truediff --git a/packages/cli/src/repowise/cli/commands/health_cmd/command.py b/packages/cli/src/repowise/cli/commands/health_cmd/command.pyindex adeef7872..767470214 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/command.py@@ -1,14 +1,16 @@"""``repowise health`` Click command + single-repo orchestration.-Mirrors the dead-code CLI: ingest → analyze → render. Reads from-``HealthFileMetric`` / ``HealthFinding`` if a fresh index exists, falls-back to a live in-process analysis when run outside an indexed repo.+Reads the health analysis the last ``init``/``update`` stored, the same rows+MCP and the web UI serve, and writes nothing. ``--recompute`` runs the+analysis in-process instead (ingest, analyze, render) and, for a whole-repo+table, writes it back to the index."""from __future__ import annotationsimport jsonfrom pathlib import Path+from typing import Anyimport clickfrom rich.table import Table@@ -32,7 +34,7 @@ from repowise.core.analysis.health.counts import (project as project_counts,)from repowise.core.analysis.health.models import split_by_origin-from repowise.core.analysis.health.rows import split_unscored+from repowise.core.analysis.health.rows import detail_map, split_unscoredfrom repowise.core.analysis.health.scope import DEFAULT_SCOPE, SCOPES, parse_scopefrom repowise.core.analysis.health.scoring import compute_kpis@@ -41,6 +43,7 @@ from .persist import (_load_fix_first,_load_persisted_coverage_map,_load_recommendations,+ _load_stored_report,_persist_health,)from .refactoring_targets import (@@ -103,8 +106,9 @@ FIX_FIRST_ROWS = 3is_flag=True,default=False,help=(- "With --refactoring-targets: analyze the working tree in-process instead "- "of reading the index. Slow on a large repo; needed outside an indexed one."+ "Analyze the working tree in-process instead of reading the stored "+ "analysis, and write a whole-repo table run back to the index. Slow on a "+ "large repo; needed outside an indexed one."),)@click.option(@@ -179,19 +183,13 @@ def health_command(badge_view: bool,verbose: bool,) -> None:- """Compute code-health scores from markers (CCN, nesting, brain-method).+ """Code-health scores from markers (CCN, nesting, brain-method).- Runs in-process — no LLM, no network. Re-uses the repowise ingestion- parser, graph builder, and git indexer.+ Reads the analysis the index stored; no LLM, no network, no writes.+ ``--recompute`` re-runs it in-process over the working tree."""configure_cli_logging(verbose=verbose)- from pathlib import Path as PathlibPath-- from repowise.core.analysis.communities import file_community_labels- from repowise.core.analysis.health import HealthAnalyzer- from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder-# Silence structlog/stdlib info+debug lines when the user asked for a# machine-readable format so stdout is pure JSON/Markdown and safe to# pipe into jq or other tools (e.g. `repowise health --format json | jq .kpis`).@@ -253,97 +251,20 @@ def health_command()return- # Analyze the same file set that was indexed: a repo initialized with- # --include-submodules persists the flag in state.json, and a flagless- # traverser here would silently score a different (smaller) tree.- state = load_state(repo_path)- include_submodules = bool(state.get("include_submodules", False))- include_nested_repos = bool(state.get("include_nested_repos", False))- # `repowise health` persists metrics into the same rows the indexer writes,- # so it has to analyze the same file set. Without the config's exclude- # patterns it scored — and overwrote rows for — files the index had- # deliberately dropped, and on a repo excluding a manifest directory it- # could write a different `module` than the index did.- exclude_patterns: list[str] = list(load_config(repo_path).get("exclude_patterns") or [])-- traverser = FileTraverser(- repo_path,- include_submodules=include_submodules,- include_nested_repos=include_nested_repos,- extra_exclude_patterns=exclude_patterns or None,- )- file_infos = list(traverser.traverse())- parser = ASTParser()- graph_builder = GraphBuilder(- repo_path,- include_submodules=include_submodules,- include_nested_repos=include_nested_repos,- )-- parsed_files = []- for fi in file_infos:- try:- source = PathlibPath(fi.abs_path).read_bytes()- parsed = parser.parse_file(fi, source)- graph_builder.add_file(parsed)- parsed_files.append(parsed)- except Exception:- continue-- from repowise.core.ingestion import wire_tsconfig_resolver-- wire_tsconfig_resolver(- graph_builder,- repo_path,- include_submodules=include_submodules,- include_nested_repos=include_nested_repos,- )- graph_builder.build()-- git_meta_map: dict = {}- try:- from repowise.core.ingestion.git_indexer import GitIndexer-- git_indexer = GitIndexer(repo_path)- _, metadata_list = run_async(git_indexer.index_repo(""))- git_meta_map = {m["file_path"]: m for m in metadata_list}- except Exception:- pass-- # Coverage folds into scoring from whatever `repowise coverage add` (or- # index-time ingest) persisted - no per-run flag. Ingestion lives solely- # in the `coverage` command group.- coverage_map = _load_persisted_coverage_map(repo_path)-- analyzer = HealthAnalyzer(- graph_builder.graph(),- git_meta_map=git_meta_map,- parsed_files=parsed_files,- community_label_map=file_community_labels(graph_builder),- coverage_map=coverage_map,- duplication_cache_dir=Path(repo_path) / ".repowise",- repo_root=repo_path,- )- # Load any .repowise/health-rules.json the user keeps in the repo.- from repowise.core.analysis.health.config import HealthConfig-- health_cfg = HealthConfig.load(repo_path)- analyzer_cfg = (- health_cfg.to_analyzer_config([pf.file_info.path for pf in parsed_files])- if (health_cfg.disabled_biomarkers or health_cfg.rules)- else None- )- report = analyzer.analyze(analyzer_cfg)-- # Persist health to the repo's wiki.db so the dashboard, MCP tools, and- # `repowise status` see the same numbers as this CLI run.- #- # Skip when fmt != "table" (json/md are read by scripts and CI; side- # effects are unwelcome) or when the run is filtered to a single- # file/module (those are inspection runs that shouldn't overwrite- # repo-level state).- if fmt == "table" and not file_filter and not module_filter:- _persist_health(repo_path, report=report)+ if recompute or generate_code is not None:+ # Written back only for a whole-repo table: json/md are read by scripts+ # and CI, and a file or module run is an inspection, not repo state.+ report, hotspots, languages = _recompute_report(+ repo_path, persist=fmt == "table" and not file_filter and not module_filter+ )+ else:+ stored = _load_stored_report(repo_path)+ if stored is None:+ raise click.ClickException(+ "No stored health analysis for this repository. Run `repowise init` "+ "or `repowise update`, or pass --recompute to analyze in-process."+ )+ report, hotspots, languages = storedmetrics = report.metricsif file_filter:@@ -368,9 +289,7 @@ def health_command(# Every figure the controls select for. Defect accuracy below is not# one of them: it scores the ranking against `prior_defect`, and# narrowing leaves it no labels to be accurate about.- report.kpis = compute_kpis(- metrics, {p for p, m in git_meta_map.items() if m.get("is_hotspot")}- )+ report.kpis = compute_kpis(metrics, hotspots)metrics_sorted = sorted(metrics, key=lambda m: m.score)findings = report.findings@@ -439,7 +358,7 @@ def health_command("file_path": f.file_path,"function_name": f.function_name,"health_impact": f.health_impact,- "details": f.details,+ "details": detail_map(f),"reason": f.reason,}for f in findings@@ -502,12 +421,9 @@ def health_command(_render_defect_accuracy_line(report)# Performance pillar section: lead with the finding COUNT + density +- # coverage (the honest signal), not the bounded /10 average. Language comes- # from the parsed files (the in-memory metrics don't carry it).- _render_performance_section(- report,- {pf.file_info.path: pf.file_info.language for pf in parsed_files},- )+ # coverage (the honest signal), not the bounded /10 average. Metrics carry+ # no language, so it comes with the report from either source.+ _render_performance_section(report, languages)table = Table(title=f"Lowest-scoring files ({min(len(metrics_sorted), 20)})")table.add_column("File", style="cyan")@@ -545,3 +461,85 @@ def health_command(f"-{f.health_impact:.2f}",)console.print(f_table)+++def _recompute_report(repo_path: Path, *, persist: bool) -> tuple[Any, set[str], dict[str, str]]:+ """Analyze the working tree in-process: ``(report, hotspot paths, language by path)``.++ ``persist`` writes the result to the index, as ``init`` would, so the+ dashboard, MCP tools and ``repowise status`` see the same numbers.+ """+ from repowise.core.analysis.communities import file_community_labels+ from repowise.core.analysis.health import HealthAnalyzer+ from repowise.core.analysis.health.config import HealthConfig++ graph_builder, parsed_files = _parse_tree(repo_path)+ git_meta_map: dict = {}+ try:+ from repowise.core.ingestion.git_indexer import GitIndexer++ _, metadata_list = run_async(GitIndexer(repo_path).index_repo(""))+ git_meta_map = {m["file_path"]: m for m in metadata_list}+ except Exception:+ pass++ analyzer = HealthAnalyzer(+ graph_builder.graph(),+ git_meta_map=git_meta_map,+ parsed_files=parsed_files,+ community_label_map=file_community_labels(graph_builder),+ # Coverage folds in from whatever `repowise coverage add` (or index-time+ # ingest) persisted; ingestion lives solely in the `coverage` group.+ coverage_map=_load_persisted_coverage_map(repo_path),+ duplication_cache_dir=Path(repo_path) / ".repowise",+ repo_root=repo_path,+ )+ # Any .repowise/health-rules.json the user keeps in the repo.+ health_cfg = HealthConfig.load(repo_path)+ analyzer_cfg = (+ health_cfg.to_analyzer_config([pf.file_info.path for pf in parsed_files])+ if (health_cfg.disabled_biomarkers or health_cfg.rules)+ else None+ )+ report = analyzer.analyze(analyzer_cfg)+ if persist:+ _persist_health(repo_path, report=report)+ hotspots = {p for p, m in git_meta_map.items() if m.get("is_hotspot")}+ return report, hotspots, {pf.file_info.path: pf.file_info.language for pf in parsed_files}+++def _parse_tree(repo_path: Path) -> tuple[Any, list[Any]]:+ """``(graph builder, parsed files)`` over the file set the index analyzed."""+ from repowise.core.ingestion import (+ ASTParser,+ FileTraverser,+ GraphBuilder,+ wire_tsconfig_resolver,+ )++ # A repo initialized with --include-submodules persists the flag in+ # state.json, and a flagless traverser would score a smaller tree.+ state = load_state(repo_path)+ flags = {+ "include_submodules": bool(state.get("include_submodules", False)),+ "include_nested_repos": bool(state.get("include_nested_repos", False)),+ }+ # `--recompute` persists into the rows the indexer writes, so it has to+ # analyze the same file set. Without the config's exclude patterns it+ # scored, and overwrote rows for, files the index had dropped, and on a+ # repo excluding a manifest directory it could write a different `module`.+ exclude_patterns: list[str] = list(load_config(repo_path).get("exclude_patterns") or [])+ traverser = FileTraverser(repo_path, **flags, extra_exclude_patterns=exclude_patterns or None)+ parser = ASTParser()+ graph_builder = GraphBuilder(repo_path, **flags)+ parsed_files = []+ for fi in traverser.traverse():+ try:+ parsed = parser.parse_file(fi, Path(fi.abs_path).read_bytes())+ graph_builder.add_file(parsed)+ parsed_files.append(parsed)+ except Exception:+ continue+ wire_tsconfig_resolver(graph_builder, repo_path, **flags)+ graph_builder.build()+ return graph_builder, parsed_filesdiff --git a/packages/cli/src/repowise/cli/commands/health_cmd/persist.py b/packages/cli/src/repowise/cli/commands/health_cmd/persist.pyindex 22d47fa7f..9774d5920 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/persist.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/persist.py@@ -9,6 +9,7 @@ from __future__ import annotationsfrom collections.abc import Sequencefrom pathlib import Path+from types import SimpleNamespacefrom typing import Anyfrom repowise.cli.helpers import console, run_async@@ -57,21 +58,15 @@ def _load_fix_first(repo_path: object, *, limit: int) -> Any:Best-effort like the coverage read: a missing repo row or an older storeleaves the report without the section; the report itself still prints."""- from repowise.cli.helpers import get_db_url_for_repo, reconcile_schema_best_effort- from repowise.core.persistence import create_engine, create_session_factory, get_session- from repowise.core.persistence.crud import get_repository_by_path+ from repowise.cli.helpers import repo_index_sessionfrom repowise.core.persistence.crud.analysis.fix_first import load_fix_firstasync def _do() -> Any:- url = get_db_url_for_repo(repo_path)- await reconcile_schema_best_effort(url)- engine = create_engine(url)- sf = create_session_factory(engine)- async with get_session(sf) as session:- repo = await get_repository_by_path(session, str(repo_path))- if repo is None:+ async with repo_index_session(Path(str(repo_path))) as opened:+ if opened is None:return None- return await load_fix_first(session, repo.id, limit=limit)+ session, repo_id = opened+ return await load_fix_first(session, repo_id, limit=limit)try:return run_async(_do())@@ -79,6 +74,53 @@ def _load_fix_first(repo_path: object, *, limit: int) -> Any:return None+def _load_stored_report(repo_path: object) -> tuple[Any, set[str], dict[str, str]] | None:+ """The health analysis the last ``init``/``update`` stored, read without writing.++ ``(report, hotspot paths, language by path)``, where the report carries the+ stored metrics and open findings and the KPIs computed over them as the+ indexer computes its snapshot. ``None`` when no store or no analysis opens;+ a store an older repowise wrote raises ``StaleIndexError`` from the session.++ Not ``crud.get_health_summary``: that is the API's summary (open-finding+ counts, perf coverage) and carries no hotspot, production or worst-test+ figure, while the report renders ``compute_kpis``'s, the figures the trend+ snapshot stores. The rows are read once and serve both the KPIs and the+ defect-accuracy line.+ """+ import click+ from sqlalchemy.exc import SQLAlchemyError++ from repowise.cli.helpers import repo_index_session+ from repowise.core.analysis.health.scoring import compute_kpis+ from repowise.core.persistence.crud import (+ get_file_language_map,+ get_health_findings,+ get_health_metrics,+ get_hotspot_file_paths,+ )++ async def _do() -> tuple[Any, set[str], dict[str, str]] | None:+ async with repo_index_session(Path(str(repo_path))) as opened:+ if opened is None:+ return None+ session, repo_id = opened+ metrics = await get_health_metrics(session, repo_id)+ if not metrics:+ return None+ findings = await get_health_findings(session, repo_id)+ hotspots = await get_hotspot_file_paths(session, repo_id)+ languages = await get_file_language_map(session, repo_id)+ kpis = compute_kpis(metrics, hotspots)+ return SimpleNamespace(metrics=metrics, findings=findings, kpis=kpis), hotspots, languages++ try:+ return run_async(_do())+ except SQLAlchemyError as exc:+ # Locked or damaged: not the same answer as "nothing stored".+ raise click.ClickException(f"Could not read the stored health analysis: {exc}") from exc++def _load_recommendations(repo_path: Path, suggestions: Sequence[Any], metrics: Sequence[Any]) -> list[dict[str, Any]]:diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/summary.py b/packages/cli/src/repowise/cli/commands/health_cmd/summary.pyindex 428ff4dd8..96f95e85a 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/summary.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/summary.py@@ -127,7 +127,7 @@ def _render_badge(average_health: object) -> None:from repowise.core.analysis.health.grading import BAND_BADGE_COLOR, band_for, format_scoreif not isinstance(average_health, (int, float)):- console.print("[yellow]No health score yet — run `repowise health` first.[/yellow]")+ console.print("[yellow]No health score yet — run `repowise init` first.[/yellow]")returncolor = BAND_BADGE_COLOR[band_for(float(average_health))]msg = f"{format_score(float(average_health))}/10"diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/trends.py b/packages/cli/src/repowise/cli/commands/health_cmd/trends.pyindex 10f08110e..8860d02a3 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/trends.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/trends.py@@ -52,8 +52,8 @@ def _render_trend(repo_path: object, *, fmt: str) -> None:rows, summary = run_async(_fetch())if not rows:console.print(- "[yellow]No health snapshots yet. Run `repowise init` or `repowise health` "- "to populate history.[/yellow]"+ "[yellow]No health snapshots yet. Run `repowise init` or `repowise health "+ "--recompute` to populate history.[/yellow]")returndiff --git a/plugins/claude-code/commands/coverage.md b/plugins/claude-code/commands/coverage.mdindex b94f005d7..3fc767cd2 100644--- a/plugins/claude-code/commands/coverage.md+++ b/plugins/claude-code/commands/coverage.md@@ -58,4 +58,4 @@ repowise coverage check origin/main...HEAD --report coverage/lcov.info --fail-unwhen the report carries per-test contexts — e.g. a coverage.py `.coverage`written with `coverage run --contexts=test`, or a per-test lcov. Reportswithout contexts ingest aggregates only; say so plainly.-- After ingesting, suggest `repowise health` so untested-hotspot markers update.+- After ingesting, suggest `repowise health --recompute` so untested-hotspot markers update.diff --git a/plugins/claude-code/commands/health.md b/plugins/claude-code/commands/health.mdindex cf59c7d96..8a793cc4a 100644--- a/plugins/claude-code/commands/health.md+++ b/plugins/claude-code/commands/health.md@@ -18,10 +18,13 @@ hotspots, and more). No LLM — works even in index-only mode.## Modes-Default (no args) — dashboard KPIs + lowest-scoring files:+Default (no args) — dashboard KPIs + lowest-scoring files, read from the stored+analysis (no writes):```repowise health```+After edits, `repowise update` refreshes what it reads; `repowise health --recompute`+analyzes the working tree in-process instead (slow on a large repo).Handle `$ARGUMENTS`:- A file or directory path → `repowise health <path>` (or `--file <path>` for a single file)@@ -33,7 +36,7 @@ Handle `$ARGUMENTS`:having been found; the default stays `all`)- "code shape" / "ignore churn" → `repowise health --counts code_shape` (leavesout the git-derived half: churn, co-change, ownership, prior fixes)-- a coverage file (e.g. `cov.lcov`, `coverage.xml`, `.coverage`) → `repowise coverage add <file>` to ingest it (folds into health markers, and builds the per-test map when the report has contexts), then `repowise health`+- a coverage file (e.g. `cov.lcov`, `coverage.xml`, `.coverage`) → `repowise coverage add <file>` to ingest it (folds into health markers, and builds the per-test map when the report has contexts), then `repowise health --recompute`Other flags: `--format json` for machine-readable output, `-v, --verbose` forpipeline debug logs, `--repo <alias>` / `--no-workspace` in workspace mode.diff --git a/plugins/claude-code/skills/code-health/SKILL.md b/plugins/claude-code/skills/code-health/SKILL.mdindex 0ed8bcba0..9d86fb3b4 100644--- a/plugins/claude-code/skills/code-health/SKILL.md+++ b/plugins/claude-code/skills/code-health/SKILL.md@@ -51,7 +51,7 @@ not just *bigger*.6. Untested-hotspot / coverage questions → tell the user coverage markerslight up once they ingest a report: `repowise coverage add cov.lcov`(LCOV / Cobertura / Clover; a coverage.py `.coverage` also builds the- per-test map), then re-run `repowise health`.+ per-test map), then `repowise health --recompute` to fold it into the scores.## CLI equivalentsdiff --git a/plugins/codex/skills/code-health/SKILL.md b/plugins/codex/skills/code-health/SKILL.mdindex b5e97b224..8ba137b86 100644--- a/plugins/codex/skills/code-health/SKILL.md+++ b/plugins/codex/skills/code-health/SKILL.md@@ -46,7 +46,7 @@ not just *bigger*.6. Untested-hotspot / coverage questions → tell the user coverage markerslight up once they ingest a report: `repowise coverage add cov.lcov`(LCOV / Cobertura / Clover; a coverage.py `.coverage` also builds the- per-test map), then re-run `repowise health`.+ per-test map), then `repowise health --recompute` to fold it into the scores.## CLI equivalentsdiff --git a/plugins/shared/commands/coverage.md b/plugins/shared/commands/coverage.mdindex d4994326b..3db34a302 100644--- a/plugins/shared/commands/coverage.md+++ b/plugins/shared/commands/coverage.md@@ -59,4 +59,4 @@ repowise coverage check origin/main...HEAD --report coverage/lcov.info --fail-unwhen the report carries per-test contexts — e.g. a coverage.py `.coverage`written with `coverage run --contexts=test`, or a per-test lcov. Reportswithout contexts ingest aggregates only; say so plainly.-- After ingesting, suggest `repowise health` so untested-hotspot markers update.+- After ingesting, suggest `repowise health --recompute` so untested-hotspot markers update.diff --git a/plugins/shared/commands/health.md b/plugins/shared/commands/health.mdindex f61421dbc..1ca755093 100644--- a/plugins/shared/commands/health.md+++ b/plugins/shared/commands/health.md@@ -19,10 +19,13 @@ hotspots, and more). No LLM — works even in index-only mode.## Modes-Default (no args) — dashboard KPIs + lowest-scoring files:+Default (no args) — dashboard KPIs + lowest-scoring files, read from the stored+analysis (no writes):```repowise health```+After edits, `repowise update` refreshes what it reads; `repowise health --recompute`+analyzes the working tree in-process instead (slow on a large repo).Handle `$ARGUMENTS`:- A file or directory path → `repowise health <path>` (or `--file <path>` for a single file)@@ -34,7 +37,7 @@ Handle `$ARGUMENTS`:having been found; the default stays `all`)- "code shape" / "ignore churn" → `repowise health --counts code_shape` (leavesout the git-derived half: churn, co-change, ownership, prior fixes)-- a coverage file (e.g. `cov.lcov`, `coverage.xml`, `.coverage`) → `repowise coverage add <file>` to ingest it (folds into health markers, and builds the per-test map when the report has contexts), then `repowise health`+- a coverage file (e.g. `cov.lcov`, `coverage.xml`, `.coverage`) → `repowise coverage add <file>` to ingest it (folds into health markers, and builds the per-test map when the report has contexts), then `repowise health --recompute`Other flags: `--format json` for machine-readable output, `-v, --verbose` forpipeline debug logs, `--repo <alias>` / `--no-workspace` in workspace mode.diff --git a/plugins/shared/skills/code-health.md b/plugins/shared/skills/code-health.mdindex eb3d61f27..ca7dc600c 100644--- a/plugins/shared/skills/code-health.md+++ b/plugins/shared/skills/code-health.md@@ -59,7 +59,7 @@ not just *bigger*.6. Untested-hotspot / coverage questions → tell the user coverage markerslight up once they ingest a report: `repowise coverage add cov.lcov`(LCOV / Cobertura / Clover; a coverage.py `.coverage` also builds the- per-test map), then re-run `repowise health`.+ per-test map), then `repowise health --recompute` to fold it into the scores.## CLI equivalentsdiff --git a/tests/unit/cli/test_analysis_cmds_include_submodules.py b/tests/unit/cli/test_analysis_cmds_include_submodules.pyindex bb9ba558a..81431e892 100644--- a/tests/unit/cli/test_analysis_cmds_include_submodules.py+++ b/tests/unit/cli/test_analysis_cmds_include_submodules.py@@ -49,7 +49,7 @@ def _init_repo_with_initialized_submodule(tmp_path, *, state: dict | None = Nonedef _health_metric_paths(tmp_path) -> set[str]:result = CliRunner().invoke(- health_command, [str(tmp_path), "--format", "json", "--no-workspace"]+ health_command, [str(tmp_path), "--format", "json", "--no-workspace", "--recompute"])assert result.exit_code == 0, result.outputpayload = json.loads(result.output[result.output.index("{") :])diff --git a/tests/unit/cli/test_health_cmd_exclusions.py b/tests/unit/cli/test_health_cmd_exclusions.pyindex ff9ac7999..d2afad387 100644--- a/tests/unit/cli/test_health_cmd_exclusions.py+++ b/tests/unit/cli/test_health_cmd_exclusions.py@@ -44,7 +44,7 @@ def _invoke(monkeypatch: pytest.MonkeyPatch, tmp_path, config: dict) -> dict:monkeypatch.setattr(health_cmd, "load_state", lambda _p: {})monkeypatch.setattr(health_cmd, "load_config", lambda _p: config)- result = CliRunner().invoke(cli, ["health", str(tmp_path)])+ result = CliRunner().invoke(cli, ["health", str(tmp_path), "--recompute"])assert isinstance(result.exception, _StopHere), result.outputreturn seen@@ -72,7 +72,7 @@ def test_the_state_flags_still_reach_it(monkeypatch, tmp_path) -> None:)monkeypatch.setattr(health_cmd, "load_config", lambda _p: {"exclude_patterns": ["x/**"]})- result = CliRunner().invoke(cli, ["health", str(tmp_path)])+ result = CliRunner().invoke(cli, ["health", str(tmp_path), "--recompute"])assert isinstance(result.exception, _StopHere), result.outputassert seen == {diff --git a/tests/unit/cli/test_health_stored_default.py b/tests/unit/cli/test_health_stored_default.pynew file mode 100644index 000000000..aedf5643e--- /dev/null+++ b/tests/unit/cli/test_health_stored_default.py@@ -0,0 +1,156 @@+"""Bare `repowise health` reads the stored analysis and writes nothing.++The in-process recompute parsed and analyzed the whole tree (minutes on a+large repository) and wrote its result back to the index. The default now+reads the rows the last `init`/`update` stored, as MCP and the web UI do;+`--recompute` keeps the in-process path.+"""++from __future__ import annotations++import json+import subprocess+from pathlib import Path+from typing import Any++import pytest+from click.testing import CliRunner++from repowise.cli.commands.health_cmd import command as health_cmd+from repowise.cli.commands.health_cmd import health_command+from repowise.cli.helpers import run_async++_PATHS = ("pkg/a.py", "pkg/b.py", "tests/test_a.py")+++async def _store(repo_path: Path) -> None:+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ crud,+ get_session,+ init_db,+ upsert_repository,+ )++ engine = create_engine(f"sqlite+aiosqlite:///{(repo_path / '.repowise' / 'wiki.db').as_posix()}")+ try:+ await init_db(engine)+ async with get_session(create_session_factory(engine)) as session:+ repo = await upsert_repository(session, name="repo", local_path=str(repo_path))+ await crud.save_health_metrics(+ session,+ repo.id,+ [+ {"file_path": p, "score": 4.0 + i, "nloc": 100, "max_ccn": 12,+ "is_test": p.startswith("tests/")}+ for i, p in enumerate(_PATHS)+ ],+ )+ await crud.save_health_findings(+ session,+ repo.id,+ [+ {"file_path": "pkg/a.py", "biomarker_type": "complex_method",+ "severity": "high", "function_name": "f", "line_start": 1, "line_end": 40,+ "details": {"ccn": 16}, "health_impact": 2.0, "reason": "seeded",+ "dimension": "defect"}+ ],+ )+ await session.commit()+ finally:+ await engine.dispose()+++def repo(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)+ monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)+ root = tmp_path.resolve()+ subprocess.run(["git", "init", "-q"], cwd=root, check=True)+ (root / ".repowise").mkdir()+ return root+++def _read_only(monkeypatch: pytest.MonkeyPatch) -> None:+ """Fail the test if the command walks the tree or writes to the index."""+ import repowise.core.ingestion as ingestion+ from repowise.cli import helpers++ def boom(*_args: Any, **_kwargs: Any) -> None:+ raise AssertionError("the stored read must not traverse, reconcile or persist")++ monkeypatch.setattr(ingestion, "FileTraverser", boom)+ monkeypatch.setattr(helpers, "reconcile_schema_best_effort", boom)+ monkeypatch.setattr(health_cmd, "_persist_health", boom)+++def test_json_reports_the_stored_rows(repo, monkeypatch):+ run_async(_store(repo))+ _read_only(monkeypatch)++ result = CliRunner().invoke(health_command, [str(repo), "--format", "json", "--no-workspace"])++ assert result.exit_code == 0, result.output+ out = json.loads(result.output[result.output.index("{") :])+ assert {m["file_path"] for m in out["metrics"]} == set(_PATHS)+ assert out["kpis"]["file_count"] == len(_PATHS)+ assert [(f["file_path"], f["details"]) for f in out["findings"]] == [+ ("pkg/a.py", {"ccn": 16})+ ]+++def test_the_table_reads_without_writing(repo, monkeypatch):+ run_async(_store(repo))+ _read_only(monkeypatch)++ result = CliRunner().invoke(health_command, [str(repo), "--no-workspace", "--scope", "production"])++ assert result.exit_code == 0, result.output+ assert "Lowest-scoring files (2)" in result.output+ assert "tests/test_a.py" not in result.output+++def test_no_stored_analysis_names_both_ways_forward(repo, monkeypatch):+ _read_only(monkeypatch)++ result = CliRunner().invoke(health_command, [str(repo), "--no-workspace"])++ assert result.exit_code != 0+ assert "--recompute" in result.output+++def test_the_table_scores_the_stored_rows_for_defect_accuracy(repo, monkeypatch):+ """The "does the score find the bugs?" line reads the same stored rows."""+ run_async(_store(repo))+ _read_only(monkeypatch)+ seen: list = []+ monkeypatch.setattr(health_cmd, "_render_defect_accuracy_line", seen.append)++ result = CliRunner().invoke(health_command, [str(repo), "--no-workspace"])++ assert result.exit_code == 0, result.output+ (report,) = seen+ assert {m.file_path for m in report.metrics} == set(_PATHS)+ assert [f.file_path for f in report.findings] == ["pkg/a.py"]+++def test_a_store_an_older_version_wrote_says_so(repo, monkeypatch):+ """Not "no stored analysis": the analysis is there, this version cannot read it."""+ import sqlite3++ from repowise.cli import helpers++ run_async(_store(repo))+ with sqlite3.connect(repo / ".repowise" / "wiki.db") as conn:+ conn.execute("ALTER TABLE health_file_metrics DROP COLUMN analyzed_commit")++ async def cannot_repair(_url: str) -> None:+ return None++ monkeypatch.setattr(helpers, "reconcile_schema_best_effort", cannot_repair)+ result = CliRunner().invoke(health_command, [str(repo), "--no-workspace"])++ assert result.exit_code != 0+ assert "older version" in result.output and "repowise update" in result.output+ assert "No stored health analysis" not in result.output