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
fix(cli): read the stored refactoring queue for health --refactoring-targets (#2813)
Raghav Chamadiyaeec1346a7495
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 2b93363ed..00d8c06bc 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1091,7 +1091,8 @@ Compute per-file code-health scores from 51 deterministic detectors (McCabe comp| `--module <prefix>` | Restrict the report to files whose path starts with this prefix || `--scope` | `all` (default) or `production`. Which files every figure describes. Tests score higher than production code, so narrowing lowers the number without a defect being found. || `--counts` | `everything` (default) or `code_shape`. `code_shape` drops the git-derived half of the deduction, which rises as a file is worked on — the reading that answers whether the code itself is improving. |-| `--refactoring-targets` | Print structured, graph-aware refactoring plans (Extract Class / Helper / Move Method / Break Cycle), ranked `impact × centrality × blast radius`. See [REFACTORING.md](../layers/REFACTORING.md) |+| `--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, Break Cycle, Split File) as ordered steps, 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. || `--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 |@@ -1104,7 +1105,7 @@ Compute per-file code-health scores from 51 deterministic detectors (McCabe comprepowise health # KPIs + lowest-scoring filesrepowise health --file packages/server/.../app.py # one file in detailrepowise health --module packages/server # restrict to a directory-repowise health --refactoring-targets # ranked by impact / effort+repowise health --refactoring-targets # the stored queue, as MCP serves itrepowise health --generate-code packages/server/app.py::handler # LLM patch for one targetrepowise health --trend # snapshot history + alertsrepowise health --counts code_shape # ignore the git-derived halfdiff --git a/packages/cli/src/repowise/cli/commands/health_cmd/command.py b/packages/cli/src/repowise/cli/commands/health_cmd/command.pyindex c9e4b43eb..8ae5a0b47 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/command.py@@ -37,7 +37,10 @@ from repowise.core.analysis.health.scoring import compute_kpisfrom .codegen import _generate_refactoring_codefrom .persist import _load_persisted_coverage_map, _load_recommendations, _persist_health-from .refactoring_targets import _render_refactoring_targets+from .refactoring_targets import (+ _render_refactoring_targets,+ _render_stored_refactoring_targets,+)from .summary import (_render_badge,_render_defect_accuracy_line,@@ -80,7 +83,19 @@ from .trends import _render_trend"refactoring_targets",is_flag=True,default=False,- help="Print top refactoring candidates (impact/effort ratio).",+ help=(+ "Print the refactoring queue the index stored, in the order MCP and the "+ "web UI serve it."+ ),+)+ "--recompute",+ is_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."+ ),)@click.option("--generate-code",@@ -145,6 +160,7 @@ def health_command(repo_alias: str | None,no_workspace: bool,refactoring_targets: bool,+ recompute: bool,generate_code: str | None,module_filter: str | None,scope: str,@@ -210,6 +226,22 @@ def health_command(_render_trend(repo_path, fmt=fmt)return+ if refactoring_targets and not recompute and generate_code is None:+ # The stored queue is the calibrated reading, as on MCP and the web UI.+ if parse_scope(scope) != DEFAULT_SCOPE or parse_counts(counts) != DEFAULT_COUNTS:+ status.print(+ "[dim]The stored queue does not take --scope or --counts; pass "+ "--recompute to apply them.[/dim]"+ )+ if not _render_stored_refactoring_targets(+ repo_path, fmt=fmt, file_filter=file_filter, module_filter=module_filter+ ):+ raise click.ClickException(+ "No stored refactoring analysis for this repository. Run `repowise init` "+ "or `repowise update`, or pass --recompute to analyze in-process."+ )+ 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.diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py b/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.pyindex 6f0cd57d9..4f82f7074 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py@@ -1,14 +1,20 @@"""Refactoring-target aggregation and per-refactoring-type plan renderers.-Ranks findings per file by impact/effort, then prints the concrete-structured plans (Extract Class/Helper/Method, Move Method, Break Cycle,-Split File) for both console and Markdown output.+Ranks findings per file by impact/effort, then prints the composed+opportunities with their concrete structured plans (Extract Class/Helper/+Method, Move Method, Break Cycle, Split File) for console, Markdown and JSON.++Two sources feed one set of renderers. The default reads what the index+stored, in the queue order MCP and the web UI serve. ``--recompute`` folds a+fresh in-process analysis instead, which is the only option outside an+indexed repository."""from __future__ import annotationsimport jsonfrom collections.abc import Mapping+from pathlib import Pathfrom typing import Any, castimport click@@ -53,6 +59,157 @@ def _render_refactoring_targets((JSON/MD) and printed as a group tree below the table."""suggestions = suggestions or []+ targets = _build_targets(metrics, findings, suggestions, limit=limit)++ # Structured plans are displayed independently of the impact/effort file+ # table (a god class worth splitting may not top that churn-weighted list).+ # The order is the canonical recommendation rank (benefit and leverage,+ # discounted by cost and risk), so preserve it rather than re-sorting.+ if suggestions and not all(+ isinstance(s, dict) and "benefit" in s and "validation" in s for s in suggestions+ ):+ from repowise.core.analysis.health.refactoring.recommendations import (+ build_recommendations,+ serialize_recommendations,+ )++ ranked_plans = serialize_recommendations(build_recommendations(suggestions))[:limit]+ else:+ ranked_plans = [_suggestion_to_dict(s) for s in suggestions][:limit]++ # The composed unit. One opportunity per file, ranked, with its plans as+ # ordered steps - the same vocabulary the board, the drawer and the agent+ # contract speak. The type-grouped dump this replaced made type the+ # organizing principle, so a file needing a split and two extractions+ # appeared three times in three sections.+ opportunities, _leads = _compose(findings, suggestions)+ plan_by_id = _plans_by_public_id(suggestions, ranked_plans)+ claimed = {s.plan_id for o in opportunities for s in o.steps} | {+ e.plan_id for o in opportunities for e in o.evidence+ }+ unattached = [row for pid, row in plan_by_id.items() if pid not in claimed]+ rows = [_opportunity_row(o) for o in opportunities]++ _emit(+ targets,+ rows,+ plan_by_id,+ fmt=fmt,+ unattached=unattached,+ json_payload={+ "targets": targets,+ "refactoring_opportunities": rows,+ "refactoring_plans": ranked_plans,+ },+ )+++def _render_stored_refactoring_targets(+ repo_path: Path,+ *,+ fmt: str,+ limit: int = 20,+ file_filter: str | None = None,+ module_filter: str | None = None,+) -> bool:+ """Render from what the index stored. False when nothing is stored.++ Reads the same service MCP and the web UI read, in its default+ (diversified) queue order, so the three surfaces list the same work in the+ same order. Nothing is parsed or analyzed: the opportunities, their plans+ and the file table all come from rows the last ``init`` or ``update``+ wrote.+ """+ from repowise.cli.helpers import repo_index_session, run_async+ from repowise.core.analysis.health.scoring import ZERO_IMPACT_DIMENSIONS+ from repowise.core.persistence import crud+ from repowise.server.services.refactoring_health import (+ RefactoringHealthService,+ parse_query,+ )++ def keep(path: str) -> bool:+ if file_filter and path != file_filter:+ return False+ return not (module_filter and not path.startswith(module_filter))++ async def _read() -> dict[str, Any] | None:+ async with repo_index_session(Path(repo_path)) as opened:+ if opened is None:+ return None+ session, repo_id = opened+ service = RefactoringHealthService(session, repo_id, Path(repo_path).name)+ summary = await service.summary()+ if summary.get("status") != "available":+ return None+ query, _ignored = parse_query(+ file_paths=[file_filter] if file_filter else None,+ path_prefix=module_filter,+ limit=limit,+ )+ page = await service.page(query)+ details = [+ await service.detail(item["opportunity_id"], step_limit=200, evidence_limit=50)+ for item in page.items+ ]+ metrics = [+ m for m in await crud.get_health_metrics(session, repo_id) if keep(m.file_path)+ ]+ findings = [+ f+ for f in await crud.get_health_findings(+ session, repo_id, exclude_dimensions=tuple(sorted(ZERO_IMPACT_DIMENSIONS))+ )+ if keep(f.file_path)+ ]+ return {+ "summary": summary,+ "total": page.total,+ "details": details,+ "metrics": metrics,+ "findings": findings,+ }++ stored = run_async(_read())+ if stored is None:+ return False++ rows = [_stored_row(d) for d in stored["details"]]+ plans = [plan for d in stored["details"] for plan in d.get("plans") or []]+ plan_by_id = {plan["id"]: plan for plan in plans if plan.get("id")}+ targets = _build_targets(stored["metrics"], stored["findings"], plans, limit=limit)+ analyzed_commit = stored["summary"].get("analyzed_commit")+ if fmt == "table":+ commit = f" at {analyzed_commit[:7]}" if analyzed_commit else ""+ console.print(+ f"[dim]Read from the index{commit}. Showing {len(rows)} of "+ f"{stored['total']} open opportunities. Pass --recompute to analyze the "+ "working tree instead.[/dim]"+ )+ _emit(+ targets,+ rows,+ plan_by_id,+ fmt=fmt,+ # The queue lists what opportunities claim; unattached clones are not+ # in it, on any surface.+ unattached=[],+ json_payload={+ "source": "index",+ "analyzed_commit": analyzed_commit,+ "opportunities_total": stored["total"],+ "targets": targets,+ "refactoring_opportunities": rows,+ "refactoring_plans": plans,+ },+ )+ return True+++def _build_targets(+ metrics: list, findings: list, suggestions: list, *, limit: int+) -> list[dict]:+ """Files ranked by impact over effort, each carrying its plans."""sugg_by_file: dict[str, list] = {}for s in suggestions:sugg_by_file.setdefault(_suggestion_path(s), []).append(s)@@ -91,49 +248,21 @@ def _render_refactoring_targets(})targets.sort(key=lambda t: (-t["impact_per_effort"], -t["total_impact"]))- targets = targets[:limit]-- # Structured plans are displayed independently of the impact/effort file- # table (a god class worth splitting may not top that churn-weighted list).- # The order is the canonical recommendation rank (benefit and leverage,- # discounted by cost and risk), so preserve it rather than re-sorting.- if suggestions and not all(- isinstance(s, dict) and "benefit" in s and "validation" in s for s in suggestions- ):- from repowise.core.analysis.health.refactoring.recommendations import (- build_recommendations,- serialize_recommendations,- )+ return targets[:limit]- ranked_plans = serialize_recommendations(build_recommendations(suggestions))[:limit]- else:- ranked_plans = [_suggestion_to_dict(s) for s in suggestions][:limit]-- # The composed unit. One opportunity per file, ranked, with its plans as- # ordered steps - the same vocabulary the board, the drawer and the agent- # contract speak. The type-grouped dump this replaced made type the- # organizing principle, so a file needing a split and two extractions- # appeared three times in three sections.- opportunities, _leads = _compose(findings, suggestions)- plan_by_id = _plans_by_public_id(suggestions, ranked_plans)- claimed = {s.plan_id for o in opportunities for s in o.steps} | {- e.plan_id for o in opportunities for e in o.evidence- }- unattached = [row for pid, row in plan_by_id.items() if pid not in claimed]+def _emit(+ targets: list[dict],+ opportunities: list[dict],+ plan_by_id: dict[str, dict],+ *,+ fmt: str,+ unattached: list[dict],+ json_payload: dict[str, Any],+) -> None:+ """Print one report, whichever source built it."""if fmt == "json":- click.echo(- json.dumps(- {- "targets": targets,- "refactoring_opportunities": [- _opportunity_row(o) for o in opportunities- ],- "refactoring_plans": ranked_plans,- },- indent=2,- )- )+ click.echo(json.dumps(json_payload, indent=2))returnif fmt == "md":click.echo("# Refactoring targets\n")@@ -217,6 +346,9 @@ def _opportunity_row(o) -> dict:"""The wire shape, matching the server's queue row field for field."""return {"opportunity_id": o.opportunity_id,+ # Freshly composed, so no triage has touched it yet: the same state the+ # stored queue lists by default.+ "status": "open","file_path": o.file_path,"lead_biomarker": o.lead_biomarker,"lead_refactoring_type": o.lead_refactoring_type,@@ -264,79 +396,125 @@ def _primary_word(value) -> str:return "no dominant problem recorded"-def _render_opportunities_console(opportunities: list, plan_by_id: dict) -> None:+def _stored_row(detail: dict[str, Any]) -> dict[str, Any]:+ """A stored opportunity detail, flattened to the wire row the renderers read."""+ row = {key: detail.get(key) for key in _ROW_KEYS}+ steps = []+ for s in detail.get("steps") or []:+ applicability = s.get("applicability") or {}+ steps.append(+ {+ "plan_id": s.get("plan_id"),+ "refactoring_type": s.get("refactoring_type"),+ "target_symbol": s.get("target_symbol"),+ "file_path": s.get("file_path"),+ "line_start": s.get("line_start"),+ "line_end": s.get("line_end"),+ "classification": applicability.get("classification"),+ "reasons": list(applicability.get("reasons") or []),+ "unknowns": list(applicability.get("unknowns") or []),+ "relocated_by": s.get("relocated_by"),+ }+ )+ row["steps"] = steps+ row["evidence"] = [+ {+ "plan_id": e.get("plan_id"),+ "refactoring_type": e.get("refactoring_type"),+ "target_symbol": e.get("target_symbol"),+ }+ for e in detail.get("evidence") or []+ ]+ return row+++_ROW_KEYS = (+ "opportunity_id",+ "status",+ "file_path",+ "lead_biomarker",+ "lead_refactoring_type",+ "addresses_primary_problem",+ "effort_bucket",+ "confidence",+ "step_count",+ "mechanical_steps",+ "recoverable_health",+ "rank_score",+)+++def _render_opportunities_console(opportunities: list[dict], plan_by_id: dict) -> None:if not opportunities:returnconsole.print(f"\n[bold]Refactoring opportunities ({len(opportunities)})[/bold]")console.print(- "[dim]One per file, in rank order. Steps are in dependency-safe order.[/dim]"+ "[dim]One per file. Steps are in dependency-safe order.[/dim]")for rank, o in enumerate(opportunities, 1):- mech = sum(1 for s in o.steps if s.applicability.classification == "mechanical")console.print(- f"\n[bold]{rank}.[/bold] [cyan]{o.file_path}[/cyan] [dim]-[/dim] "- f"{len(o.steps)} step(s), {mech} mechanical "- f"[dim](effort {o.effort_bucket}, {o.confidence} confidence, "- f"recover ~{o.recoverable_health:.2f}, "- f"{_primary_word(o.addresses_primary_problem)})[/dim]"+ f"\n[bold]{rank}.[/bold] [cyan]{o['file_path']}[/cyan] [dim]-[/dim] "+ f"{o['step_count']} step(s), {o['mechanical_steps']} mechanical "+ f"[dim](effort {o['effort_bucket']}, {o['confidence']} confidence, "+ f"recover ~{o['recoverable_health']:.2f}, "+ f"{_primary_word(o['addresses_primary_problem'])})[/dim]")- for i, s in enumerate(o.steps, 1):- mark = "mechanical" if s.applicability.classification == "mechanical" else "judgment"- span = f":{s.line_start}-{s.line_end}" if s.line_start else ""+ for i, s in enumerate(o["steps"], 1):+ mark = "mechanical" if s["classification"] == "mechanical" else "judgment"+ span = f":{s['line_start']}-{s['line_end']}" if s["line_start"] else ""console.print(- f" [bold]{i}.[/bold] {s.refactoring_type} [green]{s.target_symbol}[/green] "- f"[dim]{s.file_path}{span}[/dim] [dim]({mark})[/dim]"+ f" [bold]{i}.[/bold] {s['refactoring_type']} "+ f"[green]{s['target_symbol']}[/green] "+ f"[dim]{s['file_path']}{span}[/dim] [dim]({mark})[/dim]")- if s.relocated_by:+ if s["relocated_by"]:# The step's own path and span describe where the symbol was.console.print(" [yellow]moved by an earlier step - locate it again ""before applying[/yellow]")- for line in _plan_detail_console(plan_by_id.get(s.plan_id, {})):+ for line in _plan_detail_console(plan_by_id.get(s["plan_id"], {})):console.print(line)- if s.applicability.unknowns:- console.print(- f" [dim]not established: {', '.join(s.applicability.unknowns)}[/dim]"- )- for e in o.evidence:+ if s["unknowns"]:+ console.print(f" [dim]not established: {', '.join(s['unknowns'])}[/dim]")+ for e in o["evidence"]:console.print(- f" [dim]evidence:[/dim] {e.refactoring_type} {e.target_symbol} "+ f" [dim]evidence:[/dim] {e['refactoring_type']} {e['target_symbol']} ""[dim](an observation, not a step)[/dim]")-def _render_opportunities_md(opportunities: list, plan_by_id: dict) -> None:+def _render_opportunities_md(opportunities: list[dict], plan_by_id: dict) -> None:if not opportunities:returnclick.echo("\n## Refactoring opportunities\n")- click.echo("One per file, in rank order. Steps are in dependency-safe order.\n")+ click.echo("One per file. Steps are in dependency-safe order.\n")for rank, o in enumerate(opportunities, 1):- mech = sum(1 for s in o.steps if s.applicability.classification == "mechanical")click.echo(- f"{rank}. **{o.file_path}** - {len(o.steps)} step(s), {mech} mechanical "- f"(effort {o.effort_bucket}, {o.confidence} confidence, "- f"recover ~{o.recoverable_health:.2f}, "- f"{_primary_word(o.addresses_primary_problem)})"+ f"{rank}. **{o['file_path']}** - {o['step_count']} step(s), "+ f"{o['mechanical_steps']} mechanical "+ f"(effort {o['effort_bucket']}, {o['confidence']} confidence, "+ f"recover ~{o['recoverable_health']:.2f}, "+ f"{_primary_word(o['addresses_primary_problem'])})")- for i, s in enumerate(o.steps, 1):- mark = "mechanical" if s.applicability.classification == "mechanical" else "judgment"- span = f":{s.line_start}-{s.line_end}" if s.line_start else ""+ for i, s in enumerate(o["steps"], 1):+ mark = "mechanical" if s["classification"] == "mechanical" else "judgment"+ span = f":{s['line_start']}-{s['line_end']}" if s["line_start"] else ""click.echo(- f" {i}. {s.refactoring_type} **{s.target_symbol}** "- f"({s.file_path}{span}) - {mark}"+ f" {i}. {s['refactoring_type']} **{s['target_symbol']}** "+ f"({s['file_path']}{span}) - {mark}")- if s.relocated_by:+ if s["relocated_by"]:click.echo(" - moved by an earlier step; locate it again before applying")- for line in _plan_detail_md(plan_by_id.get(s.plan_id, {})):+ for line in _plan_detail_md(plan_by_id.get(s["plan_id"], {})):click.echo(line)- if s.applicability.unknowns:- click.echo(f" - not established: {', '.join(s.applicability.unknowns)}")- for e in o.evidence:+ if s["unknowns"]:+ click.echo(f" - not established: {', '.join(s['unknowns'])}")+ for e in o["evidence"]:click.echo(- f" - evidence: {e.refactoring_type} {e.target_symbol} "+ f" - evidence: {e['refactoring_type']} {e['target_symbol']} ""(an observation, not a step)")diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.pyindex 794027d07..9e8b18271 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py@@ -501,6 +501,7 @@ def _opportunity_filters(effort: str | None,file_paths: list[str] | None,path_contains: str | None,+ path_prefix: str | None,mechanical_only: bool,addresses_primary: bool | None,) -> list[Any]:@@ -533,6 +534,14 @@ def _opportunity_filters(f"%{escape_like(path_contains)}%", escape=LIKE_ESCAPE))+ if path_prefix:+ # A directory scope (the CLI's ``--module``), counted in the store so+ # the total is exact rather than a capped over-fetch narrowed later.+ predicates.append(+ RefactoringOpportunity.file_path.like(+ f"{escape_like(path_prefix)}%", escape=LIKE_ESCAPE+ )+ )if mechanical_only:predicates.append(RefactoringOpportunity.mechanical_steps > 0)if addresses_primary is not None:@@ -552,6 +561,7 @@ async def list_refactoring_opportunities(effort: str | None = None,file_paths: list[str] | None = None,path_contains: str | None = None,+ path_prefix: str | None = None,mechanical_only: bool = False,addresses_primary: bool | None = None,order: str = DEFAULT_ORDER,@@ -567,6 +577,7 @@ async def list_refactoring_opportunities(effort=effort,file_paths=file_paths,path_contains=path_contains,+ path_prefix=path_prefix,mechanical_only=mechanical_only,addresses_primary=addresses_primary,)diff --git a/packages/server/src/repowise/server/services/refactoring_health.py b/packages/server/src/repowise/server/services/refactoring_health.pyindex 77fd54393..81a7ad633 100644--- a/packages/server/src/repowise/server/services/refactoring_health.py+++ b/packages/server/src/repowise/server/services/refactoring_health.py@@ -87,6 +87,7 @@ class RefactoringQuery:addresses_primary: bool | None = Nonefile_paths: tuple[str, ...] | None = Nonepath_contains: str | None = None+ path_prefix: str | None = Noneview: str = DEFAULT_VIEWorder: str | None = Nonelimit: int = 20@@ -121,6 +122,7 @@ def parse_query(addresses_primary: bool | None = None,file_paths: list[str] | tuple[str, ...] | None = None,search: str | None = None,+ path_prefix: str | None = None,view: str | None = None,order: str | None = None,limit: int = 20,@@ -177,6 +179,7 @@ def parse_query(# the whole repository.file_paths=tuple(file_paths) if file_paths is not None else None,path_contains=(search or "").strip() or None,+ path_prefix=path_prefix or None,view=resolved_view,order=admit("order", order, CANONICAL_ORDERS),limit=max(int(limit), 0),@@ -245,6 +248,7 @@ class RefactoringHealthService:effort=query.effort,file_paths=list(query.file_paths) if query.file_paths is not None else None,path_contains=query.path_contains,+ path_prefix=query.path_prefix,mechanical_only=query.mechanical_only,addresses_primary=query.addresses_primary,order=query.resolved_order,diff --git a/tests/unit/cli/test_refactoring_targets_stored.py b/tests/unit/cli/test_refactoring_targets_stored.pynew file mode 100644index 000000000..9d8b8400f--- /dev/null+++ b/tests/unit/cli/test_refactoring_targets_stored.py@@ -0,0 +1,214 @@+"""`repowise health --refactoring-targets` reads the queue the index stored.++The recompute parsed and analyzed the whole tree before printing, which took+minutes on a large repository, and composed its own order. The stored read+lists the same opportunities in the same order as MCP and the web UI, and+touches no parser. ``--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 health_command+from repowise.cli.helpers import run_async+++def _git(cwd: Path, *args: str) -> None:+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True)+++def _plan(path: str, symbol: str, impact: float) -> dict[str, Any]:+ return {+ "refactoring_type": "extract_method",+ "file_path": path,+ "target_symbol": symbol,+ "line_start": 10,+ "line_end": 30,+ "plan": {"span": {"start": 12, "end": 28}, "params": ["a"], "returns": []},+ "evidence": {"ccn_removed": 6, "slice_nloc": 20},+ "impact_delta": impact,+ "effort_bucket": "S",+ "blast_radius": {"scope": "local"},+ "confidence": "high",+ "source_biomarker": "complex_method",+ }+++def _finding(path: str, symbol: str) -> dict[str, Any]:+ return {+ "file_path": path,+ "biomarker_type": "complex_method",+ "severity": "high",+ "function_name": symbol,+ "line_start": 10,+ "line_end": 30,+ "details": {},+ "health_impact": 3.0,+ "reason": "seeded",+ "dimension": "defect",+ }+++_PATHS = [f"pkg{i % 3}/mod{i}.py" for i in range(6)]+++async def _store(repo_path: Path, paths: list[str] = _PATHS) -> list[str]:+ """Seed one opportunity per file; return the stored queue order."""+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ crud,+ get_session,+ init_db,+ upsert_repository,+ )+ from repowise.server.services.refactoring_health import (+ RefactoringHealthService,+ parse_query,+ )++ db_path = repo_path / ".repowise" / "wiki.db"+ engine = create_engine(f"sqlite+aiosqlite:///{db_path.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_findings(+ session, repo.id, [_finding(p, f"sym{i}") for i, p in enumerate(paths)]+ )+ await crud.save_refactoring_suggestions(+ session,+ repo.id,+ [_plan(p, f"sym{i}", float(len(paths) - i)) for i, p in enumerate(paths)],+ )+ await crud.finalize_refactoring_opportunities(+ session, repo.id, analyzed_commit="c" * 40+ )+ await session.commit()+ page = await RefactoringHealthService(session, repo.id, "repo").page(+ parse_query(limit=20)[0]+ )+ return [item["opportunity_id"] for item in page.items]+ 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()+ _git(root, "init", "-q")+ (root / "a.py").write_text("def f():\n return 1\n")+ (root / ".repowise").mkdir()+ return root+++def _no_parse(monkeypatch: pytest.MonkeyPatch) -> None:+ """Fail the test if the command walks the tree."""+ import repowise.core.ingestion as ingestion++ def boom(*_args: Any, **_kwargs: Any) -> None:+ raise AssertionError("the stored read must not traverse the repository")++ monkeypatch.setattr(ingestion, "FileTraverser", boom)+++def test_json_lists_the_stored_queue_in_the_served_order(repo, monkeypatch):+ served = run_async(_store(repo))+ _no_parse(monkeypatch)++ result = CliRunner().invoke(+ health_command,+ [str(repo), "--refactoring-targets", "--format", "json", "--no-workspace"],+ )++ assert result.exit_code == 0, result.output+ out = json.loads(result.output[result.output.index("{") :])+ assert out["source"] == "index"+ assert out["analyzed_commit"] == "c" * 40+ assert out["opportunities_total"] == len(_PATHS)+ assert [o["opportunity_id"] for o in out["refactoring_opportunities"]] == served+ # Every step's plan is carried, so the type-specific detail can render.+ step_ids = {s["plan_id"] for o in out["refactoring_opportunities"] for s in o["steps"]}+ assert step_ids <= {p["id"] for p in out["refactoring_plans"]}+ assert {t["file_path"] for t in out["targets"]} == set(_PATHS)+++def test_markdown_renders_steps_and_their_plan_detail(repo, monkeypatch):+ run_async(_store(repo))+ _no_parse(monkeypatch)++ result = CliRunner().invoke(+ health_command,+ [str(repo), "--refactoring-targets", "--format", "md", "--no-workspace",+ "--module", "pkg1"],+ )++ assert result.exit_code == 0, result.output+ assert "## Refactoring opportunities" in result.output+ assert "extract_method **sym1**" in result.output+ assert "extract lines 12-28" in result.output+ # The module filter is a prefix over the stored rows.+ assert "pkg0/" not in result.output and "pkg2/" not in result.output+++def test_no_stored_analysis_names_both_ways_forward(repo, monkeypatch):+ _no_parse(monkeypatch)++ result = CliRunner().invoke(+ health_command, [str(repo), "--refactoring-targets", "--no-workspace"]+ )++ assert result.exit_code != 0+ assert "--recompute" in result.output+++def test_a_module_larger_than_the_page_reports_its_exact_total(repo, monkeypatch):+ """The prefix is matched in the store, so the total is counted, not capped."""+ wide = [f"big/mod{i}.py" for i in range(25)] + [f"other/mod{i}.py" for i in range(5)]+ run_async(_store(repo, wide))+ _no_parse(monkeypatch)++ result = CliRunner().invoke(+ health_command,+ [str(repo), "--refactoring-targets", "--format", "json", "--no-workspace",+ "--module", "big/"],+ )++ assert result.exit_code == 0, result.output+ out = json.loads(result.output[result.output.index("{") :])+ assert out["opportunities_total"] == 25+ assert len(out["refactoring_opportunities"]) == 20+ assert all(o["file_path"].startswith("big/") for o in out["refactoring_opportunities"])+++def test_both_sources_emit_one_row_schema(repo, monkeypatch):+ from repowise.cli.commands.health_cmd.refactoring_targets import (+ _compose,+ _opportunity_row,+ )+ from repowise.core.analysis.health.refactoring.recommendations import (+ rehydrate_suggestion,+ )++ run_async(_store(repo))+ _no_parse(monkeypatch)+ result = CliRunner().invoke(+ health_command,+ [str(repo), "--refactoring-targets", "--format", "json", "--no-workspace"],+ )+ stored = json.loads(result.output[result.output.index("{") :])["refactoring_opportunities"][0]++ suggestions = [rehydrate_suggestion(_plan("pkg0/mod0.py", "sym0", 1.0))]+ recomputed = _opportunity_row(_compose([], suggestions)[0][0])++ assert set(recomputed) == set(stored)+ assert set(recomputed["steps"][0]) == set(stored["steps"][0])